Repository: MinusKube/SmartInvs
Branch: master
Commit: 9c9dbbee1654
Files: 23
Total size: 61.3 KB
Directory structure:
gitextract_1z4twe22/
├── .gitignore
├── LICENSE.md
├── README.md
├── build.gradle
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src/
└── main/
├── java/
│ └── fr/
│ └── minuskube/
│ └── inv/
│ ├── ClickableItem.java
│ ├── InventoryListener.java
│ ├── InventoryManager.java
│ ├── SmartInventory.java
│ ├── SmartInvsPlugin.java
│ ├── content/
│ │ ├── InventoryContents.java
│ │ ├── InventoryProvider.java
│ │ ├── Pagination.java
│ │ ├── SlotIterator.java
│ │ └── SlotPos.java
│ └── opener/
│ ├── ChestInventoryOpener.java
│ ├── InventoryOpener.java
│ └── SpecialInventoryOpener.java
└── resources/
└── plugin.yml
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.iml
.idea
.gradle
build
out
================================================
FILE: LICENSE.md
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2021 Isaac Montagne
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
http://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.
================================================
FILE: README.md
================================================

[](https://github.com/MinusKube/SmartInvs/blob/master/LICENSE.md)
[](https://javadoc.io/doc/fr.minuskube.inv/smart-invs)
# SmartInvs
Advanced Inventory API for your Minecraft Bukkit plugins.
*Tested Minecraft versions: 1.7, 1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14*
**You can use this as a Plugin, or use it as a library** (see [the docs](https://minuskube.gitbook.io/smartinvs/))
## Features
* Inventories of any type (workbench, chest, furnace, ...)
* Customizable size when possible (chest, ...)
* Custom titles
* Allows to prevent the player from closing its inventory
* Custom listeners for the event related to the inventory
* Iterator for inventory slots
* Page system
* Util methods to fill an inventory's row/column/borders/...
* Actions when player clicks on an item
* Update methods to edit the content of the inventory every tick
## Docs
[Click here to read the docs on Gitbook](https://minuskube.gitbook.io/smartinvs/)
## Usage
To use the SmartInvs API, either:
- Put it in the `plugins` folder of your server, add it to your dependencies in your plugin.yml (e.g. `depend: [SmartInvs]`) and add it to the dependencies in your IDE.
- Put it inside your plugin jar, initialize an `InventoryManager` in your plugin (don't forget to call the `init()` method), and add a `.manager(invManager)` to your SmartInventory Builders.
You can download the latest version on the [Releases page](https://github.com/MinusKube/SmartInvs/releases) on Github.
You can also use a build system:
### Gradle
```gradle
repositories {
mavenCentral()
}
dependencies {
compile 'fr.minuskube.inv:smart-invs:1.2.7'
}
```
### Maven
```xml
fr.minuskube.inv
smart-invs
1.2.7
```
## TODO
* Add some Javadocs
## Issues
If you have a problem with the API, or you want to request a feature, make an issue [here](https://github.com/MinusKube/SmartInvs/issues).
================================================
FILE: build.gradle
================================================
group 'fr.minuskube.inv'
version '1.2.7'
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'signing'
sourceCompatibility = 1.8
javadoc {
options.links(
'https://hub.spigotmc.org/javadocs/spigot/',
'https://docs.oracle.com/javase/8/docs/api/'
)
options.addStringOption('Xdoclint:none', '-quiet')
}
task javadocJar(type: Jar) {
archiveClassifier = 'javadoc'
from javadoc
}
task sourcesJar(type: Jar) {
archiveClassifier = 'sources'
from sourceSets.main.allSource
}
artifacts { archives javadocJar, sourcesJar }
repositories {
mavenCentral()
maven { url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' }
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
}
dependencies {
compileOnly 'org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT'
}
jar {
archiveFileName = 'SmartInvs-' + project.version + '.jar'
}
signing {
sign configurations.archives
}
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
if(project.hasProperty("ossrhUsername") && project.hasProperty("ossrhPassword")) {
repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
authentication(userName: ossrhUsername, password: ossrhPassword)
}
snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
authentication(userName: ossrhUsername, password: ossrhPassword)
}
}
pom.project {
name 'SmartInvs'
packaging 'jar'
description 'Advanced Inventory API for your Minecraft Bukkit plugins.'
url 'https://github.com/MinusKube/SmartInvs'
scm {
connection 'scm:git:git://github.com/MinusKube/SmartInvs.git'
developerConnection 'scm:git:ssh://github.com:MinusKube/SmartInvs.git'
url 'http://github.com/MinusKube/SmartInvs/tree/master'
}
licenses {
license {
name 'GNU General Public License v3.0'
url 'https://www.gnu.org/licenses/gpl-3.0.en.html'
}
}
developers {
developer {
id 'minuskube'
name 'MinusKube'
email 'minuskube@gmail.com'
}
}
}
}
}
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Tue May 29 14:21:02 CEST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$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=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# 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
;;
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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@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 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=
@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 init
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 init
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
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
: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 %CMD_LINE_ARGS%
: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
================================================
FILE: settings.gradle
================================================
rootProject.name = 'smart-invs'
================================================
FILE: src/main/java/fr/minuskube/inv/ClickableItem.java
================================================
package fr.minuskube.inv;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import java.util.function.Consumer;
public class ClickableItem {
private ItemStack item;
private Consumer consumer;
private ClickableItem(ItemStack item, Consumer consumer) {
this.item = item;
this.consumer = consumer;
}
public static ClickableItem empty(ItemStack item) {
return of(item, e -> {});
}
public static ClickableItem of(ItemStack item, Consumer consumer) {
return new ClickableItem(item, consumer);
}
public void run(InventoryClickEvent e) { consumer.accept(e); }
public ItemStack getItem() { return item; }
}
================================================
FILE: src/main/java/fr/minuskube/inv/InventoryListener.java
================================================
package fr.minuskube.inv;
import java.util.function.Consumer;
public class InventoryListener {
private Class type;
private Consumer consumer;
public InventoryListener(Class type, Consumer consumer) {
this.type = type;
this.consumer = consumer;
}
public void accept(T t) { consumer.accept(t); }
public Class getType() { return type; }
}
================================================
FILE: src/main/java/fr/minuskube/inv/InventoryManager.java
================================================
package fr.minuskube.inv;
import fr.minuskube.inv.content.InventoryContents;
import fr.minuskube.inv.opener.ChestInventoryOpener;
import fr.minuskube.inv.opener.InventoryOpener;
import fr.minuskube.inv.opener.SpecialInventoryOpener;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.logging.Level;
public class InventoryManager {
private JavaPlugin plugin;
private PluginManager pluginManager;
private Map inventories;
private Map contents;
private List defaultOpeners;
private List openers;
public InventoryManager(JavaPlugin plugin) {
this.plugin = plugin;
this.pluginManager = Bukkit.getPluginManager();
this.inventories = new HashMap<>();
this.contents = new HashMap<>();
this.defaultOpeners = Arrays.asList(
new ChestInventoryOpener(),
new SpecialInventoryOpener()
);
this.openers = new ArrayList<>();
}
public void init() {
pluginManager.registerEvents(new InvListener(), plugin);
new InvTask().runTaskTimer(plugin, 1, 1);
}
public Optional findOpener(InventoryType type) {
Optional opInv = this.openers.stream()
.filter(opener -> opener.supports(type))
.findAny();
if (!opInv.isPresent()) {
opInv = this.defaultOpeners.stream()
.filter(opener -> opener.supports(type))
.findAny();
}
return opInv;
}
public void registerOpeners(InventoryOpener... openers) {
this.openers.addAll(Arrays.asList(openers));
}
public List getOpenedPlayers(SmartInventory inv) {
List list = new ArrayList<>();
this.inventories.forEach((player, playerInv) -> {
if (inv.equals(playerInv))
list.add(Bukkit.getPlayer(player));
});
return list;
}
public Optional getInventory(Player p) {
return Optional.ofNullable(this.inventories.get(p.getUniqueId()));
}
protected void setInventory(Player p, SmartInventory inv) {
if (inv == null)
this.inventories.remove(p.getUniqueId());
else
this.inventories.put(p.getUniqueId(), inv);
}
public Optional getContents(Player p) {
return Optional.ofNullable(this.contents.get(p.getUniqueId()));
}
protected void setContents(Player p, InventoryContents contents) {
if (contents == null)
this.contents.remove(p.getUniqueId());
else
this.contents.put(p.getUniqueId(), contents);
}
public void handleInventoryOpenError(SmartInventory inventory, Player player, Exception exception) {
inventory.close(player);
Bukkit.getLogger().log(Level.SEVERE, "Error while opening SmartInventory:", exception);
}
public void handleInventoryUpdateError(SmartInventory inventory, Player player, Exception exception) {
inventory.close(player);
Bukkit.getLogger().log(Level.SEVERE, "Error while updating SmartInventory:", exception);
}
@SuppressWarnings("unchecked")
class InvListener implements Listener {
@EventHandler(priority = EventPriority.LOW)
public void onInventoryClick(InventoryClickEvent e) {
Player p = (Player) e.getWhoClicked();
if (!inventories.containsKey(p.getUniqueId()))
return;
// Restrict putting items from the bottom inventory into the top inventory
Inventory clickedInventory = e.getClickedInventory();
if (clickedInventory == p.getOpenInventory().getBottomInventory()) {
if (e.getAction() == InventoryAction.COLLECT_TO_CURSOR || e.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
e.setCancelled(true);
return;
}
if (e.getAction() == InventoryAction.NOTHING && e.getClick() != ClickType.MIDDLE) {
e.setCancelled(true);
return;
}
}
if (clickedInventory == p.getOpenInventory().getTopInventory()) {
e.setCancelled(true);
int row = e.getSlot() / 9;
int column = e.getSlot() % 9;
if (row < 0 || column < 0)
return;
SmartInventory inv = inventories.get(p.getUniqueId());
if (row >= inv.getRows() || column >= inv.getColumns())
return;
inv.getListeners().stream()
.filter(listener -> listener.getType() == InventoryClickEvent.class)
.forEach(listener -> ((InventoryListener) listener).accept(e));
contents.get(p.getUniqueId()).get(row, column).ifPresent(item -> item.run(e));
p.updateInventory();
}
}
@EventHandler(priority = EventPriority.LOW)
public void onInventoryDrag(InventoryDragEvent e) {
Player p = (Player) e.getWhoClicked();
if (!inventories.containsKey(p.getUniqueId()))
return;
SmartInventory inv = inventories.get(p.getUniqueId());
for (int slot : e.getRawSlots()) {
if (slot >= p.getOpenInventory().getTopInventory().getSize())
continue;
e.setCancelled(true);
break;
}
inv.getListeners().stream()
.filter(listener -> listener.getType() == InventoryDragEvent.class)
.forEach(listener -> ((InventoryListener) listener).accept(e));
}
@EventHandler(priority = EventPriority.LOW)
public void onInventoryOpen(InventoryOpenEvent e) {
Player p = (Player) e.getPlayer();
if (!inventories.containsKey(p.getUniqueId()))
return;
SmartInventory inv = inventories.get(p.getUniqueId());
inv.getListeners().stream()
.filter(listener -> listener.getType() == InventoryOpenEvent.class)
.forEach(listener -> ((InventoryListener) listener).accept(e));
}
@EventHandler(priority = EventPriority.LOW)
public void onInventoryClose(InventoryCloseEvent e) {
Player p = (Player) e.getPlayer();
if (!inventories.containsKey(p.getUniqueId()))
return;
SmartInventory inv = inventories.get(p.getUniqueId());
inv.getListeners().stream()
.filter(listener -> listener.getType() == InventoryCloseEvent.class)
.forEach(listener -> ((InventoryListener) listener).accept(e));
if (inv.isCloseable()) {
e.getInventory().clear();
inventories.remove(p.getUniqueId());
contents.remove(p.getUniqueId());
} else
Bukkit.getScheduler().runTask(plugin, () -> p.openInventory(e.getInventory()));
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerQuit(PlayerQuitEvent e) {
Player p = e.getPlayer();
if (!inventories.containsKey(p.getUniqueId()))
return;
SmartInventory inv = inventories.get(p.getUniqueId());
inv.getListeners().stream()
.filter(listener -> listener.getType() == PlayerQuitEvent.class)
.forEach(listener -> ((InventoryListener) listener).accept(e));
inventories.remove(p.getUniqueId());
contents.remove(p.getUniqueId());
}
@EventHandler(priority = EventPriority.LOW)
public void onPluginDisable(PluginDisableEvent e) {
new HashMap<>(inventories).forEach((player, inv) -> {
inv.getListeners().stream()
.filter(listener -> listener.getType() == PluginDisableEvent.class)
.forEach(listener -> ((InventoryListener) listener).accept(e));
inv.close(Bukkit.getPlayer(player));
});
inventories.clear();
contents.clear();
}
}
class InvTask extends BukkitRunnable {
@Override
public void run() {
new HashMap<>(inventories).forEach((uuid, inv) -> {
Player player = Bukkit.getPlayer(uuid);
try {
inv.getProvider().update(player, contents.get(uuid));
} catch (Exception e) {
handleInventoryUpdateError(inv, player, e);
}
});
}
}
}
================================================
FILE: src/main/java/fr/minuskube/inv/SmartInventory.java
================================================
package fr.minuskube.inv;
import fr.minuskube.inv.content.InventoryContents;
import fr.minuskube.inv.content.InventoryProvider;
import fr.minuskube.inv.opener.InventoryOpener;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@SuppressWarnings("unchecked")
public class SmartInventory {
private String id;
private String title;
private InventoryType type;
private int rows, columns;
private boolean closeable;
private InventoryProvider provider;
private SmartInventory parent;
private List> listeners;
private InventoryManager manager;
private SmartInventory(InventoryManager manager) {
this.manager = manager;
}
public Inventory open(Player player) { return open(player, 0); }
public Inventory open(Player player, int page) {
Optional oldInv = this.manager.getInventory(player);
oldInv.ifPresent(inv -> {
inv.getListeners().stream()
.filter(listener -> listener.getType() == InventoryCloseEvent.class)
.forEach(listener -> ((InventoryListener) listener)
.accept(new InventoryCloseEvent(player.getOpenInventory())));
this.manager.setInventory(player, null);
});
InventoryContents contents = new InventoryContents.Impl(this, player.getUniqueId());
contents.pagination().page(page);
this.manager.setContents(player, contents);
try {
this.provider.init(player, contents);
// If the current inventory has been closed or replaced within the init method, returns
if (!this.manager.getContents(player).equals(Optional.of(contents))) {
return null;
}
InventoryOpener opener = this.manager.findOpener(type)
.orElseThrow(() -> new IllegalStateException("No opener found for the inventory type " + type.name()));
Inventory handle = opener.open(this, player);
this.manager.setInventory(player, this);
return handle;
} catch (Exception e) {
this.manager.handleInventoryOpenError(this, player, e);
return null;
}
}
@SuppressWarnings("unchecked")
public void close(Player player) {
listeners.stream()
.filter(listener -> listener.getType() == InventoryCloseEvent.class)
.forEach(listener -> ((InventoryListener) listener)
.accept(new InventoryCloseEvent(player.getOpenInventory())));
this.manager.setInventory(player, null);
player.closeInventory();
this.manager.setContents(player, null);
}
public String getId() { return id; }
public String getTitle() { return title; }
public InventoryType getType() { return type; }
public int getRows() { return rows; }
public int getColumns() { return columns; }
public boolean isCloseable() { return closeable; }
public void setCloseable(boolean closeable) { this.closeable = closeable; }
public InventoryProvider getProvider() { return provider; }
public Optional getParent() { return Optional.ofNullable(parent); }
public InventoryManager getManager() { return manager; }
List> getListeners() { return listeners; }
public static Builder builder() { return new Builder(); }
public static final class Builder {
private String id = "unknown";
private String title = "";
private InventoryType type = InventoryType.CHEST;
private int rows = 6, columns = 9;
private boolean closeable = true;
private InventoryManager manager;
private InventoryProvider provider;
private SmartInventory parent;
private List> listeners = new ArrayList<>();
private Builder() {}
public Builder id(String id) {
this.id = id;
return this;
}
public Builder title(String title) {
this.title = title;
return this;
}
public Builder type(InventoryType type) {
this.type = type;
return this;
}
public Builder size(int rows, int columns) {
this.rows = rows;
this.columns = columns;
return this;
}
public Builder closeable(boolean closeable) {
this.closeable = closeable;
return this;
}
public Builder provider(InventoryProvider provider) {
this.provider = provider;
return this;
}
public Builder parent(SmartInventory parent) {
this.parent = parent;
return this;
}
public Builder listener(InventoryListener extends Event> listener) {
this.listeners.add(listener);
return this;
}
public Builder manager(InventoryManager manager) {
this.manager = manager;
return this;
}
public SmartInventory build() {
if(this.provider == null)
throw new IllegalStateException("The provider of the SmartInventory.Builder must be set.");
InventoryManager manager = this.manager != null ? this.manager : SmartInvsPlugin.manager();
if(manager == null)
throw new IllegalStateException("The manager of the SmartInventory.Builder must be set, "
+ "or the SmartInvs should be loaded as a plugin.");
SmartInventory inv = new SmartInventory(manager);
inv.id = this.id;
inv.title = this.title;
inv.type = this.type;
inv.rows = this.rows;
inv.columns = this.columns;
inv.closeable = this.closeable;
inv.provider = this.provider;
inv.parent = this.parent;
inv.listeners = this.listeners;
return inv;
}
}
}
================================================
FILE: src/main/java/fr/minuskube/inv/SmartInvsPlugin.java
================================================
package fr.minuskube.inv;
import org.bukkit.plugin.java.JavaPlugin;
public class SmartInvsPlugin extends JavaPlugin {
private static SmartInvsPlugin instance;
private static InventoryManager invManager;
@Override
public void onEnable() {
instance = this;
invManager = new InventoryManager(this);
invManager.init();
}
public static InventoryManager manager() { return invManager; }
public static SmartInvsPlugin instance() { return instance; }
}
================================================
FILE: src/main/java/fr/minuskube/inv/content/InventoryContents.java
================================================
package fr.minuskube.inv.content;
import fr.minuskube.inv.ClickableItem;
import fr.minuskube.inv.SmartInventory;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
public interface InventoryContents {
SmartInventory inventory();
Pagination pagination();
Optional iterator(String id);
SlotIterator newIterator(String id, SlotIterator.Type type, int startRow, int startColumn);
SlotIterator newIterator(SlotIterator.Type type, int startRow, int startColumn);
SlotIterator newIterator(String id, SlotIterator.Type type, SlotPos startPos);
SlotIterator newIterator(SlotIterator.Type type, SlotPos startPos);
ClickableItem[][] all();
Optional firstEmpty();
Optional get(int row, int column);
Optional get(SlotPos slotPos);
InventoryContents set(int row, int column, ClickableItem item);
InventoryContents set(SlotPos slotPos, ClickableItem item);
InventoryContents add(ClickableItem item);
InventoryContents fill(ClickableItem item);
InventoryContents fillRow(int row, ClickableItem item);
InventoryContents fillColumn(int column, ClickableItem item);
InventoryContents fillBorders(ClickableItem item);
InventoryContents fillRect(int fromRow, int fromColumn,
int toRow, int toColumn, ClickableItem item);
InventoryContents fillRect(SlotPos fromPos, SlotPos toPos, ClickableItem item);
T property(String name);
T property(String name, T def);
InventoryContents setProperty(String name, Object value);
class Impl implements InventoryContents {
private SmartInventory inv;
private UUID player;
private ClickableItem[][] contents;
private Pagination pagination = new Pagination.Impl();
private Map iterators = new HashMap<>();
private Map properties = new HashMap<>();
public Impl(SmartInventory inv, UUID player) {
this.inv = inv;
this.player = player;
this.contents = new ClickableItem[inv.getRows()][inv.getColumns()];
}
@Override
public SmartInventory inventory() { return inv; }
@Override
public Pagination pagination() { return pagination; }
@Override
public Optional iterator(String id) {
return Optional.ofNullable(this.iterators.get(id));
}
@Override
public SlotIterator newIterator(String id, SlotIterator.Type type, int startRow, int startColumn) {
SlotIterator iterator = new SlotIterator.Impl(this, inv,
type, startRow, startColumn);
this.iterators.put(id, iterator);
return iterator;
}
@Override
public SlotIterator newIterator(String id, SlotIterator.Type type, SlotPos startPos) {
return newIterator(id, type, startPos.getRow(), startPos.getColumn());
}
@Override
public SlotIterator newIterator(SlotIterator.Type type, int startRow, int startColumn) {
return new SlotIterator.Impl(this, inv, type, startRow, startColumn);
}
@Override
public SlotIterator newIterator(SlotIterator.Type type, SlotPos startPos) {
return newIterator(type, startPos.getRow(), startPos.getColumn());
}
@Override
public ClickableItem[][] all() { return contents; }
@Override
public Optional firstEmpty() {
for (int row = 0; row < contents.length; row++) {
for(int column = 0; column < contents[0].length; column++) {
if(!this.get(row, column).isPresent())
return Optional.of(new SlotPos(row, column));
}
}
return Optional.empty();
}
@Override
public Optional get(int row, int column) {
if(row >= contents.length)
return Optional.empty();
if(column >= contents[row].length)
return Optional.empty();
return Optional.ofNullable(contents[row][column]);
}
@Override
public Optional get(SlotPos slotPos) {
return get(slotPos.getRow(), slotPos.getColumn());
}
@Override
public InventoryContents set(int row, int column, ClickableItem item) {
if(row >= contents.length)
return this;
if(column >= contents[row].length)
return this;
contents[row][column] = item;
update(row, column, item != null ? item.getItem() : null);
return this;
}
@Override
public InventoryContents set(SlotPos slotPos, ClickableItem item) {
return set(slotPos.getRow(), slotPos.getColumn(), item);
}
@Override
public InventoryContents add(ClickableItem item) {
for(int row = 0; row < contents.length; row++) {
for(int column = 0; column < contents[0].length; column++) {
if(contents[row][column] == null) {
set(row, column, item);
return this;
}
}
}
return this;
}
@Override
public InventoryContents fill(ClickableItem item) {
for(int row = 0; row < contents.length; row++)
for(int column = 0; column < contents[row].length; column++)
set(row, column, item);
return this;
}
@Override
public InventoryContents fillRow(int row, ClickableItem item) {
if(row >= contents.length)
return this;
for(int column = 0; column < contents[row].length; column++)
set(row, column, item);
return this;
}
@Override
public InventoryContents fillColumn(int column, ClickableItem item) {
for(int row = 0; row < contents.length; row++)
set(row, column, item);
return this;
}
@Override
public InventoryContents fillBorders(ClickableItem item) {
fillRect(0, 0, inv.getRows() - 1, inv.getColumns() - 1, item);
return this;
}
@Override
public InventoryContents fillRect(int fromRow, int fromColumn, int toRow, int toColumn, ClickableItem item) {
for(int row = fromRow; row <= toRow; row++) {
for(int column = fromColumn; column <= toColumn; column++) {
if(row != fromRow && row != toRow && column != fromColumn && column != toColumn)
continue;
set(row, column, item);
}
}
return this;
}
@Override
public InventoryContents fillRect(SlotPos fromPos, SlotPos toPos, ClickableItem item) {
return fillRect(fromPos.getRow(), fromPos.getColumn(), toPos.getRow(), toPos.getColumn(), item);
}
@SuppressWarnings("unchecked")
@Override
public T property(String name) {
return (T) properties.get(name);
}
@SuppressWarnings("unchecked")
@Override
public T property(String name, T def) {
return properties.containsKey(name) ? (T) properties.get(name) : def;
}
@Override
public InventoryContents setProperty(String name, Object value) {
properties.put(name, value);
return this;
}
private void update(int row, int column, ItemStack item) {
Player currentPlayer = Bukkit.getPlayer(player);
if(!inv.getManager().getOpenedPlayers(inv).contains(currentPlayer))
return;
Inventory topInventory = currentPlayer.getOpenInventory().getTopInventory();
topInventory.setItem(inv.getColumns() * row + column, item);
}
}
}
================================================
FILE: src/main/java/fr/minuskube/inv/content/InventoryProvider.java
================================================
package fr.minuskube.inv.content;
import org.bukkit.entity.Player;
public interface InventoryProvider {
void init(Player player, InventoryContents contents);
default void update(Player player, InventoryContents contents) {}
}
================================================
FILE: src/main/java/fr/minuskube/inv/content/Pagination.java
================================================
package fr.minuskube.inv.content;
import fr.minuskube.inv.ClickableItem;
import java.util.Arrays;
public interface Pagination {
ClickableItem[] getPageItems();
int getPage();
Pagination page(int page);
boolean isFirst();
boolean isLast();
Pagination first();
Pagination previous();
Pagination next();
Pagination last();
Pagination addToIterator(SlotIterator iterator);
Pagination setItems(ClickableItem... items);
Pagination setItemsPerPage(int itemsPerPage);
class Impl implements Pagination {
private int currentPage;
private ClickableItem[] items = new ClickableItem[0];
private int itemsPerPage = 5;
@Override
public ClickableItem[] getPageItems() {
return Arrays.copyOfRange(items,
currentPage * itemsPerPage,
(currentPage + 1) * itemsPerPage);
}
@Override
public int getPage() {
return this.currentPage;
}
@Override
public Pagination page(int page) {
this.currentPage = page;
return this;
}
@Override
public boolean isFirst() {
return this.currentPage == 0;
}
@Override
public boolean isLast() {
int pageCount = (int) Math.ceil((double) this.items.length / this.itemsPerPage);
return this.currentPage >= pageCount - 1;
}
@Override
public Pagination first() {
this.currentPage = 0;
return this;
}
@Override
public Pagination previous() {
if(!isFirst())
this.currentPage--;
return this;
}
@Override
public Pagination next() {
if(!isLast())
this.currentPage++;
return this;
}
@Override
public Pagination last() {
this.currentPage = this.items.length / this.itemsPerPage;
return this;
}
@Override
public Pagination addToIterator(SlotIterator iterator) {
for(ClickableItem item : getPageItems()) {
iterator.next().set(item);
if(iterator.ended())
break;
}
return this;
}
@Override
public Pagination setItems(ClickableItem... items) {
this.items = items;
return this;
}
@Override
public Pagination setItemsPerPage(int itemsPerPage) {
this.itemsPerPage = itemsPerPage;
return this;
}
}
}
================================================
FILE: src/main/java/fr/minuskube/inv/content/SlotIterator.java
================================================
package fr.minuskube.inv.content;
import fr.minuskube.inv.ClickableItem;
import fr.minuskube.inv.SmartInventory;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
public interface SlotIterator {
enum Type {
HORIZONTAL,
VERTICAL
}
Optional get();
SlotIterator set(ClickableItem item);
SlotIterator previous();
SlotIterator next();
SlotIterator blacklist(int row, int column);
SlotIterator blacklist(SlotPos slotPos);
int row();
SlotIterator row(int row);
int column();
SlotIterator column(int column);
boolean started();
boolean ended();
boolean doesAllowOverride();
SlotIterator allowOverride(boolean override);
class Impl implements SlotIterator {
private InventoryContents contents;
private SmartInventory inv;
private Type type;
private boolean started = false;
private boolean allowOverride = true;
private int row, column;
private Set blacklisted = new HashSet<>();
public Impl(InventoryContents contents, SmartInventory inv,
Type type, int startRow, int startColumn) {
this.contents = contents;
this.inv = inv;
this.type = type;
this.row = startRow;
this.column = startColumn;
}
public Impl(InventoryContents contents, SmartInventory inv,
Type type) {
this(contents, inv, type, 0, 0);
}
@Override
public Optional get() {
return contents.get(row, column);
}
@Override
public SlotIterator set(ClickableItem item) {
if(canPlace())
contents.set(row, column, item);
return this;
}
@Override
public SlotIterator previous() {
if(row == 0 && column == 0) {
this.started = true;
return this;
}
do {
if(!this.started) {
this.started = true;
}
else {
switch(type) {
case HORIZONTAL:
column--;
if(column == 0) {
column = inv.getColumns() - 1;
row--;
}
break;
case VERTICAL:
row--;
if(row == 0) {
row = inv.getRows() - 1;
column--;
}
break;
}
}
}
while(!canPlace() && (row != 0 || column != 0));
return this;
}
@Override
public SlotIterator next() {
if(ended()) {
this.started = true;
return this;
}
do {
if(!this.started) {
this.started = true;
}
else {
switch(type) {
case HORIZONTAL:
column = ++column % inv.getColumns();
if(column == 0)
row++;
break;
case VERTICAL:
row = ++row % inv.getRows();
if(row == 0)
column++;
break;
}
}
}
while(!canPlace() && !ended());
return this;
}
@Override
public SlotIterator blacklist(int row, int column) {
this.blacklisted.add(SlotPos.of(row, column));
return this;
}
@Override
public SlotIterator blacklist(SlotPos slotPos) {
return blacklist(slotPos.getRow(), slotPos.getColumn());
}
@Override
public int row() { return row; }
@Override
public SlotIterator row(int row) {
this.row = row;
return this;
}
@Override
public int column() { return column; }
@Override
public SlotIterator column(int column) {
this.column = column;
return this;
}
@Override
public boolean started() {
return this.started;
}
@Override
public boolean ended() {
return row == inv.getRows() - 1
&& column == inv.getColumns() - 1;
}
@Override
public boolean doesAllowOverride() { return allowOverride; }
@Override
public SlotIterator allowOverride(boolean override) {
this.allowOverride = override;
return this;
}
private boolean canPlace() {
return !blacklisted.contains(SlotPos.of(row, column)) && (allowOverride || !this.get().isPresent());
}
}
}
================================================
FILE: src/main/java/fr/minuskube/inv/content/SlotPos.java
================================================
package fr.minuskube.inv.content;
public class SlotPos {
private final int row;
private final int column;
public SlotPos(int row, int column) {
this.row = row;
this.column = column;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null || getClass() != obj.getClass())
return false;
SlotPos slotPos = (SlotPos) obj;
return row == slotPos.row && column == slotPos.column;
}
@Override
public int hashCode() {
int result = row;
result = 31 * result + column;
return result;
}
public int getRow() { return row; }
public int getColumn() { return column; }
public static SlotPos of(int row, int column) {
return new SlotPos(row, column);
}
}
================================================
FILE: src/main/java/fr/minuskube/inv/opener/ChestInventoryOpener.java
================================================
package fr.minuskube.inv.opener;
import com.google.common.base.Preconditions;
import fr.minuskube.inv.InventoryManager;
import fr.minuskube.inv.SmartInventory;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
public class ChestInventoryOpener implements InventoryOpener {
@Override
public Inventory open(SmartInventory inv, Player player) {
Preconditions.checkArgument(inv.getColumns() == 9,
"The column count for the chest inventory must be 9, found: %s.", inv.getColumns());
Preconditions.checkArgument(inv.getRows() >= 1 && inv.getRows() <= 6,
"The row count for the chest inventory must be between 1 and 6, found: %s", inv.getRows());
InventoryManager manager = inv.getManager();
Inventory handle = Bukkit.createInventory(player, inv.getRows() * inv.getColumns(), inv.getTitle());
fill(handle, manager.getContents(player).get());
player.openInventory(handle);
return handle;
}
@Override
public boolean supports(InventoryType type) {
return type == InventoryType.CHEST || type == InventoryType.ENDER_CHEST;
}
}
================================================
FILE: src/main/java/fr/minuskube/inv/opener/InventoryOpener.java
================================================
package fr.minuskube.inv.opener;
import fr.minuskube.inv.ClickableItem;
import fr.minuskube.inv.SmartInventory;
import fr.minuskube.inv.content.InventoryContents;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
public interface InventoryOpener {
Inventory open(SmartInventory inv, Player player);
boolean supports(InventoryType type);
default void fill(Inventory handle, InventoryContents contents) {
ClickableItem[][] items = contents.all();
for(int row = 0; row < items.length; row++) {
for(int column = 0; column < items[row].length; column++) {
if(items[row][column] != null)
handle.setItem(9 * row + column, items[row][column].getItem());
}
}
}
}
================================================
FILE: src/main/java/fr/minuskube/inv/opener/SpecialInventoryOpener.java
================================================
package fr.minuskube.inv.opener;
import com.google.common.collect.ImmutableList;
import fr.minuskube.inv.InventoryManager;
import fr.minuskube.inv.SmartInventory;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import java.util.List;
public class SpecialInventoryOpener implements InventoryOpener {
private static final List SUPPORTED = ImmutableList.of(
InventoryType.FURNACE,
InventoryType.WORKBENCH,
InventoryType.DISPENSER,
InventoryType.DROPPER,
InventoryType.ENCHANTING,
InventoryType.BREWING,
InventoryType.ANVIL,
InventoryType.BEACON,
InventoryType.HOPPER
);
@Override
public Inventory open(SmartInventory inv, Player player) {
InventoryManager manager = inv.getManager();
Inventory handle = Bukkit.createInventory(player, inv.getType(), inv.getTitle());
fill(handle, manager.getContents(player).get());
player.openInventory(handle);
return handle;
}
@Override
public boolean supports(InventoryType type) {
return SUPPORTED.contains(type);
}
}
================================================
FILE: src/main/resources/plugin.yml
================================================
name: SmartInvs
version: 1.2.7
description: Inventory API for your Bukkit Plugins.
author: MinusKube
website: https://github.com/MinusKube/SmartInvs
main: fr.minuskube.inv.SmartInvsPlugin