Merge branch 'development'

This commit is contained in:
Brianna 2019-10-08 21:17:58 -04:00
commit 4ff98506d0
85 changed files with 2615 additions and 6264 deletions

View File

@ -4,7 +4,7 @@ stages:
variables:
name: "UltimateKits"
path: "/builds/$CI_PROJECT_PATH"
version: "2.3.26"
version: "2.4"
build:
stage: build

50
pom.xml
View File

@ -52,9 +52,10 @@
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>true</minimizeJar>
<artifactSet>
<includes>
<include>com.songoda:songodaupdater</include>
<include>com.songoda:SongodaCore</include>
<include>com.zaxxer:HikariCP</include>
</includes>
</artifactSet>
@ -68,6 +69,12 @@
</excludes>
</filter>
</filters>
<relocations>
<relocation>
<pattern>com.songoda.core</pattern>
<shadedPattern>${project.groupId}.ultimatekits.core</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
@ -80,31 +87,28 @@
<url>http://repo.songoda.com/artifactory/private/</url>
</repository>
<repository>
<id>reserve-repo</id>
<url>https://dl.bintray.com/theneweconomy/java/</url>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.14.1</version>
<artifactId>spigot-api</artifactId>
<version>1.14.4-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.songoda</groupId>
<artifactId>songodaupdater</artifactId>
<version>1</version>
<artifactId>SongodaCore</artifactId>
<version>LATEST</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org</groupId>
<artifactId>kingdoms</artifactId>
<version>13.0.9</version>
</dependency>
<dependency>
<groupId>net.milkbowl</groupId>
<artifactId>vault</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>me.ryanhamshire</groupId>
<artifactId>GriefPrevention</artifactId>
@ -150,12 +154,6 @@
<artifactId>RedProtect</artifactId>
<version>7.3.0</version>
</dependency>
<dependency>
<groupId>com.gmail.filoghost.holographicdisplays</groupId>
<artifactId>holographicdisplays-api</artifactId>
<version>2.3.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.gmail.nossr50</groupId>
<artifactId>mcmmo</artifactId>
@ -191,16 +189,6 @@
<artifactId>blockstore</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>org.black_ixx</groupId>
<artifactId>playerpoints</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>xyz.wildseries</groupId>
<artifactId>wildstacker</artifactId>
<version>b6</version>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
@ -216,12 +204,6 @@
<artifactId>ultimatecore</artifactId>
<version>2.1.25</version>
</dependency>
<dependency>
<groupId>net.tnemc</groupId>
<artifactId>Reserve</artifactId>
<version>0.1.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.zrips</groupId>
<artifactId>CMI</artifactId>

View File

@ -1,20 +1,25 @@
package com.songoda.ultimatekits;
import com.songoda.ultimatekits.command.CommandManager;
import com.songoda.core.SongodaCore;
import com.songoda.core.SongodaPlugin;
import com.songoda.core.commands.CommandManager;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.configuration.Config;
import com.songoda.core.database.DataMigrationManager;
import com.songoda.core.database.DatabaseConnector;
import com.songoda.core.database.MySQLConnector;
import com.songoda.core.database.SQLiteConnector;
import com.songoda.core.gui.GuiManager;
import com.songoda.core.hooks.EconomyManager;
import com.songoda.core.hooks.HologramManager;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.commands.*;
import com.songoda.ultimatekits.conversion.Convert;
import com.songoda.ultimatekits.database.DataManager;
import com.songoda.ultimatekits.database.DataMigrationManager;
import com.songoda.ultimatekits.database.DatabaseConnector;
import com.songoda.ultimatekits.database.MySQLConnector;
import com.songoda.ultimatekits.database.SQLiteConnector;
import com.songoda.ultimatekits.economy.Economy;
import com.songoda.ultimatekits.economy.PlayerPointsEconomy;
import com.songoda.ultimatekits.economy.ReserveEconomy;
import com.songoda.ultimatekits.economy.VaultEconomy;
import com.songoda.ultimatekits.database.migrations._1_InitialMigration;
import com.songoda.ultimatekits.database.migrations._2_DuplicateMigration;
import com.songoda.ultimatekits.handlers.DisplayItemHandler;
import com.songoda.ultimatekits.handlers.ParticleHandler;
import com.songoda.ultimatekits.hologram.Hologram;
import com.songoda.ultimatekits.hologram.HologramHolographicDisplays;
import com.songoda.ultimatekits.key.Key;
import com.songoda.ultimatekits.key.KeyManager;
import com.songoda.ultimatekits.kit.*;
@ -22,46 +27,31 @@ import com.songoda.ultimatekits.listeners.BlockListeners;
import com.songoda.ultimatekits.listeners.ChatListeners;
import com.songoda.ultimatekits.listeners.EntityListeners;
import com.songoda.ultimatekits.listeners.InteractListeners;
import com.songoda.ultimatekits.utils.*;
import com.songoda.ultimatekits.utils.locale.Locale;
import com.songoda.ultimatekits.utils.settings.Setting;
import com.songoda.ultimatekits.utils.settings.SettingsManager;
import com.songoda.ultimatekits.utils.updateModules.LocaleModule;
import com.songoda.update.Plugin;
import com.songoda.update.SongodaUpdate;
import org.apache.commons.lang.ArrayUtils;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.ItemSerializer;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.*;
public class UltimateKits extends JavaPlugin {
public class UltimateKits extends SongodaPlugin {
private static UltimateKits INSTANCE;
private static CommandSender console = Bukkit.getConsoleSender();
private final Config kitFile = new Config(this, "kit.yml");
private final Config dataFile = new Config(this, "data.yml");
private final Config keyFile = new Config(this, "keys.yml");
private Locale locale;
private final GuiManager guiManager = new GuiManager(this);
private final ParticleHandler particleHandler = new ParticleHandler(this);
private final DisplayItemHandler displayItemHandler = new DisplayItemHandler(this);
private ServerVersion serverVersion = ServerVersion.fromPackageName(Bukkit.getServer().getClass().getPackage().getName());
private ConfigWrapper kitFile = new ConfigWrapper(this, "", "kit.yml");
private ConfigWrapper dataFile = new ConfigWrapper(this, "", "data.yml");
private ConfigWrapper keyFile = new ConfigWrapper(this, "", "keys.yml");
private SettingsManager settingsManager;
private KitManager kitManager;
private CommandManager commandManager;
private KeyManager keyManager;
private DisplayItemHandler displayItemHandler;
private Hologram hologram;
private Economy economy;
private ItemSerializer itemSerializer;
@ -78,82 +68,73 @@ public class UltimateKits extends JavaPlugin {
return INSTANCE;
}
/*
* On plugin enable.
*/
@Override
public void onEnable() {
public void onPluginLoad() {
INSTANCE = this;
console.sendMessage(Methods.formatText("&a============================="));
console.sendMessage(Methods.formatText("&7UltimateKits " + this.getDescription().getVersion() + " by &5Songoda <3!"));
console.sendMessage(Methods.formatText("&7Action: &aEnabling&7..."));
try {
this.itemSerializer = new ItemSerializer();
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
console.sendMessage(Methods.formatText("&cCould not load the serialization class! Please report this error."));
console.sendMessage(ChatColor.RED + "Could not load the serialization class! Please report this error.");
e.printStackTrace();
}
}
this.settingsManager = new SettingsManager(this);
this.settingsManager.setupConfig();
@Override
public void onPluginEnable() {
SongodaCore.registerPlugin(this, 14, CompatibleMaterial.BEACON);
new Locale(this, "en_US");
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode"));
// Load Economy
EconomyManager.load();
// Register Hologram Plugin
HologramManager.load(this);
new Convert(this);
// Setup Config
Settings.setupConfig();
this.setLocale(Settings.LANGUGE_MODE.getString(), false);
new ParticleHandler(this);
this.displayItemHandler = new DisplayItemHandler(this);
// Set economy preference
EconomyManager.getManager().setPreferredHook(Settings.ECONOMY_PLUGIN.getString());
// load kits
dataFile.load();
checkKeyDefaults();
loadKits();
keyFile.saveChanges();
// setup commands
this.commandManager = new CommandManager(this);
//Running Songoda Updater
Plugin plugin = new Plugin(this, 14);
plugin.addModule(new LocaleModule());
SongodaUpdate.load(plugin);
this.commandManager.addCommand(new CommandKit(guiManager));
this.commandManager.addCommand(new CommandPreviewKit(guiManager));
this.commandManager.addCommand(new CommandUltimateKits())
.addSubCommand(new CommandReload())
.addSubCommand(new CommandSettings(guiManager))
.addSubCommand(new CommandCreatekit(guiManager))
.addSubCommand(new CommandEdit(guiManager))
.addSubCommand(new CommandKey())
.addSubCommand(new CommandSet())
.addSubCommand(new CommandRemove());
this.kitManager = new KitManager();
this.keyManager = new KeyManager();
this.commandManager = new CommandManager(this);
PluginManager pluginManager = getServer().getPluginManager();
// Setup Economy
if (Setting.VAULT_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("Vault"))
this.economy = new VaultEconomy();
else if (Setting.RESERVE_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("Reserve"))
this.economy = new ReserveEconomy();
else if (Setting.PLAYER_POINTS_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("PlayerPoints"))
this.economy = new PlayerPointsEconomy();
// Register Hologram Plugin
if (pluginManager.isPluginEnabled("HolographicDisplays"))
hologram = new HologramHolographicDisplays(this);
Convert.runKitConversions();
// Event registration
PluginManager pluginManager = getServer().getPluginManager();
guiManager.init();
pluginManager.registerEvents(new BlockListeners(this), this);
pluginManager.registerEvents(new ChatListeners(this), this);
pluginManager.registerEvents(new EntityListeners(this), this);
pluginManager.registerEvents(new InteractListeners(this), this);
this.loadFromFile();
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, this::saveToFile, 6000, 6000);
// Starting Metrics
new Metrics(this);
pluginManager.registerEvents(new InteractListeners(this, guiManager), this);
try {
if (Setting.MYSQL_ENABLED.getBoolean()) {
String hostname = Setting.MYSQL_HOSTNAME.getString();
int port = Setting.MYSQL_PORT.getInt();
String database = Setting.MYSQL_DATABASE.getString();
String username = Setting.MYSQL_USERNAME.getString();
String password = Setting.MYSQL_PASSWORD.getString();
boolean useSSL = Setting.MYSQL_USE_SSL.getBoolean();
if (Settings.MYSQL_ENABLED.getBoolean()) {
String hostname = Settings.MYSQL_HOSTNAME.getString();
int port = Settings.MYSQL_PORT.getInt();
String database = Settings.MYSQL_DATABASE.getString();
String username = Settings.MYSQL_USERNAME.getString();
String password = Settings.MYSQL_PASSWORD.getString();
boolean useSSL = Settings.MYSQL_USE_SSL.getBoolean();
this.databaseConnector = new MySQLConnector(this, hostname, port, database, username, password, useSSL);
this.getLogger().info("Data handler connected using MySQL.");
@ -161,47 +142,57 @@ public class UltimateKits extends JavaPlugin {
this.databaseConnector = new SQLiteConnector(this);
this.getLogger().info("Data handler connected using SQLite.");
}
this.dataManager = new DataManager(this.databaseConnector, this);
this.dataMigrationManager = new DataMigrationManager(this.databaseConnector, this.dataManager,
new _1_InitialMigration(),
new _2_DuplicateMigration(this.databaseConnector instanceof SQLiteConnector));
this.dataMigrationManager.runMigrations();
} catch (Exception ex) {
this.getLogger().severe("Fatal error trying to connect to database. " +
"Please make sure all your connection settings are correct and try again. Plugin has been disabled.");
Bukkit.getPluginManager().disablePlugin(this);
emergencyStop();
return;
}
this.dataManager = new DataManager(this.databaseConnector, this);
this.dataMigrationManager = new DataMigrationManager(this.databaseConnector, this.dataManager);
this.dataMigrationManager.runMigrations();
Bukkit.getScheduler().runTaskLater(this, () -> {
this.dataManager.getBlockData((blockData) -> {
this.kitManager.setKitLocations(blockData);
kitManager.getKitLocations().forEach((location, data) -> {
if (hologram != null) UltimateKits.getInstance().getHologram().add(data);
});
});
}, 20L);
console.sendMessage(Methods.formatText("&a============================="));
displayItemHandler.start();
particleHandler.start();
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, this::saveKits, 6000, 6000);
Bukkit.getScheduler().runTaskLater(this, () ->
this.dataManager.getBlockData((blockData) -> {
this.kitManager.setKitLocations(blockData);
if (HologramManager.isEnabled()) {
loadHolograms();
}
}), 20L);
}
/*
* On plugin disable.
*/
@Override
public void onDisable() {
saveToFile();
dataFile.saveConfig();
public void onPluginDisable() {
saveKits();
dataFile.save();
this.dataManager.bulkUpdateBlockData(this.getKitManager().getKitLocations());
kitManager.clearKits();
console.sendMessage(Methods.formatText("&a============================="));
console.sendMessage(Methods.formatText("&7UltimateKits " + this.getDescription().getVersion() + " by &5Songoda <3!"));
console.sendMessage(Methods.formatText("&7Action: &cDisabling&7..."));
console.sendMessage(Methods.formatText("&a============================="));
HologramManager.removeAllHolograms();
}
/*
* Load configuration files into memory.
*/
private void loadFromFile() {
@Override
public List<Config> getExtraConfig() {
return Arrays.asList(kitFile, keyFile);
}
@Override
public void onConfigReload() {
this.setLocale(Settings.LANGUGE_MODE.getString(), true);
this.dataManager.bulkUpdateBlockData(this.getKitManager().getKitLocations());
loadKits();
}
void loadKits() {
kitFile.load();
Bukkit.getScheduler().runTaskLater(this, () -> {
//Empty kits from manager.
@ -210,15 +201,17 @@ public class UltimateKits extends JavaPlugin {
/*
* Register kit into KitManager from Configuration.
*/
for (String kitName : kitFile.getConfig().getConfigurationSection("Kits").getKeys(false)) {
int delay = kitFile.getConfig().getInt("Kits." + kitName + ".delay");
String title = kitFile.getConfig().getString("Kits." + kitName + ".title");
String link = kitFile.getConfig().getString("Kits." + kitName + ".link");
Material material = kitFile.getConfig().contains("Kits." + kitName + ".displayItem") ? Material.valueOf(kitFile.getConfig().getString("Kits." + kitName + ".displayItem")) : null;
boolean hidden = kitFile.getConfig().getBoolean("Kits." + kitName + ".hidden");
double price = kitFile.getConfig().getDouble("Kits." + kitName + ".price");
List<String> strContents = kitFile.getConfig().getStringList("Kits." + kitName + ".items");
String kitAnimation = kitFile.getConfig().getString("Kits." + kitName + ".animation", KitAnimation.NONE.name());
for (String kitName : kitFile.getConfigurationSection("Kits").getKeys(false)) {
int delay = kitFile.getInt("Kits." + kitName + ".delay");
String title = kitFile.getString("Kits." + kitName + ".title");
String link = kitFile.getString("Kits." + kitName + ".link");
CompatibleMaterial material = kitFile.contains("Kits." + kitName + ".displayItem")
? CompatibleMaterial.getMaterial(kitFile.getString("Kits." + kitName + ".displayItem"), CompatibleMaterial.DIAMOND_HELMET)
: null;
boolean hidden = kitFile.getBoolean("Kits." + kitName + ".hidden");
double price = kitFile.getDouble("Kits." + kitName + ".price");
List<String> strContents = kitFile.getStringList("Kits." + kitName + ".items");
String kitAnimation = kitFile.getString("Kits." + kitName + ".animation", KitAnimation.NONE.name());
List<KitItem> contents = new ArrayList<>();
@ -233,19 +226,20 @@ public class UltimateKits extends JavaPlugin {
/*
* Register kit locations into KitManager from Configuration.
*/
if (dataFile.getConfig().contains("BlockData")) {
for (String key : dataFile.getConfig().getConfigurationSection("BlockData").getKeys(false)) {
if (dataFile.contains("BlockData")) {
for (String key : dataFile.getConfigurationSection("BlockData").getKeys(false)) {
Location location = Methods.unserializeLocation(key);
Kit kit = kitManager.getKit(dataFile.getConfig().getString("BlockData." + key + ".kit"));
KitType type = KitType.valueOf(dataFile.getConfig().getString("BlockData." + key + ".type", "PREVIEW"));
boolean holograms = dataFile.getConfig().getBoolean("BlockData." + key + ".holograms");
boolean displayItems = dataFile.getConfig().getBoolean("BlockData." + key + ".displayItems");
boolean particles = dataFile.getConfig().getBoolean("BlockData." + key + ".particles");
boolean itemOverride = dataFile.getConfig().getBoolean("BlockData." + key + ".itemOverride");
Kit kit = kitManager.getKit(dataFile.getString("BlockData." + key + ".kit"));
KitType type = KitType.valueOf(dataFile.getString("BlockData." + key + ".type", "PREVIEW"));
boolean holograms = dataFile.getBoolean("BlockData." + key + ".holograms");
boolean displayItems = dataFile.getBoolean("BlockData." + key + ".displayItems");
boolean particles = dataFile.getBoolean("BlockData." + key + ".particles");
boolean itemOverride = dataFile.getBoolean("BlockData." + key + ".itemOverride");
if (kit == null) dataFile.getConfig().set("BlockData." + key, null);
else
kitManager.addKitToLocation(kit, location, type, holograms, particles, displayItems, itemOverride);
if (kit == null) dataFile.set("BlockData." + key, null);
else {
updateHologram(kitManager.addKitToLocation(kit, location, type, holograms, particles, displayItems, itemOverride));
}
}
}
@ -258,104 +252,181 @@ public class UltimateKits extends JavaPlugin {
/*
* Register keys into KitManager from Configuration.
*/
if (keyFile.getConfig().contains("Keys")) {
for (String keyName : keyFile.getConfig().getConfigurationSection("Keys").getKeys(false)) {
int amt = keyFile.getConfig().getInt("Keys." + keyName + ".Item Amount");
int kitAmount = keyFile.getConfig().getInt("Keys." + keyName + ".Amount of kit received");
if (keyFile.contains("Keys")) {
for (String keyName : keyFile.getConfigurationSection("Keys").getKeys(false)) {
int amt = keyFile.getInt("Keys." + keyName + ".Item Amount");
int kitAmount = keyFile.getInt("Keys." + keyName + ".Amount of kit received");
Key key = new Key(keyName, amt, kitAmount);
keyManager.addKey(key);
}
}
if (hologram != null)
hologram.loadHolograms();
}, 10);
}
public ServerVersion getServerVersion() {
return serverVersion;
public void removeHologram(KitBlockData data) {
if (HologramManager.isEnabled()) {
Location location = getKitLocation(data, Settings.HOLOGRAM_LAYOUT.getStringList().size());
HologramManager.removeHologram(location);
}
}
public boolean isServerVersion(ServerVersion version) {
return serverVersion == version;
public void updateHologram(Kit kit) {
for (KitBlockData data : getKitManager().getKitLocations().values()) {
if (data.getKit() != kit) continue;
updateHologram(data);
}
}
public boolean isServerVersion(ServerVersion... versions) {
return ArrayUtils.contains(versions, serverVersion);
public void updateHologram(KitBlockData data) {
if (data != null && data.isInLoadedChunk() && HologramManager.isEnabled()) {
List<String> lines = formatHologram(data);
if (!lines.isEmpty()) {
Location location = getKitLocation(data, lines.size());
if (!data.showHologram()) {
HologramManager.removeHologram(location);
} else {
HologramManager.updateHologram(location, lines);
}
}
}
}
public boolean isServerVersionAtLeast(ServerVersion version) {
return serverVersion.ordinal() >= version.ordinal();
private void loadHolograms() {
Collection<KitBlockData> kitBlocks = getKitManager().getKitLocations().values();
if (kitBlocks.isEmpty()) return;
for (KitBlockData data : kitBlocks) {
updateHologram(data);
}
}
private Location getKitLocation(KitBlockData data, int lines) {
Location location = data.getLocation();
double multi = .1 * lines;
if (data.isDisplayingItems()) {
multi += .25;
}
Material type = location.getBlock().getType();
if (type == Material.TRAPPED_CHEST
|| type == Material.CHEST
|| type.name().contains("SIGN")
|| type == Material.ENDER_CHEST) {
multi -= .10;
}
location.add(0, multi, 0);
return location;
}
private List<String> formatHologram(KitBlockData data) {
getDataManager().updateBlockData(data);
KitType kitType = data.getType();
ArrayList<String> lines = new ArrayList<>();
List<String> order = Settings.HOLOGRAM_LAYOUT.getStringList();
Kit kit = data.getKit();
for (String o : order) {
switch (o.toUpperCase()) {
case "{TITLE}":
String title = kit.getTitle();
if (title == null) {
lines.add(ChatColor.DARK_PURPLE + TextUtils.formatText(kit.getName(), true));
} else {
lines.add(ChatColor.DARK_PURPLE + TextUtils.formatText(title));
}
break;
case "{RIGHT-CLICK}":
if (kitType == KitType.CRATE) {
lines.add(getLocale().getMessage("interface.hologram.crate").getMessage());
break;
}
if (kit.getLink() != null) {
lines.add(getLocale().getMessage("interface.hologram.buylink").getMessage());
break;
}
if (kit.getPrice() != 0) {
lines.add(getLocale().getMessage("interface.hologram.buyeco")
.processPlaceholder("price", kit.getPrice() != 0
? Methods.formatEconomy(kit.getPrice())
: getLocale().getMessage("general.type.free").getMessage())
.getMessage());
}
break;
case "{LEFT-CLICK}":
if (kitType == KitType.CLAIM) {
lines.add(getLocale().getMessage("interface.hologram.daily").getMessage());
break;
}
if (kit.getLink() == null && kit.getPrice() == 0) {
lines.add(getLocale().getMessage("interface.hologram.previewonly").getMessage());
} else {
lines.add(getLocale().getMessage("interface.hologram.preview").getMessage());
}
break;
default:
lines.add(ChatColor.translateAlternateColorCodes('&', o));
break;
}
}
return lines;
}
/*
* Saves registered kits to file.
*/
private void saveToFile() {
private void saveKits() {
// Wipe old kit information
kitFile.getConfig().set("Kits", null);
// Hot fix for kit file resets.
for (String kitName : kitFile.getConfigurationSection("Kits").getKeys(false)) {
if (kitManager.getKits().stream().noneMatch(kit -> kit.getName().equals(kitName)))
kitFile.set("Kits." + kitName, null);
}
/*
* Save kit from KitManager to Configuration.
*/
for (Kit kit : kitManager.getKits()) {
kitFile.getConfig().set("Kits." + kit.getName() + ".delay", kit.getDelay());
kitFile.getConfig().set("Kits." + kit.getName() + ".title", kit.getTitle());
kitFile.getConfig().set("Kits." + kit.getName() + ".link", kit.getLink());
kitFile.getConfig().set("Kits." + kit.getName() + ".price", kit.getPrice());
kitFile.getConfig().set("Kits." + kit.getName() + ".hidden", kit.isHidden());
kitFile.getConfig().set("Kits." + kit.getName() + ".animation", kit.getKitAnimation().name());
kitFile.set("Kits." + kit.getName() + ".delay", kit.getDelay());
kitFile.set("Kits." + kit.getName() + ".title", kit.getTitle());
kitFile.set("Kits." + kit.getName() + ".link", kit.getLink());
kitFile.set("Kits." + kit.getName() + ".price", kit.getPrice());
kitFile.set("Kits." + kit.getName() + ".hidden", kit.isHidden());
kitFile.set("Kits." + kit.getName() + ".animation", kit.getKitAnimation().name());
if (kit.getDisplayItem() != null)
kitFile.getConfig().set("Kits." + kit.getName() + ".displayItem", kit.getDisplayItem().toString());
kitFile.set("Kits." + kit.getName() + ".displayItem", kit.getDisplayItem().toString());
else
kitFile.set("Kits." + kit.getName() + ".displayItem", null);
List<KitItem> contents = kit.getContents();
List<String> strContents = new ArrayList<>();
for (KitItem item : contents) strContents.add(item.getSerialized());
kitFile.getConfig().set("Kits." + kit.getName() + ".items", strContents);
kitFile.set("Kits." + kit.getName() + ".items", strContents);
}
// Save to file
kitFile.saveConfig();
kitFile.saveChanges();
}
/*
* Insert default key list into config.
*/
private void checkKeyDefaults() {
if (keyFile.getConfig().contains("Keys")) return;
keyFile.getConfig().set("Keys.Regular.Item Amount", 3);
keyFile.getConfig().set("Keys.Regular.Amount overrides", Collections.singletonList("Tools:2"));
keyFile.getConfig().set("Keys.Regular.Amount of kit received", 1);
keyFile.getConfig().set("Keys.Ultra.Item Amount", -1);
keyFile.getConfig().set("Keys.Ultra.Amount of kit received", 1);
keyFile.getConfig().set("Keys.Insane.Item Amount", -1);
keyFile.getConfig().set("Keys.Insane.Amount of kit received", 2);
keyFile.saveConfig();
}
/**
* Reload plugin yaml files.
*/
public void reload() {
this.dataManager.bulkUpdateBlockData(this.getKitManager().getKitLocations());
kitFile.reloadConfig();
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode"));
this.locale.reloadMessages();
settingsManager.reloadConfig();
loadFromFile();
Bukkit.getScheduler().runTaskLater(this, () -> {
this.dataManager.getBlockData((blockData) -> {
this.kitManager.setKitLocations(blockData);
kitManager.getKitLocations().forEach((location, data) -> {
UltimateKits.getInstance().getHologram().add(data);
});
});
}, 20L);
if (keyFile.contains("Keys")) return;
keyFile.set("Keys.Regular.Item Amount", 3);
keyFile.set("Keys.Regular.Amount overrides", Collections.singletonList("Tools:2"));
keyFile.set("Keys.Regular.Amount of kit received", 1);
keyFile.set("Keys.Ultra.Item Amount", -1);
keyFile.set("Keys.Ultra.Amount of kit received", 1);
keyFile.set("Keys.Insane.Item Amount", -1);
keyFile.set("Keys.Insane.Amount of kit received", 2);
}
/**
@ -381,7 +452,7 @@ public class UltimateKits extends JavaPlugin {
*
* @return instance of KitFile
*/
public ConfigWrapper getKitFile() {
public Config getKitFile() {
return kitFile;
}
@ -390,26 +461,16 @@ public class UltimateKits extends JavaPlugin {
*
* @return instance of DataFile
*/
public ConfigWrapper getDataFile() {
public Config getDataFile() {
return dataFile;
}
public SettingsManager getSettingsManager() {
return settingsManager;
}
public CommandManager getCommandManager() {
return commandManager;
}
public Hologram getHologram() {
return hologram;
}
public Economy getEconomy() {
return economy;
public GuiManager getGuiManager() {
return guiManager;
}
/**
@ -421,10 +482,6 @@ public class UltimateKits extends JavaPlugin {
return this.itemSerializer;
}
public Locale getLocale() {
return locale;
}
public DisplayItemHandler getDisplayItemHandler() {
return displayItemHandler;
}

View File

@ -1,72 +0,0 @@
package com.songoda.ultimatekits.command;
import com.songoda.ultimatekits.UltimateKits;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class AbstractCommand {
private final boolean noConsole;
private AbstractCommand parent = null;
private boolean hasArgs = false;
private String command;
private List<String> subCommand = new ArrayList<>();
protected AbstractCommand(AbstractCommand parent, boolean noConsole, String... command) {
if (parent != null) {
this.subCommand = Arrays.asList(command);
} else {
this.command = Arrays.asList(command).get(0);
}
this.parent = parent;
this.noConsole = noConsole;
}
protected AbstractCommand(boolean noConsole, boolean hasArgs, String... command) {
this.command = Arrays.asList(command).get(0);
this.hasArgs = hasArgs;
this.noConsole = noConsole;
}
public AbstractCommand getParent() {
return parent;
}
public String getCommand() {
return command;
}
public List<String> getSubCommand() {
return subCommand;
}
public void addSubCommand(String command) {
subCommand.add(command);
}
protected abstract ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args);
protected abstract List<String> onTab(UltimateKits instance, CommandSender sender, String... args);
public abstract String getPermissionNode();
public abstract String getSyntax();
public abstract String getDescription();
public boolean hasArgs() {
return hasArgs;
}
public boolean isNoConsole() {
return noConsole;
}
public enum ReturnType {SUCCESS, FAILURE, SYNTAX_ERROR}
}

View File

@ -1,95 +0,0 @@
package com.songoda.ultimatekits.command;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.commands.*;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CommandManager implements CommandExecutor {
private UltimateKits plugin;
private TabManager tabManager;
private List<AbstractCommand> commands = new ArrayList<>();
public CommandManager(UltimateKits plugin) {
this.plugin = plugin;
this.tabManager = new TabManager(this);
plugin.getCommand("kitadmin").setExecutor(this);
plugin.getCommand("kit").setExecutor(this);
plugin.getCommand("previewkit").setExecutor(this);
addCommand(new CommandKit());
addCommand(new CommandPreviewKit());
AbstractCommand commandUltimateKits = addCommand(new CommandUltimateKits());
addCommand(new CommandReload(commandUltimateKits));
addCommand(new CommandSettings(commandUltimateKits));
addCommand(new CommandCreatekit(commandUltimateKits));
addCommand(new CommandEdit(commandUltimateKits));
addCommand(new CommandKey(commandUltimateKits));
addCommand(new CommandSet(commandUltimateKits));
addCommand(new CommandRemove(commandUltimateKits));
for (AbstractCommand abstractCommand : commands) {
if (abstractCommand.getParent() != null) continue;
plugin.getCommand(abstractCommand.getCommand()).setTabCompleter(tabManager);
}
}
private AbstractCommand addCommand(AbstractCommand abstractCommand) {
commands.add(abstractCommand);
return abstractCommand;
}
@Override
public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
for (AbstractCommand abstractCommand : commands) {
if (abstractCommand.getCommand() != null && abstractCommand.getCommand().equalsIgnoreCase(command.getName().toLowerCase())) {
if (strings.length == 0 || abstractCommand.hasArgs()) {
processRequirements(abstractCommand, commandSender, strings);
return true;
}
} else if (strings.length != 0 && abstractCommand.getParent() != null && abstractCommand.getParent().getCommand().equalsIgnoreCase(command.getName())) {
String cmd = strings[0];
String cmd2 = strings.length >= 2 ? String.join(" ", strings[0], strings[1]) : null;
for (String cmds : abstractCommand.getSubCommand()) {
if (cmd.equalsIgnoreCase(cmds) || (cmd2 != null && cmd2.equalsIgnoreCase(cmds))) {
processRequirements(abstractCommand, commandSender, strings);
return true;
}
}
}
}
plugin.getLocale().newMessage("&7The command you entered does not exist or is spelt incorrectly.").sendPrefixedMessage(commandSender);
return true;
}
private void processRequirements(AbstractCommand command, CommandSender sender, String[] strings) {
if (!(sender instanceof Player) && command.isNoConsole()) {
sender.sendMessage("You must be a player to use this command.");
return;
}
if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) {
AbstractCommand.ReturnType returnType = command.runCommand(plugin, sender, strings);
if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) {
plugin.getLocale().newMessage("&cInvalid Syntax!").sendPrefixedMessage(sender);
plugin.getLocale().newMessage("&7The valid syntax is: &6" + command.getSyntax() + "&7.").sendPrefixedMessage(sender);
}
return;
}
plugin.getLocale().getMessage("event.general.nopermission").sendPrefixedMessage(sender);
}
public List<AbstractCommand> getCommands() {
return Collections.unmodifiableList(commands);
}
}

View File

@ -1,65 +0,0 @@
package com.songoda.ultimatekits.command;
import com.songoda.ultimatekits.UltimateKits;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import java.util.ArrayList;
import java.util.List;
public class TabManager implements TabCompleter {
private final CommandManager commandManager;
TabManager(CommandManager commandManager) {
this.commandManager = commandManager;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] strings) {
for (AbstractCommand abstractCommand : commandManager.getCommands()) {
if (command.getPermission() != null && !sender.hasPermission(command.getPermission())) continue;
if (abstractCommand.getCommand() != null && abstractCommand.getCommand().equalsIgnoreCase(command.getName()) && !abstractCommand.hasArgs()) {
if (strings.length == 1) {
List<String> subs = new ArrayList<>();
for (AbstractCommand ac : commandManager.getCommands()) {
if (ac.getSubCommand() == null) continue;
subs.addAll(ac.getSubCommand());
}
subs.removeIf(s -> !s.toLowerCase().startsWith(strings[0].toLowerCase()));
return subs;
}
} else if (strings.length != 0 && abstractCommand.getParent() != null && abstractCommand.getParent().getCommand().equalsIgnoreCase(command.getName())
|| abstractCommand.hasArgs() && abstractCommand.getCommand().equalsIgnoreCase(command.getName())) {
String[] args = abstractCommand.hasArgs() ? (String[]) ArrayUtils.add(strings, 0, command.getName()) : strings;
String cmd = abstractCommand.hasArgs() ? command.getName() : args[0];
String cmd2 = args.length >= 2 ? String.join(" ", args[0], args[1]) : null;
if (!abstractCommand.hasArgs()) {
for (String cmds : abstractCommand.getSubCommand()) {
if (cmd.equalsIgnoreCase(cmds) || (cmd2 != null && cmd2.equalsIgnoreCase(cmds))) {
return fetchList(abstractCommand, args, sender);
}
}
} else {
return fetchList(abstractCommand, args, sender);
}
}
}
return new ArrayList<>();
}
private List<String> fetchList(AbstractCommand abstractCommand, String[] args, CommandSender sender) {
List<String> list = abstractCommand.onTab(UltimateKits.getInstance(), sender, args);
String str = args[args.length - 1];
if (list != null && str != null && str.length() >= 1) {
try {
list.removeIf(s -> !s.toLowerCase().startsWith(str.toLowerCase()));
} catch (UnsupportedOperationException ignored) {
}
}
return list;
}
}

View File

@ -1,77 +0,0 @@
package com.songoda.ultimatekits.command.commands;
import bammerbom.ultimatecore.bukkit.UltimateMetrics;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.gui.GUIBlockEditor;
import com.songoda.ultimatekits.gui.GUIKitEditor;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.kit.KitManager;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class CommandEdit extends AbstractCommand {
public CommandEdit(AbstractCommand parent) {
super(parent, true, "edit");
}
@Override
protected ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
Player player = (Player) sender;
Block block = player.getTargetBlock(null, 200);
KitBlockData kitBlockData = instance.getKitManager().getKit(block.getLocation());
if (args.length > 2) return ReturnType.SYNTAX_ERROR;
if (args.length == 1) {
if (kitBlockData == null) {
instance.getLocale().newMessage("&8This block does not contain a kit.").sendPrefixedMessage(player);
return ReturnType.FAILURE;
}
new GUIBlockEditor(instance, player, block.getLocation());
} else {
String kitStr = args[1].toLowerCase().trim();
if (instance.getKitManager().getKit(kitStr) == null) {
instance.getLocale().getMessage("command.kit.kitdoesntexist").sendPrefixedMessage(player);
return ReturnType.FAILURE;
}
new GUIKitEditor(instance, player, instance.getKitManager().getKit(kitStr), null, null, 0);
}
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
if (!(sender instanceof Player)) return null;
List<String> tab = new ArrayList<>();
if (args.length == 2) {
for (Kit kit : UltimateKits.getInstance().getKitManager().getKits())
tab.add(kit.getName());
return tab;
}
return tab;
}
@Override
public String getPermissionNode() {
return "ultimatekits.admin";
}
@Override
public String getSyntax() {
return "/KitAdmin edit <kit>";
}
@Override
public String getDescription() {
return "Edit a kit.";
}
}

View File

@ -1,28 +1,33 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.gui.GuiManager;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.gui.GUIKitEditor;
import com.songoda.ultimatekits.gui.KitEditorGui;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CommandCreatekit extends AbstractCommand {
public CommandCreatekit(AbstractCommand parent) {
super(parent, true, "createkit");
final UltimateKits instance = UltimateKits.getInstance();
final GuiManager guiManager;
public CommandCreatekit(GuiManager guiManager) {
super(true, "createkit");
this.guiManager = guiManager;
}
@Override
protected ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
protected ReturnType runCommand(CommandSender sender, String... args) {
Player player = (Player) sender;
if (args.length != 2) return ReturnType.SYNTAX_ERROR;
String kitStr = args[1].toLowerCase();
if (args.length != 1) {
return ReturnType.SYNTAX_ERROR;
}
String kitStr = args[0].toLowerCase();
if (instance.getKitManager().getKit(kitStr) != null) {
instance.getLocale().getMessage("command.kit.kitalreadyexists").sendPrefixedMessage(player);
return ReturnType.FAILURE;
@ -31,12 +36,12 @@ public class CommandCreatekit extends AbstractCommand {
instance.getLocale().newMessage("&aThat kit doesn't exist. Creating it now.").sendPrefixedMessage(player);
Kit kit = new Kit(kitStr.trim());
UltimateKits.getInstance().getKitManager().addKit(kit);
new GUIKitEditor(instance, player, kit, null, null, 0);
guiManager.showGUI(player, new KitEditorGui(instance, player, kit, null));
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
protected List<String> onTab(CommandSender sender, String... args) {
return Arrays.asList("name");
}

View File

@ -0,0 +1,77 @@
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.gui.GuiManager;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.gui.BlockEditorGui;
import com.songoda.ultimatekits.gui.KitEditorGui;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class CommandEdit extends AbstractCommand {
final UltimateKits instance = UltimateKits.getInstance();
final GuiManager guiManager;
public CommandEdit(GuiManager guiManager) {
super(true, "edit");
this.guiManager = guiManager;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length > 1) return ReturnType.SYNTAX_ERROR;
final Player player = (Player) sender;
if (args.length == 0) {
Block block = player.getTargetBlock(null, 200);
KitBlockData kitBlockData = instance.getKitManager().getKit(block.getLocation());
if (kitBlockData == null) {
instance.getLocale().newMessage("command.kit.nokitatblock").sendPrefixedMessage(player);
return ReturnType.FAILURE;
}
guiManager.showGUI(player, new BlockEditorGui(instance, kitBlockData));
} else {
String kitStr = args[0].toLowerCase().trim();
if (instance.getKitManager().getKit(kitStr) == null) {
instance.getLocale().getMessage("command.kit.kitdoesntexist").sendPrefixedMessage(player);
return ReturnType.FAILURE;
}
guiManager.showGUI(player, new KitEditorGui(instance, player, instance.getKitManager().getKit(kitStr), null));
}
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
List<String> tab = new ArrayList<>();
if (args.length == 1) {
for (Kit kit : UltimateKits.getInstance().getKitManager().getKits())
tab.add(kit.getName());
return tab;
}
return tab;
}
@Override
public String getPermissionNode() {
return "ultimatekits.admin";
}
@Override
public String getSyntax() {
return "/KitAdmin edit <kit>";
}
@Override
public String getDescription() {
return "Edit a kit.";
}
}

View File

@ -1,7 +1,8 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.utils.PlayerUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.key.Key;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
@ -14,31 +15,34 @@ import java.util.Arrays;
import java.util.List;
public class CommandKey extends AbstractCommand {
final UltimateKits instance = UltimateKits.getInstance();
public CommandKey(AbstractCommand parent) {
super(parent, false, "key");
public CommandKey() {
super(false, "key");
}
@Override
protected ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
if (args.length != 4 && args.length != 5) {
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length != 3 && args.length != 4) {
return ReturnType.SYNTAX_ERROR;
}
Kit kit = instance.getKitManager().getKit(args[1]);
if (kit == null && !args[1].toLowerCase().equals("all")) {
Kit kit = instance.getKitManager().getKit(args[0]);
if (kit == null && !args[0].toLowerCase().equals("all")) {
instance.getLocale().getMessage("command.kit.kitdoesntexist").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
if (Bukkit.getPlayer(args[3]) == null && !args[3].trim().equalsIgnoreCase("all")) {
Player playerTo = null;
if (!args[2].trim().equalsIgnoreCase("all") && (playerTo = Bukkit.getPlayer(args[2])) == null) {
instance.getLocale().newMessage("&cThat username does not exist, or the user is offline!").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
int amt = 1;
if (args.length == 5) {
if (!Methods.isNumeric(args[4])) {
if (args.length == 4) {
if (!Methods.isNumeric(args[3])) {
amt = 0;
} else {
amt = Integer.parseInt(args[4]);
amt = Integer.parseInt(args[3]);
}
}
if (amt == 0) {
@ -46,23 +50,22 @@ public class CommandKey extends AbstractCommand {
return ReturnType.FAILURE;
}
Key key = instance.getKeyManager().getKey(args[2]);
Key key = instance.getKeyManager().getKey(args[1]);
if (key == null) {
instance.getLocale().newMessage("&a" + args[3] + " &cis not a key.").sendPrefixedMessage(sender);
instance.getLocale().newMessage("&a" + args[1] + " &cis not a key.").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
if (!args[3].trim().equals("all")) {
Player p = Bukkit.getPlayer(args[3]);
p.getInventory().addItem(key.getKeyItem(kit, amt));
if (playerTo != null) {
PlayerUtils.giveItem(playerTo, key.getKeyItem(kit, amt));
instance.getLocale().getMessage("event.key.given")
.processPlaceholder("kit", kit == null ? "Any" : kit.getShowableName())
.sendPrefixedMessage(p);
.sendPrefixedMessage(playerTo);
return ReturnType.SUCCESS;
}
for (Player pl : instance.getServer().getOnlinePlayers()) {
pl.getInventory().addItem(key.getKeyItem(kit, amt));
PlayerUtils.giveItem(playerTo, key.getKeyItem(kit, amt));
instance.getLocale().getMessage("event.key.given")
.processPlaceholder("kit", kit == null ? "Any" : kit.getShowableName())
.sendPrefixedMessage(pl);
@ -71,26 +74,26 @@ public class CommandKey extends AbstractCommand {
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
protected List<String> onTab(CommandSender sender, String... args) {
if (!(sender instanceof Player)) return null;
List<String> tab = new ArrayList<>();
if (args.length == 2) {
if (args.length == 1) {
tab.add("all");
for (Kit kit : UltimateKits.getInstance().getKitManager().getKits())
tab.add(kit.getName());
return tab;
} else if (args.length == 3) {
} else if (args.length == 2) {
for (Key key : UltimateKits.getInstance().getKeyManager().getKeys())
tab.add(key.getName());
return tab;
} else if (args.length == 4) {
} else if (args.length == 3) {
tab.add("all");
for (Player player : Bukkit.getOnlinePlayers())
tab.add(player.getName());
return tab;
} else if (args.length == 5) return Arrays.asList("amount");
} else if (args.length == 4) return Arrays.asList("amount");
return tab;
}

View File

@ -1,8 +1,9 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.gui.GuiManager;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.gui.GUIKitSelector;
import com.songoda.ultimatekits.gui.KitSelectorGui;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Bukkit;
@ -14,12 +15,16 @@ import java.util.List;
public class CommandKit extends AbstractCommand {
public CommandKit() {
super(false, true,"kit");
final UltimateKits instance = UltimateKits.getInstance();
final GuiManager guiManager;
public CommandKit(GuiManager guiManager) {
super(true, "kit");
this.guiManager = guiManager;
}
@Override
protected ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
protected ReturnType runCommand(CommandSender sender, String... args) {
if (!(sender instanceof Player) && args.length != 2) {
sender.sendMessage("Kits:");
for (Kit kit : instance.getKitManager().getKits()) {
@ -28,10 +33,8 @@ public class CommandKit extends AbstractCommand {
return ReturnType.SUCCESS;
}
if (args.length == 0) {
new GUIKitSelector(instance, (Player) sender);
return ReturnType.SUCCESS;
}
if (args.length == 1) {
guiManager.showGUI((Player) sender, new KitSelectorGui(instance, (Player) sender));
} else if (args.length == 1) {
Player player = (Player) sender;
String kitName = args[0].toLowerCase();
if (instance.getKitManager().getKit(kitName) == null) {
@ -42,22 +45,20 @@ public class CommandKit extends AbstractCommand {
if (sender.hasPermission("ultimatekits.admin")) {
kit.processGenericUse(player, true);
} else {
kit.buy(player);
kit.buy(player, guiManager);
}
return ReturnType.SUCCESS;
}
if (args.length == 2) {
} else if (args.length == 2) {
String kitName = args[0].toLowerCase();
if (instance.getKitManager().getKit(kitName) == null) {
instance.getLocale().getMessage("command.kit.kitdoesntexist").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
if (Bukkit.getPlayerExact(args[1]) == null) {
Player player2 = Bukkit.getPlayer(args[1]);
if (player2 == null || !player2.isOnline()) {
instance.getLocale().getMessage("command.kit.playernotfound").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
Player player2 = Bukkit.getPlayer(args[1]);
if (sender instanceof Player) {
Player player = (Player) sender;
if (!Methods.canGiveKit(player)) {
@ -70,13 +71,14 @@ public class CommandKit extends AbstractCommand {
kit.processGenericUse(player2, true);
instance.getLocale().newMessage("&7You gave &9" + player2.getDisplayName() + "&7 kit &9" + kit.getShowableName() + "&7.")
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
} else {
return ReturnType.SYNTAX_ERROR;
}
return ReturnType.SYNTAX_ERROR;
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
protected List<String> onTab(CommandSender sender, String... args) {
return new ArrayList<>();
}

View File

@ -1,7 +1,8 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.gui.GuiManager;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.kit.Kit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -11,34 +12,41 @@ import java.util.List;
public class CommandPreviewKit extends AbstractCommand {
public CommandPreviewKit() {
super(true, true,"PreviewKit");
final UltimateKits instance = UltimateKits.getInstance();
final GuiManager guiManager;
public CommandPreviewKit(GuiManager guiManager) {
super(true, "PreviewKit");
this.guiManager = guiManager;
}
@Override
protected ReturnType runCommand(UltimateKits plugin, CommandSender sender, String... args) {
protected ReturnType runCommand(CommandSender sender, String... args) {
Player player = (Player) sender;
if (args.length != 1) {
plugin.getLocale().getMessage("command.kit.nokitsupplied").sendPrefixedMessage(player);
instance.getLocale().getMessage("command.kit.nokitsupplied").sendPrefixedMessage(player);
return ReturnType.FAILURE;
}
Kit kit = plugin.getKitManager().getKit(args[0].toLowerCase().trim());
Kit kit = instance.getKitManager().getKit(args[0].toLowerCase().trim());
if (kit == null) {
plugin.getLocale().getMessage("command.kit.kitdoesntexist").sendPrefixedMessage(player);
instance.getLocale().getMessage("command.kit.kitdoesntexist").sendPrefixedMessage(player);
return ReturnType.FAILURE;
}
kit.display(player, null);
kit.display(player, guiManager, null);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
if (!(sender instanceof Player)) return null;
protected List<String> onTab(CommandSender sender, String... args) {
if (!(sender instanceof Player)) {
return null;
}
if (args.length == 2) {
List<String> tab = new ArrayList<>();
for (Kit kit : UltimateKits.getInstance().getKitManager().getKits())
for (Kit kit : UltimateKits.getInstance().getKitManager().getKits()) {
tab.add(kit.getName());
}
return tab;
}
return new ArrayList<>();

View File

@ -1,8 +1,7 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
@ -10,19 +9,20 @@ import java.util.List;
public class CommandReload extends AbstractCommand {
public CommandReload(AbstractCommand parent) {
super(parent, false, "reload");
final UltimateKits instance = UltimateKits.getInstance();
public CommandReload() {
super(false, "reload");
}
@Override
protected ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
instance.reload();
protected ReturnType runCommand(CommandSender sender, String... args) {
instance.reloadConfig();
instance.getLocale().getMessage("&7Configuration and Language files reloaded.").sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
protected List<String> onTab(CommandSender sender, String... args) {
return new ArrayList<>();
}

View File

@ -1,7 +1,8 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.hooks.HologramManager;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.kit.Kit;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
@ -12,29 +13,30 @@ import java.util.List;
public class CommandRemove extends AbstractCommand {
public CommandRemove(AbstractCommand parent) {
super(parent, true, "remove");
final UltimateKits instance = UltimateKits.getInstance();
public CommandRemove() {
super(true, "remove");
}
@Override
protected ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
if (args.length != 1) {
instance.getLocale().getMessage("command.kit.nokitsupplied").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
protected ReturnType runCommand(CommandSender sender, String... args) {
Player player = (Player) sender;
Block block = player.getTargetBlock(null, 200);
Kit kit = instance.getKitManager().removeKitFromLocation(block.getLocation());
if (kit == null) return ReturnType.FAILURE;
if (instance.getHologram() != null)
instance.getHologram().remove(kit);
if (HologramManager.isEnabled()) {
instance.getKitManager().getKitLocations().values().stream()
.filter(data -> data.getKit() == kit)
.forEach(data -> instance.removeHologram(data));
}
instance.getLocale().newMessage("&8Kit &9" + kit.getName() + " &8unassigned from: &a" + block.getType().toString() + "&8.").sendPrefixedMessage(player);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
protected List<String> onTab(CommandSender sender, String... args) {
return new ArrayList<>();
}

View File

@ -1,10 +1,9 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -14,18 +13,20 @@ import java.util.List;
public class CommandSet extends AbstractCommand {
public CommandSet(AbstractCommand parent) {
super(parent, true, "set");
final UltimateKits instance = UltimateKits.getInstance();
public CommandSet() {
super(true, "set");
}
@Override
protected ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
if (args.length != 2) {
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length != 1) {
instance.getLocale().getMessage("command.kit.nokitsupplied").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
Player player = (Player) sender;
Kit kit = instance.getKitManager().getKit(args[1].toLowerCase());
Kit kit = instance.getKitManager().getKit(args[0].toLowerCase());
if (kit == null) {
instance.getLocale().getMessage("command.kit.kitdoesntexist").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
@ -36,16 +37,20 @@ public class CommandSet extends AbstractCommand {
instance.getLocale().newMessage("&8Kit &a" + kit.getName() + " &8set to: &a" + b.getType().toString() + "&8.")
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
if (!(sender instanceof Player)) return null;
protected List<String> onTab(CommandSender sender, String... args) {
if (!(sender instanceof Player)) {
return null;
}
if (args.length == 2) {
if (args.length == 1) {
List<String> tab = new ArrayList<>();
for (Kit kit : UltimateKits.getInstance().getKitManager().getKits())
for (Kit kit : UltimateKits.getInstance().getKitManager().getKits()) {
tab.add(kit.getName());
}
return tab;
}
return new ArrayList<>();

View File

@ -1,7 +1,9 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.configuration.editor.PluginConfigGui;
import com.songoda.core.gui.GuiManager;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -10,18 +12,22 @@ import java.util.List;
public class CommandSettings extends AbstractCommand {
public CommandSettings(AbstractCommand parent) {
super(parent, true, "settings");
final UltimateKits instance = UltimateKits.getInstance();
final GuiManager guiManager;
public CommandSettings(GuiManager guiManager) {
super(true, "settings");
this.guiManager = guiManager;
}
@Override
protected ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
instance.getSettingsManager().openSettingsManager((Player) sender);
protected ReturnType runCommand(CommandSender sender, String... args) {
guiManager.showGUI((Player) sender, new PluginConfigGui(instance));
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
protected List<String> onTab(CommandSender sender, String... args) {
return new ArrayList<>();
}

View File

@ -1,28 +1,30 @@
package com.songoda.ultimatekits.command.commands;
package com.songoda.ultimatekits.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.command.AbstractCommand;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.command.CommandSender;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.List;
public class CommandUltimateKits extends AbstractCommand {
final UltimateKits instance = UltimateKits.getInstance();
public CommandUltimateKits() {
super(null, false, "KitAdmin");
super(false, "KitAdmin");
}
@Override
protected AbstractCommand.ReturnType runCommand(UltimateKits instance, CommandSender sender, String... args) {
protected AbstractCommand.ReturnType runCommand(CommandSender sender, String... args) {
sender.sendMessage("");
instance.getLocale().newMessage("&7Version " + instance.getDescription().getVersion()
+ " Created with <3 by &5&l&oSongoda").sendPrefixedMessage(sender);
for (AbstractCommand command : instance.getCommandManager().getCommands()) {
for (AbstractCommand command : instance.getCommandManager().getAllCommands()) {
if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) {
sender.sendMessage(Methods.formatText("&8 - &a" + command.getSyntax() + "&7 - " + command.getDescription()));
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8 - &a" + command.getSyntax() + "&7 - " + command.getDescription()));
}
}
sender.sendMessage("");
@ -31,7 +33,7 @@ public class CommandUltimateKits extends AbstractCommand {
}
@Override
protected List<String> onTab(UltimateKits instance, CommandSender sender, String... args) {
protected List<String> onTab(CommandSender sender, String... args) {
return new ArrayList<>();
}

View File

@ -10,68 +10,53 @@ import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
public class Convert {
private final UltimateKits instance;
private Hook hook;
public Convert(UltimateKits instance) {
this.instance = instance;
if (instance.getServer().getPluginManager().getPlugin("Essentials") != null) {
try {
Class.forName("com.earth2me.essentials.metrics.MetricsListener");
hook = new DefaultHook();
} catch (ClassNotFoundException ex) {
hook = new EssentialsHook();
public static void runKitConversions() {
if (!UltimateKits.getInstance().getKitFile().contains("Kits")) {
if (Bukkit.getPluginManager().isPluginEnabled("Essentials")) {
try {
Class.forName("com.earth2me.essentials.metrics.MetricsListener");
} catch (ClassNotFoundException ex) {
convertKits(new EssentialsHook());
}
}
if (Bukkit.getPluginManager().isPluginEnabled("UltimateCore")) {
convertKits(new UltimateCoreHook());
}
if (Bukkit.getPluginManager().isPluginEnabled("CMI")) {
convertKits(new CMIHook());
}
} else if (instance.getServer().getPluginManager().getPlugin("UltimateCore") != null) {
hook = new UltimateCoreHook();
} else if (instance.getServer().getPluginManager().getPlugin("CMI") != null) {
hook = new CMIHook();
} else {
hook = new DefaultHook();
}
if (hook.getKits().size() == 0)
hook = new DefaultHook();
convertKits();
if (!isInJsonFormat()) {
convertKits(new DefaultHook());
}
}
private void convertKits() {
private static void convertKits(Hook hook) {
Set<String> kits = hook.getKits();
if (!instance.getKitFile().getConfig().contains("Kits")) {
this.convertKits(kits);
} else if (!isInJsonFormat()) {
hook = new DefaultHook();
this.convertKits(hook.getKits());
}
}
private void convertKits(Set<String> kits) {
for (String kit : kits) {
List<String> serializedItems = new ArrayList<>();
for (ItemStack item : hook.getItems(kit)) {
serializedItems.add(instance.getItemSerializer().serializeItemStackToJson(item));
serializedItems.add(UltimateKits.getInstance().getItemSerializer().serializeItemStackToJson(item));
}
instance.getKitFile().getConfig().set("Kits." + kit + ".items", serializedItems);
instance.getKitFile().getConfig().set("Kits." + kit + ".delay", hook.getDelay(kit));
instance.getKitFile().getConfig().set("Kits." + kit + ".price", 0D);
UltimateKits.getInstance().getKitFile().set("Kits." + kit + ".items", serializedItems);
UltimateKits.getInstance().getKitFile().set("Kits." + kit + ".delay", hook.getDelay(kit));
UltimateKits.getInstance().getKitFile().set("Kits." + kit + ".price", 0D);
}
instance.getKitFile().saveConfig();
UltimateKits.getInstance().getKitFile().save();
}
private boolean isInJsonFormat() {
for (String kit : instance.getKitFile().getConfig().getConfigurationSection("Kits").getKeys(false)) {
if (instance.getKitFile().getConfig().contains("Kits." + kit + ".items")) {
List<String> itemList = instance.getKitFile().getConfig().getStringList("Kits." + kit + ".items");
private static boolean isInJsonFormat() {
for (String kit : UltimateKits.getInstance().getKitFile().getConfigurationSection("Kits").getKeys(false)) {
if (UltimateKits.getInstance().getKitFile().contains("Kits." + kit + ".items")) {
List<String> itemList = UltimateKits.getInstance().getKitFile().getStringList("Kits." + kit + ".items");
if (itemList.size() > 0) {
if (itemList.get(0).startsWith("{"))
if (itemList.get(0).startsWith("{")) {
return true;
}
}
}
}

View File

@ -1,35 +1,27 @@
package com.songoda.ultimatekits.database;
import com.songoda.core.database.DataManagerAbstract;
import com.songoda.core.database.DatabaseConnector;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.kit.KitType;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
public class DataManager {
private final DatabaseConnector databaseConnector;
private final Plugin plugin;
public class DataManager extends DataManagerAbstract {
public DataManager(DatabaseConnector databaseConnector, Plugin plugin) {
this.databaseConnector = databaseConnector;
this.plugin = plugin;
}
public String getTablePrefix() {
return this.plugin.getDescription().getName().toLowerCase() + '_';
super(databaseConnector, plugin);
}
public void bulkUpdateBlockData(Map<Location, KitBlockData> blockData) {
@ -123,10 +115,14 @@ public class DataManager {
try (Statement statement = connection.createStatement()) {
ResultSet result = statement.executeQuery(selectData);
while (result.next()) {
World world = Bukkit.getWorld(result.getString("world"));
if (world == null) continue;
KitType type = KitType.valueOf(result.getString("type"));
String kit = result.getString("kit");
Kit kit = UltimateKits.getInstance().getKitManager().getKit(result.getString("kit"));
KitType type = KitType.getKitType(result.getString("type"));
if (kit == null || type == null) continue;
boolean holograms = result.getBoolean("holograms");
boolean displayItems = result.getBoolean("displayItems");
boolean particles = result.getBoolean("particles");
@ -136,40 +132,12 @@ public class DataManager {
int z = result.getInt("z");
Location location = new Location(world, x, y, z);
KitBlockData kitBlockData =
new KitBlockData(UltimateKits.getInstance().getKitManager().getKit(kit),
location, type, holograms, particles, displayItems, itemOverride);
blockData.put(location, kitBlockData);
blockData.put(location, new KitBlockData(kit, location, type, holograms, particles, displayItems, itemOverride));
}
result.close();
}
this.sync(() -> callback.accept(blockData));
}));
}
private int lastInsertedId(Connection connection) {
String query;
if (this.databaseConnector instanceof SQLiteConnector) {
query = "SELECT last_insert_rowid()";
} else {
query = "SELECT LAST_INSERT_ID()";
}
try (Statement statement = connection.createStatement()) {
ResultSet result = statement.executeQuery(query);
result.next();
return result.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
public void async(Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, runnable);
}
public void sync(Runnable runnable) {
Bukkit.getScheduler().runTask(this.plugin, runnable);
}
}

View File

@ -1,19 +0,0 @@
package com.songoda.ultimatekits.database;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class DataMigration {
private final int revision;
public DataMigration(int revision) {
this.revision = revision;
}
public abstract void migrate(Connection connection, String tablePrefix) throws SQLException;
public int getRevision() {
return this.revision;
}
}

View File

@ -1,110 +0,0 @@
package com.songoda.ultimatekits.database;
import com.songoda.ultimatekits.database.migrations._1_InitialMigration;
import com.songoda.ultimatekits.database.migrations._2_DuplicateMigration;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class DataMigrationManager {
private final List<DataMigration> migrations;
private final DatabaseConnector databaseConnector;
private final DataManager dataManager;
public DataMigrationManager(DatabaseConnector databaseConnector, DataManager dataManager) {
this.databaseConnector = databaseConnector;
this.dataManager = dataManager;
this.migrations = Arrays.asList(
new _1_InitialMigration(),
new _2_DuplicateMigration(databaseConnector instanceof SQLiteConnector)
);
}
/**
* Runs any needed data migrations
*/
public void runMigrations() {
this.databaseConnector.connect((connection -> {
int currentMigration = -1;
boolean migrationsExist;
String query;
if (this.databaseConnector instanceof SQLiteConnector) {
query = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?";
} else {
query = "SHOW TABLES LIKE ?";
}
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, this.getMigrationsTableName());
migrationsExist = statement.executeQuery().next();
}
if (!migrationsExist) {
// No migration table exists, create one
String createTable = "CREATE TABLE " + this.getMigrationsTableName() + " (migration_version INT NOT NULL)";
try (PreparedStatement statement = connection.prepareStatement(createTable)) {
statement.execute();
}
// Insert primary row into migration table
String insertRow = "INSERT INTO " + this.getMigrationsTableName() + " VALUES (?)";
try (PreparedStatement statement = connection.prepareStatement(insertRow)) {
statement.setInt(1, -1);
statement.execute();
}
} else {
// Grab the current migration version
String selectVersion = "SELECT migration_version FROM " + this.getMigrationsTableName();
try (PreparedStatement statement = connection.prepareStatement(selectVersion)) {
ResultSet result = statement.executeQuery();
result.next();
currentMigration = result.getInt("migration_version");
}
}
// Grab required migrations
int finalCurrentMigration = currentMigration;
List<DataMigration> requiredMigrations = this.migrations
.stream()
.filter(x -> x.getRevision() > finalCurrentMigration)
.sorted(Comparator.comparingInt(DataMigration::getRevision))
.collect(Collectors.toList());
// Nothing to migrate, abort
if (requiredMigrations.isEmpty())
return;
// Migrate the data
for (DataMigration dataMigration : requiredMigrations)
dataMigration.migrate(connection, this.dataManager.getTablePrefix());
// Set the new current migration to be the highest migrated to
currentMigration = requiredMigrations
.stream()
.map(DataMigration::getRevision)
.max(Integer::compareTo)
.orElse(-1);
String updateVersion = "UPDATE " + this.getMigrationsTableName() + " SET migration_version = ?";
try (PreparedStatement statement = connection.prepareStatement(updateVersion)) {
statement.setInt(1, currentMigration);
statement.execute();
}
}));
}
/**
* @return the name of the migrations table
*/
private String getMigrationsTableName() {
return this.dataManager.getTablePrefix() + "migrations";
}
}

View File

@ -1,34 +0,0 @@
package com.songoda.ultimatekits.database;
import java.sql.Connection;
import java.sql.SQLException;
public interface DatabaseConnector {
/**
* Checks if the connection to the database has been created
*
* @return true if the connection is created, otherwise false
*/
boolean isInitialized();
/**
* Closes all open connections to the database
*/
void closeConnection();
/**
* Executes a callback with a Connection passed and automatically closes it when finished
*
* @param callback The callback to execute once the connection is retrieved
*/
void connect(ConnectionCallback callback);
/**
* Wraps a connection in a callback which will automagically handle catching sql errors
*/
interface ConnectionCallback {
void accept(Connection connection) throws SQLException;
}
}

View File

@ -1,49 +0,0 @@
package com.songoda.ultimatekits.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.bukkit.plugin.Plugin;
import java.sql.Connection;
import java.sql.SQLException;
public class MySQLConnector implements DatabaseConnector {
private final Plugin plugin;
private HikariDataSource hikari;
private boolean initializedSuccessfully;
public MySQLConnector(Plugin plugin, String hostname, int port, String database, String username, String password, boolean useSSL) {
this.plugin = plugin;
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://" + hostname + ":" + port + "/" + database + "?useSSL=" + useSSL);
config.setUsername(username);
config.setPassword(password);
config.setMaximumPoolSize(3);
try {
this.hikari = new HikariDataSource(config);
this.initializedSuccessfully = true;
} catch (Exception ex) {
this.initializedSuccessfully = false;
}
}
public boolean isInitialized() {
return this.initializedSuccessfully;
}
public void closeConnection() {
this.hikari.close();
}
public void connect(ConnectionCallback callback) {
try (Connection connection = this.hikari.getConnection()) {
callback.accept(connection);
} catch (SQLException ex) {
this.plugin.getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
ex.printStackTrace();
}
}
}

View File

@ -1,58 +0,0 @@
package com.songoda.ultimatekits.database;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLiteConnector implements DatabaseConnector {
private final Plugin plugin;
private final String connectionString;
private Connection connection;
public SQLiteConnector(Plugin plugin) {
this.plugin = plugin;
this.connectionString = "jdbc:sqlite:" + plugin.getDataFolder() + File.separator + plugin.getDescription().getName().toLowerCase() + ".db";
try {
Class.forName("org.sqlite.JDBC"); // This is required to put here for Spigot 1.10 and below for some reason
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public boolean isInitialized() {
return true; // Always available
}
public void closeConnection() {
try {
if (this.connection != null) {
this.connection.close();
}
} catch (SQLException ex) {
this.plugin.getLogger().severe("An error occurred closing the SQLite database connection: " + ex.getMessage());
}
}
public void connect(ConnectionCallback callback) {
if (this.connection == null) {
try {
this.connection = DriverManager.getConnection(this.connectionString);
} catch (SQLException ex) {
this.plugin.getLogger().severe("An error occurred retrieving the SQLite database connection: " + ex.getMessage());
}
}
try {
callback.accept(this.connection);
} catch (Exception ex) {
this.plugin.getLogger().severe("An error occurred executing an SQLite query: " + ex.getMessage());
ex.printStackTrace();
}
}
}

View File

@ -1,6 +1,6 @@
package com.songoda.ultimatekits.database.migrations;
import com.songoda.ultimatekits.database.DataMigration;
import com.songoda.core.database.DataMigration;
import java.sql.Connection;
import java.sql.SQLException;
@ -14,8 +14,8 @@ public class _1_InitialMigration extends DataMigration {
@Override
public void migrate(Connection connection, String tablePrefix) throws SQLException {
//String autoIncrement = UltimateKits.getInstance().getDatabaseConnector() instanceof
// MySQLConnector ? " AUTO_INCREMENT" : "";
// String autoIncrement = UltimateKits.getInstance().getDatabaseConnector() instanceof
// MySQLConnector ? " AUTO_INCREMENT" : "";
// Create plugin settings table
try (Statement statement = connection.createStatement()) {

View File

@ -1,99 +1,99 @@
package com.songoda.ultimatekits.database.migrations;
import com.songoda.ultimatekits.database.DataMigration;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
public class _2_DuplicateMigration extends DataMigration {
final boolean sqlite;
public _2_DuplicateMigration(boolean sqlite) {
super(2);
this.sqlite = sqlite;
}
@Override
public void migrate(Connection connection, String tablePrefix) throws SQLException {
// Fix duplicate data caused by old sqlite data duplication bug
if(sqlite) {
HashMap<String, TempKitData> data = new HashMap();
// grab a copy of the unique data values
try (Statement statement = connection.createStatement()) {
ResultSet allData = statement.executeQuery("SELECT * FROM " + tablePrefix + "blockdata");
while (allData.next()) {
String world = allData.getString("world");
int x = allData.getInt("x");
int y = allData.getInt("y");
int z = allData.getInt("z");
String key = world + ";" + x + ";" + y + ";" + z + ";";
if(!data.containsKey(key)) {
data.put(key, new TempKitData(
allData.getString("type"),
allData.getString("kit"),
allData.getBoolean("holograms"),
allData.getBoolean("displayItems"),
allData.getBoolean("particles"),
allData.getBoolean("itemOverride"),
world, x, y, z
));
}
}
allData.close();
}
if(data.isEmpty()) return;
connection.setAutoCommit(false);
// first delete old data
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("DELETE FROM " + tablePrefix + "blockdata");
}
// then re-add valid unique data
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + tablePrefix + "blockdata (" +
"type, kit, holograms, displayItems, particles, itemOverride, world, x, y, z)" +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
for(TempKitData blockData : data.values()) {
statement.setString(1, blockData.type);
statement.setString(2, blockData.kit);
statement.setBoolean(3, blockData.holograms);
statement.setBoolean(4, blockData.displayItems);
statement.setBoolean(5, blockData.particles);
statement.setBoolean(6, blockData.itemOverride);
statement.setString(7, blockData.world);
statement.setInt(8, blockData.x);
statement.setInt(9, blockData.y);
statement.setInt(10, blockData.z);
statement.addBatch();
}
statement.executeBatch();
}
connection.commit();
connection.setAutoCommit(true);
// free up disk space (sqlite command)
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("VACUUM");
}
}
}
static class TempKitData {
final String type, kit, world;
final int x, y, z;
final boolean holograms, displayItems, particles, itemOverride;
public TempKitData(String type, String kit, boolean holograms, boolean displayItems, boolean particles, boolean itemOverride, String world, int x, int y, int z) {
this.type = type;
this.kit = kit;
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.holograms = holograms;
this.displayItems = displayItems;
this.particles = particles;
this.itemOverride = itemOverride;
}
}
}
package com.songoda.ultimatekits.database.migrations;
import com.songoda.core.database.DataMigration;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
public class _2_DuplicateMigration extends DataMigration {
final boolean sqlite;
public _2_DuplicateMigration(boolean sqlite) {
super(2);
this.sqlite = sqlite;
}
@Override
public void migrate(Connection connection, String tablePrefix) throws SQLException {
// Fix duplicate data caused by old sqlite data duplication bug
if(sqlite) {
HashMap<String, TempKitData> data = new HashMap();
// grab a copy of the unique data values
try (Statement statement = connection.createStatement()) {
ResultSet allData = statement.executeQuery("SELECT * FROM " + tablePrefix + "blockdata");
while (allData.next()) {
String world = allData.getString("world");
int x = allData.getInt("x");
int y = allData.getInt("y");
int z = allData.getInt("z");
String key = world + ";" + x + ";" + y + ";" + z + ";";
if(!data.containsKey(key)) {
data.put(key, new TempKitData(
allData.getString("type"),
allData.getString("kit"),
allData.getBoolean("holograms"),
allData.getBoolean("displayItems"),
allData.getBoolean("particles"),
allData.getBoolean("itemOverride"),
world, x, y, z
));
}
}
allData.close();
}
if(data.isEmpty()) return;
connection.setAutoCommit(false);
// first delete old data
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("DELETE FROM " + tablePrefix + "blockdata");
}
// then re-add valid unique data
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + tablePrefix + "blockdata (" +
"type, kit, holograms, displayItems, particles, itemOverride, world, x, y, z)" +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
for(TempKitData blockData : data.values()) {
statement.setString(1, blockData.type);
statement.setString(2, blockData.kit);
statement.setBoolean(3, blockData.holograms);
statement.setBoolean(4, blockData.displayItems);
statement.setBoolean(5, blockData.particles);
statement.setBoolean(6, blockData.itemOverride);
statement.setString(7, blockData.world);
statement.setInt(8, blockData.x);
statement.setInt(9, blockData.y);
statement.setInt(10, blockData.z);
statement.addBatch();
}
statement.executeBatch();
}
connection.commit();
connection.setAutoCommit(true);
// free up disk space (sqlite command)
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("VACUUM");
}
}
}
static class TempKitData {
final String type, kit, world;
final int x, y, z;
final boolean holograms, displayItems, particles, itemOverride;
public TempKitData(String type, String kit, boolean holograms, boolean displayItems, boolean particles, boolean itemOverride, String world, int x, int y, int z) {
this.type = type;
this.kit = kit;
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.holograms = holograms;
this.displayItems = displayItems;
this.particles = particles;
this.itemOverride = itemOverride;
}
}
}

View File

@ -1,12 +0,0 @@
package com.songoda.ultimatekits.economy;
import org.bukkit.OfflinePlayer;
public interface Economy {
boolean hasBalance(OfflinePlayer player, double cost);
boolean withdrawBalance(OfflinePlayer player, double cost);
boolean deposit(OfflinePlayer player, double amount);
}

View File

@ -1,38 +0,0 @@
package com.songoda.ultimatekits.economy;
import org.black_ixx.playerpoints.PlayerPoints;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
public class PlayerPointsEconomy implements Economy {
private final PlayerPoints playerPoints;
public PlayerPointsEconomy() {
this.playerPoints = (PlayerPoints) Bukkit.getServer().getPluginManager().getPlugin("PlayerPoints");
}
private int convertAmount(double amount) {
return (int) Math.ceil(amount);
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);
return playerPoints.getAPI().look(player.getUniqueId()) >= amount;
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);
return playerPoints.getAPI().take(player.getUniqueId(), amount);
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
int amt = convertAmount(amount);
return playerPoints.getAPI().give(player.getUniqueId(), amt);
}
}

View File

@ -1,32 +0,0 @@
package com.songoda.ultimatekits.economy;
import net.tnemc.core.Reserve;
import net.tnemc.core.economy.EconomyAPI;
import org.bukkit.OfflinePlayer;
import java.math.BigDecimal;
public class ReserveEconomy implements Economy {
EconomyAPI economyAPI;
public ReserveEconomy() {
if (Reserve.instance().economyProvided())
economyAPI = Reserve.instance().economy();
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
return economyAPI.hasHoldings(player.getUniqueId(), new BigDecimal(cost));
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
return economyAPI.removeHoldings(player.getUniqueId(), new BigDecimal(cost));
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
return economyAPI.addHoldings(player.getUniqueId(), new BigDecimal(amount));
}
}

View File

@ -1,28 +0,0 @@
package com.songoda.ultimatekits.economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
public class VaultEconomy implements Economy {
private final net.milkbowl.vault.economy.Economy vault;
public VaultEconomy() {
this.vault = Bukkit.getServicesManager().
getRegistration(net.milkbowl.vault.economy.Economy.class).getProvider();
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
return vault.has(player, cost);
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
return vault.withdrawPlayer(player, cost).transactionSuccess();
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
return vault.depositPlayer(player, amount).transactionSuccess();
}
}

View File

@ -0,0 +1,129 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.CompatibleSound;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitItem;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.ArmorType;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.lang.WordUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class AnimatedKitGui extends Gui {
static final Random rand = new Random();
private final UltimateKits plugin;
private final Player player;
private final ItemStack give;
private final ArrayDeque<KitItem> items = new ArrayDeque();
private boolean finish = false;
private boolean done = false;
private int tick = 0, updateTick = 0;
private int ticksPerUpdate = 3;
private final int updatesPerSlow = 6;
private final int ticksPerUpdateSlow = 10;
private int task;
public AnimatedKitGui(UltimateKits plugin, Player player, Kit kit, ItemStack give) {
this.plugin = plugin;
this.player = player;
this.give = give;
setRows(3);
setAllowClose(false);
setTitle(kit.getShowableName());
setDefaultItem(GuiUtils.getBorderItem(CompatibleMaterial.GRAY_STAINED_GLASS_PANE));
// ideally, we'd populate the items in such a way that the end item isn't far from the center when the animation is complete
// would be something to do if people have large kit loot tables.
List<KitItem> kitItems = kit.getContents();
if(kitItems.isEmpty()) {
throw new RuntimeException("Cannot give an empty kit!");
}
Collections.shuffle(kitItems);
this.items.addAll(kitItems);
while (this.items.size() < 10) {
items.addAll(kitItems);
}
setItem(4, GuiUtils.getBorderItem(CompatibleMaterial.TRIPWIRE_HOOK));
setItem(22, GuiUtils.getBorderItem(CompatibleMaterial.TRIPWIRE_HOOK));
tick();
setOnOpen(event -> {
task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> tick(), 1L, 1L);
});
}
void tick() {
if (++tick < ticksPerUpdate) {
return;
}
tick = 0;
if (++updateTick >= updatesPerSlow) {
updateTick = 0;
if (++ticksPerUpdate >= ticksPerUpdateSlow) {
finish = true;
}
}
// now update the display
// rainbow disco!
for (int col = 0; col < 9; ++col) {
if(col == 4) continue;
setItem(0, col, GuiUtils.getBorderItem(CompatibleMaterial.getGlassPaneColor(rand.nextInt(16))));
setItem(2, col, GuiUtils.getBorderItem(CompatibleMaterial.getGlassPaneColor(rand.nextInt(16))));
}
// item slider
if (!done) {
CompatibleSound.UI_BUTTON_CLICK.play(player, 5F, 5F);
items.addFirst(items.getLast());
items.removeLast();
Iterator<KitItem> itemIter = items.iterator();
for (int i = 9; i < 18; i++) {
setItem(0, i, itemIter.next().getItem());
}
}
// should we try to wrap it up?
if (finish) {
ItemStack item = getItem(13);
if(item == null) {
done = true; // idk.
} else if (item.isSimilar(give)) {
if (!done) {
done = true;
if (!Settings.AUTO_EQUIP_ARMOR_ROULETTE.getBoolean() || !ArmorType.equip(player, give)) {
Map<Integer, ItemStack> overfilled = player.getInventory().addItem(give);
for (ItemStack item2 : overfilled.values()) {
player.getWorld().dropItemNaturally(player.getLocation(), item2);
}
}
CompatibleSound.ENTITY_PLAYER_LEVELUP.play(player, 10f, 10f);
plugin.getLocale().getMessage("event.create.won")
.processPlaceholder("item", WordUtils.capitalize(give.getType().name().toLowerCase().replace("_", " ")))
.sendPrefixedMessage(player);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, this::finish, 50);
setAllowClose(true);
}
}
}
}
private void finish() {
Bukkit.getScheduler().cancelTask(task);
exit();
}
}

View File

@ -0,0 +1,85 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.kit.KitType;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.ChatColor;
import org.bukkit.event.inventory.ClickType;
import java.util.Arrays;
import java.util.List;
public class BlockEditorGui extends Gui {
private final KitBlockData kitBlockData;
public BlockEditorGui(UltimateKits plugin, KitBlockData kitBlockData) {
this.kitBlockData = kitBlockData;
setRows(3);
setTitle(plugin.getLocale().getMessage("interface.kitblock.title")
.processPlaceholder("kit", kitBlockData.getKit().getShowableName())
.getMessage());
// fill glass borders
Methods.fillGlass(this);
// exit button
setButton(0, 8, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
plugin.getLocale().getMessage("interface.button.exit").getMessage()),
ClickType.LEFT,
event -> event.player.closeInventory());
// kit type
setButton(1, 2, GuiUtils.createButtonItem(CompatibleMaterial.COMPARATOR,
plugin.getLocale().getMessage("interface.kitblock.switchtype").getMessage(),
kitTypeLore(plugin)),
ClickType.LEFT,
event -> {
plugin.removeHologram(kitBlockData);
if (kitBlockData.getType() == KitType.PREVIEW) {
kitBlockData.setType(KitType.CRATE);
} else if (kitBlockData.getType() == KitType.CRATE) {
kitBlockData.setType(KitType.CLAIM);
} else if (kitBlockData.getType() == KitType.CLAIM) {
kitBlockData.setType(KitType.PREVIEW);
}
plugin.updateHologram(kitBlockData);
updateItemLore(event.slot, kitTypeLore(plugin));
plugin.getKitFile().delaySave();
});
// decor options
setButton(1, 4, GuiUtils.createButtonItem(CompatibleMaterial.POPPY,
plugin.getLocale().getMessage("interface.kitblock.decor").getMessage(),
plugin.getLocale().getMessage("interface.kitblock.decorlore").getMessage().split("\\|")),
ClickType.LEFT,
event -> event.manager.showGUI(event.player, new KitDecorOptionsGui(plugin, kitBlockData, this)));
// edit
setButton(1, 6, GuiUtils.createButtonItem(CompatibleMaterial.DIAMOND_PICKAXE,
plugin.getLocale().getMessage("interface.kitblock.edit").getMessage(),
plugin.getLocale().getMessage("interface.kitblock.editlore").getMessage().split("\\|")),
ClickType.LEFT,
event -> {
guiManager.showGUI(event.player, new KitEditorGui(UltimateKits.getInstance(), event.player, kitBlockData.getKit(), this));
});
}
List<String> kitTypeLore(UltimateKits plugin) {
String[] type = plugin.getLocale().getMessage("interface.kitblock.switchtypelore").getMessage().split("\\|");
return Arrays.asList(
type[0],
(kitBlockData.getType() == KitType.PREVIEW ? ChatColor.GOLD : ChatColor.GRAY) + (type.length > 1 ? type[1] : "Preview"),
(kitBlockData.getType() == KitType.CRATE ? ChatColor.GOLD : ChatColor.GRAY) + (type.length > 2 ? type[2] : "Crate"),
(kitBlockData.getType() == KitType.CLAIM ? ChatColor.GOLD : ChatColor.GRAY) + (type.length > 3 ? type[3] : "Claim"));
}
}

View File

@ -0,0 +1,55 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class ConfirmBuyGui extends Gui {
public ConfirmBuyGui(UltimateKits plugin, Player player, Kit kit, Gui back) {
super(back);
setRows(3);
double cost = kit.getPrice();
if (Settings.KITS_FREE_WITH_PERMS.getBoolean() && kit.hasPermission(player)) {
cost = 0;
}
setTitle(plugin.getLocale().getMessage("interface.yesno.title")
.processPlaceholder("price", cost)
.getMessage());
// fill glass borders
Methods.fillGlass(this);
// Kit information
setItem(0, 4, GuiUtils.createButtonItem(kit.getDisplayItem() != null ? kit.getDisplayItem() : CompatibleMaterial.DIAMOND_HELMET,
ChatColor.RED + TextUtils.formatText(kit.getName().toLowerCase(), true),
ChatColor.GREEN + Settings.CURRENCY_SYMBOL.getString() + Methods.formatEconomy(cost)));
// confirm button
setButton(1, 2, GuiUtils.createButtonItem(Settings.BUY_ICON.getMaterial(CompatibleMaterial.EMERALD),
plugin.getLocale().getMessage("interface.yesno.yes").getMessage()),
event -> {
kit.processPurchaseUse(event.player);
exit();
});
// cancel button
setButton(1, 6, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
plugin.getLocale().getMessage("interface.yesno.no").getMessage()),
event -> {
plugin.getLocale().getMessage("event.purchase.cancelled").sendPrefixedMessage(event.player);
event.player.closeInventory();
});
}
}

View File

@ -1,109 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.kit.KitType;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.ArrayList;
public class GUIBlockEditor extends AbstractGUI {
private KitBlockData kitBlockData;
public GUIBlockEditor(UltimateKits plugin, Player player, Location location) {
super(player);
kitBlockData = plugin.getKitManager().getKit(location);
init("&8This contains &a" + kitBlockData.getKit().getShowableName(), 27);
}
@Override
protected void constructGUI() {
Methods.fillGlass(inventory);
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(8, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(10, Methods.getBackgroundGlass(false));
inventory.setItem(16, Methods.getBackgroundGlass(false));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(18, Methods.getBackgroundGlass(true));
inventory.setItem(19, Methods.getBackgroundGlass(true));
inventory.setItem(20, Methods.getBackgroundGlass(false));
inventory.setItem(24, Methods.getBackgroundGlass(false));
inventory.setItem(25, Methods.getBackgroundGlass(true));
inventory.setItem(26, Methods.getBackgroundGlass(true));
createButton(8, Material.valueOf(UltimateKits.getInstance().getConfig().getString("Interfaces.Exit Icon")),
UltimateKits.getInstance().getLocale().getMessage("interface.button.exit").getMessage());
ArrayList<String> lore = new ArrayList<>();
lore.add(Methods.formatText("&7Click to swap this kit blocks function."));
lore.add("");
if (kitBlockData.getType() == KitType.PREVIEW) {
lore.add(Methods.formatText("&6Preview"));
lore.add(Methods.formatText("&7Crate"));
lore.add(Methods.formatText("&7Claim"));
} else if (kitBlockData.getType() == KitType.CRATE) {
lore.add(Methods.formatText("&7Preview"));
lore.add(Methods.formatText("&6Crate"));
lore.add(Methods.formatText("&7Claim"));
} else if (kitBlockData.getType() == KitType.CLAIM) {
lore.add(Methods.formatText("&7Preview"));
lore.add(Methods.formatText("&7Crate"));
lore.add(Methods.formatText("&6Claim"));
}
createButton(11, UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? Material.COMPARATOR : Material.valueOf("REDSTONE_COMPARATOR"), "&5&lSwitch kit type", lore);
createButton(13, UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? Material.POPPY : Material.valueOf("RED_ROSE"), "&9&lDecor Options",
"&7Click to edit the decoration",
"&7options for this kit.");
createButton(15, Material.DIAMOND_PICKAXE, "&a&lEdit kit",
"&7Click to edit the kit",
"&7contained in this block.");
}
@Override
protected void registerClickables() {
registerClickable(8, (player, inventory, cursor, slot, type) -> player.closeInventory());
registerClickable(11, (player, inventory, cursor, slot, type) -> {
UltimateKits instance = UltimateKits.getInstance();
if (instance.getHologram() != null)
instance.getHologram().remove(kitBlockData);
if (kitBlockData.getType() == KitType.PREVIEW) kitBlockData.setType(KitType.CRATE);
else if (kitBlockData.getType() == KitType.CRATE) kitBlockData.setType(KitType.CLAIM);
else if (kitBlockData.getType() == KitType.CLAIM) kitBlockData.setType(KitType.PREVIEW);
instance.saveConfig();
if (instance.getHologram() != null)
instance.getHologram().update(kitBlockData);
constructGUI();
});
registerClickable(13, (player, inventory, cursor, slot, type) ->
new GUIDecorOptions(UltimateKits.getInstance(), player, kitBlockData.getLocation()));
registerClickable(15, (player, inventory, cursor, slot, type) ->
new GUIKitEditor(UltimateKits.getInstance(), player, kitBlockData.getKit(), this, null, 0));
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -1,101 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
public class GUIConfirmBuy extends AbstractGUI {
private Kit kit;
private Player player;
private UltimateKits plugin;
public GUIConfirmBuy(UltimateKits plugin, Player player, Kit kit) {
super(player);
this.kit = kit;
this.player = player;
this.plugin = plugin;
init(plugin.getLocale().getMessage("interface.yesno.title")
.processPlaceholder("price", kit.getPrice()).getMessage(), 27);
}
@Override
protected void constructGUI() {
double cost = kit.getPrice();
if (kit.hasPermission(player) && plugin.getConfig().getBoolean("Main.Allow Players To Receive Kits For Free If They Have Permission")) {
cost = 0;
}
String title = Methods.formatTitle("&c" + StringUtils.capitalize(kit.getName().toLowerCase()));
ItemStack item = new ItemStack(Material.DIAMOND_HELMET);
if (kit.getDisplayItem() != null) item = new ItemStack(kit.getDisplayItem());
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(title);
ArrayList<String> lore = new ArrayList<>();
lore.add(Methods.formatText("&a$" + Methods.formatEconomy(cost)));
int nu = 0;
while (nu != 27) {
inventory.setItem(nu, Methods.getGlass());
nu++;
}
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(8, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(10, Methods.getBackgroundGlass(false));
inventory.setItem(16, Methods.getBackgroundGlass(false));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(18, Methods.getBackgroundGlass(true));
inventory.setItem(19, Methods.getBackgroundGlass(true));
inventory.setItem(20, Methods.getBackgroundGlass(false));
inventory.setItem(24, Methods.getBackgroundGlass(false));
inventory.setItem(25, Methods.getBackgroundGlass(true));
inventory.setItem(26, Methods.getBackgroundGlass(true));
ItemStack item2 = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Buy Icon")), 1);
ItemMeta itemmeta2 = item2.getItemMeta();
itemmeta2.setDisplayName(plugin.getLocale().getMessage("interface.yesno.yes").getMessage());
item2.setItemMeta(itemmeta2);
ItemStack item3 = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Exit Icon")), 1);
ItemMeta itemmeta3 = item3.getItemMeta();
itemmeta3.setDisplayName(plugin.getLocale().getMessage("interface.yesno.no").getMessage());
item3.setItemMeta(itemmeta3);
inventory.setItem(4, item);
inventory.setItem(11, item2);
inventory.setItem(15, item3);
}
@Override
protected void registerClickables() {
registerClickable(11, ((player1, inventory1, cursor, slot, type) -> {
kit.processPurchaseUse(player);
player.closeInventory();
}));
registerClickable(15, ((player1, inventory1, cursor, slot, type) -> {
plugin.getLocale().getMessage("event.purchase.cancelled").sendPrefixedMessage(player);
player.closeInventory();
}));
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -1,169 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import com.songoda.ultimatekits.utils.gui.OnClose;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
public class GUIDecorOptions extends AbstractGUI {
private UltimateKits plugin;
private KitBlockData kitBlockData;
public GUIDecorOptions(UltimateKits plugin, Player player, Location location) {
super(player);
this.plugin = plugin;
kitBlockData = plugin.getKitManager().getKit(location);
init("&8Editing decor for &a" + kitBlockData.getKit().getShowableName() + "&8.", 27);
}
@Override
protected void constructGUI() {
Kit kit = kitBlockData.getKit();
Methods.fillGlass(inventory);
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(8, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(10, Methods.getBackgroundGlass(false));
inventory.setItem(16, Methods.getBackgroundGlass(false));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(18, Methods.getBackgroundGlass(true));
inventory.setItem(19, Methods.getBackgroundGlass(true));
inventory.setItem(20, Methods.getBackgroundGlass(false));
inventory.setItem(24, Methods.getBackgroundGlass(false));
inventory.setItem(25, Methods.getBackgroundGlass(true));
inventory.setItem(26, Methods.getBackgroundGlass(true));
createButton(8, Material.valueOf(UltimateKits.getInstance().getConfig().getString("Interfaces.Exit Icon")),
UltimateKits.getInstance().getLocale().getMessage("interface.button.exit").getMessage());
ItemStack head = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.PLAYER_HEAD : Material.valueOf("SKULL_ITEM"), 1, (byte) 3);
ItemStack back = Methods.addTexture(head, "http://textures.minecraft.net/texture/3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23");
inventory.setItem(0, back);
createButton(0, back, UltimateKits.getInstance().getLocale().getMessage("interface.button.back").getMessage());
ArrayList<String> lore = new ArrayList<>();
if (kitBlockData.showHologram()) {
lore.add(Methods.formatText("&7Currently: &aEnabled&7."));
} else {
lore.add(Methods.formatText("&7Currently &cDisabled&7."));
}
createButton(10, Material.NAME_TAG, "&9&lToggle Holograms", lore);
lore = new ArrayList<>();
if (kitBlockData.hasParticles()) {
lore.add(Methods.formatText("&7Currently: &aEnabled&7."));
} else {
lore.add(Methods.formatText("&7Currently &cDisabled&7."));
}
createButton(12, Material.POTION, "&9&lToggle Particles", lore);
lore = new ArrayList<>();
if (kitBlockData.isDisplayingItems()) {
lore.add(Methods.formatText("&7Currently: &aEnabled&7."));
} else {
lore.add(Methods.formatText("&7Currently &cDisabled&7."));
}
createButton(14, Material.DIAMOND, "&9&lToggle DisplayItems", lore);
Material material = Material.BEACON;
if (kit.getDisplayItem() != null) {
material = kit.getDisplayItem();
}
lore = new ArrayList<>();
if (kitBlockData.isItemOverride()) {
lore.add(Methods.formatText("&7Currently: &aEnabled&7."));
} else {
lore.add(Methods.formatText("&7Currently &cDisabled&7."));
}
lore.add("");
lore.add(Methods.formatText("&7Enabling this option will "));
lore.add(Methods.formatText("&7override the DisplayItems"));
lore.add(Methods.formatText("&7above your kit to the single"));
lore.add(Methods.formatText("&7DisplayItem set in this kit"));
lore.add(Methods.formatText("&7GUI options."));
createButton(16, material, "&9&lToggle DisplayItem Override", lore);
}
@Override
protected void registerClickables() {
registerClickable(0, (player, inventory, cursor, slot, type) -> new GUIBlockEditor(UltimateKits.getInstance(), player, kitBlockData.getLocation()));
registerClickable(8, (player, inventory, cursor, slot, type) -> player.closeInventory());
registerClickable(10, (player, inventory, cursor, slot, type) -> {
if (plugin.getHologram() == null) return;
if (kitBlockData.showHologram()) {
kitBlockData.setShowHologram(false);
} else {
kitBlockData.setShowHologram(true);
}
UltimateKits.getInstance().getHologram().update(kitBlockData);
constructGUI();
});
registerClickable(12, (player, inventory, cursor, slot, type) -> {
if (kitBlockData.hasParticles()) {
kitBlockData.setHasParticles(false);
} else {
kitBlockData.setHasParticles(true);
}
constructGUI();
});
registerClickable(14, (player, inventory, cursor, slot, type) -> {
boolean isHolo = plugin.getHologram() != null && kitBlockData.showHologram();
if (isHolo) {
UltimateKits.getInstance().getHologram().remove(kitBlockData);
}
if (kitBlockData.isDisplayingItems()) {
kitBlockData.setDisplayingItems(false);
} else {
kitBlockData.setDisplayingItems(true);
}
if (isHolo) {
UltimateKits.getInstance().getHologram().add(kitBlockData);
}
constructGUI();
});
registerClickable(16, (player, inventory, cursor, slot, type) -> {
if (kitBlockData.isItemOverride()) {
kitBlockData.setItemOverride(false);
} else {
kitBlockData.setItemOverride(true);
}
constructGUI();
});
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -1,239 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
public class GUIDisplayKit extends AbstractGUI {
private Kit kit;
private Player player;
private UltimateKits plugin;
private AbstractGUI back;
private int max;
private boolean buyable;
private List<ItemStack> list;
public GUIDisplayKit(UltimateKits plugin, AbstractGUI back, Player player, Kit kit) {
super(player);
this.kit = kit;
this.player = player;
this.plugin = plugin;
this.back = back;
String guititle = Methods.formatTitle(plugin.getLocale().getMessage("interface.preview.title")
.processPlaceholder("kit", kit.getShowableName()).getMessage());
if (kit.getTitle() != null) {
guititle = plugin.getLocale().getMessage("interface.preview.title")
.processPlaceholder("kit", Methods.formatText(kit.getTitle(), true)).getMessage();
}
list = kit.getReadableContents(player, true, true, false);
int amt = 0;
for (ItemStack is : list) {
if (is.getAmount() > 64) {
int overflow = is.getAmount() % 64;
int stackamt = is.getAmount() / 64;
int num3 = 0;
while (num3 != stackamt) {
amt++;
num3++;
}
if (overflow != 0) {
amt++;
}
} else {
amt++;
}
}
buyable = false;
if (kit.getLink() != null || kit.getPrice() != 0) {
buyable = true;
}
int min = 0;
if (plugin.getConfig().getBoolean("Interfaces.Do Not Use Glass Borders")) {
min = 9;
if (!buyable) {
min = min + 9;
}
}
max = 54 - min;
if (amt <= 7) {
max = 27 - min;
} else if (amt <= 15) {
max = 36 - min;
} else if (amt <= 23) {
max = 45 - min;
}
init(guititle, max);
}
@Override
protected void constructGUI() {
int num = 0;
if (!plugin.getConfig().getBoolean("Interfaces.Do Not Use Glass Borders")) {
ItemStack exit = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Exit Icon")), 1);
ItemMeta exitmeta = exit.getItemMeta();
exitmeta.setDisplayName(plugin.getLocale().getMessage("interface.button.exit").getMessage());
exit.setItemMeta(exitmeta);
while (num != 10) {
inventory.setItem(num, Methods.getGlass());
num++;
}
int num2 = max - 10;
while (num2 != max) {
inventory.setItem(num2, Methods.getGlass());
num2++;
}
inventory.setItem(8, exit);
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(max - 18, Methods.getBackgroundGlass(true));
inventory.setItem(max - 9, Methods.getBackgroundGlass(true));
inventory.setItem(max - 8, Methods.getBackgroundGlass(true));
inventory.setItem(max - 10, Methods.getBackgroundGlass(true));
inventory.setItem(max - 2, Methods.getBackgroundGlass(true));
inventory.setItem(max - 1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(max - 7, Methods.getBackgroundGlass(false));
inventory.setItem(max - 3, Methods.getBackgroundGlass(false));
}
if (buyable) {
ItemStack link = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Buy Icon")), 1);
ItemMeta linkmeta = link.getItemMeta();
linkmeta.setDisplayName(plugin.getLocale().getMessage("interface.button.buynow").getMessage());
ArrayList<String> lore = new ArrayList<>();
if (kit.hasPermission(player) && plugin.getConfig().getBoolean("Main.Allow Players To Receive Kits For Free If They Have Permission")) {
lore.add(plugin.getLocale().getMessage("interface.button.clickeco")
.processPlaceholder("price", "0").getMessage());
if (player.isOp()) {
lore.add("");
lore.add(Methods.formatText("&7This is free because"));
lore.add(Methods.formatText("&7you have perms for it."));
lore.add(Methods.formatText("&7Everyone else buys"));
lore.add(Methods.formatText("&7this for &a$" + Methods.formatEconomy(kit.getPrice()) + "&7."));
}
} else {
lore.add(plugin.getLocale().getMessage("interface.button.clickeco")
.processPlaceholder("price", Methods.formatEconomy(kit.getPrice())).getMessage());
}
if (kit.getDelay() != 0 && player.isOp()) {
lore.add("");
lore.add(Methods.formatText("&7You do not have a delay"));
lore.add(Methods.formatText("&7because you have perms"));
lore.add(Methods.formatText("&7to bypass the delay."));
}
linkmeta.setLore(lore);
link.setItemMeta(linkmeta);
inventory.setItem(max - 5, link);
registerClickable(max - 5, ((player1, inventory1, cursor, slot, type) -> {
player.closeInventory();
String kitName = kit.getName();
Kit kit = plugin.getKitManager().getKit(kitName);
kit.buy(player);
}));
}
for (ItemStack is : list) {
if (!plugin.getConfig().getBoolean("Interfaces.Do Not Use Glass Borders")) {
if (num == 17 || num == (max - 18)) num++;
if (num == 18 && max == 36) num++;
}
ItemMeta meta = is.hasItemMeta() ? is.getItemMeta() : Bukkit.getItemFactory().getItemMeta(is.getType());
ArrayDeque<String> lore;
if (meta.hasLore()) {
lore = new ArrayDeque<>(meta.getLore());
} else {
lore = new ArrayDeque<>();
}
List<String> newLore = new ArrayList<>();
for (String str : lore) {
str = str.replace("{PLAYER}", player.getName()).replace("<PLAYER>", player.getName());
newLore.add(str);
}
meta.setLore(newLore);
is.setItemMeta(meta);
if (is.getAmount() > 64) {
int overflow = is.getAmount() % 64;
int stackamt = is.getAmount() / 64;
int num3 = 0;
while (num3 != stackamt) {
is.setAmount(64);
inventory.setItem(num, is);
num++;
num3++;
}
if (overflow != 0) {
is.setAmount(overflow);
inventory.setItem(num, is);
num++;
}
continue;
}
if (!plugin.getConfig().getBoolean("Main.Dont Preview Commands In Kits") || is.getType() != Material.PAPER || !is.getItemMeta().hasDisplayName() || !is.getItemMeta().getDisplayName().equals(plugin.getLocale().getMessage("general.type.command"))) {
inventory.setItem(num, is);
num++;
}
}
if (back != null && !plugin.getConfig().getBoolean("Interfaces.Do Not Use Glass Borders")) {
ItemStack head = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.PLAYER_HEAD : Material.valueOf("SKULL_ITEM"), 1, (byte) 3);
ItemStack skull2 = Methods.addTexture(head, "http://textures.minecraft.net/texture/3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23");
SkullMeta skull2Meta = (SkullMeta) skull2.getItemMeta();
skull2.setDurability((short) 3);
skull2Meta.setDisplayName(plugin.getLocale().getMessage("interface.button.back").getMessage());
skull2.setItemMeta(skull2Meta);
inventory.setItem(0, skull2);
}
}
@Override
protected void registerClickables() {
registerClickable(0, (player, inventory, cursor, slot, type) -> {
if (back == null) return;
back.init(back.getSetTitle(), back.getInventory().getSize());
});
registerClickable(8, (player, inventory, cursor, slot, type) -> player.closeInventory());
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -1,177 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractAnvilGUI;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.ArrayList;
public class GUIGUIOptions extends AbstractGUI {
private Kit kit;
private Player player;
private UltimateKits plugin;
private AbstractGUI back;
public GUIGUIOptions(UltimateKits plugin, Player player, AbstractGUI back, Kit kit) {
super(player);
this.kit = kit;
this.player = player;
this.plugin = plugin;
this.back = back;
init("&8GUI Options for &a" + kit.getShowableName() + "&8.", 27);
}
@Override
protected void constructGUI() {
Methods.fillGlass(inventory);
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(8, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(10, Methods.getBackgroundGlass(false));
inventory.setItem(16, Methods.getBackgroundGlass(false));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(18, Methods.getBackgroundGlass(true));
inventory.setItem(19, Methods.getBackgroundGlass(true));
inventory.setItem(20, Methods.getBackgroundGlass(false));
inventory.setItem(24, Methods.getBackgroundGlass(false));
inventory.setItem(25, Methods.getBackgroundGlass(true));
inventory.setItem(26, Methods.getBackgroundGlass(true));
createButton(8, Material.valueOf(UltimateKits.getInstance().getConfig().getString("Interfaces.Exit Icon")),
UltimateKits.getInstance().getLocale().getMessage("interface.button.exit").getMessage());
ItemStack head = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.PLAYER_HEAD : Material.valueOf("SKULL_ITEM"), 1, (byte) 3);
ItemStack back = Methods.addTexture(head, "http://textures.minecraft.net/texture/3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23");
SkullMeta skull2Meta = (SkullMeta) back.getItemMeta();
back.setDurability((short) 3);
skull2Meta.setDisplayName(UltimateKits.getInstance().getLocale().getMessage("interface.button.back").getMessage());
back.setItemMeta(skull2Meta);
inventory.setItem(0, back);
ArrayList<String> lore = new ArrayList<>();
if (kit.getTitle() != null)
lore.add(Methods.formatText("&7Currently: &a" + kit.getTitle() + "&7."));
else
lore.add(Methods.formatText("&7Currently: &cNot set&7."));
lore.add(Methods.formatText(""));
lore.add(Methods.formatText("&7Left-Click: &9to set"));
lore.add(Methods.formatText("&9the kit title for holograms"));
lore.add(Methods.formatText("&9and the kit / kit selector GUIs."));
lore.add(Methods.formatText(""));
lore.add(Methods.formatText("&7Right-Click: &9to reset."));
createButton(11, Material.NAME_TAG, "&9&lSet Title", lore);
lore = new ArrayList<>();
if (kit.getDisplayItem() != null) {
lore.add(Methods.formatText("&7Currently set to: &a" + kit.getDisplayItem().toString() + "&7."));
} else {
lore.add(Methods.formatText("&7Currently &cDisabled&7."));
}
lore.add("");
lore.add(Methods.formatText("&7Left-Click to: &9Set a"));
lore.add(Methods.formatText("&9display item for this kit"));
lore.add(Methods.formatText("&9to the item in your hand."));
lore.add("");
lore.add(Methods.formatText("&7Right-Click to: &9Remove the item."));
createButton(13, Material.BEACON, "&9&lSet DisplayItem", lore);
lore = new ArrayList<>();
if (kit.isHidden()) {
lore.add(Methods.formatText("&7Currently: &cHidden&7."));
} else {
lore.add(Methods.formatText("&7Currently: &aVisible&7."));
}
lore.add("");
lore.add(Methods.formatText("&7A hidden kit will not"));
lore.add(Methods.formatText("&7show up in the /kit gui."));
lore.add(Methods.formatText("&7This is usually optimal for"));
lore.add(Methods.formatText("&7preventing players from seeing"));
lore.add(Methods.formatText("&7non obtainable kit or starter kit."));
createButton(15, Material.COAL, "&9&lHide kit", lore);
}
@Override
protected void registerClickables() {
registerClickable(0, (player, inventory, cursor, slot, type) -> back.init(back.getSetTitle(), back.getInventory().getSize()));
registerClickable(8, (player, inventory, cursor, slot, type) -> player.closeInventory());
registerClickable(11, ((player1, inventory1, cursor, slot, type) -> {
if (type.isLeftClick()) {
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
kit.setTitle(msg);
plugin.saveConfig();
plugin.getLocale().newMessage("&8Title &5" + msg + "&8 added to Kit &a" + kit.getShowableName() + "&8.")
.sendPrefixedMessage(player);
if (plugin.getHologram() != null)
plugin.getHologram().update(kit);
});
gui.setOnClose((player2, inventory3) -> init(setTitle, inventory.getSize()));
ItemStack item = new ItemStack(Material.NAME_TAG);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("Enter Title");
item.setItemMeta(meta);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item);
gui.open();
} else {
kit.setTitle("");
if (plugin.getHologram() != null)
plugin.getHologram().update(kit);
constructGUI();
}
}));
registerClickable(13, ((player1, inventory1, cursor, slot, type) -> {
if (type.isLeftClick()) {
ItemStack is = player.getItemInHand();
if (is.getType() == Material.AIR) {
plugin.getLocale().newMessage("&8You must be holding an item to use this function.").sendPrefixedMessage(player);
return;
}
kit.setDisplayItem(is.getType());
plugin.getLocale().newMessage("&8Custom Item Display set for kit &a" + kit.getShowableName() + "&8.").sendPrefixedMessage(player);
} else {
kit.setDisplayItem(null);
plugin.getLocale().newMessage("&8Custom Item Display removed from kit &a" + kit.getShowableName() + "&8.").sendPrefixedMessage(player);
}
constructGUI();
}));
registerClickable(15, ((player1, inventory1, cursor, slot, type) -> {
if (kit.isHidden()) {
kit.setHidden(false);
} else {
kit.setHidden(true);
}
constructGUI();
}));
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -1,142 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractAnvilGUI;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
public class GUIGeneralOptions extends AbstractGUI {
private Kit kit;
private Player player;
private UltimateKits plugin;
private AbstractGUI back;
public GUIGeneralOptions(UltimateKits plugin, Player player, AbstractGUI back, Kit kit) {
super(player);
this.kit = kit;
this.player = player;
this.plugin = plugin;
this.back = back;
init("&8General Options for &a" + kit.getShowableName() + "&8.", 27);
}
@Override
protected void constructGUI() {
Methods.fillGlass(inventory);
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(8, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(10, Methods.getBackgroundGlass(false));
inventory.setItem(16, Methods.getBackgroundGlass(false));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(18, Methods.getBackgroundGlass(true));
inventory.setItem(19, Methods.getBackgroundGlass(true));
inventory.setItem(20, Methods.getBackgroundGlass(false));
inventory.setItem(24, Methods.getBackgroundGlass(false));
inventory.setItem(25, Methods.getBackgroundGlass(true));
inventory.setItem(26, Methods.getBackgroundGlass(true));
createButton(8, Material.valueOf(UltimateKits.getInstance().getConfig().getString("Interfaces.Exit Icon")),
UltimateKits.getInstance().getLocale().getMessage("interface.button.exit").getMessage());
ItemStack head = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.PLAYER_HEAD : Material.valueOf("SKULL_ITEM"), 1, (byte) 3);
ItemStack back = Methods.addTexture(head, "http://textures.minecraft.net/texture/3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23");
SkullMeta skull2Meta = (SkullMeta) back.getItemMeta();
back.setDurability((short) 3);
skull2Meta.setDisplayName(UltimateKits.getInstance().getLocale().getMessage("interface.button.back")
.getMessage());
back.setItemMeta(skull2Meta);
inventory.setItem(0, back);
createButton(11, plugin.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"), "&9&lChange Delay",
"&7Currently set to: &a" + kit.getDelay() + "&7.",
"",
"&7Use this to alter this kit delay.",
"",
"&7Use &6-1 &7to make this kit single",
"&7use only.");
createButton(15, Material.TNT, "&c&lDestroy Kit",
"",
"&7Click this to destroy this kit.");
}
@Override
protected void registerClickables() {
registerClickable(0, (player, inventory, cursor, slot, type) -> back.init(back.getSetTitle(), back.getInventory().getSize()));
registerClickable(8, (player, inventory, cursor, slot, type) -> player.closeInventory());
registerClickable(15, ((player1, inventory1, cursor, slot, type) -> {
String name = kit.getName();
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
if (msg.trim().equalsIgnoreCase(kit.getName())) {
plugin.getKitManager().removeKit(kit);
if (plugin.getHologram() != null)
plugin.getHologram().update(kit);
plugin.getLocale().newMessage("&cKit destroyed successfully.").sendPrefixedMessage(player);
} else {
plugin.getLocale().newMessage("&cKit was not Destroyed.").sendPrefixedMessage(player);
}
});
gui.setOnClose((player2, inventory3) -> {
if (plugin.getKitManager().getKit(name) != null) {
init(setTitle, inventory.getSize());
}
});
ItemStack item = new ItemStack(Material.BARRIER);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("Enter \"" + kit.getName() + "\"");
item.setItemMeta(meta);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item);
gui.open();
}));
registerClickable(11, ((player1, inventory1, cursor, slot, type) -> {
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
if (!Methods.isNumeric(msg)) {
player.sendMessage(Methods.formatText("&a" + msg + " &8is not a number. Please do not include a &a$&8."));
} else {
kit.setDelay(Integer.parseInt(msg));
}
});
gui.setOnClose((player2, inventory3) -> init(setTitle, inventory.getSize()));
ItemStack item = new ItemStack(Material.PAPER);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("Delay In Seconds");
item.setItemMeta(meta);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item);
gui.open();
}));
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -1,537 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitAnimation;
import com.songoda.ultimatekits.kit.KitItem;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractAnvilGUI;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import com.songoda.ultimatekits.utils.gui.Range;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GUIKitEditor extends AbstractGUI {
private UltimateKits plugin;
private Kit kit;
private AbstractGUI back;
private ItemStack[] inventoryItems;
private boolean isInFuction = false;
private boolean isInInventory = false;
private ItemStack toReplace;
private int slot;
private String title;
public GUIKitEditor(UltimateKits plugin, Player player, Kit kit, AbstractGUI back, ItemStack toReplace, int slot) {
super(player);
this.plugin = plugin;
this.kit = kit;
this.back = back;
String name = kit.getShowableName();
title = "&8You are editing kit: &9" + name + "&8.";
this.toReplace = toReplace;
this.slot = slot;
init(title, 54);
saveItemsInstance();
getInvItems();
}
@Override
protected void constructGUI() {
inventory.clear();
player.updateInventory();
createButton(8, Material.valueOf(UltimateKits.getInstance().getConfig().getString("Interfaces.Exit Icon")),
UltimateKits.getInstance().getLocale().getMessage("interface.button.exit").getMessage());
ItemStack head = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.PLAYER_HEAD : Material.valueOf("SKULL_ITEM"), 1, (byte) 3);
ItemStack back;
back = Methods.addTexture(head, "http://textures.minecraft.net/texture/3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23");
SkullMeta skull2Meta = (SkullMeta) back.getItemMeta();
back.setDurability((short) 3);
skull2Meta.setDisplayName(UltimateKits.getInstance().getLocale().getMessage("interface.button.back").getMessage());
back.setItemMeta(skull2Meta);
ItemStack it = new ItemStack(Material.CHEST, 1);
ItemMeta itmeta = it.getItemMeta();
itmeta.setDisplayName(Methods.formatText("&5&l" + kit.getName()));
ArrayList<String> lore = new ArrayList<>();
lore.add(Methods.formatText("&fPermissions:"));
lore.add(Methods.formatText("&7ultimatekits.kit." + kit.getName().toLowerCase()));
itmeta.setLore(lore);
it.setItemMeta(itmeta);
ItemStack glass = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.GRAY_STAINED_GLASS_PANE : Material.valueOf("STAINED_GLASS_PANE"), 1);
ItemMeta glassmeta = glass.getItemMeta();
glassmeta.setDisplayName(Methods.formatText("&" + kit.getName().replaceAll(".(?!$)", "$0&")));
glass.setItemMeta(glassmeta);
if (this.back != null)
inventory.setItem(0, back);
inventory.setItem(4, it);
int num = 10;
List<ItemStack> list = kit.getReadableContents(player, false, true, true);
for (ItemStack iss : list) {
if (num == 17 || num == 36)
num++;
if (num == slot && toReplace != null) {
iss = toReplace;
}
KitItem item = new KitItem(iss);
ItemStack is = item.getMoveableItem();
ItemMeta meta;
if (is.hasItemMeta()) meta = is.getItemMeta();
else meta = Bukkit.getItemFactory().getItemMeta(is.getType());
List<String> itemLore;
if (meta.hasLore()) itemLore = meta.getLore();
else itemLore = new ArrayList<>();
itemLore.add(Methods.convertToInvisibleString("----"));
itemLore.add(Methods.formatText("&7" + plugin.getLocale().getMessage("general.type.chance") + ": &6" + item.getChance() + "%"));
if (isInFuction) {
itemLore.add(Methods.formatText("&7Display Item: &6" + (item.getDisplayItem() == null ? "" : item.getDisplayItem().name())));
itemLore.add(Methods.formatText("&7Display Name: &6" + Methods.formatText(item.getDisplayName())));
itemLore.add(Methods.formatText("&7Display Lore: &6" + Methods.formatText(item.getDisplayLore())));
}
itemLore.add("");
if (isInFuction) {
itemLore.add(Methods.formatText("&7Left-Click: &6To set a display item."));
itemLore.add(Methods.formatText("&7Middle-Click: &6To set a display name."));
itemLore.add(Methods.formatText("&7Right-Click: &6To set display lore."));
itemLore.add(Methods.formatText("&7Shift-Click: &6To set chance."));
itemLore.add("");
itemLore.add(Methods.formatText("&7Display options only show up on display."));
itemLore.add(Methods.formatText("&7This can be useful if you want to explain"));
itemLore.add(Methods.formatText("&7What an item does without putting it in the"));
itemLore.add(Methods.formatText("&7permanent lore."));
itemLore.add("");
itemLore.add(Methods.formatText("&6Leave function mode to move items."));
}
meta.setLore(itemLore);
is.setItemMeta(meta);
if (is.getAmount() > 64) {
int overflow = is.getAmount() % 64;
int stackamt = (int) ((long) (is.getAmount() / 64));
int num3 = 0;
while (num3 != stackamt) {
is.setAmount(64);
inventory.setItem(num, is);
num++;
num3++;
}
if (overflow != 0) {
is.setAmount(overflow);
inventory.setItem(num, is);
num++;
}
} else {
inventory.setItem(num, is);
num++;
}
}
if (toReplace != null && slot == 0) {
if (num == 17 || num == 36)
num++;
inventory.setItem(num, toReplace);
toReplace = null;
}
inventory.setItem(3, Methods.getGlass());
inventory.setItem(5, Methods.getGlass());
inventory.setItem(48, Methods.getGlass());
inventory.setItem(50, Methods.getGlass());
if (this.back == null)
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(54 - 18, Methods.getBackgroundGlass(true));
inventory.setItem(54 - 9, Methods.getBackgroundGlass(true));
inventory.setItem(54 - 8, Methods.getBackgroundGlass(true));
inventory.setItem(54 - 10, Methods.getBackgroundGlass(true));
inventory.setItem(54 - 2, Methods.getBackgroundGlass(true));
inventory.setItem(54 - 1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(54 - 7, Methods.getBackgroundGlass(false));
inventory.setItem(54 - 3, Methods.getBackgroundGlass(false));
updateInvButton();
}
private void updateInvButton() {
if (!isInFuction) {
createButton(48, Material.PAPER, "&6Switch To Item Editing",
"&7Click to enable",
"&7item editing.");
addDraggable(new Range(10, 43, null, true), true);
addDraggable(new Range(17, 17, null, true), false);
addDraggable(new Range(36, 36, null, true), false);
registerClickables();
} else {
createButton(48, Material.PAPER, "&6Switch To Item Moving",
"&7Click to switch back",
"&7to item moving.");
removeDraggable();
registerClickables();
}
if (!isInInventory) {
createButton(50, Material.ITEM_FRAME, "&6Switch To Your Inventory",
"&7Click to switch to",
"&7your inventory.");
cancelBottom = true;
registerClickables();
} else {
createButton(50, Material.ITEM_FRAME, "&6Switch To Kit Functions",
"&7Click to switch back",
"&7to the kit functions.");
cancelBottom = false;
registerClickables();
}
}
private void saveItemsInstance() {
inventoryItems = player.getInventory().getContents().clone();
player.getInventory().clear();
}
private void getInvItems() {
isInInventory = false;
createButton(9, player.getInventory(), plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.REDSTONE_TORCH : Material.valueOf("REDSTONE_TORCH_ON"), "&6General Options",
"&7Click to edit adjust",
"&7general options.");
createButton(10, player.getInventory(), Material.EMERALD, "&9Selling Options",
"&7Click to edit adjust",
"&7selling options.");
createButton(12, player.getInventory(), Material.ITEM_FRAME, "&5GUI Options",
"&7Click to edit GUI options",
"&7for this kit.");
createButton(13, player.getInventory(), Material.PAPER, "&fAdd Command",
"&7Click to add a command",
"&7to this kit.");
createButton(14, player.getInventory(), plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.SUNFLOWER : Material.valueOf("DOUBLE_PLANT"), "&6Add Economy",
"&7Click to add money",
"&7to this kit.");
createButton(17, player.getInventory(), Material.CHEST, "&6Kit Animation",
"&7Currently: &6" + kit.getKitAnimation().name());
}
public void saveKit(Player player, Inventory i, boolean muteSave) {
ItemStack[] items = i.getContents();
int num = 0;
for (ItemStack item : items) {
if (num < 10 || num == 17 || num == 36) {
items[num] = null;
}
num++;
}
items = Arrays.copyOf(items, items.length - 10);
kit.saveKit(Arrays.asList(items));
plugin.getLocale().newMessage("&8Changes to &a" + kit.getShowableName() + " &8saved successfully.")
.sendPrefixedMessage(player);
}
public void replaceItem(Action action, Player player, ItemStack itemStack, int slot) {
if (itemStack.getItemMeta().hasLore()) {
ItemMeta meta = itemStack.getItemMeta();
List<String> newLore = new ArrayList<>();
for (String line : meta.getLore()) {
if (line.equals(Methods.convertToInvisibleString("----"))) break;
newLore.add(line);
}
meta.setLore(newLore);
itemStack.setItemMeta(meta);
}
KitItem item = new KitItem(itemStack);
switch (action) {
case CHANCE:
item.setChance(item.getChance() == 100 ? 5 : (item.getChance() + 5));
toReplace = item.getMoveableItem();
this.slot = slot;
saveKit(player, inventory, true);
constructGUI();
break;
case DISPLAY_ITEM: {
saveKit(player, this.inventory, true);
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
ItemStack toReplace = null;
try {
Material material = Material.valueOf(msg.trim().toUpperCase());
KitItem item2 = new KitItem(itemStack);
item2.setDisplayItem(material);
toReplace = item2.getMoveableItem();
} catch (Exception e) {
player.sendMessage(Methods.formatText("&a" + msg + " &8is not a valid material."));
}
this.slot = slot;
this.toReplace = toReplace;
});
gui.setOnClose((player1, inventory1) -> init(title, 54));
ItemStack item2 = new ItemStack(Material.NAME_TAG);
ItemMeta meta2 = item2.getItemMeta();
meta2.setDisplayName("Enter a Material");
item2.setItemMeta(meta2);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item2);
gui.open();
}
break;
case DISPLAY_NAME: {
saveKit(player, this.inventory, true);
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
KitItem item2 = new KitItem(itemStack);
item2.setDisplayName(msg);
this.toReplace = item2.getMoveableItem();
this.slot = slot;
});
gui.setOnClose((player1, inventory1) -> {
kit.getContents().forEach((item1) -> {
});
init(title, 54);
});
ItemStack item2 = new ItemStack(Material.NAME_TAG);
ItemMeta meta2 = item2.getItemMeta();
meta2.setDisplayName("Enter a name");
item2.setItemMeta(meta2);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item2);
gui.open();
}
break;
case DISPLAY_LORE: {
saveKit(player, this.inventory, true);
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
KitItem item2 = new KitItem(itemStack);
item2.setDisplayLore(msg);
this.toReplace = item2.getMoveableItem();
this.slot = slot;
});
gui.setOnClose((player1, inventory1) -> init(title, 54));
ItemStack item2 = new ItemStack(Material.NAME_TAG);
ItemMeta meta2 = item2.getItemMeta();
meta2.setDisplayName("Enter lore");
item2.setItemMeta(meta2);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item2);
gui.open();
}
break;
}
}
@Override
protected void registerClickables() {
resetClickables();
if (!isInInventory) {
registerClickable(9, true, ((player, inventory, cursor, slot, type) ->
new GUIGeneralOptions(plugin, player, this, kit)));
registerClickable(12, true, ((player, inventory, cursor, slot, type) ->
new GUIGUIOptions(plugin, player, this, kit)));
registerClickable(10, true, ((player, inventory, cursor, slot, type) ->
new GUISellingOptions(plugin, player, this, kit)));
registerClickable(17, true, (player, inventory, cursor, slot, type) -> {
if (kit.getKitAnimation() == KitAnimation.NONE) {
kit.setKitAnimation(KitAnimation.ROULETTE);
} else {
kit.setKitAnimation(KitAnimation.NONE);
}
getInvItems();
});
registerClickable(14, true, ((player, inventory, cursor, slot, type) -> {
saveKit(player, this.inventory, true);
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
ItemStack parseStack2 = new ItemStack(Material.PAPER, 1);
ItemMeta meta2 = parseStack2.getItemMeta();
ArrayList<String> lore2 = new ArrayList<>();
int index2 = 0;
while (index2 < msg.length()) {
lore2.add("§a$" + msg.substring(index2, Math.min(index2 + 30, msg.length())));
index2 += 30;
}
meta2.setLore(lore2);
meta2.setDisplayName(plugin.getLocale().getMessage("general.type.money").getMessage());
parseStack2.setItemMeta(meta2);
plugin.getLocale().newMessage("&8Money &5$" + msg + "&8 has been added to your kit.")
.sendPrefixedMessage(player);
this.slot = 0;
this.toReplace = parseStack2;
});
gui.setOnClose((player1, inventory1) -> init(title, 54));
ItemStack item = new ItemStack(Material.DIAMOND);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("Enter Price (No $)");
item.setItemMeta(meta);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item);
gui.open();
}));
registerClickable(13, true, ((player, inventory, cursor, slot, type) -> {
saveKit(player, this.inventory, true);
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
ItemStack parseStack = new ItemStack(Material.PAPER, 1);
ItemMeta meta = parseStack.getItemMeta();
ArrayList<String> lore = new ArrayList<>();
int index = 0;
while (index < msg.length()) {
lore.add(ChatColor.COLOR_CHAR + "a/" + msg.substring(index, Math.min(index + 30, msg.length())));
index += 30;
}
meta.setLore(lore);
meta.setDisplayName(plugin.getLocale().getMessage("general.type.command").getMessage());
parseStack.setItemMeta(meta);
plugin.getLocale().newMessage("&8Command &5" + msg + "&8 has been added to your kit.")
.sendPrefixedMessage(player);
this.slot = 0;
this.toReplace = parseStack;
});
gui.setOnClose((player1, inventory1) -> init(title, 54));
ItemStack item = new ItemStack(Material.PAPER);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("Enter Command (No /)");
item.setItemMeta(meta);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item);
gui.open();
}));
}
if (isInFuction) {
registerClickable(10, 43, ClickType.SHIFT_LEFT, (player, inventory, cursor, slot, type) -> {
if (inventory.getItem(slot) == null) return;
replaceItem(Action.CHANCE, player, inventory.getItem(slot), slot);
});
registerClickable(10, 43, ClickType.LEFT, (player, inventory, cursor, slot, type) -> {
if (inventory.getItem(slot) == null) return;
replaceItem(Action.DISPLAY_ITEM, player, inventory.getItem(slot), slot);
});
registerClickable(10, 43, ClickType.MIDDLE, (player, inventory, cursor, slot, type) -> {
if (inventory.getItem(slot) == null) return;
replaceItem(Action.DISPLAY_NAME, player, inventory.getItem(slot), slot);
});
registerClickable(10, 43, ClickType.RIGHT, (player, inventory, cursor, slot, type) -> {
if (inventory.getItem(slot) == null) return;
replaceItem(Action.DISPLAY_LORE, player, inventory.getItem(slot), slot);
});
}
registerClickable(8, (player, inventory, cursor, slot, type) -> player.closeInventory());
registerClickable(0, ((player, inventory, cursor, slot, type) -> {
if (back == null) return;
back.init(back.getSetTitle(), back.getInventory().getSize());
}));
registerClickable(48, ((player1, inventory, cursor, slot1, type) -> {
isInFuction = !isInFuction;
saveKit(player1, inventory,true);
constructGUI();
}));
registerClickable(50, (player, inventory, cursor, slot, type) -> {
if (!isInInventory) {
player.getInventory().setContents(inventoryItems);
isInInventory = true;
player.updateInventory();
} else {
saveItemsInstance();
getInvItems();
}
updateInvButton();
});
}
@Override
protected void registerOnCloses() {
registerOnClose((player1, inventory1) -> {
this.saveKit(player1, inventory1, false);
if (!isInInventory && this.inventoryItems.length != 0) {
player.getInventory().setContents(this.inventoryItems);
player.updateInventory();
}
player.playSound(player.getLocation(), plugin.isServerVersionAtLeast(ServerVersion.V1_9) ? Sound.ENTITY_VILLAGER_YES : Sound.valueOf("VILLAGER_YES"), 1F, 1F);
});
}
public enum Action {NONE, CHANCE, DISPLAY_ITEM, DISPLAY_NAME, DISPLAY_LORE}
}

View File

@ -1,314 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.ArrayList;
import java.util.List;
public class GUIKitSelector extends AbstractGUI {
private Player player;
private UltimateKits plugin;
private int timer;
private int page = 1;
private int max;
private List<String> kitList;
private boolean kitsmode = false;
private boolean glassless;
public GUIKitSelector(UltimateKits plugin, Player player) {
super(player);
this.player = player;
this.plugin = plugin;
kitList = new ArrayList<>();
setUpPage();
glassless = plugin.getConfig().getBoolean("Interfaces.Do Not Use Glass Borders");
int n = 7;
if (glassless)
n = 9;
max = 27;
if (kitList.size() > n) {
max = 36;
}
if (glassless) {
if (kitList.size() > n + 36)
max = max + 36;
else if (kitList.size() > n + 27)
max = max + 27;
else if (kitList.size() > n + 18)
max = max + 18;
else if (kitList.size() > n + 9)
max = max + 9;
}
if (glassless) max -= 18;
init(plugin.getLocale().getMessage("interface.selector.title").getMessage(), max);
timer = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
if (inventory.getViewers().isEmpty()) return;
constructGUI();
}, 20L, 20L);
}
private void setUpPage() {
int ino = 14;
if (plugin.getConfig().getBoolean("Interfaces.Do Not Use Glass Borders")) ino = 54;
int num = 0;
int start = (page - 1) * ino;
int show = 1;
kitList.clear();
for (Kit kit : plugin.getKitManager().getKits()) {
if (!kit.isHidden()
&& (!plugin.getConfig().getBoolean("Main.Only Show Players Kits They Have Permission To Use") || kit.hasPermission(player))
&& num >= start
&& show <= ino) {
kitList.add(kit.getName());
show++;
}
num++;
}
}
@Override
protected void constructGUI() {
resetClickables();
registerClickables();
ItemStack exit = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Exit Icon")), 1);
ItemMeta exitmeta = exit.getItemMeta();
exitmeta.setDisplayName(UltimateKits.getInstance().getLocale().getMessage("interface.button.exit")
.getMessage());
exit.setItemMeta(exitmeta);
int num = 0;
if (!glassless) {
while (num != max) {
ItemStack glass = Methods.getGlass();
inventory.setItem(num, glass);
num++;
}
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(8, Methods.getBackgroundGlass(true));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(max - 18, Methods.getBackgroundGlass(true));
inventory.setItem(max - 9, Methods.getBackgroundGlass(true));
inventory.setItem(max - 8, Methods.getBackgroundGlass(true));
inventory.setItem(max - 10, Methods.getBackgroundGlass(true));
inventory.setItem(max - 2, Methods.getBackgroundGlass(true));
inventory.setItem(max - 1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(max - 7, Methods.getBackgroundGlass(false));
inventory.setItem(max - 3, Methods.getBackgroundGlass(false));
}
num = glassless ? 0 : 10;
int id = 0;
int tmax = max;
if (!glassless)
tmax = tmax - 10;
for (int index = num; index != tmax; index++) {
if (!glassless) {
if (index == 17 || index == (max - 18)) index++;
if (index == 18 && max == 36) index++;
}
if (id > kitList.size() - 1) {
inventory.setItem(index, new ItemStack(Material.AIR));
continue;
}
String kitItem = kitList.get(id);
Kit kit = plugin.getKitManager().getKit(kitItem);
String title = plugin.getLocale().getMessage("interface.selector.kit")
.processPlaceholder("kit", Methods.formatText(kitItem, true)).getMessage();
if (kit.getTitle() != null)
title = Methods.formatText(kit.getTitle());
ItemStack item = new ItemStack(Material.ENCHANTED_BOOK);
if (kit.getDisplayItem() != null)
item.setType(kit.getDisplayItem());
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(Methods.convertToInvisibleString(kitItem + ":") + Methods.formatText(title));
ArrayList<String> lore = new ArrayList<>();
if (kit.getPrice() != 0)
lore.add(plugin.getLocale().getMessage("interface.selector.cost")
.processPlaceholder("cost", kit.getPrice()).getMessage());
else if (kit.getLink() != null)
lore.add(plugin.getLocale().getMessage("general.type.link").getMessage());
if (!kitsmode) {
if (!plugin.getLocale().getMessage("interface.selector.aboutkit").getMessage().trim().equals("")) {
String[] parts = plugin.getLocale().getMessage("interface.selector.aboutkit").getMessage().split("\\|");
lore.add("");
for (String line : parts)
lore.add(Methods.formatText(line));
}
if (kit.hasPermission(player)) {
if (kit.getNextUse(player) == -1) {
lore.add(plugin.getLocale().getMessage("event.claim.once").getMessage());
} else if (kit.getNextUse(player) > 0) {
if (!plugin.getLocale().getMessage("event.claim.wait").getMessage().trim().equals("")) {
lore.add(plugin.getLocale().getMessage("event.claim.wait")
.processPlaceholder("time", Methods.makeReadable(kit.getNextUse(player)))
.getMessage());
}
} else if (!plugin.getLocale().getMessage("event.claim.ready").getMessage().trim().equals("")) {
lore.add(plugin.getLocale().getMessage("event.claim.ready").getMessage());
}
} else
lore.add(plugin.getLocale().getMessage("event.claim.noaccess").getMessage());
lore.add("");
lore.add(plugin.getLocale().getMessage("interface.selector.leftpreview").getMessage());
if (kit.hasPermission(player)) {
lore.add(plugin.getLocale().getMessage("interface.selector.rightclaim").getMessage());
} else if (kit.getPrice() != 0 || kit.getLink() != null) {
lore.add(plugin.getLocale().getMessage("interface.selector.rightbuy").getMessage());
}
if (player.hasPermission("ultimatekits.admin")) {
lore.add("");
lore.add(plugin.getLocale().getMessage("interface.selector.middleclick").getMessage());
}
} else {
lore.add(Methods.formatText("&6&lEdit Mode"));
lore.add("");
lore.add(Methods.formatText("&6Left Click &7to move kit left"));
lore.add(Methods.formatText("&6Right Click &7to move kit right"));
lore.add("");
lore.add(Methods.formatText("&6Middle Click &7to go back."));
}
meta.setLore(lore);
item.setItemMeta(meta);
inventory.setItem(index, item);
registerClickable(index, ((player1, inventory1, cursor, slot, type) -> {
if (type == ClickType.MIDDLE && player.hasPermission("ultimatekits.admin")) {
kitsmode = !kitsmode;
constructGUI();
return;
}
if (kitsmode) {
if (type == ClickType.RIGHT) {
plugin.getKitManager().moveKit(kit, true);
} else if (type == ClickType.LEFT) {
plugin.getKitManager().moveKit(kit, false);
}
setUpPage();
constructGUI();
return;
}
if (type == ClickType.LEFT) {
kit.display(player, this);
return;
}
if (type == ClickType.RIGHT) {
kit.buy(player);
constructGUI();
}
}));
id++;
}
ItemStack info = new ItemStack(Material.BOOK, 1);
ItemMeta infometa = info.getItemMeta();
ArrayList<String> lore = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("interface.selector.details")
.processPlaceholder("player", player.getName()).getMessage().split("\\|");
boolean hit = false;
for (String line : parts) {
if (!hit)
infometa.setDisplayName(Methods.formatText(line));
else
lore.add(Methods.formatText(line));
hit = true;
}
infometa.setLore(lore);
info.setItemMeta(infometa);
ItemStack head = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.PLAYER_HEAD : Material.valueOf("SKULL_ITEM"), 1, (byte) 3);
ItemStack skull = Methods.addTexture(head, "http://textures.minecraft.net/texture/1b6f1a25b6bc199946472aedb370522584ff6f4e83221e5946bd2e41b5ca13b");
SkullMeta skullMeta = (SkullMeta) skull.getItemMeta();
skull.setDurability((short) 3);
skullMeta.setDisplayName(plugin.getLocale().getMessage("interface.button.next").getMessage());
skull.setItemMeta(skullMeta);
ItemStack skull2 = Methods.addTexture(head, "http://textures.minecraft.net/texture/3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23");
SkullMeta skull2Meta = (SkullMeta) skull2.getItemMeta();
skull2.setDurability((short) 3);
skull2Meta.setDisplayName(plugin.getLocale().getMessage("interface.button.next").getMessage());
skull2.setItemMeta(skull2Meta);
if (!plugin.getConfig().getBoolean("Interfaces.Do Not Use Glass Borders"))
inventory.setItem(max - 5, exit);
if (kitList.size() == 14)
inventory.setItem(max - 4, skull);
if (page != 1)
inventory.setItem(max - 6, skull2);
if (!plugin.getConfig().getBoolean("Interfaces.Do Not Use Glass Borders"))
inventory.setItem(4, info);
}
@Override
protected void registerClickables() {
registerClickable(max - 5, (player, inventory, cursor, slot, type) -> player.closeInventory());
registerClickable(max - 6, ((player1, inventory1, cursor, slot, type) -> {
if (page == 1) return;
page --;
setUpPage();
constructGUI();
}));
registerClickable(max - 4, ((player1, inventory1, cursor, slot, type) -> {
if (kitList.size() == 14) {
page++;
setUpPage();
constructGUI();
}
}));
}
@Override
protected void registerOnCloses() {
registerOnClose(((player1, inventory1) -> Bukkit.getScheduler().cancelTask(timer)));
}
}

View File

@ -1,186 +0,0 @@
package com.songoda.ultimatekits.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractAnvilGUI;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.ArrayList;
public class GUISellingOptions extends AbstractGUI {
private Kit kit;
private Player player;
private UltimateKits plugin;
private AbstractGUI back;
public GUISellingOptions(UltimateKits plugin, Player player, AbstractGUI back, Kit kit) {
super(player);
this.kit = kit;
this.player = player;
this.plugin = plugin;
this.back = back;
init("&8Selling Options for &a" + kit.getShowableName() + "&8.", 27);
}
@Override
protected void constructGUI() {
Methods.fillGlass(inventory);
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(8, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(10, Methods.getBackgroundGlass(false));
inventory.setItem(16, Methods.getBackgroundGlass(false));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(18, Methods.getBackgroundGlass(true));
inventory.setItem(19, Methods.getBackgroundGlass(true));
inventory.setItem(20, Methods.getBackgroundGlass(false));
inventory.setItem(24, Methods.getBackgroundGlass(false));
inventory.setItem(25, Methods.getBackgroundGlass(true));
inventory.setItem(26, Methods.getBackgroundGlass(true));
createButton(8, Material.valueOf(UltimateKits.getInstance().getConfig().getString("Interfaces.Exit Icon")),
UltimateKits.getInstance().getLocale().getMessage("interface.button.exit").getMessage());
ItemStack head = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.PLAYER_HEAD : Material.valueOf("SKULL_ITEM"), 1, (byte) 3);
ItemStack back = Methods.addTexture(head, "http://textures.minecraft.net/texture/3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23");
SkullMeta skull2Meta = (SkullMeta) back.getItemMeta();
back.setDurability((short) 3);
skull2Meta.setDisplayName(UltimateKits.getInstance().getLocale().getMessage("interface.button.back")
.getMessage());
back.setItemMeta(skull2Meta);
inventory.setItem(0, back);
ArrayList<String> lore = new ArrayList<>();
if (kit.getPrice() != 0 ||
kit.getLink() != null)
lore.add(Methods.formatText("&7Currently &aFor Sale&7."));
else
lore.add(Methods.formatText("&7Currently &cNot For Sale&7."));
lore.add(Methods.formatText(""));
lore.add(Methods.formatText("&7Clicking this option will"));
lore.add(Methods.formatText("&7remove this kit from sale."));
createButton(11, Material.BARRIER, "&c&lSet not for sale", lore);
lore = new ArrayList<>();
if (kit.getLink() != null)
lore.add(Methods.formatText("&7Currently: &a" + kit.getLink() + "&7."));
else
lore.add(Methods.formatText("&7Currently: &cNot set&7."));
lore.add(Methods.formatText(""));
lore.add(Methods.formatText("&7Clicking this option will"));
lore.add(Methods.formatText("&7allow you to set a link"));
lore.add(Methods.formatText("&7that players will receive"));
lore.add(Methods.formatText("&7when attempting to purchase"));
lore.add(Methods.formatText("&7this kit."));
createButton(13, Material.PAPER, "&a&lSet kit link", lore);
lore = new ArrayList<>();
if (kit.getPrice() != 0)
lore.add(Methods.formatText("&7Currently: &a$" + Methods.formatEconomy(kit.getPrice()) + "&7."));
else
lore.add(Methods.formatText("&7Currently: &cNot set&7."));
lore.add(Methods.formatText(""));
lore.add(Methods.formatText("&7Clicking this option will"));
lore.add(Methods.formatText("&7allow you to set a price"));
lore.add(Methods.formatText("&7that players will be able to"));
lore.add(Methods.formatText("&7purchase this kit for"));
lore.add(Methods.formatText("&7requires &aVault&7."));
createButton(15, plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.SUNFLOWER : Material.valueOf("DOUBLE_PLANT"), "&a&lSet kit price", lore);
}
@Override
protected void registerClickables() {
registerClickable(0, (player, inventory, cursor, slot, type) -> back.init(back.getSetTitle(), back.getInventory().getSize()));
registerClickable(8, (player, inventory, cursor, slot, type) -> player.closeInventory());
registerClickable(15, ((player1, inventory1, cursor, slot, type) -> {
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
if (plugin.getServer().getPluginManager().getPlugin("Vault") == null) {
plugin.getLocale().newMessage("&8You must have &aVault &8installed to utilize economy..")
.sendPrefixedMessage(player);
} else if (!Methods.isNumeric(msg)) {
player.sendMessage(Methods.formatText("&a" + msg + " &8is not a number. Please do not include a &a$&8."));
} else {
if (kit.getLink() != null) {
kit.setLink(null);
plugin.getLocale().newMessage("&8LINK has been removed from this kit. Note you cannot have ECO & LINK set at the same time..")
.sendPrefixedMessage(player);
}
Double eco = Double.parseDouble(msg);
kit.setPrice(eco);
if (plugin.getHologram() != null)
plugin.getHologram().update(kit);
}
});
gui.setOnClose((player2, inventory3) -> init(setTitle, inventory.getSize()));
ItemStack item = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.SUNFLOWER : Material.valueOf("DOUBLE_PLANT"));
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("Enter Price (No $)");
item.setItemMeta(meta);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item);
gui.open();
}));
registerClickable(13, ((player1, inventory1, cursor, slot, type) -> {
AbstractAnvilGUI gui = new AbstractAnvilGUI(player, event -> {
String msg = event.getName();
if (kit.getPrice() != 0) {
kit.setPrice(0);
plugin.getLocale().newMessage("&8ECO has been removed from this kit. Note you cannot have ECO & LINK set at the same time..")
.sendPrefixedMessage(player);
}
kit.setLink(msg);
if (plugin.getHologram() != null)
plugin.getHologram().update(kit);
});
gui.setOnClose((player2, inventory3) -> init(setTitle, inventory.getSize()));
ItemStack item = new ItemStack(Material.PAPER);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("Enter Link");
item.setItemMeta(meta);
gui.setSlot(AbstractAnvilGUI.AnvilSlot.INPUT_LEFT, item);
gui.open();
}));
registerClickable(11, ((player1, inventory1, cursor, slot, type) -> {
kit.setPrice(0);
kit.setLink(null);
constructGUI();
}));
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -0,0 +1,89 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.utils.ItemUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.event.inventory.ClickType;
import java.util.Random;
public class KitDecorOptionsGui extends Gui {
static final Random rand = new Random();
public KitDecorOptionsGui(UltimateKits plugin, KitBlockData kitBlockData, Gui parent) {
super(parent);
setRows(3);
setTitle(plugin.getLocale().getMessage("interface.kitdecor.title")
.processPlaceholder("kit", kitBlockData.getKit().getShowableName())
.getMessage());
Kit kit = kitBlockData.getKit();
// fill glass borders
Methods.fillGlass(this);
// exit button
setButton(0, 8, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
plugin.getLocale().getMessage("interface.button.exit").getMessage()),
ClickType.LEFT,
event -> exit());
// back button
setButton(0, 0, GuiUtils.createButtonItem(ItemUtils.getCustomHead("3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23"),
plugin.getLocale().getMessage("interface.button.back").getMessage()),
ClickType.LEFT,
event -> event.player.closeInventory());
final String enableLore = plugin.getLocale().getMessage("interface.kitdecor.settingon").getMessage();
final String disableLore = plugin.getLocale().getMessage("interface.kitdecor.settingoff").getMessage();
// Hologram
setButton(1, 1, GuiUtils.createButtonItem(CompatibleMaterial.NAME_TAG,
plugin.getLocale().getMessage("interface.kitdecor.hologram").getMessage(),
kitBlockData.showHologram() ? enableLore : disableLore),
event -> {
kitBlockData.setShowHologram(!kitBlockData.showHologram());
plugin.updateHologram(kitBlockData);
updateItemLore(event.slot, kitBlockData.showHologram() ? enableLore : disableLore);
});
// Particle effects
setButton(1, 3, GuiUtils.createButtonItem(CompatibleMaterial.POTION,
plugin.getLocale().getMessage("interface.kitdecor.particle").getMessage(),
kitBlockData.hasParticles() ? enableLore : disableLore),
event -> {
kitBlockData.setHasParticles(!kitBlockData.hasParticles());
updateItemLore(event.slot, kitBlockData.hasParticles() ? enableLore : disableLore);
});
// Item Display
setButton(1, 5, GuiUtils.createButtonItem(CompatibleMaterial.DIAMOND,
plugin.getLocale().getMessage("interface.kitdecor.display").getMessage(),
kitBlockData.isDisplayingItems() ? enableLore : disableLore),
event -> {
plugin.removeHologram(kitBlockData);
kitBlockData.setDisplayingItems(!kitBlockData.isDisplayingItems());
plugin.updateHologram(kitBlockData);
updateItemLore(event.slot, kitBlockData.isDisplayingItems() ? enableLore : disableLore);
});
// Item Display Override
setButton(1, 7, GuiUtils.createButtonItem(kit.getDisplayItem() != null ? kit.getDisplayItem() : CompatibleMaterial.BEACON,
plugin.getLocale().getMessage("interface.kitdecor.displayone").getMessage(),
plugin.getLocale().getMessage("interface.kitdecor.displayonelore")
.processPlaceholder("enabled", kitBlockData.isItemOverride() ? enableLore : disableLore)
.getMessage().split("\\|")),
event -> {
kitBlockData.setItemOverride(!kitBlockData.isItemOverride());
updateItemLore(event.slot, kitBlockData.isItemOverride() ? enableLore : disableLore);
});
}
}

View File

@ -0,0 +1,452 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.CompatibleSound;
import com.songoda.core.gui.AnvilGui;
import com.songoda.core.gui.DoubleGui;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.input.ChatPrompt;
import com.songoda.core.utils.ItemUtils;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitAnimation;
import com.songoda.ultimatekits.kit.KitItem;
import com.songoda.ultimatekits.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class KitEditorGui extends DoubleGui {
private UltimateKits plugin;
private Kit kit;
private Player player;
private ItemStack[] inventoryItems;
private boolean isInFuction = false;
private boolean isInInventory = false;
public KitEditorGui(UltimateKits plugin, Player player, Kit kit, Gui back) {
super(back);
this.plugin = plugin;
this.kit = kit;
this.player = player;
setDefaultItem(null);
setRows(6);
setTitle(plugin.getLocale().getMessage("interface.kiteditor.title")
.processPlaceholder("name", kit.getShowableName())
.getMessage());
saveItemsInstance();
setInvItems();
setOnClose((event) -> {
this.saveKit(player, inventory, false);
CompatibleSound.ENTITY_VILLAGER_YES.play(player);
if (!isInInventory && this.inventoryItems.length != 0) {
player.getInventory().setContents(this.inventoryItems);
player.updateInventory();
}
});
ItemStack glass1 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_1.getMaterial());
ItemStack glass2 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_2.getMaterial());
ItemStack glass3 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_3.getMaterial());
GuiUtils.mirrorFill(this, 0, 0, true, true, glass2);
GuiUtils.mirrorFill(this, 0, 1, true, true, glass2);
GuiUtils.mirrorFill(this, 1, 0, true, true, glass2);
GuiUtils.mirrorFill(this, 0, 2, true, true, glass3);
GuiUtils.mirrorFill(this, 0, 3, false, true, glass1);
// exit button
setButton(0, 8, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
plugin.getLocale().getMessage("interface.button.exit").getMessage()),
ClickType.LEFT,
event -> exit());
// back button
if (parent != null)
setButton(0, 0, GuiUtils.createButtonItem(ItemUtils.getCustomHead("3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23"),
plugin.getLocale().getMessage("interface.button.back").getMessage()),
ClickType.LEFT,
event -> event.player.closeInventory());
// info icon
setItem(0, 4, GuiUtils.createButtonItem(CompatibleMaterial.CHEST,
plugin.getLocale().getMessage("interface.kiteditor.info")
.processPlaceholder("kit", kit.getName())
.processPlaceholder("perm", "ultimatekits.kit." + kit.getName().toLowerCase())
.getMessage().split("\\|"))
);
paint();
}
private void paint() {
for (int i = 10; i < 44; i++) {
if (i == 17 || i == 36)
continue;
setItem(i, null);
}
int num = 10;
for (ItemStack itemStack : kit.getReadableContents(player, false, true, true)) {
if (num == 17 || num == 36)
num++;
KitItem item = new KitItem(itemStack);
ItemStack is = getCompiledMeta(item);
if (!isInFuction)
setButton(num, is, null);
else {
setButton(num, is,
(event) -> {
switch (event.clickType) {
case SHIFT_LEFT:
replaceItem(Action.CHANCE_UP, player, event.clickedItem, event.slot);
break;
case SHIFT_RIGHT:
replaceItem(Action.CHANCE_DOWN, player, event.clickedItem, event.slot);
break;
case LEFT:
replaceItem(Action.DISPLAY_ITEM, player, event.clickedItem, event.slot);
break;
case MIDDLE:
replaceItem(Action.DISPLAY_NAME, player, event.clickedItem, event.slot);
break;
case RIGHT:
replaceItem(Action.DISPLAY_LORE, player, event.clickedItem, event.slot);
break;
}
});
}
num++;
}
updateInvButton();
}
private void updateInvButton() {
ItemStack item;
if (!isInFuction) {
setUnlockedRange(1, 1, 1, 7);
setUnlockedRange(2, 0, 3, 8);
setUnlockedRange(4, 1, 4, 7);
item = GuiUtils.createButtonItem(CompatibleMaterial.PAPER,
plugin.getLocale().getMessage("interface.kiteditor.itemediting").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.itemeditinglore").getMessage().split("\\|"));
} else {
unlockedCells.clear();
item = GuiUtils.createButtonItem(CompatibleMaterial.PAPER,
plugin.getLocale().getMessage("interface.kiteditor.itemmoving").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.itemmovinglore").getMessage().split("\\|"));
}
setButton(48, item,
(event) -> {
isInFuction = !isInFuction;
saveKit(player, inventory, true);
paint();
});
ItemStack item2;
if (isInInventory) {
item2 = GuiUtils.createButtonItem(CompatibleMaterial.ITEM_FRAME,
plugin.getLocale().getMessage("interface.kiteditor.switchtokitfunctions").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.switchtokitfunctionslore").getMessage().split("\\|"));
} else {
item2 = GuiUtils.createButtonItem(CompatibleMaterial.ITEM_FRAME,
plugin.getLocale().getMessage("interface.kiteditor.switchtoinventory").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.switchtoinventorylore").getMessage().split("\\|"));
}
setButton(50, item2,
event -> {
if (!isInInventory) {
restoreItemsInstance();
setPlayerActionForRange(0, 0, 3, 8, null);
setAcceptsItems(true);
} else {
saveItemsInstance();
setInvItems();
setAcceptsItems(false);
}
updateInvButton();
});
}
private void saveItemsInstance() {
setPlayerUnlockedRange(0, 0, 3, 8, false);
inventoryItems = player.getInventory().getContents().clone();
player.getInventory().clear();
isInInventory = false;
}
private void restoreItemsInstance() {
setPlayerUnlockedRange(0, 0, 3, 8);
player.getInventory().setContents(inventoryItems);
player.updateInventory();
isInInventory = true;
}
private void setInvItems() {
this.setPlayerActionForRange(0, 0, 3, 8, event -> {
if (!isInInventory && event.player.getItemOnCursor().getType() != Material.AIR) {
event.event.setCancelled(true);
}
});
setPlayerButton(0, GuiUtils.createButtonItem(CompatibleMaterial.REDSTONE_TORCH,
plugin.getLocale().getMessage("interface.kiteditor.generaloptions").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.generaloptionslore").getMessage().split("\\|")),
(event) -> {
player.closeInventory();
guiManager.showGUI(player, new KitGeneralOptionsGui(plugin, player, kit, this));
});
setPlayerButton(1, GuiUtils.createButtonItem(CompatibleMaterial.EMERALD,
plugin.getLocale().getMessage("interface.kiteditor.sellingoptions").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.sellingoptionslore").getMessage().split("\\|")),
(event) -> {
player.closeInventory();
guiManager.showGUI(player, new KitSellingOptionsGui(plugin, player, kit, this));
});
setPlayerButton(3, GuiUtils.createButtonItem(CompatibleMaterial.ITEM_FRAME,
plugin.getLocale().getMessage("interface.kiteditor.guioptions").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.guioptionslore").getMessage().split("\\|")),
(event) -> {
player.closeInventory();
guiManager.showGUI(player, new KitGuiOptionsGui(plugin, player, kit, this));
});
setPlayerButton(4, GuiUtils.createButtonItem(CompatibleMaterial.PAPER,
plugin.getLocale().getMessage("interface.kiteditor.addcommand").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.addcommandlore").getMessage().split("\\|")),
(event) -> {
event.gui.exit();
ChatPrompt.showPrompt(event.manager.getPlugin(), event.player, "Enter a command for this kit:", response -> {
String msg = response.getMessage().trim();
ItemStack parseStack = new ItemStack(Material.PAPER, 1);
ItemMeta meta = parseStack.getItemMeta();
ArrayList<String> lore = new ArrayList<>();
int index = 0;
while (index < msg.length()) {
lore.add(ChatColor.GREEN + "/" + msg.substring(index, Math.min(index + 30, msg.length())));
index += 30;
}
meta.setLore(lore);
meta.setDisplayName(plugin.getLocale().getMessage("general.type.command").getMessage());
parseStack.setItemMeta(meta);
plugin.getLocale().newMessage(plugin.getLocale().getMessage("interface.kiteditor.addcommandok")
.processPlaceholder("command", msg).getMessage())
.sendPrefixedMessage(player);
this.inventory.addItem(parseStack);
player.closeInventory();
}).setOnClose(() -> {
event.manager.showGUI(event.player, this);
})
.setOnCancel(() -> {
event.player.sendMessage(ChatColor.RED + "Edit canceled");
event.manager.showGUI(event.player, this);
});
});
setPlayerButton(5, GuiUtils.createButtonItem(CompatibleMaterial.SUNFLOWER,
plugin.getLocale().getMessage("interface.kiteditor.addeconomy").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.addeconomylore").getMessage().split("\\|")),
(event) -> {
AnvilGui gui = new AnvilGui(player, this);
gui.setTitle(plugin.getLocale().getMessage("interface.kiteditor.addeconomyprompt").getMessage());
gui.setAction(aevent -> {
String msg = gui.getInputText().trim();
ItemStack parseStack = new ItemStack(Material.PAPER, 1);
ItemMeta meta = parseStack.getItemMeta();
ArrayList<String> lore = new ArrayList<>();
int index = 0;
while (index < msg.length()) {
lore.add(ChatColor.GREEN + "$" + msg.substring(index, Math.min(index + 30, msg.length())));
index += 30;
}
meta.setLore(lore);
meta.setDisplayName(plugin.getLocale().getMessage("general.type.money").getMessage());
parseStack.setItemMeta(meta);
plugin.getLocale().getMessage("interface.kiteditor.addeconomyok").processPlaceholder("amount", msg.trim())
.sendPrefixedMessage(player);
this.inventory.addItem(parseStack);
player.closeInventory();
});
guiManager.showGUI(event.player, gui);
});
setPlayerButton(8, GuiUtils.createButtonItem(CompatibleMaterial.CHEST,
plugin.getLocale().getMessage("interface.kiteditor.animation").getMessage(),
plugin.getLocale().getMessage("interface.kiteditor.animationlore")
.processPlaceholder("animation", kit.getKitAnimation().name())
.getMessage().split("\\|")),
(event) -> {
if (kit.getKitAnimation() == KitAnimation.NONE) {
kit.setKitAnimation(KitAnimation.ROULETTE);
} else {
kit.setKitAnimation(KitAnimation.NONE);
}
setInvItems();
});
}
public void saveKit(Player player, Inventory i, boolean muteSave) {
ItemStack[] items = i.getContents();
for (int num = 0; num < items.length; ++num) {
if (num < 10 || num == 17 || num == 36) {
items[num] = null;
}
}
items = Arrays.copyOf(items, items.length - 10);
kit.saveKit(Arrays.asList(items));
if (!muteSave)
plugin.getLocale().getMessage("interface.kiteditor.saved")
.processPlaceholder("kit", kit.getShowableName())
.sendPrefixedMessage(player);
}
public void replaceItem(Action action, Player player, ItemStack itemStack, int slot) {
if (itemStack.getItemMeta().hasLore()) {
ItemMeta meta = itemStack.getItemMeta();
List<String> newLore = new ArrayList<>();
for (String line : meta.getLore()) {
if (TextUtils.convertFromInvisibleString(line).equals("----")) break;
newLore.add(line);
}
meta.setLore(newLore);
itemStack.setItemMeta(meta);
}
KitItem item = new KitItem(itemStack);
switch (action) {
case CHANCE_UP:
case CHANCE_DOWN:
if (action == Action.CHANCE_UP)
item.setChance(item.getChance() >= 100 ? 5 : (item.getChance() + 5));
else
item.setChance(item.getChance() <= 0 ? 100 : (item.getChance() - 5));
setItem(slot, getCompiledMeta(item));
saveKit(player, inventory, true);
paint();
break;
case DISPLAY_ITEM: {
AnvilGui gui = new AnvilGui(player, this);
gui.setTitle("Enter a Material");
gui.setAction(event -> {
CompatibleMaterial compatibleMaterial = CompatibleMaterial.getMaterial(gui.getInputText());
if (compatibleMaterial == null) {
player.sendMessage(gui.getInputText() + " is not a valid material.");
} else {
Material material = compatibleMaterial.getMaterial();
KitItem newItem = new KitItem(itemStack);
newItem.setDisplayItem(material);
setItem(slot, newItem.getMoveableItem());
player.closeInventory();
saveKit(player, inventory, true);
paint();
}
});
guiManager.showGUI(player, gui);
}
break;
case DISPLAY_NAME: {
AnvilGui gui = new AnvilGui(player, this);
gui.setTitle("Enter a name");
gui.setAction(event -> {
KitItem newItem = new KitItem(itemStack);
newItem.setDisplayName(gui.getInputText());
setItem(slot, getCompiledMeta(newItem));
player.closeInventory();
saveKit(player, inventory, true);
paint();
});
guiManager.showGUI(player, gui);
}
break;
case DISPLAY_LORE: {
AnvilGui gui = new AnvilGui(player, this);
gui.setTitle("Enter lore");
gui.setAction(event -> {
KitItem newItem = new KitItem(itemStack);
newItem.setDisplayLore(gui.getInputText());
setItem(slot, getCompiledMeta(newItem));
player.closeInventory();
saveKit(player, inventory, true);
paint();
});
guiManager.showGUI(player, gui);
}
break;
}
}
private ItemStack getCompiledMeta(KitItem item) {
ItemStack is = item.getMoveableItem();
ItemMeta meta;
if (is.hasItemMeta()) meta = is.getItemMeta();
else meta = Bukkit.getItemFactory().getItemMeta(is.getType());
List<String> itemLore;
if (meta.hasLore()) itemLore = meta.getLore();
else itemLore = new ArrayList<>();
itemLore.add(TextUtils.convertToInvisibleLoreString("----"));
itemLore.add(ChatColor.GRAY.toString() + plugin.getLocale().getMessage("general.type.chance") + ": " + ChatColor.GOLD.toString() + item.getChance() + "%");
if (isInFuction) {
itemLore.addAll(Arrays.asList(plugin.getLocale().getMessage("interface.kiteditor.itemfunctionlore")
.processPlaceholder("item", item.getDisplayItem() == null ? "" : item.getDisplayItem().name())
.processPlaceholder("name", item.getDisplayName())
.processPlaceholder("lore", item.getDisplayLore())
.getMessage().split("\\|")));
}
meta.setLore(itemLore);
is.setItemMeta(meta);
return is;
}
public enum Action {NONE, CHANCE_UP, CHANCE_DOWN, DISPLAY_ITEM, DISPLAY_NAME, DISPLAY_LORE}
}

View File

@ -0,0 +1,87 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.AnvilGui;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.utils.ItemUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
public class KitGeneralOptionsGui extends Gui {
public KitGeneralOptionsGui(UltimateKits plugin, Player player, Kit kit, Gui back) {
super(back);
setRows(3);
setTitle(plugin.getLocale().getMessage("interface.kitoptions.title")
.processPlaceholder("kit", kit.getShowableName())
.getMessage());
// fill glass borders
Methods.fillGlass(this);
// exit button
setButton(0, 8, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
plugin.getLocale().getMessage("interface.button.exit").getMessage()),
ClickType.LEFT,
event -> exit());
// back button
setButton(0, 0, GuiUtils.createButtonItem(ItemUtils.getCustomHead("3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23"),
plugin.getLocale().getMessage("interface.button.back").getMessage()),
ClickType.LEFT,
event -> event.player.closeInventory());
// edit delay
setButton(1, 2, GuiUtils.createButtonItem(CompatibleMaterial.CLOCK,
plugin.getLocale().getMessage("interface.kitoptions.delay").getMessage(),
plugin.getLocale().getMessage("interface.kitoptions.delaylore")
.processPlaceholder("delay", kit.getDelay()).getMessage().split("\\|")),
event -> {
AnvilGui gui = new AnvilGui(event.player, this);
gui.setTitle(plugin.getLocale().getMessage("interface.kitoptions.delayprompt").getMessage());
gui.setAction(aevent -> {
final String msg = gui.getInputText();
final String num = msg != null ? msg.replaceAll("[^0-9]", "") : "";
if (!num.isEmpty()) {
try {
kit.setDelay(Integer.parseInt(num));
updateItemLore(event.slot, plugin.getLocale().getMessage("interface.kitoptions.delaylore")
.processPlaceholder("delay", kit.getDelay()).getMessage().split("\\|"));
aevent.player.closeInventory();
} catch (NumberFormatException e) {
}
}
plugin.getLocale().getMessage("interface.kitoptions.delaynonumber").processPlaceholder("input", msg).sendPrefixedMessage(player);
});
guiManager.showGUI(event.player, gui);
});
// delete
setButton(1, 6, GuiUtils.createButtonItem(CompatibleMaterial.TNT,
plugin.getLocale().getMessage("interface.kitoptions.destroy").getMessage(),
plugin.getLocale().getMessage("interface.kitoptions.destroylore").getMessage().split("\\|")),
event -> {
AnvilGui gui = new AnvilGui(event.player);
gui.setTitle(plugin.getLocale().getMessage("interface.kitoptions.destroyprompt").processPlaceholder("kit", kit.getName()).getMessage());
gui.setAction(aevent -> {
final String msg = gui.getInputText();
if (msg != null && msg.trim().equalsIgnoreCase(kit.getName())) {
plugin.getKitManager().removeKit(kit);
plugin.updateHologram(kit);
plugin.getLocale().getMessage("interface.kitoptions.destroyok").sendPrefixedMessage(player);
} else {
plugin.getLocale().getMessage("interface.kitoptions.destroycancel").sendPrefixedMessage(player);
}
aevent.player.closeInventory();
});
guiManager.showGUI(event.player, gui);
});
}
}

View File

@ -0,0 +1,120 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.AnvilGui;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.utils.ItemUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
public class KitGuiOptionsGui extends Gui {
private final UltimateKits plugin;
private final Kit kit;
private final Player player;
public KitGuiOptionsGui(UltimateKits plugin, Player player, Kit kit, Gui back) {
super(back);
this.plugin = plugin;
this.kit = kit;
this.player = player;
setRows(3);
setTitle(plugin.getLocale().getMessage("interface.kitblock.title")
.processPlaceholder("kit", kit.getShowableName())
.getMessage());
setAcceptsItems(true); // display item takes an item
// fill glass borders
Methods.fillGlass(this);
// exit button
setButton(0, 8, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
plugin.getLocale().getMessage("interface.button.exit").getMessage()),
ClickType.LEFT,
event -> exit());
// back button
setButton(0, 0, GuiUtils.createButtonItem(ItemUtils.getCustomHead("3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23"),
plugin.getLocale().getMessage("interface.button.back").getMessage()),
ClickType.LEFT,
event -> event.player.closeInventory());
paint();
}
private void paint() {
// set hologram title
setButton(1, 2, GuiUtils.createButtonItem(CompatibleMaterial.NAME_TAG,
plugin.getLocale().getMessage("interface.kitguioptions.holo").getMessage(),
plugin.getLocale().getMessage("interface.kitguioptions.hololore")
.processPlaceholder("onoff",
kit.getTitle() != null ? plugin.getLocale().getMessage("interface.kitguioptions.holoon").processPlaceholder("title", kit.getTitle()).getMessage()
: plugin.getLocale().getMessage("interface.kitguioptions.holooff").getMessage()
).getMessage().split("\\|")),
ClickType.LEFT,
event -> {
AnvilGui gui = new AnvilGui(event.player, this);
gui.setTitle(plugin.getLocale().getMessage("interface.kitguioptions.holoprompt").getMessage());
gui.setAction(aevent -> {
final String msg = gui.getInputText().trim();
kit.setTitle(msg);
plugin.getLocale().getMessage("interface.kitguioptions.holoset")
.processPlaceholder("title", msg)
.processPlaceholder("kit", kit.getShowableName())
.sendPrefixedMessage(player);
plugin.updateHologram(kit);
aevent.player.closeInventory();
paint();
});
guiManager.showGUI(event.player, gui);
});
setAction(1, 2, ClickType.RIGHT, event -> {
kit.setTitle(null);
plugin.updateHologram(kit);
paint();
});
setButton(1, 4, GuiUtils.createButtonItem(kit.getDisplayItem() != null ? kit.getDisplayItem() : CompatibleMaterial.BEACON,
plugin.getLocale().getMessage("interface.kitguioptions.item").getMessage(),
plugin.getLocale().getMessage("interface.kitguioptions.itemlore")
.processPlaceholder("onoff",
kit.getDisplayItem() != null ? plugin.getLocale().getMessage("interface.kitguioptions.itemon").processPlaceholder("item", kit.getDisplayItem().toString()).getMessage()
: plugin.getLocale().getMessage("interface.kitguioptions.itemoff").getMessage()
).getMessage().split("\\|")),
ClickType.LEFT,
event -> {
ItemStack is = player.getItemInHand();
if (is.getType() == Material.AIR) {
plugin.getLocale().getMessage("interface.kitguioptions.itemnoitem").sendPrefixedMessage(player);
} else {
kit.setDisplayItem(is);
plugin.getLocale().getMessage("interface.kitguioptions.itemset").processPlaceholder("item", kit.getShowableName()).sendPrefixedMessage(player);
paint();
}
});
setAction(1, 4, ClickType.RIGHT, event -> {
kit.setDisplayItem(null);
plugin.getLocale().getMessage("interface.kitguioptions.itemremoved").processPlaceholder("kit", kit.getShowableName()).sendPrefixedMessage(player);
paint();
});
setButton(1, 6, GuiUtils.createButtonItem(CompatibleMaterial.COAL,
plugin.getLocale().getMessage("interface.kitguioptions.hide").getMessage(),
plugin.getLocale().getMessage("interface.kitguioptions.hidelore")
.processPlaceholder("onoff", plugin.getLocale().getMessage(
kit.isHidden() ? "interface.kitguioptions.hideon" : "interface.kitguioptions.hideoff").getMessage()
).getMessage().split("\\|")),
ClickType.LEFT,
event -> {
kit.setHidden(!kit.isHidden());
paint();
});
}
}

View File

@ -0,0 +1,209 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.utils.ItemUtils;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.Methods;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
public class KitSelectorGui extends Gui {
private Player player;
private UltimateKits plugin;
private int timer;
private List<String> kitList;
private boolean kitsmode = false;
private boolean glassless;
private int showPerRow, showPerPage;
public KitSelectorGui(UltimateKits plugin, Player player) {
this.player = player;
this.plugin = plugin;
glassless = Settings.DO_NOT_USE_GLASS_BORDERS.getBoolean();
setTitle(plugin.getLocale().getMessage("interface.selector.title").getMessage());
loadKits();
showPerRow = glassless ? 9 : 7;
int nrows = (int) Math.ceil(kitList.size() / (double) showPerRow);
setRows(glassless ? nrows : nrows + 2);
showPerPage = showPerRow * (glassless ? (nrows == 6 ? 6 : 5) : 4);
setPages(kitList.size() / showPerPage);
setItem(0, 4, GuiUtils.createButtonItem(CompatibleMaterial.BOOK,
plugin.getLocale().getMessage("interface.selector.details")
.processPlaceholder("player", player.getName()).getMessage().split("\\|")));
if (pages > 1) {
this.setNextPage(rows - 1, 5, GuiUtils.createButtonItem(ItemUtils.getCustomHead("1b6f1a25b6bc199946472aedb370522584ff6f4e83221e5946bd2e41b5ca13b"),
plugin.getLocale().getMessage("interface.button.next").getMessage()));
this.setPrevPage(rows - 1, 3, GuiUtils.createButtonItem(ItemUtils.getCustomHead("3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23"),
plugin.getLocale().getMessage("interface.button.last").getMessage()));
this.setOnPage(pager -> showPage());
}
if (!glassless) {
setButton(rows - 1, 4, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
UltimateKits.getInstance().getLocale().getMessage("interface.button.exit").getMessage()),
event -> exit());
}
ItemStack glass2 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_2.getMaterial());
setDefaultItem(AIR);
GuiUtils.mirrorFill(this, 0, 0, true, true, glass2);
if(!glassless) {
if(Settings.RAINBOW.getBoolean()) {
animateGlass();
timer = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
if (inventory.getViewers().isEmpty()) return;
animateGlass();
}, 20L, 20L);
setOnClose(event -> Bukkit.getScheduler().cancelTask(timer));
} else {
ItemStack glass1 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_1.getMaterial());
ItemStack glass3 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_3.getMaterial());
GuiUtils.mirrorFill(this, 0, 0, true, true, glass2);
GuiUtils.mirrorFill(this, 1, 0, true, true, glass2);
GuiUtils.mirrorFill(this, 0, 1, true, true, glass2);
GuiUtils.mirrorFill(this, 0, 2, true, true, glass3);
GuiUtils.mirrorFill(this, 0, 3, false, true, glass1);
}
}
showPage();
}
private void loadKits() {
boolean showAll = !Settings.ONLY_SHOW_KITS_WITH_PERMS.getBoolean();
kitList = plugin.getKitManager().getKits().stream()
.filter(kit -> !kit.isHidden() && (showAll || kit.hasPermission(player)))
.map(kit -> kit.getName())
.collect(Collectors.toList());
}
static final Random rand = new Random();
private void animateGlass() {
for(int col = 1; col < 8; ++col) {
ItemStack it;
if((it = getItem(0, col)) == null || it.getType() == Material.AIR || it.getType().name().contains("PANE"))
setItem(0, col, GuiUtils.getBorderItem(CompatibleMaterial.getGlassPaneColor(rand.nextInt(16))));
if((it = getItem(rows - 1, col)) == null || it.getType() == Material.AIR || it.getType().name().contains("PANE"))
setItem(rows - 1, col, GuiUtils.getBorderItem(CompatibleMaterial.getGlassPaneColor(rand.nextInt(16))));
}
for(int row = 1; row + 1 < rows; ++row) {
setItem(row, 0, GuiUtils.getBorderItem(CompatibleMaterial.getGlassPaneColor(rand.nextInt(16))));
setItem(row, 8, GuiUtils.getBorderItem(CompatibleMaterial.getGlassPaneColor(rand.nextInt(16))));
}
}
private void showPage() {
int index = (page - 1) * showPerPage;
for (int row = glassless ? 0 : 1; row < (!glassless || pages != 1 ? rows - 1 : rows); ++row) {
for (int col = glassless ? 0 : 1; col < (glassless ? 9 : 8); ++col) {
if(index >= kitList.size()) {
setItem(row, col, null);
clearActions(row, col);
continue;
}
final String kitItem = kitList.get(index++);
final Kit kit = plugin.getKitManager().getKit(kitItem);
String kitTitle = kit.getTitle() != null
? ChatColor.translateAlternateColorCodes('&', kit.getTitle())
: plugin.getLocale().getMessage("interface.selector.kit")
.processPlaceholder("kit", TextUtils.formatText(kitItem, true)).getMessage();
setButton(row, col, GuiUtils.createButtonItem(
kit.getDisplayItem() != null ? kit.getDisplayItem() : CompatibleMaterial.ENCHANTED_BOOK,
TextUtils.convertToInvisibleString(kitItem + ":") + kitTitle,
getKitLore(kit)),
event -> {
if (event.clickType == ClickType.MIDDLE && player.hasPermission("ultimatekits.admin")) {
kitsmode = !kitsmode;
showPage();
} else if (kitsmode) {
if (event.clickType == ClickType.RIGHT) {
plugin.getKitManager().moveKit(kit, true);
} else if (event.clickType == ClickType.LEFT) {
plugin.getKitManager().moveKit(kit, false);
}
loadKits();
showPage();
} else if (event.clickType == ClickType.LEFT) {
kit.display(player, guiManager, this);
} else if (event.clickType == ClickType.RIGHT) {
kit.buy(event.player, event.manager);
}
});
}
}
}
private List<String> getKitLore(Kit kit) {
ArrayList<String> lore = new ArrayList<>();
if (kit.getPrice() != 0)
lore.add(plugin.getLocale().getMessage("interface.selector.aboutkitprice")
.processPlaceholder("price", String.valueOf(kit.getPrice()))
.getMessage());
else if (kit.getLink() != null)
lore.add(plugin.getLocale().getMessage("general.type.link").getMessage());
if (!kitsmode) {
if (!plugin.getLocale().getMessage("interface.selector.aboutkit").getMessage().trim().equals("")) {
String[] parts = plugin.getLocale().getMessage("interface.selector.aboutkit").getMessage().split("\\|");
lore.add("");
for (String line : parts)
lore.add(ChatColor.translateAlternateColorCodes('&', line));
}
if (kit.hasPermission(player)) {
if (kit.getNextUse(player) == -1) {
lore.add(plugin.getLocale().getMessage("event.claim.once").getMessage());
} else if (kit.getNextUse(player) > 0) {
if (!plugin.getLocale().getMessage("event.claim.wait").getMessage().trim().equals("")) {
lore.add(plugin.getLocale().getMessage("event.claim.wait")
.processPlaceholder("time", Methods.makeReadable(kit.getNextUse(player)))
.getMessage());
}
} else if (!plugin.getLocale().getMessage("event.claim.ready").getMessage().trim().equals("")) {
lore.add(plugin.getLocale().getMessage("event.claim.ready").getMessage());
}
} else
lore.add(plugin.getLocale().getMessage("event.claim.noaccess").getMessage());
lore.add("");
lore.add(plugin.getLocale().getMessage("interface.selector.leftpreview").getMessage());
if (kit.hasPermission(player)) {
lore.add(plugin.getLocale().getMessage("interface.selector.rightclaim").getMessage());
} else if (kit.getPrice() != 0 || kit.getLink() != null) {
lore.add(plugin.getLocale().getMessage("interface.selector.rightbuy").getMessage());
}
if (player.hasPermission("ultimatekits.admin")) {
lore.add("");
lore.add(plugin.getLocale().getMessage("interface.selector.adminlore").getMessage());
}
} else {
lore.addAll(Arrays.asList(plugin.getLocale().getMessage("interface.selector.editlore").getMessage().split("\\|")));
}
return lore;
}
}

View File

@ -0,0 +1,128 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.AnvilGui;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.hooks.EconomyManager;
import com.songoda.core.utils.ItemUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import java.util.Random;
public class KitSellingOptionsGui extends Gui {
private final UltimateKits plugin;
private final Player player;
private final Kit kit;
public KitSellingOptionsGui(UltimateKits plugin, Player player, Kit kit, Gui back) {
super(back);
this.plugin = plugin;
this.player = player;
this.kit = kit;
setRows(3);
setTitle(plugin.getLocale().getMessage("interface.kitblock.title")
.processPlaceholder("kit", kit.getShowableName())
.getMessage());
// fill glass borders
Methods.fillGlass(this);
// exit button
setButton(0, 8, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
plugin.getLocale().getMessage("interface.button.exit").getMessage()),
ClickType.LEFT,
event -> exit());
// back button
setButton(0, 0, GuiUtils.createButtonItem(ItemUtils.getCustomHead("3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23"),
plugin.getLocale().getMessage("interface.button.back").getMessage()),
ClickType.LEFT,
event -> event.player.closeInventory());
paint();
}
private void paint() {
// remove sale
setButton(1, 2, GuiUtils.createButtonItem(CompatibleMaterial.BARRIER,
plugin.getLocale().getMessage("interface.kitsell.nosell").getMessage(),
plugin.getLocale().getMessage("interface.kitsell.noselllore")
.processPlaceholder("onoff", plugin.getLocale().getMessage(
kit.getPrice() != 0 || kit.getLink() != null ? "interface.kitsell.nosellon" : "interface.kitsell.noselloff").getMessage()
).getMessage().split("\\|")),
event -> {
kit.setPrice(0);
kit.setLink(null);
paint();
});
// kit link
setButton(1, 4, GuiUtils.createButtonItem(CompatibleMaterial.PAPER,
plugin.getLocale().getMessage("interface.kitsell.link").getMessage(),
plugin.getLocale().getMessage("interface.kitsell.linklore")
.processPlaceholder("onoff",
kit.getLink() != null ? plugin.getLocale().getMessage("interface.kitsell.linkon").processPlaceholder("kit", kit.getLink()).getMessage()
: plugin.getLocale().getMessage("interface.kitsell.linkoff").getMessage()
).getMessage().split("\\|")),
event -> {
AnvilGui gui = new AnvilGui(event.player, this);
gui.setTitle(plugin.getLocale().getMessage("interface.kitsell.linkprompt").getMessage());
gui.setAction(aevent -> {
final String msg = gui.getInputText().trim();
if (kit.getPrice() != 0) {
kit.setPrice(0);
plugin.getLocale().getMessage("interface.kitsell.linknoeco").sendPrefixedMessage(player);
}
kit.setLink(msg);
plugin.updateHologram(kit);
aevent.player.closeInventory();
paint();
});
guiManager.showGUI(event.player, gui);
});
// kit price
setButton(1, 6, GuiUtils.createButtonItem(CompatibleMaterial.SUNFLOWER,
plugin.getLocale().getMessage("interface.kitsell.price").getMessage(),
plugin.getLocale().getMessage("interface.kitsell.pricelore")
.processPlaceholder("onoff",
kit.getPrice() != 0 ? plugin.getLocale().getMessage("interface.kitsell.priceon")
.processPlaceholder("price", kit.getPrice()).getMessage()
: plugin.getLocale().getMessage("interface.kitsell.priceoff").getMessage()
).getMessage().split("\\|")),
event -> {
if (!EconomyManager.isEnabled()) {
plugin.getLocale().getMessage("interface.kitsell.pricenoeco").sendPrefixedMessage(event.player);
return;
}
AnvilGui gui = new AnvilGui(event.player, this);
gui.setTitle(plugin.getLocale().getMessage("interface.kitsell.priceprompt").getMessage());
gui.setAction(aevent -> {
final String msg = gui.getInputText().trim();
double d = 0;
try {
d = Double.parseDouble(msg);
} catch (NumberFormatException e) {
}
if (d <= 0) {
plugin.getLocale().getMessage("interface.kitsell.pricenonumber").processPlaceholder("input", msg).sendPrefixedMessage(player);
} else {
if (kit.getLink() != null) {
kit.setLink(null);
plugin.getLocale().getMessage("interface.kitsell.pricenolink").sendPrefixedMessage(player);
}
kit.setPrice(d);
plugin.updateHologram(kit);
aevent.player.closeInventory();
paint();
}
});
guiManager.showGUI(event.player, gui);
});
}
}

View File

@ -0,0 +1,196 @@
package com.songoda.ultimatekits.gui;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.utils.ItemUtils;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class PreviewKitGui extends Gui {
private final Kit kit;
private final Player player;
private final UltimateKits plugin;
private final boolean buyable;
private final List<ItemStack> list;
private final boolean useGlassBorder = !Settings.DO_NOT_USE_GLASS_BORDERS.getBoolean();
static final Random rand = new Random();
public PreviewKitGui(UltimateKits plugin, Player player, Kit kit, Gui back) {
super(back);
this.kit = kit;
this.player = player;
this.plugin = plugin;
this.list = kit.getReadableContents(player, true, true, false);
this.buyable = (kit.getLink() != null || kit.getPrice() != 0);
setTitle(plugin.getLocale().getMessage("interface.preview.title")
.processPlaceholder("kit", kit.getTitle() != null ? TextUtils.formatText(kit.getTitle(), true) : kit.getShowableName()).getMessage());
int amt = 0;
for (ItemStack is : list) {
if (is.getAmount() > 64) {
int overflow = is.getAmount() % 64;
int stackamt = is.getAmount() / 64;
int num3 = 0;
while (num3 != stackamt) {
amt++;
num3++;
}
if (overflow != 0) {
amt++;
}
} else {
amt++;
}
}
int min = 0;
if (!useGlassBorder) {
min = 1;
if (!buyable) {
++min;
}
}
if (amt <= 7) {
setRows(3 - min);
} else if (amt <= 15) {
setRows(4 - min);
} else if (amt <= 23) {
setRows(5 - min);
} else {
setRows(6 - min);
}
if (!useGlassBorder) {
setDefaultItem(AIR);
} else {
// fill glass borders
Methods.fillGlass(this);
// exit button is only visible with a glass border
setButton(0, 8, GuiUtils.createButtonItem(Settings.EXIT_ICON.getMaterial(CompatibleMaterial.OAK_DOOR),
plugin.getLocale().getMessage("interface.button.exit").getMessage()),
event -> exit());
if (back != null) {
setButton(0, 0, GuiUtils.createButtonItem(ItemUtils.getCustomHead("3ebf907494a935e955bfcadab81beafb90fb9be49c7026ba97d798d5f1a23"),
plugin.getLocale().getMessage("interface.button.back").getMessage()),
event -> event.player.closeInventory());
}
}
// purchase button
if (buyable) {
setButton(rows - 1, 4, GuiUtils.createButtonItem(Settings.BUY_ICON.getMaterial(CompatibleMaterial.EMERALD),
plugin.getLocale().getMessage("interface.button.buynow").getMessage(),
getBuyLore()),
event -> {
exit();
kit.buy(event.player, event.manager);
});
}
// display the kit items here
Iterator<ItemStack> items = list.iterator();
int startRow = useGlassBorder ? 1 : 0;
int endRow = useGlassBorder ? rows - 2 : rows - 1;
int startCol = useGlassBorder ? 1 : 0;
int endCol = useGlassBorder ? 7 : 8;
for (int row = startRow; row <= endRow; ++row) {
for (int col = startCol; col <= endCol; ++col) {
ItemStack item;
if (!items.hasNext()) {
setItem(row, col, AIR);
} else if ((item = items.next()) == null
|| (Settings.DONT_PREVIEW_COMMANDS.getBoolean()
&& item.getType() == Material.PAPER
&& item.getItemMeta().hasDisplayName()
&& item.getItemMeta().getDisplayName().equals(plugin.getLocale().getMessage("general.type.command")))) {
setItem(row, col, AIR);
} else if (item.getAmount() <= 64) {
// display item
setItem(row, col, getKitItem(item));
} else {
// correct item amounts (up to three slots)
int itAmt = item.getAmount(), slots = 0;
for (; itAmt > 0 && slots < 3 && row <= endRow; ++row) {
for (; itAmt > 0 && slots < 3 && col <= endCol; ++col) {
setItem(row, col, getKitItem(item, Math.min(64, itAmt)));
itAmt -= 64;
++slots;
}
}
}
}
}
}
ItemStack getKitItem(ItemStack is) {
ItemMeta meta = is.getItemMeta();
List<String> newLore = new ArrayList<>();
if (meta != null && meta.hasLore()) {
for (String str : meta.getLore()) {
newLore.add(str.replace("{PLAYER}", player.getName()).replace("<PLAYER>", player.getName()));
}
meta.setLore(newLore);
}
is.setItemMeta(meta);
return is;
}
ItemStack getKitItem(ItemStack is, int amount) {
ItemStack is2 = is.clone();
ItemMeta meta = is2.getItemMeta();
List<String> newLore = new ArrayList<>();
if (meta != null && meta.hasLore()) {
for (String str : meta.getLore()) {
newLore.add(str.replace("{PLAYER}", player.getName()).replace("<PLAYER>", player.getName()));
}
}
meta.setLore(newLore);
is2.setItemMeta(meta);
is2.setAmount(amount);
return is;
}
List<String> getBuyLore() {
ArrayList<String> lore = new ArrayList<>();
if (kit.hasPermission(player) && Settings.KITS_FREE_WITH_PERMS.getBoolean()) {
lore.add(plugin.getLocale().getMessage("interface.button.clickeco")
.processPlaceholder("price", "0").getMessage());
if (player.isOp()) {
lore.add("");
lore.add(ChatColor.GRAY + "This is free because");
lore.add(ChatColor.GRAY + "you have perms for it.");
lore.add(ChatColor.GRAY + "Everyone else buys");
lore.add(ChatColor.GRAY + "this for " + ChatColor.GREEN + "$" + Methods.formatEconomy(kit.getPrice()) + ChatColor.GRAY + ".");
}
} else {
lore.add(plugin.getLocale().getMessage("interface.button.clickeco")
.processPlaceholder("price", Methods.formatEconomy(kit.getPrice())).getMessage());
}
if (kit.getDelay() != 0 && player.isOp()) {
lore.add("");
lore.add(ChatColor.GRAY + "You do not have a delay");
lore.add(ChatColor.GRAY + "because you have perms");
lore.add(ChatColor.GRAY + "to bypass the delay.");
}
return lore;
}
}

View File

@ -1,9 +1,9 @@
package com.songoda.ultimatekits.handlers;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@ -26,6 +26,9 @@ public class DisplayItemHandler {
public DisplayItemHandler(UltimateKits instance) {
this.instance = instance;
}
public void start() {
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(UltimateKits.getInstance(), this::displayItems, 30L, 30L);
}
@ -39,10 +42,11 @@ public class DisplayItemHandler {
location.add(0.5, 0, 0.5);
Kit kit = kitBlockData.getKit();
if (kit == null) return;
List<ItemStack> list = kit.getReadableContents(null, false, false, false);
if (list == null) return;
if (list.isEmpty()) return;
for (Entity e : location.getChunk().getEntities()) {
if (e.getType() != EntityType.DROPPED_ITEM
@ -60,11 +64,11 @@ public class DisplayItemHandler {
ItemStack is = list.get(inum - 1);
if (kitBlockData.isItemOverride()) {
if (kit.getDisplayItem() != null)
is = new ItemStack(kit.getDisplayItem());
is = kit.getDisplayItem().getItem();
}
ItemMeta meta = is.getItemMeta();
is.setAmount(1);
meta.setDisplayName(Methods.convertToInvisibleString(Integer.toString(inum)));
meta.setDisplayName(TextUtils.convertToInvisibleString(Integer.toString(inum)));
is.setItemMeta(meta);
i.setItemStack(is);
i.setPickupDelay(9999);
@ -75,12 +79,13 @@ public class DisplayItemHandler {
ItemStack is = list.get(0);
is.setAmount(1);
ItemMeta meta = is.getItemMeta();
meta.setDisplayName(Methods.convertToInvisibleString("0"));
meta.setDisplayName(TextUtils.convertFromInvisibleString("0"));
is.setItemMeta(meta);
Item item = location.getWorld().dropItem(location.add(0, 1, 0), list.get(0));
Vector vec = new Vector(0, 0, 0);
item.setVelocity(vec);
item.setPickupDelay(9999);
item.setMetadata("US_EXEMPT", new FixedMetadataValue(UltimateKits.getInstance(), true));
item.setMetadata("displayItem", new FixedMetadataValue(UltimateKits.getInstance(), true));
item.setMetadata("betterdrops_ignore", new FixedMetadataValue(UltimateKits.getInstance(), true));
}

View File

@ -1,8 +1,9 @@
package com.songoda.ultimatekits.handlers;
import com.songoda.core.compatibility.CompatibleParticleHandler;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@ -14,17 +15,25 @@ import java.util.Map;
public class ParticleHandler {
private final UltimateKits plugin;
int amt;
String typeName;
CompatibleParticleHandler.ParticleType type;
public ParticleHandler(UltimateKits plugin) {
this.plugin = plugin;
checkDefaults();
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(UltimateKits.getInstance(), this::applyParticles, 0, 10L);
}
public void start() {
amt = Settings.PARTICLE_AMOUNT.getInt() / 2;
typeName = Settings.PARTICLE_TYPE.getString();
type = CompatibleParticleHandler.ParticleType.getParticle(typeName);
if (type == null) {
type = CompatibleParticleHandler.ParticleType.SPELL_WITCH;
}
Bukkit.getServer().getScheduler().runTaskTimerAsynchronously(UltimateKits.getInstance(), this::applyParticles, 0, 5L);
}
private void applyParticles() {
int amt = plugin.getConfig().getInt("data.particlesettings.ammount");
String type = plugin.getConfig().getString("data.particlesettings.type");
Map<Location, KitBlockData> kitBlocks = plugin.getKitManager().getKitLocations();
for (KitBlockData kitBlockData : kitBlocks.values()) {
if (kitBlockData.getLocation().getWorld() == null || !kitBlockData.hasParticles()) continue;
@ -32,20 +41,8 @@ public class ParticleHandler {
Location location = kitBlockData.getLocation();
location.add(.5, 0, .5);
if (plugin.isServerVersionAtLeast(ServerVersion.V1_9))
location.getWorld().spawnParticle(org.bukkit.Particle.valueOf(type), location, amt, 0.25, 0.25, 0.25);
CompatibleParticleHandler.spawnParticles(type, location, amt, 0.25, 0.25, 0.25, 0.5);
}
}
private void checkDefaults() {
if (plugin.getConfig().getInt("data.particlesettings.ammount") == 0) {
plugin.getConfig().set("data.particlesettings.ammount", 25);
plugin.saveConfig();
}
if (plugin.getConfig().getString("data.particlesettings.type") != null) return;
plugin.getConfig().set("data.particlesettings.type", "SPELL_WITCH");
plugin.saveConfig();
}
}

View File

@ -1,176 +0,0 @@
package com.songoda.ultimatekits.hologram;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.kit.KitType;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public abstract class Hologram {
protected final UltimateKits instance;
Hologram(UltimateKits instance) {
this.instance = instance;
}
public void loadHolograms() {
Collection<KitBlockData> kitBlocks = instance.getKitManager().getKitLocations().values();
if (kitBlocks.size() == 0) return;
for (KitBlockData data : kitBlocks) {
if (data.getWorld() == null) continue;
add(data);
}
}
public void unloadHolograms() {
Collection<KitBlockData> kitBlocks = instance.getKitManager().getKitLocations().values();
if (kitBlocks.size() == 0) return;
for (KitBlockData data : kitBlocks) {
if (data.getWorld() == null) continue;
remove(data);
}
}
public void add(KitBlockData data) {
format(data, Action.ADD);
}
public void remove(KitBlockData data) {
format(data, Action.REMOVE);
}
public void remove(Kit kit) {
for (KitBlockData data : instance.getKitManager().getKitLocations().values()) {
if (data.getKit() != kit) continue;
remove(data);
}
}
public void update(KitBlockData data) {
format(data, Action.UPDATE);
}
public void update(Kit kit) {
for (KitBlockData data : instance.getKitManager().getKitLocations().values()) {
if (data.getKit() != kit) continue;
update(data);
}
}
private void format(KitBlockData data, Action action) {
if (data == null) return;
instance.getDataManager().updateBlockData(data);
KitType kitType = data.getType();
ArrayList<String> lines = new ArrayList<>();
List<String> order = instance.getConfig().getStringList("Main.Hologram Layout");
Kit kit = data.getKit();
for (String o : order) {
switch (o.toUpperCase()) {
case "{TITLE}":
String title = kit.getTitle();
if (title == null) {
lines.add(Methods.formatText("&5" + Methods.formatText(kit.getName(), true)));
} else {
lines.add(Methods.formatText("&5" + Methods.formatText(title)));
}
break;
case "{RIGHT-CLICK}":
if (kitType == KitType.CRATE) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.crate")
.getMessage()));
break;
}
if (kit.getLink() != null) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.buylink")
.getMessage()));
break;
}
if (kit.getPrice() != 0) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.buyeco")
.processPlaceholder("price", kit.getPrice() != 0
? Methods.formatEconomy(kit.getPrice())
: instance.getLocale().getMessage("general.type.free").getMessage())
.getMessage()));
}
break;
case "{LEFT-CLICK}":
if (kitType == KitType.CLAIM) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.daily")
.getMessage()));
break;
}
if (kit.getLink() == null && kit.getPrice() == 0) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.previewonly")
.getMessage()));
} else {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.preview")
.getMessage()));
}
break;
default:
lines.add(Methods.formatText(o));
break;
}
}
double multi = .25 * lines.size();
Location location = data.getLocation();
Block b = location.getBlock();
if (data.isDisplayingItems()) multi += .40;
if (b.getType() == Material.TRAPPED_CHEST
|| b.getType() == Material.CHEST
|| b.getType().name().contains("SIGN")
|| b.getType() == Material.ENDER_CHEST) multi -= .15;
location.add(0, multi, 0);
if (!data.showHologram()) {
remove(location);
return;
}
switch (action) {
case UPDATE:
update(location, lines);
break;
case ADD:
add(location, lines);
break;
case REMOVE:
remove(location);
break;
}
}
protected abstract void add(Location location, ArrayList<String> lines);
protected abstract void remove(Location location);
protected abstract void update(Location location, ArrayList<String> lines);
public enum Action {
UPDATE, ADD, REMOVE
}
}

View File

@ -1,56 +0,0 @@
package com.songoda.ultimatekits.hologram;
import com.gmail.filoghost.holographicdisplays.api.HologramsAPI;
import com.songoda.ultimatekits.UltimateKits;
import org.bukkit.Location;
import java.util.ArrayList;
public class HologramHolographicDisplays extends Hologram {
public HologramHolographicDisplays(UltimateKits instance) {
super(instance);
}
@Override
public void add(Location location, ArrayList<String> lines) {
fixLocation(location);
com.gmail.filoghost.holographicdisplays.api.Hologram hologram = HologramsAPI.createHologram(instance, location);
for (String line : lines) {
hologram.appendTextLine(line);
}
}
@Override
public void remove(Location location) {
fixLocation(location);
for (com.gmail.filoghost.holographicdisplays.api.Hologram hologram : HologramsAPI.getHolograms(instance)) {
if (hologram.getX() != location.getX()
|| hologram.getY() != location.getY()
|| hologram.getZ() != location.getZ()) continue;
hologram.delete();
}
}
@Override
public void update(Location location, ArrayList<String> lines) {
for (com.gmail.filoghost.holographicdisplays.api.Hologram hologram : HologramsAPI.getHolograms(instance)) {
if (hologram.getX() != location.getX()
|| hologram.getY() != location.getY()
|| hologram.getZ() != location.getZ()) continue;
fixLocation(location);
hologram.clearLines();
for (String line : lines) {
hologram.appendTextLine(line);
}
return;
}
add(location, lines);
}
private void fixLocation(Location location) {
location.add(.5, 1.3, .5);
}
}

View File

@ -1,5 +1,6 @@
package com.songoda.ultimatekits.key;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.utils.Methods;
@ -10,6 +11,7 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
public class Key {
@ -35,7 +37,7 @@ public class Key {
String kitName;
if (kit != null)
kitName = Methods.formatText(kit.getShowableName(), true);
kitName = TextUtils.formatText(kit.getShowableName(), true);
else
kitName = "Any";
@ -45,7 +47,7 @@ public class Key {
meta.addEnchant(Enchantment.DURABILITY, 1, true);
List<String> lore = new ArrayList<>();
lore.add(Methods.formatText("&e" + name + " &fKey"));
lore.add(ChatColor.YELLOW + name + " " + ChatColor.WHITE + "Key");
String desc1 = plugin.getLocale().getMessage("interface.key.description1")
.processPlaceholder("kit", kitName).getMessage();
@ -55,7 +57,7 @@ public class Key {
else
desc1 = desc1.replace("[", "").replace("]", "");
lore.add(Methods.formatText(desc1));
lore.add(desc1);
if (this.amt == -1)
lore.add(plugin.getLocale().getMessage("interface.key.description2").getMessage());
else

View File

@ -1,29 +1,34 @@
package com.songoda.ultimatekits.kit;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.CompatibleSound;
import com.songoda.core.configuration.Config;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiManager;
import com.songoda.core.hooks.EconomyManager;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.gui.GUIConfirmBuy;
import com.songoda.ultimatekits.gui.GUIDisplayKit;
import com.songoda.ultimatekits.gui.AnimatedKitGui;
import com.songoda.ultimatekits.gui.PreviewKitGui;
import com.songoda.ultimatekits.gui.ConfirmBuyGui;
import com.songoda.ultimatekits.key.Key;
import com.songoda.ultimatekits.kit.type.KitContentCommand;
import com.songoda.ultimatekits.kit.type.KitContentEconomy;
import com.songoda.ultimatekits.kit.type.KitContentItem;
import com.songoda.ultimatekits.tasks.CrateAnimateTask;
import com.songoda.ultimatekits.settings.Settings;
import com.songoda.ultimatekits.utils.ArmorType;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.gui.AbstractGUI;
import com.songoda.ultimatekits.utils.settings.Setting;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Created by songoda on 2/24/2017.
@ -36,13 +41,13 @@ public class Kit {
private String link, title;
private int delay;
private boolean hidden;
private Material displayItem;
private CompatibleMaterial displayItem;
private List<KitItem> contents;
private KitAnimation kitAnimation;
public Kit(String name, String title, String link, double price, Material displayItem, int delay, boolean hidden, List<KitItem> contents, KitAnimation kitAnimation) {
public Kit(String name, String title, String link, double price, CompatibleMaterial displayItem, int delay, boolean hidden, List<KitItem> contents, KitAnimation kitAnimation) {
this.name = name;
this.showableName = Methods.formatText(name, true);
this.showableName = TextUtils.formatText(name, true);
this.price = price;
this.link = link;
this.kitAnimation = kitAnimation;
@ -58,7 +63,7 @@ public class Kit {
this(name, null, null, 0, null, 0, false, new ArrayList<>(), KitAnimation.NONE);
}
public void buy(Player player) {
public void buy(Player player, GuiManager manager) {
if (hasPermission(player) && plugin.getConfig().getBoolean("Main.Allow Players To Receive Kits For Free If They Have Permission")) {
processGenericUse(player, false);
return;
@ -76,7 +81,7 @@ public class Kit {
player.sendMessage("");
player.closeInventory();
} else if (price != 0) {
new GUIConfirmBuy(plugin, player, this);
manager.showGUI(player, new ConfirmBuyGui(plugin, player, this, null));
} else {
UltimateKits.getInstance().getLocale().getMessage("command.general.noperms")
.sendPrefixedMessage(player);
@ -139,13 +144,13 @@ public class Kit {
}
public void processPurchaseUse(Player player) {
if (plugin.getEconomy() == null) return;
if (!EconomyManager.isEnabled()) return;
if (!player.hasPermission("ultimatekits.buy." + name)) {
UltimateKits.getInstance().getLocale().getMessage("command.general.noperms")
.sendPrefixedMessage(player);
return;
} else if (!plugin.getEconomy().hasBalance(player, price)) {
} else if (!EconomyManager.hasBalance(player, price)) {
plugin.getLocale().getMessage("event.claim.cannotafford")
.processPlaceholder("kit", showableName).sendPrefixedMessage(player);
return;
@ -161,13 +166,14 @@ public class Kit {
}
}
if (giveKit(player)) {
plugin.getEconomy().withdrawBalance(player, price);
EconomyManager.withdrawBalance(player, price);
if (delay != 0)
updateDelay(player); //updates delay on buy
plugin.getLocale().getMessage("event.claim.purchasesuccess")
.processPlaceholder("kit", showableName).sendPrefixedMessage(player);
}
plugin.getLocale().getMessage("event.claim.purchasesuccess")
.processPlaceholder("kit", showableName).sendPrefixedMessage(player);
}
public void processGenericUse(Player player, boolean forced) {
@ -188,7 +194,7 @@ public class Kit {
}
@SuppressWarnings("Duplicates")
public void display(Player player, AbstractGUI back) {
public void display(Player player, GuiManager manager, Gui back) {
if (!player.hasPermission("previewkit.use")
&& !player.hasPermission("previewkit." + name)
&& !player.hasPermission("ultimatekits.use")
@ -204,7 +210,7 @@ public class Kit {
plugin.getLocale().getMessage("event.preview.kit")
.processPlaceholder("kit", showableName).sendPrefixedMessage(player);
new GUIDisplayKit(plugin, back, player, this);
manager.showGUI(player, new PreviewKitGui(plugin, player, this, back));
}
public void saveKit(List<ItemStack> items) {
@ -216,7 +222,7 @@ public class Kit {
ItemMeta meta = is.getItemMeta();
List<String> newLore = new ArrayList<>();
for (String line : meta.getLore()) {
if (line.equals(Methods.convertToInvisibleString("----"))) break;
if (TextUtils.convertFromInvisibleString(line).equals("----")) break;
newLore.add(line);
}
meta.setLore(newLore);
@ -244,16 +250,17 @@ public class Kit {
public List<ItemStack> getReadableContents(Player player, boolean preview, boolean commands, boolean moveable) {
List<ItemStack> stacks = new ArrayList<>();
for (KitItem item : getContents()) {
if ((!item.getSerialized().startsWith("/") && !item.getSerialized().startsWith(plugin.getConfig().getString("Main.Currency Symbol"))) || commands) { //ToDO: I doubt this is correct.
if ((!item.getSerialized().startsWith("/") && !item.getSerialized().startsWith(Settings.CURRENCY_SYMBOL.getString())) || commands) { //ToDO: I doubt this is correct.
ItemStack stack = moveable ? item.getMoveableItem() : item.getItem();
if (preview) stack = item.getItemForDisplay();
if (stack == null) continue;
ItemStack fin = stack;
if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI") && stack.getItemMeta().getLore() != null) {
ArrayList<String> lore2 = new ArrayList<>();
ItemMeta meta2 = stack.getItemMeta();
for (String lor : stack.getItemMeta().getLore()) {
lor = PlaceholderAPI.setPlaceholders(player, lor.replace(" ", "_")).replace("_", " ");
lor = me.clip.placeholderapi.PlaceholderAPI.setPlaceholders(player, lor.replace(" ", "_")).replace("_", " ");
lore2.add(lor);
}
meta2.setLore(lore2);
@ -270,14 +277,12 @@ public class Kit {
}
private boolean giveKit(Player player, Key key) {
if (plugin.getConfig().getBoolean("Main.Prevent The Redeeming of a Kit When Inventory Is Full") && !hasRoom(player)) {
if (Settings.NO_REDEEM_WHEN_FULL.getBoolean() && !hasRoom(player)) {
plugin.getLocale().getMessage("event.claim.full").sendPrefixedMessage(player);
return false;
}
if (plugin.getConfig().getBoolean("Main.Sounds Enabled")
&& kitAnimation == KitAnimation.NONE
&& UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_12))
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 15.0F);
if (Settings.SOUNDS_ENABLED.getBoolean() && kitAnimation == KitAnimation.NONE)
CompatibleSound.ENTITY_PLAYER_LEVELUP.play(player, 0.6F, 15.0F);
List<KitItem> innerContents = new ArrayList<>(getContents());
int amt = innerContents.size();
@ -286,21 +291,20 @@ public class Kit {
if (amt != amtToGive || kitAnimation != KitAnimation.NONE)
Collections.shuffle(innerContents);
return generateRandomItem(innerContents, amtToGive, player);
return generateRandomItem(innerContents, amtToGive, player, -1);
}
private boolean generateRandomItem(List<KitItem> innerContents, int amtToGive, Player player) {
boolean chosenItem = false;
private boolean generateRandomItem(List<KitItem> innerContents, int amtToGive, Player player, int forceSelect) {
int canChoose = 0;
for (KitItem item : innerContents) {
if (amtToGive == 0) continue;
int ch = item.getChance() == 0 ? 100 : item.getChance();
if (amtToGive == 0) break;
int ch = canChoose++ == forceSelect || item.getChance() == 0 ? 100 : item.getChance();
double rand = Math.random() * 100;
if (rand - ch < 0 || ch == 100) {
chosenItem = true;
if (rand < ch || ch == 100) {
if (item.getContent() instanceof KitContentEconomy) {
try {
Methods.pay(player, ((KitContentEconomy) item.getContent()).getAmount());
EconomyManager.deposit(player, ((KitContentEconomy) item.getContent()).getAmount());
plugin.getLocale().getMessage("event.claim.eco")
.processPlaceholder("amt", Methods.formatEconomy(((KitContentEconomy) item.getContent()).getAmount()))
.sendPrefixedMessage(player);
@ -335,10 +339,12 @@ public class Kit {
amtToGive--;
if (kitAnimation != KitAnimation.NONE) {
new CrateAnimateTask(plugin, player, this, item.getItem());
// TODO: this is a very bad way to solve this problem.
// Giving the player kit rewards really should be done outside of the Kit class.
plugin.getGuiManager().showGUI(player, new AnimatedKitGui(plugin, player, this, item.getItem()));
return true;
} else {
if (Setting.AUTO_EQUIP_ARMOR.getBoolean() && ArmorType.equip(player, item.getItem())) continue;
if (Settings.AUTO_EQUIP_ARMOR.getBoolean() && ArmorType.equip(player, item.getItem())) continue;
Map<Integer, ItemStack> overfilled = player.getInventory().addItem(item.getItem());
for (ItemStack item2 : overfilled.values()) {
@ -348,25 +354,28 @@ public class Kit {
}
}
if (!chosenItem) generateRandomItem(innerContents, amtToGive, player);
if (amtToGive != 0 && canChoose != 0 && forceSelect == -1) {
return generateRandomItem(innerContents, amtToGive, player, (int) (Math.random() * canChoose));
} else if (amtToGive != 0) {
return false;
}
player.updateInventory();
return true;
}
public void updateDelay(Player player) {
plugin.getDataFile().getConfig().set("Kits." + name + ".delays." + player.getUniqueId().toString(), System.currentTimeMillis());
plugin.getDataFile().set("Kits." + name + ".delays." + player.getUniqueId().toString(), System.currentTimeMillis());
}
public Long getNextUse(Player player) {
String configSectionPlayer = "Kits." + name + ".delays." + player.getUniqueId().toString();
FileConfiguration config = plugin.getDataFile().getConfig();
Config config = plugin.getDataFile();
if (!config.contains(configSectionPlayer)) {
return 0L;
} else if (this.delay == -1) return -1L;
long last = config.getLong(configSectionPlayer);
long delay = (long) this.delay * 1000;
@ -428,12 +437,12 @@ public class Kit {
return showableName;
}
public Material getDisplayItem() {
public CompatibleMaterial getDisplayItem() {
return displayItem;
}
public void setDisplayItem(Material displayItem) {
this.displayItem = displayItem;
public void setDisplayItem(ItemStack item) {
this.displayItem = item != null ? CompatibleMaterial.getMaterial(item) : null;
}
public boolean isHidden() {

View File

@ -32,8 +32,7 @@ public class KitBlockData {
setHasParticles(false);
UltimateKits.getInstance().getDisplayItemHandler().displayItem(this);
if (UltimateKits.getInstance().getHologram() != null)
UltimateKits.getInstance().getHologram().remove(this);
UltimateKits.getInstance().removeHologram(this);
UltimateKits.getInstance().getDataManager().updateBlockData(this);
}
@ -45,6 +44,10 @@ public class KitBlockData {
return location.clone();
}
public boolean isInLoadedChunk() {
return location != null && location.getWorld() != null && location.getWorld().isChunkLoaded(((int) location.getX()) >> 4, ((int) location.getZ()) >> 4);
}
public int getX() {
return location.getBlockX();
}

View File

@ -1,14 +1,13 @@
package com.songoda.ultimatekits.kit;
import com.songoda.core.utils.TextUtils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.type.KitContent;
import com.songoda.ultimatekits.kit.type.KitContentCommand;
import com.songoda.ultimatekits.kit.type.KitContentEconomy;
import com.songoda.ultimatekits.kit.type.KitContentItem;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.settings.Setting;
import com.songoda.ultimatekits.settings.Settings;
import org.apache.commons.lang.WordUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
@ -56,13 +55,13 @@ public class KitItem {
}
private void processContent(String line, ItemStack item) {
if (line.startsWith(Setting.CURRENCY_SYMBOL.getString())) {
if (line.startsWith(Settings.CURRENCY_SYMBOL.getString())) {
this.content = new KitContentEconomy(Double.parseDouble(line.substring(1).trim()));
} else if (line.startsWith("/")) {
this.content = new KitContentCommand(line.substring(1));
} else {
ItemStack itemStack = item == null ? UltimateKits.getInstance().getItemSerializer().deserializeItemStackFromJson(line) : item;
this.content = new KitContentItem(itemStack);
this.content = itemStack != null ? new KitContentItem(itemStack) : null;
}
}
@ -154,47 +153,51 @@ public class KitItem {
}
public ItemStack getMoveableItem() {
if(content == null) return null;
ItemStack item = content.getItemForDisplay();
ItemMeta meta = item.getItemMeta();
if (chance != 0 || displayItem != null || displayName != null || displayLore != null) {
String capitalizedName = meta.hasDisplayName() ? meta.getDisplayName() :
WordUtils.capitalize(item.getType().toString().toLowerCase().replace("_", " "));
if (capitalizedName.contains(Methods.convertToInvisibleString(";faqe")))
capitalizedName = meta.getDisplayName().split(Methods.convertToInvisibleString(";faqe"))[1];
meta.setDisplayName(Methods.convertToInvisibleString(compileOptions() + ";faqe") + capitalizedName);
if (capitalizedName.contains(TextUtils.convertToInvisibleString(";faqe")))
capitalizedName = meta.getDisplayName().split(TextUtils.convertToInvisibleString(";faqe"))[1];
meta.setDisplayName(TextUtils.convertToInvisibleString(compileOptions() + ";faqe") + capitalizedName);
}
item.setItemMeta(meta);
return item;
}
public ItemStack getItemForDisplay() {
if(content == null) return null;
ItemStack item = content.getItemForDisplay();
ItemMeta meta = item.getItemMeta();
if (displayItem != null) {
item.setType(displayItem);
}
if (displayName != null) {
meta.setDisplayName(Methods.formatText(displayName));
}
if (displayLore != null) {
meta.setLore(Arrays.asList(Methods.formatText(displayLore)));
}
if (UltimateKits.getInstance().getConfig().getBoolean("Main.Display Chance In Preview")) {
ArrayDeque<String> lore;
if (meta.hasLore()) {
lore = new ArrayDeque<>(meta.getLore());
} else {
lore = new ArrayDeque<>();
if(meta != null) {
if (displayName != null) {
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', displayName));
}
if (displayLore != null) {
meta.setLore(Arrays.asList(ChatColor.translateAlternateColorCodes('&', displayLore)));
}
if (lore.size() != 0) lore.addFirst("");
lore.addFirst(Methods.formatText("&7" + UltimateKits.getInstance().getLocale().getMessage("general.type.chance") + ": &6" + (chance == 0 ? 100 : chance) + "%"));
meta.setLore(new ArrayList<>(lore));
}
if (UltimateKits.getInstance().getConfig().getBoolean("Main.Display Chance In Preview")) {
ArrayDeque<String> lore;
if (meta.hasLore()) {
lore = new ArrayDeque<>(meta.getLore());
} else {
lore = new ArrayDeque<>();
}
item.setItemMeta(meta);
if (!lore.isEmpty()) lore.addFirst("");
lore.addFirst(ChatColor.GRAY.toString() + UltimateKits.getInstance().getLocale().getMessage("general.type.chance") + ": " + ChatColor.GOLD + (chance == 0 ? 100 : chance) + "%");
meta.setLore(new ArrayList<>(lore));
}
item.setItemMeta(meta);
}
return item;
}

View File

@ -7,7 +7,7 @@ import java.util.*;
public final class KitManager {
private Map<Location, KitBlockData> kitsAtLocations = new HashMap<>();
private final Map<Location, KitBlockData> kitsAtLocations = new HashMap<>();
private final List<Kit> registeredKits = new LinkedList<>();
public boolean addKit(Kit kit) {
@ -38,8 +38,6 @@ public final class KitManager {
public KitBlockData addKitToLocation(Kit kit, Location location, KitType type, boolean hologram, boolean particles, boolean items, boolean itemOverride) {
KitBlockData data = new KitBlockData(kit, location, type, hologram, particles, items, itemOverride);
kitsAtLocations.put(roundLocation(location), data);
if (UltimateKits.getInstance().getHologram() != null)
UltimateKits.getInstance().getHologram().update(data);
return data;
}
@ -73,7 +71,8 @@ public final class KitManager {
}
public void setKitLocations(Map<Location, KitBlockData> kits) {
kitsAtLocations = kits;
kitsAtLocations.clear();
kitsAtLocations.putAll(kits);
}
public void clearKits() {

View File

@ -1,3 +1,17 @@
package com.songoda.ultimatekits.kit;
public enum KitType {PREVIEW, CRATE, CLAIM}
public enum KitType {
PREVIEW, CRATE, CLAIM;
public static KitType getKitType(String search) {
if (search != null) {
for (KitType t : values()) {
if (t.name().equalsIgnoreCase(search)) {
return t;
}
}
}
return null;
}
}

View File

@ -1,16 +1,16 @@
package com.songoda.ultimatekits.kit.type;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import org.bukkit.ChatColor;
public class KitContentCommand implements KitContent {
private String command; // Stored like "eco give <player> 100"
private final String command; // Stored like "eco give <player> 100"
public KitContentCommand(String command) {
this.command = command;
@ -32,7 +32,7 @@ public class KitContentCommand implements KitContent {
ArrayList<String> lore = new ArrayList<>();
int index = 0;
while (index < command.length()) {
lore.add(Methods.formatText("&a" + (index == 0 ? "/" : "") + "&a" + command.substring(index, Math.min(index + 30, command.length()))));
lore.add(ChatColor.GREEN + (index == 0 ? "/" : "") + ChatColor.GREEN + command.substring(index, Math.min(index + 30, command.length())));
index += 30;
}
meta.setLore(lore);

View File

@ -1,16 +1,16 @@
package com.songoda.ultimatekits.kit.type;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import org.bukkit.ChatColor;
public class KitContentEconomy implements KitContent {
private double amount;
private final double amount;
public KitContentEconomy(double amount) {
this.amount = amount;
@ -34,7 +34,7 @@ public class KitContentEconomy implements KitContent {
int index = 0;
while (index < String.valueOf(amount).length()) {
lore.add(Methods.formatText("&a" + (index == 0 ? UltimateKits.getInstance().getConfig().getString("Main.Currency Symbol") : "") + "&a" + String.valueOf(amount).substring(index, Math.min(index + 30, String.valueOf(amount).length()))));
lore.add(ChatColor.GREEN + (index == 0 ? UltimateKits.getInstance().getConfig().getString("Main.Currency Symbol") : "") + ChatColor.GREEN + String.valueOf(amount).substring(index, Math.min(index + 30, String.valueOf(amount).length())));
index += 30;
}
meta.setLore(lore);

View File

@ -5,7 +5,7 @@ import org.bukkit.inventory.ItemStack;
public class KitContentItem implements KitContent {
private ItemStack itemStack;
private final ItemStack itemStack;
private String serialized = null;

View File

@ -1,14 +1,18 @@
package com.songoda.ultimatekits.listeners;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.key.Key;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
/**
* Created by songoda on 2/24/2017.
@ -28,8 +32,7 @@ public class BlockListeners implements Listener {
if (kitBlockData == null) return;
Kit kit = kitBlockData.getKit();
if (instance.getHologram() != null)
instance.getHologram().remove(kitBlockData);
instance.removeHologram(kitBlockData);
instance.getKitManager().removeKitFromLocation(block.getLocation());
@ -44,5 +47,11 @@ public class BlockListeners implements Listener {
if (kitBlockData != null) {
e.setCancelled(true);
}
ItemStack item = e.getItemInHand();
if (item.getType() == Material.TRIPWIRE_HOOK && item.hasItemMeta() && item.getItemMeta().hasDisplayName()) {
Key key = instance.getKeyManager().getKey(ChatColor.stripColor(item.getItemMeta().getLore().get(0)).replace(" Key", ""));
if (key != null)
e.setCancelled(true);
}
}
}

View File

@ -1,12 +1,13 @@
package com.songoda.ultimatekits.listeners;
import com.songoda.core.compatibility.ServerVersion;
import com.songoda.core.gui.GuiManager;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.gui.GUIBlockEditor;
import com.songoda.ultimatekits.gui.BlockEditorGui;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.kit.KitType;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
@ -20,14 +21,16 @@ import org.bukkit.inventory.InventoryHolder;
public class InteractListeners implements Listener {
private final UltimateKits plugin;
private final GuiManager guiManager;
public InteractListeners(UltimateKits plugin) {
public InteractListeners(UltimateKits plugin, GuiManager guiManager) {
this.plugin = plugin;
this.guiManager = guiManager;
}
@EventHandler
public void onBlockInteract(PlayerInteractEvent event) {
if (plugin.isServerVersionAtLeast(ServerVersion.V1_9))
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9))
if (event.getHand() == EquipmentSlot.OFF_HAND) return;
Block block = event.getClickedBlock();
@ -66,16 +69,16 @@ public class InteractListeners implements Listener {
Methods.makeReadable(time)).sendPrefixedMessage(player);
}
} else if (kit.getLink() != null || kit.getPrice() != 0) {
kit.buy(player);
kit.buy(player, guiManager);
} else {
kit.display(player, null);
kit.display(player, guiManager, null);
}
} else if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (block.getState() instanceof InventoryHolder || block.getType() == Material.ENDER_CHEST) {
event.setCancelled(true);
}
if (player.isSneaking() && player.hasPermission("ultimatekits.admin")) {
new GUIBlockEditor(plugin, player, block.getLocation());
guiManager.showGUI(player, new BlockEditorGui(plugin, kitBlockData));
return;
}
if (player.getItemInHand().getType() == Material.TRIPWIRE_HOOK) {
@ -83,7 +86,7 @@ public class InteractListeners implements Listener {
kit.processKeyUse(player);
return;
}
kit.display(player, null);
kit.display(player, guiManager, null);
}
}

View File

@ -0,0 +1,97 @@
package com.songoda.ultimatekits.settings;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.configuration.Config;
import com.songoda.core.configuration.ConfigSetting;
import com.songoda.core.hooks.EconomyManager;
import com.songoda.ultimatekits.UltimateKits;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Settings {
static final Config config = UltimateKits.getInstance().getCoreConfig();
public static final ConfigSetting ONLY_SHOW_KITS_WITH_PERMS = new ConfigSetting(config, "Main.Only Show Players Kits They Have Permission To Use", false);
public static final ConfigSetting KITS_FREE_WITH_PERMS = new ConfigSetting(config, "Main.Allow Players To Receive Kits For Free If They Have Permission", true);
public static final ConfigSetting DONT_PREVIEW_COMMANDS = new ConfigSetting(config, "Main.Dont Preview Commands In Kits", false);
public static final ConfigSetting HOLOGRAM_LAYOUT = new ConfigSetting(config, "Main.Hologram Layout", Arrays.asList("{TITLE}", "{LEFT-CLICK}", "{RIGHT-CLICK}"));
public static final ConfigSetting SOUNDS_ENABLED = new ConfigSetting(config, "Main.Sounds Enabled", true);
public static final ConfigSetting NO_REDEEM_WHEN_FULL = new ConfigSetting(config, "Main.Prevent The Redeeming of a Kit When Inventory Is Full", true);
public static final ConfigSetting AUTO_EQUIP_ARMOR = new ConfigSetting(config, "Main.Automatically Equip Armor Given From a Kit", true);
public static final ConfigSetting AUTO_EQUIP_ARMOR_ROULETTE = new ConfigSetting(config, "Main.Automatically Equip Armor Given From a Kit with the Roulette Animation", false);
public static final ConfigSetting CHANCE_IN_PREVIEW = new ConfigSetting(config, "Main.Display Chance In Preview", true);
public static final ConfigSetting CURRENCY_SYMBOL = new ConfigSetting(config, "Main.Currency Symbol", "$");
public static final ConfigSetting ECONOMY_PLUGIN = new ConfigSetting(config, "Main.Economy", EconomyManager.getEconomy() == null ? "Vault" : EconomyManager.getEconomy().getName(),
"Which economy plugin should be used?",
"Supported plugins you have installed: \"" + EconomyManager.getManager().getRegisteredPlugins().stream().collect(Collectors.joining("\", \"")) + "\".");
public static final ConfigSetting EXIT_ICON = new ConfigSetting(config, "Interfaces.Exit Icon", "OAK_DOOR");
public static final ConfigSetting BUY_ICON = new ConfigSetting(config, "Interfaces.Buy Icon", "EMERALD");
public static final ConfigSetting GLASS_TYPE_1 = new ConfigSetting(config, "Interfaces.Glass Type 1", 7);
public static final ConfigSetting GLASS_TYPE_2 = new ConfigSetting(config, "Interfaces.Glass Type 2", 11);
public static final ConfigSetting GLASS_TYPE_3 = new ConfigSetting(config, "Interfaces.Glass Type 3", 3);
public static final ConfigSetting RAINBOW = new ConfigSetting(config, "Interfaces.Replace Glass Type 1 With Rainbow Glass", false);
public static final ConfigSetting DO_NOT_USE_GLASS_BORDERS = new ConfigSetting(config, "Interfaces.Do Not Use Glass Borders", false);
public static final ConfigSetting LANGUGE_MODE = new ConfigSetting(config, "System.Language Mode", "en_US",
"The enabled language file.",
"More language files (if available) can be found in the plugins data folder.");
public static final ConfigSetting MYSQL_ENABLED = new ConfigSetting(config, "MySQL.Enabled", false, "Set to 'true' to use MySQL for data storage.");
public static final ConfigSetting MYSQL_HOSTNAME = new ConfigSetting(config, "MySQL.Hostname", "localhost");
public static final ConfigSetting MYSQL_PORT = new ConfigSetting(config, "MySQL.Port", 3306);
public static final ConfigSetting MYSQL_DATABASE = new ConfigSetting(config, "MySQL.Database", "your-database");
public static final ConfigSetting MYSQL_USERNAME = new ConfigSetting(config, "MySQL.Username", "user");
public static final ConfigSetting MYSQL_PASSWORD = new ConfigSetting(config, "MySQL.Password", "pass");
public static final ConfigSetting MYSQL_USE_SSL = new ConfigSetting(config, "MySQL.Use SSL", false);
public static final ConfigSetting PARTICLE_AMOUNT = new ConfigSetting(config, "data.particlesettings.amount", 25);
public static final ConfigSetting PARTICLE_TYPE = new ConfigSetting(config, "data.particlesettings.type", "SPELL_WITCH");
/**
* In order to set dynamic economy comment correctly, this needs to be
* called after EconomyManager load
*/
public static void setupConfig() {
config
.setDefaultComment("Main", "General settings and options.")
.setDefaultComment("Interfaces",
"These settings allow you to alter the way interfaces look.",
"They are used in GUI's to make patterns, change them up then open up a",
"# GUI to see how it works.")
.setDefaultComment("System", "System related settings.");
config.load();
config.setAutoremove(true).setAutosave(true);
// convert glass pane settings
int color;
if ((color = GLASS_TYPE_1.getInt(-1)) != -1) {
config.set(GLASS_TYPE_1.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
}
if ((color = GLASS_TYPE_2.getInt(-1)) != -1) {
config.set(GLASS_TYPE_2.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
}
if ((color = GLASS_TYPE_3.getInt(-1)) != -1) {
config.set(GLASS_TYPE_3.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
}
// convert economy settings
if (config.getBoolean("Economy.Use Vault Economy") && EconomyManager.getManager().isEnabled("Vault")) {
config.set("Main.Economy", "Vault");
} else if (config.getBoolean("Economy.Use Reserve Economy") && EconomyManager.getManager().isEnabled("Reserve")) {
config.set("Main.Economy", "Reserve");
} else if (config.getBoolean("Economy.Use Player Points Economy") && EconomyManager.getManager().isEnabled("PlayerPoints")) {
config.set("Main.Economy", "PlayerPoints");
}
// spelling correction
if (config.contains("data.particlesettings.ammount")) {
config.set("data.particlesettings.amount", config.getInt("data.particlesettings.ammount"));
}
config.saveChanges();
}
}

View File

@ -1,141 +0,0 @@
package com.songoda.ultimatekits.tasks;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitItem;
import com.songoda.ultimatekits.utils.ArmorType;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import com.songoda.ultimatekits.utils.settings.Setting;
import org.apache.commons.lang.WordUtils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
public class CrateAnimateTask extends BukkitRunnable {
private final UltimateKits plugin;
private final Player player;
private final Inventory inventory;
private final ArrayDeque<KitItem> items;
private final ItemStack give;
private CrateAnimateTask instance;
private boolean slow = false;
private boolean finish = false;
private boolean done = false;
private int num = 0;
private Listener listener;
public CrateAnimateTask(UltimateKits plugin, Player player, Kit kit, ItemStack give) {
this.plugin = plugin;
this.player = player;
this.give = give;
this.inventory = Bukkit.createInventory(null, 27, Methods.formatText(kit.getShowableName()));
List<KitItem> items = kit.getContents();
Collections.shuffle(items);
this.items = new ArrayDeque<>(items);
while (this.items.size() < 10) {
for (KitItem item : items) {
if (this.items.size() < 10)
this.items.addLast(item);
}
}
this.listener = new Listener() {
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player) || event.getWhoClicked() != player) return;
event.setCancelled(true);
}
};
Bukkit.getPluginManager().registerEvents(listener, UltimateKits.getInstance());
start();
}
private void start() {
if (instance == null) instance = this;
instance.runTaskTimer(plugin, 0, 3);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
slow = true;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> finish = true, 20);
}, 60);
}
@Override
public void run() {
if (slow && num == 1) {
num = 0;
return;
}
num = slow ? 1 : 0;
for (int i = 0; i < 27; i++) {
inventory.setItem(i, Methods.getGlass(true, 0));
}
for (int i = 9; i < 18; i++) {
inventory.setItem(i, new ItemStack(plugin.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? Material.GRAY_STAINED_GLASS_PANE : Material.valueOf("STAINED_GLASS_PANE")));
}
inventory.setItem(4, new ItemStack(Material.TRIPWIRE_HOOK));
inventory.setItem(22, new ItemStack(Material.TRIPWIRE_HOOK));
if (!done) {
player.playSound(player.getLocation(), plugin.getInstance().isServerVersionAtLeast(ServerVersion.V1_9) ? Sound.UI_BUTTON_CLICK : Sound.valueOf("CLICK"), 5f, 5f);
this.items.addFirst(this.items.getLast());
this.items.removeLast();
}
List<KitItem> items = new ArrayList<>(this.items);
for (int i = 0; i < 9; i++) {
inventory.setItem(9 + i, items.get(i).getItem());
}
if (finish) {
if (inventory.getItem(13).isSimilar(give)) {
if (!done) {
if (!Setting.AUTO_EQUIP_ARMOR_ROULETTE.getBoolean()
|| !ArmorType.equip(player, give)) {
Map<Integer, ItemStack> overfilled = player.getInventory().addItem(give);
for (ItemStack item2 : overfilled.values()) {
player.getWorld().dropItemNaturally(player.getLocation(), item2);
}
}
player.playSound(player.getLocation(), UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_9) ? Sound.ENTITY_PLAYER_LEVELUP : Sound.valueOf("LEVEL_UP"), 10f, 10f);
plugin.getLocale().getMessage("event.create.won")
.processPlaceholder("item", WordUtils.capitalize(give.getType().name().toLowerCase().replace("_", " ")))
.sendPrefixedMessage(player);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, this::finish, 50);
}
done = true;
}
}
player.openInventory(inventory);
}
private void finish() {
instance.cancel();
HandlerList.unregisterAll(listener);
listener = null;
player.closeInventory();
}
}

View File

@ -1,67 +0,0 @@
package com.songoda.ultimatekits.utils;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
/**
* ConfigWrapper made by @clip
*/
public class ConfigWrapper {
private final JavaPlugin plugin;
private final String folderName, fileName;
private FileConfiguration config;
private File configFile;
public ConfigWrapper(final JavaPlugin instance, final String folderName, final String fileName) {
this.plugin = instance;
this.folderName = folderName;
this.fileName = fileName;
}
public void createNewFile(final String message, final String header) {
reloadConfig();
saveConfig();
loadConfig(header);
if (message != null) {
plugin.getLogger().info(message);
}
}
public FileConfiguration getConfig() {
if (config == null) {
reloadConfig();
}
return config;
}
public void loadConfig(final String header) {
config.options().header(header);
config.options().copyDefaults(true);
saveConfig();
}
public void reloadConfig() {
if (configFile == null) {
configFile = new File(plugin.getDataFolder() + folderName, fileName);
}
config = YamlConfiguration.loadConfiguration(configFile);
}
public void saveConfig() {
if (config == null || configFile == null) {
return;
}
try {
getConfig().save(configFile);
} catch (final IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, ex);
}
}
}

View File

@ -1,6 +1,6 @@
package com.songoda.ultimatekits.utils;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.core.compatibility.ServerVersion;
import org.bukkit.Bukkit;
import org.bukkit.inventory.ItemStack;
@ -38,9 +38,9 @@ public class ItemSerializer {
*/
public ItemSerializer() throws NoSuchMethodException, SecurityException, ClassNotFoundException {
methodParseString = classMojangsonParser.getMethod("parse", String.class);
if (UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_13))
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13))
methodToItemStack = classItemStack.getMethod("a", classNBTTagCompound);
else if (UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_11))
else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11))
constructorItemStack = classItemStack.getConstructor(classNBTTagCompound);
else
methodCreateStack = classItemStack.getMethod("createStack", classNBTTagCompound);
@ -74,9 +74,9 @@ public class ItemSerializer {
Object nbtTagCompound = methodParseString.invoke(null, jsonString);
Object citemStack;
if (UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_13))
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13))
citemStack = methodToItemStack.invoke(null, nbtTagCompound);
else if (UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_11))
else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11))
citemStack = constructorItemStack.newInstance(nbtTagCompound);
else
citemStack = methodCreateStack.invoke(null, nbtTagCompound);

View File

@ -1,64 +1,30 @@
package com.songoda.ultimatekits.utils;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiUtils;
import com.songoda.ultimatekits.UltimateKits;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.*;
import com.songoda.ultimatekits.settings.Settings;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.RegisteredServiceProvider;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* Created by songoda on 2/24/2017.
*/
public class Methods {
public static ItemStack getGlass() {
UltimateKits instance = UltimateKits.getInstance();
return Methods.getGlass(instance.getConfig().getBoolean("Interfaces.Replace Glass Type 1 With Rainbow Glass"), instance.getConfig().getInt("Interfaces.Glass Type 1"));
}
public static ItemStack getBackgroundGlass(boolean type) {
UltimateKits instance = UltimateKits.getInstance();
if (type)
return getGlass(false, instance.getConfig().getInt("Interfaces.Glass Type 2"));
else
return getGlass(false, instance.getConfig().getInt("Interfaces.Glass Type 3"));
}
/**
* Creates a glass itemstack
*
* @param rainbow Whether or not to assign a random color to the glass.
* @param type If rainbow is false, the glass color.
* @return A glass itemstack conforming to the params.
*/
public static ItemStack getGlass(boolean rainbow, int type) {
int randomNum = 1 + (int) (Math.random() * 6);
ItemStack glass;
if (rainbow) {
glass = new ItemStack(UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ?
Material.LEGACY_STAINED_GLASS_PANE : Material.valueOf("STAINED_GLASS_PANE"), 1, (short) randomNum);
} else {
glass = new ItemStack(UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ?
Material.LEGACY_STAINED_GLASS_PANE : Material.valueOf("STAINED_GLASS_PANE"), 1, (short) type);
}
ItemMeta glassmeta = glass.getItemMeta();
glassmeta.setDisplayName("§l");
glass.setItemMeta(glassmeta);
return glass;
}
static final Random rand = new Random();
public static boolean canGiveKit(Player player) {
if (player.hasPermission("ultimatekits.cangive")) return true;
@ -67,22 +33,6 @@ public class Methods {
return false;
}
public static boolean pay(Player p, double amount) {
if (UltimateKits.getInstance().getServer().getPluginManager().getPlugin("Vault") == null) return false;
RegisteredServiceProvider<Economy> rsp = UltimateKits.getInstance().getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
net.milkbowl.vault.economy.Economy econ = rsp.getProvider();
econ.depositPlayer(p, amount);
return true;
}
public static String getKitFromLocation(Location location) {
return UltimateKits.getInstance().getConfig().getString("data.block." + serializeLocation(location));
}
/**
* Serializes the location of the block specified.
*
@ -138,40 +88,6 @@ public class Methods {
return location;
}
public static String convertToInvisibleString(String s) {
if (s == null || s.equals(""))
return "";
StringBuilder hidden = new StringBuilder();
for (char c : s.toCharArray()) hidden.append(ChatColor.COLOR_CHAR + "").append(c);
return hidden.toString();
}
public static String formatTitle(String text) {
if (text == null || text.equals(""))
return "";
if (!UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_9)) {
if (text.length() > 31)
text = text.substring(0, 29) + "...";
}
text = formatText(text);
return text;
}
public static String formatText(String text) {
if (text == null || text.equals(""))
return "";
return formatText(text, false);
}
public static String formatText(String text, boolean cap) {
if (text == null || text.equals(""))
return "";
if (cap)
text = text.substring(0, 1).toUpperCase() + text.substring(1);
return ChatColor.translateAlternateColorCodes('&', text);
}
public static String makeReadable(Long time) {
if (time == null)
return "";
@ -194,7 +110,6 @@ public class Methods {
return sb.toString().trim();
}
public static long parseTime(String input) {
long result = 0;
StringBuilder number = new StringBuilder();
@ -224,7 +139,6 @@ public class Methods {
return 0;
}
/**
* Formats the specified double into the Economy format specified in the Arconix config.
*
@ -259,49 +173,30 @@ public class Methods {
return s.matches("[-+]?\\d*\\.?\\d+");
}
public static void fillGlass(Gui gui) {
/**
* Fills the provided inventory with glass panes of the specified color type.
*
* @param i The inventory to fill.
*/
public static void fillGlass(Inventory i) {
ItemStack glass = getGlass();
ItemMeta glassMeta = glass.getItemMeta();
glassMeta.setDisplayName("§5");
glass.setItemMeta(glassMeta);
int nu = 0;
while (nu != 27) {
i.setItem(nu, glass);
nu++;
// fill center with glass
if (Settings.RAINBOW.getBoolean()) {
for (int row = 0; row < gui.getRows(); ++row) {
for (int col = row == 1 ? 2 : 3; col < (row == 1 ? 7 : 6); ++col) {
gui.setItem(row, col, GuiUtils.getBorderItem(CompatibleMaterial.getGlassPaneColor(rand.nextInt(16))));
}
}
} else {
gui.setDefaultItem(GuiUtils.getBorderItem(Settings.GLASS_TYPE_1.getMaterial(CompatibleMaterial.GRAY_STAINED_GLASS_PANE)));
}
// decorate the edges
ItemStack glass2 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_2.getMaterial(CompatibleMaterial.BLUE_STAINED_GLASS_PANE));
ItemStack glass3 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_3.getMaterial(CompatibleMaterial.LIGHT_BLUE_STAINED_GLASS_PANE));
// edges will be type 3
GuiUtils.mirrorFill(gui, 0, 2, true, true, glass3);
GuiUtils.mirrorFill(gui, 1, 1, false, true, glass3);
// decorate corners with type 2
GuiUtils.mirrorFill(gui, 0, 0, true, true, glass2);
GuiUtils.mirrorFill(gui, 1, 0, true, true, glass2);
GuiUtils.mirrorFill(gui, 0, 1, true, true, glass2);
}
/**
* Adds the specified texture to the supplied head itemstack.
*
* @param item A head to apply the texture to.
* @param headURL The URL of the texture to apply.
* @return The head with the textrue.
*/
public static ItemStack addTexture(ItemStack item, String headURL) {
SkullMeta meta = (SkullMeta) item.getItemMeta();
GameProfile profile = new GameProfile(UUID.randomUUID(), null);
byte[] encodedData = Base64.getEncoder().encode(String.format("{textures:{SKIN:{url:\"%s\"}}}", new Object[]{headURL}).getBytes());
profile.getProperties().put("textures", new Property("textures", new String(encodedData)));
Field profileField;
try {
profileField = meta.getClass().getDeclaredField("profile");
profileField.setAccessible(true);
profileField.set(meta, profile);
} catch (Exception e) {
e.printStackTrace();
}
item.setItemMeta(meta);
return item;
}
}
}

View File

@ -1,695 +0,0 @@
package com.songoda.ultimatekits.utils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {
static {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
// The plugin
private final Plugin plugin;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
*/
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JSONObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JSONObject data = new JSONObject();
data.put("serverUUID", serverUUID);
data.put("playerAmount", playerAmount);
data.put("onlineMode", onlineMode);
data.put("bukkitVersion", bukkitVersion);
data.put("javaVersion", javaVersion);
data.put("osName", osName);
data.put("osArch", osArch);
data.put("osVersion", osVersion);
data.put("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JSONObject data = getServerData();
JSONArray pluginData = new JSONArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
}
} catch (NoSuchFieldException ignored) { }
}
data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data.toString());
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JSONObject getRequestJsonObject() {
JSONObject chart = new JSONObject();
chart.put("chartId", chartId);
try {
JSONObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.put("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JSONObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JSONObject value = new JSONObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.put(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.put(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JSONArray categoryValues = new JSONArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.put(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
}

View File

@ -1,27 +0,0 @@
package com.songoda.ultimatekits.utils;
public enum ServerVersion {
UNKNOWN("unknown_server_version"),
V1_7("org.bukkit.craftbukkit.v1_7"),
V1_8("org.bukkit.craftbukkit.v1_8"),
V1_9("org.bukkit.craftbukkit.v1_9"),
V1_10("org.bukkit.craftbukkit.v1_10"),
V1_11("org.bukkit.craftbukkit.v1_11"),
V1_12("org.bukkit.craftbukkit.v1_12"),
V1_13("org.bukkit.craftbukkit.v1_13"),
V1_14("org.bukkit.craftbukkit.v1_14");
private final String packagePrefix;
private ServerVersion(String packagePrefix) {
this.packagePrefix = packagePrefix;
}
public static ServerVersion fromPackageName(String packageName) {
for (ServerVersion version : values())
if (packageName.startsWith(version.packagePrefix)) return version;
return ServerVersion.UNKNOWN;
}
}

View File

@ -1,289 +0,0 @@
package com.songoda.ultimatekits.utils.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.utils.version.NMSUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class AbstractAnvilGUI {
private static Class<?> BlockPositionClass;
private static Class<?> PacketPlayOutOpenWindowClass;
private static Class<?> IChatBaseComponentClass;
private static Class<?> ICraftingClass;
private static Class<?> ContainerAnvilClass;
private static Class<?> ChatMessageClass;
private static Class<?> EntityHumanClass;
private static Class<?> ContainerClass;
private static Class<?> ContainerAccessClass;
private static Class<?> WorldClass;
private static Class<?> PlayerInventoryClass;
private static Class<?> ContainersClass;
private static Class<?> CraftPlayerClass;
private Player player;
private Map<AnvilSlot, ItemStack> items = new HashMap<>();
private OnClose onClose = null;
private Inventory inv;
private Listener listener;
static {
BlockPositionClass = NMSUtil.getNMSClass("BlockPosition");
PacketPlayOutOpenWindowClass = NMSUtil.getNMSClass("PacketPlayOutOpenWindow");
IChatBaseComponentClass = NMSUtil.getNMSClass("IChatBaseComponent");
ICraftingClass = NMSUtil.getNMSClass("ICrafting");
ContainerAnvilClass = NMSUtil.getNMSClass("ContainerAnvil");
EntityHumanClass = NMSUtil.getNMSClass("EntityHuman");
ChatMessageClass = NMSUtil.getNMSClass("ChatMessage");
ContainerClass = NMSUtil.getNMSClass("Container");
WorldClass = NMSUtil.getNMSClass("World");
PlayerInventoryClass = NMSUtil.getNMSClass("PlayerInventory");
CraftPlayerClass = NMSUtil.getCraftClass("entity.CraftPlayer");
if (NMSUtil.getVersionNumber() > 13) {
ContainerAccessClass = NMSUtil.getNMSClass("ContainerAccess");
ContainersClass = NMSUtil.getNMSClass("Containers");
}
}
public AbstractAnvilGUI(Player player, AnvilClickEventHandler handler) {
UltimateKits instance = UltimateKits.getInstance();
this.player = player;
this.listener = new Listener() {
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event) {
if (event.getWhoClicked() instanceof Player && event.getInventory().equals(AbstractAnvilGUI.this.inv)) {
event.setCancelled(true);
ItemStack item = event.getCurrentItem();
int slot = event.getRawSlot();
if (item == null || item.getType().equals(Material.AIR) || slot != 2)
return;
String name = "";
ItemMeta meta = item.getItemMeta();
if (meta != null && meta.hasDisplayName())
name = meta.getDisplayName();
AnvilClickEvent clickEvent = new AnvilClickEvent(AnvilSlot.bySlot(slot), name);
handler.onAnvilClick(clickEvent);
if (clickEvent.getWillClose())
event.getWhoClicked().closeInventory();
if (clickEvent.getWillDestroy())
AbstractAnvilGUI.this.destroy();
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClose(InventoryCloseEvent event) {
if (event.getPlayer() instanceof Player && AbstractAnvilGUI.this.inv.equals(event.getInventory())) {
Inventory inv = event.getInventory();
player.setLevel(player.getLevel() - 1);
inv.clear();
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> {
if (AbstractAnvilGUI.this.onClose != null)
AbstractAnvilGUI.this.onClose.onClose(player, inv);
AbstractAnvilGUI.this.destroy();
}, 1L);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerQuit(PlayerQuitEvent event) {
if (event.getPlayer().equals(AbstractAnvilGUI.this.player)) {
player.setLevel(player.getLevel() - 1);
AbstractAnvilGUI.this.destroy();
}
}
};
Bukkit.getPluginManager().registerEvents(this.listener, instance);
}
public Player getPlayer() {
return this.player;
}
public void setSlot(AnvilSlot slot, ItemStack item) {
this.items.put(slot, item);
}
public void open() {
this.player.setLevel(this.player.getLevel() + 1);
try {
Object craftPlayer = CraftPlayerClass.cast(this.player);
Method getHandleMethod = CraftPlayerClass.getMethod("getHandle");
Object entityPlayer = getHandleMethod.invoke(craftPlayer);
Object playerInventory = NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "inventory", false));
Object world = NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "world", false));
Object blockPosition = BlockPositionClass.getConstructor(int.class, int.class, int.class).newInstance(0, 0, 0);
Object container;
if (NMSUtil.getVersionNumber() > 13) {
container = ContainerAnvilClass
.getConstructor(int.class, PlayerInventoryClass, ContainerAccessClass)
.newInstance(7, playerInventory, ContainerAccessClass.getMethod("at", WorldClass, BlockPositionClass).invoke(null, world, blockPosition));
} else {
container = ContainerAnvilClass
.getConstructor(PlayerInventoryClass, WorldClass, BlockPositionClass, EntityHumanClass)
.newInstance(playerInventory, world, blockPosition, entityPlayer);
}
NMSUtil.getField(ContainerClass, "checkReachable", true).set(container, false);
Method getBukkitViewMethod = container.getClass().getMethod("getBukkitView");
Object bukkitView = getBukkitViewMethod.invoke(container);
Method getTopInventoryMethod = bukkitView.getClass().getMethod("getTopInventory");
this.inv = (Inventory) getTopInventoryMethod.invoke(bukkitView);
for (AnvilSlot slot : this.items.keySet()) {
this.inv.setItem(slot.getSlot(), this.items.get(slot));
}
Method nextContainerCounterMethod = entityPlayer.getClass().getMethod("nextContainerCounter");
int c = (int) nextContainerCounterMethod.invoke(entityPlayer);
Constructor<?> chatMessageConstructor = ChatMessageClass.getConstructor(String.class, Object[].class);
Object inventoryTitle = chatMessageConstructor.newInstance("Repairing", new Object[]{});
Object packet;
if (NMSUtil.getVersionNumber() > 13) {
packet = PacketPlayOutOpenWindowClass
.getConstructor(int.class, ContainersClass, IChatBaseComponentClass)
.newInstance(c, ContainersClass.getField("ANVIL").get(null), inventoryTitle);
} else {
packet = PacketPlayOutOpenWindowClass
.getConstructor(int.class, String.class, IChatBaseComponentClass, int.class)
.newInstance(c, "minecraft:anvil", inventoryTitle, 0);
}
NMSUtil.sendPacket(this.player, packet);
Field activeContainerField = NMSUtil.getField(EntityHumanClass, "activeContainer", true);
if (activeContainerField != null) {
activeContainerField.set(entityPlayer, container);
NMSUtil.getField(ContainerClass, "windowId", true).set(activeContainerField.get(entityPlayer), c);
Method addSlotListenerMethod = activeContainerField.get(entityPlayer).getClass().getMethod("addSlotListener", ICraftingClass);
addSlotListenerMethod.invoke(activeContainerField.get(entityPlayer), entityPlayer);
if (NMSUtil.getVersionNumber() > 13) {
ContainerClass.getMethod("setTitle", IChatBaseComponentClass).invoke(container, inventoryTitle);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
this.player = null;
this.items = null;
HandlerList.unregisterAll(this.listener);
this.listener = null;
}
private OnClose getOnClose() {
return this.onClose;
}
public void setOnClose(OnClose onClose) {
this.onClose = onClose;
}
public enum AnvilSlot {
INPUT_LEFT(0),
INPUT_RIGHT(1),
OUTPUT(2);
private int slot;
AnvilSlot(int slot) {
this.slot = slot;
}
public static AnvilSlot bySlot(int slot) {
for (AnvilSlot anvilSlot : values()) {
if (anvilSlot.getSlot() == slot) {
return anvilSlot;
}
}
return null;
}
public int getSlot() {
return this.slot;
}
}
@FunctionalInterface
public interface AnvilClickEventHandler {
void onAnvilClick(AnvilClickEvent event);
}
public class AnvilClickEvent {
private AnvilSlot slot;
private String name;
private boolean close = true;
private boolean destroy = true;
public AnvilClickEvent(AnvilSlot slot, String name) {
this.slot = slot;
this.name = name;
}
public AnvilSlot getSlot() {
return this.slot;
}
public String getName() {
return this.name;
}
public boolean getWillClose() {
return this.close;
}
public void setWillClose(boolean close) {
this.close = close;
}
public boolean getWillDestroy() {
return this.destroy;
}
public void setWillDestroy(boolean destroy) {
this.destroy = destroy;
}
}
}

View File

@ -1,245 +0,0 @@
package com.songoda.ultimatekits.utils.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AbstractGUI implements Listener {
private static boolean listenersInitialized = false;
protected final Player player;
protected Inventory inventory = null;
protected String setTitle = null;
protected boolean cancelBottom = false;
private Map<Range, Clickable> clickables = new HashMap<>();
private List<OnClose> onCloses = new ArrayList<>();
private Map<Range, Boolean> draggableRanges = new HashMap<>();
public AbstractGUI(Player player) {
this.player = player;
}
public static void initializeListeners(JavaPlugin plugin) {
if (listenersInitialized) return;
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler
public void onClickGUI(InventoryClickEvent event) {
Inventory inventory = event.getClickedInventory();
if (inventory == null) return;
AbstractGUI gui = getGUIFromInventory(inventory);
Player player = (Player) event.getWhoClicked();
boolean bottom = false;
InventoryType type = event.getClickedInventory().getType();
if (type != InventoryType.CHEST && type != InventoryType.PLAYER) return;
if (gui == null && event.getWhoClicked().getOpenInventory().getTopInventory() != null) {
Inventory top = event.getWhoClicked().getOpenInventory().getTopInventory();
gui = getGUIFromInventory(top);
if (gui != null && gui.cancelBottom) event.setCancelled(true);
bottom = true;
}
if (gui == null) return;
if (!bottom) event.setCancelled(true);
if (!gui.draggableRanges.isEmpty() && !bottom) {
for (Map.Entry<Range, Boolean> entry : gui.draggableRanges.entrySet()) {
Range range = entry.getKey();
if (range.getMax() == range.getMin() && event.getSlot() == range.getMin()
|| event.getSlot() >= range.getMin() && event.getSlot() <= range.getMax()) {
event.setCancelled(!entry.getValue());
if (!entry.getValue()) break;
}
}
}
Map<Range, Clickable> entries = new HashMap<>(gui.clickables);
for (Map.Entry<Range, Clickable> entry : entries.entrySet()) {
Range range = entry.getKey();
if (range.isBottom() && !bottom || !range.isBottom() && bottom || range.getClickType() != null && range.getClickType() != event.getClick())
continue;
if (event.getSlot() >= range.getMin() && event.getSlot() <= range.getMax()) {
entry.getValue().Clickable(player, inventory, event.getCursor(), event.getSlot(), event.getClick());
player.playSound(player.getLocation(), entry.getKey().getOnClickSound(), 1F, 1F);
}
}
}
@EventHandler
public void onCloseGUI(InventoryCloseEvent event) {
Inventory inventory = event.getInventory();
AbstractGUI gui = getGUIFromInventory(inventory);
if (gui == null || gui.inventory == null) return;
for (OnClose onClose : gui.onCloses) {
onClose.onClose((Player) event.getPlayer(), inventory);
}
gui.destory();
}
private AbstractGUI getGUIFromInventory(Inventory inventory) {
if (inventory.getHolder() == null) return null;
InventoryHolder holder = inventory.getHolder();
if (!(holder instanceof GUIHolder)) return null;
return ((AbstractGUI.GUIHolder) holder).getGUI();
}
}, plugin);
listenersInitialized = true;
}
public void init(String title, int slots) {
if (inventory == null
|| inventory.getSize() != slots
|| Methods.formatTitle(title) != player.getOpenInventory().getTitle()) {
this.inventory = Bukkit.getServer().createInventory(new GUIHolder(), slots, Methods.formatTitle(title));
this.setTitle = Methods.formatTitle(title);
if (this.clickables.size() == 0)
registerClickables();
if (this.onCloses.size() == 0)
registerOnCloses();
}
constructGUI();
initializeListeners(UltimateKits.getInstance());
player.openInventory(inventory);
}
private void destory() {
onCloses.clear();
clickables.clear();
draggableRanges.clear();
}
protected abstract void constructGUI();
protected void addDraggable(Range range, boolean option) {
this.draggableRanges.put(range, option);
}
protected void removeDraggable() {
this.draggableRanges.clear();
}
protected abstract void registerClickables();
protected abstract void registerOnCloses();
protected ItemStack createButton(int slot, Inventory inventory, ItemStack item, String name, String... lore) {
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
if (lore != null && lore.length != 0) {
List<String> newLore = new ArrayList<>();
for (String line : lore) newLore.add(ChatColor.translateAlternateColorCodes('&', line));
meta.setLore(newLore);
}
item.setItemMeta(meta);
inventory.setItem(slot, item);
return item;
}
protected ItemStack createButton(int slot, ItemStack item, String name, ArrayList<String> lore) {
return createButton(slot, inventory, item, name, lore.toArray(new String[0]));
}
protected ItemStack createButton(int slot, ItemStack item, String name, String... lore) {
return createButton(slot, inventory, item, name, lore);
}
protected ItemStack createButton(int slot, Object item, String name, String... lore) {
if (item instanceof ItemStack)
return createButton(slot, inventory, (ItemStack)item, name, lore);
else
return createButton(slot, inventory, (Material)item, name, lore);
}
protected ItemStack createButton(int slot, Inventory inventory, Material material, String name, String... lore) {
return createButton(slot, inventory, new ItemStack(material), name, lore);
}
protected ItemStack createButton(int slot, Material material, String name, String... lore) {
return createButton(slot, inventory, new ItemStack(material), name, lore);
}
protected ItemStack createButton(int slot, Material material, String name, ArrayList<String> lore) {
return createButton(slot, material, name, lore.toArray(new String[0]));
}
protected void registerClickable(int min, int max, ClickType clickType, boolean bottom, Clickable clickable) {
clickables.put(new Range(min, max, clickType, bottom), clickable);
}
protected void registerClickable(int min, int max, ClickType clickType, Clickable clickable) {
registerClickable(min, max, clickType, false, clickable);
}
protected void registerClickable(int slot, ClickType clickType, Clickable clickable) {
registerClickable(slot, slot, clickType, false, clickable);
}
protected void registerClickable(int min, int max, Clickable clickable) {
registerClickable(min, max, null, false, clickable);
}
protected void registerClickable(int slot, boolean bottom, Clickable clickable) {
registerClickable(slot, slot, null, bottom, clickable);
}
protected void registerClickable(int slot, Clickable clickable) {
registerClickable(slot, slot, null, false, clickable);
}
protected void resetClickables() {
clickables.clear();
}
protected void registerOnClose(OnClose onClose) {
onCloses.add(onClose);
}
public Inventory getInventory() {
return inventory;
}
public class GUIHolder implements InventoryHolder {
@Override
public Inventory getInventory() {
return inventory;
}
public AbstractGUI getGUI() {
return AbstractGUI.this;
}
}
public String getSetTitle() {
return setTitle;
}
}

View File

@ -1,11 +0,0 @@
package com.songoda.ultimatekits.utils.gui;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public interface Clickable {
void Clickable(Player player, Inventory inventory, ItemStack cursor, int slot, ClickType type);
}

View File

@ -1,10 +0,0 @@
package com.songoda.ultimatekits.utils.gui;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public interface OnClose {
void onClose(Player player, Inventory inventory);
}

View File

@ -1,51 +0,0 @@
package com.songoda.ultimatekits.utils.gui;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.utils.ServerVersion;
import org.bukkit.Sound;
import org.bukkit.event.inventory.ClickType;
public class Range {
private int min;
private int max;
private ClickType clickType;
private boolean bottom;
private Sound onClickSound;
public Range(int min, int max, ClickType clickType, boolean bottom) {
this.min = min;
this.max = max;
this.clickType = clickType;
this.bottom = bottom;
if (UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_9)) onClickSound = Sound.UI_BUTTON_CLICK;
}
public Range(int min, int max, Sound onClickSound, ClickType clickType, boolean bottom) {
this.min = min;
this.max = max;
this.onClickSound = onClickSound;
this.clickType = clickType;
this.bottom = bottom;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
public ClickType getClickType() {
return clickType;
}
public boolean isBottom() {
return bottom;
}
public Sound getOnClickSound() {
return onClickSound;
}
}

View File

@ -1,302 +0,0 @@
package com.songoda.ultimatekits.utils.locale;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Assists in the utilization of localization files.
* Created to be used by the Songoda Team.
*
* @author Brianna O'Keefe - Songoda
*/
public class Locale {
private static final List<Locale> LOCALES = new ArrayList<>();
private static final Pattern NODE_PATTERN = Pattern.compile("(\\w+(?:\\.{1}\\w+)*)\\s*=\\s*\"(.*)\"");
private static final String FILE_EXTENSION = ".lang";
private static JavaPlugin plugin;
private static File localeFolder;
private final Map<String, String> nodes = new HashMap<>();
private static String defaultLocale;
private File file;
private String name;
/**
* Instantiate the Locale class for future use
*
* @param name the name of the instantiated language
*/
private Locale(String name) {
if (plugin == null)
return;
this.name = name;
String fileName = name + FILE_EXTENSION;
this.file = new File(localeFolder, fileName);
if (!this.reloadMessages()) return;
plugin.getLogger().info("Loaded locale \"" + fileName + "\"");
}
/**
* Initialize the class to load all existing language files and update them.
* This must be called before any other methods in this class as otherwise
* the methods will fail to invoke
*
* @param plugin the plugin instance
* @param defaultLocale the default language
*/
public Locale(JavaPlugin plugin, String defaultLocale) {
Locale.plugin = plugin;
Locale.localeFolder = new File(plugin.getDataFolder(), "locales/");
if (!localeFolder.exists()) localeFolder.mkdirs();
//Save the default locale file.
Locale.defaultLocale = defaultLocale;
saveLocale(defaultLocale);
for (File file : localeFolder.listFiles()) {
String fileName = file.getName();
if (!fileName.endsWith(FILE_EXTENSION)) continue;
String name = fileName.substring(0, fileName.lastIndexOf('.'));
if (name.split("_").length != 2) continue;
if (localeLoaded(name)) continue;
LOCALES.add(new Locale(name));
}
}
/**
* Save a locale file from the InputStream, to the locale folder
*
* @param fileName the name of the file to save
* @return true if the operation was successful, false otherwise
*/
public static boolean saveLocale(String fileName) {
return saveLocale(plugin.getResource(defaultLocale + FILE_EXTENSION), fileName);
}
/**
* Save a locale file from the InputStream, to the locale folder
*
* @param in file to save
* @param fileName the name of the file to save
* @return true if the operation was successful, false otherwise
*/
public static boolean saveLocale(InputStream in, String fileName) {
if (!localeFolder.exists()) localeFolder.mkdirs();
if (!fileName.endsWith(FILE_EXTENSION))
fileName = (fileName.lastIndexOf(".") == -1 ? fileName : fileName.substring(0, fileName.lastIndexOf('.'))) + FILE_EXTENSION;
File destinationFile = new File(localeFolder, fileName);
if (destinationFile.exists())
return compareFiles(in, destinationFile);
try (OutputStream outputStream = new FileOutputStream(destinationFile)) {
copy(in, outputStream);
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
if (fileName.split("_").length != 2) return false;
LOCALES.add(new Locale(fileName));
if (defaultLocale == null) defaultLocale = fileName;
return true;
} catch (IOException e) {
return false;
}
}
// Write new changes to existing files, if any at all
private static boolean compareFiles(InputStream in, File existingFile) {
InputStream defaultFile =
in == null ? plugin.getResource((defaultLocale != null ? defaultLocale : "en_US") + FILE_EXTENSION) : in;
boolean changed = false;
List<String> defaultLines, existingLines;
try (BufferedReader defaultReader = new BufferedReader(new InputStreamReader(defaultFile));
BufferedReader existingReader = new BufferedReader(new FileReader(existingFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(existingFile, true))) {
defaultLines = defaultReader.lines().collect(Collectors.toList());
existingLines = existingReader.lines().map(s -> s.split("\\s*=")[0]).collect(Collectors.toList());
for (String defaultValue : defaultLines) {
if (defaultValue.isEmpty() || defaultValue.startsWith("#")) continue;
String key = defaultValue.split("\\s*=")[0];
if (!existingLines.contains(key)) {
if (!changed) {
writer.newLine();
writer.newLine();
// Leave a note alerting the user of the newly added messages.
writer.write("# New messages for " + plugin.getName() + " v" + plugin.getDescription().getVersion() + ".");
// If changes were found outside of the default file leave a note explaining that.
if (in == null) {
writer.newLine();
writer.write("# These translations were found untranslated, join");
writer.newLine();
writer.write("# our translation Discord https://discord.gg/f7fpZEf");
writer.newLine();
writer.write("# to request an official update!");
}
}
writer.newLine();
writer.write(defaultValue);
changed = true;
}
}
if (in != null && !changed) compareFiles(null, existingFile);
} catch (IOException e) {
return false;
}
return changed;
}
/**
* Check whether a locale exists and is registered or not
*
* @param name the whole language tag (i.e. "en_US")
* @return true if it exists
*/
public static boolean localeLoaded(String name) {
for (Locale locale : LOCALES)
if (locale.getName().equals(name)) return true;
return false;
}
/**
* Get a locale by its entire proper name (i.e. "en_US")
*
* @param name the full name of the locale
* @return locale of the specified name
*/
public static Locale getLocale(String name) {
for (Locale locale : LOCALES)
if (locale.getName().equalsIgnoreCase(name)) return locale;
return null;
}
/**
* Clear the previous message cache and load new messages directly from file
*
* @return reload messages from file
*/
public boolean reloadMessages() {
if (!this.file.exists()) {
plugin.getLogger().warning("Could not find file for locale \"" + this.name + "\"");
return false;
}
this.nodes.clear(); // Clear previous data (if any)
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
for (int lineNumber = 0; (line = reader.readLine()) != null; lineNumber++) {
if (line.trim().isEmpty() || line.startsWith("#") /* Comment */) continue;
Matcher matcher = NODE_PATTERN.matcher(line);
if (!matcher.find()) {
System.err.println("Invalid locale syntax at (line=" + lineNumber + ")");
continue;
}
nodes.put(matcher.group(1), matcher.group(2));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Supply the Message object with the plugins prefix.
*
* @param message message to be applied
* @return applied message
*/
private Message supplyPrefix(Message message) {
return message.setPrefix(this.nodes.getOrDefault("general.nametag.prefix", "[Plugin]"));
}
/**
* Create a new unsaved Message
*
* @param message the message to create
* @return the created message
*/
public Message newMessage(String message) {
return supplyPrefix(new Message(message));
}
/**
* Get a message set for a specific node.
*
* @param node the node to get
* @return the message for the specified node
*/
public Message getMessage(String node) {
return this.getMessageOrDefault(node, node);
}
/**
* Get a message set for a specific node
*
* @param node the node to get
* @param defaultValue the default value given that a value for the node was not found
* @return the message for the specified node. Default if none found
*/
public Message getMessageOrDefault(String node, String defaultValue) {
return supplyPrefix(new Message(this.nodes.getOrDefault(node, defaultValue)));
}
/**
* Return the locale name (i.e. "en_US")
*
* @return the locale name
*/
public String getName() {
return name;
}
private static void copy(InputStream input, OutputStream output) {
int n;
byte[] buffer = new byte[1024 * 4];
try {
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,115 +0,0 @@
package com.songoda.ultimatekits.utils.locale;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* The Message object. This holds the message to be sent
* as well as the plugins prefix so that they can both be
* easily manipulated then deployed
*/
public class Message {
private String prefix = null;
private String message;
/**
* create a new message
*
* @param message the message text
*/
public Message(String message) {
this.message = message;
}
/**
* Format and send the held message to a player
*
* @param player player to send the message to
*/
public void sendMessage(Player player) {
player.sendMessage(this.getMessage());
}
/**
* Format and send the held message with the
* appended plugin prefix to a player
*
* @param player player to send the message to
*/
public void sendPrefixedMessage(Player player) {
player.sendMessage(this.getPrefixedMessage());
}
/**
* Format and send the held message to a player
*
* @param sender command sender to send the message to
*/
public void sendMessage(CommandSender sender) {
sender.sendMessage(this.getMessage());
}
/**
* Format and send the held message with the
* appended plugin prefix to a command sender
*
* @param sender command sender to send the message to
*/
public void sendPrefixedMessage(CommandSender sender) {
sender.sendMessage(this.getPrefixedMessage());
}
/**
* Format the held message and append the plugins
* prefix
*
* @return the prefixed message
*/
public String getPrefixedMessage() {
return ChatColor.translateAlternateColorCodes('&',(prefix == null ? "" : this.prefix)
+ " " + this.message);
}
/**
* Get and format the held message
*
* @return the message
*/
public String getMessage() {
return ChatColor.translateAlternateColorCodes('&', this.message);
}
/**
* Get the held message
*
* @return the message
*/
public String getUnformattedMessage() {
return this.message;
}
/**
* Replace the provided placeholder with the
* provided object
*
* @param placeholder the placeholder to replace
* @param replacement the replacement object
* @return the modified Message
*/
public Message processPlaceholder(String placeholder, Object replacement) {
this.message = message.replace("%" + placeholder + "%", replacement.toString());
return this;
}
Message setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String toString() {
return this.message;
}
}

View File

@ -1,23 +0,0 @@
package com.songoda.ultimatekits.utils.settings;
public enum Category {
MAIN("General settings and options."),
INTERFACES("These settings allow you to alter the way interfaces look.",
"They are used in GUI's to make patterns, change them up then open up a",
"GUI to see how it works."),
SYSTEM("System related settings.");
private String[] comments;
Category(String... comments) {
this.comments = comments;
}
public String[] getComments() {
return comments;
}
}

View File

@ -1,118 +0,0 @@
package com.songoda.ultimatekits.utils.settings;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.utils.ServerVersion;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public enum Setting {
ONLY_SHOW_KITS_WITH_PERMS("Main.Only Show Players Kits They Have Permission To Use", false),
KITS_FREE_WITH_PERMS("Main.Allow Players To Receive Kits For Free If They Have Permission", true),
DONT_PREVIEW_COMMANDS("Main.Dont Preview Commands In Kits", false),
HOLOGRAM_LAYOUT("Main.Hologram Layout", Arrays.asList("{TITLE}", "{LEFT-CLICK}", "{RIGHT-CLICK}")),
SOUNDS_ENABLED("Main.Sounds Enabled", true),
NO_REDEEM_WHEN_FULL("Main.Prevent The Redeeming of a Kit When Inventory Is Full", true),
AUTO_EQUIP_ARMOR("Main.Automatically Equip Armor Given From a Kit", true),
AUTO_EQUIP_ARMOR_ROULETTE("Main.Automatically Equip Armor Given From a Kit with the Roulette Animation", false),
CHANCE_IN_PREVIEW("Main.Display Chance In Preview", true),
CURRENCY_SYMBOL("Main.Currency Symbol", "$"),
VAULT_ECONOMY("Economy.Use Vault Economy", true,
"Should Vault be used?"),
RESERVE_ECONOMY("Economy.Use Reserve Economy", true,
"Should Reserve be used?"),
PLAYER_POINTS_ECONOMY("Economy.Use Player Points Economy", false,
"Should PlayerPoints be used?"),
EXIT_ICON("Interfaces.Exit Icon", UltimateKits.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "OAK_DOOR" : "WOOD_DOOR"),
BUY_ICON("Interfaces.Buy Icon", "EMERALD"),
GLASS_TYPE_1("Interfaces.Glass Type 1", 7),
GLASS_TYPE_2("Interfaces.Glass Type 2", 11),
GLASS_TYPE_3("Interfaces.Glass Type 3", 3),
RAINBOW("Interfaces.Replace Glass Type 1 With Rainbow Glass", false),
DO_NOT_USE_GLASS_BORDERS("Interfaces.Do Not Use Glass Borders", false),
LANGUGE_MODE("System.Language Mode", "en_US",
"The enabled language file.",
"More language files (if available) can be found in the plugins data folder."),
MYSQL_ENABLED("MySQL.Enabled", false, "Set to 'true' to use MySQL for data storage."),
MYSQL_HOSTNAME("MySQL.Hostname", "localhost"),
MYSQL_PORT("MySQL.Port", 3306),
MYSQL_DATABASE("MySQL.Database", "your-database"),
MYSQL_USERNAME("MySQL.Username", "user"),
MYSQL_PASSWORD("MySQL.Password", "pass"),
MYSQL_USE_SSL("MySQL.Use SSL", false);
private String setting;
private Object option;
private String[] comments;
Setting(String setting, Object option, String... comments) {
this.setting = setting;
this.option = option;
this.comments = comments;
}
Setting(String setting, Object option) {
this.setting = setting;
this.option = option;
this.comments = null;
}
public static Setting getSetting(String setting) {
List<Setting> settings = Arrays.stream(values()).filter(setting1 -> setting1.setting.equals(setting)).collect(Collectors.toList());
if (settings.isEmpty()) return null;
return settings.get(0);
}
public String getSetting() {
return setting;
}
public Object getOption() {
return option;
}
public String[] getComments() {
return comments;
}
public List<Integer> getIntegerList() {
return UltimateKits.getInstance().getConfig().getIntegerList(setting);
}
public List<String> getStringList() {
return UltimateKits.getInstance().getConfig().getStringList(setting);
}
public boolean getBoolean() {
return UltimateKits.getInstance().getConfig().getBoolean(setting);
}
public int getInt() {
return UltimateKits.getInstance().getConfig().getInt(setting);
}
public long getLong() {
return UltimateKits.getInstance().getConfig().getLong(setting);
}
public String getString() {
return UltimateKits.getInstance().getConfig().getString(setting);
}
public char getChar() {
return UltimateKits.getInstance().getConfig().getString(setting).charAt(0);
}
public double getDouble() {
return UltimateKits.getInstance().getConfig().getDouble(setting);
}
}

View File

@ -1,311 +0,0 @@
package com.songoda.ultimatekits.utils.settings;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.utils.Methods;
import com.songoda.ultimatekits.utils.ServerVersion;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.*;
import java.util.*;
/**
* Created by songoda on 6/4/2017.
*/
public class SettingsManager implements Listener {
private final UltimateKits plugin;
private Map<Player, String> cat = new HashMap<>();
private Map<Player, String> current = new HashMap<>();
public SettingsManager(UltimateKits plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (event.getView().getType() != InventoryType.CHEST) return;
ItemStack clickedItem = event.getCurrentItem();
if (event.getInventory() != event.getWhoClicked().getOpenInventory().getTopInventory()
|| clickedItem == null || !clickedItem.hasItemMeta()
|| !clickedItem.getItemMeta().hasDisplayName()) {
return;
}
if (event.getView().getTitle().equals(plugin.getName() + " Settings Manager")) {
event.setCancelled(true);
if (clickedItem.getType().name().contains("STAINED_GLASS")) return;
String type = ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName());
this.cat.put((Player) event.getWhoClicked(), type);
this.openEditor((Player) event.getWhoClicked());
} else if (event.getView().getTitle().equals(plugin.getName() + " Settings Editor")) {
event.setCancelled(true);
if (clickedItem.getType().name().contains("STAINED_GLASS")) return;
Player player = (Player) event.getWhoClicked();
String key = cat.get(player) + "." + ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName());
if (plugin.getConfig().get(key).getClass().getName().equals("java.lang.Boolean")) {
this.plugin.getConfig().set(key, !plugin.getConfig().getBoolean(key));
this.finishEditing(player);
} else {
this.editObject(player, key);
}
}
}
@EventHandler
public void onChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
if (!current.containsKey(player)) return;
String value = current.get(player);
FileConfiguration config = plugin.getConfig();
if (config.isLong(value)) {
config.set(value, Long.parseLong(event.getMessage()));
} else if (config.isInt(value)) {
config.set(value, Integer.parseInt(event.getMessage()));
} else if (config.isDouble(value)) {
config.set(value, Double.parseDouble(event.getMessage()));
} else if (config.isString(value)) {
config.set(value, event.getMessage());
}
Bukkit.getScheduler().scheduleSyncDelayedTask(UltimateKits.getInstance(), () ->
this.finishEditing(player), 0L);
event.setCancelled(true);
}
private void finishEditing(Player player) {
this.current.remove(player);
this.saveConfig();
this.openEditor(player);
}
private void editObject(Player player, String current) {
this.current.put(player, ChatColor.stripColor(current));
player.closeInventory();
player.sendMessage("");
player.sendMessage(Methods.formatText("&7Please enter a value for &6" + current + "&7."));
if (plugin.getConfig().isInt(current) || plugin.getConfig().isDouble(current)) {
player.sendMessage(Methods.formatText("&cUse only numbers."));
}
player.sendMessage("");
}
public void openSettingsManager(Player player) {
Inventory inventory = Bukkit.createInventory(null, 27, plugin.getName() + " Settings Manager");
ItemStack glass = Methods.getGlass();
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, glass);
}
int slot = 10;
for (String key : plugin.getConfig().getDefaultSection().getKeys(false)) {
ItemStack item = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.LEGACY_WOOL : Material.valueOf("WOOL"), 1, (byte) (slot - 9));
ItemMeta meta = item.getItemMeta();
meta.setLore(Collections.singletonList(Methods.formatText("&6Click To Edit This Category.")));
meta.setDisplayName(Methods.formatText("&f&l" + key));
item.setItemMeta(meta);
inventory.setItem(slot, item);
slot++;
}
player.openInventory(inventory);
}
private void openEditor(Player player) {
Inventory inventory = Bukkit.createInventory(null, 54, plugin.getName() + " Settings Editor");
FileConfiguration config = plugin.getConfig();
int slot = 0;
for (String key : config.getConfigurationSection(cat.get(player)).getKeys(true)) {
String fKey = cat.get(player) + "." + key;
ItemStack item = new ItemStack(Material.DIAMOND_HELMET);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(Methods.formatText("&6" + key));
List<String> lore = new ArrayList<>();
if (config.isBoolean(fKey)) {
item.setType(Material.LEVER);
lore.add(Methods.formatText(config.getBoolean(fKey) ? "&atrue" : "&cfalse"));
} else if (config.isString(fKey)) {
item.setType(Material.PAPER);
lore.add(Methods.formatText("&7" + config.getString(fKey)));
} else if (config.isInt(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getInt(fKey)));
} else if (config.isLong(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getLong(fKey)));
} else if (config.isDouble(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getDouble(fKey)));
}
Setting setting = Setting.getSetting(fKey);
if (setting != null && setting.getComments() != null) {
lore.add("");
String comment = String.join(" ", setting.getComments());
int lastIndex = 0;
for (int n = 0; n < comment.length(); n++) {
if (n - lastIndex < 30)
continue;
if (comment.charAt(n) == ' ') {
lore.add(Methods.formatText("&8" + comment.substring(lastIndex, n).trim()));
lastIndex = n;
}
}
if (lastIndex - comment.length() < 30)
lore.add(Methods.formatText("&8" + comment.substring(lastIndex).trim()));
}
meta.setLore(lore);
item.setItemMeta(meta);
inventory.setItem(slot, item);
slot++;
}
player.openInventory(inventory);
}
public void reloadConfig() {
plugin.reloadConfig();
this.setupConfig();
}
public void setupConfig() {
FileConfiguration config = plugin.getConfig();
for (Setting setting : Setting.values()) {
config.addDefault(setting.getSetting(), setting.getOption());
}
plugin.getConfig().options().copyDefaults(true);
saveConfig();
}
private void saveConfig() {
String dump = plugin.getConfig().saveToString();
StringBuilder config = new StringBuilder();
BufferedReader bufReader = new BufferedReader(new StringReader(dump));
try {
boolean first = true;
String line;
int currentTab = 0;
String category = "";
while ((line = bufReader.readLine()) != null) {
if (line.trim().startsWith("#")) continue;
int tabChange = line.length() - line.trim().length();
if (currentTab != tabChange) {
category = category.contains(".") && tabChange != 0 ? category.substring(0, category.indexOf(".")) : "";
currentTab = tabChange;
}
if (line.endsWith(":")) {
bufReader.mark(1000);
String found = bufReader.readLine();
bufReader.reset();
if (!found.trim().startsWith("-")) {
String newCategory = line.substring(0, line.length() - 1).trim();
if (category.equals(""))
category = newCategory;
else
category += "." + newCategory;
currentTab = tabChange + 2;
if (!first) {
config.append("\n\n");
} else {
first = false;
}
if (!category.contains("."))
config.append("#").append("\n");
try {
Category categoryObj = Category.valueOf(category.toUpperCase()
.replace(" ", "_")
.replace(".", "_"));
config.append(new String(new char[tabChange]).replace('\0', ' '));
for (String l : categoryObj.getComments())
config.append("# ").append(l).append("\n");
} catch (IllegalArgumentException e) {
config.append("# ").append(category).append("\n");
}
if (!category.contains("."))
config.append("#").append("\n");
config.append(line).append("\n");
continue;
}
}
if (line.trim().startsWith("-")) {
config.append(line).append("\n");
continue;
}
String key = category + "." + (line.split(":")[0].trim());
for (Setting setting : Setting.values()) {
if (!setting.getSetting().equals(key) || setting.getComments() == null) continue;
config.append(" ").append("\n");
for (String l : setting.getComments()) {
config.append(new String(new char[currentTab]).replace('\0', ' '));
config.append("# ").append(l).append("\n");
}
}
config.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (!plugin.getDataFolder().exists())
plugin.getDataFolder().mkdir();
BufferedWriter writer =
new BufferedWriter(new FileWriter(new File(plugin.getDataFolder() + File.separator + "config.yml")));
writer.write(config.toString());
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,32 +0,0 @@
package com.songoda.ultimatekits.utils.updateModules;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.update.Module;
import com.songoda.update.Plugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class LocaleModule implements Module {
@Override
public void run(Plugin plugin) {
JSONObject json = plugin.getJson();
try {
JSONArray files = (JSONArray) json.get("neededFiles");
for (Object o : files) {
JSONObject file = (JSONObject) o;
if (file.get("type").equals("locale")) {
InputStream in = new URL((String) file.get("link")).openStream();
UltimateKits.getInstance().getLocale().saveLocale(in, (String) file.get("name"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,100 +0,0 @@
package com.songoda.ultimatekits.utils.version;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
public class NMSUtil {
public static String getVersion() {
String name = Bukkit.getServer().getClass().getPackage().getName();
return name.substring(name.lastIndexOf('.') + 1) + ".";
}
public static int getVersionNumber() {
String name = getVersion().substring(3);
return Integer.valueOf(name.substring(0, name.length() - 4));
}
public static int getVersionReleaseNumber() {
String NMSVersion = getVersion();
return Integer.valueOf(NMSVersion.substring(NMSVersion.length() - 2).replace(".", ""));
}
public static Class<?> getNMSClass(String className) {
try {
String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = Class.forName(fullName);
return clazz;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Class<?> getCraftClass(String className) {
try {
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = Class.forName(fullName);
return clazz;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Field getField(Class<?> clazz, String name, boolean declared) {
try {
Field field;
if (declared) {
field = clazz.getDeclaredField(name);
} else {
field = clazz.getField(name);
}
field.setAccessible(true);
return field;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Object getFieldObject(Object object, Field field) {
try {
return field.get(object);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void setField(Object object, String fieldName, Object fieldValue, boolean declared) {
try {
Field field;
if (declared) {
field = object.getClass().getDeclaredField(fieldName);
} else {
field = object.getClass().getField(fieldName);
}
field.setAccessible(true);
field.set(object, fieldValue);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendPacket(Player player, Object packet) {
try {
Object handle = player.getClass().getMethod("getHandle").invoke(player);
Object playerConnection = handle.getClass().getField("playerConnection").get(handle);
playerConnection.getClass().getMethod("sendPacket", getNMSClass("Packet")).invoke(playerConnection, packet);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -11,13 +11,14 @@ general.type.free = "Free"
interface.selector.kit = "&c%kit%"
interface.selector.title = "&8Server kits"
interface.selector.details = "&7Hello &e%player%&7!|&7Listed below are our servers kit.||&7Click on the &eicon &7representing the &ekit |&7inorder to &epreview, claim or buy &7it."
interface.selector.details = "&7Hello &e%player%&7!|&7Listed below are our server's kits.||&7Click on the &eicon &7representing the &ekit |&7inorder to &epreview, claim or buy &7it."
interface.selector.aboutkitprice = "&7This kit costs &a$%price%&7."
interface.selector.aboutkit = "&7Can't open a kit?|&7Rank up to gain access!"
interface.selector.leftpreview = "&6&lLEFT CLICK &7to preview kit."
interface.selector.rightclaim = "&6&lRIGHT CLICK &7to claim kit."
interface.selector.rightbuy = "&6&lRIGHT CLICK &7to buy kit."
interface.selector.cost = "&7This kit costs &a$%cost%&7."
interface.selector.middleclick = "&6Middle Click &7to edit positioning."
interface.selector.adminlore = "&6Middle Click &7to edit positioning."
interface.selector.editlore = "&6&lEdit Mode||&6Left Click &7to move kit left|&6Right Click &7to move kit right||&6Middle Click &7to go back."
interface.hologram.previewonly = "Click to Preview!"
interface.hologram.preview = "Right-Click to Preview!"
interface.hologram.buylink = "Left-Click for Buy Link!"
@ -40,11 +41,105 @@ interface.key.description2 = "&rand receive its contents!"
interface.key.description3 = "&rand receive some of its contents!"
interface.key.description4 = "&rGives kit &c&l%amt% &rtimes."
# Administrative interfaces
interface.kitblock.title = "&8This contains &a%kit%"
interface.kitblock.switchtype = "&5&lSwitch kit type"
interface.kitblock.switchtypelore = "&7Click to swap this kit blocks function.|Preview|Crate|Claim"
interface.kitblock.decor = "&9&lDecor Options"
interface.kitblock.decorlore = "&7Click to edit the decoration|&7options for this kit."
interface.kitblock.edit = "&a&lEdit kit"
interface.kitblock.editlore = "&7Click to edit the kit|&7contained in this block."
interface.kitdecor.title = "&8Editing decor for &a%kit%&8.
interface.kitdecor.hologram = "&9&lToggle Holograms"
interface.kitdecor.particle = "&9&lToggle Particles"
interface.kitdecor.display = "&9&lToggle DisplayItems"
interface.kitdecor.displayone = "&9&lToggle DisplayItem Override"
interface.kitdecor.displayonelore = "%enabled%||&7Enabling this option will|&7override the DisplayItems|&7above your kit to the single|&7DisplayItem set in this kit|&7GUI options."
interface.kitdecor.settingon = "&7Currently: &aEnabled&7."
interface.kitdecor.settingoff = "&7Currently &cDisabled&7."
interface.kitsell.title = "&8Selling Options for &a%kit%&8."
interface.kitsell.nosell = "&c&lSet not for sale"
interface.kitsell.nosellon = "&7Currently &aFor Sale&7."
interface.kitsell.noselloff = "&7Currently &cNot For Sale&7."
interface.kitsell.noselllore = "%onoff%||&7Clicking this option will|&7remove this kit from sale."
interface.kitsell.link = "&a&lSet kit link"
interface.kitsell.linkon = "&7Currently: &a%kit%&7."
interface.kitsell.linkoff = "&7Currently: &cNot set&7."
interface.kitsell.linklore = "%onoff%||&7Clicking this option will|&7allow you to set a link|&7that players will receive|&7when attempting to purchase|&7this kit."
interface.kitsell.linkprompt = "Kit to link:"
interface.kitsell.linknoeco = "&8ECO has been removed from this kit. Note you cannot have ECO & LINK set at the same time.."
interface.kitsell.price = "&a&lSet kit price"
interface.kitsell.priceon = "&7Currently: &a$%price%&7."
interface.kitsell.priceoff = "&7Currently: &cNot set&7."
interface.kitsell.pricelore = "%onoff%||&7Clicking this option will|&7allow you to set a price|&7that players will be able to|&7purchase this kit for|&7requires a compatible economy plugin&7."
interface.kitsell.pricenoeco = "&8You must have an economy plugin installed to utilize economy.."
interface.kitsell.priceprompt = "Set Price:"
interface.kitsell.pricenonumber = "&a%input% &8is not a positive number."
interface.kitsell.pricenolink = "&8LINK has been removed from this kit. Note you cannot have ECO & LINK set at the same time.."
interface.kitguioptions.title = "&8GUI Options for &a%kit%&8."
interface.kitguioptions.holo = "&9&lSet Title"
interface.kitguioptions.holoon = "&7Currently: &a%title%&7."
interface.kitguioptions.holooff = "&7Currently: &cNot set&7."
interface.kitguioptions.hololore = "%onoff%||&7Left-Click: &9to set|&9the kit title for holograms|&9and the kit / kit selector GUIs.||&7Right-Click: &9to reset."
interface.kitguioptions.holoprompt = "Set Title:"
interface.kitguioptions.holoset = "&8Title &5%title%&8 added to Kit &a%kit%&8."
interface.kitguioptions.item = "&9&lSet DisplayItem"
interface.kitguioptions.itemon = "&7Currently set to: &a%item%&7."
interface.kitguioptions.itemoff = "&7Currently &cDisabled&7."
interface.kitguioptions.itemlore = "%onoff%||&7Left-Click to: &9Set a|&9display item for this kit|&9to the item in your hand.||&7Right-Click to: &9Remove the item."
interface.kitguioptions.itemnoitem = "&8You must be holding an item to use this function."
interface.kitguioptions.itemset = "&8Custom Item Display set for kit &a%item%&8."
interface.kitguioptions.itemremoved = "&8Custom Item Display removed from kit &a%kit%&8."
interface.kitguioptions.hide = "&9&lHide kit"
interface.kitguioptions.hideon = "&7Currently: &cHidden&7."
interface.kitguioptions.hideoff = "&7Currently: &aVisible&7."
interface.kitguioptions.hidelore = "%onoff%||&7A hidden kit will not|&7show up in the /kit gui.|&7This is usually optimal for|&7preventing players from seeing|&7non obtainable kit or starter kit."
interface.kitoptions.title = "&8General Options for &a%kit%&8."
interface.kitoptions.delay = "&9&lChange Delay"
interface.kitoptions.delaylore = "&7Currently set to: &a%delay%&7.||&7Use this to alter this kit delay.||&7Use &6-1 &7to make this kit single|&7use only."
interface.kitoptions.delayprompt = "Delay in Seconds:"
interface.kitoptions.delaynonumber = "&a%input% &8is not a number."
interface.kitoptions.destroy = "&c&lDestroy Kit"
interface.kitoptions.destroylore = "|&7Click this to destroy this kit."
interface.kitoptions.destroyprompt = "Enter \"%kit%\""
interface.kitoptions.destroyok = "&cKit destroyed successfully."
interface.kitoptions.destroycancel = "&cKit was not Destroyed."
interface.kiteditor.title = "&8You are editing kit: &9%name%&8."
interface.kiteditor.info = "&5&l%kit%|&fPermissions:|&7%perm%"
interface.kiteditor.generaloptions = "&6General Options"
interface.kiteditor.generaloptionslore = "&7Click to edit adjust|&7general options."
interface.kiteditor.sellingoptions = "&9Selling Options"
interface.kiteditor.sellingoptionslore = "&7Click to edit adjust|&7selling options."
interface.kiteditor.guioptions = "&5GUI Options"
interface.kiteditor.guioptionslore = "&7Click to edit GUI options|&7for this kit."
interface.kiteditor.addcommand = "&fAdd Command"
interface.kiteditor.addcommandlore = "&7Click to add a command|&7to this kit."
interface.kiteditor.addcommandprompt = "Enter Command (No /)"
interface.kiteditor.addcommandok = "&8Command &5%command%&8 has been added to your kit."
interface.kiteditor.addeconomy = "&6Add Economy"
interface.kiteditor.addeconomylore = "&7Click to add money|&7to this kit."
interface.kiteditor.addeconomyprompt = "Enter Price (No $)"
interface.kiteditor.addeconomyok = "&8Money &5$%amount%&8 has been added to your kit."
interface.kiteditor.animation = "&6Kit Animation"
interface.kiteditor.animationlore = "&7Currently: &6%animation%"
interface.kiteditor.itemediting = "&6Switch To Item Editing"
interface.kiteditor.itemeditinglore = "&7Click to enable|&7item editing."
interface.kiteditor.itemmoving = "&6Switch To Item Moving"
interface.kiteditor.itemmovinglore = "&7Click to switch back|&7to item moving."
interface.kiteditor.switchtoinventory = "&6Switch To Your Inventory"
interface.kiteditor.switchtoinventorylore = "&7Click to switch to|&7your inventory."
interface.kiteditor.switchtokitfunctions = "&6Switch To Kit Functions"
interface.kiteditor.switchtokitfunctionslore = "&7Click to switch back|&7to the kit functions."
interface.kiteditor.itemfunctionlore = "&7Display Item: &6%item%|&7Display Name: &6%name%|&7Display Lore: &6||&7Left-Click: &6To set a display item.|&7Middle-Click: &6To set a display name.|&7Right-Click: &6To set display lore.|&7Shift-Click: &6To set chance.||&7Display options only show up on display.|&7This can be useful if you want to explain|&7What an item does without putting it in the|&7permanent lore.||&6Leave function mode to move items."
interface.kiteditor.saved = "&8Changes to &a%kit% &8saved successfully."
#Command Messages
command.general.noperms = "&cYou do not have permission to do that!"
command.kit.nokitsupplied = "&7Please include a kit to preview."
command.kit.kitdoesntexist = "&cThat kit does not exist."
command.kit.nokitatblock = "&8This block does not contain a kit."
command.kit.kitalreadyexists = "&cThat kit already exists."
command.kit.playernotfound = "&cThis player is not online or doesn't exist."
@ -65,6 +160,6 @@ event.claim.noaccess = "&7Cooldown: &cNo Access.."
event.claim.full = "&cYour inventory is too full to claim this kit!"
event.create.won = "&7You got a &6%item%&7."
event.crate.wrongkey = "&cThis key doesn't belong to this kit.."
event.purchase.cancelled = "&cPurchase Cancelled."
event.purchase.cancelled = "&cPurchase Canceled."
event.key.given = "&9You have received a &a%kit% &9kit key."
event.key.success = "&9You have successfully redeemed a key for the kit &7%kit%&9."

View File

@ -1,7 +1,7 @@
name: UltimateKits
main: com.songoda.ultimatekits.UltimateKits
version: maven-version-number
softdepend: [HolographicDisplays, PlaceholderAPI, Vault, UltimateCore, Essentials, MiniKitPvP]
softdepend: [HolographicDisplays, Holograms, CMI, Vault, PlayerPoints, Reserve, PlaceholderAPI, UltimateCore, Essentials, MiniKitPvP]
description: View a kit before you purchase it!
author: Songoda
api-version: 1.13