().configureEach {
- sourceCompatibility = "21"
- targetCompatibility = "21"
-
- options.encoding = "UTF-8"
-}
-
-kotlin {
- compilerOptions {
- apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
- jvmTarget.set(JvmTarget.JVM_21)
- }
-}
diff --git a/nms/v1_21R7/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R7_PacketManager.kt b/nms/v1_21R7/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R7_PacketManager.kt
deleted file mode 100644
index 59ae9ce..0000000
--- a/nms/v1_21R7/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R7_PacketManager.kt
+++ /dev/null
@@ -1,33 +0,0 @@
-package xyz.alexcrea.cuanvil.dependency.packet.versions
-
-import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket
-import net.minecraft.world.entity.player.Abilities
-import org.bukkit.craftbukkit.entity.CraftPlayer
-import org.bukkit.entity.Player
-import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
-import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
-
-class V1_21R7_PacketManager : PacketManagerBase(), PacketManager {
- override val canSetInstantBuild: Boolean
- get() = true
-
- override fun setInstantBuild(player: Player, instantBuild: Boolean) {
- val nmsPlayer = (player as CraftPlayer).handle
- val playerAbilities = nmsPlayer.abilities
- val sendedAbilities: Abilities
- if (playerAbilities.instabuild == instantBuild) {
- sendedAbilities = playerAbilities
- } else {
- sendedAbilities = Abilities()
- sendedAbilities.invulnerable = playerAbilities.invulnerable
- sendedAbilities.flying = playerAbilities.flying
- sendedAbilities.mayfly = playerAbilities.mayfly
- sendedAbilities.instabuild = instantBuild
- sendedAbilities.mayBuild = playerAbilities.mayBuild
- sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed
- sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed
- }
- val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities)
- nmsPlayer.connection.send(packet)
- }
-}
\ No newline at end of file
diff --git a/settings.gradle.kts b/settings.gradle.kts
index 9de7d8c..03fe07e 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -1,22 +1,2 @@
rootProject.name = "CustomAnvil"
-// NMS subproject
-include("nms:nms-common")
-findProject(":nms:nms-common")?.name = "nms-common"
-include("nms:nms-paper")
-findProject(":nms:nms-paper")?.name = "nms-paper"
-
-
-val reobfNMS = providers.gradleProperty("subprojects.reobfnms")
- .get().split(",")
-
-for (nmsPart in reobfNMS) {
- include("nms:$nmsPart")
- findProject(":nms:$nmsPart")?.name = nmsPart
-}
-
-// compatibility subprojects
-include(":impl:LegacyEcoEnchant")
-findProject(":impl:LegacyEcoEnchant")?.name = "LegacyEcoEnchant"
-include("impl:ExcellentEnchant5_4")
-findProject(":impl:ExcellentEnchant5_4")?.name = "ExcellentEnchant5_4"
\ No newline at end of file
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/AnvilRecipeBuilder.java b/src/main/java/xyz/alexcrea/cuanvil/api/AnvilRecipeBuilder.java
index 4292fa0..74e8118 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/AnvilRecipeBuilder.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/AnvilRecipeBuilder.java
@@ -14,10 +14,7 @@ public class AnvilRecipeBuilder {
private @NotNull String name;
private boolean exactCount;
- private int levelCostPerCraft;
- private int linearXpCostPerCraft;
-
- private boolean removeExactLinearXp;
+ private int xpCostPerCraft;
private @Nullable ItemStack leftItem;
private @Nullable ItemStack rightItem;
@@ -26,7 +23,7 @@ public class AnvilRecipeBuilder {
/**
* Instantiates a new Anvil recipe builder.
* exact count default to true.
- * xp level and linear cost per craft default to 0.
+ * xp cost per craft default to 1.
*
* @param name The recipe name
*/
@@ -34,9 +31,7 @@ public class AnvilRecipeBuilder {
this.name = name;
this.exactCount = true;
- this.levelCostPerCraft = 0;
- this.linearXpCostPerCraft = 0;
- this.removeExactLinearXp = false;
+ this.xpCostPerCraft = 1;
this.leftItem = null;
this.rightItem = null;
@@ -65,7 +60,7 @@ public class AnvilRecipeBuilder {
}
/**
- * Get if the recipe is exact count. (default 0)
+ * Get if the recipe is exact count.
*
* Exact count mean the recipe can only be crafted 1 by 1.
* If set to false, then it will craft as much as possible in 1 go and will keep unused material onto the anvil inventory.
@@ -91,14 +86,12 @@ public class AnvilRecipeBuilder {
}
/**
- * Get the xp level cost per craft. (default 0)
+ * Get the xp level cost per craft.
*
* @return The xp level cost per craft
- * @deprecated use {@link #getLevelCostPerCraft() getLevelCostPerCraft} instead
*/
- @Deprecated(since = "1.13.0")
public int getXpCostPerCraft() {
- return getLevelCostPerCraft();
+ return xpCostPerCraft;
}
/**
@@ -106,78 +99,9 @@ public class AnvilRecipeBuilder {
*
* @param xpCostPerCraft The xp level cost per craft
* @return This recipe builder instance.
- * @deprecated use {@link #setLevelCostPerCraft(int) setLevelCostPerCraft} instead
*/
- @Deprecated(since = "1.13.0")
public AnvilRecipeBuilder setXpCostPerCraft(int xpCostPerCraft) {
- return setLevelCostPerCraft(xpCostPerCraft);
- }
-
- /**
- * Get the xp level cost per craft. (default 0)
- *
- * @return The xp level cost per craft
- */
- public int getLevelCostPerCraft() {
- return levelCostPerCraft;
- }
-
- /**
- * Sets the xp level cost per craft.
- *
- * @param levelCostPerCraft The xp level cost per craft
- * @return This recipe builder instance.
- */
- public AnvilRecipeBuilder setLevelCostPerCraft(int levelCostPerCraft) {
- this.levelCostPerCraft = levelCostPerCraft;
- return this;
- }
-
- /**
- * Get the linear xp cost (not xp level cost) per craft.
- *
- * @return The xp level cost per craft
- */
- public int getLinearXpCostPerCraft() {
- return linearXpCostPerCraft;
- }
-
- /**
- * Sets the linear xp cost (not xp level cost) per craft.
- *
- * @param linearXpCostPerCraft The linear xp cost per craft
- * @return This recipe builder instance.
- */
- public AnvilRecipeBuilder setLinearXpCostPerCraft(int linearXpCostPerCraft) {
- this.linearXpCostPerCraft = linearXpCostPerCraft;
- return this;
- }
-
- /**
- * Get if the linear xp should get removed by an exact amount.
- *
- * If false (default) level cost will be the level that would be reached by a player with this amount of xp.
- * If true will require the level that has at least the specified level of xp then on click remove only the necessary xp
- *
- * linear xp cost are applied after level cost
- * @return if we should remove the exact amount of linear xp
- */
- public boolean isRemoveExactLinearXp() {
- return removeExactLinearXp;
- }
-
- /**
- * Set if the linear xp should get removed by an exact amount.
- *
- * If false (default) level cost will be the level that would be reached by a player with this amount of xp.
- * If true will require the level that has at least the specified level of xp then on click remove only the necessary xp
- *
- * linear xp cost are applied after level cost
- * @param removeExactLinearXp if we should remove the exact amount of linear xp
- * @return This recipe builder instance.
- */
- public AnvilRecipeBuilder setRemoveExactLinearXp(boolean removeExactLinearXp) {
- this.removeExactLinearXp = removeExactLinearXp;
+ this.xpCostPerCraft = xpCostPerCraft;
return this;
}
@@ -258,14 +182,12 @@ public class AnvilRecipeBuilder {
*/
@Nullable // null if missing argument
public AnvilCustomRecipe build() {
- if (leftItem == null || resultItem == null) return null;
+ if(leftItem == null || rightItem == null) return null;
return new AnvilCustomRecipe(
this.name,
this.exactCount,
- this.levelCostPerCraft,
- this.linearXpCostPerCraft,
- this.removeExactLinearXp,
+ this.xpCostPerCraft,
this.leftItem, this.rightItem, this.resultItem
);
}
@@ -276,7 +198,7 @@ public class AnvilRecipeBuilder {
*
* @return True if successful.
*/
- public boolean registerIfAbsent() {
+ public boolean registerIfAbsent(){
return CustomAnvilRecipeApi.addRecipe(this);
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/ConflictAPI.java b/src/main/java/xyz/alexcrea/cuanvil/api/ConflictAPI.java
index fe2715e..db577a1 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/ConflictAPI.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/ConflictAPI.java
@@ -1,11 +1,11 @@
package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil;
+import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.dependency.DependencyManager;
import xyz.alexcrea.cuanvil.group.EnchantConflictGroup;
import xyz.alexcrea.cuanvil.gui.config.global.EnchantConflictGui;
@@ -19,41 +19,39 @@ import java.util.List;
@SuppressWarnings("unused")
public class ConflictAPI {
- private ConflictAPI() {
- }
+ private ConflictAPI() {}
- private static Object saveChangeTask = null;
- private static Object reloadChangeTask = null;
+ private static int saveChangeTask = -1;
+ private static int reloadChangeTask = -1;
/**
* Write and add a conflict.
* Will not write the conflict if it already exists.
- * Will not be successful if the conflict is empty.
*
* @param builder The conflict builder to be based on
* @return True if successful.
*/
- public static boolean addConflict(@NotNull ConflictBuilder builder) {
+ public static boolean addConflict(@NotNull ConflictBuilder builder){
return addConflict(builder, false);
}
/**
* Write and add a conflict.
* Will not write the conflict if it already exists.
- * Will not be successful if the conflict is empty.
*
- * @param builder The conflict builder to be based on
+ * @param builder The conflict builder to be based on
* @param overrideDeleted If we should write even if the conflict was previously deleted.
* @return True if successful.
*/
- public static boolean addConflict(@NotNull ConflictBuilder builder, boolean overrideDeleted) {
+ public static boolean addConflict(@NotNull ConflictBuilder builder, boolean overrideDeleted){
FileConfiguration config = ConfigHolder.CONFLICT_HOLDER.getConfig();
// Test if conflict can be added
- if (!overrideDeleted && ConfigHolder.CONFLICT_HOLDER.isDeleted(builder.getName())) return false;
- if (config.contains(builder.getName())) return false;
+ if(!overrideDeleted && ConfigHolder.CONFLICT_HOLDER.isDeleted(builder.getName())) return false;
+ if(config.contains(builder.getName())) return false;
+
+ if(!writeConflict(builder, false)) return false;
- if (!writeConflict(builder, false)) return false;
EnchantConflictGroup conflict = builder.build();
// Register conflict
@@ -61,7 +59,7 @@ public class ConflictAPI {
// Add conflict to gui
EnchantConflictGui conflictGui = EnchantConflictGui.getCurrentInstance();
- if (conflictGui != null) conflictGui.updateValueForGeneric(conflict, true);
+ if(conflictGui != null) conflictGui.updateValueForGeneric(conflict, true);
return true;
}
@@ -71,10 +69,10 @@ public class ConflictAPI {
*
* You may want to use {@link #addConflict(ConflictBuilder)} instead as it is more performance in most case as this function will reload every conflict.
*
- * @param builder the builder
- * @return true if was written successfully.
+ * @param builder The builder
+ * @return True if successful.
*/
- public static boolean writeConflict(@NotNull ConflictBuilder builder) {
+ public static boolean writeConflict(@NotNull ConflictBuilder builder){
return writeConflict(builder, true);
}
@@ -85,14 +83,14 @@ public class ConflictAPI {
*
* @param builder The builder
* @param updatePlanned If we should plan a global update for conflicts
- * @return true if was written successfully.
+ * @return True if successful.
*/
- public static boolean writeConflict(@NotNull ConflictBuilder builder, boolean updatePlanned) {
+ public static boolean writeConflict(@NotNull ConflictBuilder builder, boolean updatePlanned){
FileConfiguration config = ConfigHolder.CONFLICT_HOLDER.getConfig();
String name = builder.getName();
- if (name.contains(".")) {
- CustomAnvil.instance.getLogger().warning("Conflict " + name + " contain \".\" in its name but should not. this conflict is ignored.");
+ if(name.contains(".")) {
+ CustomAnvil.instance.getLogger().warning("Conflict " + name +" contain \".\" in its name but should not. this conflict is ignored.");
logConflictOrigin(builder);
return false;
}
@@ -101,30 +99,27 @@ public class ConflictAPI {
List enchantments = extractEnchantments(builder);
List excludedGroups = new ArrayList<>(builder.getExcludedGroupNames());
- if (!enchantments.isEmpty()) config.set(basePath + "enchantments", enchantments);
- if (!excludedGroups.isEmpty()) config.set(basePath + "notAffectedGroups", excludedGroups);
- if (builder.getMaxBeforeConflict() > 0)
- config.set(basePath + "maxEnchantmentBeforeConflict", builder.getMaxBeforeConflict());
+ if(!enchantments.isEmpty()) config.set(basePath + "enchantments", enchantments);
+ if(!excludedGroups.isEmpty()) config.set(basePath + "notAffectedGroups", excludedGroups);
+ if(builder.getMaxBeforeConflict() > 0) config.set(basePath + "maxEnchantmentBeforeConflict", builder.getMaxBeforeConflict());
- if (!config.isConfigurationSection(name)) return false;
prepareSaveTask();
- if (updatePlanned) prepareUpdateTask();
+ if(updatePlanned) prepareUpdateTask();
return true;
}
/**
* Extract every enchantment names from a builder.
- *
* @param builder The builder storing the enchantments
* @return Builder's stored enchantment.
*/
@NotNull
- private static List extractEnchantments(@NotNull ConflictBuilder builder) {
+ private static List extractEnchantments(@NotNull ConflictBuilder builder){
List result = new ArrayList<>(builder.getEnchantmentNames());
for (NamespacedKey enchantmentKey : builder.getEnchantmentKeys()) {
- result.add(enchantmentKey.toString());
+ result.add(enchantmentKey.getKey());
}
return result;
@@ -136,7 +131,7 @@ public class ConflictAPI {
* @param conflict The conflict to remove
* @return True if successful.
*/
- public static boolean removeConflict(@NotNull EnchantConflictGroup conflict) {
+ public static boolean removeConflict(@NotNull EnchantConflictGroup conflict){
// Remove from registry
ConfigHolder.CONFLICT_HOLDER.getConflictManager().removeConflict(conflict);
@@ -146,7 +141,8 @@ public class ConflictAPI {
// Remove from gui
EnchantConflictGui conflictGui = EnchantConflictGui.getCurrentInstance();
- if (conflictGui != null) conflictGui.removeGeneric(conflict);
+ if(conflictGui != null) conflictGui.removeGeneric(conflict);
+
return true;
}
@@ -155,40 +151,40 @@ public class ConflictAPI {
* Prepare a task to save conflict configuration.
*/
private static void prepareSaveTask() {
- if (saveChangeTask != null) return;
+ if(saveChangeTask != -1) return;
- saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> {
+ saveChangeTask = Bukkit.getScheduler().scheduleSyncDelayedTask(CustomAnvil.instance, ()->{
ConfigHolder.CONFLICT_HOLDER.saveToDisk(true);
- saveChangeTask = null;
- });
+ saveChangeTask = -1;
+ }, 0L);
}
/**
* Prepare a task to reload every conflict.
*/
private static void prepareUpdateTask() {
- if (reloadChangeTask != null) return;
+ if(reloadChangeTask != -1) return;
- reloadChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> {
+ reloadChangeTask = Bukkit.getScheduler().scheduleSyncDelayedTask(CustomAnvil.instance, ()->{
ConfigHolder.CONFLICT_HOLDER.reload();
EnchantConflictGui conflictGui = EnchantConflictGui.getCurrentInstance();
- if (conflictGui != null) conflictGui.reloadValues();
+ if(conflictGui != null) conflictGui.reloadValues();
+
+ reloadChangeTask = -1;
+ }, 0L);
- reloadChangeTask = null;
- });
}
- static void logConflictOrigin(@NotNull ConflictBuilder builder) {
+ static void logConflictOrigin(@NotNull ConflictBuilder builder){
CustomAnvil.instance.getLogger().warning("Conflict " + builder.getName() + " came from " + builder.getSourceName() + ".");
}
/**
* Get every registered conflict.
- *
* @return An immutable collection of conflict.
*/
@NotNull
- public static List getRegisteredConflict() {
+ public static List getRegisteredConflict(){
List mutableList = ConfigHolder.CONFLICT_HOLDER.getConflictManager().getConflictList();
return Collections.unmodifiableList(mutableList);
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/ConflictBuilder.java b/src/main/java/xyz/alexcrea/cuanvil/api/ConflictBuilder.java
index 1460766..3e63b36 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/ConflictBuilder.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/ConflictBuilder.java
@@ -10,10 +10,8 @@ import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.group.*;
import java.util.HashSet;
-import java.util.List;
import java.util.Set;
-//TODO add conflict after level
/**
* A Builder for material conflict.
*/
@@ -37,7 +35,7 @@ public class ConflictBuilder {
* @param maxBeforeConflict Maximum number of conflicting enchantment before conflict is active
* @param source The conflict source
*/
- public ConflictBuilder(@NotNull String name, int maxBeforeConflict, @Nullable Plugin source) {
+ public ConflictBuilder(@NotNull String name, int maxBeforeConflict, @Nullable Plugin source){
this.source = source;
this.name = name;
@@ -55,7 +53,7 @@ public class ConflictBuilder {
* @param name The conflict name
* @param source The conflict source
*/
- public ConflictBuilder(@NotNull String name, @Nullable Plugin source) {
+ public ConflictBuilder(@NotNull String name, @Nullable Plugin source){
this(name, 0, source);
}
@@ -64,7 +62,7 @@ public class ConflictBuilder {
*
* @param name The conflict name
*/
- public ConflictBuilder(@NotNull String name) {
+ public ConflictBuilder(@NotNull String name){
this(name, null);
}
@@ -85,7 +83,7 @@ public class ConflictBuilder {
*/
@NotNull
public String getSourceName() {
- if (source == null) return "an unknown source";
+ if(source == null) return "an unknown source";
return source.getName();
}
@@ -178,7 +176,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder addEnchantment(@NotNull String enchantmentName) {
+ public ConflictBuilder addEnchantment(@NotNull String enchantmentName){
enchantmentNames.add(enchantmentName);
return this;
}
@@ -190,7 +188,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder addEnchantment(@NotNull NamespacedKey enchantmentKey) {
+ public ConflictBuilder addEnchantment(@NotNull NamespacedKey enchantmentKey){
enchantmentKeys.add(enchantmentKey);
return this;
}
@@ -202,7 +200,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder addEnchantment(@NotNull CAEnchantment enchantment) {
+ public ConflictBuilder addEnchantment(@NotNull CAEnchantment enchantment){
addEnchantment(enchantment.getKey());
return this;
}
@@ -214,7 +212,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder removeEnchantment(@NotNull String enchantmentName) {
+ public ConflictBuilder removeEnchantment(@NotNull String enchantmentName){
enchantmentNames.remove(enchantmentName);
return this;
}
@@ -226,7 +224,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder removeEnchantment(@NotNull NamespacedKey enchantmentKey) {
+ public ConflictBuilder removeEnchantment(@NotNull NamespacedKey enchantmentKey){
enchantmentKeys.remove(enchantmentKey);
return removeEnchantment(enchantmentKey.getKey());
}
@@ -238,7 +236,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder removeEnchantment(@NotNull CAEnchantment enchantment) {
+ public ConflictBuilder removeEnchantment(@NotNull CAEnchantment enchantment){
return removeEnchantment(enchantment.getKey());
}
@@ -257,7 +255,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder addExcludedGroup(@NotNull String groupName) {
+ public ConflictBuilder addExcludedGroup(@NotNull String groupName){
excludedGroupNames.add(groupName);
return this;
}
@@ -277,7 +275,7 @@ public class ConflictBuilder {
* @return this conflict builder instance.
*/
@NotNull
- public ConflictBuilder addExcludedGroup(@NotNull AbstractMaterialGroup group) {
+ public ConflictBuilder addExcludedGroup(@NotNull AbstractMaterialGroup group){
return addExcludedGroup(group.getName());
}
@@ -296,7 +294,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder removeExcludedGroup(@NotNull String groupName) {
+ public ConflictBuilder removeExcludedGroup(@NotNull String groupName){
excludedGroupNames.remove(groupName);
return this;
}
@@ -316,7 +314,7 @@ public class ConflictBuilder {
* @return This conflict builder instance.
*/
@NotNull
- public ConflictBuilder removeExcludedGroup(@NotNull AbstractMaterialGroup group) {
+ public ConflictBuilder removeExcludedGroup(@NotNull AbstractMaterialGroup group){
return removeExcludedGroup(group.getName());
}
@@ -329,7 +327,7 @@ public class ConflictBuilder {
public ConflictBuilder copy() {
ConflictBuilder copy = new ConflictBuilder(this.name, this.source);
- copy.setMaxBeforeConflict(this.maxBeforeConflict);
+ setMaxBeforeConflict(this.maxBeforeConflict);
// Set Enchantments
for (NamespacedKey key : this.enchantmentKeys) {
@@ -346,13 +344,11 @@ public class ConflictBuilder {
return copy;
}
-
/**
* Build a new Enchant conflict group by this builder.
- *
* @return An Enchant conflict group with this builder parameters.
*/
- public EnchantConflictGroup build() {
+ public EnchantConflictGroup build(){
AbstractMaterialGroup materials = extractGroups();
EnchantConflictGroup conflict = new EnchantConflictGroup(getName(), materials, getMaxBeforeConflict());
appendEnchantments(conflict);
@@ -362,21 +358,10 @@ public class ConflictBuilder {
/**
* Register this conflict if not yet registered.
- * Equivalent to {@link ConflictAPI#addConflict(ConflictBuilder, boolean) ConflictAPI.addConflict(this, true)}}
- *
+ * Equivalent to {@link ConflictAPI#addConflict(ConflictBuilder)}
* @return True if successful.
*/
- public boolean registerIfAbsent() {
- return ConflictAPI.addConflict(this, true);
- }
-
- /**
- * Register this conflict if not yet registered or deleted.
- * Equivalent to {@link ConflictAPI#addConflict(ConflictBuilder) ConflictAPI.addConflict(this)}
- *
- * @return True if successful.
- */
- public boolean registerIfNew() {
+ public boolean registerIfAbsent(){
return ConflictAPI.addConflict(this);
}
@@ -385,15 +370,15 @@ public class ConflictBuilder {
*
* @param conflict The conflict target
*/
- protected void appendEnchantments(@NotNull EnchantConflictGroup conflict) {
- for (String enchantmentName : getEnchantmentNames()) {
- if (appendEnchantments(conflict, EnchantmentApi.getListByName(enchantmentName)) == 0) {
+ protected void appendEnchantments(@NotNull EnchantConflictGroup conflict){
+ for (String enchantmentName : getEnchantmentNames()){
+ if(appendEnchantment(conflict, EnchantmentApi.getByName(enchantmentName))){
CustomAnvil.instance.getLogger().warning("Could not find enchantment " + enchantmentName + " for conflict " + getName());
ConflictAPI.logConflictOrigin(this);
}
}
- for (NamespacedKey enchantmentKey : getEnchantmentKeys()) {
- if (!appendEnchantment(conflict, EnchantmentApi.getByKey(enchantmentKey))) {
+ for (NamespacedKey enchantmentKey : getEnchantmentKeys()){
+ if(!appendEnchantment(conflict, EnchantmentApi.getByKey(enchantmentKey))){
CustomAnvil.instance.getLogger().warning("Could not find enchantment " + enchantmentKey + " for conflict " + getName());
ConflictAPI.logConflictOrigin(this);
}
@@ -407,44 +392,26 @@ public class ConflictBuilder {
* @param enchantment The enchantment
* @return True if successful.
*/
- protected static boolean appendEnchantment(@NotNull EnchantConflictGroup conflict, @Nullable CAEnchantment enchantment) {
- if (enchantment == null)
+ protected static boolean appendEnchantment(@NotNull EnchantConflictGroup conflict, @Nullable CAEnchantment enchantment){
+ if(enchantment == null)
return false;
conflict.addEnchantment(enchantment);
return true;
}
- /**
- * Append a list of enchantments.
- *
- * @param conflict The conflict target
- * @param enchantments List of enchantment to add
- * @return Number of enchantment added
- */
- protected static int appendEnchantments(@NotNull EnchantConflictGroup conflict, @NotNull List enchantments) {
- int numberValid = 0;
- for (CAEnchantment enchantment : enchantments) {
- if (appendEnchantment(conflict, enchantment)) {
- numberValid++;
- }
- }
-
- return numberValid;
- }
-
/**
* Extract group abstract material group.
*
* @return The abstract material group from the builder.
*/
- protected AbstractMaterialGroup extractGroups() {
+ protected AbstractMaterialGroup extractGroups(){
ItemGroupManager itemGroupManager = ConfigHolder.ITEM_GROUP_HOLDER.getItemGroupsManager();
IncludeGroup group = new IncludeGroup(EnchantConflictManager.DEFAULT_GROUP_NAME);
for (String groupName : getExcludedGroupNames()) {
AbstractMaterialGroup materialGroup = itemGroupManager.get(groupName);
- if (materialGroup == null) {
+ if(materialGroup == null){
CustomAnvil.instance.getLogger().warning("Material group " + groupName + " do not exist but is ask by conflict " + getName());
ConflictAPI.logConflictOrigin(this);
continue;
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/CustomAnvilRecipeApi.java b/src/main/java/xyz/alexcrea/cuanvil/api/CustomAnvilRecipeApi.java
index 8f80aa3..250e854 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/CustomAnvilRecipeApi.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/CustomAnvilRecipeApi.java
@@ -1,10 +1,10 @@
package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil;
+import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.dependency.DependencyManager;
import xyz.alexcrea.cuanvil.gui.config.global.CustomRecipeConfigGui;
import xyz.alexcrea.cuanvil.recipe.AnvilCustomRecipe;
@@ -19,7 +19,7 @@ public class CustomAnvilRecipeApi {
private CustomAnvilRecipeApi(){}
- private static Object saveChangeTask = null;
+ private static int saveChangeTask = -1;
/**
* Write and add a custom anvil recipe.
@@ -78,7 +78,6 @@ public class CustomAnvilRecipeApi {
return true;
}
- // TODO remove by name and/or by builder (as name is keept) (and maybe create a get by name)
/**
* Remove a custom anvil recipe.
*
@@ -87,8 +86,7 @@ public class CustomAnvilRecipeApi {
*/
public static boolean removeRecipe(@NotNull AnvilCustomRecipe recipe){
// Remove from registry
- boolean result = ConfigHolder.CUSTOM_RECIPE_HOLDER.getRecipeManager().cleanRemove(recipe);
- if(!result) return false;
+ ConfigHolder.CUSTOM_RECIPE_HOLDER.getRecipeManager().cleanRemove(recipe);
// Delete and save to file
ConfigHolder.CUSTOM_RECIPE_HOLDER.delete(recipe.getName());
@@ -105,12 +103,12 @@ public class CustomAnvilRecipeApi {
* Prepare a task to save custom recipe configuration.
*/
private static void prepareSaveTask() {
- if(saveChangeTask != null) return;
+ if(saveChangeTask != -1) return;
- saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, ()->{
+ saveChangeTask = Bukkit.getScheduler().scheduleSyncDelayedTask(CustomAnvil.instance, ()->{
ConfigHolder.CONFLICT_HOLDER.saveToDisk(true);
- saveChangeTask = null;
- });
+ saveChangeTask = -1;
+ }, 0L);
}
/**
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java b/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java
index ac98225..d2244ad 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java
@@ -1,14 +1,13 @@
package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil;
-import io.delilaheve.util.ConfigOptions;
+import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.dependency.DependencyManager;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry;
import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
@@ -19,7 +18,6 @@ import xyz.alexcrea.cuanvil.gui.config.global.EnchantCostConfigGui;
import xyz.alexcrea.cuanvil.gui.config.global.EnchantLimitConfigGui;
import java.util.Collections;
-import java.util.List;
import java.util.Map;
/**
@@ -28,7 +26,7 @@ import java.util.Map;
@SuppressWarnings("unused")
public class EnchantmentApi {
- private static Object saveChangeTask = null;
+ private static int saveChangeTask = -1;
private EnchantmentApi() {}
@@ -106,7 +104,7 @@ public class EnchantmentApi {
* @return True if successful.
*/
public static boolean unregisterEnchantment(@NotNull NamespacedKey key){
- CAEnchantment enchantment = CAEnchantment.getByKey(key);
+ CAEnchantment enchantment = CAEnchantmentRegistry.getInstance().getByKey(key);
return unregisterEnchantment(enchantment);
}
@@ -128,7 +126,7 @@ public class EnchantmentApi {
*/
@Nullable
public static CAEnchantment getByKey(@NotNull NamespacedKey key){
- return CAEnchantment.getByKey(key);
+ return CAEnchantmentRegistry.getInstance().getByKey(key);
}
/**
@@ -136,22 +134,10 @@ public class EnchantmentApi {
*
* @param name The name used to fetch
* @return The custom anvil enchantment of this name. null if not found.
- * @deprecated use {@link #getListByName(String)}
*/
- @Deprecated(since = "1.6.3")
@Nullable
public static CAEnchantment getByName(@NotNull String name){
- return CAEnchantment.getByName(name);
- }
-
- /**
- * Get list of enchantment using the provided name.
- *
- * @param name The name used to fetch
- * @return List of custom anvil enchantments of this name. May be empty if not found.
- */
- public static List getListByName(@NotNull String name){
- return CAEnchantment.getListByName(name);
+ return CAEnchantmentRegistry.getInstance().getByName(name);
}
/**
@@ -171,49 +157,35 @@ public class EnchantmentApi {
*/
public static boolean writeDefaultConfig(CAEnchantment enchantment, boolean override){
FileConfiguration config = ConfigHolder.DEFAULT_CONFIG.getConfig();
+ if(!override && config.contains(enchantment.getName())) return false;
- if(tryWriteDefaultConfig(config, enchantment, override)){
- prepareSaveTask();
- }
+ writeDefaultConfig(config, enchantment);
+
+ prepareSaveTask();
return true;
}
- private static boolean tryWriteDefaultConfig(FileConfiguration defaultConfig, CAEnchantment enchantment, boolean override) {
- boolean hasChange = false;
- String levelPath = ConfigOptions.ENCHANT_LIMIT_ROOT + "." + enchantment.getKey();
- if(override || !defaultConfig.isSet(levelPath)){
- defaultConfig.set(levelPath, enchantment.defaultMaxLevel());
- hasChange = true;
- }
+ private static void writeDefaultConfig(FileConfiguration defaultConfig, CAEnchantment enchantment) {
+ defaultConfig.set("enchant_limits." + enchantment.getKey().getKey(), enchantment.defaultMaxLevel());
- String basePath = ConfigOptions.ENCHANT_VALUES_ROOT + "." + enchantment.getKey();
+ String basePath = "enchant_values." + enchantment.getKey().getKey();
EnchantmentRarity rarity = enchantment.defaultRarity();
- String itemPath = basePath + ".item";
- String bookPath = basePath + ".book";
- if(override || !defaultConfig.isSet(itemPath)){
- defaultConfig.set(itemPath, rarity.getItemValue());
- hasChange = true;
- }
- if(override || !defaultConfig.isSet(bookPath)){
- defaultConfig.set(bookPath, rarity.getBookValue());
- hasChange = true;
- }
-
- return hasChange;
+ defaultConfig.set(basePath + ".item", rarity.getItemValue());
+ defaultConfig.set(basePath + ".book", rarity.getBookValue());
}
/**
* Prepare a task to save custom recipe configuration.
*/
private static void prepareSaveTask() {
- if(saveChangeTask != null) return;
+ if(saveChangeTask != -1) return;
- saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, ()->{
+ saveChangeTask = Bukkit.getScheduler().scheduleSyncDelayedTask(CustomAnvil.instance, ()->{
ConfigHolder.DEFAULT_CONFIG.saveToDisk(true);
- saveChangeTask = null;
- });
+ saveChangeTask = -1;
+ }, 0L);
}
/**
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/MaterialGroupApi.java b/src/main/java/xyz/alexcrea/cuanvil/api/MaterialGroupApi.java
index cd71c7a..6e50ff9 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/MaterialGroupApi.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/MaterialGroupApi.java
@@ -2,13 +2,12 @@ package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil;
import io.delilaheve.util.ConfigOptions;
+import org.bukkit.Bukkit;
import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.dependency.DependencyManager;
import xyz.alexcrea.cuanvil.group.AbstractMaterialGroup;
import xyz.alexcrea.cuanvil.group.ExcludeGroup;
import xyz.alexcrea.cuanvil.group.IncludeGroup;
@@ -23,51 +22,49 @@ import java.util.*;
@SuppressWarnings("unused")
public class MaterialGroupApi {
- private MaterialGroupApi() {
- }
+ private MaterialGroupApi(){}
+
+ private static int saveChangeTask = -1;
+ private static int reloadChangeTask = -1;
- private static Object saveChangeTask = null;
- private static Object reloadChangeTask = null;
/**
* Write and add a group.
* Will not write the group if it already exists.
- * Will not be successful if the group is empty.
*
* @param group The group to add
* @return true if successful.
*/
- public static boolean addMaterialGroup(@NotNull AbstractMaterialGroup group) {
+ public static boolean addMaterialGroup(@NotNull AbstractMaterialGroup group){
return addMaterialGroup(group, false);
}
/**
* Write and add a group.
* Will not write the group if it already exists.
- * Will not be successful if the group is empty.
*
- * @param group The group to add
+ * @param group The group to add
* @param overrideDeleted If we should write even if the group was previously deleted.
* @return true if successful.
*/
- public static boolean addMaterialGroup(@NotNull AbstractMaterialGroup group, boolean overrideDeleted) {
+ public static boolean addMaterialGroup(@NotNull AbstractMaterialGroup group, boolean overrideDeleted){
ItemGroupManager itemGroupManager = ConfigHolder.ITEM_GROUP_HOLDER.getItemGroupsManager();
// Test if it exists/existed
- if (!overrideDeleted && ConfigHolder.ITEM_GROUP_HOLDER.isDeleted(group.getName())) return false;
- if (itemGroupManager.get(group.getName()) != null) return false;
+ if(!overrideDeleted && ConfigHolder.ITEM_GROUP_HOLDER.isDeleted(group.getName())) return false;
+ if(itemGroupManager.get(group.getName()) != null) return false;
// Add group
itemGroupManager.getGroupMap().put(group.getName(), group);
- if (!writeMaterialGroup(group, false)) return false;
+ if(!writeMaterialGroup(group, false)) return false;
- if (group instanceof IncludeGroup includeGroup) {
+ if(group instanceof IncludeGroup includeGroup){
GroupConfigGui configGui = GroupConfigGui.getCurrentInstance();
- if (configGui != null) configGui.updateValueForGeneric(includeGroup, true);
+ if(configGui != null) configGui.updateValueForGeneric(includeGroup, true);
}
- if (ConfigOptions.INSTANCE.getVerboseDebugLog()) {
+ if(ConfigOptions.INSTANCE.getVerboseDebugLog()){
CustomAnvil.instance.getLogger().info("Registered group " + group.getName());
}
@@ -80,9 +77,9 @@ public class MaterialGroupApi {
* You may want to use {@link #addMaterialGroup(AbstractMaterialGroup)} instead as it is more performance in most case as this function will reload every conflict.
*
* @param group the group to write
- * @return true if was written successfully.
+ * @return true if successful.
*/
- public static boolean writeMaterialGroup(@NotNull AbstractMaterialGroup group) {
+ public static boolean writeMaterialGroup(@NotNull AbstractMaterialGroup group){
return writeMaterialGroup(group, true);
}
@@ -93,82 +90,64 @@ public class MaterialGroupApi {
*
* @param group the group to write
* @param updatePlanned if we should plan a global update for material groups
- * @return true if was written successfully.
+ * @return true if successful.
*/
- public static boolean writeMaterialGroup(@NotNull AbstractMaterialGroup group, boolean updatePlanned) {
+ public static boolean writeMaterialGroup(@NotNull AbstractMaterialGroup group, boolean updatePlanned){
String name = group.getName();
- if (name.contains(".")) {
- CustomAnvil.instance.getLogger().warning("Group " + name + " contain . in its name but should not. this material group is ignored.");
+ if(name.contains(".")) {
+ CustomAnvil.instance.getLogger().warning("Group " + name +" contain . in its name but should not. this material group is ignored.");
return false;
}
- boolean changed;
- if (group instanceof IncludeGroup includeGroup) {
- changed = writeKnownGroup("include", includeGroup);
- } else if (group instanceof ExcludeGroup excludeGroup) {
- throw new UnsupportedOperationException("exclude group is temporarily disable for the time being. sorry");
- // This code do not do what is intended ? idk why do it exist
- //changed = writeKnownGroup("exclude", excludeGroup);
- } else {
- changed = writeUnknownGroup(group);
+ if(group instanceof IncludeGroup includeGroup){
+ writeKnownGroup("include", includeGroup);
+ }else if(group instanceof ExcludeGroup excludeGroup){
+ writeKnownGroup("exclude", excludeGroup);
+ }else{
+ writeUnknownGroup(group);
}
- if (!changed) return false;
prepareSaveTask();
- if (updatePlanned) prepareUpdateTask();
+ if(updatePlanned) prepareUpdateTask();
return true;
}
- private static boolean writeKnownGroup(@NotNull String groupType, @NotNull AbstractMaterialGroup group) {
+ private static void writeKnownGroup(@NotNull String groupType, @NotNull AbstractMaterialGroup group){
FileConfiguration config = ConfigHolder.ITEM_GROUP_HOLDER.getConfig();
String basePath = group.getName() + ".";
- Set materialSet = group.getNonGroupInheritedMaterials();
+ Set materialSet = group.getNonGroupInheritedMaterials();
Set groupSet = group.getGroups();
- boolean empty = true;
- if (!materialSet.isEmpty()) {
- config.set(basePath + ItemGroupManager.MATERIAL_LIST_PATH, materialSetToStringList(materialSet));
- empty = false;
- } else {
- config.set(basePath + ItemGroupManager.MATERIAL_LIST_PATH, null);
- }
- if (!groupSet.isEmpty()) {
- config.set(basePath + ItemGroupManager.GROUP_LIST_PATH, materialGroupSetToStringList(groupSet));
- empty = false;
- } else {
- config.set(basePath + ItemGroupManager.GROUP_LIST_PATH, null);
- }
-
- if (empty) {
- config.set(basePath + ItemGroupManager.GROUP_TYPE_PATH, null);
- return false;
- }
-
config.set(basePath + ItemGroupManager.GROUP_TYPE_PATH, groupType);
- return true;
+ if(!materialSet.isEmpty()){
+ config.set(basePath + ItemGroupManager.MATERIAL_LIST_PATH, materialSetToStringList(materialSet));
+ }
+ if(!groupSet.isEmpty()){
+ config.set(basePath + ItemGroupManager.GROUP_LIST_PATH, materialGroupSEtToStringList(groupSet));
+ }
+
}
- private static boolean writeUnknownGroup(@NotNull AbstractMaterialGroup group) {
+ private static void writeUnknownGroup(@NotNull AbstractMaterialGroup group) {
FileConfiguration config = ConfigHolder.ITEM_GROUP_HOLDER.getConfig();
String basePath = group.getName() + ".";
- Set materials = group.getMaterials();
-
- if (materials.isEmpty()) return false;
+ EnumSet materials = group.getMaterials();
config.set(basePath + ItemGroupManager.GROUP_TYPE_PATH, "include");
- config.set(basePath + ItemGroupManager.MATERIAL_LIST_PATH, materialSetToStringList(materials));
+ if(!materials.isEmpty()){
+ config.set(basePath + ItemGroupManager.MATERIAL_LIST_PATH, materialSetToStringList(materials));
+ }
- return true;
}
- public static List materialSetToStringList(@NotNull Set materials) {
- return materials.stream().map(NamespacedKey::toString).toList();
+ public static List materialSetToStringList(@NotNull Set materials){
+ return materials.stream().map(material -> material.getKey().getKey().toLowerCase()).toList();
}
- public static List materialGroupSetToStringList(@NotNull Set groups) {
+ public static List materialGroupSEtToStringList(@NotNull Set groups){
return groups.stream().map(AbstractMaterialGroup::getName).toList();
}
@@ -178,21 +157,20 @@ public class MaterialGroupApi {
* For that reason, it is not recommended to use this function.
*
* @param group The recipe to remove
- * @return True if the group was present.
+ * @return True if successful.
*/
- public static boolean removeGroup(@NotNull AbstractMaterialGroup group) {
+ public static boolean removeGroup(@NotNull AbstractMaterialGroup group){
// Remove from registry
- AbstractMaterialGroup removed = ConfigHolder.ITEM_GROUP_HOLDER.getItemGroupsManager().groupMap.remove(group.getName());
- if (removed == null) return false;
+ ConfigHolder.ITEM_GROUP_HOLDER.getItemGroupsManager().groupMap.remove(group.getName());
// Delete and save to file
ConfigHolder.ITEM_GROUP_HOLDER.delete(group.getName());
prepareSaveTask();
// Remove from gui
- if (group instanceof IncludeGroup includeGroup) {
+ if(group instanceof IncludeGroup includeGroup){
GroupConfigGui configGui = GroupConfigGui.getCurrentInstance();
- if (configGui != null) configGui.removeGeneric(includeGroup);
+ if(configGui != null) configGui.removeGeneric(includeGroup);
}
return true;
@@ -202,28 +180,28 @@ public class MaterialGroupApi {
* Prepare a task to reload every conflict.
*/
private static void prepareSaveTask() {
- if (saveChangeTask != null) return;
+ if(saveChangeTask != -1) return;
- saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> {
+ saveChangeTask = Bukkit.getScheduler().scheduleSyncDelayedTask(CustomAnvil.instance, ()->{
ConfigHolder.ITEM_GROUP_HOLDER.saveToDisk(true);
- saveChangeTask = null;
- });
+ saveChangeTask = -1;
+ }, 0L);
}
/**
* Prepare a task to save configuration.
*/
private static void prepareUpdateTask() {
- if (reloadChangeTask != null) return;
+ if(reloadChangeTask != -1) return;
- reloadChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> {
+ reloadChangeTask = Bukkit.getScheduler().scheduleSyncDelayedTask(CustomAnvil.instance, ()->{
ConfigHolder.ITEM_GROUP_HOLDER.reload();
GroupConfigGui configGui = GroupConfigGui.getCurrentInstance();
- if (configGui != null) configGui.reloadValues();
+ if(configGui != null) configGui.reloadValues();
- reloadChangeTask = null;
- });
+ reloadChangeTask = -1;
+ }, 0L);
}
@@ -234,17 +212,16 @@ public class MaterialGroupApi {
* @return the abstract group of this name. null if not found.
*/
@Nullable
- public static AbstractMaterialGroup getGroup(@NotNull String groupName) {
+ public static AbstractMaterialGroup getGroup(@NotNull String groupName){
return ConfigHolder.ITEM_GROUP_HOLDER.getItemGroupsManager().get(groupName);
}
/**
* Get every registered material groups.
- *
* @return An immutable map of group name as its key and group as mapped value.
*/
@NotNull
- public static Map getRegisteredGroups() {
+ public static Map getRegisteredGroups(){
return Collections.unmodifiableMap(ConfigHolder.ITEM_GROUP_HOLDER.getItemGroupsManager().getGroupMap());
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/UnitRepairApi.java b/src/main/java/xyz/alexcrea/cuanvil/api/UnitRepairApi.java
index bc50c16..fe3c164 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/UnitRepairApi.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/UnitRepairApi.java
@@ -2,14 +2,13 @@ package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil;
import kotlin.Triple;
+import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.dependency.DependencyManager;
import xyz.alexcrea.cuanvil.gui.config.global.UnitRepairConfigGui;
-import xyz.alexcrea.cuanvil.gui.config.list.MappedGuiListConfigGui;
import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui;
import java.util.ArrayList;
@@ -24,7 +23,7 @@ public class UnitRepairApi {
private UnitRepairApi(){}
- private static Object saveChangeTask = null;
+ private static int saveChangeTask = -1;
/**
* Write and add a custom anvil unit repair recipe.
@@ -95,9 +94,9 @@ public class UnitRepairApi {
// Add to gui
UnitRepairConfigGui repairConfigGui = UnitRepairConfigGui.getCurrentInstance();
if(repairConfigGui != null) {
- UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored();
+ UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit);
- if(elementGui != null) elementGui.updateValueForGeneric(repairableName, true);
+ elementGui.updateValueForGeneric(repairableName, true);
repairConfigGui.updateValueForGeneric(unit, true);
}
@@ -117,24 +116,22 @@ public class UnitRepairApi {
String repairableName = repairable.name();
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
- config.set(unitName.toLowerCase() + "." + repairableName.toUpperCase(), null);
- config.set(unitName.toUpperCase() + "." + repairableName.toLowerCase(), null);
- config.set(unitName.toUpperCase() + "." + repairableName.toUpperCase(), null);
- config.set(unitName.toLowerCase() + "." + repairableName.toLowerCase(), null);
+ config.set(unitName.toLowerCase() + repairableName.toUpperCase(), null);
+ config.set(unitName.toUpperCase() + repairableName.toLowerCase(), null);
+ config.set(unitName.toUpperCase() + repairableName.toUpperCase(), null);
// Test if it was the last value of this section
boolean lastValue = false;
if(config.isConfigurationSection(unitName.toLowerCase())) {
ConfigurationSection section = config.getConfigurationSection(unitName.toLowerCase());
-
- if(section != null && section.getKeys(false).isEmpty()) {
+ if(section.getKeys(false).isEmpty()) {
lastValue = true;
config.set(unitName.toLowerCase(), null);
}
} else if (config.isConfigurationSection(unitName.toUpperCase())) {
ConfigurationSection section = config.getConfigurationSection(unitName.toUpperCase());
- if(section != null && section.getKeys(false).isEmpty()) {
+ if(section.getKeys(false).isEmpty()) {
lastValue = true;
config.set(unitName.toUpperCase(), null);
}
@@ -143,15 +140,15 @@ public class UnitRepairApi {
// We only need to "delete" as the lower case to be counted as deleted
- ConfigHolder.UNIT_REPAIR_HOLDER.delete(unitName.toLowerCase() + "." + repairableName.toLowerCase());
+ ConfigHolder.UNIT_REPAIR_HOLDER.delete(unitName.toLowerCase() + repairableName.toLowerCase());
prepareSaveTask();
// Remove from gui
UnitRepairConfigGui repairConfigGui = UnitRepairConfigGui.getCurrentInstance();
if(repairConfigGui != null) {
- UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored();
+ UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit);
- if(elementGui != null) elementGui.removeGeneric(repairableName);
+ elementGui.removeGeneric(repairableName);
if(lastValue){
repairConfigGui.removeGeneric(unit);
}
@@ -164,12 +161,12 @@ public class UnitRepairApi {
* Prepare a task to save custom unit repair recipe configuration.
*/
private static void prepareSaveTask() {
- if(saveChangeTask != null) return;
+ if(saveChangeTask != -1) return;
- saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, ()->{
+ saveChangeTask = Bukkit.getScheduler().scheduleSyncDelayedTask(CustomAnvil.instance, ()->{
ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(true);
- saveChangeTask = null;
- });
+ saveChangeTask = -1;
+ }, 0L);
}
/**
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/CAConfigReadyEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/CAConfigReadyEvent.java
index 67d27a8..24691db 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/event/CAConfigReadyEvent.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/event/CAConfigReadyEvent.java
@@ -3,23 +3,6 @@ package xyz.alexcrea.cuanvil.api.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
-/**
- * Called when the configuration of CustomAnvil is ready.
- * It is called either on the plugin startup or on the plugin config reload.
- *
- * If you want to listen to the first trigger of this event (first configuration load. aka plugin load)
- * you will need to register the listener on your plugin onEnable or earlier
- *
- * This event indicate that can start to register your recipes, item groups and conflicts.
- * The vanilla and custom enchantments should already have been provided to CustomAnvil.
- * Configuration can be changed any time after this event is triggered but never before.
- *
- * use {@link xyz.alexcrea.cuanvil.api.ConflictAPI ConflictApi},
- * {@link xyz.alexcrea.cuanvil.gui.config.global.CustomRecipeConfigGui CustomRecipeConfigGui},
- * {@link xyz.alexcrea.cuanvil.api.MaterialGroupApi MaterialGroupApi}
- * and {@link xyz.alexcrea.cuanvil.api.UnitRepairApi UnitRepairApi}
- * to add/remove/edit configurations
- */
public class CAConfigReadyEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList();
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/CAEnchantRegistryReadyEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/CAEnchantRegistryReadyEvent.java
index 3ffe372..3e2fdf8 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/event/CAEnchantRegistryReadyEvent.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/event/CAEnchantRegistryReadyEvent.java
@@ -3,17 +3,6 @@ package xyz.alexcrea.cuanvil.api.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
-/**
- * Called when custom anvil is ready to accept registration on custom enchantment.
- *
- * If you want to listen this event
- * you will need to register the listener on your plugin onEnable or earlier
- *
- * Custom enchantments may be registered later but may cause issue if registered too later
- * (after configuration loading phase. see {@link CAConfigReadyEvent})
- *
- * use {@link xyz.alexcrea.cuanvil.api.EnchantmentApi EnchantmentApi} to register and unregister your custom enchantments
- */
public class CAEnchantRegistryReadyEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList();
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAClickResultBypassEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAClickResultBypassEvent.java
deleted file mode 100644
index fe5e199..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAClickResultBypassEvent.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package xyz.alexcrea.cuanvil.api.event.listener;
-
-import org.bukkit.event.Cancellable;
-import org.bukkit.event.Event;
-import org.bukkit.event.HandlerList;
-import org.bukkit.event.inventory.InventoryClickEvent;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * Called before custom anvil process the click on the result on the anvil inventory.
- *
- * This event is called after checking that the inventory is an anvil inventory and that the click is on the result slot
- * but before checking if the player has the custom anvil affected permission.
- *
- * This event being cancelled will make CustomAnvil abort the click on result process.
- *
- * Most of the time you would likely need {@link CAPreAnvilBypassEvent} or {@link CAEarlyPreAnvilBypassEvent}
- * for this event to be useful.
- *
- * There is also {@link CATreatAnvilResult2Event} that may be better for some use case.
- */
-public class CAClickResultBypassEvent extends Event implements Cancellable {
-
- private static final HandlerList HANDLERS = new HandlerList();
-
- public static HandlerList getHandlerList() {
- return HANDLERS;
- }
-
- @Override
- public @NotNull HandlerList getHandlers() {
- return HANDLERS;
- }
-
- private boolean cancelled = false;
-
- @Override
- public boolean isCancelled() {
- return cancelled;
- }
-
- @Override
- public void setCancelled(boolean cancel) {
- this.cancelled = cancel;
- }
-
- @NotNull
- private final InventoryClickEvent event;
-
- /**
- * Get the bukkit inventory click event causing to this event
- *
- * @return The click event causing to this event
- */
- @NotNull
- public InventoryClickEvent getEvent() {
- return event;
- }
-
- public CAClickResultBypassEvent(@NotNull InventoryClickEvent event) {
- this.event = event;
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAEarlyPreAnvilBypassEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAEarlyPreAnvilBypassEvent.java
deleted file mode 100644
index e92b4cd..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAEarlyPreAnvilBypassEvent.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package xyz.alexcrea.cuanvil.api.event.listener;
-
-import org.bukkit.event.Cancellable;
-import org.bukkit.event.Event;
-import org.bukkit.event.HandlerList;
-import org.bukkit.event.inventory.PrepareAnvilEvent;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * Called before custom anvil process the prepare anvil event.
- *
- * This event will always get called when CustomAnvil need to handle
- *
- * This event being cancelled will make CustomAnvil abort the anvil process.
- *
- * You should also use {@link CAClickResultBypassEvent} if you want to use this event for something useful.
- *
- * It is also recommended that you read about {@link CAPreAnvilBypassEvent} and {@link CATreatAnvilResult2Event}
- * as your use case may be more prone to use theses.
- */
-public class CAEarlyPreAnvilBypassEvent extends Event implements Cancellable {
-
- private static final HandlerList HANDLERS = new HandlerList();
-
- public static HandlerList getHandlerList() {
- return HANDLERS;
- }
-
- @Override
- public @NotNull HandlerList getHandlers() {
- return HANDLERS;
- }
-
- private boolean cancelled = false;
-
- @Override
- public boolean isCancelled() {
- return cancelled;
- }
-
- @Override
- public void setCancelled(boolean cancel) {
- this.cancelled = cancel;
- }
-
- @NotNull
- private final PrepareAnvilEvent event;
-
- /**
- * Get the bukkit pre anvil event causing this event
- *
- * @return The pre anvil event causing to this event
- */
- @NotNull
- public PrepareAnvilEvent getEvent() {
- return event;
- }
-
- public CAEarlyPreAnvilBypassEvent(@NotNull PrepareAnvilEvent event) {
- this.event = event;
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAPreAnvilBypassEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAPreAnvilBypassEvent.java
deleted file mode 100644
index 9103a4b..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAPreAnvilBypassEvent.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package xyz.alexcrea.cuanvil.api.event.listener;
-
-import org.bukkit.event.Cancellable;
-import org.bukkit.event.Event;
-import org.bukkit.event.HandlerList;
-import org.bukkit.event.inventory.PrepareAnvilEvent;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * Called before custom anvil process the prepare anvil event.
- *
- * This event is called after {@link CAEarlyPreAnvilBypassEvent},
- * after checking that there is at least an item on the left slot
- * and after checking if any of the 2 item is marked as immutable
- * but before checking if the player has the custom anvil affected permission.
- *
- * This event being cancelled will make CustomAnvil abort the anvil process.
- *
- * You should also use {@link CAClickResultBypassEvent} if you want to use this event for something useful.
- *
- * It is also recommended that you read about {@link CAEarlyPreAnvilBypassEvent} and {@link CATreatAnvilResult2Event}
- * as your use case may be more prone to use theses.
- */
-public class CAPreAnvilBypassEvent extends Event implements Cancellable {
-
- private static final HandlerList HANDLERS = new HandlerList();
-
- public static HandlerList getHandlerList() {
- return HANDLERS;
- }
-
- @Override
- public @NotNull HandlerList getHandlers() {
- return HANDLERS;
- }
-
- private boolean cancelled = false;
-
- @Override
- public boolean isCancelled() {
- return cancelled;
- }
-
- @Override
- public void setCancelled(boolean cancel) {
- this.cancelled = cancel;
- }
-
- @NotNull
- private final PrepareAnvilEvent event;
-
- /**
- * Get the bukkit pre anvil event causing this event
- *
- * @return The pre anvil event causing this event
- */
- @NotNull
- public PrepareAnvilEvent getEvent() {
- return event;
- }
-
- public CAPreAnvilBypassEvent(@NotNull PrepareAnvilEvent event) {
- this.event = event;
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResult2Event.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResult2Event.java
deleted file mode 100644
index 30c5380..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResult2Event.java
+++ /dev/null
@@ -1,196 +0,0 @@
-package xyz.alexcrea.cuanvil.api.event.listener;
-
-import org.bukkit.event.Event;
-import org.bukkit.event.HandlerList;
-import org.bukkit.inventory.Inventory;
-import org.bukkit.inventory.InventoryView;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.ApiStatus;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import xyz.alexcrea.cuanvil.anvil.AnvilCost;
-import xyz.alexcrea.cuanvil.anvil.AnvilUseType;
-
-/**
- * Called after custom anvil processed the click on the result on the anvil inventory.
- * This event should be used to modify the result of an anvil use.
- *
- * You may also want to check {@link CAClickResultBypassEvent},
- * {@link CAPreAnvilBypassEvent}
- * and {@link CAEarlyPreAnvilBypassEvent} for your use case
- *
- * A null result will cancel this event
- */
-@SuppressWarnings("unused")
-public class CATreatAnvilResult2Event extends Event {
-
- private static final HandlerList HANDLERS = new HandlerList();
-
- public static HandlerList getHandlerList() {
- return HANDLERS;
- }
-
- @Override
- public @NotNull HandlerList getHandlers() {
- return HANDLERS;
- }
-
- @NotNull
- private final InventoryView view;
-
- private final AnvilUseType useType;
-
- @Nullable
- private final ItemStack left;
- @Nullable
- private final ItemStack right;
-
- @Nullable
- private ItemStack result;
-
- private final AnvilCost cost;
-
- @ApiStatus.Internal
- public CATreatAnvilResult2Event(
- @NotNull InventoryView view,
- Inventory inv,
- AnvilUseType useType,
- @Nullable ItemStack result,
- AnvilCost cost) {
- this.view = view;
- this.useType = useType;
-
- this.left = inv.getItem(0); // TODO use view here
- this.right = inv.getItem(1);
- this.result = result;
- this.cost = cost;
- }
-
- /**
- * Get the bukkit inventory view.
- *
- * Temporarily marked as internal as it will get changed to anvil view on legacy removal
- * so signature will change
- *
- * @return The inventory view of this event.
- */
- @ApiStatus.Internal
- public @NotNull InventoryView getView() {
- return view;
- }
-
-
- /**
- * Get the type of use source of the result.
- *
- * @return The craft use type.
- */
- public AnvilUseType getUseType() {
- return useType;
- }
-
- /**
- * Get the left item of the anvil use
- *
- * @return the left item
- */
- public @Nullable ItemStack getLeftItem() {
- return left;
- }
-
- /**
- * Get the right item of the anvil use
- *
- * @return the right item
- */
- public @Nullable ItemStack getRightItem() {
- return right;
- }
-
- /**
- * Get the current result
- *
- * note that it will not be null unless another listener previously set it to null.
- *
- * @return The current result.
- */
- public @Nullable ItemStack getResult() {
- return result;
- }
-
- /**
- * Set the current result
- *
- * note that a null result will cancel this anvil use.
- *
- * @param result The new result
- */
- public void setResult(@Nullable ItemStack result) {
- this.result = result;
- }
-
- /**
- * Get the level cost displayed on the anvil.
- *
Important note:
- * the final price are re calculated on click for the following use case:
- *
- * - Custom craft
- * - Unit repair
- * - Lore edit
- *
- * This value will be used as final price for:
- * Item merge
- * Item rename
- *
- *
- * @return The current cost.
- * @deprecated use #{@link #getCost()} instead
- */
- @Deprecated(forRemoval = true, since = "1.17.0")
- public int getLevelCost() {
- return cost.asXpCost();
- }
-
- /**
- * Set the level cost displayed on the anvil.
- * Important note:
- * the final price are re calculated on click for the following use case:
- *
- * - Custom craft
- * - Unit repair
- * - Lore edit
- *
- * This value will be used as final price for:
- * Item merge
- * Item rename
- *
- *
- * @param levelCost The new cost.
- * @deprecated use #{@link #getCost()} and set value on this instead
- */
- @Deprecated(forRemoval = true, since = "1.17.0")
- public void setLevelCost(int levelCost) {
- cost.setGeneric(levelCost - cost.getGeneric() - cost.asXpCost());
- }
-
- /**
- * Allow access to the current cost of the event
- * Note that modifying this object will change the event resulting cost
- *
- * Important note:
- * the final price are re calculated on click for the following use case:
- *
- * - Custom craft
- * - Unit repair
- * - Lore edit
- *
- * This value will be used as final price for:
- * Item merge
- * Item rename
- *
- * @return the current anvil cost
- */
- public AnvilCost getCost() {
- return cost;
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResultEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResultEvent.java
deleted file mode 100644
index 80965b5..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResultEvent.java
+++ /dev/null
@@ -1,162 +0,0 @@
-package xyz.alexcrea.cuanvil.api.event.listener;
-
-import org.bukkit.event.Event;
-import org.bukkit.event.HandlerList;
-import org.bukkit.event.inventory.PrepareAnvilEvent;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import xyz.alexcrea.cuanvil.anvil.AnvilCost;
-import xyz.alexcrea.cuanvil.anvil.AnvilUseType;
-
-/**
- * Called after custom anvil processed the click on the result on the anvil inventory.
- * This event should be used to modify the result of an anvil use.
- *
- * You may also want to check {@link CAClickResultBypassEvent},
- * {@link CAPreAnvilBypassEvent}
- * and {@link CAEarlyPreAnvilBypassEvent} for your use case
- *
- * A null result will cancel this pre anvil event
- *
- * @deprecated Prepare anvil Event cannot be provided as it can be called on result and therefore not have prepared anvil event
- * use {@link CATreatAnvilResult2Event} instead
- */
-@SuppressWarnings("unused")
-@Deprecated(forRemoval = true, since = "1.17.0")
-public class CATreatAnvilResultEvent extends Event {
-
- private static final HandlerList HANDLERS = new HandlerList();
-
- public static HandlerList getHandlerList() {
- return HANDLERS;
- }
-
- @Override
- public @NotNull HandlerList getHandlers() {
- return HANDLERS;
- }
-
- @NotNull
- private final PrepareAnvilEvent event;
-
- private final AnvilUseType useType;
-
- @Nullable
- private ItemStack result;
-
- private final AnvilCost cost;
-
- public CATreatAnvilResultEvent(@NotNull PrepareAnvilEvent event, AnvilUseType useType, @Nullable ItemStack result, AnvilCost cost) {
- this.event = event;
- this.useType = useType;
- this.result = result;
- this.cost = cost;
- }
-
- /**
- * Get the bukkit inventory click event causing to this event.
- *
- * @return The click event causing to this event.
- */
- public @NotNull PrepareAnvilEvent getEvent() {
- return event;
- }
-
- /**
- * Get the type of use source of the result.
- *
- * @return The craft use type.
- */
- public AnvilUseType getUseType() {
- return useType;
- }
-
- /**
- * Get the current result
- *
- * note that it will not be null unless another listener previously set it to null.
- *
- * @return The current result.
- */
- public @Nullable ItemStack getResult() {
- return result;
- }
-
- /**
- * Set the current result
- *
- * note that a null result will cancel this anvil use.
- *
- * @param result The new result
- */
- public void setResult(@Nullable ItemStack result) {
- this.result = result;
- }
-
- /**
- * Get the level cost displayed on the anvil.
- *
Important note:
- * the final price are re calculated on click for the following use case:
- *
- * - Custom craft
- * - Unit repair
- * - Lore edit
- *
- * This value will be used as final price for:
- * Item merge
- * Item rename
- *
- *
- * @return The current cost.
- * @deprecated use #{@link #getCost()} instead
- */
- @Deprecated(forRemoval = true, since = "1.17.0")
- public int getLevelCost() {
- return cost.asXpCost();
- }
-
- /**
- * Set the level cost displayed on the anvil.
- * Important note:
- * the final price are re calculated on click for the following use case:
- *
- * - Custom craft
- * - Unit repair
- * - Lore edit
- *
- * This value will be used as final price for:
- * Item merge
- * Item rename
- *
- *
- * @param levelCost The new cost.
- * @deprecated use #{@link #getCost()} and set value on this instead
- */
- @Deprecated(forRemoval = true, since = "1.17.0")
- public void setLevelCost(int levelCost) {
- cost.setGeneric(levelCost - cost.getGeneric() - cost.asXpCost());
- }
-
- /**
- * Allow access to the current cost of the event
- * Note that modifying this object will change the event resulting cost
- *
- * Important note:
- * the final price are re calculated on click for the following use case:
- *
- * - Custom craft
- * - Unit repair
- * - Lore edit
- *
- * This value will be used as final price for:
- * Item merge
- * Item rename
- *
- * @return the current anvil cost
- */
- public AnvilCost getCost() {
- return cost;
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/config/ConfigHolder.java b/src/main/java/xyz/alexcrea/cuanvil/config/ConfigHolder.java
index f6a7e80..2037e23 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/config/ConfigHolder.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/config/ConfigHolder.java
@@ -9,7 +9,6 @@ import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.group.EnchantConflictManager;
import xyz.alexcrea.cuanvil.group.ItemGroupManager;
import xyz.alexcrea.cuanvil.recipe.CustomAnvilRecipeManager;
-import xyz.alexcrea.cuanvil.util.MetricsUtil;
import java.io.File;
import java.io.IOException;
@@ -146,7 +145,6 @@ public abstract class ConfigHolder {
sufficientSuccess = true;
} catch (IOException e) {
CustomAnvil.instance.getLogger().log(Level.WARNING, "Could not copy backup saving config " + base.getName(), e);
- MetricsUtil.INSTANCE.trackError(e);
}
}
// save last backup
@@ -277,7 +275,6 @@ public abstract class ConfigHolder {
this.deletedConfigFile.createNewFile();
} catch (IOException e) {
CustomAnvil.instance.getLogger().log(Level.WARNING, "Could not create " + this.deletedConfigFile.getPath(), e);
- MetricsUtil.INSTANCE.trackError(e);
}
loadDeletedListFile(false);
@@ -315,7 +312,6 @@ public abstract class ConfigHolder {
this.deletedListConfig.save(this.deletedConfigFile);
} catch (IOException e) {
CustomAnvil.instance.getLogger().log(Level.WARNING, "Could not save " + this.deletedConfigFile.getPath(), e);
- MetricsUtil.INSTANCE.trackError(e);
return false;
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/config/WorkPenaltyType.java b/src/main/java/xyz/alexcrea/cuanvil/config/WorkPenaltyType.java
deleted file mode 100644
index d374999..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/config/WorkPenaltyType.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package xyz.alexcrea.cuanvil.config;
-
-import com.google.common.collect.ImmutableMap;
-import org.jetbrains.annotations.Nullable;
-import xyz.alexcrea.cuanvil.anvil.AnvilUseType;
-
-import java.util.EnumMap;
-
-public class WorkPenaltyType {
-
- public record WorkPenaltyPart(
- boolean penaltyIncrease,
- boolean penaltyAdditive,
- boolean exclusivePenaltyIncrease,
- boolean exclusivePenaltyAdditive
- ) {
-
- @Override
- public boolean equals(Object obj) {
- if(!(obj instanceof WorkPenaltyPart other)) return false;
-
- return other.penaltyIncrease == this.penaltyIncrease &&
- other.penaltyAdditive == this.penaltyAdditive &&
- other.exclusivePenaltyIncrease == this.exclusivePenaltyIncrease &&
- other.exclusivePenaltyAdditive == this.exclusivePenaltyAdditive;
- }
-
- public WorkPenaltyPart(boolean penaltyIncrease, boolean penaltyAdditive) {
- this(penaltyIncrease, penaltyAdditive, false, false);
- }
- }
-
- private final EnumMap partMap;
-
- public WorkPenaltyType(@Nullable EnumMap partMap) {
- this.partMap = new EnumMap<>(partMap != null ? partMap : new EnumMap<>(AnvilUseType.class));
- }
-
- public ImmutableMap getPartMap() {
- return ImmutableMap.copyOf(partMap);
- }
-
- public WorkPenaltyPart getPenaltyInfo(AnvilUseType type) {
- return partMap.getOrDefault(type, type.getDefaultPenalty());
- }
-
- public boolean isPenaltyIncreasing(AnvilUseType type) {
- return partMap.getOrDefault(type, type.getDefaultPenalty()).penaltyIncrease;
- }
-
- public boolean isPenaltyAdditive(AnvilUseType type) {
- return partMap.getOrDefault(type, type.getDefaultPenalty()).penaltyAdditive;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof WorkPenaltyType that)) return false;
-
- for (AnvilUseType type : AnvilUseType.getEntries()) {
- if(!getPenaltyInfo(type).equals(that.getPenaltyInfo(type))) return false;
- }
- return true;
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/AdditionalTestEnchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/AdditionalTestEnchantment.java
index 821838f..832e5af 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/AdditionalTestEnchantment.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/AdditionalTestEnchantment.java
@@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.enchant;
import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@@ -12,23 +11,24 @@ public interface AdditionalTestEnchantment {
/**
* 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 itemType Material namespaced key of the tested item.
+ * @param itemMat Material of the tested item.
* @return If there is a conflict with the enchantments.
*/
boolean isEnchantConflict(
@NotNull Map enchantments,
- @NotNull NamespacedKey itemType);
+ @NotNull Material itemMat);
+
/**
* 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 itemType Material namespaced key of the tested item.
+ * @param itemMat Material of the tested item.
* @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.
*/
boolean isItemConflict(
@NotNull Map enchantments,
- @NotNull NamespacedKey itemType,
+ @NotNull Material itemMat,
@NotNull ItemStack item);
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantment.java
index ea657ac..0303733 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantment.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantment.java
@@ -12,7 +12,6 @@ import xyz.alexcrea.cuanvil.group.EnchantConflictGroup;
import java.util.Collection;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
/**
@@ -207,6 +206,7 @@ public interface CAEnchantment {
@NotNull ItemMeta meta,
@NotNull Map enchantments,
@NotNull Collection enchantmentToTest){
+
for (CAEnchantment enchantment : enchantmentToTest) {
if(enchantment.isEnchantmentPresent(item, meta)){
enchantments.put(enchantment, enchantment.getLevel(item, meta));
@@ -226,24 +226,12 @@ public interface CAEnchantment {
}
/**
- * Gets the enchantment by the provided name.
- * @param name Name to fetch.
- * @return Registered enchantment. null if absent.
- *
- * @deprecated use {@link #getListByName(String)}
+ * Gets a list of all the unoptimised enchantments.
+ * @param name The enchantment name
+ * @return List of enchantment.
*/
- @Deprecated(since = "1.6.3")
static @Nullable CAEnchantment getByName(@NotNull String name){
return CAEnchantmentRegistry.getInstance().getByName(name);
}
- /**
- * Gets list of enchantment using the provided name.
- * @param name Name to fetch.
- * @return List of registered enchantment.
- */
- static List getListByName(@NotNull String name){
- return CAEnchantmentRegistry.getInstance().getListByName(name);
- }
-
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantmentRegistry.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantmentRegistry.java
index 854ed55..01262f9 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantmentRegistry.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantmentRegistry.java
@@ -5,12 +5,10 @@ import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.enchant.bulk.BukkitEnchantBulkOperation;
import xyz.alexcrea.cuanvil.enchant.bulk.BulkCleanEnchantOperation;
import xyz.alexcrea.cuanvil.enchant.bulk.BulkGetEnchantOperation;
import xyz.alexcrea.cuanvil.enchant.wrapped.CABukkitEnchantment;
-import xyz.alexcrea.cuanvil.util.MetricsUtil;
import java.util.*;
import java.util.logging.Level;
@@ -18,14 +16,13 @@ import java.util.logging.Level;
public class CAEnchantmentRegistry {
private static final CAEnchantmentRegistry instance = new CAEnchantmentRegistry();
-
public static CAEnchantmentRegistry getInstance() {
return instance;
}
// Register enchantment functions
private final HashMap byKeyMap;
- private final HashMap> byNameMap;
+ private final HashMap byNameMap;
private final SortedSet nameSortedEnchantments;
@@ -52,7 +49,7 @@ public class CAEnchantmentRegistry {
* This should only be called on main of custom anvil.
* If called more than one time, chance of thing being broken will be high.
*/
- public void registerBukkit() {
+ public void registerBukkit(){
// Register enchantment
for (Enchantment enchantment : Enchantment.values()) {
register(new CABukkitEnchantment(enchantment));
@@ -62,58 +59,39 @@ public class CAEnchantmentRegistry {
BukkitEnchantBulkOperation bukkitOperation = new BukkitEnchantBulkOperation();
optimisedGetOperators.add(bukkitOperation);
optimisedCleanOperators.add(bukkitOperation);
- }
- private static boolean hasWarnedRegistering = false;
+ }
/**
* Can be used to register new enchantment.
*
* No guarantee that the enchantment will be present on the config gui if registered late.
* (By late I mean after custom anvil startup.)
- *
* @param enchantment The enchantment to be registered.
* @return If the operation was successful.
*/
- public boolean register(@NotNull CAEnchantment enchantment) {
- if (byKeyMap.containsKey(enchantment.getKey())) {
- if (Objects.equals(enchantment, byKeyMap.get(enchantment.getKey()))) {
- // We are trying to register the exact same enchantment. so we just skip it.
- return false;
- }
-
- if (ConfigHolder.DEFAULT_CONFIG.getConfig().getBoolean("caution_secret_do_not_log_duplicated_registered_key", false)) {
- return false;
- }
-
- var error = new IllegalStateException("enchantment " + enchantment.getKey() + " was already registered");
+ public boolean register(@NotNull CAEnchantment enchantment){
+ if(byKeyMap.containsKey(enchantment.getKey())){
CustomAnvil.instance.getLogger().log(Level.WARNING,
- "Duplicate distinct registered enchantment. This should NOT happen any time.\n" +
- "If you are a custom anvil developer: Maybe custom anvil detected your enchantment as a bukkit enchantment. " +
- "you should maybe remove enchantment with the same key before registering yours",
- error);
- MetricsUtil.INSTANCE.trackError(error);
+ "Duplicate registered enchantment. This should NOT happen.",
+ new IllegalStateException(enchantment.getKey()+" enchantment was already registered"));
return false;
}
-
- if ((!hasWarnedRegistering) && byNameMap.containsKey(enchantment.getName())) {
- hasWarnedRegistering = true;
-
+ if(byNameMap.containsKey(enchantment.getName())){
CustomAnvil.instance.getLogger().log(Level.WARNING,
- "Duplicate registered enchantment name. Please check that configuration is using namespace.");
+ "Duplicate registered enchantment name. There will have issue. " +
+ "\nI hope this do not happen to you on a production server. If it do, there is probably a plugin trying to register an enchantment with the same name than another one",
+ new IllegalStateException(enchantment.getKey()+" enchantment name was already registered"));
}
byKeyMap.put(enchantment.getKey(), enchantment);
-
- byNameMap.putIfAbsent(enchantment.getName(), new ArrayList<>());
- byNameMap.get(enchantment.getName()).add(enchantment);
-
+ byNameMap.put(enchantment.getName(), enchantment);
nameSortedEnchantments.add(enchantment);
- if (!enchantment.isGetOptimised()) {
+ if(!enchantment.isGetOptimised()){
unoptimisedGetValues.add(enchantment);
}
- if (!enchantment.isCleanOptimised()) {
+ if(!enchantment.isCleanOptimised()){
unoptimisedCleanValues.add(enchantment);
}
@@ -127,15 +105,14 @@ public class CAEnchantmentRegistry {
*
* No guarantee that the enchantment will absent if the config guis if unregistered late.
* (By late I mean after custom anvil startup.)
- *
* @param enchantment The enchantment to be unregistered.
* @return If the operation was successful.
*/
- public boolean unregister(@Nullable CAEnchantment enchantment) {
- if (enchantment == null) return false;
+ public boolean unregister(@Nullable CAEnchantment enchantment){
+ if(enchantment == null) return false;
byKeyMap.remove(enchantment.getKey());
- byNameMap.get(enchantment.getName()).remove(enchantment);
+ byNameMap.remove(enchantment.getName());
nameSortedEnchantments.remove(enchantment);
@@ -146,45 +123,26 @@ public class CAEnchantmentRegistry {
/**
* Gets the enchantment by the provided key.
- *
* @param key Key to fetch.
* @return Registered enchantment. null if absent.
*/
@Nullable
- public CAEnchantment getByKey(@NotNull NamespacedKey key) {
+ public CAEnchantment getByKey(@NotNull NamespacedKey key){
return byKeyMap.get(key);
}
/**
* Gets the enchantment by the provided name.
- *
* @param name Name to fetch.
* @return Registered enchantment. null if absent.
- * @deprecated use {@link #getListByName(String)}
*/
- @Deprecated(since = "1.6.3")
@Nullable
- public CAEnchantment getByName(@NotNull String name) {
- List enchantments = getListByName(name);
- if (enchantments.isEmpty()) return null;
-
- return enchantments.get(0);
- }
-
- /**
- * Gets list of enchantment using the provided name.
- *
- * @param name Name to fetch.
- * @return List of registered enchantment.
- */
- @NotNull
- public List getListByName(@NotNull String name) {
- return byNameMap.getOrDefault(name, Collections.emptyList());
+ public CAEnchantment getByName(@NotNull String name){
+ return byNameMap.get(name);
}
/**
* Gets an array of all the registered enchantments.
- *
* @return Array of enchantments.
*/
@NotNull
@@ -194,7 +152,6 @@ public class CAEnchantmentRegistry {
/**
* Gets a map of all the registered enchantments.
- *
* @return Immutable map of enchantments.
*/
public Map registeredEnchantments() {
@@ -203,7 +160,6 @@ public class CAEnchantmentRegistry {
/**
* Gets a list of all the unoptimised get operation enchantments.
- *
* @return List of unoptimised enchantments.
*/
@NotNull
@@ -213,7 +169,6 @@ public class CAEnchantmentRegistry {
/**
* Gets a list of all the unoptimised clean operation enchantments.
- *
* @return List of unoptimised enchantments.
*/
@NotNull
@@ -223,7 +178,6 @@ public class CAEnchantmentRegistry {
/**
* Get "clean optimised operation" for get enchantments.
- *
* @return Mutable "clean enchantments optimised operation" list.
*/
public List getOptimisedCleanOperators() {
@@ -232,7 +186,6 @@ public class CAEnchantmentRegistry {
/**
* Get "get optimised operation" for get enchantments.
- *
* @return Mutable "get enchantments optimised operation" list.
*/
public List getOptimisedGetOperators() {
@@ -241,7 +194,6 @@ public class CAEnchantmentRegistry {
/**
* Get custom anvil enchantment sorted by name.
- *
* @return An immutable sorted set of every registered enchantment sorted by name.
*/
public SortedSet getNameSortedEnchantments() {
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/EnchantmentRarity.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/EnchantmentRarity.java
index 3718f39..57ccb72 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/EnchantmentRarity.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/EnchantmentRarity.java
@@ -12,12 +12,12 @@ public class EnchantmentRarity {
private final int itemValue;
private final int bookValue;
- private EnchantmentRarity(int itemValue, int bookValue) {
+ public EnchantmentRarity(int itemValue, int bookValue) {
this.itemValue = itemValue;
this.bookValue = bookValue;
}
- private EnchantmentRarity(int itemValue) {
+ public EnchantmentRarity(int itemValue) {
this(itemValue, Math.max(1, itemValue / 2));
}
@@ -29,24 +29,4 @@ public class EnchantmentRarity {
return itemValue;
}
-
- public static EnchantmentRarity getRarity(int itemValue, int bookValue){
- int expectedBook = Math.max(1, itemValue / 2);
- if((expectedBook == bookValue) && (itemValue != 0)) return getRarity(itemValue);
-
- if(itemValue == 0 && bookValue == 0) return NO_RARITY;
- return new EnchantmentRarity(itemValue, bookValue);
- }
-
- public static EnchantmentRarity getRarity(int itemValue){
- return switch (itemValue) {
- case 0 -> NO_RARITY;
- case 1 -> COMMON;
- case 2 -> UNCOMMON;
- case 4 -> RARE;
- case 8 -> VERY_RARE;
- default -> new EnchantmentRarity(itemValue);
- };
- }
-
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/BukkitEnchantBulkOperation.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/BukkitEnchantBulkOperation.java
index 73e4185..d34bd49 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/BukkitEnchantBulkOperation.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/BukkitEnchantBulkOperation.java
@@ -1,10 +1,7 @@
package xyz.alexcrea.cuanvil.enchant.bulk;
-import io.delilaheve.CustomAnvil;
-import io.delilaheve.util.ConfigOptions;
import io.delilaheve.util.ItemUtil;
import org.bukkit.Material;
-import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
@@ -17,37 +14,22 @@ import java.util.Map;
public class BukkitEnchantBulkOperation implements BulkGetEnchantOperation, BulkCleanEnchantOperation {
@Override
- public void bulkGet(@NotNull Map enchantmentMap, @NotNull ItemStack item, @NotNull ItemMeta meta) {
- boolean isBook = ItemUtil.INSTANCE.isEnchantedBook(item);
-
- if (isBook) {
- ((EnchantmentStorageMeta) meta).getStoredEnchants().forEach((enchantment, level) ->
- addEnchantment(enchantmentMap, enchantment, level)
+ public void bulkGet(@NotNull Map enchantmentList, @NotNull ItemStack item, @NotNull ItemMeta meta) {
+ if (ItemUtil.INSTANCE.isEnchantedBook(item)) {
+ ((EnchantmentStorageMeta)meta).getStoredEnchants().forEach((enchantment, level) ->
+ enchantmentList.put(EnchantmentApi.getByKey(enchantment.getKey()), level)
);
- }
- if(!isBook || ConfigOptions.INSTANCE.getAddBookEnchantmentAsStoredEnchantment()){
+ } else {
item.getEnchantments().forEach((enchantment, level) ->
- addEnchantment(enchantmentMap, enchantment, level)
+ enchantmentList.put(EnchantmentApi.getByKey(enchantment.getKey()), level)
);
}
}
- public void addEnchantment(@NotNull Map enchantmentMap, @NotNull Enchantment enchantment, int level) {
- CAEnchantment enchant = EnchantmentApi.getByKey(enchantment.getKey());
- if (enchant == null) {
- CustomAnvil.instance.getLogger().warning("Enchantment of key " + enchantment.getKey() +
- " somehow not found in CustomAnvil ?");
- return;
- }
-
- enchantmentMap.put(enchant, level);
- }
-
@Override
public void bulkClear(@NotNull ItemStack item) {
- if (item.getType() != Material.ENCHANTED_BOOK || ConfigOptions.INSTANCE.getAddBookEnchantmentAsStoredEnchantment()) {
-
- item.getEnchantments().forEach((enchantment, level) ->
+ if (item.getType() != Material.ENCHANTED_BOOK) {
+ item.getEnchantments().forEach((enchantment, leve) ->
item.removeEnchantment(enchantment)
);
}
@@ -61,6 +43,5 @@ public class BukkitEnchantBulkOperation implements BulkGetEnchantOperation, Bulk
bookMeta.removeStoredEnchant(enchantment)
);
}
-
}
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/BulkGetEnchantOperation.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/BulkGetEnchantOperation.java
index 7c66e8a..a985edd 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/BulkGetEnchantOperation.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/BulkGetEnchantOperation.java
@@ -14,10 +14,10 @@ public interface BulkGetEnchantOperation {
/**
* Bulk get part of the stored enchantment of this item.
- * @param enchantmentMap Mutable map of collected enchantment. should b
+ * @param enchantmentList Mutable map of collected enchantment. should b
* @param item The item to get enchantment from. Should not get edited.
* @param meta The item meta to get enchantment from. Should not get edited.
*/
- void bulkGet(@NotNull Map enchantmentMap, @NotNull ItemStack item, @NotNull ItemMeta meta);
+ void bulkGet(@NotNull Map enchantmentList, @NotNull ItemStack item, @NotNull ItemMeta meta);
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/EnchantSquaredBulkOperation.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/EnchantSquaredBulkOperation.java
index 57ecf60..59bd6ec 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/EnchantSquaredBulkOperation.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/EnchantSquaredBulkOperation.java
@@ -5,7 +5,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.dependency.DependencyManager;
-import xyz.alexcrea.cuanvil.dependency.plugins.EnchantmentSquaredDependency;
+import xyz.alexcrea.cuanvil.dependency.EnchantmentSquaredDependency;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import java.util.Collections;
@@ -14,10 +14,10 @@ import java.util.Map;
public class EnchantSquaredBulkOperation implements BulkGetEnchantOperation, BulkCleanEnchantOperation {
@Override
- public void bulkGet(@NotNull Map enchantmentMap, @NotNull ItemStack item, @NotNull ItemMeta meta) {
+ public void bulkGet(@NotNull Map enchantmentList, @NotNull ItemStack item, @NotNull ItemMeta meta) {
EnchantmentSquaredDependency enchantmentSquared = DependencyManager.INSTANCE.getEnchantmentSquaredCompatibility();
if(enchantmentSquared != null){
- enchantmentSquared.getEnchantmentsSquared(item, enchantmentMap);
+ enchantmentSquared.getEnchantmentsSquared(item, enchantmentList);
}
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/SuperEnchantBulkOperation.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/SuperEnchantBulkOperation.java
deleted file mode 100644
index 8bc729a..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/bulk/SuperEnchantBulkOperation.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package xyz.alexcrea.cuanvil.enchant.bulk;
-
-import com.maddoxh.superEnchants.items.EnchantApplicator;
-import com.maddoxh.superEnchants.items.EnchantReader;
-import io.delilaheve.CustomAnvil;
-import org.bukkit.NamespacedKey;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.inventory.meta.ItemMeta;
-import org.bukkit.plugin.Plugin;
-import org.jetbrains.annotations.NotNull;
-import xyz.alexcrea.cuanvil.api.EnchantmentApi;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
-
-import java.util.Map;
-
-public class SuperEnchantBulkOperation implements BulkGetEnchantOperation, BulkCleanEnchantOperation {
-
- private Plugin plugin;
- public SuperEnchantBulkOperation(Plugin plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public void bulkGet(@NotNull Map enchantmentMap, @NotNull ItemStack item, @NotNull ItemMeta meta) {
- EnchantReader.INSTANCE.readEnchants(item).forEach((ench, level) -> {
- var enchantment = EnchantmentApi.getByKey(NamespacedKey.fromString(ench, plugin));
- if(enchantment == null) {
- CustomAnvil.log("Enchantment " + ench + " not found in custom anvil");
- return;
- }
-
- enchantmentMap.put(enchantment, level);
- }
- );
- }
-
- @Override
- public void bulkClear(@NotNull ItemStack item) {
- EnchantApplicator.INSTANCE.clearAllCustomEnchants(item);
- }
-
- @Override
- public void bulkClear(@NotNull ItemStack item, @NotNull ItemMeta meta) {
- // item meta is not preferred for enchantment squared clear
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CABukkitEnchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CABukkitEnchantment.java
index 0e630ea..0f4a0e3 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CABukkitEnchantment.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CABukkitEnchantment.java
@@ -1,10 +1,7 @@
package xyz.alexcrea.cuanvil.enchant.wrapped;
-import io.delilaheve.CustomAnvil;
-import io.delilaheve.util.ConfigOptions;
import io.delilaheve.util.ItemUtil;
import org.bukkit.enchantments.Enchantment;
-import org.bukkit.enchantments.EnchantmentTarget;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
@@ -14,30 +11,24 @@ import xyz.alexcrea.cuanvil.enchant.CAEnchantmentBase;
import xyz.alexcrea.cuanvil.enchant.EnchantmentProperties;
import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.HashMap;
import java.util.Locale;
-import java.util.Map;
-import java.util.Objects;
-import java.util.logging.Level;
/**
* Custom Anvil enchantment implementation for vanilla registered enchantment.
*/
public class CABukkitEnchantment extends CAEnchantmentBase {
- public final @NotNull Enchantment bukkit;
+ private final @NotNull Enchantment enchantment;
- public CABukkitEnchantment(@NotNull Enchantment bukkit, @Nullable EnchantmentRarity rarity) {
- super(bukkit.getKey(),
+ public CABukkitEnchantment(@NotNull Enchantment enchantment, @Nullable EnchantmentRarity rarity){
+ super(enchantment.getKey(),
rarity,
- bukkit.getMaxLevel());
- this.bukkit = bukkit;
+ enchantment.getMaxLevel());
+ this.enchantment = enchantment;
}
- public CABukkitEnchantment(@NotNull Enchantment bukkit) {
- this(bukkit, getRarity(bukkit));
+ public CABukkitEnchantment(@NotNull Enchantment enchantment){
+ this(enchantment, getRarity(enchantment));
}
@Override
@@ -53,34 +44,33 @@ public class CABukkitEnchantment extends CAEnchantmentBase {
@Override
public int getLevel(@NotNull ItemStack item, @NotNull ItemMeta meta) {
if (ItemUtil.INSTANCE.isEnchantedBook(item)) {
- return ((EnchantmentStorageMeta) meta).getStoredEnchantLevel(this.bukkit);
+ return ((EnchantmentStorageMeta)meta).getStoredEnchantLevel(this.enchantment);
} else {
- return meta.getEnchantLevel(this.bukkit);
+ return meta.getEnchantLevel(this.enchantment);
}
}
@Override
public boolean isEnchantmentPresent(@NotNull ItemStack item, @NotNull ItemMeta meta) {
if (ItemUtil.INSTANCE.isEnchantedBook(item)) {
- EnchantmentStorageMeta bookMeta = ((EnchantmentStorageMeta) meta);
+ EnchantmentStorageMeta bookMeta = ((EnchantmentStorageMeta)meta);
- return bookMeta.getStoredEnchants().containsKey(this.bukkit) ||
- (ConfigOptions.INSTANCE.getAddBookEnchantmentAsStoredEnchantment() && item.containsEnchantment(this.bukkit));
- } else {
- return item.containsEnchantment(this.bukkit);
+ return bookMeta.getStoredEnchants().containsKey(this.enchantment);
+ }else{
+ return item.containsEnchantment(this.enchantment);
}
}
@Override
public void addEnchantmentUnsafe(@NotNull ItemStack item, int level) {
if (ItemUtil.INSTANCE.isEnchantedBook(item)) {
- EnchantmentStorageMeta bookMeta = ((EnchantmentStorageMeta) item.getItemMeta());
+ EnchantmentStorageMeta bookMeta = ((EnchantmentStorageMeta)item.getItemMeta());
assert bookMeta != null;
- bookMeta.addStoredEnchant(this.bukkit, level, true);
+ bookMeta.addStoredEnchant(this.enchantment, level, true);
item.setItemMeta(bookMeta);
} else {
- item.addUnsafeEnchantment(this.bukkit, level);
+ item.addUnsafeEnchantment(this.enchantment, level);
}
}
@@ -88,87 +78,28 @@ public class CABukkitEnchantment extends CAEnchantmentBase {
@Override
public void removeFrom(@NotNull ItemStack item) {
if (ItemUtil.INSTANCE.isEnchantedBook(item)) {
- EnchantmentStorageMeta bookMeta = ((EnchantmentStorageMeta) item.getItemMeta());
+ EnchantmentStorageMeta bookMeta = ((EnchantmentStorageMeta)item.getItemMeta());
assert bookMeta != null;
- bookMeta.removeStoredEnchant(this.bukkit);
- bookMeta.removeEnchant(this.bukkit);
+ bookMeta.removeStoredEnchant(this.enchantment);
item.setItemMeta(bookMeta);
- } else {
- item.removeEnchantment(this.bukkit);
+ }else{
+ item.removeEnchantment(this.enchantment);
}
}
@NotNull
- public static EnchantmentRarity getRarity(Enchantment enchantment) {
+ public static EnchantmentRarity getRarity(Enchantment enchantment){
try {
return EnchantmentProperties.valueOf(enchantment.getKey().getKey().toUpperCase(Locale.ENGLISH)).getRarity();
} catch (IllegalArgumentException ignored) {
- return findRarity(enchantment);
+ return EnchantmentRarity.COMMON;
}
}
@NotNull
protected Enchantment getEnchant() {
- return this.bukkit;
+ return this.enchantment;
}
-
- private static Method getAnvilCostMethod;
-
- static {
- Class clazz = Enchantment.class;
- try {
- getAnvilCostMethod = clazz.getDeclaredMethod("getAnvilCost");
- getAnvilCostMethod.setAccessible(true);
-
- CustomAnvil.Companion.log("Detected getAnvilCost method");
- } catch (NoSuchMethodException e) {
- getAnvilCostMethod = null;
- }
-
- }
-
- private static final Map targetToGroup = new HashMap<>();
- static {
- targetToGroup.put(EnchantmentTarget.ARMOR, "armors");
- targetToGroup.put(EnchantmentTarget.ARMOR_HEAD, "helmets");
- targetToGroup.put(EnchantmentTarget.ARMOR_TORSO, "chestplate");
- targetToGroup.put(EnchantmentTarget.ARMOR_LEGS, "leggings");
- targetToGroup.put(EnchantmentTarget.ARMOR_FEET, "boots");
- targetToGroup.put(EnchantmentTarget.BOW, "bow");
- targetToGroup.put(EnchantmentTarget.BREAKABLE, "can_unbreak");
- targetToGroup.put(EnchantmentTarget.CROSSBOW, "crossbow");
- targetToGroup.put(EnchantmentTarget.FISHING_ROD, "fishing_rod");
- targetToGroup.put(EnchantmentTarget.TOOL, "tools");
- targetToGroup.put(EnchantmentTarget.TRIDENT, "trident");
- targetToGroup.put(EnchantmentTarget.VANISHABLE, "can_vanish");
- targetToGroup.put(EnchantmentTarget.WEAPON, "swords");
- targetToGroup.put(EnchantmentTarget.WEARABLE, "wearable");
- }
-
- private static EnchantmentRarity findRarity(Enchantment enchantment) {
- if (getAnvilCostMethod == null) return EnchantmentRarity.COMMON;
-
- try {
- int itemCost = (int) getAnvilCostMethod.invoke(enchantment);
-
- return EnchantmentRarity.getRarity(itemCost);
- } catch (IllegalAccessException | InvocationTargetException e) {
- CustomAnvil.instance.getLogger().log(Level.SEVERE, "could not find cost for enchantment " + enchantment.getKey(), e);
-
- return EnchantmentRarity.COMMON;
- }
-
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof CABukkitEnchantment other)) {
- return false;
- }
-
- return Objects.equals(this.bukkit, other.getEnchant());
- }
-
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEPreV5Enchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEPreV5Enchantment.java
deleted file mode 100644
index 783798d..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEPreV5Enchantment.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package xyz.alexcrea.cuanvil.enchant.wrapped;
-
-import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.excellentenchants.api.enchantment.CustomEnchantment;
-import su.nightexpress.excellentenchants.api.enchantment.Definition;
-import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Map;
-import java.util.Set;
-
-public class CAEEPreV5Enchantment extends CABukkitEnchantment implements AdditionalTestEnchantment {
-
- @NotNull CustomEnchantment eeenchantment;
- @NotNull Definition definition;
-
- public CAEEPreV5Enchantment(@NotNull CustomEnchantment enchantment) {
- super(enchantment.getBukkitEnchantment(), getRarity(enchantment.getBukkitEnchantment()));
- this.eeenchantment = enchantment;
- try {
- this.definition = (Definition) getDefinition.invoke(enchantment);
- } catch (IllegalAccessException | InvocationTargetException e) {
- throw new RuntimeException(e);
- }
-
- }
-
- private final static Method getDefinition;
- static {
- try {
- getDefinition = CustomEnchantment.class.getMethod("getDefinition");
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType) {
- if (!definition.hasConflicts()) return false;
-
- Set conflicts = definition.getConflicts();
-
- for (CAEnchantment caEnchantment : enchantments.keySet()) {
- if (conflicts.contains(caEnchantment.getName())) return true;
- }
-
- return false;
- }
-
- @Override
- public boolean isItemConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType, @NotNull ItemStack item) {
- if (Material.ENCHANTED_BOOK.getKey().equals(itemType)) return false;
-
- return !definition.getSupportedItems().is(item);
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEV5Enchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEV5Enchantment.java
deleted file mode 100644
index 2d8f945..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEV5Enchantment.java
+++ /dev/null
@@ -1,128 +0,0 @@
-package xyz.alexcrea.cuanvil.enchant.wrapped;
-
-import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.excellentenchants.api.enchantment.CustomEnchantment;
-import su.nightexpress.excellentenchants.api.item.ItemSet;
-import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
-import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Map;
-import java.util.Set;
-
-public class CAEEV5Enchantment extends CABukkitEnchantment implements AdditionalTestEnchantment {
-
- @NotNull CustomEnchantment eeenchantment;
- @NotNull Object definition;
-
- public CAEEV5Enchantment(@NotNull CustomEnchantment enchantment) {
- super(enchantment.getBukkitEnchantment(), EnchantmentRarity.getRarity(getAnvilCost(enchantment)));
- this.eeenchantment = enchantment;
- this.definition = getDefinition(enchantment);
-
- }
-
- @Override
- public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType) {
- if (!hasConflicts()) return false;
-
- Set conflicts = getExclusiveSet();
-
- for (CAEnchantment caEnchantment : enchantments.keySet()) {
- if (conflicts.contains(caEnchantment.getName())) return true;
- if (conflicts.contains(caEnchantment.getKey().toString())) return true;
- }
-
- return false;
- }
-
- @Override
- public boolean isItemConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType, @NotNull ItemStack item) {
- if (Material.ENCHANTED_BOOK.getKey().equals(itemType)) return false;
-
- String key = itemType.getKey();
- ItemSet primary = eeenchantment.getPrimaryItems();
- if (primary.getMaterials().contains(key)) return false;
-
- ItemSet supported = eeenchantment.getSupportedItems();
- if (supported.getMaterials().contains(key)) return false;
-
- return true;
- }
-
-
- private static final Method getDefinitonMethod;
-
- private static final Method getAnvilCostMethod;
- private static final Method hasConflictsMethod;
- private static final Method getExclusiveSetMethod;
- static {
- var enchClazz = CustomEnchantment.class;
- try {
- getDefinitonMethod = enchClazz.getDeclaredMethod("getDefinition");
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
-
- Class> definitionClazz;
- try {
- definitionClazz = Class.forName("su.nightexpress.excellentenchants.api.EnchantDefinition");
- } catch (ClassNotFoundException e) {
- try {
- definitionClazz = Class.forName("su.nightexpress.excellentenchants.api.wrapper.EnchantDefinition");
- } catch (ClassNotFoundException ex) {
- throw new RuntimeException(ex);
- }
- }
-
- // Now definition methods
- try {
- getAnvilCostMethod = definitionClazz.getDeclaredMethod("getAnvilCost");
- hasConflictsMethod = definitionClazz.getDeclaredMethod("hasConflicts");
- getExclusiveSetMethod = definitionClazz.getDeclaredMethod("getExclusiveSet");
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
-
- }
-
- private static Object getDefinition(CustomEnchantment enchantment) {
- try {
- return getDefinitonMethod.invoke(enchantment);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private static int getAnvilCost(CustomEnchantment enchantment) {
- try {
- return (int) getAnvilCostMethod.invoke(getDefinition(enchantment));
- } catch (IllegalAccessException | InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
-
- private boolean hasConflicts() {
- try {
- return (boolean) hasConflictsMethod.invoke(definition);
- } catch (IllegalAccessException | InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
-
-
- private Set getExclusiveSet() {
- try {
- return (Set) getExclusiveSetMethod.invoke(definition);
- } catch (IllegalAccessException | InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
-
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEV5_4Enchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEV5_4Enchantment.java
deleted file mode 100644
index 7fb8627..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEEV5_4Enchantment.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package xyz.alexcrea.cuanvil.enchant.wrapped;
-
-import org.bukkit.NamespacedKey;
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.excellentenchants.api.enchantment.CustomEnchantment;
-import xyz.alexcrea.cuanvil.dependency.plugins.ExcellentEnchant5_4EnchantSettings;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
-
-import java.util.Map;
-
-public class CAEEV5_4Enchantment extends CAEEV5Enchantment {
-
- public CAEEV5_4Enchantment(@NotNull CustomEnchantment enchantment) {
- super(enchantment);
- }
-
- @Override
- public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemMat) {
- if(super.isEnchantConflict(enchantments, itemMat)) return true;
-
- var limit = ExcellentEnchant5_4EnchantSettings.anvilLimit();
- var count = enchantments.keySet().stream()
- .filter(key -> key instanceof CAEEV5_4Enchantment)
- .count();
-
- return count > limit;
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEcoEnchant.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEcoEnchant.java
index 32d1346..0d85ffd 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEcoEnchant.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEcoEnchant.java
@@ -2,16 +2,13 @@ package xyz.alexcrea.cuanvil.enchant.wrapped;
import com.willfp.ecoenchants.enchant.EcoEnchant;
import com.willfp.ecoenchants.target.EnchantmentTarget;
-import com.willfp.ecoenchants.type.EnchantmentType;
import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
-import java.util.HashMap;
import java.util.Map;
public class CAEcoEnchant extends CABukkitEnchantment implements AdditionalTestEnchantment {
@@ -24,52 +21,33 @@ public class CAEcoEnchant extends CABukkitEnchantment implements AdditionalTestE
}
@Override
- public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType) {
- if (enchantments.isEmpty()) return false;
-
- // Check if there is only self
- if (enchantments.size() == 1 && this.equals(enchantments.keySet().stream().findFirst().get()))
- return false;
-
- if (this.ecoEnchant.getConflictsWithEverything()) {
- return true;
- }
-
- HashMap typeAmountMap = new HashMap<>();
-
- for (CAEnchantment other : enchantments.keySet()) {
- if (other instanceof CABukkitEnchantment otherVanilla
- && this.ecoEnchant.conflictsWith(otherVanilla.getEnchant())) {
+ public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull Material itemMat) {
+ if(!enchantments.isEmpty()) {
+ if (this.ecoEnchant.getConflictsWithEverything()) {
return true;
}
- if (other instanceof CAEcoEnchant ecoOther) {
- EnchantmentType type = ecoOther.ecoEnchant.getType();
- typeAmountMap.putIfAbsent(type, 0);
-
- int amount = typeAmountMap.get(type) + 1;
- if (amount > type.getLimit()) {
+ for (CAEnchantment other : enchantments.keySet()) {
+ if(other instanceof CABukkitEnchantment otherVanilla
+ && this.ecoEnchant.conflictsWith(otherVanilla.getEnchant())){
return true;
}
-
- typeAmountMap.put(type, amount);
}
}
-
return false;
}
@Override
public boolean isItemConflict(@NotNull Map enchantments,
- @NotNull NamespacedKey itemType,
+ @NotNull Material itemMat,
@NotNull ItemStack item) {
- if (Material.ENCHANTED_BOOK.getKey().equals(itemType)) {
+ if(Material.ENCHANTED_BOOK.equals(itemMat)){
return false;
}
for (EnchantmentTarget target : this.ecoEnchant.getTargets()) {
- if (target.matches(item)) {
+ if(target.matches(item)){
return false;
}
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEnchantSquaredEnchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEnchantSquaredEnchantment.java
index 8f1058e..56b4bc7 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEnchantSquaredEnchantment.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEnchantSquaredEnchantment.java
@@ -3,6 +3,7 @@ package xyz.alexcrea.cuanvil.enchant.wrapped;
import me.athlaeos.enchantssquared.enchantments.CustomEnchant;
import me.athlaeos.enchantssquared.managers.CustomEnchantManager;
import org.bukkit.entity.HumanEntity;
+import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
@@ -16,20 +17,15 @@ import java.util.Objects;
public class CAEnchantSquaredEnchantment extends CAEnchantmentBase {
public final @NotNull CustomEnchant enchant;
-
public CAEnchantSquaredEnchantment(@NotNull CustomEnchant enchant) {
super(Objects.requireNonNull(
- Objects.requireNonNull(DependencyManager.INSTANCE.getEnchantmentSquaredCompatibility()).getKeyFromEnchant(enchant)),
+ Objects.requireNonNull(DependencyManager.INSTANCE.getEnchantmentSquaredCompatibility()).getKeyFromEnchant(enchant)),
EnchantmentRarity.COMMON,
enchant.getMaxLevel());
this.enchant = enchant;
}
- public @NotNull CustomEnchant getEnchant() {
- return enchant;
- }
-
@Override
public boolean isGetOptimised() {
return true;
@@ -66,14 +62,4 @@ public class CAEnchantSquaredEnchantment extends CAEnchantmentBase {
CustomEnchantManager.getInstance().removeEnchant(item, this.enchant.getType());
}
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof CAEnchantSquaredEnchantment other)) {
- return false;
- }
-
- return this.enchant.equals(other.getEnchant());
- }
-
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAIncompatibleAllEnchant.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAIncompatibleAllEnchant.java
deleted file mode 100644
index 552ecd4..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAIncompatibleAllEnchant.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package xyz.alexcrea.cuanvil.enchant.wrapped;
-
-import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
-import org.bukkit.enchantments.Enchantment;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import xyz.alexcrea.cuanvil.enchant.*;
-
-import java.util.Map;
-
-/**
- * Represent an enchantment incompatible with every other enchantments
- */
-public class CAIncompatibleAllEnchant extends CABukkitEnchantment implements AdditionalTestEnchantment {
-
- public CAIncompatibleAllEnchant(@NotNull Enchantment enchantment, @Nullable EnchantmentRarity rarity) {
- super(enchantment, rarity);
- }
-
- public CAIncompatibleAllEnchant(@NotNull Enchantment enchantment) {
- super(enchantment);
- }
-
-
- @Override
- public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType) {
- return !enchantments.isEmpty() && !(enchantments.size() == 1 && enchantments.containsKey(this));
- }
-
- @Override
- public boolean isItemConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType, @NotNull ItemStack item) {
- return false;
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CALegacyEEEnchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CALegacyEEEnchantment.java
deleted file mode 100644
index 74068d4..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CALegacyEEEnchantment.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package xyz.alexcrea.cuanvil.enchant.wrapped;
-
-import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.excellentenchants.api.enchantment.EnchantmentData;
-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.Set;
-
-public class CALegacyEEEnchantment extends CABukkitEnchantment implements AdditionalTestEnchantment {
-
- @NotNull EnchantmentData eeenchantment;
-
- public CALegacyEEEnchantment(@NotNull EnchantmentData enchantment) {
- super(enchantment.getEnchantment(), EnchantmentRarity.getRarity(enchantment.getAnvilCost()));
- this.eeenchantment = enchantment;
-
- }
-
- @Override
- public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType) {
- if (!eeenchantment.hasConflicts()) return false;
-
- Set conflicts = eeenchantment.getConflicts();
-
- for (CAEnchantment caEnchantment : enchantments.keySet()) {
- if (conflicts.contains(caEnchantment.getName())) return true;
- }
-
- return false;
- }
-
- @Override
- public boolean isItemConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType, @NotNull ItemStack item) {
- if (Material.ENCHANTED_BOOK.getKey().equals(itemType)) return false;
-
- return !eeenchantment.getSupportedItems().is(item);
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CALegacyEcoEnchant.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CALegacyEcoEnchant.java
deleted file mode 100644
index cb24def..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CALegacyEcoEnchant.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package xyz.alexcrea.cuanvil.enchant.wrapped;
-
-import com.willfp.ecoenchants.enchantments.EcoEnchant;
-import com.willfp.ecoenchants.enchantments.meta.EnchantmentTarget;
-import com.willfp.ecoenchants.enchantments.meta.EnchantmentType;
-import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
-import org.bukkit.enchantments.Enchantment;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
-import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
-import xyz.alexcrea.cuanvil.util.MaterialUtil;
-
-import java.util.Map;
-
-public class CALegacyEcoEnchant extends CABukkitEnchantment implements AdditionalTestEnchantment {
-
- private final @NotNull EcoEnchant ecoEnchant;
-
- public CALegacyEcoEnchant(@NotNull EcoEnchant ecoEnchant, @NotNull Enchantment enchantment) {
- super(enchantment, EnchantmentRarity.COMMON);
- this.ecoEnchant = ecoEnchant;
- }
-
- @Override
- public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType) {
- if (enchantments.isEmpty()) return false;
-
- EnchantmentType type = this.ecoEnchant.getType();
- boolean isSingular = type.isSingular();
-
- for (CAEnchantment other : enchantments.keySet()) {
- if (other instanceof CABukkitEnchantment otherVanilla
- && this.ecoEnchant.conflictsWith(otherVanilla.getEnchant())) {
- return true;
- }
-
- if (isSingular &&
- other != this &&
- (other instanceof CALegacyEcoEnchant otherEco) &&
- type.equals(otherEco.ecoEnchant.getType())) {
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- public boolean isItemConflict(@NotNull Map enchantments,
- @NotNull NamespacedKey itemType,
- @NotNull ItemStack item) {
- if (Material.ENCHANTED_BOOK.getKey().equals(itemType)) {
- return false;
- }
-
- var mat = MaterialUtil.INSTANCE.getMatFromKey(itemType);
- for (EnchantmentTarget target : this.ecoEnchant.getTargets()) {
- if (target.getMaterials().contains(mat)) {
- return false;
- }
- }
-
- return true;
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CASuperEnchantEnchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CASuperEnchantEnchantment.java
deleted file mode 100644
index 6039dc8..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CASuperEnchantEnchantment.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package xyz.alexcrea.cuanvil.enchant.wrapped;
-
-import com.maddoxh.superEnchants.enchants.CustomEnchant;
-import com.maddoxh.superEnchants.enchants.EnchantManager;
-import com.maddoxh.superEnchants.items.EnchantApplicator;
-import com.maddoxh.superEnchants.items.EnchantReader;
-import com.maddoxh.superEnchants.util.ConflictChecker;
-import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.inventory.meta.ItemMeta;
-import org.bukkit.plugin.Plugin;
-import org.jetbrains.annotations.NotNull;
-import xyz.alexcrea.cuanvil.enchant.AdditionalTestEnchantment;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantmentBase;
-import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class CASuperEnchantEnchantment extends CAEnchantmentBase implements AdditionalTestEnchantment {
-
- private @NotNull CustomEnchant enchant;
- private @NotNull EnchantManager enchantManager;
-
- public CASuperEnchantEnchantment(@NotNull CustomEnchant enchant, @NotNull Plugin plugin, @NotNull EnchantManager enchantManager) {
- super(NamespacedKey.fromString(enchant.getId(), plugin), EnchantmentRarity.COMMON, enchant.getMaxLevel());
-
- this.enchant = enchant;
- this.enchantManager = enchantManager;
- }
-
- @Override
- public int getLevel(@NotNull ItemStack item, @NotNull ItemMeta meta) {
- return EnchantReader.INSTANCE.getEnchantLevel(item, enchant.getId());
- }
-
- @Override
- public boolean isEnchantmentPresent(@NotNull ItemStack item, @NotNull ItemMeta meta) {
- return EnchantReader.INSTANCE.hasEnchant(item, enchant.getId());
- }
-
- @Override
- public void addEnchantmentUnsafe(@NotNull ItemStack item, int level) {
- EnchantApplicator.INSTANCE.applyEnchant(item, enchant.getId(), level);
- }
-
- @Override
- public void removeFrom(@NotNull ItemStack item) {
- EnchantApplicator.INSTANCE.removeEnchant(item, enchant.getId());
- }
-
- @Override
- public boolean isEnchantConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType) {
- var idMap = new HashMap();
-
- enchantments.forEach((enchant, level) -> {
- if(!(enchant instanceof CASuperEnchantEnchantment superEnch)) return;
- idMap.put(superEnch.enchant.getId(), level);
- });
-
- return ConflictChecker.INSTANCE.hasConflict(
- idMap,
- enchant.getId(),
- enchantManager
- ) != null;
- }
-
- @Override
- public boolean isItemConflict(@NotNull Map enchantments, @NotNull NamespacedKey itemType, @NotNull ItemStack item) {
- if(Material.ENCHANTED_BOOK.equals(item.getType())) return false;
-
- return !enchant.canApplyTo(item.getType());
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/MainConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/MainConfigGui.java
index cc4fddc..db4da89 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/MainConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/MainConfigGui.java
@@ -8,10 +8,9 @@ import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
-import xyz.alexcrea.cuanvil.dependency.packet.PacketManager;
+import xyz.alexcrea.cuanvil.dependency.protocolib.PacketManager;
import xyz.alexcrea.cuanvil.gui.config.global.*;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
-import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
import java.util.Collections;
@@ -24,13 +23,13 @@ public class MainConfigGui extends ChestGui {
}
private MainConfigGui() {
- super(3, "§8Anvil Config", CustomAnvil.instance);
+ super(3, "\u00A78Anvil Config", CustomAnvil.instance);
}
public void init(PacketManager packetManager) {
Pattern pattern = new Pattern(
- GuiSharedConstant.EMPTY_GUI_FULL_LINE,
- "012345678",
+ "000000000",
+ "012304567",
"Q00000000"
);
PatternPane pane = new PatternPane(0, 0, 9, 3, pattern);
@@ -43,8 +42,8 @@ public class MainConfigGui extends ChestGui {
ItemMeta basicConfigMeta = basicConfigItemstack.getItemMeta();
assert basicConfigMeta != null;
- basicConfigMeta.setDisplayName("§aBasic Config Menu");
- basicConfigMeta.setLore(Collections.singletonList("§7Click here to open basic config menu"));
+ basicConfigMeta.setDisplayName("\u00A7aBasic Config Menu");
+ basicConfigMeta.setLore(Collections.singletonList("\u00A77Click here to open basic config menu"));
basicConfigItemstack.setItemMeta(basicConfigMeta);
GuiItem basicConfigItem = GuiGlobalItems.goToGuiItem(basicConfigItemstack, new BasicConfigGui(packetManager));
@@ -55,92 +54,80 @@ public class MainConfigGui extends ChestGui {
ItemMeta enchantLimitMeta = enchantLimitItemstack.getItemMeta();
assert enchantLimitMeta != null;
- enchantLimitMeta.setDisplayName("§aEnchantment Level Limit");
- enchantLimitMeta.setLore(Collections.singletonList("§7Click here to open enchantment level limit menu"));
+ enchantLimitMeta.setDisplayName("\u00A7aEnchantment Level Limit");
+ enchantLimitMeta.setLore(Collections.singletonList("\u00A77Click here to open enchantment level limit menu"));
enchantLimitItemstack.setItemMeta(enchantLimitMeta);
GuiItem enchantLimitItem = GuiGlobalItems.goToGuiItem(enchantLimitItemstack, new EnchantLimitConfigGui());
pane.bindItem('2', enchantLimitItem);
- // enchant level limit item
- ItemStack enchantMergeLimitItemstack = new ItemStack(Material.ENCHANTED_BOOK);
- ItemMeta enchantMergeLimitMeta = enchantMergeLimitItemstack.getItemMeta();
- assert enchantMergeLimitMeta != null;
-
- enchantMergeLimitMeta.setDisplayName("§aEnchantment Merge Limit");
- enchantMergeLimitMeta.setLore(Collections.singletonList("§7Click here to open enchantment merge limit menu"));
- enchantMergeLimitItemstack.setItemMeta(enchantMergeLimitMeta);
-
- GuiItem enchantMergeLimitItem = GuiGlobalItems.goToGuiItem(enchantMergeLimitItemstack, new EnchantMergeLimitConfigGui());
- pane.bindItem('3', enchantMergeLimitItem);
-
// enchant cost item
ItemStack enchantCostItemstack = new ItemStack(Material.EXPERIENCE_BOTTLE);
ItemMeta enchantCostMeta = enchantCostItemstack.getItemMeta();
assert enchantCostMeta != null;
- enchantCostMeta.setDisplayName("§aEnchantment Cost");
- enchantCostMeta.setLore(Collections.singletonList("§7Click here to open enchantment costs menu"));
+ enchantCostMeta.setDisplayName("\u00A7aEnchantment Cost");
+ enchantCostMeta.setLore(Collections.singletonList("\u00A77Click here to open enchantment costs menu"));
enchantCostItemstack.setItemMeta(enchantCostMeta);
GuiItem enchantCostItem = GuiGlobalItems.goToGuiItem(enchantCostItemstack, new EnchantCostConfigGui());
- pane.bindItem('4', enchantCostItem);
+ pane.bindItem('3', enchantCostItem);
// Enchantment Conflicts item
ItemStack enchantConflictItemstack = new ItemStack(Material.OAK_FENCE);
ItemMeta enchantConflictMeta = enchantConflictItemstack.getItemMeta();
assert enchantConflictMeta != null;
- enchantConflictMeta.setDisplayName("§aEnchantment Conflict");
- enchantConflictMeta.setLore(Collections.singletonList("§7Click here to open enchantment conflict menu"));
+ enchantConflictMeta.setDisplayName("\u00A7aEnchantment Conflict");
+ enchantConflictMeta.setLore(Collections.singletonList("\u00A77Click here to open enchantment conflict menu"));
enchantConflictItemstack.setItemMeta(enchantConflictMeta);
GuiItem enchantConflictItem = GuiGlobalItems.goToGuiItem(enchantConflictItemstack, EnchantConflictGui.getInstance());
- pane.bindItem('5', enchantConflictItem);
+ pane.bindItem('4', enchantConflictItem);
// Group config items
ItemStack groupItemstack = new ItemStack(Material.CHEST);
ItemMeta groupMeta = groupItemstack.getItemMeta();
assert groupMeta != null;
- groupMeta.setDisplayName("§aItem Groups");
- groupMeta.setLore(Collections.singletonList("§7Click here to open item group menu"));
+ groupMeta.setDisplayName("\u00A7aGroups");
+ groupMeta.setLore(Collections.singletonList("\u00A77Click here to open material group menu"));
groupItemstack.setItemMeta(groupMeta);
GuiItem groupConfigItem = GuiGlobalItems.goToGuiItem(groupItemstack, GroupConfigGui.getInstance());
- pane.bindItem('6', groupConfigItem);
+ pane.bindItem('5', groupConfigItem);
// Unit repair item
ItemStack unirRepairItemstack = new ItemStack(Material.DIAMOND);
ItemMeta unitRepairMeta = unirRepairItemstack.getItemMeta();
assert unitRepairMeta != null;
- unitRepairMeta.setDisplayName("§aUnit Repair");
- unitRepairMeta.setLore(Collections.singletonList("§7Click here to open anvil unit repair menu"));
+ unitRepairMeta.setDisplayName("\u00A7aUnit Repair");
+ unitRepairMeta.setLore(Collections.singletonList("\u00A77Click here to open anvil unit repair menu"));
unirRepairItemstack.setItemMeta(unitRepairMeta);
GuiItem unitRepairItem = GuiGlobalItems.goToGuiItem(unirRepairItemstack, UnitRepairConfigGui.getInstance());
- pane.bindItem('7', unitRepairItem);
+ pane.bindItem('6', unitRepairItem);
// Custom recipe item
ItemStack customRecipeItemstack = new ItemStack(Material.CRAFTING_TABLE);
ItemMeta customRecipeMeta = customRecipeItemstack.getItemMeta();
assert customRecipeMeta != null;
- customRecipeMeta.setDisplayName("§aCustom recipes");
- customRecipeMeta.setLore(Collections.singletonList("§7Click here to open anvil custom recipe menu"));
+ customRecipeMeta.setDisplayName("\u00A7aCustom recipes");
+ customRecipeMeta.setLore(Collections.singletonList("\u00A77Click here to open anvil custom recipe menu"));
customRecipeItemstack.setItemMeta(customRecipeMeta);
GuiItem customRecipeItem = GuiGlobalItems.goToGuiItem(customRecipeItemstack, CustomRecipeConfigGui.getInstance());
- pane.bindItem('8', customRecipeItem);
+ pane.bindItem('7', customRecipeItem);
// quit item
ItemStack quitItemstack = new ItemStack(Material.BARRIER);
ItemMeta quitMeta = quitItemstack.getItemMeta();
assert quitMeta != null;
- quitMeta.setDisplayName("§cQuit");
+ quitMeta.setDisplayName("\u00A7cQuit");
quitItemstack.setItemMeta(quitMeta);
GuiItem quitItem = new GuiItem(quitItemstack, event -> {
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectGroupContainer.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectGroupContainer.java
index 49f8b3b..c8668d0 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectGroupContainer.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectGroupContainer.java
@@ -19,12 +19,12 @@ public interface SelectGroupContainer {
static List getGroupLore(SelectGroupContainer container, String containerType, String groupAction){
// Prepare group lore
ArrayList groupLore = new ArrayList<>();
- groupLore.add("§7Allow you to select a list of §3Groups §7that this " + containerType + " should " + groupAction);
+ groupLore.add("\u00A77Allow you to select a list of \u00A73Groups \u00A77that this " + containerType + " should " + groupAction);
Set grouos = container.getSelectedGroups();
if (grouos.isEmpty()) {
- groupLore.add("§7There is no "+groupAction+"d group for this "+containerType+".");
+ groupLore.add("\u00A77There is no "+groupAction+"d group for this "+containerType+".");
} else {
- groupLore.add("§7List of "+groupAction+"d groups for this "+containerType+":");
+ groupLore.add("\u00A77List of "+groupAction+"d groups for this "+containerType+":");
Iterator groupIterator = grouos.iterator();
boolean greaterThanMax = grouos.size() > 5;
@@ -32,11 +32,11 @@ public interface SelectGroupContainer {
for (int i = 0; i < maxindex; i++) {
// format string like "- Melee Weapons"
String formattedName = CasedStringUtil.snakeToUpperSpacedCase(groupIterator.next().getName());
- groupLore.add("§7- §3" + formattedName);
+ groupLore.add("\u00A77- \u00A73" + formattedName);
}
if (greaterThanMax) {
- groupLore.add("§7And " + (grouos.size() - 4) + " more...");
+ groupLore.add("\u00A77And " + (grouos.size() - 4) + " more...");
}
}
return groupLore;
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectMaterialContainer.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectMaterialContainer.java
index 3756341..397030e 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectMaterialContainer.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectMaterialContainer.java
@@ -1,40 +1,39 @@
package xyz.alexcrea.cuanvil.gui.config;
import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import java.util.*;
public interface SelectMaterialContainer {
- Set getSelectedMaterials();
+ EnumSet getSelectedMaterials();
- boolean setSelectedMaterials(Set materials);
+ boolean setSelectedMaterials(EnumSet materials);
- Set illegalMaterials();
+ EnumSet illegalMaterials();
static List getMaterialLore(SelectMaterialContainer container, String containerType, String action){
// Prepare material lore
ArrayList groupLore = new ArrayList<>();
- groupLore.add("§7Allow you to select a list of §ematerials §7that this " + containerType + " should " + action);
- Set materialSet = container.getSelectedMaterials();
+ groupLore.add("\u00A77Allow you to select a list of \u00A7ematerials \u00A77that this " + containerType + " should " + action);
+ Set materialSet = container.getSelectedMaterials();
if (materialSet.isEmpty()) {
- groupLore.add("§7There is no "+action+"d material for this "+containerType+".");
+ groupLore.add("\u00A77There is no "+action+"d material for this "+containerType+".");
} else {
- groupLore.add("§7List of "+action+"d materials for this "+containerType+":");
- Iterator materialIterator = materialSet.iterator();
+ groupLore.add("\u00A77List of "+action+"d materials for this "+containerType+":");
+ Iterator materialIterator = materialSet.iterator();
boolean greaterThanMax = materialSet.size() > 5;
int maxindex = (greaterThanMax ? 4 : materialSet.size());
for (int i = 0; i < maxindex; i++) {
// format string like "- Stone Sword"
- String formattedName = CasedStringUtil.snakeToUpperSpacedCase(materialIterator.next().getKey().toLowerCase());
- groupLore.add("§7- §e" + formattedName);
+ String formattedName = CasedStringUtil.snakeToUpperSpacedCase(materialIterator.next().name().toLowerCase());
+ groupLore.add("\u00A77- \u00A7e" + formattedName);
}
if (greaterThanMax) {
- groupLore.add("§7And " + (materialSet.size() - 4) + " more...");
+ groupLore.add("\u00A77And " + (materialSet.size() - 4) + " more...");
}
}
return groupLore;
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/ask/ConfirmActionGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/ask/ConfirmActionGui.java
index 5839663..d306ff1 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/ask/ConfirmActionGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/ask/ConfirmActionGui.java
@@ -11,7 +11,6 @@ import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
-import xyz.alexcrea.cuanvil.util.MetricsUtil;
import java.util.Arrays;
import java.util.function.Supplier;
@@ -42,12 +41,11 @@ public class ConfirmActionGui extends AbstractAskGui {
success = onConfirm.get();
} catch (Exception e) {
CustomAnvil.instance.getLogger().log(Level.WARNING, "Could not process confirmation supplier.", e);
- MetricsUtil.INSTANCE.trackError(e);
success = false;
}
if (!success) {
- event.getWhoClicked().sendMessage("§cAction could not be completed. ");
+ event.getWhoClicked().sendMessage("\u00A7cAction could not be completed. ");
}
backOnConfirm.show(player);
@@ -57,7 +55,7 @@ public class ConfirmActionGui extends AbstractAskGui {
ItemStack infoItem = new ItemStack(Material.PAPER);
ItemMeta infoMeta = infoItem.getItemMeta();
- infoMeta.setDisplayName("§eAre you sure ?");
+ infoMeta.setDisplayName("\u00A7eAre you sure ?");
if(actionDescription != null){
infoMeta.setLore(Arrays.asList(actionDescription.split("\n")));
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/ask/SelectItemTypeGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/ask/SelectItemTypeGui.java
index 66411bd..eb15243 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/ask/SelectItemTypeGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/ask/SelectItemTypeGui.java
@@ -12,7 +12,6 @@ import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
-import xyz.alexcrea.cuanvil.util.MaterialUtil;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
@@ -53,7 +52,7 @@ public class SelectItemTypeGui extends AbstractAskGui {
event.setCancelled(true);
ItemStack cursor = event.getWhoClicked().getItemOnCursor();
- if(MaterialUtil.INSTANCE.isAir(cursor)) return;
+ if(cursor.getType().isAir()) return;
ItemStack finalItem;
if(materialOnly){
@@ -72,7 +71,7 @@ public class SelectItemTypeGui extends AbstractAskGui {
this.pane.bindItem('V', selectGuiItem.get());
// Temporary leave item
- GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(Material.YELLOW_STAINED_GLASS_PANE, this);
+ GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(Material.YELLOW_TERRACOTTA, this);
this.pane.bindItem('s', temporaryLeave);
@@ -81,7 +80,7 @@ public class SelectItemTypeGui extends AbstractAskGui {
private ItemStack setDisplayMeta(ItemStack item, String actionDescription){
ItemMeta meta = item.getItemMeta();
- meta.setDisplayName("§ePlace an item here");
+ meta.setDisplayName("\u00A7ePlace an item here");
meta.setLore(Arrays.asList(actionDescription.split("\n")));
item.setItemMeta(meta);
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/AbstractEnchantConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/AbstractEnchantConfigGui.java
index 6bd7ea3..f9e2903 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/AbstractEnchantConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/AbstractEnchantConfigGui.java
@@ -20,7 +20,7 @@ import java.util.function.Consumer;
*
* @param Type of the factory of the type of setting the gui should edit.
*/
-public abstract class AbstractEnchantConfigGui extends SettingGuiListConfigGui{
+public abstract class AbstractEnchantConfigGui extends SettingGuiListConfigGui implements ValueUpdatableGui {
/**
* Constructor for a gui displaying available enchantment to edit a enchantment setting.
@@ -44,11 +44,11 @@ public abstract class AbstractEnchantConfigGui lore = new ArrayList<>();
- lore.add("§7Whenever anvil cost is above §e39§7 should display the true price and not §cToo Expensive§7.");
- lore.add("§7However, when bypassing §cToo Expensive§7, anvil price will be displayed as §aGreen§7.");
- lore.add("§7Even if cost is displayed as §aGreen§7:");
- lore.add("§7If the player do not have the required xp level, the action will not be completable.");
+ lore.add("\u00A77Whenever anvil cost is above \u00A7e39\u00A77 should display the true price and not \u00A7cToo Expensive\u00A77.");
+ lore.add("\u00A77However, when bypassing \u00A7cToo Expensive\u00A77, anvil price will be displayed as \u00A7aGreen\u00A77.");
+ lore.add("\u00A77Even if cost is displayed as \u00A7aGreen\u00A77:");
+ lore.add("\u00A77If the player do not have the required xp level, the action will not be completable.");
- if(!this.packetManager.getCanSetInstantBuild()){
+ if(!this.packetManager.isProtocoLibInstalled()){
lore.add("");
- lore.add("§4/!\\§cCaution§4/!\\ §cYou need ProtocoLib installed and working or a paper server.");
- lore.add("§cCurrently ProtocoLib is not detected.");
+ lore.add("\u00A74/!\\\u00A7cCaution/!\\ \u00A7cYou need ProtocoLib installed for this to work.");
}
String[] loreAsArray = new String[lore.size()];
@@ -333,10 +330,6 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
GuiItem illegalCostItem = this.sacrificeIllegalEnchantCost.getItem(Material.ENCHANTED_BOOK);
pane.bindItem('S', illegalCostItem);
- // work penalty type
- GuiItem workPenaltyType = WorkPenaltyTypeSettingGui.getDisplayItem(this, Material.DAMAGED_ANVIL, "§aWork Penalty Type");
- pane.bindItem('W', workPenaltyType);
-
// allow color code
GuiItem allowColorCodeItem = this.allowColorCode.getItem();
pane.bindItem('c', allowColorCodeItem);
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/CustomRecipeConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/CustomRecipeConfigGui.java
index e21ad75..81bb259 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/CustomRecipeConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/CustomRecipeConfigGui.java
@@ -10,26 +10,25 @@ import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.gui.config.list.MappedGuiListConfigGui;
import xyz.alexcrea.cuanvil.gui.config.list.elements.CustomRecipeSubSettingGui;
-import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
import xyz.alexcrea.cuanvil.recipe.AnvilCustomRecipe;
import xyz.alexcrea.cuanvil.util.CasedStringUtil;
-import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
-public class CustomRecipeConfigGui extends MappedGuiListConfigGui> {
+public class CustomRecipeConfigGui extends MappedGuiListConfigGui {
+
private static CustomRecipeConfigGui INSTANCE = new CustomRecipeConfigGui();
@Nullable
- public static CustomRecipeConfigGui getCurrentInstance() {
+ public static CustomRecipeConfigGui getCurrentInstance(){
return INSTANCE;
}
@NotNull
- public static CustomRecipeConfigGui getInstance() {
- if (INSTANCE == null) INSTANCE = new CustomRecipeConfigGui();
+ public static CustomRecipeConfigGui getInstance(){
+ if(INSTANCE == null) INSTANCE = new CustomRecipeConfigGui();
return INSTANCE;
}
@@ -44,43 +43,36 @@ public class CustomRecipeConfigGui extends MappedGuiListConfigGui getRecipeLore(AnvilCustomRecipe recipe) {
boolean shouldWork = recipe.validate();
- ArrayList lore = new ArrayList<>();
- lore.add("§7Is valid: §" + (shouldWork ? "aYes" : "cNo"));
- lore.add("§7Exact count: §" + (recipe.getExactCount() ? "aYes" : "cNo"));
- lore.add("§7Recipe Level Cost: §e" + recipe.getLevelCostPerCraft());
- lore.add("§7Recipe Linear Xp Cost: §e" + recipe.getXpCostPerCraft());
- if (recipe.getXpCostPerCraft() != 0) {
- lore.add("§7Exact Linear xp remove: §" + (recipe.getRemoveExactLinearXp() ? "aYes" : "cNo"));
- }
- return lore;
+ meta.setLore(Arrays.asList(
+ "\u00A77Should work: \u00A7"+(shouldWork ? "aYes" : "cNo"),
+ "\u00A77Exact count: \u00A7"+(recipe.getExactCount() ? "aYes" : "cNo"),
+ "\u00A77Recipe Xp Cost: \u00A7e"+recipe.getXpCostPerCraft()
+
+ ));
+
+ displaydItem.setItemMeta(meta);
+ return displaydItem;
}
@Override
- protected LazyElement newInstanceOfGui(AnvilCustomRecipe generic, GuiItem item) {
- return new LazyElement<>(item, () -> new CustomRecipeSubSettingGui(this, generic));
+ protected CustomRecipeSubSettingGui newInstanceOfGui(AnvilCustomRecipe generic, GuiItem item) {
+ return new CustomRecipeSubSettingGui(this, generic, item);
}
@Override
@@ -94,11 +86,7 @@ public class CustomRecipeConfigGui extends MappedGuiListConfigGui> {
+public class EnchantConflictGui extends MappedGuiListConfigGui {
private static EnchantConflictGui INSTANCE;
@@ -75,11 +74,11 @@ public class EnchantConflictGui extends MappedGuiListConfigGui newInstanceOfGui(EnchantConflictGroup conflict, GuiItem item) {
- return new LazyElement<>(item, () -> new EnchantConflictSubSettingGui(this, conflict));
+ protected EnchantConflictSubSettingGui newInstanceOfGui(EnchantConflictGroup conflict, GuiItem item) {
+ return new EnchantConflictSubSettingGui(this, conflict, item);
}
@Override
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantCostConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantCostConfigGui.java
index a614536..b45a7b3 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantCostConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantCostConfigGui.java
@@ -36,7 +36,7 @@ public class EnchantCostConfigGui extends AbstractEnchantConfigGui lore = new ArrayList<>();
- lore.add("§7Item Cost: §e" + itemCost);
- lore.add("§7Book Cost: §e" + bookCost);
+ lore.add("\u00A77Item Cost: \u00A7e" + itemCost);
+ lore.add("\u00A77Book Cost: \u00A7e" + bookCost);
List displayLore = factory.getDisplayLore();
if(!displayLore.isEmpty()){
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantLimitConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantLimitConfigGui.java
index e9edbeb..9529495 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantLimitConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantLimitConfigGui.java
@@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem;
-import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material;
import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
@@ -17,7 +16,7 @@ import java.util.Locale;
*/
public class EnchantLimitConfigGui extends AbstractEnchantConfigGui {
- private static final String SECTION_NAME = ConfigOptions.ENCHANT_LIMIT_ROOT;
+ private static final String SECTION_NAME = "enchant_limits";
private static EnchantLimitConfigGui INSTANCE = null;
@@ -30,7 +29,7 @@ public class EnchantLimitConfigGui extends AbstractEnchantConfigGui "Default (" + defaultValue + ")";
- case RESET -> String.valueOf(defaultValue);
- default -> "Default";
- };
-
- }
- else return super.valueDisplayName(type, value);
- }
- };
+ 0, 255,
+ enchant.defaultMaxLevel(),
+ 1, 5, 10, 50, 100);
}
@Override
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantMergeLimitConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantMergeLimitConfigGui.java
deleted file mode 100644
index 0d391e7..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/EnchantMergeLimitConfigGui.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package xyz.alexcrea.cuanvil.gui.config.global;
-
-import com.github.stefvanschie.inventoryframework.gui.GuiItem;
-import io.delilaheve.util.ConfigOptions;
-import org.bukkit.Material;
-import org.jetbrains.annotations.Nullable;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
-import xyz.alexcrea.cuanvil.gui.config.settings.IntSettingsGui;
-import xyz.alexcrea.cuanvil.util.CasedStringUtil;
-
-import java.util.Arrays;
-import java.util.Locale;
-
-public class EnchantMergeLimitConfigGui extends AbstractEnchantConfigGui {
-
- private static final String SECTION_NAME = "disable-merge-over";
-
- private static EnchantMergeLimitConfigGui INSTANCE = null;
-
- @Nullable
- public static EnchantMergeLimitConfigGui getInstance() {
- return INSTANCE;
- }
-
- /**
- * Constructor of this Global gui for enchantment level limit settings.
- */
- public EnchantMergeLimitConfigGui() {
- super("§8Enchantment Maximum Merge Level");
- if(INSTANCE == null) INSTANCE = this;
-
- init();
- }
-
- @Override
- public IntSettingsGui.IntSettingFactory createFactory(CAEnchantment enchant) {
- String key = enchant.getKey().toString().toLowerCase(Locale.ROOT);
- String prettyKey = CasedStringUtil.snakeToUpperSpacedCase(key.replace(":", "_"));
-
- return new IntSettingsGui.IntSettingFactory(prettyKey + " Merge Limit", this,
- SECTION_NAME + '.' + key, ConfigHolder.DEFAULT_CONFIG,
- Arrays.asList(
- "§7Maximum merge level for for " + prettyKey,
- "",
- "§7For example, if set to §e2§7, §alvl1 §7+ §alvl1 §7of will give a §alvl2",
- "§7But §alvl2 §7+ §alvl2 §7will not give a §clv3§7.",
- "§7Will still not merge above max enchantment level",
- "§e-1 §7(default) will set the merge limit to enchantment's maximum level"
- ),
- -1, 255, -1,
- 1, 5, 10, 50, 100){
-
- @Override
- public int getConfiguredValue() {
- return ConfigOptions.INSTANCE.maxBeforeMergeDisabled(enchant);
- }
- };
- }
-
- @Override
- public GuiItem itemFromFactory(CAEnchantment enchantment, IntSettingsGui.IntSettingFactory inventoryFactory) {
- return inventoryFactory.getItem(
- Material.ENCHANTED_BOOK,
- inventoryFactory.getTitle());
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/GroupConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/GroupConfigGui.java
index 8e20751..80bbe8c 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/GroupConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/GroupConfigGui.java
@@ -15,13 +15,12 @@ import xyz.alexcrea.cuanvil.group.ItemGroupManager;
import xyz.alexcrea.cuanvil.gui.config.list.MappedGuiListConfigGui;
import xyz.alexcrea.cuanvil.gui.config.list.elements.GroupConfigSubSettingGui;
import xyz.alexcrea.cuanvil.util.CasedStringUtil;
-import xyz.alexcrea.cuanvil.util.LazyValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-public class GroupConfigGui extends MappedGuiListConfigGui> {
+public class GroupConfigGui extends MappedGuiListConfigGui {
private static GroupConfigGui INSTANCE;
@@ -50,12 +49,12 @@ public class GroupConfigGui extends MappedGuiListConfigGui newInstanceOfGui(IncludeGroup group, GuiItem item) {
- return new LazyElement<>(item, () -> new GroupConfigSubSettingGui(this, group));
+ protected GroupConfigSubSettingGui newInstanceOfGui(IncludeGroup group, GuiItem item) {
+ return new GroupConfigSubSettingGui(this, group, item);
}
@Override
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/UnitRepairConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/UnitRepairConfigGui.java
index 0e366ae..0c8819b 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/UnitRepairConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/UnitRepairConfigGui.java
@@ -18,8 +18,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-public class UnitRepairConfigGui extends
- MappedGuiListConfigGui> {
+public class UnitRepairConfigGui extends MappedGuiListConfigGui {
private static UnitRepairConfigGui INSTANCE;
@@ -42,12 +41,10 @@ public class UnitRepairConfigGui extends
}
@Override
- protected LazyElement newInstanceOfGui(Material material, GuiItem item) {
- return new LazyElement<>(item, () -> {
- UnitRepairElementListGui element = new UnitRepairElementListGui(material, this);
- element.init();
- return element;
- });
+ protected UnitRepairElementListGui newInstanceOfGui(Material material, GuiItem item) {
+ UnitRepairElementListGui element = new UnitRepairElementListGui(material, this, item);
+ element.init();
+ return element;
}
@Override
@@ -65,10 +62,10 @@ public class UnitRepairConfigGui extends
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§eRepaired by " +materialName);
+ meta.setDisplayName("\u00A7eRepaired by " +materialName);
meta.setLore(Arrays.asList(
- "§7There is currently §e" +reparableItemCount+ " §7reparable item with "+materialName,
- "§7Click here to open the menu to edit reparable item by " + materialName
+ "\u00A77There is currently \u00A7e" +reparableItemCount+ " \u00A77reparable item with "+materialName,
+ "\u00A77Click here to open the menu to edit reparable item by " + materialName
));
item.setItemMeta(meta);
@@ -96,10 +93,10 @@ public class UnitRepairConfigGui extends
ItemMeta createMeta = createItem.getItemMeta();
assert createMeta != null;
- createMeta.setDisplayName("§aSelect a new unit material");
+ createMeta.setDisplayName("\u00A7aSelect a new unit material");
createMeta.setLore(Arrays.asList(
- "§7Select a new unit material to be used.",
- "§7You will be asked the material to use."
+ "\u00A77Select a new unit material to be used.",
+ "\u00A77You will be asked the material to use."
));
createItem.setItemMeta(createMeta);
@@ -109,8 +106,8 @@ public class UnitRepairConfigGui extends
new SelectItemTypeGui(
"Select unit repair item.",
- "§7Click here with an item to set the item\n" +
- "§7You like to be an unit repair item",
+ "\u00A77Click here with an item to set the item\n" +
+ "\u00A77You like to be an unit repair item",
this,
(itemStack, player) -> {
Material type = itemStack.getType();
@@ -118,7 +115,7 @@ public class UnitRepairConfigGui extends
updateValueForGeneric(type, true);
// Display material edit setting
- this.elementGuiMap.get(type).get().getMappedGui().show(player);
+ this.elementGuiMap.get(type).getMappedGui().show(player);
},
true
).show(clickEvent.getWhoClicked());
@@ -126,8 +123,8 @@ public class UnitRepairConfigGui extends
}
@NotNull
- public LazyElement getInstanceOrCreate(Material mat){
- LazyElement element = this.elementGuiMap.get(mat);
+ public UnitRepairElementListGui getInstanceOrCreate(Material mat){
+ UnitRepairElementListGui element = this.elementGuiMap.get(mat);
if(element == null){
updateValueForGeneric(mat, false);
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/ElementListConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/ElementListConfigGui.java
index f3cc0b4..8e7d189 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/ElementListConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/ElementListConfigGui.java
@@ -16,6 +16,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
+import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
@@ -30,29 +31,24 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
protected PatternPane backgroundPane;
- public static final int LIST_FILLER_START_X = 1;
- public static final int LIST_FILLER_START_Y = 1;
- public static final int LIST_FILLER_LENGTH = 7;
- public static final int LIST_FILLER_HEIGHT = 4;
-
- protected ElementListConfigGui(@NotNull String title, Gui parent) {
+ protected ElementListConfigGui(@NotNull String title) {
super(6, title, CustomAnvil.instance);
this.namePrefix = title;
// Back item panel
Pattern pattern = getBackgroundPattern();
this.backgroundPane = new PatternPane(0, 0, 9, 6, Pane.Priority.LOW, pattern);
- GuiGlobalItems.addBackItem(this.backgroundPane, parent);
+ GuiGlobalItems.addBackItem(this.backgroundPane, MainConfigGui.getInstance());
}
protected Pattern getBackgroundPattern(){
return new Pattern(
- GuiSharedConstant.UPPER_FILLER_FULL_PLANE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
"B11L1R11C"
);
}
@@ -83,7 +79,7 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
protected void prepareStaticValues(){
// Left item creation for consumer & bind
- this.goLeftItem = new GuiItem(new ItemStack(Material.RED_STAINED_GLASS_PANE), event -> {
+ this.goLeftItem = new GuiItem(new ItemStack(Material.RED_TERRACOTTA), event -> {
HumanEntity viewer = event.getWhoClicked();
UUID playerUUID = viewer.getUniqueId();
int page = this.pageMap.getOrDefault(playerUUID, 0);
@@ -98,7 +94,7 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
}, CustomAnvil.instance);
// Right item creation for consumer & bind
- this.goRightItem = new GuiItem(new ItemStack(Material.LIME_STAINED_GLASS_PANE), event -> {
+ this.goRightItem = new GuiItem(new ItemStack(Material.GREEN_TERRACOTTA), event -> {
HumanEntity viewer = event.getWhoClicked();
UUID playerUUID = viewer.getUniqueId();
int page = pageMap.getOrDefault(playerUUID, 0);
@@ -132,7 +128,7 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
protected abstract GuiItem prepareCreateNewItem();
protected OutlinePane createEmptyPage() {
- OutlinePane page = new OutlinePane(LIST_FILLER_START_X, LIST_FILLER_START_Y, LIST_FILLER_LENGTH, LIST_FILLER_HEIGHT);
+ OutlinePane page = new OutlinePane(0, 0, 9, 5);
page.align(OutlinePane.Alignment.BEGIN);
page.setOrientation(Orientable.Orientation.HORIZONTAL);
@@ -150,7 +146,7 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
protected void addToPage(GuiItem guiItem) {
// Get first available page or create one
OutlinePane page = this.pages.get(this.pages.size() - 1);
- if (page.getItems().size() >= LIST_FILLER_LENGTH * LIST_FILLER_HEIGHT) {
+ if (page.getItems().size() >= 5 * 9) {
page = createEmptyPage();
this.pages.add(page);
}
@@ -203,7 +199,7 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
ItemStack leftItem = this.goLeftItem.getItem();
ItemMeta leftMeta = leftItem.getItemMeta();
- leftMeta.setDisplayName("§eReturn to page " + (page));
+ leftMeta.setDisplayName("\u00A7eReturn to page " + (page));
leftItem.setItemMeta(leftMeta);
this.goLeftItem.setItem(leftItem);
@@ -220,7 +216,7 @@ public abstract class ElementListConfigGui< T > extends ChestGui implements Valu
ItemStack rightItem = this.goRightItem.getItem();
ItemMeta rightMeta = rightItem.getItemMeta();
- rightMeta.setDisplayName("§eGo to page " + (page + 2));
+ rightMeta.setDisplayName("\u00A7eGo to page " + (page + 2));
rightItem.setItemMeta(rightMeta);
this.goRightItem.setItem(rightItem);
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedElementListConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedElementListConfigGui.java
index 31ab718..f2793a8 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedElementListConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedElementListConfigGui.java
@@ -7,7 +7,6 @@ import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
-import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
import java.util.Arrays;
@@ -18,7 +17,7 @@ public abstract class MappedElementListConfigGui< T, S > extends ElementListConf
protected final HashMap elementGuiMap;
protected MappedElementListConfigGui(@NotNull String title) {
- super(title, MainConfigGui.getInstance());
+ super(title);
this.elementGuiMap = new HashMap<>();
}
@@ -30,11 +29,11 @@ public abstract class MappedElementListConfigGui< T, S > extends ElementListConf
ItemMeta createMeta = createItem.getItemMeta();
assert createMeta != null;
- createMeta.setDisplayName("§aCreate new "+genericDisplayedName());
+ createMeta.setDisplayName("\u00A7aCreate new "+genericDisplayedName());
createMeta.setLore(Arrays.asList(
- "§7Create a new "+genericDisplayedName()+".",
- "§7You will be asked to name the "+genericDisplayedName()+" in chat.",
- "§7Then, you should edit the "+genericDisplayedName()+" config as you need"
+ "\u00A77Create a new "+genericDisplayedName()+".",
+ "\u00A77You will be asked to name the "+genericDisplayedName()+" in chat.",
+ "\u00A77Then, you should edit the "+genericDisplayedName()+" config as you need"
));
createItem.setItemMeta(createMeta);
@@ -51,8 +50,8 @@ public abstract class MappedElementListConfigGui< T, S > extends ElementListConf
}
player.closeInventory();
- player.sendMessage("§eWrite the "+genericDisplayedName()+" name you want to create in the chat.\n" +
- "§eOr write §ccancel §eto go back to "+genericDisplayedName()+" config menu");
+ player.sendMessage("\u00A7eWrite the "+genericDisplayedName()+" name you want to create in the chat.\n" +
+ "\u00A7eOr write \u00A7ccancel \u00A7eto go back to "+genericDisplayedName()+" config menu");
CustomAnvil.Companion.getChatListener().setListenedCallback(player, prepareCreateItemConsumer(player));
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedGuiListConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedGuiListConfigGui.java
index 3aa18e0..9c73760 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedGuiListConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedGuiListConfigGui.java
@@ -3,19 +3,15 @@ package xyz.alexcrea.cuanvil.gui.config.list;
import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import io.delilaheve.CustomAnvil;
import org.bukkit.entity.HumanEntity;
-import org.bukkit.event.inventory.InventoryClickEvent;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.gui.config.list.elements.ElementMappedToListGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
-import xyz.alexcrea.cuanvil.util.LazyValue;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
-import java.util.function.Supplier;
-public abstract class MappedGuiListConfigGui< T, S extends MappedGuiListConfigGui.LazyElement>>
- extends MappedElementListConfigGui< T, S > {
+public abstract class MappedGuiListConfigGui< T, S extends ElementMappedToListGui> extends MappedElementListConfigGui< T, S > {
protected MappedGuiListConfigGui(@NotNull String title) {
super(title);
@@ -24,10 +20,7 @@ public abstract class MappedGuiListConfigGui< T, S extends MappedGuiListConfigGu
@Override
public void reloadValues() {
- this.elementGuiMap.forEach((conflict, element) -> {
- ElementMappedToListGui gui = element.getStored();
- if(gui != null) gui.cleanAndBeUnusable();
- });
+ this.elementGuiMap.forEach((conflict, gui) -> gui.cleanAndBeUnusable());
this.elementGuiMap.clear();
super.reloadValues();
@@ -37,24 +30,23 @@ public abstract class MappedGuiListConfigGui< T, S extends MappedGuiListConfigGu
protected S newElementRequested(T generic, GuiItem newItem) {
S element = newInstanceOfGui(generic, newItem);
- newItem.setAction(element.openAction());
+ newItem.setAction(GuiGlobalActions.openGuiAction(element.getMappedGui()));
return element;
}
@Override
protected GuiItem findItemFromElement(T generic, S element) {
- return element.getParentItem();
+ return element.getParentItemForThisGui();
}
@Override
protected void updateElement(T generic, S element) {
- ElementMappedToListGui gui = element.getStored();
- if(gui != null) gui.updateLocal();
+ element.updateLocal();
}
@Override
protected GuiItem findGuiItemForRemoval(T generic, S element) {
- return element.getParentItem();
+ return element.getParentItemForThisGui();
}
@Override
@@ -82,7 +74,7 @@ public abstract class MappedGuiListConfigGui< T, S extends MappedGuiListConfigGu
// Not the most efficient on large number of conflict, but it should not run often.
for (T generic : getEveryDisplayableInstanceOfGeneric()) {
if (generic.toString().equalsIgnoreCase(message)) {
- player.sendMessage("§cPlease enter a "+genericDisplayedName()+" name that do not already exist...");
+ player.sendMessage("\u00A7cPlease enter a "+genericDisplayedName()+" name that do not already exist...");
// wait next message.
CustomAnvil.Companion.getChatListener().setListenedCallback(player, selfRef.get());
return;
@@ -98,7 +90,7 @@ public abstract class MappedGuiListConfigGui< T, S extends MappedGuiListConfigGu
updateValueForGeneric(generic, true);
// show the new conflict config to the player
- this.elementGuiMap.get(generic).get().getMappedGui().show(player);
+ this.elementGuiMap.get(generic).getMappedGui().show(player);
update();
};
@@ -113,28 +105,4 @@ public abstract class MappedGuiListConfigGui< T, S extends MappedGuiListConfigGu
protected abstract T createAndSaveNewEmptyGeneric(String name);
- public static class LazyElement extends LazyValue {
-
- private final GuiItem parentItem;
- private final LazyValue> lazyOpenConsumer;
- public LazyElement(GuiItem parentItem, Supplier valueSupplier) {
- super(valueSupplier);
- this.parentItem = parentItem;
-
- this.lazyOpenConsumer = new LazyValue<>(() ->
- GuiGlobalActions.openGuiAction(this.get().getMappedGui()))
- ;
- }
-
- public GuiItem getParentItem() {
- return parentItem;
- }
-
- @NotNull
- public Consumer openAction(){
- return event -> lazyOpenConsumer.get().accept(event);
- }
-
- }
-
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/SettingGuiListConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/SettingGuiListConfigGui.java
index f0e7cb0..808b40d 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/SettingGuiListConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/SettingGuiListConfigGui.java
@@ -1,14 +1,12 @@
package xyz.alexcrea.cuanvil.gui.config.list;
import com.github.stefvanschie.inventoryframework.gui.GuiItem;
-import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
-import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
import xyz.alexcrea.cuanvil.gui.config.settings.SettingGui;
import java.util.HashMap;
@@ -19,16 +17,12 @@ public abstract class SettingGuiListConfigGui< T, S extends SettingGui.SettingGu
protected HashMap guiItemMap;
protected HashMap factoryMap;
- protected SettingGuiListConfigGui(@NotNull String title, Gui parent) {
- super(title, parent);
+ protected SettingGuiListConfigGui(@NotNull String title) {
+ super(title);
this.guiItemMap = new HashMap<>();
this.factoryMap = new HashMap<>();
}
- protected SettingGuiListConfigGui(@NotNull String title) {
- this(title, MainConfigGui.getInstance());
- }
-
@Override
protected GuiItem prepareCreateNewItem() {
ItemStack createItem = new ItemStack(Material.PAPER);
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/UnitRepairElementListGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/UnitRepairElementListGui.java
index 35f8ebb..ed38078 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/UnitRepairElementListGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/UnitRepairElementListGui.java
@@ -26,14 +26,17 @@ import java.util.function.Consumer;
public class UnitRepairElementListGui extends SettingGuiListConfigGui implements ElementMappedToListGui {
+ private final GuiItem parentItem;
private final Material parentMaterial;
private final UnitRepairConfigGui parentGui;
private final String materialName;
private boolean shouldWork = true;
public UnitRepairElementListGui(@NotNull Material parentMaterial,
- @NotNull UnitRepairConfigGui parentGui) {
- super("§e" + CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase()) + " §rUnit repair");
+ @NotNull UnitRepairConfigGui parentGui,
+ @NotNull GuiItem parentItem) {
+ super("\u00A7e" + CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase()) + " \u00A7rUnit repair");
+ this.parentItem = parentItem;
this.parentMaterial = parentMaterial;
this.parentGui = parentGui;
this.materialName = CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase());
@@ -45,8 +48,8 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui getCreateItemLore() {
return Arrays.asList(
- "§7Select a new item to be repairable.",
- "§7You will be asked the material to use."
+ "\u00A77Select a new item to be repairable.",
+ "\u00A77You will be asked the material to use."
);
}
@@ -61,19 +64,19 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui {
ItemMeta meta = itemStack.getItemMeta();
Material type = itemStack.getType();
if(!(meta instanceof Damageable) || (type.getMaxDurability() <= 0)) {
- player.sendMessage("§cThis item can't be damaged, so it can't be repaired.");
+ player.sendMessage("\u00A7cThis item can't be damaged, so it can't be repaired.");
return;
}
if(type == this.parentMaterial){
- player.sendMessage("§cItem can't repair something of the same type.");
+ player.sendMessage("\u00A7cItem can't repair something of the same type.");
return;
}
@@ -102,21 +105,21 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui {
event.setCancelled(true);
EnchantSelectSettingGui enchantGui = new EnchantSelectSettingGui(
- "§e" + CasedStringUtil.snakeToUpperSpacedCase(enchantConflict.toString()) + "§5",
+ "\u00A7e" + CasedStringUtil.snakeToUpperSpacedCase(enchantConflict.toString()) + "\u00A75",
this, this);
enchantGui.show(event.getWhoClicked());
}, CustomAnvil.instance);
@@ -89,17 +90,17 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
this.groupSettingItem = new GuiItem(new ItemStack(Material.PAPER), event -> {
event.setCancelled(true);
GroupSelectSettingGui enchantGui = new GroupSelectSettingGui(
- "§e" + CasedStringUtil.snakeToUpperSpacedCase(this.enchantConflict.toString()) + " §3Groups",
+ "\u00A7e" + CasedStringUtil.snakeToUpperSpacedCase(this.enchantConflict.toString()) + " \u00A73Groups",
this, this, 0);
enchantGui.show(event.getWhoClicked());
}, CustomAnvil.instance);
- this.minBeforeActiveSettingFactory = new IntSettingsGui.IntSettingFactory(
- "§8Minimum enchantment count",
+ this.minBeforeActiveSettingFactory = IntSettingsGui.intFactory(
+ "\u00A78Minimum enchantment count",
this, this.enchantConflict + ".maxEnchantmentBeforeConflict", ConfigHolder.CONFLICT_HOLDER,
Arrays.asList(
- "§7Minimum enchantment count set to X mean only X enchantment can be put",
- "§7on an item before the conflict is active."
+ "\u00A77Minimum enchantment count set to X mean only X enchantment can be put",
+ "\u00A77on an item before the conflict is active."
),
0, 255, 0, 1
);
@@ -137,8 +138,8 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
return success;
};
- return new ConfirmActionGui("§cDelete §e" + CasedStringUtil.snakeToUpperSpacedCase(this.enchantConflict.toString()) + "§c?",
- "§7Confirm that you want to delete this conflict.",
+ return new ConfirmActionGui("\u00A7cDelete \u00A7e" + CasedStringUtil.snakeToUpperSpacedCase(this.enchantConflict.toString()) + "\u00A7c?",
+ "\u00A77Confirm that you want to delete this conflict.",
this, this.parent, deleteSupplier
);
}
@@ -159,12 +160,12 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
// Prepare enchantment lore
ArrayList enchantLore = new ArrayList<>();
- enchantLore.add("§7Allow you to select a list of §5Enchantments §7that this conflict should include");
+ enchantLore.add("\u00A77Allow you to select a list of \u00A75Enchantments \u00A77that this conflict should include");
Set enchants = getSelectedEnchantments();
if (enchants.isEmpty()) {
- enchantLore.add("§7There is no included enchantment for this conflict.");
+ enchantLore.add("\u00A77There is no included enchantment for this conflict.");
} else {
- enchantLore.add("§7List of included enchantment for this conflict:");
+ enchantLore.add("\u00A77List of included enchantment for this conflict:");
Iterator enchantIterator = enchants.iterator();
boolean greaterThanMax = enchants.size() > 5;
@@ -172,10 +173,10 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
for (int i = 0; i < maxindex; i++) {
// format string like "- Fire Protection"
String formattedName = CasedStringUtil.snakeToUpperSpacedCase(enchantIterator.next().getKey().getKey());
- enchantLore.add("§7- §5" + formattedName);
+ enchantLore.add("\u00A77- \u00A75" + formattedName);
}
if (greaterThanMax) {
- enchantLore.add("§7And " + (enchants.size() - 4) + " more...");
+ enchantLore.add("\u00A77And " + (enchants.size() - 4) + " more...");
}
}
@@ -188,7 +189,7 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
ItemMeta enchantMeta = enchantItem.getItemMeta();
assert enchantMeta != null;
- enchantMeta.setDisplayName("§aSelect included §5Enchantments §aSettings");
+ enchantMeta.setDisplayName("\u00A7aSelect included \u00A75Enchantments \u00A7aSettings");
enchantMeta.setLore(enchantLore);
enchantItem.setItemMeta(enchantMeta);
@@ -200,7 +201,7 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
ItemMeta groupMeta = groupItem.getItemMeta();
assert groupMeta != null;
- groupMeta.setDisplayName("§aSelect Excluded §3Groups §aSettings");
+ groupMeta.setDisplayName("\u00A7aSelect Excluded \u00A73Groups \u00A7aSettings");
groupMeta.setLore(groupLore);
groupItem.setItemMeta(groupMeta);
@@ -257,7 +258,7 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
String[] enchantKeys = new String[enchantments.size()];
int index = 0;
for (CAEnchantment enchantment : enchantments) {
- enchantKeys[index++] = enchantment.getKey().toString();
+ enchantKeys[index++] = enchantment.getKey().getKey();
}
ConfigHolder.CONFLICT_HOLDER.getConfig().set(enchantConflict + ".enchantments", enchantKeys);
@@ -265,7 +266,6 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
updateGuiValues();
} catch (Exception e) {
CustomAnvil.instance.getLogger().log(Level.WARNING, "An error occurred while updating enchants for " + this.enchantConflict, e);
- MetricsUtil.INSTANCE.trackError(e);
}
// Save file configuration to disk
@@ -310,7 +310,6 @@ public class EnchantConflictSubSettingGui extends MappedToListSubSettingGui impl
updateGuiValues();
} catch (Exception e) {
CustomAnvil.instance.getLogger().log(Level.WARNING, "An error occurred while updating group for " + this.enchantConflict, e);
- MetricsUtil.INSTANCE.trackError(e);
}
// Save file configuration to disk
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/elements/GroupConfigSubSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/elements/GroupConfigSubSettingGui.java
index 3d05674..bcf66db 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/elements/GroupConfigSubSettingGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/elements/GroupConfigSubSettingGui.java
@@ -5,7 +5,6 @@ import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag;
@@ -38,9 +37,10 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
public GroupConfigSubSettingGui(
@NotNull GroupConfigGui parent,
- @NotNull IncludeGroup group) {
- super(3,
- "§e" + CasedStringUtil.snakeToUpperSpacedCase(group.getName()) + " §rConfig");
+ @NotNull IncludeGroup group,
+ @NotNull GuiItem item) {
+ super(item, 3,
+ CasedStringUtil.snakeToUpperSpacedCase(group.getName()) + " Config");
this.parent = parent;
this.group = group;
@@ -65,38 +65,27 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
ItemStack deleteItem = new ItemStack(Material.RED_TERRACOTTA);
ItemMeta deleteMeta = deleteItem.getItemMeta();
- deleteMeta.setDisplayName("§4DELETE GROUP");
- deleteMeta.setLore(Collections.singletonList("§cCaution with this button !"));
+ deleteMeta.setDisplayName("\u00A74DELETE GROUP");
+ deleteMeta.setLore(Collections.singletonList("\u00A7cCaution with this button !"));
deleteItem.setItemMeta(deleteMeta);
this.pane.bindItem('D', new GuiItem(deleteItem, openGuiAndCheckAction(), CustomAnvil.instance));
// Displayed item will be updated later
- String materialSelectionName = "§e" + CasedStringUtil.snakeToUpperSpacedCase(group.getName()) + " §rMaterials";
- ItemStack selectItem = new ItemStack(Material.DIAMOND_SWORD);
- ItemMeta selectItemMeta = selectItem.getItemMeta();
- selectItemMeta.setDisplayName(materialSelectionName);
-
- selectItem.setItemMeta(selectItemMeta);
- this.materialSelection = new GuiItem(selectItem, (event) -> {
+ this.materialSelection = new GuiItem(new ItemStack(Material.DIAMOND_SWORD), (event) -> {
event.setCancelled(true);
+
MaterialSelectSettingGui selectGui = new MaterialSelectSettingGui(this,
- materialSelectionName
+ CasedStringUtil.snakeToUpperSpacedCase(group.getName()) + " Materials"
, this);
selectGui.show(event.getWhoClicked());
}, CustomAnvil.instance);
- String selectGroupName = "§e" + CasedStringUtil.snakeToUpperSpacedCase(this.group.getName()) + " §rGroups";
- ItemStack selectGroup = new ItemStack(Material.CHEST);
- ItemMeta selectGroupMeta = selectGroup.getItemMeta();
- selectGroupMeta.setDisplayName(selectGroupName);
-
- selectGroup.setItemMeta(selectGroupMeta);
- this.groupSelection = new GuiItem(selectGroup, (event) -> {
+ this.groupSelection = new GuiItem(new ItemStack(Material.CHEST), (event) -> {
event.setCancelled(true);
GroupSelectSettingGui enchantGui = new GroupSelectSettingGui(
- selectGroupName,
+ CasedStringUtil.snakeToUpperSpacedCase(this.group.getName()) + " Groups",
this, this, 0);
enchantGui.show(event.getWhoClicked());
}, CustomAnvil.instance);
@@ -151,8 +140,8 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
return success;
};
- return new ConfirmActionGui("§cDelete §e" + CasedStringUtil.snakeToUpperSpacedCase(this.group.toString()) + "§c?",
- "§7Confirm that you want to delete this group.",
+ return new ConfirmActionGui("\u00A7cDelete \u00A7e" + CasedStringUtil.snakeToUpperSpacedCase(this.group.toString()) + "\u00A7c?",
+ "\u00A77Confirm that you want to delete this group.",
this, this.parent, deleteSupplier
);
}
@@ -162,8 +151,8 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
if(usedLoc.isEmpty()){
return false;
}
- StringBuilder stb = new StringBuilder("§cCan't delete group " +this.group.getName()+
- "\n§eUsed by:");
+ StringBuilder stb = new StringBuilder("\u00A7cCan't delete group " +this.group.getName()+
+ "\n\u00A7eUsed by:");
int maxIndex = usedLoc.size();
int nbMore = 0;
if(maxIndex > 10){
@@ -171,10 +160,10 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
maxIndex = 9;
}
for (int i = 0; i < maxIndex; i++) {
- stb.append("\n§r-§e ").append(usedLoc.get(i));
+ stb.append("\n\u00A7r-\u00A7e ").append(usedLoc.get(i));
}
if(nbMore > 0){
- stb.append("§cAnd ").append(nbMore).append(" More...");
+ stb.append("\u00A7cAnd ").append(nbMore).append(" More...");
}
player.sendMessage(stb.toString());
@@ -225,7 +214,7 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
ItemStack matSelectItem = this.materialSelection.getItem();
ItemMeta matSelectMeta = matSelectItem.getItemMeta();
- matSelectMeta.setDisplayName("§aSelect included §eMaterials §aSettings");
+ matSelectMeta.setDisplayName("\u00A7aSelect included \u00A7eMaterials \u00A7aSettings");
matSelectMeta.setLore(matLore);
matSelectMeta.addItemFlags(ItemFlag.values());
@@ -237,7 +226,7 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
ItemStack groupSelectItem = this.groupSelection.getItem();
ItemMeta groupSelectMeta = groupSelectItem.getItemMeta();
- groupSelectMeta.setDisplayName("§aSelect included §3Groups §aSettings");
+ groupSelectMeta.setDisplayName("\u00A7aSelect included \u00A73Groups \u00A7aSettings");
groupSelectMeta.setLore(groupLore);
groupSelectItem.setItemMeta(groupSelectMeta);
@@ -322,23 +311,23 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
// ----------------------------
// End of SelectGroupContainer related methods
// ----------------------------
- // SelectMaterialContainer related methods
+ // SelectGroupContainer related methods
// ----------------------------
@Override
- public Set getSelectedMaterials() {
+ public EnumSet getSelectedMaterials() {
return this.group.getNonGroupInheritedMaterials();
}
@Override
- public boolean setSelectedMaterials(Set materials) {
+ public boolean setSelectedMaterials(EnumSet materials) {
this.group.setNonGroupInheritedMaterials(materials);
// Write to file configuration
String[] groupNames = new String[materials.size()];
int index = 0;
- for (NamespacedKey otherGroup : materials) {
- groupNames[index++] = otherGroup.getKey().toLowerCase();
+ for (Material otherGroup : materials) {
+ groupNames[index++] = otherGroup.name().toLowerCase();
}
ConfigHolder.ITEM_GROUP_HOLDER.getConfig().set(this.group.getName()+"."+ItemGroupManager.MATERIAL_LIST_PATH, groupNames);
@@ -354,12 +343,12 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
}
@Override
- public Set illegalMaterials() {
- return Set.of(Material.AIR.getKey());
+ public EnumSet illegalMaterials() {
+ return EnumSet.of(Material.AIR);
}
// ----------------------------
- // End of SelectMaterialContainer related methods
+ // End of SelectGroupContainer related methods
// ----------------------------
private void updateDirectReferencingGroups(AbstractMaterialGroup referenceTo){
@@ -382,7 +371,7 @@ public class GroupConfigSubSettingGui extends MappedToListSubSettingGui implemen
for (AbstractMaterialGroup otherGroup : everyStoredGroups) {
if(otherGroup.getGroups().contains(testGroup)){
otherGroup.updateMaterials();
- updateFuture.add(otherGroup);
+ toUpdate.add(otherGroup);
}
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/elements/MappedToListSubSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/elements/MappedToListSubSettingGui.java
index 1d86781..020e6ed 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/elements/MappedToListSubSettingGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/elements/MappedToListSubSettingGui.java
@@ -9,10 +9,18 @@ import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
public abstract class MappedToListSubSettingGui extends ChestGui implements ValueUpdatableGui, ElementMappedToListGui {
+ private final GuiItem item;
protected MappedToListSubSettingGui(
+ GuiItem item,
int rows,
@NotNull String title) {
super(rows, title, CustomAnvil.instance);
+ this.item = item;
+ }
+
+ @Override
+ public GuiItem getParentItemForThisGui() {
+ return item;
}
@Override
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/AbstractSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/AbstractSettingGui.java
index b07e7c1..c9ce78e 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/AbstractSettingGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/AbstractSettingGui.java
@@ -17,7 +17,7 @@ import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
*/
public abstract class AbstractSettingGui extends ChestGui implements SettingGui {
- public static final String CLICK_LORE = "§7Click Here to change the value";
+ protected static final String CLICK_LORE = "\u00A77Click Here to change the value";
private PatternPane pane;
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/BoolSettingsGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/BoolSettingsGui.java
index 1d5e73d..bb058c6 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/BoolSettingsGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/BoolSettingsGui.java
@@ -66,9 +66,9 @@ public class BoolSettingsGui extends AbstractSettingGui {
// Prepare default Value text
String defaultValueLore;
if(holder.defaultVal){
- defaultValueLore = "§aYes §7Is the default value";
+ defaultValueLore = "\u00A7aYes \u00A77Is the default value";
}else{
- defaultValueLore = "§cNo §7Is the default value";
+ defaultValueLore = "\u00A7cNo \u00A77Is the default value";
}
// Create reset to default item
@@ -76,7 +76,7 @@ public class BoolSettingsGui extends AbstractSettingGui {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§eReset to default value");
+ meta.setDisplayName("\u00A7eReset to default value");
meta.setLore(Collections.singletonList(defaultValueLore));
item.setItemMeta(meta);
returnToDefault = new GuiItem(item, event -> {
@@ -97,10 +97,10 @@ public class BoolSettingsGui extends AbstractSettingGui {
String displayedName;
Material displayedMat;
if (now) {
- displayedName = "§aYes";
+ displayedName = "\u00A7aYes";
displayedMat = Material.GREEN_TERRACOTTA;
} else {
- displayedName = "§cNo";
+ displayedName = "\u00A7cNo";
displayedMat = Material.RED_TERRACOTTA;
}
@@ -161,6 +161,28 @@ public class BoolSettingsGui extends AbstractSettingGui {
return now != before;
}
+ /**
+ * Create a bool setting factory from setting's parameters.
+ *
+ * @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 defaultVal Default value if not found on the config.
+ * @param displayLore Gui display item lore.
+ * @return A factory for a boolean setting gui.
+ */
+ public static BoolSettingFactory boolFactory(@NotNull String title, @NotNull ValueUpdatableGui parent,
+ @NotNull ConfigHolder config,
+ @NotNull String configPath, boolean defaultVal,
+ String... displayLore) {
+ return new BoolSettingFactory(
+ title, parent,
+ config,
+ configPath, defaultVal,
+ displayLore);
+ }
+
/**
* A factory for a boolean setting gui that hold setting's information.
*/
@@ -184,7 +206,7 @@ public class BoolSettingsGui extends AbstractSettingGui {
* @param defaultVal Default value if not found on the config.
* @param displayLore Gui display item lore.
*/
- public BoolSettingFactory(
+ protected BoolSettingFactory(
@NotNull String title, @NotNull ValueUpdatableGui parent,
@NotNull ConfigHolder config, @NotNull String configPath,
boolean defaultVal, String... displayLore) {
@@ -232,14 +254,14 @@ public class BoolSettingsGui extends AbstractSettingGui {
boolean value = getConfiguredValue();
Material itemMat;
- StringBuilder itemName = new StringBuilder("§e");
+ StringBuilder itemName = new StringBuilder("\u00A7e");
String finalValue;
if (value) {
itemMat = Material.GREEN_TERRACOTTA;
- finalValue = "§aYes";
+ finalValue = "\u00A7aYes";
} else {
itemMat = Material.RED_TERRACOTTA;
- finalValue = "§cNo";
+ finalValue = "\u00A7cNo";
}
itemName.append(name);
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/DoubleSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/DoubleSettingGui.java
index c0dcff6..6ff7469 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/DoubleSettingGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/DoubleSettingGui.java
@@ -68,9 +68,9 @@ public class DoubleSettingGui extends AbstractSettingGui {
ItemMeta meta = DELETE_ITEM_STACK.getItemMeta();
assert meta != null;
- meta.setDisplayName("§cDisable item being repaired ?");
- meta.setLore(Arrays.asList("§7Confirm disabling unit repair for this item..",
- "§4Cation: This action can't be canceled."));
+ meta.setDisplayName("\u00A7cDisable item being repaired ?");
+ meta.setLore(Arrays.asList("\u00A77Confirm disabling unit repair for this item..",
+ "\u00A74Cation: This action can't be canceled."));
DELETE_ITEM_STACK.setItemMeta(meta);
}
@@ -121,8 +121,8 @@ public class DoubleSettingGui extends AbstractSettingGui {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§eReset to default value");
- meta.setLore(Collections.singletonList("§7Default value is §e" + displayValue(holder.defaultVal)));
+ meta.setDisplayName("\u00A7eReset to default value");
+ meta.setLore(Collections.singletonList("\u00A77Default value is \u00A7e" + displayValue(holder.defaultVal)));
item.setItemMeta(meta);
returnToDefault = new GuiItem(item, event -> {
event.setCancelled(true);
@@ -144,7 +144,7 @@ public class DoubleSettingGui extends AbstractSettingGui {
if (now.compareTo(holder.min) > 0) {
BigDecimal planned = holder.min.max(now.subtract(step));
- minusItem = getSetValueItem(Material.RED_TERRACOTTA, planned, "§c-");
+ minusItem = getSetValueItem(Material.RED_TERRACOTTA, planned, "\u00A7c-");
} else {
minusItem = GuiGlobalItems.backgroundItem(Material.BARRIER);
}
@@ -155,7 +155,7 @@ public class DoubleSettingGui extends AbstractSettingGui {
if (now.compareTo(holder.max) < 0) {
BigDecimal planned = holder.max.min(now.add(step));
- plusItem = getSetValueItem(Material.GREEN_TERRACOTTA, planned, "§a+");
+ plusItem = getSetValueItem(Material.GREEN_TERRACOTTA, planned, "\u00A7a+");
} else {
plusItem = GuiGlobalItems.backgroundItem(Material.BARRIER);
}
@@ -166,7 +166,7 @@ public class DoubleSettingGui extends AbstractSettingGui {
ItemMeta resultMeta = resultPaper.getItemMeta();
assert resultMeta != null;
- resultMeta.setDisplayName("§fValue: §e" + displayValue(now));
+ resultMeta.setDisplayName("\u00A7fValue: \u00A7e" + displayValue(now));
resultPaper.setItemMeta(resultMeta);
GuiItem resultItem = new GuiItem(resultPaper, GuiGlobalActions.stayInPlace, CustomAnvil.instance);
@@ -197,8 +197,8 @@ public class DoubleSettingGui extends AbstractSettingGui {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§e" + displayValue(now) + " §f-> §e" + displayValue(planned)
- + " §r(" + numberPrefix + (displayValue(planned.subtract(now).abs()) + "§r)"));
+ meta.setDisplayName("\u00A7e" + displayValue(now) + " \u00A7f-> \u00A7e" + displayValue(planned)
+ + " \u00A7r(" + numberPrefix + (displayValue(planned.subtract(now).abs()) + "\u00A7r)"));
meta.setLore(setLoreItem);
item.setItemMeta(meta);
@@ -271,21 +271,21 @@ public class DoubleSettingGui extends AbstractSettingGui {
// Get material properties
Material stepMat;
- StringBuilder stepName = new StringBuilder("§");
+ StringBuilder stepName = new StringBuilder("\u00A7");
List stepLore;
Consumer clickEvent;
if (stepValue.compareTo(step) == 0) {
stepMat = Material.GREEN_STAINED_GLASS_PANE;
stepName.append('a');
- stepLore = Collections.singletonList("§7Value is changing by " + displayValue(stepValue));
+ stepLore = Collections.singletonList("\u00A77Value is changing by " + displayValue(stepValue));
clickEvent = GuiGlobalActions.stayInPlace;
} else {
stepMat = Material.RED_STAINED_GLASS_PANE;
stepName.append('c');
- stepLore = Collections.singletonList("§7Click here to change the value by " + displayValue(stepValue));
+ stepLore = Collections.singletonList("\u00A77Click here to change the value by " + displayValue(stepValue));
clickEvent = updateStepValue(stepValue);
}
- stepName.append("Step of §e").append(displayValue(stepValue));
+ stepName.append("Step of \u00A7e").append(displayValue(stepValue));
// Create item stack then gui item
ItemStack item = new ItemStack(stepMat);
@@ -352,6 +352,42 @@ public class DoubleSettingGui extends AbstractSettingGui {
return value.toString();
}
+ /**
+ * Create a double setting factory from setting's parameters.
+ *
+ * @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.
+ * @return A factory for a double setting gui.
+ */
+ @NotNull
+ public static DoubleSettingFactory doubleFactory(@NotNull String title, @NotNull ValueUpdatableGui parent,
+ @NotNull ConfigHolder config,
+ @NotNull String configPath,
+ @Nullable List displayLore,
+ int scale, boolean asPercentage, boolean nullOnZero,
+ double min, double max, double defaultVal, double... steps) {
+ return new DoubleSettingFactory(
+ title, parent,
+ config,
+ configPath,
+ displayLore,
+ scale, asPercentage, nullOnZero,
+ min, max, defaultVal, steps);
+ }
+
/**
* A factory for a double setting gui that hold setting's information.
*/
@@ -391,7 +427,7 @@ public class DoubleSettingGui extends AbstractSettingGui {
* it is visually preferable to have an odd number of step.
* If step only contain 1 value, no step item should be displayed.
*/
- public DoubleSettingFactory(
+ protected DoubleSettingFactory(
@NotNull String title, @NotNull ValueUpdatableGui parent,
@NotNull ConfigHolder config,
@NotNull String configPath,
@@ -451,10 +487,10 @@ public class DoubleSettingGui extends AbstractSettingGui {
public GuiItem getItem(Material itemMat, String name){
// Get item properties
BigDecimal value = getConfiguredValue();
- StringBuilder itemName = new StringBuilder("§a").append(name);
+ StringBuilder itemName = new StringBuilder("\u00A7a").append(name);
return GuiGlobalItems.createGuiItemFromProperties(this, itemMat, itemName,
- "§e" + displayValue(value, this.asPercentage),
+ "\u00A7e" + displayValue(value, this.asPercentage),
this.displayLore, true);
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantCostSettingsGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantCostSettingsGui.java
index 3bd923b..f347588 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantCostSettingsGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantCostSettingsGui.java
@@ -5,7 +5,6 @@ import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil;
-import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag;
@@ -14,7 +13,6 @@ import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
@@ -85,10 +83,10 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
ItemMeta bookMeta = bookItemstack.getItemMeta();
assert bookMeta != null;
- bookMeta.setDisplayName("§aCost of an Enchantment by Book");
+ bookMeta.setDisplayName("\u00A7aCost of an Enchantment by Book");
bookMeta.setLore(Arrays.asList(
- "§7Cost per result item level of an sacrifice enchantment",
- "§7Only apply if sacrificed item §cis §7a book"));
+ "\u00A77Cost per result item level of an sacrifice enchantment",
+ "\u00A77Only apply if sacrificed item \u00A7cis \u00A77a book"));
bookItemstack.setItemMeta(bookMeta);
// sword display
@@ -97,10 +95,10 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
assert swordMeta != null;
swordMeta.addItemFlags(ItemFlag.values());
- swordMeta.setDisplayName("§aCost of an Enchantment by Item");
+ swordMeta.setDisplayName("\u00A7aCost of an Enchantment by Item");
swordMeta.setLore(Arrays.asList(
- "§7Cost per result item level of an sacrifice enchantment",
- "§7Only apply if sacrificed item §cis not §7a book"));
+ "\u00A77Cost per result item level of an sacrifice enchantment",
+ "\u00A77Only apply if sacrificed item \u00A7cis not \u00A77a book"));
swordItemstack.setItemMeta(swordMeta);
pane.bindItem('1', GuiGlobalItems.backgroundItem(Material.BLACK_STAINED_GLASS_PANE));
@@ -117,10 +115,10 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
// assume holder is an instance of EnchantCostSettingFactory
EnchantCostSettingFactory holder = (EnchantCostSettingFactory) this.holder;
- meta.setDisplayName("§eReset to default value");
+ meta.setDisplayName("\u00A7eReset to default value");
meta.setLore(Arrays.asList(
- "§7Default item value is: §e" + holder.defaultVal,
- "§7Default book value is: §e" + holder.defaultBookVal));
+ "\u00A77Default item value is: \u00A7e" + holder.defaultVal,
+ "\u00A77Default book value is: \u00A7e" + holder.defaultBookVal));
item.setItemMeta(meta);
returnToDefault = new GuiItem(item, event -> {
event.setCancelled(true);
@@ -149,7 +147,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§e" + nowBook + " §f-> §e" + planned + " §r(§c-" + (nowBook - planned) + "§r)");
+ meta.setDisplayName("\u00A7e" + nowBook + " \u00A7f-> \u00A7e" + planned + " \u00A7r(\u00A7c-" + (nowBook - planned) + "\u00A7r)");
meta.setLore(Collections.singletonList(AbstractSettingGui.CLICK_LORE));
item.setItemMeta(meta);
@@ -167,7 +165,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§e" + nowBook + " §f-> §e" + planned + " §r(§a+" + (planned - nowBook) + "§r)");
+ meta.setDisplayName("\u00A7e" + nowBook + " \u00A7f-> \u00A7e" + planned + " \u00A7r(\u00A7a+" + (planned - nowBook) + "\u00A7r)");
meta.setLore(Collections.singletonList(AbstractSettingGui.CLICK_LORE));
item.setItemMeta(meta);
@@ -182,7 +180,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
ItemMeta nowMeta = nowPaper.getItemMeta();
assert nowMeta != null;
- nowMeta.setDisplayName("§fValue: §e" + nowBook);
+ nowMeta.setDisplayName("\u00A7fValue: \u00A7e" + nowBook);
if(!holder.displayLore.isEmpty()){
nowMeta.setLore(holder.displayLore);
}
@@ -239,45 +237,73 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
return super.hadChange() || nowBook != beforeBook;
}
+ /**
+ * Create an int setting factory from setting's parameters.
+ *
+ * @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 min Minimum value of this setting.
+ * @param max Maximum value of this setting.
+ * @param defaultItemVal Default item value if not found on the config.
+ * @param defaultBookVal Default book 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 3 (included).
+ * it is visually preferable to have an odd number of step.
+ * If step only contain 1 value, no step item should be displayed.
+ * @return A factory for an enchant cost setting gui.
+ */
+ public static EnchantCostSettingFactory enchantCostFactory(
+ @NotNull String title, @NotNull ValueUpdatableGui parent,
+ @NotNull ConfigHolder config, @NotNull String configPath,
+ @Nullable List displayLore,
+ int min, int max, int defaultItemVal, int defaultBookVal,
+ int... steps) {
+ return new EnchantCostSettingFactory(
+ title, parent,
+ configPath, config,
+ displayLore,
+ min, max, defaultItemVal, defaultBookVal, steps);
+ }
+
/**
* A factory for an enchantment cost setting gui that hold setting's information.
*/
public static class EnchantCostSettingFactory extends IntSettingsGui.IntSettingFactory {
int defaultBookVal;
- @NotNull CAEnchantment enchantment;
/**
* Constructor for an enchantment cost setting gui factory.
*
- * @param title The title of the gui.
- * @param parent Parent gui to go back when completed.
- * @param configPath Configuration path of this setting.
- * @param config Configuration holder of this setting.
- * @param displayLore Gui display item lore.
- * @param min Minimum value of this setting.
- * @param max Maximum value of this setting.
- * @param enchantment Enchantment to change the cost to
- * @param steps List of step the value can increment/decrement.
- * List's size should be between 1 (included) and 3 (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 title The title of the gui.
+ * @param parent Parent gui to go back when completed.
+ * @param configPath Configuration path of this setting.
+ * @param config Configuration holder of this setting.
+ * @param displayLore Gui display item lore.
+ * @param min Minimum value of this setting.
+ * @param max Maximum value of this setting.
+ * @param defaultItemVal Default item value if not found on the config.
+ * @param defaultBookVal Default book 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 3 (included).
+ * it is visually preferable to have an odd number of step.
+ * If step only contain 1 value, no step item should be displayed.
*/
- public EnchantCostSettingFactory(
+ protected EnchantCostSettingFactory(
@NotNull String title, ValueUpdatableGui parent,
@NotNull String configPath, @NotNull ConfigHolder config,
@Nullable List displayLore,
- @NotNull CAEnchantment enchantment,
- int min, int max, int... steps) {
+ int min, int max, int defaultItemVal, int defaultBookVal,
+ int... steps) {
super(title, parent,
configPath, config,
displayLore,
- min, max, enchantment.defaultRarity().getItemValue(),
- steps);
-
- this.defaultBookVal = enchantment.defaultRarity().getBookValue();
- this.enchantment = enchantment;
+ min, max, defaultItemVal, steps);
+ this.defaultBookVal = defaultBookVal;
}
/**
@@ -285,14 +311,14 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
*/
@Override
public int getConfiguredValue() {
- return ConfigOptions.INSTANCE.enchantmentValue(enchantment, false);
+ return this.config.getConfig().getInt(this.configPath + ITEM_PATH, this.defaultVal);
}
/**
* @return The configured value for the enchant setting book value.
*/
public int getConfiguredBookValue() {
- return ConfigOptions.INSTANCE.enchantmentValue(enchantment, true);
+ return this.config.getConfig().getInt(this.configPath + BOOK_PATH, this.defaultBookVal);
}
@Override
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantSelectSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantSelectSettingGui.java
index 176da55..2c50042 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantSelectSettingGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantSelectSettingGui.java
@@ -15,7 +15,6 @@ import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
-import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
import xyz.alexcrea.cuanvil.gui.config.SelectEnchantmentContainer;
import xyz.alexcrea.cuanvil.gui.config.list.SettingGuiListConfigGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
@@ -36,7 +35,7 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui(enchantContainer.getSelectedEnchantments());
@@ -53,11 +52,11 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui TRUE_LORE = Collections.singletonList("§7Value: §aSelected");
- private static final List FALSE_LORE = Collections.singletonList("§7Value: §cNot Selected");
+ private static final List TRUE_LORE = Collections.singletonList("\u00A77Value: \u00A7aSelected");
+ private static final List FALSE_LORE = Collections.singletonList("\u00A77Value: \u00A7cNot Selected");
public void setEnchantItemMeta(ItemStack item, String name, boolean isIn) {
ItemMeta meta = item.getItemMeta();
@@ -139,7 +138,7 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui & EnumSettingGui.ConfigurableEnum> extends AbstractSettingGui {
-
- private final EnumSettingFactory holder;
- private final T before;
- private T now;
-
- /**
- * Create an item setting config gui.
- *
- * @param holder Configuration factory of this setting.
- * @param now The defined value of this setting.
- */
- protected EnumSettingGui(EnumSettingFactory holder, T now) {
- super(3, holder.getTitle(), holder.parent);
- this.holder = holder;
- this.before = now;
- this.now = now;
-
- prepareStaticItems();
- updateValueDisplay();
- }
-
- @Override
- public Pattern getGuiPattern() {
- return new Pattern(
- GuiSharedConstant.EMPTY_GUI_FULL_LINE,
- "D000v0000",
- "B0000000S"
- );
- }
-
-
- public void prepareStaticItems(){
- prepareReturnToDefault();
- }
-
-
- protected GuiItem returnToDefault;
-
- /**
- * Prepare "return to default value" gui item.
- */
- protected void prepareReturnToDefault() {
- ItemStack item = new ItemStack(Material.COMMAND_BLOCK);
- ItemMeta meta = item.getItemMeta();
- assert meta != null;
-
- meta.setDisplayName("§eReset to default value");
- meta.setLore(Collections.singletonList("§7Default value is §e" + holder.getDefault().configurationGuiName()));
- item.setItemMeta(meta);
- returnToDefault = new GuiItem(item, event -> {
- event.setCancelled(true);
- now = holder.getDefault();
- updateValueDisplay();
- update();
- }, CustomAnvil.instance);
- }
-
- /**
- * Update item using the setting value to match the new value
- */
- protected void updateValueDisplay() {
- PatternPane pane = getPane();
-
- // Get displayed value for this config.
- ItemStack displayedItem = now.configurationGuiItem();
-
- GuiItem resultItem = new GuiItem(displayedItem, selectNext(), CustomAnvil.instance);
- pane.bindItem('v', resultItem);
-
- // reset to default
- GuiItem returnToDefault;
- if (now != holder.getDefault()) {
- returnToDefault = this.returnToDefault;
- } else {
- returnToDefault = GuiGlobalItems.backgroundItem();
- }
- pane.bindItem('D', returnToDefault);
-
- }
-
- /**
- * @return A consumer to update the current setting's value.
- */
- protected Consumer selectNext() {
- return event -> {
- event.setCancelled(true);
-
- this.now = this.holder.next(this.now);
-
- updateValueDisplay();
- update();
- };
-
- }
-
- @Override
- public boolean onSave() {
- holder.config.getConfig().set(holder.configPath, this.now.configName());
-
- if (GuiSharedConstant.TEMPORARY_DO_SAVE_TO_DISK_EVERY_CHANGE) {
- return holder.config.saveToDisk(GuiSharedConstant.TEMPORARY_DO_BACKUP_EVERY_SAVE);
- }
- return true;
- }
-
- @Override
- public boolean hadChange() {
- return !now.equals(before);
- }
-
-
- /**
- * A factory for an enum setting gui that hold setting's information.
- */
- public abstract static class EnumSettingFactory & ConfigurableEnum> extends SettingGuiFactory {
- @NotNull
- String title;
- @NotNull
- ValueUpdatableGui parent;
-
- /**
- * Constructor for an enum settings gui factory
- *
- * @param title The title of the gui.
- * @param parent Parent gui to go back when completed.
- * @param configPath Configuration path of this setting.
- * @param config Configuration holder of this setting.
- */
- protected EnumSettingFactory(
- @NotNull String title, @NotNull ValueUpdatableGui parent,
- @NotNull String configPath, @NotNull ConfigHolder config) {
- super(configPath, config);
- this.title = title;
- this.parent = parent;
-
- }
- /**
- * @return Get setting's gui title.
- */
- @NotNull
- public String getTitle() {
- return title;
- }
-
- /**
- * @return The configured value for the associated setting.
- */
- @NotNull
- public abstract T getConfiguredValue();
-
- @NotNull
- public abstract List getDisplayLore(T value);
-
- /**
- * @return Next value for a given enum
- */
- @NotNull
- public T next(@NotNull T now){
- Class clazz = now.getDeclaringClass();
- T[] values = clazz.getEnumConstants();
-
- int index = now.ordinal();
- if(index == values.length - 1)
- return values[0];
-
- return values[index + 1];
- }
-
- /**
- * Get default value value
- * @return default value
- */
- @NotNull
- public abstract T getDefault();
-
- @Override
- public Gui create() {
- // Get value or default
- T now = getConfiguredValue();
-
- // create new gui
- return new EnumSettingGui<>(this, now);
- }
-
- /**
- * Create a new enum setting GuiItem.
- * This item will create and open an enum setting GUI from the factory.
- *
- * @param name Name of the display.
- * @return A formatted GuiItem that will create and open a GUI for the enum setting.
- */
- public GuiItem getItem(@NotNull Material material, @NotNull String name) {
- T value = getConfiguredValue();
-
- ItemStack item = new ItemStack(material);
- ItemMeta meta = item.getItemMeta();
- assert meta != null;
-
- meta.setDisplayName(name);
- meta.setLore(getDisplayLore(value));
- meta.addItemFlags(ItemFlag.values());
-
- item.setItemMeta(meta);
-
- return GuiGlobalItems.openSettingGuiItem(item, this);
- }
- }
-
- public interface ConfigurableEnum {
-
- String configName();
-
- ItemStack configurationGuiItem();
- String configurationGuiName();
-
-
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/GroupSelectSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/GroupSelectSettingGui.java
index 69986a0..9808a8b 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/GroupSelectSettingGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/GroupSelectSettingGui.java
@@ -17,7 +17,6 @@ import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.group.AbstractMaterialGroup;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
import xyz.alexcrea.cuanvil.gui.config.SelectGroupContainer;
-import xyz.alexcrea.cuanvil.gui.config.list.ElementListConfigGui;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
import xyz.alexcrea.cuanvil.util.CasedStringUtil;
@@ -51,22 +50,18 @@ public class GroupSelectSettingGui extends AbstractSettingGui {
@Override
protected Pattern getGuiPattern() {
return new Pattern(
- GuiSharedConstant.UPPER_FILLER_FULL_PLANE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
"B1111111S"
);
}
protected void initGroups() {
// Add enchantment gui item
- OutlinePane filledEnchant = new OutlinePane(
- ElementListConfigGui.LIST_FILLER_START_X,
- ElementListConfigGui.LIST_FILLER_START_Y,
- ElementListConfigGui.LIST_FILLER_LENGTH,
- ElementListConfigGui.LIST_FILLER_HEIGHT);
+ OutlinePane filledEnchant = new OutlinePane(0, 0, 9, 5);
filledEnchant.setPriority(Pane.Priority.HIGH);
filledEnchant.align(OutlinePane.Alignment.BEGIN);
filledEnchant.setOrientation(Orientable.Orientation.HORIZONTAL);
@@ -96,8 +91,8 @@ public class GroupSelectSettingGui extends AbstractSettingGui {
return guiItem;
}
- private static final List TRUE_LORE = Collections.singletonList("§7Value: §aSelected");
- private static final List FALSE_LORE = Collections.singletonList("§7Value: §cNot Selected");
+ private static final List TRUE_LORE = Collections.singletonList("\u00A77Value: \u00A7aSelected");
+ private static final List FALSE_LORE = Collections.singletonList("\u00A77Value: \u00A7cNot Selected");
public void setGroupItemMeta(ItemStack item, String name, boolean isIn) {
ItemMeta meta = item.getItemMeta();
@@ -110,7 +105,7 @@ public class GroupSelectSettingGui extends AbstractSettingGui {
assert meta != null;
}
- meta.setDisplayName("§" + (isIn ? 'a' : 'c') + CasedStringUtil.snakeToUpperSpacedCase(name));
+ meta.setDisplayName("\u00A7" + (isIn ? 'a' : 'c') + CasedStringUtil.snakeToUpperSpacedCase(name));
if (isIn) {
meta.addEnchant(Enchantment.DAMAGE_UNDEAD, 1, true);
meta.setLore(TRUE_LORE);
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/IntSettingsGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/IntSettingsGui.java
index 73121a6..389546b 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/IntSettingsGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/IntSettingsGui.java
@@ -71,9 +71,8 @@ public class IntSettingsGui extends AbstractSettingGui {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§eReset to default value");
- meta.setLore(Collections.singletonList("§7Default value is §e" +
- holder.valueDisplayName(ValueDisplayType.RESET, holder.defaultVal)));
+ meta.setDisplayName("\u00A7eReset to default value");
+ meta.setLore(Collections.singletonList("\u00A77Default value is \u00A7e" + holder.defaultVal));
item.setItemMeta(meta);
returnToDefault = new GuiItem(item, event -> {
event.setCancelled(true);
@@ -87,23 +86,41 @@ public class IntSettingsGui extends AbstractSettingGui {
* Update item using the setting value to match the new value.
*/
protected void updateValueDisplay() {
+
PatternPane pane = getPane();
// minus item
GuiItem minusItem;
if (now > holder.min) {
int planned = Math.max(holder.min, now - step);
- minusItem = valueEditItem(Material.RED_TERRACOTTA, ValueDisplayType.REMOVE, planned);
+ ItemStack item = new ItemStack(Material.RED_TERRACOTTA);
+ ItemMeta meta = item.getItemMeta();
+ assert meta != null;
+
+ meta.setDisplayName("\u00A7e" + now + " \u00A7f-> \u00A7e" + planned + " \u00A7r(\u00A7c-" + (now - planned) + "\u00A7r)");
+ meta.setLore(Collections.singletonList(AbstractSettingGui.CLICK_LORE));
+ item.setItemMeta(meta);
+
+ minusItem = new GuiItem(item, updateNowConsumer(planned), CustomAnvil.instance);
} else {
minusItem = GuiGlobalItems.backgroundItem(Material.BARRIER);
}
pane.bindItem('-', minusItem);
//plus item
+ // may do a function to generalise ?
GuiItem plusItem;
if (now < holder.max) {
int planned = Math.min(holder.max, now + step);
- plusItem = valueEditItem(Material.GREEN_TERRACOTTA, ValueDisplayType.ADD, planned);
+ ItemStack item = new ItemStack(Material.GREEN_TERRACOTTA);
+ ItemMeta meta = item.getItemMeta();
+ assert meta != null;
+
+ meta.setDisplayName("\u00A7e" + now + " \u00A7f-> \u00A7e" + planned + " \u00A7r(\u00A7a+" + (planned - now) + "\u00A7r)");
+ meta.setLore(Collections.singletonList(AbstractSettingGui.CLICK_LORE));
+ item.setItemMeta(meta);
+
+ plusItem = new GuiItem(item, updateNowConsumer(planned), CustomAnvil.instance);
} else {
plusItem = GuiGlobalItems.backgroundItem(Material.BARRIER);
}
@@ -114,7 +131,7 @@ public class IntSettingsGui extends AbstractSettingGui {
ItemMeta resultMeta = resultPaper.getItemMeta();
assert resultMeta != null;
- resultMeta.setDisplayName("§fValue: §e" + holder.valueDisplayName(ValueDisplayType.CURRENT, now));
+ resultMeta.setDisplayName("\u00A7fValue: \u00A7e" + now);
resultMeta.setLore(holder.displayLore);
resultPaper.setItemMeta(resultMeta);
@@ -132,21 +149,7 @@ public class IntSettingsGui extends AbstractSettingGui {
}
pane.bindItem('D', returnToDefault);
- }
- private GuiItem valueEditItem(Material mat, ValueDisplayType type, int planned) {
- ItemStack item = new ItemStack(mat);
- ItemMeta meta = item.getItemMeta();
- assert meta != null;
-
- var nowDisplay = holder.valueDisplayName(type, now);
- var plannedDisplay = holder.valueDisplayName(type, planned);
- var deltaDisplay = holder.deltaDisplay(type, now, planned);
- meta.setDisplayName("§e" + nowDisplay + " §f-> §e" + plannedDisplay + " §r(§c" + deltaDisplay + "§r)");
-
- meta.setLore(Collections.singletonList(AbstractSettingGui.CLICK_LORE));
- item.setItemMeta(meta);
- return new GuiItem(item, updateNowConsumer(planned), CustomAnvil.instance);
}
/**
@@ -215,21 +218,21 @@ public class IntSettingsGui extends AbstractSettingGui {
// Get material properties
Material stepMat;
- StringBuilder stepName = new StringBuilder("§");
+ StringBuilder stepName = new StringBuilder("\u00A7");
List stepLore;
Consumer clickEvent;
if (stepValue == step) {
stepMat = Material.GREEN_STAINED_GLASS_PANE;
stepName.append('a');
- stepLore = Collections.singletonList("§7Value is changing by " + stepValue);
+ stepLore = Collections.singletonList("\u00A77Value is changing by " + stepValue);
clickEvent = GuiGlobalActions.stayInPlace;
} else {
stepMat = Material.RED_STAINED_GLASS_PANE;
stepName.append('c');
- stepLore = Collections.singletonList("§7Click here to change the value by " + stepValue);
+ stepLore = Collections.singletonList("\u00A77Click here to change the value by " + stepValue);
clickEvent = updateStepValue(stepValue);
}
- stepName.append("Step of: §e").append(stepValue);
+ stepName.append("Step of: \u00A7e").append(stepValue);
// Create item stack then gui item
ItemStack item = new ItemStack(stepMat);
@@ -272,11 +275,38 @@ public class IntSettingsGui extends AbstractSettingGui {
return now != before;
}
+ /**
+ * Create an int setting factory from setting's parameters.
+ *
+ * @param title The title of the gui.
+ * @param parent Parent gui to go back when completed.
+ * @param configPath Configuration path of this setting.
+ * @param config Configuration holder of this setting.
+ * @param displayLore Gui display item lore.
+ * @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.
+ * @return A factory for an int setting gui.
+ */
+ public static IntSettingFactory intFactory(@NotNull String title, ValueUpdatableGui parent,
+ String configPath, ConfigHolder config,
+ @Nullable List displayLore,
+ int min, int max, int defaultVal, int... steps) {
+ return new IntSettingFactory(
+ title, parent,
+ configPath, config,
+ displayLore,
+ min, max, defaultVal, steps);
+ }
+
/**
* A factory for an int setting gui that hold setting's information.
*/
public static class IntSettingFactory extends SettingGuiFactory {
-
@NotNull
String title;
@NotNull
@@ -305,7 +335,7 @@ public class IntSettingsGui extends AbstractSettingGui {
* it is visually preferable to have an odd number of step.
* If step only contain 1 value, no step item should be displayed.
*/
- public IntSettingFactory(
+ protected IntSettingFactory(
@NotNull String title, @NotNull ValueUpdatableGui parent,
@NotNull String configPath, @NotNull ConfigHolder config,
@Nullable List displayLore,
@@ -363,10 +393,10 @@ public class IntSettingsGui extends AbstractSettingGui {
) {
// Get item properties
int value = getConfiguredValue();
- StringBuilder itemName = new StringBuilder("§a").append(name);
+ StringBuilder itemName = new StringBuilder("\u00A7a").append(name);
return GuiGlobalItems.createGuiItemFromProperties(this, itemMat, itemName,
- "§e" + value,
+ "\u00A7e" + value,
this.displayLore, true);
}
@@ -386,23 +416,6 @@ public class IntSettingsGui extends AbstractSettingGui {
return getItem(itemMat, CasedStringUtil.detectToUpperSpacedCase(configPath));
}
- protected String valueDisplayName(ValueDisplayType type, int value) {
- return String.valueOf(value);
- }
-
- protected String deltaDisplay(ValueDisplayType type, int now, int planned) {
- var delta = planned - now;
- if(delta < 0) return "§c" + delta;
- else return "§a+" + delta;
- }
-
- }
-
- public enum ValueDisplayType {
- ADD,
- CURRENT,
- REMOVE,
- RESET,
}
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/ItemSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/ItemSettingGui.java
index 3df2af8..e49daa7 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/ItemSettingGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/ItemSettingGui.java
@@ -62,7 +62,7 @@ public class ItemSettingGui extends AbstractSettingGui {
public void prepareStaticItems(){
prepareReturnToDefault();
- GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(Material.YELLOW_STAINED_GLASS_PANE, this);
+ GuiItem temporaryLeave = GuiGlobalItems.temporaryCloseGuiToSelectItem(Material.YELLOW_TERRACOTTA, this);
getPane().bindItem('s', temporaryLeave);
}
@@ -77,8 +77,8 @@ public class ItemSettingGui extends AbstractSettingGui {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§eReset to default value");
- meta.setLore(Collections.singletonList("§7Default value is §e" + holder.defaultVal));
+ meta.setDisplayName("\u00A7eReset to default value");
+ meta.setLore(Collections.singletonList("\u00A77Default value is \u00A7e" + holder.defaultVal));
item.setItemMeta(meta);
returnToDefault = new GuiItem(item, event -> {
event.setCancelled(true);
@@ -88,7 +88,7 @@ public class ItemSettingGui extends AbstractSettingGui {
}, CustomAnvil.instance);
}
- protected final static List CLICK_LORE = Collections.singletonList("§7Click Here with an item to change the value");
+ protected final static List CLICK_LORE = Collections.singletonList("\u00A77Click Here with an item to change the value");
/**
* Update item using the setting value to match the new value
@@ -105,7 +105,7 @@ public class ItemSettingGui extends AbstractSettingGui {
ItemMeta valueMeta = displayedItem.getItemMeta();
assert valueMeta != null;
- valueMeta.setDisplayName("§4NO ITEM SET");
+ valueMeta.setDisplayName("\u00A74NO ITEM SET");
valueMeta.setLore(CLICK_LORE);
displayedItem.setItemMeta(valueMeta);
@@ -163,6 +163,27 @@ public class ItemSettingGui extends AbstractSettingGui {
return !now.equals(before);
}
+ /**
+ * Create aa item setting factory from setting's parameters.
+ *
+ * @param title The title of the gui.
+ * @param parent Parent gui to go back when completed.
+ * @param configPath Configuration path of this setting.
+ * @param config Configuration holder of this setting.
+ * @param defaultVal Default value if not found on the config.
+ * @param displayLore Gui display item lore.
+ * @return A factory for an item setting gui.
+ */
+ public static ItemSettingGui.ItemSettingFactory itemFactory(@NotNull String title, @NotNull ValueUpdatableGui parent,
+ @NotNull String configPath, @NotNull ConfigHolder config,
+ @Nullable ItemStack defaultVal,
+ String... displayLore) {
+ return new ItemSettingGui.ItemSettingFactory(
+ title, parent,
+ configPath, config,
+ defaultVal, displayLore);
+ }
+
/**
* A factory for an item setting gui that hold setting's information.
*/
@@ -186,7 +207,7 @@ public class ItemSettingGui extends AbstractSettingGui {
* @param defaultVal Default value if not found on the config.
* @param displayLore Gui display item lore.
*/
- public ItemSettingFactory(
+ protected ItemSettingFactory(
@NotNull String title, @NotNull ValueUpdatableGui parent,
@NotNull String configPath, @NotNull ConfigHolder config,
@Nullable ItemStack defaultVal,
@@ -245,7 +266,7 @@ public class ItemSettingGui extends AbstractSettingGui {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§a" + name);
+ meta.setDisplayName("\u00A7a" + name);
meta.setLore(getDisplayLore());
meta.addItemFlags(ItemFlag.values());
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/MaterialSelectSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/MaterialSelectSettingGui.java
index fc519ff..7998548 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/MaterialSelectSettingGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/MaterialSelectSettingGui.java
@@ -5,7 +5,6 @@ import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag;
@@ -19,19 +18,18 @@ import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
import xyz.alexcrea.cuanvil.util.CasedStringUtil;
-import xyz.alexcrea.cuanvil.util.MaterialUtil;
import java.util.*;
import java.util.function.Consumer;
-public class MaterialSelectSettingGui extends MappedElementListConfigGui {
+public class MaterialSelectSettingGui extends MappedElementListConfigGui {
private final SelectMaterialContainer selector;
private final Gui backGui;
private boolean instantRemove;
- private final List defaultMaterials;
- private final Set illegalMaterials;
+ private final List defaultMaterials;
+ private final EnumSet illegalMaterials;
private final int defaultMaterialHash;
private int nowMaterialHash;
@@ -59,11 +57,11 @@ public class MaterialSelectSettingGui extends MappedElementListConfigGui result = new HashSet<>(this.elementGuiMap.keySet());
+ EnumSet result = EnumSet.noneOf(Material.class);
+ result.addAll(this.elementGuiMap.keySet());
if(!this.selector.setSelectedMaterials(result)){
- player.sendMessage("§cSomething went wrong while saving the change of value.");
+ player.sendMessage("\u00A7cSomething went wrong while saving the change of value.");
}
// Return to parent
@@ -186,8 +185,8 @@ public class MaterialSelectSettingGui extends MappedElementListConfigGui getEveryDisplayableInstanceOfGeneric() {
+ protected Collection getEveryDisplayableInstanceOfGeneric() {
return this.defaultMaterials;
}
@Override
- protected void updateElement(NamespacedKey material, GuiItem element) {
+ protected void updateElement(Material material, GuiItem element) {
// Nothing happen here I think
}
@Override
- protected GuiItem newElementRequested(NamespacedKey material, GuiItem newItem) {
+ protected GuiItem newElementRequested(Material material, GuiItem newItem) {
newItem.setAction(event -> {
if(this.instantRemove){
removeMaterial(material);
}else {
- String materialName = CasedStringUtil.snakeToUpperSpacedCase(material.getKey().toLowerCase());
+ String materialName = CasedStringUtil.snakeToUpperSpacedCase(material.name().toLowerCase());
// Create and show confirm remove gui.
ConfirmActionGui confirmGui = new ConfirmActionGui(
"Remove " + materialName,
- "§7Confirm Remove " + materialName.toLowerCase() + " from this list.",
+ "\u00A77Confirm Remove " + materialName.toLowerCase() + " from this list.",
this, this,
() -> {
removeMaterial(material);
@@ -251,7 +250,7 @@ public class MaterialSelectSettingGui extends MappedElementListConfigGui materialList){
+ private static int hashFromMaterialList(List materialList){
int defaultMaterialHash = 0;
- for (NamespacedKey material : materialList) {
+ for (Material material : materialList) {
defaultMaterialHash ^= material.hashCode();
}
return defaultMaterialHash;
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/WorkPenaltyTypeSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/WorkPenaltyTypeSettingGui.java
deleted file mode 100644
index 4345aa1..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/WorkPenaltyTypeSettingGui.java
+++ /dev/null
@@ -1,252 +0,0 @@
-package xyz.alexcrea.cuanvil.gui.config.settings;
-
-import com.github.stefvanschie.inventoryframework.gui.GuiItem;
-import com.github.stefvanschie.inventoryframework.pane.PatternPane;
-import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
-import io.delilaheve.CustomAnvil;
-import io.delilaheve.util.ConfigOptions;
-import org.bukkit.Material;
-import org.bukkit.configuration.file.FileConfiguration;
-import org.bukkit.entity.HumanEntity;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.inventory.meta.ItemMeta;
-import org.jetbrains.annotations.NotNull;
-import xyz.alexcrea.cuanvil.anvil.AnvilUseType;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.config.WorkPenaltyType;
-import xyz.alexcrea.cuanvil.gui.config.global.BasicConfigGui;
-import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
-
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-
-public class WorkPenaltyTypeSettingGui extends AbstractSettingGui {
-
- private static final String INCREASING_EXPLANATION = "§eIncreasing§7: will penalty be increased (in item)";
- private static final String ADDING_EXPLANATION = "§eAdditive§7: will penalty be added to the cost";
-
- private static final String SHARED_EXPLANATION = "§eShared§7: Vanilla, shared penalty. it will be kept from before the plugin installation.";
- private static final String EXCLUSIVE_EXPLANATION = "§eExclusive§7: Custom, per anvil use type penalty. it will be lost after plugin uninstallation";
-
- private final @NotNull WorkPenaltyType currentType;
- private final @NotNull Map items;
-
- public WorkPenaltyTypeSettingGui(@NotNull BasicConfigGui parent) {
- super(4, "§8Work Penalty Type", parent);
-
- this.currentType = ConfigOptions.INSTANCE.getWorkPenaltyType();
- this.items = new EnumMap<>(this.currentType.getPartMap());
-
- for (AnvilUseType type : useTypes.keySet()) {
- updateGuiForType(type);
- }
- }
-
- public static GuiItem getDisplayItem(@NotNull BasicConfigGui parent,
- @NotNull Material itemMat,
- @NotNull String name) {
- List displayLore = new ArrayList<>();
-
- displayLore.add("§7Work penalty increase the price for every anvil use.");
- displayLore.add("§7This config allow you to choose the comportment of work penalty.");
- displayLore.add(INCREASING_EXPLANATION);
- displayLore.add(ADDING_EXPLANATION);
- displayLore.add("");
- displayLore.add("§7About shared/exclusive penalty:");
- displayLore.add(SHARED_EXPLANATION);
- displayLore.add(EXCLUSIVE_EXPLANATION);
-
- ItemStack item = new ItemStack(itemMat);
-
- ItemMeta meta = item.getItemMeta();
- meta.setDisplayName(name);
- meta.setLore(displayLore);
-
- item.setItemMeta(meta);
-
- return new GuiItem(item, (event) -> {
- event.setCancelled(true);
- HumanEntity player = event.getWhoClicked();
-
- // Do not allow to open inventory if player do not have edit configuration permission
- if (!player.hasPermission(CustomAnvil.editConfigPermission)) {
- player.closeInventory();
- player.sendMessage(GuiGlobalActions.NO_EDIT_PERM);
- return;
- }
- new WorkPenaltyTypeSettingGui(parent).show(player);
- }, CustomAnvil.instance);
- }
-
- private static final Map useTypes =
- Map.of(
- AnvilUseType.RENAME_ONLY, "a1z9Z",
- AnvilUseType.MERGE, "b2y8Y",
- AnvilUseType.UNIT_REPAIR, "c3x7X",
- AnvilUseType.CUSTOM_CRAFT, "d4w6W"
- );
-
- @Override
- protected Pattern getGuiPattern() {
- return new Pattern( // Yeah that a mess
- "00a1z9Z00",
- "00b2y8Y00",
- "00c3x7X00",
- "B004w600S"
- );
- }
-
- public void updateGuiForType(AnvilUseType type) {
- PatternPane pane = getPane();
-
- String typeVals = useTypes.get(type);
-
- char increment = typeVals.charAt(0);
- char additive = typeVals.charAt(1);
- char display = typeVals.charAt(2);
- char exclusiveIncrement = typeVals.charAt(3);
- char exclusiveAdditive = typeVals.charAt(4);
-
- WorkPenaltyType.WorkPenaltyPart part = items.get(type);
- String increasingStr = (part.penaltyIncrease() ? "§a" : "§c") + "Increasing";
- String additiveStr = (part.penaltyAdditive() ? "§a" : "§c") + "Additive";
- String exclusiveIncreasingStr = (part.exclusivePenaltyIncrease() ? "§a" : "§c") + "Increasing";
- String exclusiveAdditiveStr = (part.exclusivePenaltyAdditive() ? "§a" : "§c") + "Additive";
-
- // Display item
- ItemStack displayItem = new ItemStack(type.getDisplayMat());
-
- ArrayList displayLore = new ArrayList<>();
- displayLore.add("§eShared§7: " + additiveStr + " §7| " + increasingStr);
- displayLore.add("§eExclusive§7: " + exclusiveAdditiveStr + " §7| " + exclusiveIncreasingStr);
-
- ItemMeta meta = displayItem.getItemMeta();
- meta.setDisplayName("§e" + type.getDisplayName());
- meta.setLore(displayLore);
- displayItem.setItemMeta(meta);
-
- pane.bindItem(display, new GuiItem(displayItem, (event) -> {
- event.setCancelled(true);
- }));
-
- // Can probably put this in a function but this works so
- // "Increment" item
- ItemStack incrementItem = new ItemStack(part.penaltyIncrease() ? Material.GREEN_TERRACOTTA : Material.RED_TERRACOTTA);
-
- meta = incrementItem.getItemMeta();
- meta.setDisplayName(increasingStr);
- meta.setLore(List.of(INCREASING_EXPLANATION));
- meta.setLore(List.of(SHARED_EXPLANATION));
- incrementItem.setItemMeta(meta);
-
- pane.bindItem(increment, new GuiItem(incrementItem, (event) -> {
- event.setCancelled(true);
-
- WorkPenaltyType.WorkPenaltyPart newPart = new WorkPenaltyType.WorkPenaltyPart(
- !part.penaltyIncrease(), part.penaltyAdditive(),
- part.exclusivePenaltyIncrease(), part.exclusivePenaltyAdditive());
- items.replace(type, newPart);
- updateGuiForType(type);
- update();
- }));
-
- // "Additive" item
- ItemStack additiveItem = new ItemStack(part.penaltyAdditive() ? Material.GREEN_TERRACOTTA : Material.RED_TERRACOTTA);
-
- meta = additiveItem.getItemMeta();
- meta.setDisplayName(additiveStr);
- meta.setLore(List.of(ADDING_EXPLANATION));
- meta.setLore(List.of(SHARED_EXPLANATION));
- additiveItem.setItemMeta(meta);
-
- pane.bindItem(additive, new GuiItem(additiveItem, (event) -> {
- event.setCancelled(true);
-
- WorkPenaltyType.WorkPenaltyPart newPart = new WorkPenaltyType.WorkPenaltyPart(
- part.penaltyIncrease(), !part.penaltyAdditive(),
- part.exclusivePenaltyIncrease(), part.exclusivePenaltyAdditive());
- items.replace(type, newPart);
- updateGuiForType(type);
- update();
- }));
-
- // exclusive "Increment" item
- ItemStack exclusiveIncrementItem = new ItemStack(part.exclusivePenaltyIncrease() ? Material.GREEN_TERRACOTTA : Material.RED_TERRACOTTA);
-
- meta = exclusiveIncrementItem.getItemMeta();
- meta.setDisplayName(exclusiveIncreasingStr);
- meta.setLore(List.of(INCREASING_EXPLANATION));
- meta.setLore(List.of(EXCLUSIVE_EXPLANATION));
- exclusiveIncrementItem.setItemMeta(meta);
-
- pane.bindItem(exclusiveIncrement, new GuiItem(exclusiveIncrementItem, (event) -> {
- event.setCancelled(true);
-
- WorkPenaltyType.WorkPenaltyPart newPart = new WorkPenaltyType.WorkPenaltyPart(
- part.penaltyIncrease(), part.penaltyAdditive(),
- !part.exclusivePenaltyIncrease(), part.exclusivePenaltyAdditive());
- items.replace(type, newPart);
- updateGuiForType(type);
- update();
- }));
-
- // exclusive "Additive" item
- ItemStack exclusiveAdditiveItem = new ItemStack(part.exclusivePenaltyAdditive() ? Material.GREEN_TERRACOTTA : Material.RED_TERRACOTTA);
-
- meta = exclusiveAdditiveItem.getItemMeta();
- meta.setDisplayName(exclusiveAdditiveStr);
- meta.setLore(List.of(ADDING_EXPLANATION));
- meta.setLore(List.of(EXCLUSIVE_EXPLANATION));
- exclusiveAdditiveItem.setItemMeta(meta);
-
- pane.bindItem(exclusiveAdditive, new GuiItem(exclusiveAdditiveItem, (event) -> {
- event.setCancelled(true);
-
- WorkPenaltyType.WorkPenaltyPart newPart = new WorkPenaltyType.WorkPenaltyPart(
- part.penaltyIncrease(), part.penaltyAdditive(),
- part.exclusivePenaltyIncrease(), !part.exclusivePenaltyAdditive());
- items.replace(type, newPart);
- updateGuiForType(type);
- update();
- }));
- }
-
- @Override
- public boolean onSave() {
- return saveWorkPenalty(items);
- }
-
- public static boolean saveWorkPenalty(Map partEnum) {
- ConfigHolder configHolder = ConfigHolder.DEFAULT_CONFIG;
- FileConfiguration config = configHolder.getConfig();
-
- partEnum.forEach((key, value) -> {
- String partPath = key.getPath();
-
- if (key.getDefaultPenalty().equals(value)) {
- config.set(partPath, null);
- return;
- }
-
- config.set(partPath + '.' + ConfigOptions.WORK_PENALTY_INCREASE, value.penaltyIncrease());
- config.set(partPath + '.' + ConfigOptions.WORK_PENALTY_ADDITIVE, value.penaltyAdditive());
- config.set(partPath + '.' + ConfigOptions.EXCLUSIVE_WORK_PENALTY_INCREASE, value.exclusivePenaltyIncrease());
- config.set(partPath + '.' + ConfigOptions.EXCLUSIVE_WORK_PENALTY_ADDITIVE, value.exclusivePenaltyAdditive());
- });
-
- return configHolder.saveToDisk(true);
- }
-
- @Override
- public boolean hadChange() {
- for (AnvilUseType type : items.keySet()) {
- if (!currentType.getPenaltyInfo(type).equals(items.get(type))) {
- return true;
- }
- }
-
- return false;
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiGlobalActions.java b/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiGlobalActions.java
index 694fa14..d18d170 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiGlobalActions.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiGlobalActions.java
@@ -133,7 +133,7 @@ public class GuiGlobalActions {
// Save setting
if (!setting.onSave()) {
- player.sendMessage("§cSomething went wrong while saving the change of value.");
+ player.sendMessage("\u00A7cSomething went wrong while saving the change of value.");
}
// Update gui for those who have it open.
goal.updateGuiValues();
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiGlobalItems.java b/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiGlobalItems.java
index 79f1462..2eb42e3 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiGlobalItems.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiGlobalItems.java
@@ -30,7 +30,7 @@ public class GuiGlobalItems {
ItemMeta meta = BACK_ITEM.getItemMeta();
assert meta != null;
- meta.setDisplayName("§cBack");
+ meta.setDisplayName("\u00A7cBack");
BACK_ITEM.setItemMeta(meta);
}
@@ -82,7 +82,7 @@ public class GuiGlobalItems {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§c");
+ meta.setDisplayName("\u00A7c");
item.setItemMeta(meta);
return new GuiItem(item, GuiGlobalActions.stayInPlace, CustomAnvil.instance);
}
@@ -139,7 +139,7 @@ public class GuiGlobalItems {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§aSave");
+ meta.setDisplayName("\u00A7aSave");
item.setItemMeta(meta);
return new GuiItem(item,
GuiGlobalActions.saveSettingAction(setting, goal),
@@ -154,7 +154,7 @@ public class GuiGlobalItems {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§7No change. can't save.");
+ meta.setDisplayName("\u00A77No change. can't save.");
item.setItemMeta(meta);
NO_CHANGE_ITEM = new GuiItem(item, GuiGlobalActions.stayInPlace, CustomAnvil.instance);
}
@@ -185,7 +185,7 @@ public class GuiGlobalItems {
}
// Prefix of the one line lore that will be added to setting's item.
- public static final String SETTING_ITEM_LORE_PREFIX = "§7value: ";
+ public static final String SETTING_ITEM_LORE_PREFIX = "\u00A77value: ";
/**
* Create an arbitrary GuiItem from a unique setting and item's property.
@@ -247,8 +247,8 @@ public class GuiGlobalItems {
ItemMeta meta = item.getItemMeta();
assert meta != null;
- meta.setDisplayName("§eTemporary close this menu");
- meta.setLore(Collections.singletonList("§7Allow you to chose other item then return here."));
+ meta.setDisplayName("\u00A7eTemporary close this menu");
+ meta.setLore(Collections.singletonList("\u00A77Allow you to chose other item then return here."));
item.setItemMeta(meta);
return new GuiItem(item, event -> {
@@ -263,7 +263,7 @@ public class GuiGlobalItems {
});
- player.sendMessage("§eWrite something in chat to return to the item config menu.");
+ player.sendMessage("\u00A7eWrite something in chat to return to the item config menu.");
player.closeInventory();
}, CustomAnvil.instance);
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiSharedConstant.java b/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiSharedConstant.java
index 11f3657..c2bccf9 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiSharedConstant.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/util/GuiSharedConstant.java
@@ -9,8 +9,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
-import java.util.Arrays;
-import java.util.Collections;
+import java.util.*;
public class GuiSharedConstant {
@@ -19,9 +18,7 @@ public class GuiSharedConstant {
public static final Material SECONDARY_BACKGROUND_MATERIAL = Material.BLACK_STAINED_GLASS_PANE;
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 EMPTY_GUI_FULL_LINE = "000000000";
- public static final String EMPTY_FILLER_FULL_LINE = "100000001";
// Temporary values, until I get something better.
public static final boolean TEMPORARY_DO_SAVE_TO_DISK_EVERY_CHANGE = true;
@@ -31,11 +28,11 @@ public class GuiSharedConstant {
static {
Pattern pattern = new Pattern(
- GuiSharedConstant.UPPER_FILLER_FULL_PLANE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
- GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
+ GuiSharedConstant.EMPTY_GUI_FULL_LINE,
"B11111111"
);
BACK_TO_MAIN_MENU_BIG_LIST_DISPLAY_BACKGROUND_PANE = new PatternPane(0, 0, 9, 6, Pane.Priority.LOW, pattern);
@@ -56,25 +53,25 @@ public class GuiSharedConstant {
ItemMeta meta = CANCEL_ITEM.getItemMeta();
assert meta != null;
- meta.setDisplayName("§cCancel");
- meta.setLore(Collections.singletonList("§7Cancel current action and return to previous menu."));
+ meta.setDisplayName("\u00A7cCancel");
+ meta.setLore(Collections.singletonList("\u00A77Cancel current action and return to previous menu."));
CANCEL_ITEM.setItemMeta(meta);
CONFIRM_ITEM = new ItemStack(Material.GREEN_TERRACOTTA);
meta = CONFIRM_ITEM.getItemMeta();
assert meta != null;
- meta.setDisplayName("§aConfirm");
- meta.setLore(Collections.singletonList("§7Confirm current action."));
+ meta.setDisplayName("\u00A7aConfirm");
+ meta.setLore(Collections.singletonList("\u00A77Confirm current action."));
CONFIRM_ITEM.setItemMeta(meta);
CONFIRM_PERMANENT_ITEM = new ItemStack(Material.GREEN_TERRACOTTA);
meta = CONFIRM_PERMANENT_ITEM.getItemMeta();
assert meta != null;
- meta.setDisplayName("§aConfirm");
- meta.setLore(Arrays.asList("§7Confirm current action.",
- "§4Cation: This action can't be canceled."));
+ meta.setDisplayName("\u00A7aConfirm");
+ meta.setLore(Arrays.asList("\u00A77Confirm current action.",
+ "\u00A74Cation: This action can't be canceled."));
CONFIRM_PERMANENT_ITEM.setItemMeta(meta);
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/ModrinthUpdateChecker.java b/src/main/java/xyz/alexcrea/cuanvil/update/ModrinthUpdateChecker.java
deleted file mode 100644
index 489c636..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/ModrinthUpdateChecker.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * MIT License
- *
- * Copyright (c) 2025 Clickism
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all
- * copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- * OTHER DEALINGS IN THE SOFTWARE.
- */
-
-package xyz.alexcrea.cuanvil.update;
-
-import com.google.gson.*;
-import org.jetbrains.annotations.Nullable;
-
-import java.net.URI;
-import java.net.http.HttpClient;
-import java.net.http.HttpRequest;
-import java.net.http.HttpResponse;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-import java.util.function.Function;
-
-/**
- * Utility class to check for newer versions of a project hosted on Modrinth.
- */
-public class ModrinthUpdateChecker {
-
- private static final String API_URL = "https://api.modrinth.com/v2/project/{id}/version";
-
- private final String projectId;
- private final String loader;
- @Nullable
- private final String minecraftVersion;
-
- @Nullable
- private Boolean featured = null;
-
- @Nullable
- public Consumer onError = null;
- @Nullable
- public Function getRawVersion = ModrinthUpdateChecker::getRawVersion;
-
- /**
- * Create a new update checker for the given project.
- * This will check the latest version for the given loader and any minecraft version.
- *
- * @param projectId the project ID
- * @param loader the loader
- */
- public ModrinthUpdateChecker(String projectId, String loader) {
- this(projectId, loader, null);
- }
-
- /**
- * Create a new update checker for the given project.
- * This will check the latest version for the given loader and minecraft version.
- *
- * @param projectId the project ID
- * @param loader the loader
- * @param minecraftVersion the minecraft version, or null for any version
- */
- public ModrinthUpdateChecker(String projectId, String loader, @Nullable String minecraftVersion) {
- this.projectId = projectId;
- this.loader = loader;
- this.minecraftVersion = minecraftVersion;
- }
-
- /**
- * Check the latest version of the project for the given loader and minecraft version
- * and call the consumer with it.
- *
- * @param consumer the consumer
- */
- public void checkVersion(Consumer consumer) {
- try {
- HttpClient client = HttpClient.newHttpClient();
- HttpRequest request = HttpRequest.newBuilder()
- .uri(prepareURI())
- .GET()
- .build();
-
- client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
- .thenAcceptAsync(response -> {
- if (response.statusCode() != 200) {
- if(onError != null)
- onError.accept(new RuntimeException("wrong response status code: " + response.statusCode()));
- return;
- }
- JsonArray versionsArray = JsonParser.parseString(response.body()).getAsJsonArray();
- String latestVersion = getLatestVersion(versionsArray);
- if (latestVersion == null) {
- if(onError != null)
- onError.accept(new RuntimeException("latest version is null"));
- return;
- }
- consumer.accept(latestVersion);
- });
- } catch (Exception e) {
- if(onError != null) onError.accept(e);
- }
- }
-
- /**
- * Get the latest compatible version from the versions array.
- *
- * @param versions the versions array
- * @return the latest compatible version
- */
- @Nullable
- protected String getLatestVersion(JsonArray versions) {
- return versions.asList().stream().findFirst()
- .map(JsonElement::getAsJsonObject)
- .map(version -> version.get("version_number").getAsString())
- .map(getRawVersion != null ? getRawVersion : (v -> v))
- .orElse(null);
- }
-
- /**
- * Gets the raw version from a version string.
- * i.E: "fabric-1.2+1.17.1" -> "1.2"
- *
- * @param version the version string
- * @return the raw version string
- */
- public static String getRawVersion(String version) {
- if (version.isEmpty()) return version;
- version = version.replaceAll("^\\D+", "");
- String[] split = version.split("\\+");
- return split[0];
- }
-
- /**
- * Prepare this request uri based on current parameters.
- * @return the request uri
- */
- private URI prepareURI() {
- var url = new StringBuilder(API_URL.replace("{id}", projectId));
-
- var parameters = prepareParameters();
- String[] paramArray = new String[parameters.size()];
- int i = 0;
- for (Map.Entry entry : parameters.entrySet()) {
- paramArray[i++] = entry.getKey() + '=' + entry.getValue();
- }
- url.append('?').append(String.join("&", paramArray));
-
- return URI.create(url.toString());
- }
-
- /**
- * Get the parameters for the version request.
- *
- * @return a map of key-value map of the request parameters
- */
- private Map prepareParameters(){
- var parameters = new HashMap();
-
- parameters.put("loaders", List.of(loader).toString());
- if(minecraftVersion != null) parameters.put("game_versions", List.of(minecraftVersion).toString());
- if(featured != null) parameters.put("featured", featured.toString());
-
- parameters.put("include_changelog", "false");
- return parameters;
- }
-
- /**
- * Only get featured or non-featured versions.
- * Null represent no filter.
- * @param featured should be restricted to featured version ? default null if not called
- * @return this
- */
- public ModrinthUpdateChecker setFeatured(@Nullable Boolean featured) {
- this.featured = featured;
- return this;
- }
-
- /**
- * Function called on error calling the api.
- * @param onError What should happen on error
- * @return this
- */
- public ModrinthUpdateChecker setOnError(@Nullable Consumer onError) {
- this.onError = onError;
- return this;
- }
-
- /**
- * Set the function to get raw version from the modrinth version.
- * If null provided raw version will act as in the identity function.
- * @param getRawVersion The function transforming modrinth version to raw version
- * @return this
- */
- public ModrinthUpdateChecker setGetRawVersion(@Nullable Function getRawVersion) {
- this.getRawVersion = getRawVersion;
- return this;
- }
-}
\ No newline at end of file
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/PluginSetDefault.java b/src/main/java/xyz/alexcrea/cuanvil/update/PluginSetDefault.java
deleted file mode 100644
index 707a218..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/PluginSetDefault.java
+++ /dev/null
@@ -1,98 +0,0 @@
-package xyz.alexcrea.cuanvil.update;
-
-import io.delilaheve.CustomAnvil;
-import io.delilaheve.util.ConfigOptions;
-import org.bukkit.configuration.file.FileConfiguration;
-import org.jetbrains.annotations.NotNull;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.util.MetricType;
-import xyz.alexcrea.cuanvil.util.config.LoreEditConfigUtil;
-import xyz.alexcrea.cuanvil.util.config.LoreEditType;
-
-import static io.delilaheve.util.ConfigOptions.*;
-import static xyz.alexcrea.cuanvil.util.config.LoreEditConfigUtil.*;
-
-public class PluginSetDefault {
-
- public static void reAddMissingDefault() {
- FileConfiguration config = ConfigHolder.DEFAULT_CONFIG.getConfig();
-
- int nbSet = 0;
-
- nbSet += trySetDefault(config, METRIC_TYPE, MetricType.AUTO.getValue());
- nbSet += trySetDefault(config, METRIC_COLLECT_ERROR, true);
-
- nbSet += trySetDefault(config, CAP_ANVIL_COST, DEFAULT_CAP_ANVIL_COST);
- nbSet += trySetDefault(config, MAX_ANVIL_COST, DEFAULT_MAX_ANVIL_COST);
- nbSet += trySetDefault(config, REMOVE_ANVIL_COST_LIMIT, DEFAULT_REMOVE_ANVIL_COST_LIMIT);
- nbSet += trySetDefault(config, REPLACE_TOO_EXPENSIVE, DEFAULT_REPLACE_TOO_EXPENSIVE);
- nbSet += trySetDefault(config, ITEM_REPAIR_COST, DEFAULT_ITEM_REPAIR_COST);
- nbSet += trySetDefault(config, UNIT_REPAIR_COST, DEFAULT_UNIT_REPAIR_COST);
- nbSet += trySetDefault(config, ITEM_RENAME_COST, DEFAULT_ITEM_RENAME_COST);
- nbSet += trySetDefault(config, SACRIFICE_ILLEGAL_COST, DEFAULT_SACRIFICE_ILLEGAL_COST);
- nbSet += trySetDefault(config, ConfigOptions.ALLOW_COLOR_CODE, ConfigOptions.DEFAULT_ALLOW_COLOR_CODE);
- nbSet += trySetDefault(config, ALLOW_HEXADECIMAL_COLOR, DEFAULT_ALLOW_HEXADECIMAL_COLOR);
- nbSet += trySetDefault(config, PERMISSION_NEEDED_FOR_COLOR, DEFAULT_PERMISSION_NEEDED_FOR_COLOR);
- nbSet += trySetDefault(config, USE_OF_COLOR_COST, DEFAULT_USE_OF_COLOR_COST);
- nbSet += trySetDefault(config, PER_COLOR_CODE_PERMISSION, DEFAULT_PER_COLOR_CODE_PERMISSION);
-
- // Lore Edit defaults
- for (@NotNull LoreEditType value : LoreEditType.values()) {
- String path = value.getRootPath() + ".";
-
- nbSet += trySetDefault(config, path + IS_ENABLED, DEFAULT_IS_ENABLED);
- nbSet += trySetDefault(config, path + FIXED_COST, DEFAULT_FIXED_COST);
-
- nbSet += trySetDefault(config, path + DO_CONSUME, DEFAULT_DO_CONSUME);
- if (value.isMultiLine()) {
- nbSet += trySetDefault(config, path + PER_LINE_COST, DEFAULT_PER_LINE_COST);
- }
- if (value.isAppend()) {
- nbSet += trySetDefault(config, path + LoreEditConfigUtil.ALLOW_COLOR_CODE, LoreEditConfigUtil.DEFAULT_ALLOW_COLOR_CODE);
- nbSet += trySetDefault(config, path + ALLOW_HEX_COLOR, DEFAULT_ALLOW_HEX_COLOR);
- nbSet += trySetDefault(config, path + USE_COLOR_COST, DEFAULT_USE_COLOR_COST);
- } else {
- nbSet += trySetDefault(config, path + REMOVE_COLOR_COST, DEFAULT_REMOVE_COLOR_COST);
- }
- }
-
- nbSet += trySetDefault(config, BOOK_PERMISSION_NEEDED, DEFAULT_BOOK_PERMISSION_NEEDED);
- nbSet += trySetDefault(config, PAPER_PERMISSION_NEEDED, DEFAULT_PAPER_PERMISSION_NEEDED);
-
- nbSet += trySetDefault(config, PAPER_EDIT_ORDER, DEFAULT_PAPER_EDIT_ORDER);
-
- nbSet += trySetDefault(config, DIALOG_RENAME_ENABLED, DEFAULT_DIALOG_RENAME_ENABLED);
- nbSet += trySetDefault(config, DIALOG_MAX_SIZE, DEFAULT_DIALOG_MAX_SIZE);
- nbSet += trySetDefault(config, DIALOG_RENAME_USE_PERMISSION, DEFAULT_DIALOG_RENAME_USE_PERMISSION);
- nbSet += trySetDefault(config, DIALOG_KEEP_USER_TEXT, DEFAULT_DIALOG_KEEP_USER_TEXT);
-
- if (nbSet > 0) {
- CustomAnvil.instance.getLogger().info("Adding " + nbSet + " absent default config values.");
- ConfigHolder.DEFAULT_CONFIG.saveToDisk(true);
- }
-
- }
-
- private static int trySetDefault(@NotNull FileConfiguration config, @NotNull String path, @NotNull String value) {
- if (config.isSet(path)) return 0;
-
- config.set(path, value);
- return 1;
- }
-
- private static int trySetDefault(@NotNull FileConfiguration config, @NotNull String path, int value) {
- if (config.isSet(path)) return 0;
-
- config.set(path, value);
- return 1;
- }
-
- private static int trySetDefault(@NotNull FileConfiguration config, @NotNull String path, boolean value) {
- if (config.isSet(path)) return 0;
-
- config.set(path, value);
- return 1;
- }
-
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/UpdateHandler.java b/src/main/java/xyz/alexcrea/cuanvil/update/UpdateHandler.java
deleted file mode 100644
index 660accb..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/UpdateHandler.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package xyz.alexcrea.cuanvil.update;
-
-import io.delilaheve.CustomAnvil;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.update.minecraft.MCUpdate;
-import xyz.alexcrea.cuanvil.update.minecraft.Update_1_21;
-import xyz.alexcrea.cuanvil.update.minecraft.Update_1_21_11;
-import xyz.alexcrea.cuanvil.update.minecraft.Update_1_21_9;
-import xyz.alexcrea.cuanvil.update.plugin.*;
-
-import javax.annotation.Nonnull;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Consumer;
-
-public class UpdateHandler {
-
- private static final String CONFIG_VERSION_PATH = "configVersion";
-
- // Handle mc version update then plugin version update
- public static void handleUpdates() {
- handleMCVersionUpdate();
- handlePluginUpdate();
- }
-
- private static final Map>> pUpdateMap = Map.of(
- new Version(1, 6, 2), PUpdate_1_6_2::handleUpdate,
- new Version(1, 6, 7), PUpdate_1_6_7::handleUpdate,
- new Version(1, 8, 0), PUpdate_1_8_0::handleUpdate,
- new Version(1, 11, 0), PUpdate_1_11_0::handleUpdate,
- new Version(1, 15, 5), PUpdate_1_15_5::handleUpdate,
- new Version(1, 15, 6), PUpdate_1_15_6::handleUpdate
- );
-
- private static final List mcUpdateMap = List.of(
- new Update_1_21(),
- new Update_1_21_9(),
- new Update_1_21_11()
- );
-
- // Handle only plugin update
- private static void handlePluginUpdate() {
- String versionString = ConfigHolder.DEFAULT_CONFIG.getConfig().getString(CONFIG_VERSION_PATH);
- Version current = versionString == null ? new Version(0) : Version.fromString(versionString);
-
- Set toSave = new HashSet<>();
-
- AtomicReference latest = new AtomicReference<>(null);
-
- // Hopefully, should iterate in the "insertion" order
- pUpdateMap.forEach((ver, consumer) -> {
- if (ver.greaterThan(current)) {
- CustomAnvil.log("handling plugin update to " + ver);
- consumer.accept(toSave);
-
- latest.set(ver);
- }
- });
-
- if (latest.get() != null) {
- finishConfiguration(latest.get().toString(), toSave);
- }
- }
-
- // Handle minecraft version update (not plugin version update)
- public static void handleMCVersionUpdate() {
- Version current = UpdateUtils.currentMinecraftVersion();
-
- boolean hadUpdate = false;
- for (MCUpdate mcUpdate : mcUpdateMap) {
- hadUpdate |= mcUpdate.handleUpdate(current, hadUpdate);
- }
-
- if (hadUpdate) {
- CustomAnvil.instance.getLogger().info("Updating Done !");
- }
-
- if(current.major() == 1 && current.minor() < 21) {
- var logger = CustomAnvil.instance.getLogger();
- logger.warning("Your are running an old version of minecraft (lower than 1.21)");
- logger.warning("Custom Anvil will stop supporting this version on the first of july 2026");
- }
- }
-
- private static void finishConfiguration(@Nonnull String newVersion, @Nonnull Set toSave) {
- CustomAnvil.instance.getLogger().info("Configuration file updated to " + newVersion);
- ConfigHolder.DEFAULT_CONFIG.getConfig().set(CONFIG_VERSION_PATH, newVersion);
-
- toSave.add(ConfigHolder.DEFAULT_CONFIG);
- // save
- for (ConfigHolder configHolder : toSave) {
- configHolder.saveToDisk(true);
- }
-
- // then reload
- for (ConfigHolder configHolder : toSave) {
- configHolder.reload();
- }
-
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/UpdateUtils.java b/src/main/java/xyz/alexcrea/cuanvil/update/UpdateUtils.java
index 2907fef..6448ced 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/update/UpdateUtils.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/update/UpdateUtils.java
@@ -1,6 +1,5 @@
package xyz.alexcrea.cuanvil.update;
-import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.ArrayList;
@@ -8,29 +7,23 @@ import java.util.Arrays;
import java.util.List;
public class UpdateUtils {
- public static final String MINECRAFT_VERSION_PATH = "lowMinecraftVersion";
+ public final static String MINECRAFT_VERSION_PATH = "lowMinecraftVersion";
- public static Version currentMinecraftVersion() {
- String versionString = Bukkit.getServer().getBukkitVersion().split("-")[0];
- return Version.fromString(versionString);
+ static int[] readVersionFromString(String versionString){
+ String[] partialVersion = versionString.split("\\.");
+ int[] versionParts = new int[]{0, 0, 0};
+
+ for (int i = 0; i < Math.min(3, partialVersion.length); i++) {
+ versionParts[i] = Integer.parseInt(partialVersion[i]);
+ }
+ return versionParts;
}
- public static void addToStringList(FileConfiguration config, String path, String... toAdd) {
+ static void addToStringList(FileConfiguration config, String path, String... toAdd){
List groups = new ArrayList<>(config.getStringList(path));
groups.addAll(Arrays.asList(toAdd));
config.set(path, groups);
}
- public static void addAbsentToList(FileConfiguration config, String path, String... toAdd) {
- List groups = new ArrayList<>(config.getStringList(path));
- for (String val : toAdd) {
- if (groups.contains(val)) continue;
-
- groups.add(val);
- }
- config.set(path, groups);
-
- }
-
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/Update_1_21.java b/src/main/java/xyz/alexcrea/cuanvil/update/Update_1_21.java
new file mode 100644
index 0000000..dca039a
--- /dev/null
+++ b/src/main/java/xyz/alexcrea/cuanvil/update/Update_1_21.java
@@ -0,0 +1,98 @@
+package xyz.alexcrea.cuanvil.update;
+
+import io.delilaheve.CustomAnvil;
+import org.bukkit.Bukkit;
+import org.bukkit.configuration.file.FileConfiguration;
+import xyz.alexcrea.cuanvil.config.ConfigHolder;
+
+import static xyz.alexcrea.cuanvil.update.UpdateUtils.addToStringList;
+
+// This is a temporary class that aim to handle 1.21 update.
+// It will be replaced by a better system later.
+public class Update_1_21 {
+
+ public static void handleUpdate(){
+ // Assume if version path is not null then it's 1.21
+ String oldVersion = ConfigHolder.DEFAULT_CONFIG.getConfig().getString(UpdateUtils.MINECRAFT_VERSION_PATH);
+ if(oldVersion != null){
+ int[] versionParts = UpdateUtils.readVersionFromString(oldVersion);
+
+ // Test 1.21
+ if((versionParts[0] >= 1) && (versionParts[1] >= 21)){
+ return;
+ }
+ }
+
+ String versionString = Bukkit.getServer().getBukkitVersion().split("-")[0];
+ int[] versionParts = UpdateUtils.readVersionFromString(versionString);
+
+ // Test 1.21
+ if((versionParts[0] >= 1) && (versionParts[1] >= 21)){
+ doUpdate();
+ }
+
+ }
+
+ private static void doUpdate() {
+ CustomAnvil.instance.getLogger().info("Updating config to support 1.21 ...");
+
+ FileConfiguration baseConfig = ConfigHolder.DEFAULT_CONFIG.getConfig();
+ FileConfiguration groupConfig = ConfigHolder.ITEM_GROUP_HOLDER.getConfig();
+ FileConfiguration conflictConfig = ConfigHolder.CONFLICT_HOLDER.getConfig();
+
+ // Add mace to groups
+ groupConfig.set("mace.type", "include");
+ addToStringList(groupConfig, "mace.items", "mace");
+
+ addToStringList(groupConfig, "can_unbreak.groups", "mace");
+
+ // Add new enchant conflicts
+ addToStringList(conflictConfig, "restriction_density.enchantments", "density");
+ addToStringList(conflictConfig, "restriction_density.notAffectedGroups", "mace");
+
+ addToStringList(conflictConfig, "restriction_breach.enchantments", "breach");
+ addToStringList(conflictConfig, "restriction_breach.notAffectedGroups", "mace");
+
+ addToStringList(conflictConfig, "restriction_wind_burst.enchantments", "wind_burst");
+ addToStringList(conflictConfig, "restriction_wind_burst.notAffectedGroups", "mace");
+
+ // Add mace to conflicts
+ addToStringList(conflictConfig, "restriction_fire_aspect.notAffectedGroups", "mace");
+ addToStringList(conflictConfig, "restriction_smite.notAffectedGroups", "mace");
+ addToStringList(conflictConfig, "restriction_bane_of_arthropods.notAffectedGroups", "mace");
+
+ addToStringList(conflictConfig, "mace_enchant_conflict.enchantments", "density", "breach", "smite", "bane_of_arthropods");
+ conflictConfig.set("mace_enchant_conflict.maxEnchantmentBeforeConflict", 1);
+
+ // Add level limit
+ baseConfig.set("enchant_limits.density", 5);
+ baseConfig.set("enchant_limits.breach", 4);
+ baseConfig.set("enchant_limits.wind_burst", 3);
+
+ // Add enchant values
+ baseConfig.set("enchant_values.density.item", 1);
+ baseConfig.set("enchant_values.density.book", 1);
+
+ baseConfig.set("enchant_values.breach.item", 4);
+ baseConfig.set("enchant_values.breach.book", 2);
+
+ baseConfig.set("enchant_values.wind_burst.item", 4);
+ baseConfig.set("enchant_values.wind_burst.book", 2);
+
+ // Set version string as 1.21
+ baseConfig.set(UpdateUtils.MINECRAFT_VERSION_PATH, "1.21");
+
+ // Save
+ ConfigHolder.DEFAULT_CONFIG.saveToDisk(true);
+ ConfigHolder.ITEM_GROUP_HOLDER.saveToDisk(true);
+ ConfigHolder.CONFLICT_HOLDER.saveToDisk(true);
+
+ // imply reload of CONFLICT_HOLDER
+ // We also do not need to reload base config as there is no object related to it.
+ ConfigHolder.ITEM_GROUP_HOLDER.reload();
+
+ CustomAnvil.instance.getLogger().info("Updating Done !");
+
+ }
+
+}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/Version.java b/src/main/java/xyz/alexcrea/cuanvil/update/Version.java
deleted file mode 100644
index a49fbdd..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/Version.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package xyz.alexcrea.cuanvil.update;
-
-import org.jetbrains.annotations.NotNull;
-
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
-public record Version(int major, int minor, int patch) {
-
- public Version(int major, int minor){
- this(major, minor, 0);
- }
- public Version(int major){
- this(major, 0, 0);
- }
-
- public static Version fromString(@Nullable String versionString){
- if(versionString == null) return new Version(0, 0, 0);
-
- String[] partialVersion = versionString.split("\\.");
- int[] versionParts = new int[]{0, 0, 0};
-
- for (int i = 0; i < Math.min(3, partialVersion.length); i++) {
- try {
- versionParts[i] = Integer.parseInt(partialVersion[i]);
- } catch (NumberFormatException e) {
- break;
- }
- }
- return new Version(versionParts[0], versionParts[1], versionParts[2]);
- }
-
- public boolean greaterThan(@Nonnull Version other){
- return this.major > other.major || (this.major == other.major &&
- (this.minor > other.minor || (this.minor == other.minor &&
- this.patch > other.patch)));
- }
-
- public boolean greaterEqual(@Nonnull Version other){
- return this.major > other.major || (this.major == other.major &&
- (this.minor > other.minor || (this.minor == other.minor &&
- this.patch >= other.patch)));
- }
-
- public boolean lesserThan(@Nonnull Version other){
- return this.major < other.major || (this.major == other.major &&
- (this.minor < other.minor || (this.minor == other.minor &&
- this.patch < other.patch)));
- }
-
- public boolean lesserEqual(@Nonnull Version other){
- return this.major < other.major || (this.major == other.major &&
- (this.minor < other.minor || (this.minor == other.minor &&
- this.patch <= other.patch)));
- }
-
- @NotNull
- @Override
- public String toString() {
- return major + "." + minor + "." + patch;
- }
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/MCUpdate.java b/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/MCUpdate.java
deleted file mode 100644
index 40fc587..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/MCUpdate.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package xyz.alexcrea.cuanvil.update.minecraft;
-
-import io.delilaheve.CustomAnvil;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.update.UpdateUtils;
-import xyz.alexcrea.cuanvil.update.Version;
-
-public abstract class MCUpdate {
-
- public final Version version;
-
- public MCUpdate(Version version){
- this.version = version;
- }
-
- public boolean handleUpdate(Version current, boolean hadUpdate){
- // Test if we are running in this update version or better
- if(version.greaterThan(current))
- return false;
-
- // if version path is not null then check if its it's before this update version
- String oldVersion = ConfigHolder.DEFAULT_CONFIG.getConfig().getString(UpdateUtils.MINECRAFT_VERSION_PATH);
- if(oldVersion != null){
- var version = Version.fromString(oldVersion);
- if(this.version.lesserEqual(version)) return false;
- }
-
- if(!hadUpdate){
- CustomAnvil.instance.getLogger().info("Updating config to support minecraft " + current +" ...");
- }
- doUpdate();
- return true;
- }
-
- protected abstract void doUpdate();
-
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21.java b/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21.java
deleted file mode 100644
index 3aa6073..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21.java
+++ /dev/null
@@ -1,79 +0,0 @@
-package xyz.alexcrea.cuanvil.update.minecraft;
-
-import io.delilaheve.CustomAnvil;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.update.UpdateUtils;
-import xyz.alexcrea.cuanvil.update.Version;
-
-import static xyz.alexcrea.cuanvil.update.UpdateUtils.addAbsentToList;
-
-public class Update_1_21 extends MCUpdate {
-
- public Update_1_21() {
- super(new Version(1, 21));
- }
-
- @Override
- protected void doUpdate() {
- var baseConfig = ConfigHolder.DEFAULT_CONFIG.getConfig();
- var groupConfig = ConfigHolder.ITEM_GROUP_HOLDER.getConfig();
- var conflictConfig = ConfigHolder.CONFLICT_HOLDER.getConfig();
- var unitConfig = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
-
- // Add mace to groups
- groupConfig.set("mace.type", "include");
- addAbsentToList(groupConfig, "mace.items", "mace");
-
- addAbsentToList(groupConfig, "can_unbreak.groups", "mace");
-
- // Add new enchant conflicts
- addAbsentToList(conflictConfig, "restriction_density.enchantments", "minecraft:density");
- addAbsentToList(conflictConfig, "restriction_density.notAffectedGroups", "mace", "enchanted_book");
-
- addAbsentToList(conflictConfig, "restriction_breach.enchantments", "minecraft:breach");
- addAbsentToList(conflictConfig, "restriction_breach.notAffectedGroups", "mace", "enchanted_book");
-
- addAbsentToList(conflictConfig, "restriction_wind_burst.enchantments", "minecraft:wind_burst");
- addAbsentToList(conflictConfig, "restriction_wind_burst.notAffectedGroups", "mace", "enchanted_book");
-
- // Add mace to conflicts
- addAbsentToList(conflictConfig, "restriction_fire_aspect.notAffectedGroups", "mace");
- addAbsentToList(conflictConfig, "restriction_smite.notAffectedGroups", "mace");
- addAbsentToList(conflictConfig, "restriction_bane_of_arthropods.notAffectedGroups", "mace");
-
- addAbsentToList(conflictConfig, "sword_enchant_conflict.enchantments",
- "minecraft:density", "minecraft:breach");
-
- // Add level limit
- baseConfig.set("enchant_limits.minecraft:density", 5);
- baseConfig.set("enchant_limits.minecraft:breach", 4);
- baseConfig.set("enchant_limits.minecraft:wind_burst", 3);
-
- // Add enchant values
- baseConfig.set("enchant_values.minecraft:density.item", 2);
- baseConfig.set("enchant_values.minecraft:density.book", 1);
-
- baseConfig.set("enchant_values.minecraft:breach.item", 4);
- baseConfig.set("enchant_values.minecraft:breach.book", 2);
-
- baseConfig.set("enchant_values.minecraft:wind_burst.item", 4);
- baseConfig.set("enchant_values.minecraft:wind_burst.book", 2);
-
- // Add unit repair for mace
- unitConfig.set("breeze_rod.mace", 0.25);
-
- // Set version string as current
- baseConfig.set(UpdateUtils.MINECRAFT_VERSION_PATH, version.toString());
-
- // Save
- ConfigHolder.DEFAULT_CONFIG.saveToDisk(true);
- ConfigHolder.ITEM_GROUP_HOLDER.saveToDisk(true);
- ConfigHolder.CONFLICT_HOLDER.saveToDisk(true);
- ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(true);
-
- // imply reload of CONFLICT_HOLDER
- // We also do not need to reload base config as there is no object related to it.
- ConfigHolder.ITEM_GROUP_HOLDER.reload();
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21_11.java b/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21_11.java
deleted file mode 100644
index d639596..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21_11.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package xyz.alexcrea.cuanvil.update.minecraft;
-
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.update.UpdateUtils;
-import xyz.alexcrea.cuanvil.update.Version;
-
-import static xyz.alexcrea.cuanvil.update.UpdateUtils.addAbsentToList;
-
-public class Update_1_21_11 extends MCUpdate{
-
- public Update_1_21_11() {
- super(new Version(1, 21, 11));
- }
-
- @Override
- protected void doUpdate() {
- var baseConfig = ConfigHolder.DEFAULT_CONFIG.getConfig();
- var groupConfig = ConfigHolder.ITEM_GROUP_HOLDER.getConfig();
- var conflictConfig = ConfigHolder.CONFLICT_HOLDER.getConfig();
- var unitConfig = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
-
- // Create spear group
- groupConfig.set("spears.type", "include");
- addAbsentToList(groupConfig, "spears.items",
- "wooden_spear",
- "golden_spear",
- "stone_spear",
- "copper_spear",
- "iron_spear",
- "diamond_spear",
- "netherite_spear");
-
- // Add spear group to super group and enchantments
- addAbsentToList(groupConfig, "melee_weapons.groups", "spears");
-
- addAbsentToList(conflictConfig, "restriction_looting.notAffectedGroups", "spears");
- addAbsentToList(conflictConfig, "restriction_knockback.notAffectedGroups", "spears");
- addAbsentToList(conflictConfig, "restriction_fire_aspect.notAffectedGroups", "spears");
-
- // Unit repair for spears
- unitConfig.set("gold_ingot.golden_spear", 0.25);
- unitConfig.set("copper_ingot.copper_spear", 0.25);
- unitConfig.set("iron_ingot.iron_spear", 0.25);
- unitConfig.set("diamond.diamond_spear", 0.25);
- unitConfig.set("netherite_ingot.netherite_spear", 0.25);
-
- unitConfig.set("cobblestone.stone_spear", 0.25);
- unitConfig.set("cobbled_deepslate.stone_spear", 0.25);
-
- unitConfig.set("oak_planks.wooden_spear", 0.25);
- unitConfig.set("spruce_planks.wooden_spear", 0.25);
- unitConfig.set("birch_planks.wooden_spear", 0.25);
- unitConfig.set("jungle_planks.wooden_spear", 0.25);
- unitConfig.set("acacia_planks.wooden_spear", 0.25);
- unitConfig.set("dark_oak_planks.wooden_spear", 0.25);
- unitConfig.set("mangrove_planks.wooden_spear", 0.25);
- unitConfig.set("cherry_planks.wooden_spear", 0.25);
- unitConfig.set("bamboo_planks.wooden_spear", 0.25);
- unitConfig.set("crimson_planks.wooden_spear", 0.25);
- unitConfig.set("warped_planks.wooden_spear", 0.25);
-
- // Create lunge enchant value and group
- baseConfig.set("enchant_limits.minecraft:lunge", 3);
- baseConfig.set("enchant_values.minecraft:lunge.item", 2);
- baseConfig.set("enchant_values.minecraft:lunge.book", 1);
-
- addAbsentToList(conflictConfig, "restriction_lunge.enchantments", "minecraft:lunge");
- addAbsentToList(conflictConfig, "restriction_lunge.notAffectedGroups", "spears", "enchanted_book");
-
- // Set version string as current
- baseConfig.set(UpdateUtils.MINECRAFT_VERSION_PATH, version.toString());
-
- // Save
- ConfigHolder.DEFAULT_CONFIG.saveToDisk(true);
- ConfigHolder.ITEM_GROUP_HOLDER.saveToDisk(true);
- ConfigHolder.CONFLICT_HOLDER.saveToDisk(true);
- ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(true);
-
- // imply reload of CONFLICT_HOLDER
- // We also do not need to reload base config as there is no object related to it.
- ConfigHolder.ITEM_GROUP_HOLDER.reload();
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21_9.java b/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21_9.java
deleted file mode 100644
index d289b9b..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/minecraft/Update_1_21_9.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package xyz.alexcrea.cuanvil.update.minecraft;
-
-import org.bukkit.configuration.file.FileConfiguration;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.update.UpdateUtils;
-import xyz.alexcrea.cuanvil.update.Version;
-
-import static xyz.alexcrea.cuanvil.update.UpdateUtils.addAbsentToList;
-
-public class Update_1_21_9 extends MCUpdate{
-
- public Update_1_21_9() {
- super(new Version(1, 21, 9));
- }
-
- @Override
- protected void doUpdate() {
- var baseConfig = ConfigHolder.DEFAULT_CONFIG.getConfig();
- var groupConfig = ConfigHolder.ITEM_GROUP_HOLDER.getConfig();
- var unitConfig = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
-
- // Add cooper items to groups
- addAbsentToList(groupConfig, "helmets.items", "copper_helmet");
- addAbsentToList(groupConfig, "chestplate.items", "copper_chestplate");
- addAbsentToList(groupConfig, "leggings.items", "copper_leggings");
- addAbsentToList(groupConfig, "boots.items", "copper_boots");
-
- addAbsentToList(groupConfig, "pickaxes.items", "copper_pickaxe");
- addAbsentToList(groupConfig, "shovels.items", "copper_shovel");
- addAbsentToList(groupConfig, "hoes.items", "copper_hoe");
- addAbsentToList(groupConfig, "axes.items", "copper_axe");
- addAbsentToList(groupConfig, "swords.items", "copper_sword");
-
- // Add unit repair
- addCopperUnitRepair(unitConfig);
-
- // Set version string as current
- baseConfig.set(UpdateUtils.MINECRAFT_VERSION_PATH, version.toString());
-
- // Save
- ConfigHolder.DEFAULT_CONFIG.saveToDisk(true);
- ConfigHolder.ITEM_GROUP_HOLDER.saveToDisk(true);
- ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(true);
-
- // imply reload of CONFLICT_HOLDER
- // We also do not need to reload base config as there is no object related to it.
- ConfigHolder.ITEM_GROUP_HOLDER.reload();
- }
-
- public static void addCopperUnitRepair(FileConfiguration unitConfig) {
- // Add unit repair
- unitConfig.set("copper_ingot.copper_helmet", 0.25);
- unitConfig.set("copper_ingot.copper_chestplate", 0.25);
- unitConfig.set("copper_ingot.copper_leggings", 0.25);
- unitConfig.set("copper_ingot.copper_boots", 0.25);
-
- unitConfig.set("copper_ingot.copper_pickaxe", 0.25);
- unitConfig.set("copper_ingot.copper_shovel", 0.25);
- unitConfig.set("copper_ingot.copper_hoe", 0.25);
- unitConfig.set("copper_ingot.copper_axe", 0.25);
- unitConfig.set("copper_ingot.copper_sword", 0.25);
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_11_0.java b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_11_0.java
deleted file mode 100644
index 9740971..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_11_0.java
+++ /dev/null
@@ -1,137 +0,0 @@
-package xyz.alexcrea.cuanvil.update.plugin;
-
-import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
-import org.bukkit.configuration.ConfigurationSection;
-import org.bukkit.configuration.file.FileConfiguration;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import xyz.alexcrea.cuanvil.api.MaterialGroupApi;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.group.AbstractMaterialGroup;
-import xyz.alexcrea.cuanvil.group.IncludeGroup;
-
-import javax.annotation.Nonnull;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-import static xyz.alexcrea.cuanvil.update.UpdateUtils.addAbsentToList;
-
-public class PUpdate_1_11_0 {
-
- private static final List mace_expected = List.of(
- "density",
- "breach",
- "smite",
- "bane_of_arthropods"
- );
- private static final List sword_expected = List.of(
- "sharpness",
- "smite",
- "bane_of_arthropods"
- );
-
- private static final Material[] PICKAXES = new Material[]{
- Material.WOODEN_PICKAXE, Material.STONE_PICKAXE,
- Material.IRON_PICKAXE, Material.DIAMOND_PICKAXE,
- Material.GOLDEN_PICKAXE, Material.NETHERITE_PICKAXE
- };
-
- private static final Material[] SHOVELS = new Material[]{
- Material.WOODEN_SHOVEL, Material.STONE_SHOVEL,
- Material.IRON_SHOVEL, Material.DIAMOND_SHOVEL,
- Material.GOLDEN_SHOVEL, Material.NETHERITE_SHOVEL
- };
-
- private static final Material[] HOES = new Material[]{
- Material.WOODEN_HOE, Material.STONE_HOE,
- Material.IRON_HOE, Material.DIAMOND_HOE,
- Material.GOLDEN_HOE, Material.NETHERITE_HOE
- };
-
- public static void handleUpdate(@Nonnull Set toSave) {
- handleToolsMigration();
- handleMaceMigration(toSave);
- }
-
- private static void handleToolsMigration() {
- // We migrate the mace conflict if exist and unmodified
- AbstractMaterialGroup tools = MaterialGroupApi.getGroup("tools");
-
- migrateTools(tools, "pickaxes", PICKAXES);
- migrateTools(tools, "shovels", SHOVELS);
- migrateTools(tools, "hoes", HOES);
- }
-
- private static void migrateTools(
- @Nullable AbstractMaterialGroup tools,
- @NotNull String toolset,
- @NotNull Material[] toolMats) {
-
- // Create new group
- IncludeGroup group = new IncludeGroup(toolset);
- NamespacedKey[] keys = new NamespacedKey[toolMats.length];
- for (int i = 0; i < toolMats.length; i++) {
- keys[i] = toolMats[i].getKey();
- }
-
- group.addAll(keys);
-
- MaterialGroupApi.addMaterialGroup(group, true);
-
- // Try to see if all the materials was in the tools group. and if so, replace it with the new group
- if (tools == null) return;
- if (!(tools instanceof IncludeGroup include)) return;
-
- List mats = List.of(keys);
- Set