replace most Material with ItemType

This commit is contained in:
alexcrea 2025-07-27 10:48:40 +02:00
parent dedca9b940
commit 239dbed5e0
Signed by: alexcrea
GPG key ID: E346CD16413450E3
65 changed files with 713 additions and 551 deletions

View file

@ -352,8 +352,8 @@ public class ConflictBuilder {
* @return An Enchant conflict group with this builder parameters. * @return An Enchant conflict group with this builder parameters.
*/ */
public EnchantConflictGroup build() { public EnchantConflictGroup build() {
AbstractItemTypeGroup materials = extractGroups(); AbstractItemTypeGroup groups = extractGroups();
EnchantConflictGroup conflict = new EnchantConflictGroup(getName(), materials, getMaxBeforeConflict()); EnchantConflictGroup conflict = new EnchantConflictGroup(getName(), groups, getMaxBeforeConflict());
appendEnchantments(conflict); appendEnchantments(conflict);
return conflict; return conflict;
@ -441,15 +441,15 @@ public class ConflictBuilder {
IncludeItemTypeGroup group = new IncludeItemTypeGroup(EnchantConflictManager.DEFAULT_GROUP_NAME); IncludeItemTypeGroup group = new IncludeItemTypeGroup(EnchantConflictManager.DEFAULT_GROUP_NAME);
for (String groupName : getExcludedGroupNames()) { for (String groupName : getExcludedGroupNames()) {
AbstractItemTypeGroup materialGroup = itemGroupManager.get(groupName); AbstractItemTypeGroup typeGroup = itemGroupManager.get(groupName);
if (materialGroup == null) { if (typeGroup == null) {
CustomAnvil.instance.getLogger().warning("Material group " + groupName + " do not exist but is ask by conflict " + getName()); CustomAnvil.instance.getLogger().warning("Material group " + groupName + " do not exist but is ask by conflict " + getName());
ConflictAPI.logConflictOrigin(this); ConflictAPI.logConflictOrigin(this);
continue; continue;
} }
group.addToPolicy(materialGroup); group.addToPolicy(typeGroup);
} }
return group; return group;

View file

@ -14,12 +14,15 @@ import xyz.alexcrea.cuanvil.group.IncludeItemTypeGroup;
import xyz.alexcrea.cuanvil.group.ItemGroupManager; import xyz.alexcrea.cuanvil.group.ItemGroupManager;
import xyz.alexcrea.cuanvil.gui.config.global.GroupConfigGui; import xyz.alexcrea.cuanvil.gui.config.global.GroupConfigGui;
import java.util.*; import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* Custom Anvil api for material group registry. * Custom Anvil api for material group registry.
*/ */
@SuppressWarnings({"unused", "UnstableApiUsage"}) @SuppressWarnings({"unused"})
public class MaterialGroupApi { public class MaterialGroupApi {
private MaterialGroupApi() { private MaterialGroupApi() {

View file

@ -2,14 +2,15 @@ package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import kotlin.Triple; import kotlin.Triple;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.dependency.DependencyManager; import xyz.alexcrea.cuanvil.dependency.DependencyManager;
import xyz.alexcrea.cuanvil.gui.config.global.UnitRepairConfigGui; import xyz.alexcrea.cuanvil.gui.config.global.UnitRepairConfigGui;
import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui; import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui;
import xyz.alexcrea.cuanvil.util.ItemTypeUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -31,11 +32,11 @@ public class UnitRepairApi {
* Will not write the recipe if it already exists or was deleted. * Will not write the recipe if it already exists or was deleted.
* Set the value to minecraft default value (0.25 = 25%) * Set the value to minecraft default value (0.25 = 25%)
* *
* @param unit The unit material used to repair the bellow item. * @param unit The unit type used to repair the bellow item.
* @param repairable The item to be repaired. * @param repairable The item to be repaired.
* @return true if successful. * @return true if successful.
*/ */
public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable) { public static boolean addUnitRepair(@NotNull ItemType unit, @NotNull ItemType repairable) {
return addUnitRepair(unit, repairable, 0.25, false); return addUnitRepair(unit, repairable, 0.25, false);
} }
@ -48,7 +49,7 @@ public class UnitRepairApi {
* @param value The amount to be repaired by every unit. (1% = 0.01) * @param value The amount to be repaired by every unit. (1% = 0.01)
* @return true if successful. * @return true if successful.
*/ */
public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value) { public static boolean addUnitRepair(@NotNull ItemType unit, @NotNull ItemType repairable, double value) {
return addUnitRepair(unit, repairable, value, false); return addUnitRepair(unit, repairable, value, false);
} }
@ -56,15 +57,15 @@ public class UnitRepairApi {
* Write and add a custom anvil unit repair recipe. * Write and add a custom anvil unit repair recipe.
* Will not write the recipe if it already exists. * Will not write the recipe if it already exists.
* *
* @param unit The unit material used to repair the bellow item. * @param unit The unit type used to repair the bellow item.
* @param repairable The item to be repaired. * @param repairable The item to be repaired.
* @param value The amount to be repaired by every unit. (1% = 0.01) * @param value The amount to be repaired by every unit. (1% = 0.01)
* @param overrideDeleted If we should write even if the recipe was previously deleted. * @param overrideDeleted If we should write even if the recipe was previously deleted.
* @return true if successful. * @return true if successful.
*/ */
public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value, boolean overrideDeleted) { public static boolean addUnitRepair(@NotNull ItemType unit, @NotNull ItemType repairable, double value, boolean overrideDeleted) {
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
String path = unit.name().toLowerCase() + "." + repairable.name().toLowerCase(); String path = unit.getKey() + "." + repairable.getKey();
if (!overrideDeleted && ConfigHolder.UNIT_REPAIR_HOLDER.isDeleted(path)) return false; if (!overrideDeleted && ConfigHolder.UNIT_REPAIR_HOLDER.isDeleted(path)) return false;
if (config.contains(path)) return false; if (config.contains(path)) return false;
@ -77,16 +78,15 @@ public class UnitRepairApi {
* Write and add a custom anvil unit repair recipe. * Write and add a custom anvil unit repair recipe.
* Do not check if it previously existed or exist. * Do not check if it previously existed or exist.
* *
* @param unit The unit material used to repair the bellow item. * @param unit The unit type used to repair the bellow item.
* @param repairable The item to be repaired. * @param repairable The item to be repaired.
* @param value The amount to be repaired by every unit. (1% = 0.01) * @param value The amount to be repaired by every unit. (1% = 0.01)
* @return true if successful. * @return true if successful.
*/ */
public static boolean setUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value) { public static boolean setUnitRepair(@NotNull ItemType unit, @NotNull ItemType repairable, double value) {
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
String repairableName = repairable.name().toLowerCase(); String path = unit.getKey() + "." + repairable.getKey();
String path = unit.name().toLowerCase() + "." + repairableName;
// Add to config then prepare save // Add to config then prepare save
config.set(path, value); config.set(path, value);
@ -97,7 +97,7 @@ public class UnitRepairApi {
if (repairConfigGui != null) { if (repairConfigGui != null) {
UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored(); UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored();
if (elementGui != null) elementGui.updateValueForGeneric(repairableName, true); if (elementGui != null) elementGui.updateValueForGeneric(repairable, true);
repairConfigGui.updateValueForGeneric(unit, true); repairConfigGui.updateValueForGeneric(unit, true);
} }
@ -107,43 +107,40 @@ public class UnitRepairApi {
/** /**
* Remove a custom anvil unit repair recipe. * Remove a custom anvil unit repair recipe.
* *
* @param unit The unit material used to repair the bellow item. * @param unit The unit type used to repair the bellow item.
* @param repairable The item used to be repaired. * @param repairable The item used to be repaired.
* @return true if successful. * @return true if successful.
*/ */
public static boolean removeUnitRepair(@NotNull Material unit, @NotNull Material repairable) { public static boolean removeUnitRepair(@NotNull ItemType unit, @NotNull ItemType repairable) {
// Delete every possible variation and save to file // Delete every possible variation and save to file
String unitName = unit.name();
String repairableName = repairable.name();
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
config.set(unitName.toLowerCase() + "." + repairableName.toUpperCase(), null); config.set(unit.getKey() + "." + repairable.getKey(), null);
config.set(unitName.toUpperCase() + "." + repairableName.toLowerCase(), null); config.set(unit.getKey().getKey() + "." + repairable.getKey().getKey(), null);
config.set(unitName.toUpperCase() + "." + repairableName.toUpperCase(), null); config.set(unit.getKey().getKey() + "." + repairable.getKey(), null);
config.set(unitName.toLowerCase() + "." + repairableName.toLowerCase(), null); config.set(unit.getKey() + "." + repairable.getKey().getKey(), null);
// Test if it was the last value of this section // Test if it was the last value of this section
boolean lastValue = false; boolean lastValue = false;
if (config.isConfigurationSection(unitName.toLowerCase())) { if (config.isConfigurationSection(unit.getKey().toString())) {
ConfigurationSection section = config.getConfigurationSection(unitName.toLowerCase()); ConfigurationSection section = config.getConfigurationSection(unit.getKey().toString());
if (section != null && section.getKeys(false).isEmpty()) { if (section != null && section.getKeys(false).isEmpty()) {
lastValue = true; lastValue = true;
config.set(unitName.toLowerCase(), null); config.set(unit.getKey().toString(), null);
} }
} else if (config.isConfigurationSection(unitName.toUpperCase())) { } else if (config.isConfigurationSection(unit.getKey().getKey())) {
ConfigurationSection section = config.getConfigurationSection(unitName.toUpperCase()); ConfigurationSection section = config.getConfigurationSection(unit.getKey().getKey());
if (section != null && section.getKeys(false).isEmpty()) { if (section != null && section.getKeys(false).isEmpty()) {
lastValue = true; lastValue = true;
config.set(unitName.toUpperCase(), null); config.set(unit.getKey().getKey(), null);
} }
} else lastValue = true; } else lastValue = true;
// We only need to "delete" as the lower case to be counted as deleted // We only need to "delete" as the primary path to be counted as deleted
ConfigHolder.UNIT_REPAIR_HOLDER.delete(unitName.toLowerCase() + "." + repairableName.toLowerCase()); ConfigHolder.UNIT_REPAIR_HOLDER.delete(unit.getKey() + "." + repairable.getKey());
prepareSaveTask(); prepareSaveTask();
// Remove from gui // Remove from gui
@ -151,7 +148,7 @@ public class UnitRepairApi {
if (repairConfigGui != null) { if (repairConfigGui != null) {
UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored(); UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored();
if (elementGui != null) elementGui.removeGeneric(repairableName); if (elementGui != null) elementGui.removeGeneric(repairable);
if (lastValue) { if (lastValue) {
repairConfigGui.removeGeneric(unit); repairConfigGui.removeGeneric(unit);
} }
@ -179,23 +176,23 @@ public class UnitRepairApi {
* <p> * <p>
* Each element of the provided triple represent a part of the recipe * Each element of the provided triple represent a part of the recipe
* <ul> * <ul>
* <li>First object is the unit material used to repair the bellow item. * <li>First object is the unit item type used to repair the bellow item.
* <li>Second object is the item to be repaired. * <li>Second object is the item type of the item to be repaired.
* <li>Last object is the amount to be repaired by every unit. (1% = 0.01) * <li>Last object is the amount to be repaired by every unit. (1% = 0.01)
* </ul> * </ul>
*/ */
@NotNull @NotNull
public static List<Triple<Material, Material, Double>> getUnitRepairs() { public static List<Triple<ItemType, ItemType, Double>> getUnitRepairs() {
List<Triple<Material, Material, Double>> mutableList = new ArrayList<>(); List<Triple<ItemType, ItemType, Double>> mutableList = new ArrayList<>();
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
for (String unitKey : config.getKeys(false)) { for (String unitKey : config.getKeys(false)) {
// Test if config section exist // Test if config section exist
if (!config.isConfigurationSection(unitKey)) continue; if (!config.isConfigurationSection(unitKey)) continue;
// Test if unit is a material // Test if unit is a correct item type
Material unit = Material.getMaterial(unitKey.toUpperCase()); ItemType unit = ItemTypeUtil.INSTANCE.getItemType(unitKey);
if (unit == null) continue; if(unit == null) continue;
// Iterate over reparable items // Iterate over reparable items
ConfigurationSection section = config.getConfigurationSection(unitKey); ConfigurationSection section = config.getConfigurationSection(unitKey);
@ -205,7 +202,7 @@ public class UnitRepairApi {
if (!section.isDouble(repairableKey)) continue; if (!section.isDouble(repairableKey)) continue;
// Test if repairable is valid a material // Test if repairable is valid a material
Material repairable = Material.getMaterial(repairableKey.toUpperCase()); ItemType repairable = ItemTypeUtil.INSTANCE.getItemType(repairableKey);
if (repairable == null) continue; if (repairable == null) continue;
// Add the values // Add the values

View file

@ -1,7 +1,7 @@
package xyz.alexcrea.cuanvil.enchant; package xyz.alexcrea.cuanvil.enchant;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Map; import java.util.Map;
@ -11,24 +11,24 @@ public interface AdditionalTestEnchantment {
/** /**
* Test if the provided enchantments can be compatible with this enchantment. only non-Custom Anvil conflict. * Test if the provided enchantments can be compatible with this enchantment. only non-Custom Anvil conflict.
* @param enchantments Immutable map of validated enchantments for the item. * @param enchantments Immutable map of validated enchantments for the item.
* @param itemMat Material of the tested item. * @param type Type of the tested item.
* @return If there is a conflict with the enchantments. * @return If there is a conflict with the enchantments.
*/ */
boolean isEnchantConflict( boolean isEnchantConflict(
@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull Map<CAEnchantment, Integer> enchantments,
@NotNull Material itemMat); @NotNull ItemType type);
/** /**
* Test if the provided item can be compatible with this enchantment. only non-Custom Anvil conflict. * Test if the provided item can be compatible with this enchantment. only non-Custom Anvil conflict.
* @param enchantments Immutable map of validated enchantments for the item. * @param enchantments Immutable map of validated enchantments for the item.
* @param itemMat Material of the tested item. * @param type Type of the tested item.
* @param item Provide a new instance of the used item stack with the partial enchantment applied. * @param item Provide a new instance of the used item stack with the partial enchantment applied.
* @return If there is a conflict with the enchantment and the item. * @return If there is a conflict with the enchantment and the item.
*/ */
boolean isItemConflict( boolean isItemConflict(
@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull Map<CAEnchantment, Integer> enchantments,
@NotNull Material itemMat, @NotNull ItemType type,
@NotNull ItemStack item); @NotNull ItemStack item);
} }

View file

@ -3,9 +3,9 @@ package xyz.alexcrea.cuanvil.enchant.bulk;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import io.delilaheve.util.ItemUtil; import io.delilaheve.util.ItemUtil;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -14,6 +14,7 @@ import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import java.util.Map; import java.util.Map;
@SuppressWarnings("UnstableApiUsage")
public class BukkitEnchantBulkOperation implements BulkGetEnchantOperation, BulkCleanEnchantOperation { public class BukkitEnchantBulkOperation implements BulkGetEnchantOperation, BulkCleanEnchantOperation {
@Override @Override
@ -45,7 +46,8 @@ public class BukkitEnchantBulkOperation implements BulkGetEnchantOperation, Bulk
@Override @Override
public void bulkClear(@NotNull ItemStack item) { public void bulkClear(@NotNull ItemStack item) {
if (item.getType() != Material.ENCHANTED_BOOK || ConfigOptions.INSTANCE.getAddBookEnchantmentAsStoredEnchantment()) { if (item.getType().asItemType() != ItemType.ENCHANTED_BOOK ||
ConfigOptions.INSTANCE.getAddBookEnchantmentAsStoredEnchantment()) {
item.getEnchantments().forEach((enchantment, level) -> item.getEnchantments().forEach((enchantment, level) ->
item.removeEnchantment(enchantment) item.removeEnchantment(enchantment)
@ -55,7 +57,7 @@ public class BukkitEnchantBulkOperation implements BulkGetEnchantOperation, Bulk
@Override @Override
public void bulkClear(@NotNull ItemStack item, @NotNull ItemMeta meta) { public void bulkClear(@NotNull ItemStack item, @NotNull ItemMeta meta) {
if (item.getType() == Material.ENCHANTED_BOOK) { if (item.getType().asItemType() == ItemType.ENCHANTED_BOOK) {
EnchantmentStorageMeta bookMeta = (EnchantmentStorageMeta) meta; EnchantmentStorageMeta bookMeta = (EnchantmentStorageMeta) meta;
bookMeta.getStoredEnchants().forEach((enchantment, leve) -> bookMeta.getStoredEnchants().forEach((enchantment, leve) ->
bookMeta.removeStoredEnchant(enchantment) bookMeta.removeStoredEnchant(enchantment)

View file

@ -1,7 +1,7 @@
package xyz.alexcrea.cuanvil.enchant.wrapped; package xyz.alexcrea.cuanvil.enchant.wrapped;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import su.nightexpress.excellentenchants.api.enchantment.CustomEnchantment; import su.nightexpress.excellentenchants.api.enchantment.CustomEnchantment;
import su.nightexpress.excellentenchants.api.item.ItemSet; import su.nightexpress.excellentenchants.api.item.ItemSet;
@ -13,6 +13,7 @@ import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@SuppressWarnings("UnstableApiUsage")
public class CAEEV5Enchantment extends CABukkitEnchantment implements AdditionalTestEnchantment { public class CAEEV5Enchantment extends CABukkitEnchantment implements AdditionalTestEnchantment {
@NotNull CustomEnchantment eeenchantment; @NotNull CustomEnchantment eeenchantment;
@ -26,7 +27,7 @@ public class CAEEV5Enchantment extends CABukkitEnchantment implements Additional
} }
@Override @Override
public boolean isEnchantConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull Material itemMat) { public boolean isEnchantConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull ItemType type) {
if (!definition.hasConflicts()) return false; if (!definition.hasConflicts()) return false;
Set<String> conflicts = definition.getExclusiveSet(); Set<String> conflicts = definition.getExclusiveSet();
@ -39,10 +40,10 @@ public class CAEEV5Enchantment extends CABukkitEnchantment implements Additional
} }
@Override @Override
public boolean isItemConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull Material itemMat, @NotNull ItemStack item) { public boolean isItemConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull ItemType type, @NotNull ItemStack item) {
if (Material.ENCHANTED_BOOK.equals(itemMat)) return false; if (ItemType.ENCHANTED_BOOK.equals(type)) return false;
String key = itemMat.getKey().getKey(); String key = type.getKey().getKey();
ItemSet primary = eeenchantment.getPrimaryItems(); ItemSet primary = eeenchantment.getPrimaryItems();
if (primary.getMaterials().contains(key)) return false; if (primary.getMaterials().contains(key)) return false;

View file

@ -3,8 +3,8 @@ package xyz.alexcrea.cuanvil.enchant.wrapped;
import com.willfp.ecoenchants.enchant.EcoEnchant; import com.willfp.ecoenchants.enchant.EcoEnchant;
import com.willfp.ecoenchants.target.EnchantmentTarget; import com.willfp.ecoenchants.target.EnchantmentTarget;
import com.willfp.ecoenchants.type.EnchantmentType; import com.willfp.ecoenchants.type.EnchantmentType;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment; import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment; import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
@ -13,6 +13,7 @@ import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@SuppressWarnings("UnstableApiUsage")
public class CAEcoEnchant extends CABukkitEnchantment implements AdditionalTestEnchantment { public class CAEcoEnchant extends CABukkitEnchantment implements AdditionalTestEnchantment {
private final @NotNull EcoEnchant ecoEnchant; private final @NotNull EcoEnchant ecoEnchant;
@ -23,7 +24,7 @@ public class CAEcoEnchant extends CABukkitEnchantment implements AdditionalTestE
} }
@Override @Override
public boolean isEnchantConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull Material itemMat) { public boolean isEnchantConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull ItemType itemType) {
if (enchantments.isEmpty()) return false; if (enchantments.isEmpty()) return false;
if (this.ecoEnchant.getConflictsWithEverything()) { if (this.ecoEnchant.getConflictsWithEverything()) {
@ -57,9 +58,9 @@ public class CAEcoEnchant extends CABukkitEnchantment implements AdditionalTestE
@Override @Override
public boolean isItemConflict(@NotNull Map<CAEnchantment, Integer> enchantments, public boolean isItemConflict(@NotNull Map<CAEnchantment, Integer> enchantments,
@NotNull Material itemMat, @NotNull ItemType type,
@NotNull ItemStack item) { @NotNull ItemStack item) {
if (Material.ENCHANTED_BOOK.equals(itemMat)) { if (ItemType.ENCHANTED_BOOK.equals(type)) {
return false; return false;
} }

View file

@ -1,11 +1,13 @@
package xyz.alexcrea.cuanvil.enchant.wrapped; package xyz.alexcrea.cuanvil.enchant.wrapped;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.enchant.*; import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
import java.util.Map; import java.util.Map;
@ -24,12 +26,12 @@ public class CAIncompatibleAllEnchant extends CABukkitEnchantment implements Add
@Override @Override
public boolean isEnchantConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull Material itemMat) { public boolean isEnchantConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull ItemType type) {
return !enchantments.isEmpty() && !(enchantments.size() == 1 && enchantments.containsKey(this)); return !enchantments.isEmpty() && !(enchantments.size() == 1 && enchantments.containsKey(this));
} }
@Override @Override
public boolean isItemConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull Material itemMat, @NotNull ItemStack item) { public boolean isItemConflict(@NotNull Map<CAEnchantment, Integer> enchantments, @NotNull ItemType type, @NotNull ItemStack item) {
return false; return false;
} }
} }

View file

@ -5,8 +5,8 @@ import com.github.stefvanschie.inventoryframework.gui.type.ChestGui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase; import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase;
import xyz.alexcrea.cuanvil.gui.config.global.*; import xyz.alexcrea.cuanvil.gui.config.global.*;
@ -15,6 +15,7 @@ import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
import java.util.Collections; import java.util.Collections;
@SuppressWarnings("UnstableApiUsage")
public class MainConfigGui extends ChestGui { public class MainConfigGui extends ChestGui {
private static final MainConfigGui INSTANCE = new MainConfigGui(); private static final MainConfigGui INSTANCE = new MainConfigGui();
@ -39,7 +40,7 @@ public class MainConfigGui extends ChestGui {
GuiGlobalItems.addBackgroundItem(pane); GuiGlobalItems.addBackgroundItem(pane);
// Basic config item // Basic config item
ItemStack basicConfigItemstack = new ItemStack(Material.COMMAND_BLOCK); ItemStack basicConfigItemstack = ItemType.COMMAND_BLOCK.createItemStack();
ItemMeta basicConfigMeta = basicConfigItemstack.getItemMeta(); ItemMeta basicConfigMeta = basicConfigItemstack.getItemMeta();
assert basicConfigMeta != null; assert basicConfigMeta != null;
@ -51,7 +52,7 @@ public class MainConfigGui extends ChestGui {
pane.bindItem('1', basicConfigItem); pane.bindItem('1', basicConfigItem);
// enchant level limit item // enchant level limit item
ItemStack enchantLimitItemstack = new ItemStack(Material.ENCHANTED_BOOK); ItemStack enchantLimitItemstack = ItemType.ENCHANTED_BOOK.createItemStack();
ItemMeta enchantLimitMeta = enchantLimitItemstack.getItemMeta(); ItemMeta enchantLimitMeta = enchantLimitItemstack.getItemMeta();
assert enchantLimitMeta != null; assert enchantLimitMeta != null;
@ -63,7 +64,7 @@ public class MainConfigGui extends ChestGui {
pane.bindItem('2', enchantLimitItem); pane.bindItem('2', enchantLimitItem);
// enchant level limit item // enchant level limit item
ItemStack enchantMergeLimitItemstack = new ItemStack(Material.ENCHANTED_BOOK); ItemStack enchantMergeLimitItemstack = ItemType.ENCHANTED_BOOK.createItemStack();
ItemMeta enchantMergeLimitMeta = enchantMergeLimitItemstack.getItemMeta(); ItemMeta enchantMergeLimitMeta = enchantMergeLimitItemstack.getItemMeta();
assert enchantMergeLimitMeta != null; assert enchantMergeLimitMeta != null;
@ -75,7 +76,7 @@ public class MainConfigGui extends ChestGui {
pane.bindItem('3', enchantMergeLimitItem); pane.bindItem('3', enchantMergeLimitItem);
// enchant cost item // enchant cost item
ItemStack enchantCostItemstack = new ItemStack(Material.EXPERIENCE_BOTTLE); ItemStack enchantCostItemstack = ItemType.EXPERIENCE_BOTTLE.createItemStack();
ItemMeta enchantCostMeta = enchantCostItemstack.getItemMeta(); ItemMeta enchantCostMeta = enchantCostItemstack.getItemMeta();
assert enchantCostMeta != null; assert enchantCostMeta != null;
@ -87,7 +88,7 @@ public class MainConfigGui extends ChestGui {
pane.bindItem('4', enchantCostItem); pane.bindItem('4', enchantCostItem);
// Enchantment Conflicts item // Enchantment Conflicts item
ItemStack enchantConflictItemstack = new ItemStack(Material.OAK_FENCE); ItemStack enchantConflictItemstack = ItemType.OAK_FENCE.createItemStack();
ItemMeta enchantConflictMeta = enchantConflictItemstack.getItemMeta(); ItemMeta enchantConflictMeta = enchantConflictItemstack.getItemMeta();
assert enchantConflictMeta != null; assert enchantConflictMeta != null;
@ -99,7 +100,7 @@ public class MainConfigGui extends ChestGui {
pane.bindItem('5', enchantConflictItem); pane.bindItem('5', enchantConflictItem);
// Group config items // Group config items
ItemStack groupItemstack = new ItemStack(Material.CHEST); ItemStack groupItemstack = ItemType.CHEST.createItemStack();
ItemMeta groupMeta = groupItemstack.getItemMeta(); ItemMeta groupMeta = groupItemstack.getItemMeta();
assert groupMeta != null; assert groupMeta != null;
@ -112,7 +113,7 @@ public class MainConfigGui extends ChestGui {
pane.bindItem('6', groupConfigItem); pane.bindItem('6', groupConfigItem);
// Unit repair item // Unit repair item
ItemStack unirRepairItemstack = new ItemStack(Material.DIAMOND); ItemStack unirRepairItemstack = ItemType.DIAMOND.createItemStack();
ItemMeta unitRepairMeta = unirRepairItemstack.getItemMeta(); ItemMeta unitRepairMeta = unirRepairItemstack.getItemMeta();
assert unitRepairMeta != null; assert unitRepairMeta != null;
@ -124,7 +125,7 @@ public class MainConfigGui extends ChestGui {
pane.bindItem('7', unitRepairItem); pane.bindItem('7', unitRepairItem);
// Custom recipe item // Custom recipe item
ItemStack customRecipeItemstack = new ItemStack(Material.CRAFTING_TABLE); ItemStack customRecipeItemstack = ItemType.CRAFTING_TABLE.createItemStack();
ItemMeta customRecipeMeta = customRecipeItemstack.getItemMeta(); ItemMeta customRecipeMeta = customRecipeItemstack.getItemMeta();
assert customRecipeMeta != null; assert customRecipeMeta != null;
@ -136,7 +137,7 @@ public class MainConfigGui extends ChestGui {
pane.bindItem('8', customRecipeItem); pane.bindItem('8', customRecipeItem);
// quit item // quit item
ItemStack quitItemstack = new ItemStack(Material.BARRIER); ItemStack quitItemstack = ItemType.BARRIER.createItemStack();
ItemMeta quitMeta = quitItemstack.getItemMeta(); ItemMeta quitMeta = quitItemstack.getItemMeta();
assert quitMeta != null; assert quitMeta != null;

View file

@ -3,7 +3,10 @@ package xyz.alexcrea.cuanvil.gui.config;
import org.bukkit.inventory.ItemType; import org.bukkit.inventory.ItemType;
import xyz.alexcrea.cuanvil.util.CasedStringUtil; import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import java.util.*; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@SuppressWarnings("UnstableApiUsage") @SuppressWarnings("UnstableApiUsage")
public interface SelectItemTypeContainer { public interface SelectItemTypeContainer {

View file

@ -4,9 +4,9 @@ import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui; import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions; import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
@ -16,6 +16,7 @@ import java.util.Arrays;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.logging.Level; import java.util.logging.Level;
@SuppressWarnings("UnstableApiUsage")
public class ConfirmActionGui extends AbstractAskGui { public class ConfirmActionGui extends AbstractAskGui {
public ConfirmActionGui(@NotNull String title, String actionDescription, public ConfirmActionGui(@NotNull String title, String actionDescription,
@ -52,7 +53,7 @@ public class ConfirmActionGui extends AbstractAskGui {
}, CustomAnvil.instance)); }, CustomAnvil.instance));
// Info item // Info item
ItemStack infoItem = new ItemStack(Material.PAPER); ItemStack infoItem = ItemType.PAPER.createItemStack();
ItemMeta infoMeta = infoItem.getItemMeta(); ItemMeta infoMeta = infoItem.getItemMeta();
infoMeta.setDisplayName("§eAre you sure ?"); infoMeta.setDisplayName("§eAre you sure ?");

View file

@ -4,9 +4,9 @@ import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui; import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions; import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
@ -17,6 +17,7 @@ import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@SuppressWarnings("UnstableApiUsage")
public class SelectItemTypeGui extends AbstractAskGui { public class SelectItemTypeGui extends AbstractAskGui {
private ItemStack selectedItem; private ItemStack selectedItem;
@ -45,7 +46,7 @@ public class SelectItemTypeGui extends AbstractAskGui {
this.pane.bindItem('S', GuiGlobalItems.backgroundItem()); this.pane.bindItem('S', GuiGlobalItems.backgroundItem());
// Select item // Select item
ItemStack selectItem = setDisplayMeta(new ItemStack(Material.BARRIER), actionDescription); ItemStack selectItem = setDisplayMeta(ItemType.BARRIER.createItemStack(), actionDescription);
AtomicReference<GuiItem> selectGuiItem = new AtomicReference<>(); AtomicReference<GuiItem> selectGuiItem = new AtomicReference<>();
selectGuiItem.set(new GuiItem(selectItem, event -> { selectGuiItem.set(new GuiItem(selectItem, event -> {
@ -56,7 +57,9 @@ public class SelectItemTypeGui extends AbstractAskGui {
ItemStack finalItem; ItemStack finalItem;
if(materialOnly){ if(materialOnly){
finalItem = setDisplayMeta(new ItemStack(cursor.getType()), actionDescription); finalItem = setDisplayMeta(
cursor.getType().asItemType().createItemStack(),
actionDescription);
}else{ }else{
finalItem = cursor.clone(); finalItem = cursor.clone();
} }
@ -71,7 +74,7 @@ public class SelectItemTypeGui extends AbstractAskGui {
this.pane.bindItem('V', selectGuiItem.get()); this.pane.bindItem('V', selectGuiItem.get());
// Temporary leave item // Temporary leave item
GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(Material.YELLOW_STAINED_GLASS_PANE, this); GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(ItemType.YELLOW_STAINED_GLASS_PANE, this);
this.pane.bindItem('s', temporaryLeave); this.pane.bindItem('s', temporaryLeave);

View file

@ -8,8 +8,8 @@ import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import kotlin.ranges.IntRange; import kotlin.ranges.IntRange;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -32,6 +32,7 @@ import java.util.List;
/** /**
* Global config to edit basic basic settings. * Global config to edit basic basic settings.
*/ */
@SuppressWarnings("UnstableApiUsage")
public class BasicConfigGui extends ChestGui implements ValueUpdatableGui { public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
private static BasicConfigGui INSTANCE = null; private static BasicConfigGui INSTANCE = null;
@ -109,7 +110,7 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
"§7In other words:", "§7In other words:",
"§7For any anvil cost greater than §aMax Anvil Cost§7, Cost will be set to §aMax Anvil Cost§7."); "§7For any anvil cost greater than §aMax Anvil Cost§7, Cost will be set to §aMax Anvil Cost§7.");
// cap anvil cost not needed // cap anvil cost not needed
ItemStack item = new ItemStack(Material.BARRIER); ItemStack item = ItemType.BARRIER.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -134,7 +135,7 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
ConfigOptions.DEFAULT_MAX_ANVIL_COST, ConfigOptions.DEFAULT_MAX_ANVIL_COST,
1, 5, 10); 1, 5, 10);
// max anvil cost not needed // max anvil cost not needed
item = new ItemStack(Material.BARRIER); item = ItemType.BARRIER.createItemStack();
meta = item.getItemMeta(); meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -238,7 +239,7 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
"§7Give player §eca.color.hex§7 Permission to allow use of hexadecimal color."); "§7Give player §eca.color.hex§7 Permission to allow use of hexadecimal color.");
// Permission needed for color not necessary // Permission needed for color not necessary
item = new ItemStack(Material.BARRIER); item = ItemType.BARRIER.createItemStack();
meta = item.getItemMeta(); meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -262,7 +263,7 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
1, 5, 10, 50, 100); 1, 5, 10, 50, 100);
// Permission needed for color not necessary // Permission needed for color not necessary
item = new ItemStack(Material.BARRIER); item = ItemType.BARRIER.createItemStack();
meta = item.getItemMeta(); meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -300,7 +301,7 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
GuiItem maxAnvilCostItem; GuiItem maxAnvilCostItem;
if (!this.removeAnvilCostLimit.getConfiguredValue()) { if (!this.removeAnvilCostLimit.getConfiguredValue()) {
capAnvilCostItem = this.capAnvilCost.getItem("Cap Anvil Cost"); capAnvilCostItem = this.capAnvilCost.getItem("Cap Anvil Cost");
maxAnvilCostItem = this.maxAnvilCost.getItem(Material.EXPERIENCE_BOTTLE, "Max Anvil Cost"); maxAnvilCostItem = this.maxAnvilCost.getItem(ItemType.EXPERIENCE_BOTTLE, "Max Anvil Cost");
} else { } else {
capAnvilCostItem = this.noCapRepairItem; capAnvilCostItem = this.noCapRepairItem;
maxAnvilCostItem = this.noMaxCostItem; maxAnvilCostItem = this.noMaxCostItem;
@ -319,23 +320,23 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
// item repair cost // item repair cost
GuiItem itemRepairCostItem = this.itemRepairCost.getItem(Material.ANVIL); GuiItem itemRepairCostItem = this.itemRepairCost.getItem(ItemType.ANVIL);
pane.bindItem('I', itemRepairCostItem); pane.bindItem('I', itemRepairCostItem);
// unit repair cost // unit repair cost
GuiItem unitRepairCostItem = this.unitRepairCost.getItem(Material.DIAMOND); GuiItem unitRepairCostItem = this.unitRepairCost.getItem(ItemType.DIAMOND);
pane.bindItem('U', unitRepairCostItem); pane.bindItem('U', unitRepairCostItem);
// item rename cost // item rename cost
GuiItem itemRenameCostItem = this.itemRenameCost.getItem(Material.NAME_TAG); GuiItem itemRenameCostItem = this.itemRenameCost.getItem(ItemType.NAME_TAG);
pane.bindItem('r', itemRenameCostItem); pane.bindItem('r', itemRenameCostItem);
// sacrifice illegal enchant cost // sacrifice illegal enchant cost
GuiItem illegalCostItem = this.sacrificeIllegalEnchantCost.getItem(Material.ENCHANTED_BOOK); GuiItem illegalCostItem = this.sacrificeIllegalEnchantCost.getItem(ItemType.ENCHANTED_BOOK);
pane.bindItem('S', illegalCostItem); pane.bindItem('S', illegalCostItem);
// work penalty type // work penalty type
GuiItem workPenaltyType = WorkPenaltyTypeSettingGui.getDisplayItem(this, Material.DAMAGED_ANVIL, "§aWork Penalty Type"); GuiItem workPenaltyType = WorkPenaltyTypeSettingGui.getDisplayItem(this, ItemType.DAMAGED_ANVIL, "§aWork Penalty Type");
pane.bindItem('W', workPenaltyType); pane.bindItem('W', workPenaltyType);
// allow color code // allow color code
@ -353,7 +354,7 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
pane.bindItem('p', permissionNeededItem); pane.bindItem('p', permissionNeededItem);
// using color cost // using color cost
GuiItem useColorCostItem = this.useOfColorCost.getItem(Material.EXPERIENCE_BOTTLE, "Use color"); GuiItem useColorCostItem = this.useOfColorCost.getItem(ItemType.EXPERIENCE_BOTTLE, "Use color");
pane.bindItem('P', useColorCostItem); pane.bindItem('P', useColorCostItem);
} else { } else {
pane.bindItem('p', this.noPermissionNeededItem); pane.bindItem('p', this.noPermissionNeededItem);

View file

@ -1,9 +1,9 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import org.bukkit.Material;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -17,6 +17,7 @@ import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@SuppressWarnings("UnstableApiUsage")
public class CustomRecipeConfigGui extends MappedGuiListConfigGui<AnvilCustomRecipe, public class CustomRecipeConfigGui extends MappedGuiListConfigGui<AnvilCustomRecipe,
MappedGuiListConfigGui.LazyElement<CustomRecipeSubSettingGui>> { MappedGuiListConfigGui.LazyElement<CustomRecipeSubSettingGui>> {
@ -46,7 +47,7 @@ public class CustomRecipeConfigGui extends MappedGuiListConfigGui<AnvilCustomRec
ItemStack craftResultItem = recipe.getResultItem(); ItemStack craftResultItem = recipe.getResultItem();
ItemStack displayedItem; ItemStack displayedItem;
if (craftResultItem == null) { if (craftResultItem == null) {
displayedItem = new ItemStack(Material.BARRIER); displayedItem = ItemType.BARRIER.createItemStack();
} else { } else {
displayedItem = craftResultItem.clone(); displayedItem = craftResultItem.clone();
} }

View file

@ -1,8 +1,8 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
@ -19,6 +19,7 @@ import java.util.Locale;
/** /**
* Global Config gui for enchantment cost settings. * Global Config gui for enchantment cost settings.
*/ */
@SuppressWarnings("UnstableApiUsage")
public class EnchantCostConfigGui extends AbstractEnchantConfigGui<EnchantCostSettingsGui.EnchantCostSettingFactory> { public class EnchantCostConfigGui extends AbstractEnchantConfigGui<EnchantCostSettingsGui.EnchantCostSettingFactory> {
private static final String SECTION_NAME = "enchant_values"; private static final String SECTION_NAME = "enchant_values";
@ -62,7 +63,7 @@ public class EnchantCostConfigGui extends AbstractEnchantConfigGui<EnchantCostSe
int bookCost = factory.getConfiguredBookValue(); int bookCost = factory.getConfiguredBookValue();
String itemName = "§a" + factory.getTitle(); String itemName = "§a" + factory.getTitle();
// Create item // Create item
ItemStack item = new ItemStack(Material.ENCHANTED_BOOK); ItemStack item = ItemType.ENCHANTED_BOOK.createItemStack();
ItemMeta itemMeta = item.getItemMeta(); ItemMeta itemMeta = item.getItemMeta();
assert itemMeta != null; assert itemMeta != null;

View file

@ -2,7 +2,7 @@ package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material; import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment; import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
@ -15,6 +15,7 @@ import java.util.Locale;
/** /**
* Global Config gui for enchantment level limit settings. * Global Config gui for enchantment level limit settings.
*/ */
@SuppressWarnings("UnstableApiUsage")
public class EnchantLimitConfigGui extends AbstractEnchantConfigGui<IntSettingsGui.IntSettingFactory> { public class EnchantLimitConfigGui extends AbstractEnchantConfigGui<IntSettingsGui.IntSettingFactory> {
private static final String SECTION_NAME = "enchant_limits"; private static final String SECTION_NAME = "enchant_limits";
@ -60,7 +61,7 @@ public class EnchantLimitConfigGui extends AbstractEnchantConfigGui<IntSettingsG
@Override @Override
public GuiItem itemFromFactory(CAEnchantment enchantment, IntSettingsGui.IntSettingFactory inventoryFactory) { public GuiItem itemFromFactory(CAEnchantment enchantment, IntSettingsGui.IntSettingFactory inventoryFactory) {
return inventoryFactory.getItem( return inventoryFactory.getItem(
Material.ENCHANTED_BOOK, ItemType.ENCHANTED_BOOK,
inventoryFactory.getTitle()); inventoryFactory.getTitle());
} }

View file

@ -2,7 +2,7 @@ package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material; import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment; import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
@ -12,6 +12,7 @@ import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import java.util.Arrays; import java.util.Arrays;
import java.util.Locale; import java.util.Locale;
@SuppressWarnings("UnstableApiUsage")
public class EnchantMergeLimitConfigGui extends AbstractEnchantConfigGui<IntSettingsGui.IntSettingFactory> { public class EnchantMergeLimitConfigGui extends AbstractEnchantConfigGui<IntSettingsGui.IntSettingFactory> {
private static final String SECTION_NAME = "disable-merge-over"; private static final String SECTION_NAME = "disable-merge-over";
@ -61,7 +62,7 @@ public class EnchantMergeLimitConfigGui extends AbstractEnchantConfigGui<IntSett
@Override @Override
public GuiItem itemFromFactory(CAEnchantment enchantment, IntSettingsGui.IntSettingFactory inventoryFactory) { public GuiItem itemFromFactory(CAEnchantment enchantment, IntSettingsGui.IntSettingFactory inventoryFactory) {
return inventoryFactory.getItem( return inventoryFactory.getItem(
Material.ENCHANTED_BOOK, ItemType.ENCHANTED_BOOK,
inventoryFactory.getTitle()); inventoryFactory.getTitle());
} }
} }

View file

@ -2,9 +2,9 @@ package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -13,13 +13,15 @@ import xyz.alexcrea.cuanvil.gui.config.ask.SelectItemTypeGui;
import xyz.alexcrea.cuanvil.gui.config.list.MappedGuiListConfigGui; import xyz.alexcrea.cuanvil.gui.config.list.MappedGuiListConfigGui;
import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui; import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui;
import xyz.alexcrea.cuanvil.util.CasedStringUtil; import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import xyz.alexcrea.cuanvil.util.ItemTypeUtil;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet;
@SuppressWarnings("UnstableApiUsage")
public class UnitRepairConfigGui extends public class UnitRepairConfigGui extends
MappedGuiListConfigGui<Material, MappedGuiListConfigGui.LazyElement<UnitRepairElementListGui>> { MappedGuiListConfigGui<ItemType, MappedGuiListConfigGui.LazyElement<UnitRepairElementListGui>> {
private static UnitRepairConfigGui INSTANCE; private static UnitRepairConfigGui INSTANCE;
@ -42,33 +44,51 @@ public class UnitRepairConfigGui extends
} }
@Override @Override
protected LazyElement<UnitRepairElementListGui> newInstanceOfGui(Material material, GuiItem item) { protected LazyElement<UnitRepairElementListGui> newInstanceOfGui(ItemType type, GuiItem item) {
return new LazyElement<>(item, () -> { return new LazyElement<>(item, () -> {
UnitRepairElementListGui element = new UnitRepairElementListGui(material, this); UnitRepairElementListGui element = new UnitRepairElementListGui(type, this);
element.init(); element.init();
return element; return element;
}); });
} }
@Override private void aggregateFromSection(HashSet<ItemType> set, String sectionName){
protected ItemStack createItemForGeneric(Material material) { ConfigurationSection section = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getConfigurationSection(sectionName);
ConfigurationSection materialSection = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getConfigurationSection(material.name().toLowerCase()); if(section == null) return;
String materialName = CasedStringUtil.snakeToUpperSpacedCase(material.name().toLowerCase());
if(material.isAir()){ for (String key : section.getKeys(false)) {
material = Material.BARRIER; ItemType type = ItemTypeUtil.INSTANCE.getItemTypeExact(key);
if(type != null) set.add(type);
}
}
private int numberOfChildren(ItemType type){
HashSet<ItemType> set = new HashSet<>();
aggregateFromSection(set, type.getKey().toString());
aggregateFromSection(set, type.getKey().getKey());
return set.size();
}
@Override
protected ItemStack createItemForGeneric(ItemType type) {
String typeName = CasedStringUtil.snakeToUpperSpacedCase(ItemTypeUtil.INSTANCE.name(type));
if(type == ItemType.AIR){
type = ItemType.BARRIER;
} }
int reparableItemCount = materialSection == null ? 0 : materialSection.getKeys(false).size(); // Probably an expensive call but... why not int reparableItemCount = numberOfChildren(type);
ItemStack item = new ItemStack(material); ItemStack item = type.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
meta.setDisplayName("§eRepaired by " +materialName); meta.setDisplayName("§eRepaired by " +typeName);
meta.setLore(Arrays.asList( meta.setLore(Arrays.asList(
"§7There is currently §e" +reparableItemCount+ " §7reparable item with "+materialName, "§7There is currently §e" +reparableItemCount+ " §7reparable item with "+typeName,
"§7Click here to open the menu to edit reparable item by " + materialName "§7Click here to open the menu to edit reparable item by " + typeName
)); ));
item.setItemMeta(meta); item.setItemMeta(meta);
@ -77,29 +97,29 @@ public class UnitRepairConfigGui extends
} }
@Override @Override
protected Collection<Material> getEveryDisplayableInstanceOfGeneric() { protected Collection<ItemType> getEveryDisplayableInstanceOfGeneric() {
ArrayList<Material> materials = new ArrayList<>(); HashSet<ItemType> types = new HashSet<>(); // we need set to avoid duplicate
for (String matName : ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getKeys(false)) { for (String typeName : ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getKeys(false)) {
Material mat = Material.getMaterial(matName.toUpperCase()); ItemType type = ItemTypeUtil.INSTANCE.getItemTypeExact(typeName);
if(mat != null){ if(type != null){
materials.add(mat); types.add(type);
} }
} }
return materials; return types;
} }
@Override @Override
protected GuiItem prepareCreateNewItem() { protected GuiItem prepareCreateNewItem() {
// Create new conflict item // Create new conflict item
ItemStack createItem = new ItemStack(Material.PAPER); ItemStack createItem = ItemType.PAPER.createItemStack();
ItemMeta createMeta = createItem.getItemMeta(); ItemMeta createMeta = createItem.getItemMeta();
assert createMeta != null; assert createMeta != null;
createMeta.setDisplayName("§aSelect a new unit material"); createMeta.setDisplayName("§aSelect a new unit type");
createMeta.setLore(Arrays.asList( createMeta.setLore(Arrays.asList(
"§7Select a new unit material to be used.", "§7Select a new unit to be used.",
"§7You will be asked the material to use." "§7You will be asked the item/item type to use."
)); ));
createItem.setItemMeta(createMeta); createItem.setItemMeta(createMeta);
@ -113,11 +133,11 @@ public class UnitRepairConfigGui extends
"§7You like to be an unit repair item", "§7You like to be an unit repair item",
this, this,
(itemStack, player) -> { (itemStack, player) -> {
Material type = itemStack.getType(); ItemType type = itemStack.getType().asItemType();
// Add new material // Add new item type
updateValueForGeneric(type, true); updateValueForGeneric(type, true);
// Display material edit setting // Display item type edit setting
this.elementGuiMap.get(type).get().getMappedGui().show(player); this.elementGuiMap.get(type).get().getMappedGui().show(player);
}, },
true true
@ -126,7 +146,7 @@ public class UnitRepairConfigGui extends
} }
@NotNull @NotNull
public LazyElement<UnitRepairElementListGui> getInstanceOrCreate(Material mat){ public LazyElement<UnitRepairElementListGui> getInstanceOrCreate(ItemType mat){
LazyElement<UnitRepairElementListGui> element = this.elementGuiMap.get(mat); LazyElement<UnitRepairElementListGui> element = this.elementGuiMap.get(mat);
if(element == null){ if(element == null){
updateValueForGeneric(mat, false); updateValueForGeneric(mat, false);
@ -142,7 +162,7 @@ public class UnitRepairConfigGui extends
return "this function Should not be used."; return "this function Should not be used.";
} }
@Override // Not used in this implementation. @Override // Not used in this implementation.
protected Material createAndSaveNewEmptyGeneric(String name) { protected ItemType createAndSaveNewEmptyGeneric(String name) {
return null; return null;
} }
} }

View file

@ -9,10 +9,10 @@ import com.github.stefvanschie.inventoryframework.pane.Pane;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui; import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
@ -24,6 +24,7 @@ import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.UUID; import java.util.UUID;
@SuppressWarnings("UnstableApiUsage")
public abstract class ElementListConfigGui< T > extends ChestGui implements ValueUpdatableGui { public abstract class ElementListConfigGui< T > extends ChestGui implements ValueUpdatableGui {
private final String namePrefix; private final String namePrefix;
@ -83,14 +84,14 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
protected void prepareStaticValues(){ protected void prepareStaticValues(){
// Left item creation for consumer & bind // Left item creation for consumer & bind
this.goLeftItem = new GuiItem(new ItemStack(Material.RED_STAINED_GLASS_PANE), event -> { this.goLeftItem = new GuiItem(ItemType.RED_STAINED_GLASS_PANE.createItemStack(), event -> {
HumanEntity viewer = event.getWhoClicked(); HumanEntity viewer = event.getWhoClicked();
UUID playerUUID = viewer.getUniqueId(); UUID playerUUID = viewer.getUniqueId();
int page = this.pageMap.getOrDefault(playerUUID, 0); int page = this.pageMap.getOrDefault(playerUUID, 0);
this.pageMap.put(playerUUID, page - 1); this.pageMap.put(playerUUID, page - 1);
ItemStack cursor = viewer.getItemOnCursor(); ItemStack cursor = viewer.getItemOnCursor();
viewer.setItemOnCursor(new ItemStack(Material.AIR)); viewer.setItemOnCursor(ItemType.AIR.createItemStack());
show(viewer); show(viewer);
@ -98,14 +99,14 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
}, CustomAnvil.instance); }, CustomAnvil.instance);
// Right item creation for consumer & bind // Right item creation for consumer & bind
this.goRightItem = new GuiItem(new ItemStack(Material.LIME_STAINED_GLASS_PANE), event -> { this.goRightItem = new GuiItem(ItemType.LIME_STAINED_GLASS_PANE.createItemStack(), event -> {
HumanEntity viewer = event.getWhoClicked(); HumanEntity viewer = event.getWhoClicked();
UUID playerUUID = viewer.getUniqueId(); UUID playerUUID = viewer.getUniqueId();
int page = pageMap.getOrDefault(playerUUID, 0); int page = pageMap.getOrDefault(playerUUID, 0);
this.pageMap.put(playerUUID, page + 1); this.pageMap.put(playerUUID, page + 1);
ItemStack cursor = viewer.getItemOnCursor(); ItemStack cursor = viewer.getItemOnCursor();
viewer.setItemOnCursor(new ItemStack(Material.AIR)); viewer.setItemOnCursor(ItemType.AIR.createItemStack());
show(viewer); show(viewer);

View file

@ -2,9 +2,9 @@ package xyz.alexcrea.cuanvil.gui.config.list;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui; import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
@ -14,9 +14,10 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.function.Consumer; import java.util.function.Consumer;
public abstract class MappedElementListConfigGui< T, S > extends ElementListConfigGui< T > { public abstract class MappedElementListConfigGui<T, S> extends ElementListConfigGui<T> {
protected final HashMap<T, S> elementGuiMap; protected final HashMap<T, S> elementGuiMap;
protected MappedElementListConfigGui(@NotNull String title) { protected MappedElementListConfigGui(@NotNull String title) {
super(title, MainConfigGui.getInstance()); super(title, MainConfigGui.getInstance());
this.elementGuiMap = new HashMap<>(); this.elementGuiMap = new HashMap<>();
@ -24,17 +25,17 @@ public abstract class MappedElementListConfigGui< T, S > extends ElementListConf
} }
@Override @Override
protected GuiItem prepareCreateNewItem(){ protected GuiItem prepareCreateNewItem() {
// Create new conflict item // Create new conflict item
ItemStack createItem = new ItemStack(Material.PAPER); ItemStack createItem = ItemType.PAPER.createItemStack();
ItemMeta createMeta = createItem.getItemMeta(); ItemMeta createMeta = createItem.getItemMeta();
assert createMeta != null; assert createMeta != null;
createMeta.setDisplayName("§aCreate new "+genericDisplayedName()); createMeta.setDisplayName("§aCreate new " + genericDisplayedName());
createMeta.setLore(Arrays.asList( createMeta.setLore(Arrays.asList(
"§7Create a new "+genericDisplayedName()+".", "§7Create a new " + genericDisplayedName() + ".",
"§7You will be asked to name the "+genericDisplayedName()+" in chat.", "§7You will be asked to name the " + genericDisplayedName() + " in chat.",
"§7Then, you should edit the "+genericDisplayedName()+" config as you need" "§7Then, you should edit the " + genericDisplayedName() + " config as you need"
)); ));
createItem.setItemMeta(createMeta); createItem.setItemMeta(createMeta);
@ -51,8 +52,8 @@ public abstract class MappedElementListConfigGui< T, S > extends ElementListConf
} }
player.closeInventory(); player.closeInventory();
player.sendMessage("§eWrite the "+genericDisplayedName()+" name you want to create in the chat.\n" + player.sendMessage("§eWrite the " + genericDisplayedName() + " name you want to create in the chat.\n" +
"§eOr write §ccancel §eto go back to "+genericDisplayedName()+" config menu"); "§eOr write §ccancel §eto go back to " + genericDisplayedName() + " config menu");
CustomAnvil.Companion.getChatListener().setListenedCallback(player, prepareCreateItemConsumer(player)); CustomAnvil.Companion.getChatListener().setListenedCallback(player, prepareCreateItemConsumer(player));

View file

@ -3,9 +3,9 @@ package xyz.alexcrea.cuanvil.gui.config.list;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui; import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui; import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
@ -31,7 +31,7 @@ public abstract class SettingGuiListConfigGui< T, S extends SettingGui.SettingGu
@Override @Override
protected GuiItem prepareCreateNewItem() { protected GuiItem prepareCreateNewItem() {
ItemStack createItem = new ItemStack(Material.PAPER); ItemStack createItem = ItemType.PAPER.createItemStack();
ItemMeta createMeta = createItem.getItemMeta(); ItemMeta createMeta = createItem.getItemMeta();
assert createMeta != null; assert createMeta != null;

View file

@ -2,10 +2,10 @@ package xyz.alexcrea.cuanvil.gui.config.list;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui; import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -17,26 +17,29 @@ import xyz.alexcrea.cuanvil.gui.config.settings.DoubleSettingGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems; import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant; import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
import xyz.alexcrea.cuanvil.util.CasedStringUtil; import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import xyz.alexcrea.cuanvil.util.ItemTypeUtil;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
public class UnitRepairElementListGui extends SettingGuiListConfigGui<String, DoubleSettingGui.DoubleSettingFactory> implements ElementMappedToListGui { public class UnitRepairElementListGui extends
SettingGuiListConfigGui<ItemType, DoubleSettingGui.DoubleSettingFactory> implements ElementMappedToListGui {
private final Material parentMaterial; private final ItemType parentType;
private final UnitRepairConfigGui parentGui; private final UnitRepairConfigGui parentGui;
private final String materialName; private final String materialName;
private boolean shouldWork = true; private boolean shouldWork = true;
public UnitRepairElementListGui(@NotNull Material parentMaterial,
public UnitRepairElementListGui(@NotNull ItemType parentType,
@NotNull UnitRepairConfigGui parentGui) { @NotNull UnitRepairConfigGui parentGui) {
super("§e" + CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase()) + " §rUnit repair"); super("§e" + CasedStringUtil.snakeToUpperSpacedCase(parentType.getKey().getKey()) + " §rUnit repair");
this.parentMaterial = parentMaterial; this.parentType = parentType;
this.parentGui = parentGui; this.parentGui = parentGui;
this.materialName = CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase()); this.materialName = CasedStringUtil.snakeToUpperSpacedCase(parentType.getKey().getKey());
GuiGlobalItems.addBackItem(this.backgroundPane, parentGui); GuiGlobalItems.addBackItem(this.backgroundPane, parentGui);
} }
@ -54,7 +57,7 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<String, Do
protected Consumer<InventoryClickEvent> getCreateClickConsumer() { protected Consumer<InventoryClickEvent> getCreateClickConsumer() {
return event -> { return event -> {
event.setCancelled(true); event.setCancelled(true);
if(!this.shouldWork){ if (!this.shouldWork) {
return; return;
} }
event.setCancelled(true); event.setCancelled(true);
@ -66,29 +69,29 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<String, Do
this, this,
(itemStack, player) -> { (itemStack, player) -> {
ItemMeta meta = itemStack.getItemMeta(); ItemMeta meta = itemStack.getItemMeta();
Material type = itemStack.getType(); ItemType type = itemStack.getType().asItemType();
if(!(meta instanceof Damageable) || (type.getMaxDurability() <= 0)) { if (!(meta instanceof Damageable)) {
player.sendMessage("§cThis item can't be damaged, so it can't be repaired."); player.sendMessage("§cThis item can't be damaged, so it can't be repaired.");
return; return;
} }
if(type == this.parentMaterial){ if (type == this.parentType) {
player.sendMessage("§cItem can't repair something of the same type."); player.sendMessage("§cItem can't repair something of the same type.");
return; return;
} }
String materialName = type.name().toLowerCase(); String materialName = type.getKey().getKey().toLowerCase();
// Add new material // Add new material
ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().set(parentMaterial.name().toLowerCase() + "." + materialName,0.25); ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().set(parentType.getKey() + "." + type.getKey(), 0.25);
if (GuiSharedConstant.TEMPORARY_DO_SAVE_TO_DISK_EVERY_CHANGE) { if (GuiSharedConstant.TEMPORARY_DO_SAVE_TO_DISK_EVERY_CHANGE) {
ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(GuiSharedConstant.TEMPORARY_DO_BACKUP_EVERY_SAVE); ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(GuiSharedConstant.TEMPORARY_DO_BACKUP_EVERY_SAVE);
} }
// Update gui // Update gui
updateValueForGeneric(materialName, true); updateValueForGeneric(type, true);
this.parentGui.updateValueForGeneric(this.parentMaterial, true); this.parentGui.updateValueForGeneric(this.parentType, true);
// Display material edit setting // Display material edit setting
@ -106,71 +109,81 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<String, Do
} }
@Override @Override
protected DoubleSettingGui.DoubleSettingFactory createFactory(String materialName) { protected DoubleSettingGui.DoubleSettingFactory createFactory(ItemType type) {
String materialDisplayName = CasedStringUtil.snakeToUpperSpacedCase(materialName); String materialDisplayName = CasedStringUtil.snakeToUpperSpacedCase(type.getKey().getKey());
return new DoubleSettingGui.DoubleSettingFactory( return new DoubleSettingGui.DoubleSettingFactory(
"§0%§8" + materialDisplayName +" Repair", "§0%§8" + materialDisplayName + " Repair",
this, this,
ConfigHolder.UNIT_REPAIR_HOLDER, ConfigHolder.UNIT_REPAIR_HOLDER,
this.parentMaterial.name().toLowerCase()+"."+materialName, this.parentType.getKey() + "." + type.getKey(),
Arrays.asList( Arrays.asList(
"§7Click here to change how many §e% §7of §a" + materialDisplayName, "§7Click here to change how many §e% §7of §a" + materialDisplayName,
"§7Should get repaired by §e"+this.materialName "§7Should get repaired by §e" + this.materialName
), ),
2, 2,
true, true, true, true,
0, 0,
1, 1,
0.25, 0.25,
0.01, 0.05, 0.25 new double[]{0.01, 0.05, 0.25},
this.parentType.getKey().getKey() + "." + type.getKey().getKey(),
this.parentType.getKey() + "." + type.getKey().getKey(),
this.parentType.getKey().getKey() + "." + type.getKey()
); );
} }
@Override @Override
protected GuiItem itemFromFactory(String materialName, DoubleSettingGui.DoubleSettingFactory factory) { protected GuiItem itemFromFactory(ItemType type, DoubleSettingGui.DoubleSettingFactory factory) {
return factory.getItem(materialFromName(materialName), return factory.getItem(type,
"§7%§a" + CasedStringUtil.snakeToUpperSpacedCase(materialName)+ " §erepaired by §a" + this.materialName); "§7%§a" + CasedStringUtil.snakeToUpperSpacedCase(type.getKey().getKey()) + " §erepaired by §a" + this.materialName);
}
private void fillSet(HashSet<ItemType> set, String path){
ConfigurationSection materialSection = ConfigHolder.UNIT_REPAIR_HOLDER
.getConfig()
.getConfigurationSection(path);
if (materialSection != null) {
for (String key : materialSection.getKeys(false)) {
ItemType type = ItemTypeUtil.INSTANCE.getItemTypeExact(key);
if(type == null) continue; // maybe warn the user ?
set.add(type);
}
}
} }
@Override @Override
protected Collection<String> getEveryDisplayableInstanceOfGeneric() { protected Collection<ItemType> getEveryDisplayableInstanceOfGeneric() {
ArrayList<String> keys = new ArrayList<>(); HashSet<ItemType> keys = new HashSet<>();
if(!this.shouldWork){ if (!this.shouldWork) {
return keys; return keys;
} }
ConfigurationSection materialSection = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getConfigurationSection(parentMaterial.name().toLowerCase()); fillSet(keys, parentType.getKey().toString());
if(materialSection == null){ fillSet(keys, parentType.getKey().getKey());
return keys;
}
keys.addAll(materialSection.getKeys(false));
return keys; return keys;
} }
private Material materialFromName(String materialName){
Material mat = Material.getMaterial(materialName.toUpperCase());
if(mat == null || mat.isAir()) return Material.BARRIER;
return mat;
}
@Override @Override
public void updateGuiValues() { public void updateGuiValues() {
super.updateGuiValues(); super.updateGuiValues();
this.parentGui.updateValueForGeneric(this.parentMaterial, true); this.parentGui.updateValueForGeneric(this.parentType, true);
} }
// ElementMappedToListGui methods // ElementMappedToListGui methods
@Override // Not used in this implementation @Override // Not used in this implementation
public void updateLocal() {} public void updateLocal() {
}
@Override @Override
public void cleanAndBeUnusable() { public void cleanAndBeUnusable() {
this.shouldWork = false; this.shouldWork = false;
this.backgroundPane.bindItem('S', GuiGlobalItems.backgroundItem(Material.BLACK_STAINED_GLASS_PANE)); this.backgroundPane.bindItem('S', GuiGlobalItems.backgroundItem(ItemType.BLACK_STAINED_GLASS_PANE));
this.backgroundPane.bindItem('L', GuiGlobalItems.backgroundItem(Material.BLACK_STAINED_GLASS_PANE)); this.backgroundPane.bindItem('L', GuiGlobalItems.backgroundItem(ItemType.BLACK_STAINED_GLASS_PANE));
this.backgroundPane.bindItem('R', GuiGlobalItems.backgroundItem(Material.BLACK_STAINED_GLASS_PANE)); this.backgroundPane.bindItem('R', GuiGlobalItems.backgroundItem(ItemType.BLACK_STAINED_GLASS_PANE));
for (HumanEntity viewer : getViewers()) { for (HumanEntity viewer : getViewers()) {
viewer.sendMessage("This config do not exist anymore"); viewer.sendMessage("This config do not exist anymore");
@ -185,10 +198,11 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<String, Do
@Override @Override
public void show(@NotNull HumanEntity humanEntity) { public void show(@NotNull HumanEntity humanEntity) {
if(!this.shouldWork){ if (!this.shouldWork) {
humanEntity.closeInventory(); humanEntity.closeInventory();
return; return;
} }
super.show(humanEntity); super.show(humanEntity);
} }

View file

@ -5,9 +5,9 @@ import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import kotlin.ranges.IntRange; import kotlin.ranges.IntRange;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
@ -26,6 +26,7 @@ import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import java.util.Collections; import java.util.Collections;
import java.util.function.Supplier; import java.util.function.Supplier;
@SuppressWarnings("UnstableApiUsage")
public class CustomRecipeSubSettingGui extends MappedToListSubSettingGui { public class CustomRecipeSubSettingGui extends MappedToListSubSettingGui {
private final CustomRecipeConfigGui parent; private final CustomRecipeConfigGui parent;
@ -69,7 +70,7 @@ public class CustomRecipeSubSettingGui extends MappedToListSubSettingGui {
GuiGlobalItems.addBackgroundItem(this.pane); GuiGlobalItems.addBackgroundItem(this.pane);
// Delete item // Delete item
ItemStack deleteItem = new ItemStack(Material.RED_TERRACOTTA); ItemStack deleteItem = ItemType.RED_TERRACOTTA.createItemStack();
ItemMeta deleteMeta = deleteItem.getItemMeta(); ItemMeta deleteMeta = deleteItem.getItemMeta();
assert deleteMeta != null; assert deleteMeta != null;
@ -89,7 +90,7 @@ public class CustomRecipeSubSettingGui extends MappedToListSubSettingGui {
ConfigHolder.CUSTOM_RECIPE_HOLDER, ConfigHolder.CUSTOM_RECIPE_HOLDER,
this.anvilRecipe + "." + AnvilCustomRecipe.REMOVE_EXACT_XP_CONFIG, AnvilCustomRecipe.DEFAULT_REMOVE_EXACT_XP_CONFIG); this.anvilRecipe + "." + AnvilCustomRecipe.REMOVE_EXACT_XP_CONFIG, AnvilCustomRecipe.DEFAULT_REMOVE_EXACT_XP_CONFIG);
ItemStack item = new ItemStack(Material.BARRIER); ItemStack item = ItemType.BARRIER.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -189,11 +190,11 @@ public class CustomRecipeSubSettingGui extends MappedToListSubSettingGui {
this.pane.bindItem('a', removeExactLinearXpFactory.getItem()); this.pane.bindItem('a', removeExactLinearXpFactory.getItem());
} }
GuiItem levelCostItem = this.levelCostFactory.getItem(Material.EXPERIENCE_BOTTLE); GuiItem levelCostItem = this.levelCostFactory.getItem(ItemType.EXPERIENCE_BOTTLE);
this.pane.bindItem('2', levelCostItem); this.pane.bindItem('2', levelCostItem);
GuiItem xpCostItem = this.linearXpCostFactory.getItem(Material.EXPERIENCE_BOTTLE); GuiItem xpCostItem = this.linearXpCostFactory.getItem(ItemType.EXPERIENCE_BOTTLE);
this.pane.bindItem('b', xpCostItem); this.pane.bindItem('b', xpCostItem);
GuiItem leftGuiItem = this.leftItemFactory.getItem(); GuiItem leftGuiItem = this.leftItemFactory.getItem();

View file

@ -4,9 +4,9 @@ import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
@ -30,6 +30,7 @@ import java.util.*;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.logging.Level; import java.util.logging.Level;
@SuppressWarnings("UnstableApiUsage")
public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui implements SelectEnchantmentContainer, SelectGroupContainer { public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui implements SelectEnchantmentContainer, SelectGroupContainer {
private final EnchantConflictGui parent; private final EnchantConflictGui parent;
@ -66,7 +67,7 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
GuiGlobalItems.addBackgroundItem(this.pane); GuiGlobalItems.addBackgroundItem(this.pane);
// Delete item // Delete item
ItemStack deleteItem = new ItemStack(Material.RED_TERRACOTTA); ItemStack deleteItem = ItemType.RED_TERRACOTTA.createItemStack();
ItemMeta deleteMeta = deleteItem.getItemMeta(); ItemMeta deleteMeta = deleteItem.getItemMeta();
assert deleteMeta != null; assert deleteMeta != null;
@ -77,7 +78,7 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
this.pane.bindItem('D', new GuiItem(deleteItem, GuiGlobalActions.openGuiAction(createDeleteGui()), CustomAnvil.instance)); this.pane.bindItem('D', new GuiItem(deleteItem, GuiGlobalActions.openGuiAction(createDeleteGui()), CustomAnvil.instance));
// Displayed item will be updated later // Displayed item will be updated later
this.enchantSettingItem = new GuiItem(new ItemStack(Material.ENCHANTED_BOOK), event -> { this.enchantSettingItem = new GuiItem(ItemType.ENCHANTED_BOOK.createItemStack(), event -> {
event.setCancelled(true); event.setCancelled(true);
EnchantSelectSettingGui enchantGui = new EnchantSelectSettingGui( EnchantSelectSettingGui enchantGui = new EnchantSelectSettingGui(
"§e" + CasedStringUtil.snakeToUpperSpacedCase(enchantConflict.toString()) + "§5", "§e" + CasedStringUtil.snakeToUpperSpacedCase(enchantConflict.toString()) + "§5",
@ -85,7 +86,7 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
enchantGui.show(event.getWhoClicked()); enchantGui.show(event.getWhoClicked());
}, CustomAnvil.instance); }, CustomAnvil.instance);
this.groupSettingItem = new GuiItem(new ItemStack(Material.PAPER), event -> { this.groupSettingItem = new GuiItem(ItemType.PAPER.createItemStack(), event -> {
event.setCancelled(true); event.setCancelled(true);
GroupSelectSettingGui enchantGui = new GroupSelectSettingGui( GroupSelectSettingGui enchantGui = new GroupSelectSettingGui(
"§e" + CasedStringUtil.snakeToUpperSpacedCase(this.enchantConflict.toString()) + " §3Groups", "§e" + CasedStringUtil.snakeToUpperSpacedCase(this.enchantConflict.toString()) + " §3Groups",
@ -145,7 +146,7 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
@Override @Override
public void updateGuiValues() { public void updateGuiValues() {
// update value from config to conflict // update value from config to conflict
int minBeforeBlock = ConfigHolder.CONFLICT_HOLDER.getConfig().getInt(this.enchantConflict.toString()+'.'+EnchantConflictManager.ENCH_MAX_PATH, 0); int minBeforeBlock = ConfigHolder.CONFLICT_HOLDER.getConfig().getInt(this.enchantConflict.toString() + '.' + EnchantConflictManager.ENCH_MAX_PATH, 0);
this.enchantConflict.setMinBeforeBlock(minBeforeBlock); this.enchantConflict.setMinBeforeBlock(minBeforeBlock);
// Parent should call updateLocal with this call // Parent should call updateLocal with this call
@ -206,7 +207,7 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
this.groupSettingItem.setItem(groupItem); // Just in case this.groupSettingItem.setItem(groupItem); // Just in case
this.pane.bindItem('M', this.minBeforeActiveSettingFactory.getItem(Material.COMMAND_BLOCK, this.pane.bindItem('M', this.minBeforeActiveSettingFactory.getItem(ItemType.COMMAND_BLOCK,
"Minimum Enchantment Count")); "Minimum Enchantment Count"));
update(); update();
} }

View file

@ -4,7 +4,6 @@ import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
@ -64,7 +63,7 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
GuiGlobalItems.addBackgroundItem(this.pane); GuiGlobalItems.addBackgroundItem(this.pane);
// Delete item // Delete item
ItemStack deleteItem = new ItemStack(Material.RED_TERRACOTTA); ItemStack deleteItem = ItemType.RED_TERRACOTTA.createItemStack();
ItemMeta deleteMeta = deleteItem.getItemMeta(); ItemMeta deleteMeta = deleteItem.getItemMeta();
deleteMeta.setDisplayName("§4DELETE GROUP"); deleteMeta.setDisplayName("§4DELETE GROUP");
@ -75,7 +74,7 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
// Displayed item will be updated later // Displayed item will be updated later
String materialSelectionName = "§e" + CasedStringUtil.snakeToUpperSpacedCase(group.getName()) + " §rMaterials"; String materialSelectionName = "§e" + CasedStringUtil.snakeToUpperSpacedCase(group.getName()) + " §rMaterials";
ItemStack selectItem = new ItemStack(Material.DIAMOND_SWORD); ItemStack selectItem = ItemType.DIAMOND_SWORD.createItemStack();
ItemMeta selectItemMeta = selectItem.getItemMeta(); ItemMeta selectItemMeta = selectItem.getItemMeta();
selectItemMeta.setDisplayName(materialSelectionName); selectItemMeta.setDisplayName(materialSelectionName);
@ -90,7 +89,7 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
}, CustomAnvil.instance); }, CustomAnvil.instance);
String selectGroupName = "§e" + CasedStringUtil.snakeToUpperSpacedCase(this.group.getName()) + " §rGroups"; String selectGroupName = "§e" + CasedStringUtil.snakeToUpperSpacedCase(this.group.getName()) + " §rGroups";
ItemStack selectGroup = new ItemStack(Material.CHEST); ItemStack selectGroup = ItemType.CHEST.createItemStack();
ItemMeta selectGroupMeta = selectGroup.getItemMeta(); ItemMeta selectGroupMeta = selectGroup.getItemMeta();
selectGroupMeta.setDisplayName(selectGroupName); selectGroupMeta.setDisplayName(selectGroupName);

View file

@ -5,9 +5,9 @@ import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
@ -25,6 +25,7 @@ import java.util.function.Consumer;
/** /**
* An instance of a gui used to edit a boolean setting. * An instance of a gui used to edit a boolean setting.
*/ */
@SuppressWarnings("UnstableApiUsage")
public class BoolSettingsGui extends AbstractSettingGui { public class BoolSettingsGui extends AbstractSettingGui {
private final BoolSettingFactory holder; private final BoolSettingFactory holder;
@ -65,14 +66,14 @@ public class BoolSettingsGui extends AbstractSettingGui {
protected void prepareReturnToDefault() { protected void prepareReturnToDefault() {
// Prepare default Value text // Prepare default Value text
String defaultValueLore; String defaultValueLore;
if(holder.defaultVal){ if (holder.defaultVal) {
defaultValueLore = "§aYes §7Is the default value"; defaultValueLore = "§aYes §7Is the default value";
}else{ } else {
defaultValueLore = "§cNo §7Is the default value"; defaultValueLore = "§cNo §7Is the default value";
} }
// Create reset to default item // Create reset to default item
ItemStack item = new ItemStack(Material.COMMAND_BLOCK); ItemStack item = ItemType.COMMAND_BLOCK.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -95,24 +96,24 @@ public class BoolSettingsGui extends AbstractSettingGui {
// Get displayed value for this config. // Get displayed value for this config.
String displayedName; String displayedName;
Material displayedMat; ItemType displayedType;
if (now) { if (now) {
displayedName = "§aYes"; displayedName = "§aYes";
displayedMat = Material.GREEN_TERRACOTTA; displayedType = ItemType.GREEN_TERRACOTTA;
} else { } else {
displayedName = "§cNo"; displayedName = "§cNo";
displayedMat = Material.RED_TERRACOTTA; displayedType = ItemType.RED_TERRACOTTA;
} }
// create & set Value item // create & set Value item
ArrayList<String> valueLore = new ArrayList<>(); ArrayList<String> valueLore = new ArrayList<>();
if(!holder.displayLore.isEmpty()){ if (!holder.displayLore.isEmpty()) {
valueLore.addAll(holder.displayLore); valueLore.addAll(holder.displayLore);
valueLore.add(""); valueLore.add("");
} }
valueLore.add(AbstractSettingGui.CLICK_LORE); valueLore.add(AbstractSettingGui.CLICK_LORE);
ItemStack valueItemStack = new ItemStack(displayedMat); ItemStack valueItemStack = displayedType.createItemStack();
ItemMeta valueMeta = valueItemStack.getItemMeta(); ItemMeta valueMeta = valueItemStack.getItemMeta();
assert valueMeta != null; assert valueMeta != null;
@ -177,12 +178,12 @@ public class BoolSettingsGui extends AbstractSettingGui {
/** /**
* Constructor for a boolean setting gui factory. * Constructor for a boolean setting gui factory.
* *
* @param title The title of the gui. * @param title The title of the gui.
* @param parent Parent gui to go back when completed. * @param parent Parent gui to go back when completed.
* @param config Configuration holder of this setting. * @param config Configuration holder of this setting.
* @param configPath Configuration path of this setting. * @param configPath Configuration path of this setting.
* @param defaultVal Default value if not found on the config. * @param defaultVal Default value if not found on the config.
* @param displayLore Gui display item lore. * @param displayLore Gui display item lore.
*/ */
public BoolSettingFactory( public BoolSettingFactory(
@NotNull String title, @NotNull ValueUpdatableGui parent, @NotNull String title, @NotNull ValueUpdatableGui parent,
@ -227,23 +228,23 @@ public class BoolSettingsGui extends AbstractSettingGui {
* @param name Name of the item. * @param name Name of the item.
* @return A formatted GuiItem that will create and open a GUI for the boolean setting. * @return A formatted GuiItem that will create and open a GUI for the boolean setting.
*/ */
public GuiItem getItem(String name){ public GuiItem getItem(String name) {
// Get item properties // Get item properties
boolean value = getConfiguredValue(); boolean value = getConfiguredValue();
Material itemMat; ItemType itemType;
StringBuilder itemName = new StringBuilder("§e"); StringBuilder itemName = new StringBuilder("§e");
String finalValue; String finalValue;
if (value) { if (value) {
itemMat = Material.GREEN_TERRACOTTA; itemType = ItemType.GREEN_TERRACOTTA;
finalValue = "§aYes"; finalValue = "§aYes";
} else { } else {
itemMat = Material.RED_TERRACOTTA; itemType = ItemType.RED_TERRACOTTA;
finalValue = "§cNo"; finalValue = "§cNo";
} }
itemName.append(name); itemName.append(name);
return GuiGlobalItems.createGuiItemFromProperties(this, itemMat, itemName, finalValue, this.displayLore, false); return GuiGlobalItems.createGuiItemFromProperties(this, itemType, itemName, finalValue, this.displayLore, false);
} }
/** /**
@ -254,7 +255,7 @@ public class BoolSettingsGui extends AbstractSettingGui {
* *
* @return A formatted GuiItem that will create and open a GUI for the boolean setting. * @return A formatted GuiItem that will create and open a GUI for the boolean setting.
*/ */
public GuiItem getItem(){ public GuiItem getItem() {
// Get item properties // Get item properties
String configPath = GuiGlobalItems.getConfigNameFromPath(getConfigPath()); String configPath = GuiGlobalItems.getConfigNameFromPath(getConfigPath());

View file

@ -5,10 +5,10 @@ import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -24,6 +24,7 @@ import java.math.RoundingMode;
import java.util.*; import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
@SuppressWarnings("UnstableApiUsage")
public class DoubleSettingGui extends AbstractSettingGui { public class DoubleSettingGui extends AbstractSettingGui {
protected final DoubleSettingFactory holder; protected final DoubleSettingFactory holder;
@ -60,7 +61,8 @@ public class DoubleSettingGui extends AbstractSettingGui {
updateValueDisplay(); updateValueDisplay();
} }
private static final ItemStack DELETE_ITEM_STACK = new ItemStack(Material.RED_TERRACOTTA); private static final ItemStack DELETE_ITEM_STACK = ItemType.RED_TERRACOTTA.createItemStack();
static { static {
ItemMeta meta = DELETE_ITEM_STACK.getItemMeta(); ItemMeta meta = DELETE_ITEM_STACK.getItemMeta();
assert meta != null; assert meta != null;
@ -88,13 +90,13 @@ public class DoubleSettingGui extends AbstractSettingGui {
boolean shouldDelete = isNull() && hadChange(); boolean shouldDelete = isNull() && hadChange();
GuiItem tempSaveItem = this.saveItem; GuiItem tempSaveItem = this.saveItem;
if(shouldDelete){ if (shouldDelete) {
this.saveItem = this.askDelete; this.saveItem = this.askDelete;
} }
super.update(); super.update();
if(shouldDelete){ if (shouldDelete) {
this.saveItem = tempSaveItem; this.saveItem = tempSaveItem;
} }
} }
@ -114,7 +116,7 @@ public class DoubleSettingGui extends AbstractSettingGui {
* Prepare "return to default value" gui item. * Prepare "return to default value" gui item.
*/ */
protected void prepareReturnToDefault() { protected void prepareReturnToDefault() {
ItemStack item = new ItemStack(Material.COMMAND_BLOCK); ItemStack item = ItemType.COMMAND_BLOCK.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -141,9 +143,9 @@ public class DoubleSettingGui extends AbstractSettingGui {
if (now.compareTo(holder.min) > 0) { if (now.compareTo(holder.min) > 0) {
BigDecimal planned = holder.min.max(now.subtract(step)); BigDecimal planned = holder.min.max(now.subtract(step));
minusItem = getSetValueItem(Material.RED_TERRACOTTA, planned, "§c-"); minusItem = getSetValueItem(ItemType.RED_TERRACOTTA, planned, "§c-");
} else { } else {
minusItem = GuiGlobalItems.backgroundItem(Material.BARRIER); minusItem = GuiGlobalItems.backgroundItem(ItemType.BARRIER);
} }
pane.bindItem('-', minusItem); pane.bindItem('-', minusItem);
@ -152,14 +154,14 @@ public class DoubleSettingGui extends AbstractSettingGui {
if (now.compareTo(holder.max) < 0) { if (now.compareTo(holder.max) < 0) {
BigDecimal planned = holder.max.min(now.add(step)); BigDecimal planned = holder.max.min(now.add(step));
plusItem = getSetValueItem(Material.GREEN_TERRACOTTA, planned, "§a+"); plusItem = getSetValueItem(ItemType.GREEN_TERRACOTTA, planned, "§a+");
} else { } else {
plusItem = GuiGlobalItems.backgroundItem(Material.BARRIER); plusItem = GuiGlobalItems.backgroundItem(ItemType.BARRIER);
} }
pane.bindItem('+', plusItem); pane.bindItem('+', plusItem);
// "result" display // "result" display
ItemStack resultPaper = new ItemStack(Material.PAPER); ItemStack resultPaper = ItemType.PAPER.createItemStack();
ItemMeta resultMeta = resultPaper.getItemMeta(); ItemMeta resultMeta = resultPaper.getItemMeta();
assert resultMeta != null; assert resultMeta != null;
@ -180,17 +182,17 @@ public class DoubleSettingGui extends AbstractSettingGui {
} }
private GuiItem getSetValueItem(Material mat, BigDecimal planned, String numberPrefix){ private GuiItem getSetValueItem(ItemType type, BigDecimal planned, String numberPrefix) {
// Create set item lore // Create set item lore
ArrayList<String> setLoreItem = new ArrayList<>(); ArrayList<String> setLoreItem = new ArrayList<>();
if(!holder.displayLore.isEmpty()){ if (!holder.displayLore.isEmpty()) {
setLoreItem.addAll(holder.displayLore); setLoreItem.addAll(holder.displayLore);
setLoreItem.add(""); setLoreItem.add("");
} }
setLoreItem.add(AbstractSettingGui.CLICK_LORE); setLoreItem.add(AbstractSettingGui.CLICK_LORE);
// Create & return set value item // Create & return set value item
ItemStack item = new ItemStack(mat); ItemStack item = type.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -267,17 +269,17 @@ public class DoubleSettingGui extends AbstractSettingGui {
BigDecimal stepValue = holder.steps[stepIndex]; BigDecimal stepValue = holder.steps[stepIndex];
// Get material properties // Get material properties
Material stepMat; ItemType stepType;
StringBuilder stepName = new StringBuilder("§"); StringBuilder stepName = new StringBuilder("§");
List<String> stepLore; List<String> stepLore;
Consumer<InventoryClickEvent> clickEvent; Consumer<InventoryClickEvent> clickEvent;
if (stepValue.compareTo(step) == 0) { if (stepValue.compareTo(step) == 0) {
stepMat = Material.GREEN_STAINED_GLASS_PANE; stepType = ItemType.GREEN_STAINED_GLASS_PANE;
stepName.append('a'); stepName.append('a');
stepLore = Collections.singletonList("§7Value is changing by " + displayValue(stepValue)); stepLore = Collections.singletonList("§7Value is changing by " + displayValue(stepValue));
clickEvent = GuiGlobalActions.stayInPlace; clickEvent = GuiGlobalActions.stayInPlace;
} else { } else {
stepMat = Material.RED_STAINED_GLASS_PANE; stepType = ItemType.RED_STAINED_GLASS_PANE;
stepName.append('c'); stepName.append('c');
stepLore = Collections.singletonList("§7Click here to change the value by " + displayValue(stepValue)); stepLore = Collections.singletonList("§7Click here to change the value by " + displayValue(stepValue));
clickEvent = updateStepValue(stepValue); clickEvent = updateStepValue(stepValue);
@ -285,7 +287,7 @@ public class DoubleSettingGui extends AbstractSettingGui {
stepName.append("Step of §e").append(displayValue(stepValue)); stepName.append("Step of §e").append(displayValue(stepValue));
// Create item stack then gui item // Create item stack then gui item
ItemStack item = new ItemStack(stepMat); ItemStack item = stepType.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -312,13 +314,13 @@ public class DoubleSettingGui extends AbstractSettingGui {
@Override @Override
public boolean onSave() { public boolean onSave() {
if(isNull()){ if (isNull()) {
if(this.holder.config instanceof ConfigHolder.DeletableResource deletableResource){ if (this.holder.config instanceof ConfigHolder.DeletableResource deletableResource) {
deletableResource.delete(this.holder.configPath); deletableResource.delete(this.holder.configPath);
}else{ } else {
this.holder.config.getConfig().set(this.holder.configPath, null); this.holder.config.getConfig().set(this.holder.configPath, null);
} }
}else{ } else {
this.holder.config.getConfig().set(this.holder.configPath, now.doubleValue()); this.holder.config.getConfig().set(this.holder.configPath, now.doubleValue());
} }
@ -333,18 +335,19 @@ public class DoubleSettingGui extends AbstractSettingGui {
return now.compareTo(before) != 0; return now.compareTo(before) != 0;
} }
public boolean isNull(){ public boolean isNull() {
return this.nullOnZero && (this.now.compareTo(BigDecimal.ZERO) == 0); return this.nullOnZero && (this.now.compareTo(BigDecimal.ZERO) == 0);
} }
private static final BigDecimal PERCENTAGE_OFFSET = BigDecimal.valueOf(100); private static final BigDecimal PERCENTAGE_OFFSET = BigDecimal.valueOf(100);
public String displayValue(BigDecimal value){
public String displayValue(BigDecimal value) {
return displayValue(value, this.asPercentage); return displayValue(value, this.asPercentage);
} }
public static String displayValue(BigDecimal value, boolean isAsPercentage){ public static String displayValue(BigDecimal value, boolean isAsPercentage) {
if(isAsPercentage){ if (isAsPercentage) {
return value.multiply(PERCENTAGE_OFFSET).setScale(value.scale()-2, RoundingMode.HALF_UP) + "%"; return value.multiply(PERCENTAGE_OFFSET).setScale(value.scale() - 2, RoundingMode.HALF_UP) + "%";
} }
return value.toString(); return value.toString();
} }
@ -365,6 +368,7 @@ public class DoubleSettingGui extends AbstractSettingGui {
BigDecimal max; BigDecimal max;
BigDecimal defaultVal; BigDecimal defaultVal;
BigDecimal[] steps; BigDecimal[] steps;
String[] alternativePaths;
@NotNull @NotNull
List<String> displayLore; List<String> displayLore;
@ -411,6 +415,53 @@ public class DoubleSettingGui extends AbstractSettingGui {
} }
this.displayLore = Objects.requireNonNullElse(displayLore, Collections.emptyList()); this.displayLore = Objects.requireNonNullElse(displayLore, Collections.emptyList());
this.alternativePaths = new String[0];
}
/**
* Constructor for a double setting gui factory.
*
* @param title The title of the gui.
* @param parent Parent gui to go back when completed.
* @param config Configuration holder of this setting.
* @param configPath Configuration path of this setting.
* @param displayLore Gui display item lore.
* @param scale The scale of the decimal.
* @param asPercentage If we should display the value as a %.
* @param nullOnZero Set the value as null (deleting it) when equal to 0
* @param min Minimum value of this setting.
* @param max Maximum value of this setting.
* @param defaultVal Default value if not found on the config.
* @param steps List of step the value can increment/decrement.
* List's size should be between 1 (included) and 5 (included).
* it is visually preferable to have an odd number of step.
* If step only contain 1 value, no step item should be displayed.
* @param alternatePaths Alternative config path where the value will be tried to fetch here if absent in the primary config path
*/
public DoubleSettingFactory(
@NotNull String title, @NotNull ValueUpdatableGui parent,
@NotNull ConfigHolder config,
@NotNull String configPath,
@Nullable List<String> displayLore,
int scale, boolean asPercentage, boolean nullOnZero,
double min, double max, double defaultVal, double[] steps, String... alternatePaths) {
super(configPath, config);
this.title = title;
this.parent = parent;
this.scale = scale;
this.asPercentage = asPercentage;
this.nullOnZero = nullOnZero;
this.min = BigDecimal.valueOf(min).setScale(scale, RoundingMode.HALF_UP);
this.max = BigDecimal.valueOf(max).setScale(scale, RoundingMode.HALF_UP);
this.defaultVal = BigDecimal.valueOf(defaultVal).setScale(scale, RoundingMode.HALF_UP);
this.steps = new BigDecimal[steps.length];
for (int i = 0; i < steps.length; i++) {
this.steps[i] = BigDecimal.valueOf(steps[i]).setScale(scale, RoundingMode.HALF_UP);
}
this.displayLore = Objects.requireNonNullElse(displayLore, Collections.emptyList());
this.alternativePaths = alternatePaths;
} }
/** /**
@ -426,9 +477,17 @@ public class DoubleSettingGui extends AbstractSettingGui {
*/ */
public BigDecimal getConfiguredValue() { public BigDecimal getConfiguredValue() {
ConfigurationSection section = this.config.getConfig(); ConfigurationSection section = this.config.getConfig();
if(section.isDouble(this.configPath)){ if (section.isDouble(this.configPath)) {
return BigDecimal.valueOf(section.getDouble(this.configPath)).setScale(2, RoundingMode.HALF_UP); return BigDecimal.valueOf(section.getDouble(this.configPath)).setScale(2, RoundingMode.HALF_UP);
} }
for (String alternativePath : alternativePaths) {
section = this.config.getConfig();
if (section.isDouble(alternativePath)) {
return BigDecimal.valueOf(section.getDouble(this.configPath)).setScale(2, RoundingMode.HALF_UP);
}
}
return this.defaultVal; return this.defaultVal;
} }
@ -440,22 +499,21 @@ public class DoubleSettingGui extends AbstractSettingGui {
return new DoubleSettingGui(this, now, this.asPercentage, this.nullOnZero); return new DoubleSettingGui(this, now, this.asPercentage, this.nullOnZero);
} }
public GuiItem getItem(ItemType type, String name) {
public GuiItem getItem(Material itemMat, String name){
// Get item properties // Get item properties
BigDecimal value = getConfiguredValue(); BigDecimal value = getConfiguredValue();
StringBuilder itemName = new StringBuilder("§a").append(name); StringBuilder itemName = new StringBuilder("§a").append(name);
return GuiGlobalItems.createGuiItemFromProperties(this, itemMat, itemName, return GuiGlobalItems.createGuiItemFromProperties(this, type, itemName,
"§e" + displayValue(value, this.asPercentage), "§e" + displayValue(value, this.asPercentage),
this.displayLore, true); this.displayLore, true);
} }
public GuiItem getItem(Material itemMat){ public GuiItem getItem(ItemType type) {
// Get item properties // Get item properties
String configPath = GuiGlobalItems.getConfigNameFromPath(getConfigPath()); String configPath = GuiGlobalItems.getConfigNameFromPath(getConfigPath());
return getItem(itemMat, CasedStringUtil.detectToUpperSpacedCase(configPath)); return getItem(type, CasedStringUtil.detectToUpperSpacedCase(configPath));
} }
} }

View file

@ -6,10 +6,10 @@ import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -29,6 +29,7 @@ import java.util.function.Consumer;
* An instance of a gui used to edit an enchantment cost setting. * An instance of a gui used to edit an enchantment cost setting.
* May be considered as a 2 int setting. * May be considered as a 2 int setting.
*/ */
@SuppressWarnings("UnstableApiUsage")
public class EnchantCostSettingsGui extends IntSettingsGui { public class EnchantCostSettingsGui extends IntSettingsGui {
protected final static String ITEM_PATH = ".item"; protected final static String ITEM_PATH = ".item";
@ -81,7 +82,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
PatternPane pane = getPane(); PatternPane pane = getPane();
// book display // book display
ItemStack bookItemstack = new ItemStack(Material.BOOK); ItemStack bookItemstack = ItemType.BOOK.createItemStack();
ItemMeta bookMeta = bookItemstack.getItemMeta(); ItemMeta bookMeta = bookItemstack.getItemMeta();
assert bookMeta != null; assert bookMeta != null;
@ -92,7 +93,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
bookItemstack.setItemMeta(bookMeta); bookItemstack.setItemMeta(bookMeta);
// sword display // sword display
ItemStack swordItemstack = new ItemStack(Material.WOODEN_SWORD); ItemStack swordItemstack = ItemType.WOODEN_SWORD.createItemStack();
ItemMeta swordMeta = swordItemstack.getItemMeta(); ItemMeta swordMeta = swordItemstack.getItemMeta();
assert swordMeta != null; assert swordMeta != null;
@ -103,14 +104,14 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
"§7Only apply if sacrificed item §cis not §7a book")); "§7Only apply if sacrificed item §cis not §7a book"));
swordItemstack.setItemMeta(swordMeta); swordItemstack.setItemMeta(swordMeta);
pane.bindItem('1', GuiGlobalItems.backgroundItem(Material.BLACK_STAINED_GLASS_PANE)); pane.bindItem('1', GuiGlobalItems.backgroundItem(ItemType.BLACK_STAINED_GLASS_PANE));
pane.bindItem('2', new GuiItem(bookItemstack, GuiGlobalActions.stayInPlace, CustomAnvil.instance)); pane.bindItem('2', new GuiItem(bookItemstack, GuiGlobalActions.stayInPlace, CustomAnvil.instance));
pane.bindItem('3', new GuiItem(swordItemstack, GuiGlobalActions.stayInPlace, CustomAnvil.instance)); pane.bindItem('3', new GuiItem(swordItemstack, GuiGlobalActions.stayInPlace, CustomAnvil.instance));
} }
@Override @Override
protected void prepareReturnToDefault() { protected void prepareReturnToDefault() {
ItemStack item = new ItemStack(Material.COMMAND_BLOCK); ItemStack item = ItemType.COMMAND_BLOCK.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -145,7 +146,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
GuiItem minusItem; GuiItem minusItem;
if (nowBook > holder.min) { if (nowBook > holder.min) {
int planned = Math.max(holder.min, nowBook - step); int planned = Math.max(holder.min, nowBook - step);
ItemStack item = new ItemStack(Material.RED_TERRACOTTA); ItemStack item = ItemType.RED_TERRACOTTA.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -155,7 +156,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
minusItem = new GuiItem(item, updateNowBookConsumer(planned), CustomAnvil.instance); minusItem = new GuiItem(item, updateNowBookConsumer(planned), CustomAnvil.instance);
} else { } else {
minusItem = GuiGlobalItems.backgroundItem(Material.BARRIER); minusItem = GuiGlobalItems.backgroundItem(ItemType.BARRIER);
} }
pane.bindItem('M', minusItem); pane.bindItem('M', minusItem);
@ -163,7 +164,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
GuiItem plusItem; GuiItem plusItem;
if (nowBook < holder.max) { if (nowBook < holder.max) {
int planned = Math.min(holder.max, nowBook + step); int planned = Math.min(holder.max, nowBook + step);
ItemStack item = new ItemStack(Material.GREEN_TERRACOTTA); ItemStack item = ItemType.GREEN_TERRACOTTA.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -173,12 +174,12 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
plusItem = new GuiItem(item, updateNowBookConsumer(planned), CustomAnvil.instance); plusItem = new GuiItem(item, updateNowBookConsumer(planned), CustomAnvil.instance);
} else { } else {
plusItem = GuiGlobalItems.backgroundItem(Material.BARRIER); plusItem = GuiGlobalItems.backgroundItem(ItemType.BARRIER);
} }
pane.bindItem('P', plusItem); pane.bindItem('P', plusItem);
// now value display // now value display
ItemStack nowPaper = new ItemStack(Material.PAPER); ItemStack nowPaper = ItemType.PAPER.createItemStack();
ItemMeta nowMeta = nowPaper.getItemMeta(); ItemMeta nowMeta = nowPaper.getItemMeta();
assert nowMeta != null; assert nowMeta != null;

View file

@ -9,6 +9,7 @@ import org.bukkit.enchantments.Enchantment;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
@ -26,6 +27,7 @@ import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Stream; import java.util.stream.Stream;
@SuppressWarnings("UnstableApiUsage")
public class EnchantSelectSettingGui extends SettingGuiListConfigGui<CAEnchantment, EnchantSelectSettingGui.DummyFactory> implements SettingGui { public class EnchantSelectSettingGui extends SettingGuiListConfigGui<CAEnchantment, EnchantSelectSettingGui.DummyFactory> implements SettingGui {
private final SelectEnchantmentContainer enchantContainer; private final SelectEnchantmentContainer enchantContainer;
@ -88,13 +90,13 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui<CAEnchantme
protected GuiItem itemFromFactory(CAEnchantment enchantment, DummyFactory factory) { protected GuiItem itemFromFactory(CAEnchantment enchantment, DummyFactory factory) {
boolean isIn = this.selectedEnchant.contains(enchantment); boolean isIn = this.selectedEnchant.contains(enchantment);
Material usedMaterial; ItemType usedType;
if (isIn) { if (isIn) {
usedMaterial = Material.ENCHANTED_BOOK; usedType = ItemType.ENCHANTED_BOOK;
} else { } else {
usedMaterial = Material.BOOK; usedType = ItemType.BOOK;
} }
ItemStack item = new ItemStack(usedMaterial); ItemStack item = usedType.createItemStack();
setEnchantItemMeta(item, enchantment.getKey().getKey(), isIn); setEnchantItemMeta(item, enchantment.getKey().getKey(), isIn);
@ -104,7 +106,7 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui<CAEnchantme
} }
private GuiItem createDisplayUnusedItem() { private GuiItem createDisplayUnusedItem() {
ItemStack item = new ItemStack(this.displayUnselected ? Material.BOOK : Material.ENCHANTED_BOOK); ItemStack item = (this.displayUnselected ? ItemType.BOOK : ItemType.ENCHANTED_BOOK).createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -134,7 +136,7 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui<CAEnchantme
if (meta == null) { if (meta == null) {
CustomAnvil.instance.getLogger().warning("Could not create item for enchantment: " + name + ":\n" + CustomAnvil.instance.getLogger().warning("Could not create item for enchantment: " + name + ":\n" +
"Item do not gave item meta: " + item + ". Using a placeholder item instead"); "Item do not gave item meta: " + item + ". Using a placeholder item instead");
item.setType(Material.PAPER); item = item.withType(Material.PAPER);
meta = item.getItemMeta(); meta = item.getItemMeta();
assert meta != null; assert meta != null;
} }
@ -161,14 +163,14 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui<CAEnchantme
boolean isIn = this.selectedEnchant.contains(enchant); boolean isIn = this.selectedEnchant.contains(enchant);
if (isIn) { if (isIn) {
this.selectedEnchant.remove(enchant); this.selectedEnchant.remove(enchant);
item.setType(Material.BOOK); item = item.withType(Material.BOOK);
} else { } else {
this.selectedEnchant.add(enchant); this.selectedEnchant.add(enchant);
item.setType(Material.ENCHANTED_BOOK); item = item.withType(Material.ENCHANTED_BOOK);
} }
setEnchantItemMeta(item, enchant.getKey().getKey(), !isIn); setEnchantItemMeta(item, enchant.getKey().getKey(), !isIn);
guiItem.setItem(item);// Just in case guiItem.setItem(item);
update(); update();
}; };

View file

@ -5,10 +5,10 @@ import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
@ -20,6 +20,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
@SuppressWarnings("UnstableApiUsage")
public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum> extends AbstractSettingGui { public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum> extends AbstractSettingGui {
private final EnumSettingFactory<T> holder; private final EnumSettingFactory<T> holder;
@ -52,7 +53,7 @@ public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum>
} }
public void prepareStaticItems(){ public void prepareStaticItems() {
prepareReturnToDefault(); prepareReturnToDefault();
} }
@ -63,7 +64,7 @@ public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum>
* Prepare "return to default value" gui item. * Prepare "return to default value" gui item.
*/ */
protected void prepareReturnToDefault() { protected void prepareReturnToDefault() {
ItemStack item = new ItemStack(Material.COMMAND_BLOCK); ItemStack item = ItemType.COMMAND_BLOCK.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -157,6 +158,7 @@ public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum>
this.parent = parent; this.parent = parent;
} }
/** /**
* @return Get setting's gui title. * @return Get setting's gui title.
*/ */
@ -178,12 +180,12 @@ public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum>
* @return Next value for a given enum * @return Next value for a given enum
*/ */
@NotNull @NotNull
public T next(@NotNull T now){ public T next(@NotNull T now) {
Class<T> clazz = now.getDeclaringClass(); Class<T> clazz = now.getDeclaringClass();
T[] values = clazz.getEnumConstants(); T[] values = clazz.getEnumConstants();
int index = now.ordinal(); int index = now.ordinal();
if(index == values.length - 1) if (index == values.length - 1)
return values[0]; return values[0];
return values[index + 1]; return values[index + 1];
@ -191,6 +193,7 @@ public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum>
/** /**
* Get default value value * Get default value value
*
* @return default value * @return default value
*/ */
@NotNull @NotNull
@ -212,10 +215,10 @@ public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum>
* @param name Name of the display. * @param name Name of the display.
* @return A formatted GuiItem that will create and open a GUI for the enum setting. * @return A formatted GuiItem that will create and open a GUI for the enum setting.
*/ */
public GuiItem getItem(@NotNull Material material, @NotNull String name) { public GuiItem getItem(@NotNull ItemType type, @NotNull String name) {
T value = getConfiguredValue(); T value = getConfiguredValue();
ItemStack item = new ItemStack(material); ItemStack item = type.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -234,6 +237,7 @@ public class EnumSettingGui<T extends Enum<T> & EnumSettingGui.ConfigurableEnum>
String configName(); String configName();
ItemStack configurationGuiItem(); ItemStack configurationGuiItem();
String configurationGuiName(); String configurationGuiName();

View file

@ -98,13 +98,13 @@ public class GroupSelectSettingGui extends AbstractSettingGui {
private static final List<String> TRUE_LORE = Collections.singletonList("§7Value: §aSelected"); private static final List<String> TRUE_LORE = Collections.singletonList("§7Value: §aSelected");
private static final List<String> FALSE_LORE = Collections.singletonList("§7Value: §cNot Selected"); private static final List<String> FALSE_LORE = Collections.singletonList("§7Value: §cNot Selected");
public void setGroupItemMeta(ItemStack item, String name, boolean isIn) { public ItemStack setGroupItemMeta(ItemStack item, String name, boolean isIn) {
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
if (meta == null) { if (meta == null) {
CustomAnvil.instance.getLogger().warning("Could not create item for group: " + name + ":\n" + CustomAnvil.instance.getLogger().warning("Could not create item for group: " + name + ":\n" +
"Item do not gave item meta: " + item + ". Using placeholder instead"); "Item do not gave item meta: " + item + ". Using placeholder instead");
item.setType(Material.PAPER); item = item.withType(Material.PAPER);
meta = item.getItemMeta(); meta = item.getItemMeta();
assert meta != null; assert meta != null;
} }
@ -120,6 +120,7 @@ public class GroupSelectSettingGui extends AbstractSettingGui {
meta.addItemFlags(ItemFlag.values()); meta.addItemFlags(ItemFlag.values());
item.setItemMeta(meta); item.setItemMeta(meta);
return item;
} }
private Consumer<InventoryClickEvent> getGroupItemConsumer(AbstractItemTypeGroup group, GuiItem guiItem) { private Consumer<InventoryClickEvent> getGroupItemConsumer(AbstractItemTypeGroup group, GuiItem guiItem) {
@ -134,7 +135,7 @@ public class GroupSelectSettingGui extends AbstractSettingGui {
} }
ItemStack item = guiItem.getItem(); ItemStack item = guiItem.getItem();
setGroupItemMeta(item, group.getName(), !isIn); item = setGroupItemMeta(item, group.getName(), !isIn);
guiItem.setItem(item);// Just in case guiItem.setItem(item);// Just in case
update(); update();

View file

@ -5,9 +5,9 @@ import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -26,6 +26,7 @@ import java.util.function.Consumer;
/** /**
* An instance of a gui used to edit an int setting. * An instance of a gui used to edit an int setting.
*/ */
@SuppressWarnings("UnstableApiUsage")
public class IntSettingsGui extends AbstractSettingGui { public class IntSettingsGui extends AbstractSettingGui {
protected final IntSettingFactory holder; protected final IntSettingFactory holder;
@ -68,7 +69,7 @@ public class IntSettingsGui extends AbstractSettingGui {
* Prepare "return to default value" gui item. * Prepare "return to default value" gui item.
*/ */
protected void prepareReturnToDefault() { protected void prepareReturnToDefault() {
ItemStack item = new ItemStack(Material.COMMAND_BLOCK); ItemStack item = ItemType.COMMAND_BLOCK.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -94,7 +95,7 @@ public class IntSettingsGui extends AbstractSettingGui {
GuiItem minusItem; GuiItem minusItem;
if (now > holder.min) { if (now > holder.min) {
int planned = Math.max(holder.min, now - step); int planned = Math.max(holder.min, now - step);
ItemStack item = new ItemStack(Material.RED_TERRACOTTA); ItemStack item = ItemType.RED_TERRACOTTA.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -104,7 +105,7 @@ public class IntSettingsGui extends AbstractSettingGui {
minusItem = new GuiItem(item, updateNowConsumer(planned), CustomAnvil.instance); minusItem = new GuiItem(item, updateNowConsumer(planned), CustomAnvil.instance);
} else { } else {
minusItem = GuiGlobalItems.backgroundItem(Material.BARRIER); minusItem = GuiGlobalItems.backgroundItem(ItemType.BARRIER);
} }
pane.bindItem('-', minusItem); pane.bindItem('-', minusItem);
@ -113,7 +114,7 @@ public class IntSettingsGui extends AbstractSettingGui {
GuiItem plusItem; GuiItem plusItem;
if (now < holder.max) { if (now < holder.max) {
int planned = Math.min(holder.max, now + step); int planned = Math.min(holder.max, now + step);
ItemStack item = new ItemStack(Material.GREEN_TERRACOTTA); ItemStack item = ItemType.GREEN_TERRACOTTA.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -123,12 +124,12 @@ public class IntSettingsGui extends AbstractSettingGui {
plusItem = new GuiItem(item, updateNowConsumer(planned), CustomAnvil.instance); plusItem = new GuiItem(item, updateNowConsumer(planned), CustomAnvil.instance);
} else { } else {
plusItem = GuiGlobalItems.backgroundItem(Material.BARRIER); plusItem = GuiGlobalItems.backgroundItem(ItemType.BARRIER);
} }
pane.bindItem('+', plusItem); pane.bindItem('+', plusItem);
// "result" display // "result" display
ItemStack resultPaper = new ItemStack(Material.PAPER); ItemStack resultPaper = ItemType.PAPER.createItemStack();
ItemMeta resultMeta = resultPaper.getItemMeta(); ItemMeta resultMeta = resultPaper.getItemMeta();
assert resultMeta != null; assert resultMeta != null;
@ -218,17 +219,17 @@ public class IntSettingsGui extends AbstractSettingGui {
int stepValue = holder.steps[stepIndex]; int stepValue = holder.steps[stepIndex];
// Get material properties // Get material properties
Material stepMat; ItemType stepMat;
StringBuilder stepName = new StringBuilder("§"); StringBuilder stepName = new StringBuilder("§");
List<String> stepLore; List<String> stepLore;
Consumer<InventoryClickEvent> clickEvent; Consumer<InventoryClickEvent> clickEvent;
if (stepValue == step) { if (stepValue == step) {
stepMat = Material.GREEN_STAINED_GLASS_PANE; stepMat = ItemType.GREEN_STAINED_GLASS_PANE;
stepName.append('a'); stepName.append('a');
stepLore = Collections.singletonList("§7Value is changing by " + stepValue); stepLore = Collections.singletonList("§7Value is changing by " + stepValue);
clickEvent = GuiGlobalActions.stayInPlace; clickEvent = GuiGlobalActions.stayInPlace;
} else { } else {
stepMat = Material.RED_STAINED_GLASS_PANE; stepMat = ItemType.RED_STAINED_GLASS_PANE;
stepName.append('c'); stepName.append('c');
stepLore = Collections.singletonList("§7Click here to change the value by " + stepValue); stepLore = Collections.singletonList("§7Click here to change the value by " + stepValue);
clickEvent = updateStepValue(stepValue); clickEvent = updateStepValue(stepValue);
@ -236,7 +237,7 @@ public class IntSettingsGui extends AbstractSettingGui {
stepName.append("Step of: §e").append(stepValue); stepName.append("Step of: §e").append(stepValue);
// Create item stack then gui item // Create item stack then gui item
ItemStack item = new ItemStack(stepMat); ItemStack item = stepMat.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -353,19 +354,19 @@ public class IntSettingsGui extends AbstractSettingGui {
* This item will create and open an int setting GUI from the factory. * This item will create and open an int setting GUI from the factory.
* The item will have its value written in the lore part of the item. * The item will have its value written in the lore part of the item.
* *
* @param itemMat Displayed material of the item. * @param type Displayed item type
* @param name Name of the item. * @param name Name of the item.
* @return A formatted GuiItem that will create and open a GUI for the int setting. * @return A formatted GuiItem that will create and open a GUI for the int setting.
*/ */
public GuiItem getItem( public GuiItem getItem(
@NotNull Material itemMat, @NotNull ItemType type,
@NotNull String name @NotNull String name
) { ) {
// Get item properties // Get item properties
int value = getConfiguredValue(); int value = getConfiguredValue();
StringBuilder itemName = new StringBuilder("§a").append(name); StringBuilder itemName = new StringBuilder("§a").append(name);
return GuiGlobalItems.createGuiItemFromProperties(this, itemMat, itemName, return GuiGlobalItems.createGuiItemFromProperties(this, type, itemName,
"§e" + value, "§e" + value,
this.displayLore, true); this.displayLore, true);
} }
@ -376,14 +377,14 @@ public class IntSettingsGui extends AbstractSettingGui {
* The item will have its value written in the lore part of the item. * The item will have its value written in the lore part of the item.
* Item's name will be the factory set title. * Item's name will be the factory set title.
* *
* @param itemMat Displayed material of the item. * @param type Displayed item type.
* @return A formatted GuiItem that will create and open a GUI for the int setting. * @return A formatted GuiItem that will create and open a GUI for the int setting.
*/ */
public GuiItem getItem( public GuiItem getItem(
@NotNull Material itemMat @NotNull ItemType type
) { ) {
String configPath = GuiGlobalItems.getConfigNameFromPath(getConfigPath()); String configPath = GuiGlobalItems.getConfigNameFromPath(getConfigPath());
return getItem(itemMat, CasedStringUtil.detectToUpperSpacedCase(configPath)); return getItem(type, CasedStringUtil.detectToUpperSpacedCase(configPath));
} }
} }

View file

@ -5,11 +5,11 @@ import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -27,6 +27,7 @@ import java.util.function.Consumer;
/** /**
* An instance of a gui used to edit an item setting. * An instance of a gui used to edit an item setting.
*/ */
@SuppressWarnings("UnstableApiUsage")
public class ItemSettingGui extends AbstractSettingGui { public class ItemSettingGui extends AbstractSettingGui {
private final ItemSettingFactory holder; private final ItemSettingFactory holder;
@ -62,7 +63,8 @@ public class ItemSettingGui extends AbstractSettingGui {
public void prepareStaticItems(){ public void prepareStaticItems(){
prepareReturnToDefault(); prepareReturnToDefault();
GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(Material.YELLOW_STAINED_GLASS_PANE, this); GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(
ItemType.YELLOW_STAINED_GLASS_PANE, this);
getPane().bindItem('s', temporaryLeave); getPane().bindItem('s', temporaryLeave);
} }
@ -73,7 +75,7 @@ public class ItemSettingGui extends AbstractSettingGui {
* Prepare "return to default value" gui item. * Prepare "return to default value" gui item.
*/ */
protected void prepareReturnToDefault() { protected void prepareReturnToDefault() {
ItemStack item = new ItemStack(Material.COMMAND_BLOCK); ItemStack item = ItemType.COMMAND_BLOCK.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -101,7 +103,7 @@ public class ItemSettingGui extends AbstractSettingGui {
if(this.now != null){ if(this.now != null){
displayedItem = this.now.clone(); displayedItem = this.now.clone();
}else{ }else{
displayedItem = new ItemStack(Material.BARRIER); displayedItem = ItemType.BARRIER.createItemStack();
ItemMeta valueMeta = displayedItem.getItemMeta(); ItemMeta valueMeta = displayedItem.getItemMeta();
assert valueMeta != null; assert valueMeta != null;
@ -238,7 +240,7 @@ public class ItemSettingGui extends AbstractSettingGui {
public GuiItem getItem(@NotNull String name) { public GuiItem getItem(@NotNull String name) {
ItemStack item = getConfiguredValue(); ItemStack item = getConfiguredValue();
if(item == null || item.getType().isAir()){ if(item == null || item.getType().isAir()){
item = new ItemStack(Material.BARRIER); item = ItemType.BARRIER.createItemStack();
}else{ }else{
item = item.clone(); item = item.clone();
} }

View file

@ -4,7 +4,6 @@ import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui; import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
@ -79,11 +78,12 @@ public class MaterialSelectSettingGui extends MappedElementListConfigGui<ItemTyp
super.prepareStaticValues(); super.prepareStaticValues();
// Temporary leave item // Temporary leave item
GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(Material.YELLOW_STAINED_GLASS_PANE, this); GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(
ItemType.YELLOW_STAINED_GLASS_PANE, this);
this.backgroundPane.bindItem('T', temporaryLeave); this.backgroundPane.bindItem('T', temporaryLeave);
// Select new mat item // Select new mat item
ItemStack selectItem = new ItemStack(Material.BLUE_STAINED_GLASS_PANE); ItemStack selectItem = ItemType.BLUE_STAINED_GLASS_PANE.createItemStack();
ItemMeta selectMeta = selectItem.getItemMeta(); ItemMeta selectMeta = selectItem.getItemMeta();
assert selectMeta != null; assert selectMeta != null;
@ -103,7 +103,7 @@ public class MaterialSelectSettingGui extends MappedElementListConfigGui<ItemTyp
this.backgroundPane.bindItem('S', this.noChangeItem); this.backgroundPane.bindItem('S', this.noChangeItem);
// Instant Remove On item // Instant Remove On item
ItemStack instantRemoveOnItem = new ItemStack(Material.LIME_STAINED_GLASS_PANE); ItemStack instantRemoveOnItem = ItemType.LIME_STAINED_GLASS_PANE.createItemStack();
ItemMeta instantRemoveOnMeta = instantRemoveOnItem.getItemMeta(); ItemMeta instantRemoveOnMeta = instantRemoveOnItem.getItemMeta();
assert instantRemoveOnMeta != null; assert instantRemoveOnMeta != null;
@ -114,7 +114,7 @@ public class MaterialSelectSettingGui extends MappedElementListConfigGui<ItemTyp
instantRemoveOnItem.setItemMeta(instantRemoveOnMeta); instantRemoveOnItem.setItemMeta(instantRemoveOnMeta);
// Instant Remove Off item // Instant Remove Off item
ItemStack instantRemoveOffItem = new ItemStack(Material.RED_STAINED_GLASS_PANE); ItemStack instantRemoveOffItem = ItemType.RED_STAINED_GLASS_PANE.createItemStack();
ItemMeta instantRemoveOffMeta = instantRemoveOffItem.getItemMeta(); ItemMeta instantRemoveOffMeta = instantRemoveOffItem.getItemMeta();
assert instantRemoveOffMeta != null; assert instantRemoveOffMeta != null;
@ -141,7 +141,7 @@ public class MaterialSelectSettingGui extends MappedElementListConfigGui<ItemTyp
} }
private GuiItem prepareSaveItem() { private GuiItem prepareSaveItem() {
ItemStack saveItemStack = new ItemStack(GuiGlobalItems.DEFAULT_SAVE_ITEM); ItemStack saveItemStack = GuiGlobalItems.DEFAULT_SAVE_ITEM.createItemStack();
ItemMeta saveMeta = saveItemStack.getItemMeta(); ItemMeta saveMeta = saveItemStack.getItemMeta();
assert saveMeta != null; assert saveMeta != null;

View file

@ -5,10 +5,10 @@ import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
@ -45,7 +45,7 @@ public class WorkPenaltyTypeSettingGui extends AbstractSettingGui {
} }
public static GuiItem getDisplayItem(@NotNull BasicConfigGui parent, public static GuiItem getDisplayItem(@NotNull BasicConfigGui parent,
@NotNull Material itemMat, @NotNull ItemType type,
@NotNull String name) { @NotNull String name) {
List<String> displayLore = new ArrayList<>(); List<String> displayLore = new ArrayList<>();
@ -58,7 +58,7 @@ public class WorkPenaltyTypeSettingGui extends AbstractSettingGui {
displayLore.add(SHARED_EXPLANATION); displayLore.add(SHARED_EXPLANATION);
displayLore.add(EXCLUSIVE_EXPLANATION); displayLore.add(EXCLUSIVE_EXPLANATION);
ItemStack item = new ItemStack(itemMat); ItemStack item = type.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name); meta.setDisplayName(name);
@ -116,7 +116,7 @@ public class WorkPenaltyTypeSettingGui extends AbstractSettingGui {
String exclusiveAdditiveStr = (part.exclusivePenaltyAdditive() ? "§a" : "§c") + "Additive"; String exclusiveAdditiveStr = (part.exclusivePenaltyAdditive() ? "§a" : "§c") + "Additive";
// Display item // Display item
ItemStack displayItem = new ItemStack(type.getDisplayMat()); ItemStack displayItem = type.getDisplayMat().createItemStack();
ArrayList<String> displayLore = new ArrayList<>(); ArrayList<String> displayLore = new ArrayList<>();
displayLore.add("§eShared§7: " + additiveStr + " §7| " + increasingStr); displayLore.add("§eShared§7: " + additiveStr + " §7| " + increasingStr);
@ -133,7 +133,7 @@ public class WorkPenaltyTypeSettingGui extends AbstractSettingGui {
// Can probably put this in a function but this works so // Can probably put this in a function but this works so
// "Increment" item // "Increment" item
ItemStack incrementItem = new ItemStack(part.penaltyIncrease() ? Material.GREEN_TERRACOTTA : Material.RED_TERRACOTTA); ItemStack incrementItem = (part.penaltyIncrease() ? ItemType.GREEN_TERRACOTTA : ItemType.RED_TERRACOTTA).createItemStack();
meta = incrementItem.getItemMeta(); meta = incrementItem.getItemMeta();
meta.setDisplayName(increasingStr); meta.setDisplayName(increasingStr);
@ -153,7 +153,7 @@ public class WorkPenaltyTypeSettingGui extends AbstractSettingGui {
})); }));
// "Additive" item // "Additive" item
ItemStack additiveItem = new ItemStack(part.penaltyAdditive() ? Material.GREEN_TERRACOTTA : Material.RED_TERRACOTTA); ItemStack additiveItem = (part.penaltyAdditive() ? ItemType.GREEN_TERRACOTTA : ItemType.RED_TERRACOTTA).createItemStack();
meta = additiveItem.getItemMeta(); meta = additiveItem.getItemMeta();
meta.setDisplayName(additiveStr); meta.setDisplayName(additiveStr);
@ -173,7 +173,7 @@ public class WorkPenaltyTypeSettingGui extends AbstractSettingGui {
})); }));
// exclusive "Increment" item // exclusive "Increment" item
ItemStack exclusiveIncrementItem = new ItemStack(part.exclusivePenaltyIncrease() ? Material.GREEN_TERRACOTTA : Material.RED_TERRACOTTA); ItemStack exclusiveIncrementItem = (part.exclusivePenaltyIncrease() ? ItemType.GREEN_TERRACOTTA : ItemType.RED_TERRACOTTA).createItemStack();
meta = exclusiveIncrementItem.getItemMeta(); meta = exclusiveIncrementItem.getItemMeta();
meta.setDisplayName(exclusiveIncreasingStr); meta.setDisplayName(exclusiveIncreasingStr);
@ -193,7 +193,7 @@ public class WorkPenaltyTypeSettingGui extends AbstractSettingGui {
})); }));
// exclusive "Additive" item // exclusive "Additive" item
ItemStack exclusiveAdditiveItem = new ItemStack(part.exclusivePenaltyAdditive() ? Material.GREEN_TERRACOTTA : Material.RED_TERRACOTTA); ItemStack exclusiveAdditiveItem = (part.exclusivePenaltyAdditive() ? ItemType.GREEN_TERRACOTTA : ItemType.RED_TERRACOTTA).createItemStack();
meta = exclusiveAdditiveItem.getItemMeta(); meta = exclusiveAdditiveItem.getItemMeta();
meta.setDisplayName(exclusiveAdditiveStr); meta.setDisplayName(exclusiveAdditiveStr);

View file

@ -4,10 +4,10 @@ import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui; import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui; import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
@ -20,13 +20,14 @@ import java.util.List;
/** /**
* A utility class to store function that create generic GUI item. * A utility class to store function that create generic GUI item.
*/ */
@SuppressWarnings("UnstableApiUsage")
public class GuiGlobalItems { public class GuiGlobalItems {
// statically create default back itemstack // statically create default back itemstack
private static final ItemStack BACK_ITEM; private static final ItemStack BACK_ITEM;
static { static {
BACK_ITEM = new ItemStack(Material.BARRIER); BACK_ITEM = ItemType.BARRIER.createItemStack();
ItemMeta meta = BACK_ITEM.getItemMeta(); ItemMeta meta = BACK_ITEM.getItemMeta();
assert meta != null; assert meta != null;
@ -68,17 +69,17 @@ public class GuiGlobalItems {
target.bindItem('B', backItem(goal)); target.bindItem('B', backItem(goal));
} }
private static final Material DEFAULT_BACKGROUND_MAT = Material.LIGHT_GRAY_STAINED_GLASS_PANE; private static final ItemType DEFAULT_BACKGROUND_TYPE = ItemType.LIGHT_GRAY_STAINED_GLASS_PANE;
/** /**
* Get a background item with backgroundMat as the displayed material. * Get a background item with backgroundMat as the displayed material.
* A background item is a GuiItem that do nothing when interacted with and have an empty name. * A background item is a GuiItem that do nothing when interacted with and have an empty name.
* *
* @param backgroundMat The material to which the background item should be made of. * @param backgroundType The item type of the background.
* @return A background item with backgroundMat as material. * @return A background item with backgroundMat as material.
*/ */
public static GuiItem backgroundItem(Material backgroundMat) { public static GuiItem backgroundItem(ItemType backgroundType) {
ItemStack item = new ItemStack(backgroundMat); ItemStack item = backgroundType.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -94,19 +95,19 @@ public class GuiGlobalItems {
* @return A new instance of the default background item. * @return A new instance of the default background item.
*/ */
public static GuiItem backgroundItem() { public static GuiItem backgroundItem() {
return backgroundItem(DEFAULT_BACKGROUND_MAT); return backgroundItem(DEFAULT_BACKGROUND_TYPE);
} }
/** /**
* Add default background item to a GUI pattern with the reserved character key <strong>0</strong>. * Add default background item to a GUI pattern with the reserved character key <strong>0</strong>.
* A background item is a GuiItem that do nothing when interacted with and have an empty name. * A background item is a GuiItem that do nothing when interacted with and have an empty name.
* *
* @param target The pattern to add the background item. * @param target The pattern to add the background item.
* @param backgroundMat The material of the background item. * @param backgroundType The item type of the background.
*/ */
public static void addBackgroundItem(@NotNull PatternPane target, public static void addBackgroundItem(@NotNull PatternPane target,
@NotNull Material backgroundMat) { @NotNull ItemType backgroundType) {
target.bindItem('0', backgroundItem(backgroundMat)); target.bindItem('0', backgroundItem(backgroundType));
} }
/** /**
@ -116,11 +117,11 @@ public class GuiGlobalItems {
* @param target The pattern to add the background item. * @param target The pattern to add the background item.
*/ */
public static void addBackgroundItem(@NotNull PatternPane target) { public static void addBackgroundItem(@NotNull PatternPane target) {
addBackgroundItem(target, DEFAULT_BACKGROUND_MAT); addBackgroundItem(target, DEFAULT_BACKGROUND_TYPE);
} }
public static final Material DEFAULT_SAVE_ITEM = Material.LIME_DYE; public static final ItemType DEFAULT_SAVE_ITEM = ItemType.LIME_DYE;
public static final Material DEFAULT_NO_CHANGE_ITEM = Material.GRAY_DYE; public static final ItemType DEFAULT_NO_CHANGE_ITEM = ItemType.GRAY_DYE;
/** /**
* Create a new save setting GuiItem. * Create a new save setting GuiItem.
@ -135,7 +136,7 @@ public class GuiGlobalItems {
@NotNull SettingGui setting, @NotNull SettingGui setting,
@NotNull ValueUpdatableGui goal) { @NotNull ValueUpdatableGui goal) {
ItemStack item = new ItemStack(DEFAULT_SAVE_ITEM); ItemStack item = DEFAULT_SAVE_ITEM.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -150,7 +151,7 @@ public class GuiGlobalItems {
private static final GuiItem NO_CHANGE_ITEM; private static final GuiItem NO_CHANGE_ITEM;
static { static {
ItemStack item = new ItemStack(DEFAULT_NO_CHANGE_ITEM); ItemStack item = DEFAULT_NO_CHANGE_ITEM.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -191,7 +192,7 @@ public class GuiGlobalItems {
* Create an arbitrary GuiItem from a unique setting and item's property. * Create an arbitrary GuiItem from a unique setting and item's property.
* *
* @param factory The setting's GUI factory. * @param factory The setting's GUI factory.
* @param itemMat Displayed material of the item. * @param type Displayed item type
* @param itemName Name of the item. * @param itemName Name of the item.
* @param value Value of the setting when the item is created. * @param value Value of the setting when the item is created.
* Will not update automatically, if the setting's value change, the item need to be created again. * Will not update automatically, if the setting's value change, the item need to be created again.
@ -200,7 +201,7 @@ public class GuiGlobalItems {
*/ */
public static GuiItem createGuiItemFromProperties( public static GuiItem createGuiItemFromProperties(
@NotNull SettingGui.SettingGuiFactory factory, @NotNull SettingGui.SettingGuiFactory factory,
@NotNull Material itemMat, @NotNull ItemType type,
@NotNull StringBuilder itemName, @NotNull StringBuilder itemName,
@NotNull Object value, @NotNull Object value,
@NotNull List<String> displayLore, @NotNull List<String> displayLore,
@ -208,14 +209,14 @@ public class GuiGlobalItems {
) { ) {
// Prepare lore // Prepare lore
ArrayList<String> lore = new ArrayList<>(); ArrayList<String> lore = new ArrayList<>();
lore.add((displayValuePrefix ? SETTING_ITEM_LORE_PREFIX : "") + value); lore.add((displayValuePrefix ? SETTING_ITEM_LORE_PREFIX : "") + value);
if(!displayLore.isEmpty()){ if (!displayLore.isEmpty()) {
lore.add(""); lore.add("");
lore.addAll(displayLore); lore.addAll(displayLore);
} }
// Create & initialise item // Create & initialise item
ItemStack item = new ItemStack(itemMat); ItemStack item = type.createItemStack();
ItemMeta itemMeta = item.getItemMeta(); ItemMeta itemMeta = item.getItemMeta();
assert itemMeta != null; assert itemMeta != null;
@ -242,8 +243,8 @@ public class GuiGlobalItems {
return path.substring(indexOfDot + 1); return path.substring(indexOfDot + 1);
} }
public static GuiItem temporaryCloseGuiToSelectItem(Material itemMaterial, Gui openBack){ public static GuiItem temporaryCloseGuiToSelectItem(ItemType type, Gui openBack) {
ItemStack item = new ItemStack(itemMaterial); ItemStack item = type.createItemStack();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
@ -256,9 +257,9 @@ public class GuiGlobalItems {
HumanEntity player = event.getWhoClicked(); HumanEntity player = event.getWhoClicked();
CustomAnvil.Companion.getChatListener().setListenedCallback(player, (message) ->{ CustomAnvil.Companion.getChatListener().setListenedCallback(player, (message) -> {
if(message == null) return; if (message == null) return;
openBack.show(player); openBack.show(player);
}); });

View file

@ -4,19 +4,20 @@ import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.pane.Pane; import com.github.stefvanschie.inventoryframework.pane.Pane;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui; import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@SuppressWarnings("UnstableApiUsage")
public class GuiSharedConstant { public class GuiSharedConstant {
private GuiSharedConstant(){} private GuiSharedConstant(){}
public static final Material SECONDARY_BACKGROUND_MATERIAL = Material.BLACK_STAINED_GLASS_PANE; public static final ItemType SECONDARY_BACKGROUND_MATERIAL = ItemType.BLACK_STAINED_GLASS_PANE;
public static final GuiItem SECONDARY_BACKGROUND_ITEM = GuiGlobalItems.backgroundItem(GuiSharedConstant.SECONDARY_BACKGROUND_MATERIAL); public static final GuiItem SECONDARY_BACKGROUND_ITEM = GuiGlobalItems.backgroundItem(GuiSharedConstant.SECONDARY_BACKGROUND_MATERIAL);
public static final String UPPER_FILLER_FULL_PLANE = "111111111"; public static final String UPPER_FILLER_FULL_PLANE = "111111111";
@ -52,7 +53,7 @@ public class GuiSharedConstant {
public static final ItemStack CONFIRM_PERMANENT_ITEM; public static final ItemStack CONFIRM_PERMANENT_ITEM;
static { static {
CANCEL_ITEM = new ItemStack(Material.RED_TERRACOTTA); CANCEL_ITEM = ItemType.RED_TERRACOTTA.createItemStack();
ItemMeta meta = CANCEL_ITEM.getItemMeta(); ItemMeta meta = CANCEL_ITEM.getItemMeta();
assert meta != null; assert meta != null;
@ -60,7 +61,7 @@ public class GuiSharedConstant {
meta.setLore(Collections.singletonList("§7Cancel current action and return to previous menu.")); meta.setLore(Collections.singletonList("§7Cancel current action and return to previous menu."));
CANCEL_ITEM.setItemMeta(meta); CANCEL_ITEM.setItemMeta(meta);
CONFIRM_ITEM = new ItemStack(Material.GREEN_TERRACOTTA); CONFIRM_ITEM = ItemType.GREEN_TERRACOTTA.createItemStack();
meta = CONFIRM_ITEM.getItemMeta(); meta = CONFIRM_ITEM.getItemMeta();
assert meta != null; assert meta != null;
@ -68,7 +69,7 @@ public class GuiSharedConstant {
meta.setLore(Collections.singletonList("§7Confirm current action.")); meta.setLore(Collections.singletonList("§7Confirm current action."));
CONFIRM_ITEM.setItemMeta(meta); CONFIRM_ITEM.setItemMeta(meta);
CONFIRM_PERMANENT_ITEM = new ItemStack(Material.GREEN_TERRACOTTA); CONFIRM_PERMANENT_ITEM = ItemType.GREEN_TERRACOTTA.createItemStack();
meta = CONFIRM_PERMANENT_ITEM.getItemMeta(); meta = CONFIRM_PERMANENT_ITEM.getItemMeta();
assert meta != null; assert meta != null;

View file

@ -2,8 +2,8 @@ package io.delilaheve.util
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import io.delilaheve.util.EnchantmentUtil.enchantmentName import io.delilaheve.util.EnchantmentUtil.enchantmentName
import org.bukkit.Material
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import org.bukkit.inventory.ItemType
import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.config.WorkPenaltyType import xyz.alexcrea.cuanvil.config.WorkPenaltyType
import xyz.alexcrea.cuanvil.config.WorkPenaltyType.WorkPenaltyPart import xyz.alexcrea.cuanvil.config.WorkPenaltyType.WorkPenaltyPart
@ -348,8 +348,8 @@ object ConfigOptions {
* *
* @return the current enchantment limit. -1 if none * @return the current enchantment limit. -1 if none
*/ */
fun getEnchantCountLimit(type: Material): Int? { fun getEnchantCountLimit(type: ItemType): Int? {
val limit = materialEnchantCountLimit(type) val limit = itemEnchantCountLimit(type)
if(limit != null) return limit if(limit != null) return limit
if(defaultEnchantCountLimit >= 0) return defaultEnchantCountLimit if(defaultEnchantCountLimit >= 0) return defaultEnchantCountLimit
@ -362,7 +362,7 @@ object ConfigOptions {
* *
* @return The current enchantment limit. -1 if none * @return The current enchantment limit. -1 if none
*/ */
private fun materialEnchantCountLimit(type: Material): Int? { private fun itemEnchantCountLimit(type: ItemType): Int? {
val path = "$ENCHANT_COUNT_LIMIT_ITEMS.${type.key.key.lowercase()}" val path = "$ENCHANT_COUNT_LIMIT_ITEMS.${type.key.key.lowercase()}"
if(!ConfigHolder.DEFAULT_CONFIG.config.isInt(path)) if(!ConfigHolder.DEFAULT_CONFIG.config.isInt(path))
return null return null

View file

@ -4,9 +4,9 @@ import io.delilaheve.CustomAnvil
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.dependency.DependencyManager
import xyz.alexcrea.cuanvil.enchant.CAEnchantment import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.group.ConflictType import xyz.alexcrea.cuanvil.group.ConflictType
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.itemType
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
@ -34,7 +34,7 @@ object EnchantmentUtil {
val bypassFuse = player.hasPermission(CustomAnvil.bypassFusePermission) val bypassFuse = player.hasPermission(CustomAnvil.bypassFusePermission)
val bypassLevel = player.hasPermission(CustomAnvil.bypassLevelPermission) val bypassLevel = player.hasPermission(CustomAnvil.bypassLevelPermission)
var maxEnchantCount = ConfigOptions.getEnchantCountLimit(item.type) var maxEnchantCount = ConfigOptions.getEnchantCountLimit(item.itemType)
if(maxEnchantCount == null || maxEnchantCount < 0) maxEnchantCount = Int.MAX_VALUE if(maxEnchantCount == null || maxEnchantCount < 0) maxEnchantCount = Int.MAX_VALUE
other.forEach { (enchantment, level) -> other.forEach { (enchantment, level) ->

View file

@ -1,9 +1,10 @@
package io.delilaheve.util package io.delilaheve.util
import org.bukkit.Material.ENCHANTED_BOOK
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.ItemType.ENCHANTED_BOOK
import org.bukkit.inventory.meta.Damageable import org.bukkit.inventory.meta.Damageable
import xyz.alexcrea.cuanvil.enchant.CAEnchantment import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.itemType
import kotlin.math.ceil import kotlin.math.ceil
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
@ -11,12 +12,13 @@ import kotlin.math.min
/** /**
* Item manipulation utilities * Item manipulation utilities
*/ */
@Suppress("UnstableApiUsage")
object ItemUtil { object ItemUtil {
/** /**
* Check if this [ItemStack] is an [ENCHANTED_BOOK] * Check if this [ItemStack] is an [ENCHANTED_BOOK]
*/ */
fun ItemStack.isEnchantedBook() = type == ENCHANTED_BOOK fun ItemStack.isEnchantedBook() = itemType == ENCHANTED_BOOK
/** /**
* Find the enchantment map for this [ItemStack] and return it as a [MutableMap] * Find the enchantment map for this [ItemStack] and return it as a [MutableMap]

View file

@ -8,11 +8,11 @@ import org.bukkit.entity.HumanEntity
import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.PrepareAnvilEvent import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.api.event.listener.CAClickResultBypassEvent import xyz.alexcrea.cuanvil.api.event.listener.CAClickResultBypassEvent
import xyz.alexcrea.cuanvil.api.event.listener.CAEarlyPreAnvilBypassEvent import xyz.alexcrea.cuanvil.api.event.listener.CAEarlyPreAnvilBypassEvent
import xyz.alexcrea.cuanvil.api.event.listener.CAPreAnvilBypassEvent import xyz.alexcrea.cuanvil.api.event.listener.CAPreAnvilBypassEvent
import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResultEvent import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResultEvent
import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.dependency.datapack.DataPackDependency import xyz.alexcrea.cuanvil.dependency.datapack.DataPackDependency
import xyz.alexcrea.cuanvil.dependency.gui.ExternGuiTester import xyz.alexcrea.cuanvil.dependency.gui.ExternGuiTester

View file

@ -2,8 +2,6 @@ package xyz.alexcrea.cuanvil.dependency.datapack
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import io.papermc.paper.datapack.Datapack import io.papermc.paper.datapack.Datapack
import io.papermc.paper.registry.RegistryAccess
import io.papermc.paper.registry.RegistryKey
import org.bukkit.Bukkit import org.bukkit.Bukkit
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import org.bukkit.configuration.file.FileConfiguration import org.bukkit.configuration.file.FileConfiguration
@ -18,6 +16,7 @@ import xyz.alexcrea.cuanvil.enchant.wrapped.CAIncompatibleAllEnchant
import xyz.alexcrea.cuanvil.group.IncludeItemTypeGroup import xyz.alexcrea.cuanvil.group.IncludeItemTypeGroup
import xyz.alexcrea.cuanvil.update.UpdateUtils import xyz.alexcrea.cuanvil.update.UpdateUtils
import xyz.alexcrea.cuanvil.update.Version import xyz.alexcrea.cuanvil.update.Version
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.getItemType
import java.io.InputStreamReader import java.io.InputStreamReader
object DataPackDependency { object DataPackDependency {
@ -136,8 +135,6 @@ object DataPackDependency {
// Order matter for this file // Order matter for this file
// Could rewrite to not matter but not really important, so I keep it like that // Could rewrite to not matter but not really important, so I keep it like that
private fun handleItemGroups(yml: YamlConfiguration) { private fun handleItemGroups(yml: YamlConfiguration) {
val itemRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.ITEM)
for (groupName in yml.getKeys(false)) { for (groupName in yml.getKeys(false)) {
val section = yml.getConfigurationSection(groupName) ?: continue val section = yml.getConfigurationSection(groupName) ?: continue
@ -147,10 +144,9 @@ object DataPackDependency {
if (group == null) group = IncludeItemTypeGroup(groupName) if (group == null) group = IncludeItemTypeGroup(groupName)
for (name in section.getStringList("items")) { for (name in section.getStringList("items")) {
val key = NamespacedKey.fromString(name.lowercase())
if (key == null) throw IllegalStateException("Invalid item type: $name")
val type = itemRegistry.get(key) // Test if repairable is a valid item type
val type = getItemType(name)
if (type == null) { if (type == null) {
throw IllegalStateException("Could not find item type $name for item group $groupName") throw IllegalStateException("Could not find item type $name for item group $groupName")
} }

View file

@ -1,10 +1,10 @@
package xyz.alexcrea.cuanvil.dependency.plugins package xyz.alexcrea.cuanvil.dependency.plugins
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import org.bukkit.Material
import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.PrepareAnvilEvent import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.ItemType
import org.bukkit.plugin.RegisteredListener import org.bukkit.plugin.RegisteredListener
import xyz.alexcrea.cuanvil.api.EnchantmentApi import xyz.alexcrea.cuanvil.api.EnchantmentApi
import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResultEvent import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResultEvent
@ -13,6 +13,7 @@ import java.lang.reflect.Method
import su.nightexpress.excellentenchants.api.EnchantRegistry as V5EnchantRegistry import su.nightexpress.excellentenchants.api.EnchantRegistry as V5EnchantRegistry
import su.nightexpress.excellentenchants.manager.listener.AnvilListener as V5AnvilListener import su.nightexpress.excellentenchants.manager.listener.AnvilListener as V5AnvilListener
@SuppressWarnings("UnstableApiUsage")
class ExcellentEnchantsDependency { class ExcellentEnchantsDependency {
init { init {
@ -93,7 +94,7 @@ class ExcellentEnchantsDependency {
} }
private fun treatInput(item: ItemStack?): ItemStack { private fun treatInput(item: ItemStack?): ItemStack {
if (item == null) return ItemStack(Material.AIR) if (item == null) return ItemType.AIR.createItemStack()
return item return item
} }

View file

@ -8,6 +8,7 @@ import org.bukkit.inventory.ItemStack
import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment
import xyz.alexcrea.cuanvil.enchant.CAEnchantment import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.itemType
import java.util.* import java.util.*
@Suppress("UnstableApiUsage") @Suppress("UnstableApiUsage")
@ -176,10 +177,9 @@ class EnchantConflictManager {
item: ItemStack, item: ItemStack,
newEnchant: CAEnchantment newEnchant: CAEnchantment
): ConflictType { ): ConflictType {
val mat = item.type val type = item.itemType
val itemType = mat.asItemType()!!
CustomAnvil.verboseLog("Testing conflict for ${newEnchant.key} on ${itemType.key}") CustomAnvil.verboseLog("Testing conflict for ${newEnchant.key} on ${type.key}")
val conflictList = newEnchant.conflicts val conflictList = newEnchant.conflicts
var result = ConflictType.NO_CONFLICT var result = ConflictType.NO_CONFLICT
@ -190,7 +190,7 @@ class EnchantConflictManager {
continue continue
} }
val allowed = conflict.allowed(appliedEnchants.keys, itemType) val allowed = conflict.allowed(appliedEnchants.keys, type)
CustomAnvil.verboseLog("Was against $conflict and conflicting: ${!allowed} ") CustomAnvil.verboseLog("Was against $conflict and conflicting: ${!allowed} ")
if (!allowed) { if (!allowed) {
if (conflict.getEnchants().size <= 1) { if (conflict.getEnchants().size <= 1) {
@ -206,7 +206,7 @@ class EnchantConflictManager {
val immutableEnchants = Collections.unmodifiableMap(appliedEnchants) val immutableEnchants = Collections.unmodifiableMap(appliedEnchants)
for (appliedEnchant in appliedEnchants.keys) { for (appliedEnchant in appliedEnchants.keys) {
if (appliedEnchant is AdditionalTestEnchantment) { if (appliedEnchant is AdditionalTestEnchantment) {
val doConflict = appliedEnchant.isEnchantConflict(immutableEnchants, mat) val doConflict = appliedEnchant.isEnchantConflict(immutableEnchants, type)
if (doConflict) { if (doConflict) {
CustomAnvil.verboseLog("Big conflict by additional test, stopping") CustomAnvil.verboseLog("Big conflict by additional test, stopping")
return ConflictType.ENCHANTMENT_CONFLICT return ConflictType.ENCHANTMENT_CONFLICT
@ -218,7 +218,7 @@ class EnchantConflictManager {
if ((result != ConflictType.ITEM_CONFLICT) && (newEnchant is AdditionalTestEnchantment)) { if ((result != ConflictType.ITEM_CONFLICT) && (newEnchant is AdditionalTestEnchantment)) {
val partialItem = createPartialResult(item, immutableEnchants) val partialItem = createPartialResult(item, immutableEnchants)
if (newEnchant.isItemConflict(immutableEnchants, mat, partialItem)) { if (newEnchant.isItemConflict(immutableEnchants, type, partialItem)) {
return ConflictType.ITEM_CONFLICT return ConflictType.ITEM_CONFLICT
} }

View file

@ -1,18 +1,16 @@
package xyz.alexcrea.cuanvil.group package xyz.alexcrea.cuanvil.group
import io.papermc.paper.registry.RegistryAccess import org.bukkit.Registry
import io.papermc.paper.registry.RegistryKey
import org.bukkit.inventory.ItemType import org.bukkit.inventory.ItemType
import java.util.* import java.util.*
@Deprecated("Need rework to reduce memory cost as not enum set") @Deprecated("Need rework to reduce memory cost as not enum set")
@Suppress("UnstableApiUsage")
class ExcludeItemTypeGroup(name: String) : AbstractItemTypeGroup(name) { class ExcludeItemTypeGroup(name: String) : AbstractItemTypeGroup(name) {
override fun createDefaultSet(): MutableSet<ItemType> { override fun createDefaultSet(): MutableSet<ItemType> {
val types: MutableSet<ItemType> = HashSet() val types: MutableSet<ItemType> = HashSet()
types.addAll(RegistryAccess.registryAccess().getRegistry(RegistryKey.ITEM)) types.addAll(Registry.ITEM)
return types return types
} }

View file

@ -3,7 +3,6 @@ package xyz.alexcrea.cuanvil.group
import org.bukkit.inventory.ItemType import org.bukkit.inventory.ItemType
import java.util.* import java.util.*
@Suppress("UnstableApiUsage")
class IncludeItemTypeGroup(name: String) : AbstractItemTypeGroup(name) { class IncludeItemTypeGroup(name: String) : AbstractItemTypeGroup(name) {
override fun createDefaultSet(): MutableSet<ItemType> { override fun createDefaultSet(): MutableSet<ItemType> {
return HashSet() return HashSet()

View file

@ -1,10 +1,8 @@
package xyz.alexcrea.cuanvil.group package xyz.alexcrea.cuanvil.group
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import io.papermc.paper.registry.RegistryAccess
import io.papermc.paper.registry.RegistryKey
import org.bukkit.NamespacedKey
import org.bukkit.configuration.ConfigurationSection import org.bukkit.configuration.ConfigurationSection
import xyz.alexcrea.cuanvil.util.ItemTypeUtil
import java.util.* import java.util.*
@SuppressWarnings("UnstableApiUsage") @SuppressWarnings("UnstableApiUsage")
@ -79,21 +77,10 @@ class ItemGroupManager {
config: ConfigurationSection, config: ConfigurationSection,
keys: Set<String> keys: Set<String>
) { ) {
val itemRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.ITEM)
// Read material to include in this group policy // Read material to include in this group policy
val materialList = groupSection.getStringList(MATERIAL_LIST_PATH) val materialList = groupSection.getStringList(MATERIAL_LIST_PATH)
for (typeName in materialList) { for (typeName in materialList) {
val key = NamespacedKey.fromString(typeName.lowercase()) val type = ItemTypeUtil.getItemType(typeName)
if (key == null) {
CustomAnvil.instance.logger.warning(
"Malformed item type $typeName on group ${group.getName()}"
)
continue
}
val type = itemRegistry.get(key)
if (type == null) { if (type == null) {
// Check if we should warn the user // Check if we should warn the user
if (typeName !in FUTURE_MATERIAL) { if (typeName !in FUTURE_MATERIAL) {

View file

@ -5,7 +5,6 @@ import io.delilaheve.util.ConfigOptions
import io.delilaheve.util.ItemUtil.canMergeWith import io.delilaheve.util.ItemUtil.canMergeWith
import io.delilaheve.util.ItemUtil.unitRepair import io.delilaheve.util.ItemUtil.unitRepair
import org.bukkit.GameMode import org.bukkit.GameMode
import org.bukkit.Material
import org.bukkit.entity.Player import org.bukkit.entity.Player
import org.bukkit.event.Event import org.bukkit.event.Event
import org.bukkit.event.EventHandler import org.bukkit.event.EventHandler
@ -13,6 +12,7 @@ import org.bukkit.event.Listener
import org.bukkit.event.inventory.ClickType import org.bukkit.event.inventory.ClickType
import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.ItemType
import org.bukkit.inventory.meta.BookMeta import org.bukkit.inventory.meta.BookMeta
import org.bukkit.inventory.view.AnvilView import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.dependency.DependencyManager
@ -24,6 +24,7 @@ import xyz.alexcrea.cuanvil.util.AnvilLoreEditUtil
import xyz.alexcrea.cuanvil.util.AnvilUseType import xyz.alexcrea.cuanvil.util.AnvilUseType
import xyz.alexcrea.cuanvil.util.AnvilXpUtil import xyz.alexcrea.cuanvil.util.AnvilXpUtil
import xyz.alexcrea.cuanvil.util.CustomRecipeUtil import xyz.alexcrea.cuanvil.util.CustomRecipeUtil
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.itemType
import xyz.alexcrea.cuanvil.util.UnitRepairUtil.getRepair import xyz.alexcrea.cuanvil.util.UnitRepairUtil.getRepair
import xyz.alexcrea.cuanvil.util.config.LoreEditConfigUtil import xyz.alexcrea.cuanvil.util.config.LoreEditConfigUtil
import xyz.alexcrea.cuanvil.util.config.LoreEditType import xyz.alexcrea.cuanvil.util.config.LoreEditType
@ -365,7 +366,7 @@ class AnvilResultListener : Listener {
rightItem: ItemStack, rightItem: ItemStack,
output: ItemStack, output: ItemStack,
): Boolean { ): Boolean {
if (Material.WRITABLE_BOOK != rightItem.type) return false if (ItemType.WRITABLE_BOOK != rightItem.itemType) return false
val bookMeta = rightItem.itemMeta as BookMeta? ?: return false val bookMeta = rightItem.itemMeta as BookMeta? ?: return false
val editType = AnvilLoreEditUtil.bookLoreEditIsAppend(leftItem, rightItem) ?: return false val editType = AnvilLoreEditUtil.bookLoreEditIsAppend(leftItem, rightItem) ?: return false
@ -437,7 +438,7 @@ class AnvilResultListener : Listener {
rightItem: ItemStack, rightItem: ItemStack,
output: ItemStack, output: ItemStack,
): Boolean { ): Boolean {
if (Material.PAPER != rightItem.type) return false if (ItemType.PAPER != rightItem.itemType) return false
val paperMeta = rightItem.itemMeta ?: return false val paperMeta = rightItem.itemMeta ?: return false
val editType = AnvilLoreEditUtil.paperLoreEditIsAppend(leftItem, rightItem) ?: return false val editType = AnvilLoreEditUtil.paperLoreEditIsAppend(leftItem, rightItem) ?: return false
@ -534,21 +535,21 @@ class AnvilResultListener : Listener {
} }
//check hotbare full //check hotbare full
var slotIndex = 8 var slotIndex = 8
while (slotIndex >= 0 && ((inventory.getItem(slotIndex)?.type ?: Material.AIR) != Material.AIR)) { while (slotIndex >= 0 && ((inventory.getItem(slotIndex)?.type ?: ItemType.AIR) != ItemType.AIR)) {
slotIndex-- slotIndex--
} }
if (slotIndex >= 0) { if (slotIndex >= 0) {
return SlotContainer(SlotType.INVENTORY, slotIndex) return SlotContainer(SlotType.INVENTORY, slotIndex)
} }
slotIndex = 35 //4*9 - 1 (max of player inventory) slotIndex = 35 //4*9 - 1 (max of player inventory)
while (slotIndex >= 9 && ((inventory.getItem(slotIndex)?.type ?: Material.AIR) != Material.AIR)) { while (slotIndex >= 9 && ((inventory.getItem(slotIndex)?.type ?: ItemType.AIR) != ItemType.AIR)) {
slotIndex-- slotIndex--
} }
if (slotIndex < 9) { if (slotIndex < 9) {
return NO_SLOT return NO_SLOT
} }
return SlotContainer(SlotType.INVENTORY, slotIndex) return SlotContainer(SlotType.INVENTORY, slotIndex)
} else if (player.itemOnCursor.type != Material.AIR) return NO_SLOT } else if (player.itemOnCursor.itemType != ItemType.AIR) return NO_SLOT
return CURSOR_SLOT return CURSOR_SLOT
} }

View file

@ -10,19 +10,20 @@ import io.delilaheve.util.ItemUtil.repairFrom
import io.delilaheve.util.ItemUtil.setEnchantmentsUnsafe import io.delilaheve.util.ItemUtil.setEnchantmentsUnsafe
import io.delilaheve.util.ItemUtil.unitRepair import io.delilaheve.util.ItemUtil.unitRepair
import org.bukkit.ChatColor import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import org.bukkit.event.EventHandler import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority import org.bukkit.event.EventPriority
import org.bukkit.event.Listener import org.bukkit.event.Listener
import org.bukkit.event.inventory.PrepareAnvilEvent import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.ItemType
import org.bukkit.inventory.meta.EnchantmentStorageMeta import org.bukkit.inventory.meta.EnchantmentStorageMeta
import org.bukkit.inventory.meta.ItemMeta import org.bukkit.inventory.meta.ItemMeta
import org.bukkit.inventory.view.AnvilView import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.dependency.DependencyManager
import xyz.alexcrea.cuanvil.enchant.CAEnchantment import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.util.* import xyz.alexcrea.cuanvil.util.*
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.itemType
import xyz.alexcrea.cuanvil.util.UnitRepairUtil.getRepair import xyz.alexcrea.cuanvil.util.UnitRepairUtil.getRepair
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
@ -322,13 +323,13 @@ class PrepareAnvilListener : Listener {
event: PrepareAnvilEvent, view: AnvilView, player: HumanEntity, event: PrepareAnvilEvent, view: AnvilView, player: HumanEntity,
first: ItemStack, second: ItemStack first: ItemStack, second: ItemStack
): Boolean { ): Boolean {
val type = second.type val type = second.itemType
var result: ItemStack? = null var result: ItemStack? = null
val xpCost = AtomicInteger() val xpCost = AtomicInteger()
if (Material.WRITABLE_BOOK == type) { if (ItemType.WRITABLE_BOOK == type) {
result = AnvilLoreEditUtil.tryLoreEditByBook(player, first, second, xpCost) result = AnvilLoreEditUtil.tryLoreEditByBook(player, first, second, xpCost)
} else if (Material.PAPER == type) { } else if (ItemType.PAPER == type) {
result = AnvilLoreEditUtil.tryLoreEditByPaper(player, first, second, xpCost) result = AnvilLoreEditUtil.tryLoreEditByPaper(player, first, second, xpCost)
} }

View file

@ -1,19 +1,20 @@
package xyz.alexcrea.cuanvil.recipe package xyz.alexcrea.cuanvil.recipe
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import org.bukkit.Material
import org.bukkit.configuration.file.FileConfiguration import org.bukkit.configuration.file.FileConfiguration
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.ItemType
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.itemType
class CustomAnvilRecipeManager { class CustomAnvilRecipeManager {
lateinit var recipeList: ArrayList<AnvilCustomRecipe> lateinit var recipeList: ArrayList<AnvilCustomRecipe>
lateinit var recipeByMat: HashMap<Material, ArrayList<AnvilCustomRecipe>> lateinit var recipeByType: HashMap<ItemType, ArrayList<AnvilCustomRecipe>>
fun prepareRecipes(config: FileConfiguration) { fun prepareRecipes(config: FileConfiguration) {
recipeList = ArrayList() recipeList = ArrayList()
recipeByMat = HashMap() recipeByType = HashMap()
// read all configs // read all configs
val keys = config.getKeys(false) val keys = config.getKeys(false)
@ -43,9 +44,9 @@ class CustomAnvilRecipeManager {
// Remove left item mat if exist // Remove left item mat if exist
val oldLeftItem = recipe.leftItem val oldLeftItem = recipe.leftItem
if (oldLeftItem != null) { if (oldLeftItem != null) {
val oldMat = oldLeftItem.type val oldMat = oldLeftItem.itemType
val test = recipeByMat[oldMat] val test = recipeByType[oldMat]
test!!.remove(recipe) test!!.remove(recipe)
} }
if (leftItem != null) { if (leftItem != null) {
@ -56,10 +57,10 @@ class CustomAnvilRecipeManager {
} }
private fun addToMatMap(recipe: AnvilCustomRecipe, leftItem: ItemStack) { private fun addToMatMap(recipe: AnvilCustomRecipe, leftItem: ItemStack) {
var recipeList = recipeByMat[leftItem.type] var recipeList = recipeByType[leftItem.itemType]
if (recipeList == null) { if (recipeList == null) {
recipeList = ArrayList() recipeList = ArrayList()
recipeByMat[leftItem.type] = recipeList recipeByType[leftItem.itemType] = recipeList
} }
recipeList.add(recipe) recipeList.add(recipe)

View file

@ -1,61 +1,61 @@
package xyz.alexcrea.cuanvil.util package xyz.alexcrea.cuanvil.util
import org.bukkit.Material import org.bukkit.inventory.ItemType
import xyz.alexcrea.cuanvil.config.WorkPenaltyType.WorkPenaltyPart import xyz.alexcrea.cuanvil.config.WorkPenaltyType.WorkPenaltyPart
import xyz.alexcrea.cuanvil.util.config.LoreEditType
@Suppress("UnstableApiUsage")
enum class AnvilUseType( enum class AnvilUseType(
val typeName: String, val path: String, val typeName: String, val path: String,
val defaultPenalty: WorkPenaltyPart, val defaultPenalty: WorkPenaltyPart,
val displayName: String, val displayMat: Material val displayName: String, val displayMat: ItemType
) { ) {
RENAME_ONLY( RENAME_ONLY(
"rename_only", "rename_only",
WorkPenaltyPart(false, true), WorkPenaltyPart(false, true),
"Rename Only", Material.NAME_TAG "Rename Only", ItemType.NAME_TAG
), ),
MERGE( MERGE(
"merge", "merge",
WorkPenaltyPart(true, true), WorkPenaltyPart(true, true),
"Merge", Material.ANVIL "Merge", ItemType.ANVIL
), ),
UNIT_REPAIR( UNIT_REPAIR(
"unit_repair", "unit_repair",
WorkPenaltyPart(true, true), WorkPenaltyPart(true, true),
"Unit Repair", Material.DIAMOND "Unit Repair", ItemType.DIAMOND
), ),
CUSTOM_CRAFT( CUSTOM_CRAFT(
"custom_craft", "custom_craft",
WorkPenaltyPart(false, false), WorkPenaltyPart(false, false),
"Custom Craft", Material.CRAFTING_TABLE "Custom Craft", ItemType.CRAFTING_TABLE
), ),
LORE_EDIT_BOOK_APPEND( LORE_EDIT_BOOK_APPEND(
"lore_edit_book_append", "lore_edit.book_and_quil.append", "lore_edit_book_append", "lore_edit.book_and_quil.append",
WorkPenaltyPart(false, false), WorkPenaltyPart(false, false),
"Book Add", Material.WRITABLE_BOOK "Book Add", ItemType.WRITABLE_BOOK
), ),
LORE_EDIT_BOOK_REMOVE( LORE_EDIT_BOOK_REMOVE(
"lore_edit_book_remove", "lore_edit.book_and_quil.remove", "lore_edit_book_remove", "lore_edit.book_and_quil.remove",
WorkPenaltyPart(false, false), WorkPenaltyPart(false, false),
"Book Remove", Material.WRITABLE_BOOK "Book Remove", ItemType.WRITABLE_BOOK
), ),
LORE_EDIT_PAPER_APPEND( LORE_EDIT_PAPER_APPEND(
"lore_edit_paper_append", "lore_edit.paper.append_line", "lore_edit_paper_append", "lore_edit.paper.append_line",
WorkPenaltyPart(false, false), WorkPenaltyPart(false, false),
"Paper Add", Material.WRITABLE_BOOK "Paper Add", ItemType.WRITABLE_BOOK
), ),
LORE_EDIT_PAPER_REMOVE( LORE_EDIT_PAPER_REMOVE(
"lore_edit_paper_remove", "lore_edit.paper.remove_line", "lore_edit_paper_remove", "lore_edit.paper.remove_line",
WorkPenaltyPart(false, false), WorkPenaltyPart(false, false),
"Paper Remove", Material.WRITABLE_BOOK "Paper Remove", ItemType.WRITABLE_BOOK
), ),
; ;
constructor( constructor(
typeName: String, typeName: String,
defaultPenalty: WorkPenaltyPart, defaultPenalty: WorkPenaltyPart,
displayName: String, displayMat: Material displayName: String, displayMat: ItemType
) : ) :
this( this(
typeName, typeName,

View file

@ -9,8 +9,6 @@ import org.bukkit.GameMode
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import org.bukkit.entity.Player import org.bukkit.entity.Player
import org.bukkit.inventory.AnvilInventory
import org.bukkit.inventory.InventoryView
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.Repairable import org.bukkit.inventory.meta.Repairable
import org.bukkit.inventory.view.AnvilView import org.bukkit.inventory.view.AnvilView

View file

@ -4,6 +4,7 @@ import io.delilaheve.CustomAnvil
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.recipe.AnvilCustomRecipe import xyz.alexcrea.cuanvil.recipe.AnvilCustomRecipe
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.itemType
import kotlin.math.min import kotlin.math.min
object CustomRecipeUtil { object CustomRecipeUtil {
@ -12,7 +13,7 @@ object CustomRecipeUtil {
leftItem: ItemStack, leftItem: ItemStack,
rightItem: ItemStack?) : AnvilCustomRecipe? { rightItem: ItemStack?) : AnvilCustomRecipe? {
val recipeList = ConfigHolder.CUSTOM_RECIPE_HOLDER.recipeManager.recipeByMat[leftItem.type] ?: return null val recipeList = ConfigHolder.CUSTOM_RECIPE_HOLDER.recipeManager.recipeByType[leftItem.itemType] ?: return null
CustomAnvil.verboseLog("Testing " + recipeList.size + " recipe...") CustomAnvil.verboseLog("Testing " + recipeList.size + " recipe...")
for (recipe in recipeList) { for (recipe in recipeList) {

View file

@ -0,0 +1,43 @@
package xyz.alexcrea.cuanvil.util
import org.bukkit.NamespacedKey
import org.bukkit.Registry
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.ItemType
object ItemTypeUtil {
/**
* Get item type by its name
* @return the item type or null if absent or malformed key
*/
fun getItemType(name: String): ItemType? {
val key = NamespacedKey.fromString(name.lowercase())
if (key == null) return null;
return Registry.ITEM.get(key)
}
/**
* Get item type by its name
* @return the item type or null if absent or malformed key
*/
fun getItemTypeExact(name: String): ItemType? {
val key = NamespacedKey.fromString(name)
if (key == null) return null;
return Registry.ITEM.get(key)
}
fun ItemType.name(): String {
return this.key.key
}
val ItemStack.itemType: ItemType
get() {
// we assume material of an item stack is a material of an item...
return this.type.asItemType()!!
}
}

View file

@ -3,6 +3,7 @@ package xyz.alexcrea.cuanvil.util
import org.bukkit.configuration.ConfigurationSection import org.bukkit.configuration.ConfigurationSection
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.util.ItemTypeUtil.itemType
object UnitRepairUtil { object UnitRepairUtil {
@ -21,14 +22,16 @@ object UnitRepairUtil {
): Double? { ): Double? {
if (other == null) return null if (other == null) return null
val config = ConfigHolder.UNIT_REPAIR_HOLDER.config val config = ConfigHolder.UNIT_REPAIR_HOLDER.config
// Get configuration section if exist
val otherName = other.type.name.lowercase()
var section = config.getConfigurationSection(otherName)
if (section == null) {
section = config.getConfigurationSection(otherName.uppercase())
if (section == null) return null
val otherKey = other.itemType.key
// Get configuration section if exist
var section = config.getConfigurationSection(otherKey.toString())
if (section == null) {
section = config.getConfigurationSection(otherKey.key)
if (section == null) return null
} }
// Get repair amount // Get repair amount
var userDefault = config.getDouble(UNIT_REPAIR_DEFAULT_PATH, DEFAULT_DEFAULT_UNIT_REPAIR) var userDefault = config.getDouble(UNIT_REPAIR_DEFAULT_PATH, DEFAULT_DEFAULT_UNIT_REPAIR)
if (userDefault <= 0) { if (userDefault <= 0) {
@ -44,14 +47,16 @@ object UnitRepairUtil {
* If value is set to less than or equal to 0 then it will be set to default * If value is set to less than or equal to 0 then it will be set to default
*/ */
private fun getRepairAmount(item: ItemStack, section: ConfigurationSection, default: Double): Double? { private fun getRepairAmount(item: ItemStack, section: ConfigurationSection, default: Double): Double? {
val itemName = item.type.name.lowercase() val itemKey = item.itemType.key
val repairValue = if (section.isDouble(itemName)) {
section.getDouble(itemName) val repairValue = if (section.isDouble(itemKey.toString())) {
} else if (section.isDouble(itemName.uppercase())) { section.getDouble(itemKey.toString())
section.getDouble(itemName.uppercase()) } else if (section.isDouble(itemKey.key)) {
section.getDouble(itemKey.key)
} else { } else {
return null return null
} }
if (repairValue <= 0) if (repairValue <= 0)
return default return default
return repairValue return repairValue

View file

@ -1,24 +1,24 @@
package io.delilaheve.util; package io.delilaheve.util;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachment;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockbukkit.mockbukkit.entity.PlayerMock; import org.mockbukkit.mockbukkit.entity.PlayerMock;
import org.mockbukkit.mockbukkit.inventory.ItemStackMock;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.tests.ConfigResetCustomAnvilTest;
import xyz.alexcrea.cuanvil.data.AnvilFuseTestData; import xyz.alexcrea.cuanvil.data.AnvilFuseTestData;
import xyz.alexcrea.cuanvil.tests.ConfigResetCustomAnvilTest;
import xyz.alexcrea.cuanvil.util.AnvilFuseTestUtil; import xyz.alexcrea.cuanvil.util.AnvilFuseTestUtil;
import java.util.List; import java.util.List;
@SuppressWarnings("UnstableApiUsage")
public class EnchantmentUtilTests extends ConfigResetCustomAnvilTest { public class EnchantmentUtilTests extends ConfigResetCustomAnvilTest {
private AnvilInventory anvil; private AnvilInventory anvil;
@ -48,21 +48,21 @@ public class EnchantmentUtilTests extends ConfigResetCustomAnvilTest {
"Caution with that as it will break some server CustomAnvil setup."); "Caution with that as it will break some server CustomAnvil setup.");
// Create ingredient item // Create ingredient item
ItemStack normalStick = new ItemStackMock(Material.STICK); ItemStack normalStick = ItemType.STICK.createItemStack();
ItemStack sharpnessBook = AnvilFuseTestUtil.prepareItem( ItemStack sharpnessBook = AnvilFuseTestUtil.prepareItem(
Material.ENCHANTED_BOOK, ItemType.ENCHANTED_BOOK,
List.of("sharpness"), 1); List.of("sharpness"), 1);
ItemStack sharpnessStick = AnvilFuseTestUtil.prepareItem( ItemStack sharpnessStick = AnvilFuseTestUtil.prepareItem(
Material.STICK, ItemType.STICK,
List.of("sharpness"), 1); List.of("sharpness"), 1);
// Create result item // Create result item
ItemStack sharpnessResultStick = AnvilFuseTestUtil.prepareItem( ItemStack sharpnessResultStick = AnvilFuseTestUtil.prepareItem(
Material.STICK, 1, ItemType.STICK, 1,
List.of("sharpness"), 1); List.of("sharpness"), 1);
ItemStack sharpness2ResultStick = AnvilFuseTestUtil.prepareItem( ItemStack sharpness2ResultStick = AnvilFuseTestUtil.prepareItem(
Material.STICK, 1, ItemType.STICK, 1,
List.of("sharpness"), 2); List.of("sharpness"), 2);
// Create failing anvil fuse data // Create failing anvil fuse data
@ -108,25 +108,25 @@ public class EnchantmentUtilTests extends ConfigResetCustomAnvilTest {
// Create ingredient item // Create ingredient item
ItemStack sharpness5Sword = AnvilFuseTestUtil.prepareItem( ItemStack sharpness5Sword = AnvilFuseTestUtil.prepareItem(
Material.DIAMOND_SWORD, ItemType.DIAMOND_SWORD,
List.of("sharpness"), 5); List.of("sharpness"), 5);
ItemStack sharpnessBook = AnvilFuseTestUtil.prepareItem( ItemStack sharpnessBook = AnvilFuseTestUtil.prepareItem(
Material.ENCHANTED_BOOK, ItemType.ENCHANTED_BOOK,
List.of("sharpness"), 1); List.of("sharpness"), 1);
ItemStack sharpness5Book = AnvilFuseTestUtil.prepareItem( ItemStack sharpness5Book = AnvilFuseTestUtil.prepareItem(
Material.ENCHANTED_BOOK, ItemType.ENCHANTED_BOOK,
List.of("sharpness"), 5); List.of("sharpness"), 5);
ItemStack sharpness6Book = AnvilFuseTestUtil.prepareItem( ItemStack sharpness6Book = AnvilFuseTestUtil.prepareItem(
Material.ENCHANTED_BOOK, ItemType.ENCHANTED_BOOK,
List.of("sharpness"), 6); List.of("sharpness"), 6);
// Create result item // Create result item
ItemStack sharpness2BookResult = AnvilFuseTestUtil.prepareItem( ItemStack sharpness2BookResult = AnvilFuseTestUtil.prepareItem(
Material.ENCHANTED_BOOK, 1, ItemType.ENCHANTED_BOOK, 1,
List.of("sharpness"), 2); List.of("sharpness"), 2);
ItemStack sharpness6SwordResult = AnvilFuseTestUtil.prepareItem( ItemStack sharpness6SwordResult = AnvilFuseTestUtil.prepareItem(
Material.DIAMOND_SWORD, 1, ItemType.DIAMOND_SWORD, 1,
List.of("sharpness"), 6); List.of("sharpness"), 6);
// Create failing anvil fuse data // Create failing anvil fuse data

View file

@ -2,11 +2,11 @@ package xyz.alexcrea.cuanvil.anvil;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.Repairable; import org.bukkit.inventory.meta.Repairable;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
@ -15,11 +15,11 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockbukkit.mockbukkit.entity.PlayerMock; import org.mockbukkit.mockbukkit.entity.PlayerMock;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.tests.SharedCustomAnvilTest;
import xyz.alexcrea.cuanvil.data.AnvilFuseTestData; import xyz.alexcrea.cuanvil.data.AnvilFuseTestData;
import xyz.alexcrea.cuanvil.util.AnvilFuseTestUtil; import xyz.alexcrea.cuanvil.tests.SharedCustomAnvilTest;
import xyz.alexcrea.cuanvil.util.CommonItemUtil; import xyz.alexcrea.cuanvil.util.CommonItemUtil;
@SuppressWarnings("UnstableApiUsage")
public class AnvilFuseTests extends SharedCustomAnvilTest { public class AnvilFuseTests extends SharedCustomAnvilTest {
private static AnvilInventory anvil; private static AnvilInventory anvil;
@ -107,7 +107,7 @@ public class AnvilFuseTests extends SharedCustomAnvilTest {
// Note: currently anvil can only have null name. maybe handle differently later // Note: currently anvil can only have null name. maybe handle differently later
@Test @Test
public void nullNameResetTest(){ public void nullNameResetTest(){
ItemStack base = new ItemStack(Material.NETHERITE_SWORD); ItemStack base = ItemType.NETHERITE_SWORD.createItemStack();
ItemStack expected = base.clone(); ItemStack expected = base.clone();
ItemMeta meta = expected.getItemMeta(); ItemMeta meta = expected.getItemMeta();

View file

@ -1,12 +1,12 @@
package xyz.alexcrea.cuanvil.anvil; package xyz.alexcrea.cuanvil.anvil;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -29,6 +29,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@SuppressWarnings("UnstableApiUsage")
public class LoreEditTests extends SharedCustomAnvilTest { public class LoreEditTests extends SharedCustomAnvilTest {
private static AnvilInventory anvil; private static AnvilInventory anvil;
@ -93,7 +94,7 @@ public class LoreEditTests extends SharedCustomAnvilTest {
ConfigHolder.DEFAULT_CONFIG.getConfig().set(ConfigOptions.VERBOSE_DEBUG_LOGGING, true); ConfigHolder.DEFAULT_CONFIG.getConfig().set(ConfigOptions.VERBOSE_DEBUG_LOGGING, true);
// Applied item // Applied item
ItemStack item = new ItemStack(Material.STICK, 33); ItemStack item = ItemType.STICK.createItemStack(33);
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
ArrayList<String> lore = new ArrayList<>(); ArrayList<String> lore = new ArrayList<>();
@ -122,7 +123,7 @@ public class LoreEditTests extends SharedCustomAnvilTest {
lore.clear(); lore.clear();
// Paper items // Paper items
item = new ItemStack(Material.PAPER, 64); item = ItemType.PAPER.createItemStack(64);
meta = item.getItemMeta(); meta = item.getItemMeta();
emptyPaperStack = item.clone(); emptyPaperStack = item.clone();
item.setAmount(63); item.setAmount(63);
@ -149,7 +150,7 @@ public class LoreEditTests extends SharedCustomAnvilTest {
uncoloredPaperOne = item.clone(); uncoloredPaperOne = item.clone();
// Book items // Book items
item = new ItemStack(Material.WRITABLE_BOOK); item = ItemType.WRITABLE_BOOK.createItemStack();
BookMeta bookmeta = (BookMeta) item.getItemMeta(); BookMeta bookmeta = (BookMeta) item.getItemMeta();
emptyBook = item.clone(); emptyBook = item.clone();

View file

@ -1,14 +1,13 @@
package xyz.alexcrea.cuanvil.api; package xyz.alexcrea.cuanvil.api;
import org.bukkit.inventory.ItemType;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import xyz.alexcrea.cuanvil.tests.SharedOnlyMockBukkit; import xyz.alexcrea.cuanvil.tests.SharedOnlyMockBukkit;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@SuppressWarnings("UnstableApiUsage")
public class AnvilRecipeBuilderTest extends SharedOnlyMockBukkit { public class AnvilRecipeBuilderTest extends SharedOnlyMockBukkit {
private AnvilRecipeBuilder builder; private AnvilRecipeBuilder builder;
@ -19,56 +18,56 @@ public class AnvilRecipeBuilderTest extends SharedOnlyMockBukkit {
builder = new AnvilRecipeBuilder("test"); builder = new AnvilRecipeBuilder("test");
builder2 = new AnvilRecipeBuilder("test"); builder2 = new AnvilRecipeBuilder("test");
builder2.setLeftItem(new ItemStack(Material.STICK)); builder2.setLeftItem(ItemType.STICK.createItemStack());
builder2.setResultItem(new ItemStack(Material.STICK)); builder2.setResultItem(ItemType.STICK.createItemStack());
} }
@Test @Test
void createBuilder_NoLeftItem(){ void createBuilder_NoLeftItem() {
builder.setResultItem(new ItemStack(Material.STICK)); builder.setResultItem(ItemType.STICK.createItemStack());
assertNull(builder.build()); assertNull(builder.build());
} }
@Test @Test
void createBuilder_NoResultItem(){ void createBuilder_NoResultItem() {
builder.setLeftItem(new ItemStack(Material.STICK)); builder.setLeftItem(ItemType.STICK.createItemStack());
assertNull(builder.build()); assertNull(builder.build());
} }
@Test @Test
void createBuilder_minimalist(){ void createBuilder_minimalist() {
builder.setLeftItem(new ItemStack(Material.STICK)) builder.setLeftItem(ItemType.STICK.createItemStack())
.setResultItem(new ItemStack(Material.STICK)); .setResultItem(ItemType.STICK.createItemStack());
assertNotNull(builder.build()); assertNotNull(builder.build());
assertNotNull(builder2.build()); assertNotNull(builder2.build());
} }
@Test @Test
void setLeftItem(){ void setLeftItem() {
assertNull(builder.getLeftItem()); assertNull(builder.getLeftItem());
builder.setLeftItem(new ItemStack(Material.STICK)); builder.setLeftItem(ItemType.STICK.createItemStack());
assertNotNull(builder.getLeftItem()); assertNotNull(builder.getLeftItem());
} }
@Test @Test
void setRightItem(){ void setRightItem() {
assertNull(builder.getRightItem()); assertNull(builder.getRightItem());
builder.setRightItem(new ItemStack(Material.STICK)); builder.setRightItem(ItemType.STICK.createItemStack());
assertNotNull(builder.getRightItem()); assertNotNull(builder.getRightItem());
} }
@Test @Test
void setResultItem(){ void setResultItem() {
assertNull(builder.getResultItem()); assertNull(builder.getResultItem());
builder.setResultItem(new ItemStack(Material.STICK)); builder.setResultItem(ItemType.STICK.createItemStack());
assertNotNull(builder.getResultItem()); assertNotNull(builder.getResultItem());
} }
@Test @Test
void setXpCostPerCraft(){ void setXpCostPerCraft() {
assertEquals(0, builder2.getLevelCostPerCraft()); assertEquals(0, builder2.getLevelCostPerCraft());
assertEquals(0, builder2.build().getLevelCostPerCraft()); assertEquals(0, builder2.build().getLevelCostPerCraft());
builder2.setLevelCostPerCraft(2); builder2.setLevelCostPerCraft(2);
@ -77,7 +76,7 @@ public class AnvilRecipeBuilderTest extends SharedOnlyMockBukkit {
} }
@Test @Test
void setLinearXpCostPerCraft(){ void setLinearXpCostPerCraft() {
assertEquals(0, builder2.getLinearXpCostPerCraft()); assertEquals(0, builder2.getLinearXpCostPerCraft());
assertEquals(0, builder2.build().getXpCostPerCraft()); assertEquals(0, builder2.build().getXpCostPerCraft());
builder2.setLinearXpCostPerCraft(2); builder2.setLinearXpCostPerCraft(2);
@ -87,7 +86,7 @@ public class AnvilRecipeBuilderTest extends SharedOnlyMockBukkit {
@Test @Test
void setExactCount(){ void setExactCount() {
assertTrue(builder2.isExactCount()); assertTrue(builder2.isExactCount());
assertTrue(builder2.build().getExactCount()); assertTrue(builder2.build().getExactCount());
builder2.setExactCount(false); builder2.setExactCount(false);
@ -96,7 +95,7 @@ public class AnvilRecipeBuilderTest extends SharedOnlyMockBukkit {
} }
@Test @Test
void setName(){ void setName() {
assertEquals("test", builder2.getName()); assertEquals("test", builder2.getName());
assertEquals("test", builder2.build().getName()); assertEquals("test", builder2.build().getName());
builder2.setName("other"); builder2.setName("other");

View file

@ -1,11 +1,11 @@
package xyz.alexcrea.cuanvil.api; package xyz.alexcrea.cuanvil.api;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
@ -13,10 +13,10 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockbukkit.mockbukkit.entity.PlayerMock; import org.mockbukkit.mockbukkit.entity.PlayerMock;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.data.AnvilFuseTestData;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment; import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.group.EnchantConflictGroup; import xyz.alexcrea.cuanvil.group.EnchantConflictGroup;
import xyz.alexcrea.cuanvil.tests.ConfigResetCustomAnvilTest; import xyz.alexcrea.cuanvil.tests.ConfigResetCustomAnvilTest;
import xyz.alexcrea.cuanvil.data.AnvilFuseTestData;
import xyz.alexcrea.cuanvil.util.AnvilFuseTestUtil; import xyz.alexcrea.cuanvil.util.AnvilFuseTestUtil;
import xyz.alexcrea.cuanvil.util.CommonItemUtil; import xyz.alexcrea.cuanvil.util.CommonItemUtil;
@ -25,6 +25,7 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@SuppressWarnings("UnstableApiUsage")
public class ConflictApiTests extends ConfigResetCustomAnvilTest { public class ConflictApiTests extends ConfigResetCustomAnvilTest {
private AnvilInventory anvil; private AnvilInventory anvil;
@ -51,7 +52,7 @@ public class ConflictApiTests extends ConfigResetCustomAnvilTest {
ItemStack sharpness1 = CommonItemUtil.sharpness(1); ItemStack sharpness1 = CommonItemUtil.sharpness(1);
ItemStack arthropods1 = CommonItemUtil.bane_of_arthropods(1); ItemStack arthropods1 = CommonItemUtil.bane_of_arthropods(1);
ItemStack illegalResult = AnvilFuseTestUtil.prepareItem( ItemStack illegalResult = AnvilFuseTestUtil.prepareItem(
Material.DIAMOND_SWORD, 1, ItemType.DIAMOND_SWORD, 1,
List.of("bane_of_arthropods", "sharpness"), List.of("bane_of_arthropods", "sharpness"),
1, 1 1, 1
); );

View file

@ -1,25 +1,25 @@
package xyz.alexcrea.cuanvil.api; package xyz.alexcrea.cuanvil.api;
import org.bukkit.Material;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockbukkit.mockbukkit.entity.PlayerMock; import org.mockbukkit.mockbukkit.entity.PlayerMock;
import org.mockbukkit.mockbukkit.inventory.ItemStackMock;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.data.AnvilClickTestData; import xyz.alexcrea.cuanvil.data.AnvilClickTestData;
import xyz.alexcrea.cuanvil.data.AnvilFuseTestData;
import xyz.alexcrea.cuanvil.data.TestDataContainer; import xyz.alexcrea.cuanvil.data.TestDataContainer;
import xyz.alexcrea.cuanvil.recipe.AnvilCustomRecipe; import xyz.alexcrea.cuanvil.recipe.AnvilCustomRecipe;
import xyz.alexcrea.cuanvil.tests.ConfigResetCustomAnvilTest; import xyz.alexcrea.cuanvil.tests.ConfigResetCustomAnvilTest;
import xyz.alexcrea.cuanvil.data.AnvilFuseTestData;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@SuppressWarnings("UnstableApiUsage")
public class CustomAnvilRecipeApiTests extends ConfigResetCustomAnvilTest { public class CustomAnvilRecipeApiTests extends ConfigResetCustomAnvilTest {
private AnvilInventory anvil; private AnvilInventory anvil;
@ -44,7 +44,7 @@ public class CustomAnvilRecipeApiTests extends ConfigResetCustomAnvilTest {
@Test @Test
public void testBasicRecipe() { public void testBasicRecipe() {
String recipeName = "stick_recipe"; String recipeName = "stick_recipe";
ItemStack stick = new ItemStackMock(Material.STICK); ItemStack stick = ItemType.STICK.createItemStack();
AnvilFuseTestData nullResultData = new AnvilFuseTestData( AnvilFuseTestData nullResultData = new AnvilFuseTestData(
stick, stick, stick, stick,
@ -97,10 +97,10 @@ public class CustomAnvilRecipeApiTests extends ConfigResetCustomAnvilTest {
@Test @Test
public void testUnitRecipe() { public void testUnitRecipe() {
String recipeName = "stick_recipe"; String recipeName = "stick_recipe";
ItemStack stick = new ItemStackMock(Material.STICK); ItemStack stick = ItemType.STICK.createItemStack();
ItemStack stick2 = new ItemStackMock(Material.STICK, 2); ItemStack stick2 = ItemType.STICK.createItemStack(2);
ItemStack stick5 = new ItemStackMock(Material.STICK, 5); ItemStack stick5 = ItemType.STICK.createItemStack(5);
ItemStack stick10 = new ItemStackMock(Material.STICK, 10); ItemStack stick10 = ItemType.STICK.createItemStack(10);
AnvilFuseTestData nullResultData = new AnvilFuseTestData( AnvilFuseTestData nullResultData = new AnvilFuseTestData(
stick, stick, stick, stick,
@ -139,10 +139,10 @@ public class CustomAnvilRecipeApiTests extends ConfigResetCustomAnvilTest {
@Test @Test
public void testLinearXpCost() { public void testLinearXpCost() {
String recipeName = "stick_recipe"; String recipeName = "stick_recipe";
ItemStack stick = new ItemStackMock(Material.STICK); ItemStack stick = ItemType.STICK.createItemStack();
ItemStack stick2 = new ItemStackMock(Material.STICK, 2); ItemStack stick2 = ItemType.STICK.createItemStack(2);
ItemStack stick5 = new ItemStackMock(Material.STICK, 5); ItemStack stick5 = ItemType.STICK.createItemStack(5);
ItemStack stick10 = new ItemStackMock(Material.STICK, 10); ItemStack stick10 = ItemType.STICK.createItemStack(10);
AnvilFuseTestData nullResultData = new AnvilFuseTestData( AnvilFuseTestData nullResultData = new AnvilFuseTestData(
@ -193,10 +193,10 @@ public class CustomAnvilRecipeApiTests extends ConfigResetCustomAnvilTest {
@Test @Test
public void testLinearXpCostRemoveExact() { public void testLinearXpCostRemoveExact() {
String recipeName = "stick_recipe"; String recipeName = "stick_recipe";
ItemStack stick = new ItemStackMock(Material.STICK); ItemStack stick = ItemType.STICK.createItemStack();
ItemStack stick2 = new ItemStackMock(Material.STICK, 2); ItemStack stick2 = ItemType.STICK.createItemStack(2);
ItemStack stick5 = new ItemStackMock(Material.STICK, 5); ItemStack stick5 = ItemType.STICK.createItemStack(5);
ItemStack stick10 = new ItemStackMock(Material.STICK, 10); ItemStack stick10 = ItemType.STICK.createItemStack(10);
AnvilFuseTestData nullResultData = new AnvilFuseTestData( AnvilFuseTestData nullResultData = new AnvilFuseTestData(
stick, stick, stick, stick,

View file

@ -1,23 +1,23 @@
package xyz.alexcrea.cuanvil.api; package xyz.alexcrea.cuanvil.api;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.Repairable; import org.bukkit.inventory.meta.Repairable;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockbukkit.mockbukkit.entity.PlayerMock; import org.mockbukkit.mockbukkit.entity.PlayerMock;
import org.mockbukkit.mockbukkit.inventory.ItemStackMock;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.tests.ConfigResetCustomAnvilTest;
import xyz.alexcrea.cuanvil.data.AnvilFuseTestData; import xyz.alexcrea.cuanvil.data.AnvilFuseTestData;
import xyz.alexcrea.cuanvil.util.AnvilFuseTestUtil; import xyz.alexcrea.cuanvil.tests.ConfigResetCustomAnvilTest;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SuppressWarnings("UnstableApiUsage")
public class UnitRepairApiTests extends ConfigResetCustomAnvilTest { public class UnitRepairApiTests extends ConfigResetCustomAnvilTest {
private AnvilInventory anvil; private AnvilInventory anvil;
@ -40,17 +40,17 @@ public class UnitRepairApiTests extends ConfigResetCustomAnvilTest {
} }
@Test @Test
void vanillaUnitRepair(){ void vanillaUnitRepair() {
ItemStack damagedPickaxe = new ItemStackMock(Material.DIAMOND_PICKAXE); ItemStack damagedPickaxe = ItemType.DIAMOND_PICKAXE.createItemStack();
damagedPickaxe.setDurability((short) (Material.DIAMOND_PICKAXE.getMaxDurability() -1)); damagedPickaxe.setDurability((short) (ItemType.DIAMOND_PICKAXE.getMaxDurability() - 1));
ItemStack resultPickaxe = new ItemStackMock(Material.DIAMOND_PICKAXE); ItemStack resultPickaxe = ItemType.DIAMOND_PICKAXE.createItemStack();
resultPickaxe.setDurability((short) (Material.DIAMOND_PICKAXE.getMaxDurability()/2)); resultPickaxe.setDurability((short) (ItemType.DIAMOND_PICKAXE.getMaxDurability() / 2));
ItemMeta meta = resultPickaxe.getItemMeta(); ItemMeta meta = resultPickaxe.getItemMeta();
((Repairable) meta).setRepairCost(1); ((Repairable) meta).setRepairCost(1);
resultPickaxe.setItemMeta(meta); resultPickaxe.setItemMeta(meta);
ItemStack diamond2 = new ItemStackMock(Material.DIAMOND, 2); ItemStack diamond2 = ItemType.DIAMOND.createItemStack(2);
AnvilFuseTestData legalResultData = new AnvilFuseTestData( AnvilFuseTestData legalResultData = new AnvilFuseTestData(
damagedPickaxe, diamond2, damagedPickaxe, diamond2,
@ -62,11 +62,11 @@ public class UnitRepairApiTests extends ConfigResetCustomAnvilTest {
} }
@Test @Test
void removeUnitRepair(){ void removeUnitRepair() {
ItemStack damagedPickaxe = new ItemStackMock(Material.DIAMOND_PICKAXE); ItemStack damagedPickaxe = ItemType.DIAMOND_PICKAXE.createItemStack();
damagedPickaxe.setDurability((short) (Material.DIAMOND_PICKAXE.getMaxDurability() -1)); damagedPickaxe.setDurability((short) (ItemType.DIAMOND_PICKAXE.getMaxDurability() - 1));
ItemStack diamond2 = new ItemStackMock(Material.DIAMOND, 2); ItemStack diamond2 = ItemType.DIAMOND.createItemStack(2);
AnvilFuseTestData nullResultData = new AnvilFuseTestData( AnvilFuseTestData nullResultData = new AnvilFuseTestData(
damagedPickaxe, diamond2, damagedPickaxe, diamond2,
@ -74,28 +74,28 @@ public class UnitRepairApiTests extends ConfigResetCustomAnvilTest {
); );
// Remove unit repair // Remove unit repair
assertTrue(UnitRepairApi.removeUnitRepair(Material.DIAMOND, Material.DIAMOND_PICKAXE)); assertTrue(UnitRepairApi.removeUnitRepair(ItemType.DIAMOND, ItemType.DIAMOND_PICKAXE));
nullResultData.executeTest(anvil, player); nullResultData.executeTest(anvil, player);
// see override // see override
assertFalse(UnitRepairApi.addUnitRepair(Material.DIAMOND, Material.DIAMOND_PICKAXE, 0.25)); assertFalse(UnitRepairApi.addUnitRepair(ItemType.DIAMOND, ItemType.DIAMOND_PICKAXE, 0.25));
assertTrue(UnitRepairApi.addUnitRepair(Material.DIAMOND, Material.DIAMOND_PICKAXE, 0.25, true)); assertTrue(UnitRepairApi.addUnitRepair(ItemType.DIAMOND, ItemType.DIAMOND_PICKAXE, 0.25, true));
} }
@Test @Test
void addUnitRepair(){ void addUnitRepair() {
ItemStack damagedPickaxe = new ItemStackMock(Material.DIAMOND_PICKAXE); ItemStack damagedPickaxe = ItemType.DIAMOND_PICKAXE.createItemStack();
damagedPickaxe.setDurability((short) (Material.DIAMOND_PICKAXE.getMaxDurability() -1)); damagedPickaxe.setDurability((short) (ItemType.DIAMOND_PICKAXE.getMaxDurability() - 1));
ItemStack resultPickaxe = new ItemStackMock(Material.DIAMOND_PICKAXE); ItemStack resultPickaxe = ItemType.DIAMOND_PICKAXE.createItemStack();
resultPickaxe.setDurability((short) (Material.DIAMOND_PICKAXE.getMaxDurability()/2)); resultPickaxe.setDurability((short) (ItemType.DIAMOND_PICKAXE.getMaxDurability() / 2));
ItemMeta meta = resultPickaxe.getItemMeta(); ItemMeta meta = resultPickaxe.getItemMeta();
((Repairable) meta).setRepairCost(1); ((Repairable) meta).setRepairCost(1);
resultPickaxe.setItemMeta(meta); resultPickaxe.setItemMeta(meta);
ItemStack stick2 = new ItemStackMock(Material.STICK, 2); ItemStack stick2 = ItemType.STICK.createItemStack(2);
AnvilFuseTestData nullResultData = new AnvilFuseTestData( AnvilFuseTestData nullResultData = new AnvilFuseTestData(
damagedPickaxe, stick2, damagedPickaxe, stick2,
@ -110,8 +110,8 @@ public class UnitRepairApiTests extends ConfigResetCustomAnvilTest {
nullResultData.executeTest(anvil, player); nullResultData.executeTest(anvil, player);
// Add unit repair // Add unit repair
assertTrue(UnitRepairApi.addUnitRepair(Material.STICK, Material.DIAMOND_PICKAXE)); assertTrue(UnitRepairApi.addUnitRepair(ItemType.STICK, ItemType.DIAMOND_PICKAXE));
assertFalse(UnitRepairApi.addUnitRepair(Material.STICK, Material.DIAMOND_PICKAXE)); assertFalse(UnitRepairApi.addUnitRepair(ItemType.STICK, ItemType.DIAMOND_PICKAXE));
legalResultData.executeTest(anvil, player); legalResultData.executeTest(anvil, player);
} }

View file

@ -7,7 +7,6 @@ import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import xyz.alexcrea.cuanvil.util.AnvilFuseTestUtil;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public record TestDataContainer( public record TestDataContainer(

View file

@ -1,13 +1,13 @@
package xyz.alexcrea.cuanvil.util; package xyz.alexcrea.cuanvil.util;
import io.delilaheve.util.ItemUtil; import io.delilaheve.util.ItemUtil;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.inventory.*; import org.bukkit.event.inventory.*;
import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.Repairable; import org.bukkit.inventory.meta.Repairable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -24,18 +24,19 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@SuppressWarnings("UnstableApiUsage")
public class AnvilFuseTestUtil { public class AnvilFuseTestUtil {
private static PrepareAnvilListener PREPARE_LISTENER = new PrepareAnvilListener(); private static PrepareAnvilListener PREPARE_LISTENER = new PrepareAnvilListener();
private static AnvilResultListener RESULT_LISTENER = new AnvilResultListener(); private static AnvilResultListener RESULT_LISTENER = new AnvilResultListener();
public static ItemStack prepareItem(@NotNull Material material, public static ItemStack prepareItem(@NotNull ItemType type,
@NotNull List<CAEnchantment> enchantments, @NotNull List<CAEnchantment> enchantments,
@NotNull List<Integer> level) { @NotNull List<Integer> level) {
return prepareItem(material, 0, enchantments, level); return prepareItem(type, 0, enchantments, level);
} }
public static ItemStack prepareItem(@NotNull Material material, public static ItemStack prepareItem(@NotNull ItemType type,
int repairCost, int repairCost,
@NotNull List<CAEnchantment> enchantments, @NotNull List<CAEnchantment> enchantments,
@NotNull List<Integer> level) { @NotNull List<Integer> level) {
@ -46,7 +47,7 @@ public class AnvilFuseTestUtil {
enchantmentMap.put(enchantments.get(i), level.get(i)); enchantmentMap.put(enchantments.get(i), level.get(i));
} }
ItemStack item = new ItemStack(material); ItemStack item = type.createItemStack();
ItemUtil.INSTANCE.setEnchantmentsUnsafe(item, enchantmentMap); ItemUtil.INSTANCE.setEnchantmentsUnsafe(item, enchantmentMap);
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
@ -57,13 +58,13 @@ public class AnvilFuseTestUtil {
} }
public static ItemStack prepareItem(@NotNull Material material, public static ItemStack prepareItem(@NotNull ItemType type,
@NotNull List<String> enchantmentNames, @NotNull List<String> enchantmentNames,
Integer... levels) { Integer... levels) {
return prepareItem(material, 0, enchantmentNames, levels); return prepareItem(type, 0, enchantmentNames, levels);
} }
public static ItemStack prepareItem(@NotNull Material material, public static ItemStack prepareItem(@NotNull ItemType type,
int repairCost, int repairCost,
@NotNull List<String> enchantmentNames, @NotNull List<String> enchantmentNames,
Integer... levels) { Integer... levels) {
@ -77,7 +78,7 @@ public class AnvilFuseTestUtil {
enchantments.addAll(enchantmentList); enchantments.addAll(enchantmentList);
} }
return prepareItem(material, repairCost, enchantments, List.of(levels)); return prepareItem(type, repairCost, enchantments, List.of(levels));
} }

View file

@ -1,15 +1,16 @@
package xyz.alexcrea.cuanvil.util; package xyz.alexcrea.cuanvil.util;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ItemType;
import java.util.List; import java.util.List;
@SuppressWarnings("UnstableApiUsage")
public class CommonItemUtil { public class CommonItemUtil {
public static ItemStack sharpness(int level){ public static ItemStack sharpness(int level){
return AnvilFuseTestUtil.prepareItem( return AnvilFuseTestUtil.prepareItem(
Material.DIAMOND_SWORD, ItemType.DIAMOND_SWORD,
List.of("sharpness"), List.of("sharpness"),
level level
); );
@ -17,11 +18,10 @@ public class CommonItemUtil {
public static ItemStack bane_of_arthropods(int level){ public static ItemStack bane_of_arthropods(int level){
return AnvilFuseTestUtil.prepareItem( return AnvilFuseTestUtil.prepareItem(
Material.DIAMOND_SWORD, ItemType.DIAMOND_SWORD,
List.of("bane_of_arthropods"), List.of("bane_of_arthropods"),
level level
); );
} }
} }