().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..e661a74 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -1,22 +1,36 @@
+import java.net.URI
+
rootProject.name = "CustomAnvil"
+// for Disenchantment dependency
+sourceControl {
+ gitRepository(URI.create("https://github.com/H7KZ/Disenchantment.git")) {
+ producesModule("cz.kominekjan:Disenchantment")
+ }
+}
+
// 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
+include("nms:v1_17R1")
+findProject(":nms:v1_17R1")?.name = "v1_17R1"
+include("nms:v1_18R1")
+findProject(":nms:v1_18R1")?.name = "v1_18R1"
+include("nms:v1_18R2")
+findProject(":nms:v1_18R2")?.name = "v1_18R2"
+include("nms:v1_19R1")
+findProject(":nms:v1_19R1")?.name = "v1_19R1"
+include("nms:v1_19R2")
+findProject(":nms:v1_19R2")?.name = "v1_19R2"
+include("nms:v1_19R3")
+findProject(":nms:v1_19R3")?.name = "v1_19R3"
+include("nms:v1_20R1")
+findProject(":nms:v1_20R1")?.name = "v1_20R1"
+include("nms:v1_20R2")
+findProject(":nms:v1_20R2")?.name = "v1_20R2"
+include("nms:v1_20R3")
+findProject(":nms:v1_20R3")?.name = "v1_20R3"
+include("nms:v1_20R4")
+findProject(":nms:v1_20R4")?.name = "v1_20R4"
+include("nms:v1_21R1")
+findProject(":nms:v1_21R1")?.name = "v1_21R1"
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..ad01827 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/ConflictAPI.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/ConflictAPI.java
@@ -19,8 +19,7 @@ import java.util.List;
@SuppressWarnings("unused")
public class ConflictAPI {
- private ConflictAPI() {
- }
+ private ConflictAPI() {}
private static Object saveChangeTask = null;
private static Object reloadChangeTask = null;
@@ -28,32 +27,31 @@ public class ConflictAPI {
/**
* 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,9 +151,9 @@ public class ConflictAPI {
* Prepare a task to save conflict configuration.
*/
private static void prepareSaveTask() {
- if (saveChangeTask != null) return;
+ if(saveChangeTask != null) return;
- saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> {
+ saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, ()->{
ConfigHolder.CONFLICT_HOLDER.saveToDisk(true);
saveChangeTask = null;
});
@@ -167,28 +163,28 @@ public class ConflictAPI {
* Prepare a task to reload every conflict.
*/
private static void prepareUpdateTask() {
- if (reloadChangeTask != null) return;
+ if(reloadChangeTask != null) return;
- reloadChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> {
+ reloadChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, ()->{
ConfigHolder.CONFLICT_HOLDER.reload();
EnchantConflictGui conflictGui = EnchantConflictGui.getCurrentInstance();
- if (conflictGui != null) conflictGui.reloadValues();
+ if(conflictGui != null) conflictGui.reloadValues();
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..32db73b 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/CustomAnvilRecipeApi.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/CustomAnvilRecipeApi.java
@@ -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());
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java b/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java
index ac98225..01c5ed8 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java
@@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil;
-import io.delilaheve.util.ConfigOptions;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.enchantments.Enchantment;
@@ -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;
/**
@@ -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,37 +157,23 @@ 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());
}
/**
diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/MaterialGroupApi.java b/src/main/java/xyz/alexcrea/cuanvil/api/MaterialGroupApi.java
index cd71c7a..dd34eb6 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/MaterialGroupApi.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/MaterialGroupApi.java
@@ -3,7 +3,6 @@ package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil;
import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material;
-import org.bukkit.NamespacedKey;
import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -23,51 +22,49 @@ import java.util.*;
@SuppressWarnings("unused")
public class MaterialGroupApi {
- private MaterialGroupApi() {
- }
+ private MaterialGroupApi(){}
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,9 +180,9 @@ public class MaterialGroupApi {
* Prepare a task to reload every conflict.
*/
private static void prepareSaveTask() {
- if (saveChangeTask != null) return;
+ if(saveChangeTask != null) return;
- saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> {
+ saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, ()->{
ConfigHolder.ITEM_GROUP_HOLDER.saveToDisk(true);
saveChangeTask = null;
});
@@ -214,13 +192,13 @@ public class MaterialGroupApi {
* Prepare a task to save configuration.
*/
private static void prepareUpdateTask() {
- if (reloadChangeTask != null) return;
+ if(reloadChangeTask != null) return;
- reloadChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> {
+ reloadChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, ()->{
ConfigHolder.ITEM_GROUP_HOLDER.reload();
GroupConfigGui configGui = GroupConfigGui.getCurrentInstance();
- if (configGui != null) configGui.reloadValues();
+ if(configGui != null) configGui.reloadValues();
reloadChangeTask = null;
});
@@ -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..d471b19 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/api/UnitRepairApi.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/api/UnitRepairApi.java
@@ -9,7 +9,6 @@ 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;
@@ -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);
}
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
index d374999..95edca6 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/config/WorkPenaltyType.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/config/WorkPenaltyType.java
@@ -1,66 +1,114 @@
package xyz.alexcrea.cuanvil.config;
-import com.google.common.collect.ImmutableMap;
+import org.bukkit.Material;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.inventory.meta.ItemMeta;
+import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import xyz.alexcrea.cuanvil.anvil.AnvilUseType;
+import xyz.alexcrea.cuanvil.gui.config.settings.AbstractSettingGui;
+import xyz.alexcrea.cuanvil.gui.config.settings.EnumSettingGui;
-import java.util.EnumMap;
+import java.util.ArrayList;
+import java.util.List;
-public class WorkPenaltyType {
+public enum WorkPenaltyType implements EnumSettingGui.ConfigurableEnum {
+ DEFAULT("default", true, true, "§aDefault", Material.LIME_TERRACOTTA),
+ ADDITIVE("add_only", false, true, "§eAdd Only", Material.YELLOW_TERRACOTTA),
+ INCREASE("increase_only", true, false, "§eIncrease Only", Material.YELLOW_TERRACOTTA),
+ DISABLED("disabled", false, false, "§cDisabled", Material.RED_TERRACOTTA),
+ ;
- public record WorkPenaltyPart(
- boolean penaltyIncrease,
- boolean penaltyAdditive,
- boolean exclusivePenaltyIncrease,
- boolean exclusivePenaltyAdditive
- ) {
+ private final String name;
+ private final boolean penaltyIncrease;
+ private final boolean penaltyAdditive;
- @Override
- public boolean equals(Object obj) {
- if(!(obj instanceof WorkPenaltyPart other)) return false;
+ private final String configName;
+ private final Material configMaterial;
- return other.penaltyIncrease == this.penaltyIncrease &&
- other.penaltyAdditive == this.penaltyAdditive &&
- other.exclusivePenaltyIncrease == this.exclusivePenaltyIncrease &&
- other.exclusivePenaltyAdditive == this.exclusivePenaltyAdditive;
+ WorkPenaltyType(String name, boolean penaltyIncrease, boolean penaltyAdditive, String configName, Material configMaterial) {
+ this.name = name;
+ this.penaltyIncrease = penaltyIncrease;
+ this.penaltyAdditive = penaltyAdditive;
+ this.configName = configName;
+ this.configMaterial = configMaterial;
+ }
+
+ public boolean isPenaltyIncreasing() {
+ return penaltyIncrease;
+ }
+
+ public boolean isPenaltyAdditive() {
+ return penaltyAdditive;
+ }
+
+ private boolean doRepresentThisType(String toTest){
+ return name.equalsIgnoreCase(toTest);
+ }
+
+ @NotNull
+ public static WorkPenaltyType fromString(@Nullable String toTest){
+ if(toTest == null) return DEFAULT;
+
+ // Test if it matches any of values
+ for (WorkPenaltyType value : values()) {
+ if(value.doRepresentThisType(toTest)){
+ return value;
+ }
}
- public WorkPenaltyPart(boolean penaltyIncrease, boolean penaltyAdditive) {
- this(penaltyIncrease, penaltyAdditive, false, false);
- }
+ // Use default if not found
+ return DEFAULT;
}
- private final EnumMap partMap;
+ @NotNull
+ public static WorkPenaltyType next(@NotNull WorkPenaltyType now){
+ return switch (now){
+ case DEFAULT -> ADDITIVE;
+ case ADDITIVE -> INCREASE;
+ case INCREASE -> DISABLED;
+ case DISABLED -> DEFAULT;
- 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;
+ public ItemStack configurationGuiItem() {
+ ItemStack displayedItem = new ItemStack(this.configMaterial);
+ ItemMeta valueMeta = displayedItem.getItemMeta();
+ assert valueMeta != null;
- for (AnvilUseType type : AnvilUseType.getEntries()) {
- if(!getPenaltyInfo(type).equals(that.getPenaltyInfo(type))) return false;
- }
- return true;
+ valueMeta.setDisplayName(this.configName);
+
+ List lore = new ArrayList<>();
+
+ lore.add(configDisplayForAdd());
+ lore.add(configDisplayForIncrease());
+ lore.add("");
+
+ lore.add(AbstractSettingGui.CLICK_LORE);
+ valueMeta.setLore(lore);
+
+ displayedItem.setItemMeta(valueMeta);
+
+ return displayedItem;
}
+ public String configDisplayForAdd(){
+ return ("§7Add penalty: " + (penaltyAdditive ? "§aYes" : "§cNo"));
+ }
+
+ public String configDisplayForIncrease(){
+ return ("§7Increase penalty: " + (penaltyIncrease ? "§aYes" : "§cNo"));
+ }
+
+ @Override
+ public String configName() {
+ return this.name;
+ }
+
+ @Override
+ public String configurationGuiName() {
+ return this.configName;
+ }
}
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/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..6b062aa 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CABukkitEnchantment.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CABukkitEnchantment.java
@@ -1,7 +1,6 @@
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;
@@ -19,7 +18,6 @@ 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;
/**
@@ -27,17 +25,17 @@ import java.util.logging.Level;
*/
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 +51,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,20 +85,19 @@ 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) {
@@ -111,11 +107,10 @@ public class CABukkitEnchantment extends CAEnchantmentBase {
@NotNull
protected Enchantment getEnchant() {
- return this.bukkit;
+ return this.enchantment;
}
private static Method getAnvilCostMethod;
-
static {
Class clazz = Enchantment.class;
try {
@@ -148,27 +143,18 @@ public class CABukkitEnchantment extends CAEnchantmentBase {
}
private static EnchantmentRarity findRarity(Enchantment enchantment) {
- if (getAnvilCostMethod == null) return EnchantmentRarity.COMMON;
+ 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);
+ 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..ee5b9c0 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEnchantSquaredEnchantment.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/wrapped/CAEnchantSquaredEnchantment.java
@@ -16,20 +16,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 +61,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..4f98cc3 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/MainConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/MainConfigGui.java
@@ -30,7 +30,7 @@ public class MainConfigGui extends ChestGui {
public void init(PacketManager packetManager) {
Pattern pattern = new Pattern(
GuiSharedConstant.EMPTY_GUI_FULL_LINE,
- "012345678",
+ "012304567",
"Q00000000"
);
PatternPane pane = new PatternPane(0, 0, 9, 3, pattern);
@@ -62,18 +62,6 @@ public class MainConfigGui extends ChestGui {
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();
@@ -84,7 +72,7 @@ public class MainConfigGui extends ChestGui {
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);
@@ -96,20 +84,20 @@ public class MainConfigGui extends ChestGui {
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("§aGroups");
+ groupMeta.setLore(Collections.singletonList("§7Click 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);
@@ -121,7 +109,7 @@ public class MainConfigGui extends ChestGui {
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);
@@ -133,7 +121,7 @@ public class MainConfigGui extends ChestGui {
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);
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..2f76694 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectMaterialContainer.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/SelectMaterialContainer.java
@@ -1,35 +1,34 @@
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();
+ Set materialSet = container.getSelectedMaterials();
if (materialSet.isEmpty()) {
groupLore.add("§7There is no "+action+"d material for this "+containerType+".");
} else {
groupLore.add("§7List of "+action+"d materials for this "+containerType+":");
- Iterator materialIterator = materialSet.iterator();
+ 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());
+ String formattedName = CasedStringUtil.snakeToUpperSpacedCase(materialIterator.next().name().toLowerCase());
groupLore.add("§7- §e" + formattedName);
}
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..56bf848 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,7 +41,6 @@ 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;
}
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..b2d6afe 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){
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..a65b54b 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.
diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/BasicConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/BasicConfigGui.java
index 51936c7..d689921 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/BasicConfigGui.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/global/BasicConfigGui.java
@@ -14,13 +14,13 @@ 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.dependency.MinecraftVersionUtil;
+import xyz.alexcrea.cuanvil.config.WorkPenaltyType;
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
import xyz.alexcrea.cuanvil.gui.config.settings.BoolSettingsGui;
+import xyz.alexcrea.cuanvil.gui.config.settings.EnumSettingGui;
import xyz.alexcrea.cuanvil.gui.config.settings.IntSettingsGui;
-import xyz.alexcrea.cuanvil.gui.config.settings.WorkPenaltyTypeSettingGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
@@ -28,6 +28,7 @@ import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.List;
/**
* Global config to edit basic basic settings.
@@ -88,6 +89,8 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
private IntSettingsGui.IntSettingFactory itemRenameCost; // r character
private IntSettingsGui.IntSettingFactory sacrificeIllegalEnchantCost; // S character
+ private EnumSettingGui.EnumSettingFactory workPenaltyType; // W character
+
private BoolSettingsGui.BoolSettingFactory allowColorCode; // c character
private BoolSettingsGui.BoolSettingFactory allowHexColor; // h character
@@ -208,6 +211,46 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
ConfigOptions.DEFAULT_SACRIFICE_ILLEGAL_COST,
1, 5, 10, 50, 100);
+ // -------------
+ // Work Penalty
+ // -------------
+
+ this.workPenaltyType = new EnumSettingGui.EnumSettingFactory<>("§8Work Penalty Type", this,
+ ConfigOptions.WORK_PENALTY_TYPE, ConfigHolder.DEFAULT_CONFIG
+ ) {
+ @NotNull
+ @Override
+ public WorkPenaltyType getConfiguredValue() {
+ return ConfigOptions.INSTANCE.getWorkPenaltyType();
+ }
+
+ @NotNull
+ @Override
+ public WorkPenaltyType getDefault() {
+ return WorkPenaltyType.DEFAULT;
+ }
+
+ @NotNull
+ @Override
+ public List getDisplayLore(WorkPenaltyType value) {
+ return List.of(
+ "§7Work penalty increase the price for every anvil use.",
+ "§7This config allow you to choose the comportment of work penalty.",
+ "",
+ value.configDisplayForAdd(),
+ value.configDisplayForIncrease()
+
+ );
+ }
+
+ @NotNull
+ @Override
+ public WorkPenaltyType next(@NotNull WorkPenaltyType now) {
+ return WorkPenaltyType.next(now);
+ }
+
+ };
+
// -------------
// Color config
// -------------
@@ -284,7 +327,7 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
if(!this.packetManager.getCanSetInstantBuild()){
lore.add("");
- lore.add("§4/!\\§cCaution§4/!\\ §cYou need ProtocoLib installed and working or a paper server.");
+ lore.add("§4/!\\§cCaution§4/!\\ §cYou need ProtocoLib installed and working or a newer version of this plugin for this to work.");
lore.add("§cCurrently ProtocoLib is not detected.");
}
@@ -334,7 +377,7 @@ public class BasicConfigGui extends ChestGui implements ValueUpdatableGui {
pane.bindItem('S', illegalCostItem);
// work penalty type
- GuiItem workPenaltyType = WorkPenaltyTypeSettingGui.getDisplayItem(this, Material.DAMAGED_ANVIL, "§aWork Penalty Type");
+ GuiItem workPenaltyType = this.workPenaltyType.getItem(Material.DAMAGED_ANVIL, "§aWork Penalty Type");
pane.bindItem('W', workPenaltyType);
// allow color code
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..5a68e6e 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
@@ -14,22 +14,22 @@ 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 +44,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(
+ "§7Should work: §"+(shouldWork ? "aYes" : "cNo"),
+ "§7Exact count: §"+(recipe.getExactCount() ? "aYes" : "cNo"),
+ "§7Recipe Xp Cost: §e"+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 +87,7 @@ public class CustomRecipeConfigGui extends MappedGuiListConfigGui> {
+public class EnchantConflictGui extends MappedGuiListConfigGui {
private static EnchantConflictGui INSTANCE;
@@ -87,8 +86,8 @@ 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..6c44fac 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
@@ -44,16 +44,24 @@ public class EnchantCostConfigGui 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;
@@ -38,39 +37,17 @@ 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..8684d4d 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;
@@ -74,8 +73,8 @@ 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..833aea1 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
@@ -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/MappedGuiListConfigGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/MappedGuiListConfigGui.java
index 3aa18e0..cf4b852 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
@@ -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/UnitRepairElementListGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/list/UnitRepairElementListGui.java
index 35f8ebb..0bf2a03 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) {
+ @NotNull UnitRepairConfigGui parentGui,
+ @NotNull GuiItem parentItem) {
super("§e" + CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase()) + " §rUnit repair");
+ this.parentItem = parentItem;
this.parentMaterial = parentMaterial;
this.parentGui = parentGui;
this.materialName = CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase());
@@ -162,6 +165,11 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui {
+ 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);
@@ -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/EnchantCostSettingsGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantCostSettingsGui.java
index 3bd923b..b0997cb 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;
@@ -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/IntSettingsGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/IntSettingsGui.java
index 73121a6..af977e9 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
@@ -72,8 +72,7 @@ public class IntSettingsGui extends AbstractSettingGui {
assert meta != null;
meta.setDisplayName("§eReset to default value");
- meta.setLore(Collections.singletonList("§7Default value is §e" +
- holder.valueDisplayName(ValueDisplayType.RESET, holder.defaultVal)));
+ meta.setLore(Collections.singletonList("§7Default value is §e" + 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("§e" + now + " §f-> §e" + planned + " §r(§c-" + (now - planned) + "§r)");
+ 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("§e" + now + " §f-> §e" + planned + " §r(§a+" + (planned - now) + "§r)");
+ 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("§fValue: §e" + 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);
}
/**
@@ -386,23 +389,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/MaterialSelectSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/MaterialSelectSettingGui.java
index fc519ff..a3963ce 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;
@@ -163,7 +161,8 @@ 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.");
@@ -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(
@@ -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/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
index 707a218..248cc5f 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/update/PluginSetDefault.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/update/PluginSetDefault.java
@@ -5,90 +5,53 @@ 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.*;
+import xyz.alexcrea.cuanvil.config.WorkPenaltyType;
public class PluginSetDefault {
- public static void reAddMissingDefault() {
+ 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, ConfigOptions.CAP_ANVIL_COST, ConfigOptions.DEFAULT_CAP_ANVIL_COST);
+ nbSet+= trySetDefault(config, ConfigOptions.MAX_ANVIL_COST, ConfigOptions.DEFAULT_MAX_ANVIL_COST);
+ nbSet+= trySetDefault(config, ConfigOptions.REMOVE_ANVIL_COST_LIMIT, ConfigOptions.DEFAULT_REMOVE_ANVIL_COST_LIMIT);
+ nbSet+= trySetDefault(config, ConfigOptions.REPLACE_TOO_EXPENSIVE, ConfigOptions.DEFAULT_REPLACE_TOO_EXPENSIVE);
+ nbSet+= trySetDefault(config, ConfigOptions.ITEM_REPAIR_COST, ConfigOptions.DEFAULT_ITEM_REPAIR_COST);
+ nbSet+= trySetDefault(config, ConfigOptions.UNIT_REPAIR_COST, ConfigOptions.DEFAULT_UNIT_REPAIR_COST);
+ nbSet+= trySetDefault(config, ConfigOptions.ITEM_RENAME_COST, ConfigOptions.DEFAULT_ITEM_RENAME_COST);
+ nbSet+= trySetDefault(config, ConfigOptions.SACRIFICE_ILLEGAL_COST, ConfigOptions.DEFAULT_SACRIFICE_ILLEGAL_COST);
+ nbSet+= trySetDefault(config, ConfigOptions.ALLOW_COLOR_CODE, ConfigOptions.DEFAULT_ALLOW_COLOR_CODE);
+ nbSet+= trySetDefault(config, ConfigOptions.ALLOW_HEXADECIMAL_COLOR, ConfigOptions.DEFAULT_ALLOW_HEXADECIMAL_COLOR);
+ nbSet+= trySetDefault(config, ConfigOptions.PERMISSION_NEEDED_FOR_COLOR, ConfigOptions.DEFAULT_PERMISSION_NEEDED_FOR_COLOR);
+ nbSet+= trySetDefault(config, ConfigOptions.USE_OF_COLOR_COST, ConfigOptions.DEFAULT_USE_OF_COLOR_COST);
+ nbSet+= trySetDefault(config, ConfigOptions.WORK_PENALTY_TYPE, WorkPenaltyType.DEFAULT.configName());
+ nbSet+= trySetDefault(config, ConfigOptions.DEFAULT_LIMIT_PATH, ConfigOptions.DEFAULT_ENCHANT_LIMIT);
- 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) {
+ 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;
+ 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;
+ 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;
+ 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..93d37aa 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/update/UpdateUtils.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/update/UpdateUtils.java
@@ -10,27 +10,32 @@ import java.util.List;
public class UpdateUtils {
public static final String MINECRAFT_VERSION_PATH = "lowMinecraftVersion";
- public static Version currentMinecraftVersion() {
+ public static Version currentMinecraftVersion(){
String versionString = Bukkit.getServer().getBukkitVersion().split("-")[0];
return Version.fromString(versionString);
}
- public static void addToStringList(FileConfiguration config, String path, String... toAdd) {
+ @Deprecated
+ public static int[] currentMinecraftVersionArray(){
+ String versionString = Bukkit.getServer().getBukkitVersion().split("-")[0];
+ return UpdateUtils.readVersionFromString(versionString);
+ }
+
+ public 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){
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..3211497
--- /dev/null
+++ b/src/main/java/xyz/alexcrea/cuanvil/update/Update_1_21.java
@@ -0,0 +1,100 @@
+package xyz.alexcrea.cuanvil.update;
+
+import io.delilaheve.CustomAnvil;
+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 {
+
+ private static final Version V1_21 = new Version(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){
+ Version version = Version.fromString(oldVersion);
+
+ // Test 1.21
+ if(V1_21.greaterEqual(version)) return;
+ }
+ Version current = UpdateUtils.currentMinecraftVersion();
+
+ // Test 1.21
+ if(current.greaterEqual(V1_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();
+ FileConfiguration unitConfig = ConfigHolder.UNIT_REPAIR_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", "enchanted_book");
+
+ addToStringList(conflictConfig, "restriction_breach.enchantments", "breach");
+ addToStringList(conflictConfig, "restriction_breach.notAffectedGroups", "mace", "enchanted_book");
+
+ addToStringList(conflictConfig, "restriction_wind_burst.enchantments", "wind_burst");
+ addToStringList(conflictConfig, "restriction_wind_burst.notAffectedGroups", "mace", "enchanted_book");
+
+ // 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);
+
+ // Add unit repair for mace
+ unitConfig.set("breeze_rod.mace", 0.25);
+
+ // 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);
+ 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();
+
+ 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
index a49fbdd..ffa8660 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/update/Version.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/update/Version.java
@@ -1,9 +1,6 @@
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) {
@@ -14,18 +11,12 @@ public record Version(int major, int minor, int patch) {
this(major, 0, 0);
}
- public static Version fromString(@Nullable String versionString){
- if(versionString == null) return new Version(0, 0, 0);
-
+ public static Version fromString(@Nonnull String versionString){
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;
- }
+ versionParts[i] = Integer.parseInt(partialVersion[i]);
}
return new Version(versionParts[0], versionParts[1], versionParts[2]);
}
@@ -54,9 +45,4 @@ public record Version(int major, int minor, int patch) {
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 matSet = include.getNonGroupInheritedMaterials();
- if (!matSet.containsAll(mats)) return;
-
- mats.forEach(matSet::remove);
- tools.addToPolicy(group);
- MaterialGroupApi.writeMaterialGroup(tools);
- }
-
- private static void handleMaceMigration(@Nonnull Set toSave) {
- // We migrate the mace conflict if exist and unmodified
- FileConfiguration config = ConfigHolder.CONFLICT_HOLDER.getConfig();
-
- if (!config.isConfigurationSection("sword_enchant_conflict")) return;
- if (!config.isConfigurationSection("mace_enchant_conflict")) return;
-
- ConfigurationSection mace_conflict = config.getConfigurationSection("mace_enchant_conflict");
- // Test mace conflict if default
- if (mace_conflict == null) return;
- if (mace_conflict.getInt("maxEnchantmentBeforeConflict", 0) != 1) return;
-
- if (mace_conflict.isList("notAffectedGroups") && !mace_conflict.getList("notAffectedGroups").isEmpty()) return;
-
- List enchantments = mace_conflict.getStringList("enchantments");
- if (enchantments.size() != 4) return;
- for (String ench : mace_expected) {
- if (!enchantments.contains(ench) && !enchantments.contains("minecraft:" + ench)) return;
- }
-
- // Test sword_enchant_conflict is default
- ConfigurationSection sword_conflict = config.getConfigurationSection("sword_enchant_conflict");
- if (sword_conflict.getInt("maxEnchantmentBeforeConflict", 0) != 1) return;
-
- if (sword_conflict.isList("notAffectedGroups") && !sword_conflict.getList("notAffectedGroups").isEmpty())
- return;
-
- enchantments = sword_conflict.getStringList("enchantments");
- if (enchantments.size() != 3) return;
- for (String ench : sword_expected) {
- if (!enchantments.contains(ench) && !enchantments.contains("minecraft:" + ench)) return;
- }
-
- // Finally we know both conflict are default. so we fix
- addAbsentToList(config, "sword_enchant_conflict.enchantments",
- "minecraft:density", "minecraft:breach");
-
- config.set("mace_enchant_conflict", null);
- toSave.add(ConfigHolder.CONFLICT_HOLDER);
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_15_5.java b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_15_5.java
deleted file mode 100644
index 76f51af..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_15_5.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package xyz.alexcrea.cuanvil.update.plugin;
-
-import org.bukkit.configuration.file.FileConfiguration;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-
-import javax.annotation.Nonnull;
-import java.util.Set;
-
-import static xyz.alexcrea.cuanvil.update.UpdateUtils.addAbsentToList;
-
-public class PUpdate_1_15_5 {
-
- public static void handleUpdate(@Nonnull Set toSave) {
- FileConfiguration config = ConfigHolder.CONFLICT_HOLDER.getConfig();
-
- if (config.isConfigurationSection("restriction_luck_of_the_sea")) return;
-
- // We fix the luck of the see enchantment
- addAbsentToList(config, "restriction_luck_of_the_sea.enchantments",
- "minecraft:luck_of_the_sea");
- addAbsentToList(config, "restriction_luck_of_the_sea.notAffectedGroups",
- "enchanted_book", "fishing_rod");
-
- toSave.add(ConfigHolder.CONFLICT_HOLDER);
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_15_6.java b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_15_6.java
deleted file mode 100644
index fde7cfc..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_15_6.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package xyz.alexcrea.cuanvil.update.plugin;
-
-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 xyz.alexcrea.cuanvil.update.minecraft.Update_1_21_9;
-
-import javax.annotation.Nonnull;
-import java.util.Set;
-
-public class PUpdate_1_15_6 {
-
- public static void handleUpdate(@Nonnull Set toSave) {
- // fix only needed for 1.21.9 and above
- Version current = UpdateUtils.currentMinecraftVersion();
- if (new Version(1, 21, 9).greaterThan(current)) return;
-
- FileConfiguration unitConfig = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
-
- // Add unit repair
- Update_1_21_9.addCopperUnitRepair(unitConfig);
-
- toSave.add(ConfigHolder.UNIT_REPAIR_HOLDER);
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_6_2.java b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_6_2.java
index a4078de..d004d2d 100644
--- a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_6_2.java
+++ b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_6_2.java
@@ -1,12 +1,13 @@
package xyz.alexcrea.cuanvil.update.plugin;
+import io.delilaheve.CustomAnvil;
import org.bukkit.configuration.file.FileConfiguration;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
import javax.annotation.Nonnull;
import java.util.Set;
-import static xyz.alexcrea.cuanvil.update.UpdateUtils.addAbsentToList;
+import static xyz.alexcrea.cuanvil.update.UpdateUtils.addToStringList;
public class PUpdate_1_6_2 {
@@ -29,7 +30,7 @@ public class PUpdate_1_6_2 {
}
if(!contained){
- addAbsentToList(config, path, "enchanted_book");
+ addToStringList(config, path, "enchanted_book");
conflictUpdated = true;
}
}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_6_7.java b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_6_7.java
deleted file mode 100644
index ee544dc..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_6_7.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package xyz.alexcrea.cuanvil.update.plugin;
-
-import org.bukkit.configuration.file.FileConfiguration;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-
-import javax.annotation.Nonnull;
-import java.util.Set;
-
-public class PUpdate_1_6_7 {
-
- public static void handleUpdate(@Nonnull Set toSave) {
- FileConfiguration config = ConfigHolder.DEFAULT_CONFIG.getConfig();
-
- // We fix the density enchantment
- String value = config.getString("enchant_values.minecraft:density.item");
- if(value == null) value = config.getString("enchant_values.density.item");
-
- if(value == null || "1".equalsIgnoreCase(value)){
- config.set("enchant_values.minecraft:density.item", 2);
-
- toSave.add(ConfigHolder.DEFAULT_CONFIG);
- }
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_8_0.java b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_8_0.java
deleted file mode 100644
index 81ce1aa..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PUpdate_1_8_0.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package xyz.alexcrea.cuanvil.update.plugin;
-
-import io.delilaheve.util.ConfigOptions;
-import org.bukkit.configuration.file.FileConfiguration;
-import xyz.alexcrea.cuanvil.anvil.AnvilUseType;
-import xyz.alexcrea.cuanvil.config.ConfigHolder;
-import xyz.alexcrea.cuanvil.config.WorkPenaltyType;
-import xyz.alexcrea.cuanvil.gui.config.settings.WorkPenaltyTypeSettingGui;
-
-import javax.annotation.Nonnull;
-import java.util.EnumMap;
-import java.util.Set;
-
-public class PUpdate_1_8_0 {
-
- private static final String WORK_PENALTY_TYPE = "work_penalty_type";
-
- public static void handleUpdate(@Nonnull Set toSave) {
- FileConfiguration config = ConfigHolder.DEFAULT_CONFIG.getConfig();
-
- // We migrate the work penalty type if it exists
- String penaltyTypeValue = config.getString(WORK_PENALTY_TYPE);
- if (penaltyTypeValue == null) return;
-
- EnumMap partEnum;
- partEnum = new EnumMap<>(ConfigOptions.INSTANCE.getWorkPenaltyType().getPartMap());
-
- boolean keepIncrease;
- boolean keepAdditive;
-
- switch (penaltyTypeValue.toLowerCase()) {
- case "add_only":
- keepIncrease = false;
- keepAdditive = true;
- break;
- case "increase_only":
- keepIncrease = true;
- keepAdditive = false;
- break;
- case "disabled":
- keepIncrease = false;
- keepAdditive = false;
- break;
- default:
- keepIncrease = true;
- keepAdditive = true;
- }
-
- for (AnvilUseType type : partEnum.keySet()) {
- WorkPenaltyType.WorkPenaltyPart part = partEnum.get(type);
- part = new WorkPenaltyType.WorkPenaltyPart(
- keepIncrease & part.penaltyIncrease(),
- keepAdditive & part.penaltyAdditive(),
- part.exclusivePenaltyIncrease(),
- part.exclusivePenaltyAdditive());
- partEnum.replace(type, part);
- }
-
- if(WorkPenaltyTypeSettingGui.saveWorkPenalty(partEnum)){
- config.set(WORK_PENALTY_TYPE, null);
- }
-
- toSave.add(ConfigHolder.DEFAULT_CONFIG);
- }
-
-}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PluginUpdates.java b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PluginUpdates.java
new file mode 100644
index 0000000..cc0901b
--- /dev/null
+++ b/src/main/java/xyz/alexcrea/cuanvil/update/plugin/PluginUpdates.java
@@ -0,0 +1,39 @@
+package xyz.alexcrea.cuanvil.update.plugin;
+
+import io.delilaheve.CustomAnvil;
+import xyz.alexcrea.cuanvil.config.ConfigHolder;
+import xyz.alexcrea.cuanvil.update.Version;
+
+import javax.annotation.Nonnull;
+import java.util.HashSet;
+import java.util.Set;
+
+public class PluginUpdates {
+
+ private static final String CONFIG_VERSION_PATH = "configVersion";
+
+ public 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<>();
+
+ if(new Version(1, 6, 2).greaterThan(current)){
+ PUpdate_1_6_2.handleUpdate(toSave);
+
+ finishConfiguration("1.6.2", toSave);
+ }
+
+ }
+
+ 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);
+ for (ConfigHolder configHolder : toSave) {
+ configHolder.saveToDisk(true);
+ }
+ }
+
+}
diff --git a/src/main/java/xyz/alexcrea/cuanvil/util/LazyValue.java b/src/main/java/xyz/alexcrea/cuanvil/util/LazyValue.java
deleted file mode 100644
index 3ae8fdd..0000000
--- a/src/main/java/xyz/alexcrea/cuanvil/util/LazyValue.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package xyz.alexcrea.cuanvil.util;
-
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.util.function.Supplier;
-
-public class LazyValue {
-
- private final Supplier valueSupplier;
- private T storedValue;
-
- public LazyValue(Supplier valueSupplier) {
- this.valueSupplier = valueSupplier;
- this.storedValue = null;
- }
-
- @Nullable
- public T getStored(){
- return storedValue;
- }
-
- @NotNull
- public T get(){
- if (storedValue != null) return storedValue;
-
- synchronized(this) {
- if(storedValue == null) {
- storedValue = valueSupplier.get();
- }
- }
-
- return storedValue;
- }
-
-}
diff --git a/src/main/kotlin/io/delilaheve/AnvilEventListener.kt b/src/main/kotlin/io/delilaheve/AnvilEventListener.kt
new file mode 100644
index 0000000..e2f92e9
--- /dev/null
+++ b/src/main/kotlin/io/delilaheve/AnvilEventListener.kt
@@ -0,0 +1,580 @@
+package io.delilaheve
+
+import io.delilaheve.util.ConfigOptions
+import io.delilaheve.util.EnchantmentUtil.combineWith
+import io.delilaheve.util.ItemUtil.canMergeWith
+import io.delilaheve.util.ItemUtil.findEnchantments
+import io.delilaheve.util.ItemUtil.isEnchantedBook
+import io.delilaheve.util.ItemUtil.repairFrom
+import io.delilaheve.util.ItemUtil.setEnchantmentsUnsafe
+import io.delilaheve.util.ItemUtil.unitRepair
+import org.bukkit.ChatColor
+import org.bukkit.GameMode
+import org.bukkit.Material
+import org.bukkit.entity.HumanEntity
+import org.bukkit.entity.Player
+import org.bukkit.event.Event
+import org.bukkit.event.EventHandler
+import org.bukkit.event.EventPriority.HIGHEST
+import org.bukkit.event.Listener
+import org.bukkit.event.inventory.ClickType
+import org.bukkit.event.inventory.InventoryClickEvent
+import org.bukkit.event.inventory.InventoryCloseEvent
+import org.bukkit.event.inventory.PrepareAnvilEvent
+import org.bukkit.inventory.AnvilInventory
+import org.bukkit.inventory.InventoryView.Property.REPAIR_COST
+import org.bukkit.inventory.ItemStack
+import xyz.alexcrea.cuanvil.config.ConfigHolder
+import xyz.alexcrea.cuanvil.dependency.DependencyManager
+import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
+import xyz.alexcrea.cuanvil.recipe.AnvilCustomRecipe
+import xyz.alexcrea.cuanvil.util.AnvilXpUtil.calculatePenalty
+import xyz.alexcrea.cuanvil.util.AnvilXpUtil.getRightValues
+import xyz.alexcrea.cuanvil.util.AnvilXpUtil.setAnvilInvXp
+import xyz.alexcrea.cuanvil.util.UnitRepairUtil.getRepair
+import java.util.regex.Matcher
+import java.util.regex.Pattern
+import kotlin.math.min
+
+
+/**
+ * Listener for anvil events
+ */
+class AnvilEventListener(private val packetManager: PacketManager) : Listener {
+
+ companion object {
+ // Anvil's output slot
+ const val ANVIL_INPUT_LEFT = 0
+ const val ANVIL_INPUT_RIGHT = 1
+ const val ANVIL_OUTPUT_SLOT = 2
+
+ // static slot container
+ private val NO_SLOT = SlotContainer(SlotType.NO_SLOT, 0)
+ private val CURSOR_SLOT = SlotContainer(SlotType.CURSOR, 0)
+ }
+
+ /**
+ * Event handler logic for when an anvil contains items to be combined
+ */
+ @EventHandler(priority = HIGHEST)
+ fun anvilCombineCheck(event: PrepareAnvilEvent) {
+ // Test if the event should bypass custom anvil.
+ if(DependencyManager.tryEventPreAnvilBypass(event)) return
+
+ val inventory = event.inventory
+ val first = inventory.getItem(ANVIL_INPUT_LEFT) ?: return
+ val second = inventory.getItem(ANVIL_INPUT_RIGHT)
+
+ // Should find player
+ val player = event.view.player
+ if (!player.hasPermission(CustomAnvil.affectedByPluginPermission)) return
+
+ // Test custom recipe
+ val recipe = getCustomRecipe(first, second)
+ CustomAnvil.verboseLog("custom recipe not null? ${recipe != null}")
+ if(recipe != null){
+ val amount = getCustomRecipeAmount(recipe, first, second)
+
+ val resultItem: ItemStack = recipe.resultItem!!.clone()
+ resultItem.amount *= amount
+
+ event.result = resultItem
+ setAnvilInvXp(inventory, event.view, recipe.xpCostPerCraft * amount, true)
+
+ return
+ }
+
+ // Test rename lonely item
+ if (second == null) {
+ val resultItem = first.clone()
+ var anvilCost = handleRename(resultItem, inventory, player)
+
+ // Test/stop if nothing changed.
+ if (first == resultItem) {
+ CustomAnvil.log("no right item, But input is same as output")
+ event.result = null
+ return
+ }
+
+ event.result = resultItem
+
+ anvilCost += calculatePenalty(first, null, resultItem)
+
+ setAnvilInvXp(inventory, event.view, anvilCost)
+ return
+ }
+
+ // Test for merge
+ if (first.canMergeWith(second)) {
+ val newEnchants = first.findEnchantments()
+ .combineWith(second.findEnchantments(), first, player)
+ val resultItem = first.clone()
+ resultItem.setEnchantmentsUnsafe(newEnchants)
+
+ // Calculate enchantment cost
+ var anvilCost = getRightValues(second, resultItem)
+ // Calculate repair cost
+ if (!first.isEnchantedBook() && !second.isEnchantedBook()) {
+ // we only need to be concerned with repair when neither item is a book
+ val repaired = resultItem.repairFrom(first, second)
+ anvilCost += if (repaired) ConfigOptions.itemRepairCost else 0
+ }
+
+ // Test/stop if nothing changed.
+ if (first == resultItem) {
+ CustomAnvil.log("Mergable with second, But input is same as output")
+ event.result = null
+ return
+ }
+ // As calculatePenalty edit result, we need to calculate penalty after checking equality
+ anvilCost += calculatePenalty(first, second, resultItem)
+ // Calculate rename cost
+ anvilCost += handleRename(resultItem, inventory, player)
+
+ // Finally, we set result
+ event.result = resultItem
+
+ setAnvilInvXp(inventory, event.view, anvilCost)
+ return
+ }
+
+ // Test for unit repair
+ val unitRepairAmount = first.getRepair(second)
+ if (unitRepairAmount != null) {
+ val resultItem = first.clone()
+ var anvilCost = handleRename(resultItem, inventory, player)
+
+ val repairAmount = resultItem.unitRepair(second.amount, unitRepairAmount)
+ if (repairAmount > 0) {
+ anvilCost += repairAmount * ConfigOptions.unitRepairCost
+ }
+ // We do not care about right item penalty for unit repair
+ anvilCost += calculatePenalty(first, null, resultItem, true)
+
+ // Test/stop if nothing changed.
+ if (first == resultItem) {
+ CustomAnvil.log("unit repair, But input is same as output")
+ event.result = null
+ return
+ }
+ event.result = resultItem
+
+ setAnvilInvXp(inventory, event.view, anvilCost)
+ } else {
+ CustomAnvil.log("no anvil fuse type found")
+ event.result = null
+ }
+
+ }
+
+ private fun handleRename(resultItem: ItemStack, inventory: AnvilInventory, player: HumanEntity): Int {
+ // Rename item and add renaming cost
+ resultItem.itemMeta?.let {
+ val displayName = ChatColor.stripColor(it.displayName)
+ var inventoryName = ChatColor.stripColor(inventory.renameText)
+
+ var sumCost = 0
+
+ var useColor = false
+ if(ConfigOptions.renameColorPossible){
+ val resultString = StringBuilder(inventoryName)
+
+ useColor = handleRenamingColor(resultString, player)
+
+ if(useColor) {
+ inventoryName = resultString.toString()
+
+ sumCost+= ConfigOptions.useOfColorCost
+ }
+ }
+
+ if ((!useColor && (!displayName.contentEquals(inventoryName))) || (useColor && !(it.displayName).contentEquals(inventoryName))) {
+ it.setDisplayName(inventoryName)
+ resultItem.itemMeta = it
+
+ sumCost+= ConfigOptions.itemRenameCost
+ }
+
+ return sumCost
+ }
+ return 0
+ }
+
+ private fun handleRenamingColor(textToColor: StringBuilder, player: HumanEntity): Boolean {
+ val usePermission = ConfigOptions.permissionNeededForColor
+ val canUseColorCode = ConfigOptions.allowColorCode && (!usePermission || player.hasPermission("ca.color.code"))
+ val canUseHexColor = ConfigOptions.allowHexadecimalColor && (!usePermission || player.hasPermission("ca.color.hex"))
+
+ if((!canUseColorCode) && (!canUseHexColor)) return false
+
+ var useColor = false
+ // Handle color code
+ if(canUseColorCode){
+ var nbReplacement = replaceAll(textToColor, "&", "§", 2)
+ nbReplacement -= 2 * replaceAll(textToColor, "§§", "&", 2)
+
+ if(nbReplacement > 0) useColor = true
+ }
+
+ if(canUseHexColor){
+ val nbReplacement = replaceHexToColor(textToColor, 7)
+
+ if(nbReplacement > 0) useColor = true
+ }
+
+ return useColor
+ }
+
+ /**
+ * Replace every instance of "from" to "to".
+ * @param builder The builder to replace the string from.
+ * @param from The source that should be replaced.
+ * @param to The string that should replace.
+ * @param endOffset Amount of character that should be ignored at the end.
+ * @return The number of replacement was that was done.
+ */
+ private fun replaceAll(builder: java.lang.StringBuilder, from: String, to: String, endOffset: Int): Int {
+ var index = builder.indexOf(from)
+ var numberOfChanges = 0
+
+ while (index != -1 && index < builder.length - endOffset) {
+ builder.replace(index, index + from.length, to)
+ index += to.length
+ index = builder.indexOf(from, index)
+
+ numberOfChanges+=1
+ }
+
+ return numberOfChanges
+ }
+
+ val HEX_PATTERN: Pattern = Pattern.compile("#[A-Fa-f0-9]{6}") // pattern to find hexadecimal string
+ /**
+ * Replace every hex color formatted like #000000 to the minecraft format
+ * @param builder The builder to replace the hex color from.
+ * @param endOffset Amount of character that should be ignored at the end.
+ * @return The number of replacement was that was done.
+ */
+ private fun replaceHexToColor(builder: StringBuilder, endOffset: Int): Int {
+ val matcher: Matcher = HEX_PATTERN.matcher(builder)
+
+ var numberOfChanges = 0
+ var startIndex = 0
+
+ while(matcher.find(startIndex)){
+ startIndex = matcher.start()
+ if(startIndex >= builder.length - endOffset) break
+
+ builder.replace(startIndex, startIndex + 1, "§x")
+ startIndex+=2
+ for (i in 0..5) {
+ builder.insert(startIndex, '§')
+ startIndex+=2
+ }
+
+ numberOfChanges+=1
+ }
+
+ return numberOfChanges
+ }
+
+ /**
+ * Event handler logic for when a player is trying to pull an item out of the anvil
+ */
+ @EventHandler(ignoreCancelled = true)
+ fun anvilExtractionCheck(event: InventoryClickEvent) {
+ val player = event.whoClicked as? Player ?: return
+ if (!player.hasPermission(CustomAnvil.affectedByPluginPermission)) return
+ val inventory = event.inventory as? AnvilInventory ?: return
+
+ if (event.rawSlot != ANVIL_OUTPUT_SLOT) {
+ return
+ }
+ // Test if the event should bypass custom anvil.
+ if(DependencyManager.tryClickAnvilResultBypass(event, inventory)) return
+
+ val output = inventory.getItem(ANVIL_OUTPUT_SLOT) ?: return
+ val leftItem = inventory.getItem(ANVIL_INPUT_LEFT) ?: return
+ val rightItem = inventory.getItem(ANVIL_INPUT_RIGHT)
+
+ // Test custom recipe
+ val recipe = getCustomRecipe(leftItem, rightItem)
+ if(recipe != null){
+ event.result = Event.Result.ALLOW
+ onCustomCraft(
+ event, recipe, player,
+ leftItem, rightItem, output, inventory)
+ return
+ }
+
+ val canMerge = leftItem.canMergeWith(rightItem)
+ val unitRepairResult = leftItem.getRepair(rightItem)
+ val allowed = (rightItem == null)
+ || (canMerge)
+ || (unitRepairResult != null)
+
+ // True if there was no change or not allowed
+ if ((output == inventory.getItem(ANVIL_INPUT_LEFT))
+ || !allowed
+ ) {
+ event.result = Event.Result.DENY
+ return
+ }
+ if (rightItem == null) {
+ event.result = Event.Result.ALLOW
+ return
+ }
+ if (canMerge) {
+ event.result = Event.Result.ALLOW
+ } else if (unitRepairResult != null) {
+ onUnitRepairExtract(
+ leftItem, rightItem, output,
+ unitRepairResult, event, player, inventory
+ )
+
+ return
+ }
+ }
+
+ private fun onCustomCraft(event: InventoryClickEvent,
+ recipe: AnvilCustomRecipe,
+ player: Player,
+ leftItem: ItemStack,
+ rightItem: ItemStack?,
+ output: ItemStack,
+ inventory: AnvilInventory) {
+ event.result = Event.Result.DENY
+
+ if(recipe.leftItem == null) return // in case it changed
+
+ val amount = getCustomRecipeAmount(recipe, leftItem, rightItem)
+ val xpCost = amount * recipe.xpCostPerCraft
+
+ if ((player.gameMode != GameMode.CREATIVE) && (player.level < xpCost)) return
+
+ // We give the item manually
+ // But first we check if we should give the item
+ val slotDestination = getActionSlot(event, player)
+ if (slotDestination.type == SlotType.NO_SLOT) return
+
+ // If not creative middle click...
+ if (event.click != ClickType.MIDDLE) {
+ // We remove what should be removed
+ leftItem.amount -= amount * recipe.leftItem!!.amount
+ inventory.setItem(ANVIL_INPUT_LEFT, leftItem)
+
+ if(rightItem != null){
+ if(recipe.rightItem == null) return // in case it changed
+
+ rightItem.amount -= amount * recipe.rightItem!!.amount
+ inventory.setItem(ANVIL_INPUT_RIGHT, rightItem)
+ }
+
+ if(player.gameMode != GameMode.CREATIVE){
+ player.level -= xpCost
+ }
+
+ // Then we try to find the new values for the anvil
+ val newAmount = getCustomRecipeAmount(recipe, leftItem, rightItem)
+
+ CustomAnvil.verboseLog("new amount is $newAmount")
+ if(newAmount <= 0 || recipe.exactCount){
+ inventory.setItem(ANVIL_OUTPUT_SLOT, null)
+ }else{
+ val resultItem: ItemStack = recipe.resultItem!!.clone()
+ resultItem.amount *= newAmount
+
+ val newXp = newAmount * newAmount
+
+ inventory.repairCost = newXp
+ event.view.setProperty(REPAIR_COST, newXp)
+
+ inventory.setItem(ANVIL_OUTPUT_SLOT, resultItem)
+
+ player.updateInventory()
+ }
+ }
+
+ // Finally, we add the item to the player
+ if (slotDestination.type == SlotType.CURSOR) {
+ player.setItemOnCursor(output)
+ } else {// We assume SlotType == SlotType.INVENTORY
+ player.inventory.setItem(slotDestination.slot, output)
+ }
+
+
+ }
+
+ private fun onUnitRepairExtract(
+ leftItem: ItemStack,
+ rightItem: ItemStack,
+ output: ItemStack,
+ unitRepairResult: Double,
+ event: InventoryClickEvent,
+ player: Player,
+ inventory: AnvilInventory
+ ) {
+ val resultCopy = leftItem.clone()
+ val resultAmount = resultCopy.unitRepair(
+ rightItem.amount, unitRepairResult
+ )
+
+ // To avoid vanilla, we cancel the event for unit repair
+ event.result = Event.Result.DENY
+ event.isCancelled = true
+ // And we give the item manually
+ // But first we check if we should give the item
+ val slotDestination = getActionSlot(event, player)
+ if (slotDestination.type == SlotType.NO_SLOT) return
+
+ // Test repair cost
+ var repairCost = 0
+ if (player.gameMode != GameMode.CREATIVE) {
+ // Get repairCost
+ leftItem.itemMeta?.let { leftMeta ->
+ val leftName = leftMeta.displayName
+ output.itemMeta?.let {
+ // Rename cost
+ if (!leftName.contentEquals(it.displayName)) {
+ repairCost += ConfigOptions.itemRenameCost
+
+ // Color cost
+ if(it.displayName.contains('§')){
+ repairCost += ConfigOptions.useOfColorCost
+ }
+ }
+ }
+ }
+
+ repairCost += calculatePenalty(leftItem, null, resultCopy)
+ repairCost += resultAmount * ConfigOptions.unitRepairCost
+
+ if (
+ !ConfigOptions.doRemoveCostLimit &&
+ ConfigOptions.doCapCost) {
+
+ repairCost = min(repairCost, ConfigOptions.maxAnvilCost)
+ }
+
+ if ((inventory.maximumRepairCost <= repairCost)
+ || (player.level < repairCost)
+ ) return
+ }
+ // If not creative middle click...
+ if (event.click != ClickType.MIDDLE) {
+ // We remove what should be removed
+ inventory.setItem(ANVIL_INPUT_LEFT, null)
+ rightItem.amount -= resultAmount
+ inventory.setItem(ANVIL_INPUT_RIGHT, rightItem)
+ inventory.setItem(ANVIL_OUTPUT_SLOT, null)
+ player.level -= repairCost
+ }
+
+ // Finally, we add the item to the player
+ if (slotDestination.type == SlotType.CURSOR) {
+ player.setItemOnCursor(output)
+ } else {// We assume SlotType == SlotType.INVENTORY
+ player.inventory.setItem(slotDestination.slot, output)
+ }
+ }
+
+ /**
+ * Get the destination slot or "NO_SLOT" slot container if there is no slot available
+ */
+ private fun getActionSlot(event: InventoryClickEvent, player: Player): SlotContainer {
+ if (event.isShiftClick) {
+ val inventory = player.inventory
+ val firstEmpty = inventory.firstEmpty()
+ if (firstEmpty == -1) {
+ return NO_SLOT
+ }
+ //check hotbare full
+ var slotIndex = 8
+ while (slotIndex >= 0 && ((inventory.getItem(slotIndex)?.type ?: Material.AIR) != Material.AIR)) {
+ slotIndex--
+ }
+ if (slotIndex >= 0) {
+ return SlotContainer(SlotType.INVENTORY, slotIndex)
+ }
+ slotIndex = 35 //4*9 - 1 (max of player inventory)
+ while (slotIndex >= 9 && ((inventory.getItem(slotIndex)?.type ?: Material.AIR) != Material.AIR)) {
+ slotIndex--
+ }
+ if (slotIndex < 9) {
+ return NO_SLOT
+ }
+ return SlotContainer(SlotType.INVENTORY, slotIndex)
+ } else {
+ if (player.itemOnCursor.type != Material.AIR) {
+ return NO_SLOT
+ }
+ return CURSOR_SLOT
+ }
+ }
+
+ private fun getCustomRecipe (
+ leftItem: ItemStack,
+ rightItem: ItemStack?) : AnvilCustomRecipe? {
+
+ val recipeList = ConfigHolder.CUSTOM_RECIPE_HOLDER.recipeManager.recipeByMat[leftItem.type] ?: return null
+
+ CustomAnvil.verboseLog("Testing " + recipeList.size+" recipe...")
+ for (recipe in recipeList) {
+ if(recipe.testItem(leftItem, rightItem)){
+ return recipe
+ }
+ }
+
+ return null
+ }
+
+ private fun getCustomRecipeAmount(
+ recipe: AnvilCustomRecipe,
+ leftItem: ItemStack,
+ rightItem: ItemStack?
+ ): Int{
+ return if(recipe.exactCount) {
+ if(leftItem.amount != recipe.leftItem!!.amount){
+ 0
+ }else if(rightItem != null && rightItem.amount != recipe.rightItem!!.amount){
+ 0
+ }else{
+ 1
+ }
+ }
+ else {
+ // test amount
+ val resultItem = recipe.resultItem!! // we know exist as the recipe was returned to us
+ val maxResultAmount = resultItem.type.maxStackSize/resultItem.amount
+ val maxLeftAmount = leftItem.amount/recipe.leftItem!!.amount
+ val maxRightAmount = if(rightItem == null){ maxLeftAmount } else{ rightItem.amount/recipe.rightItem!!.amount }
+
+ CustomAnvil.verboseLog("resultItem: $resultItem, maxResultAmount: $maxResultAmount, maxLeftAmount: $maxLeftAmount, maxRightAmount: $maxRightAmount")
+
+ min(min(maxResultAmount, maxLeftAmount), maxRightAmount)
+ }
+ }
+
+
+ @EventHandler
+ fun onAnvilClose(event: InventoryCloseEvent){
+ val player = event.player
+ if(event.inventory !is AnvilInventory) return
+ if(player is Player && GameMode.CREATIVE != player.gameMode){
+ packetManager.setInstantBuild(player, false)
+ }
+
+ }
+
+}
+
+
+
+
+private class SlotContainer(val type: SlotType, val slot: Int)
+private enum class SlotType {
+ CURSOR,
+ INVENTORY,
+ NO_SLOT
+
+}
diff --git a/src/main/kotlin/io/delilaheve/CustomAnvil.kt b/src/main/kotlin/io/delilaheve/CustomAnvil.kt
index 4d99faf..cbeb5cd 100644
--- a/src/main/kotlin/io/delilaheve/CustomAnvil.kt
+++ b/src/main/kotlin/io/delilaheve/CustomAnvil.kt
@@ -6,25 +6,18 @@ import org.bukkit.configuration.file.YamlConfiguration
import org.bukkit.plugin.java.JavaPlugin
import xyz.alexcrea.cuanvil.api.event.CAConfigReadyEvent
import xyz.alexcrea.cuanvil.api.event.CAEnchantRegistryReadyEvent
-import xyz.alexcrea.cuanvil.command.CustomAnvilCommand
import xyz.alexcrea.cuanvil.command.EditConfigExecutor
import xyz.alexcrea.cuanvil.command.ReloadExecutor
import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.dependency.DependencyManager
-import xyz.alexcrea.cuanvil.dependency.MinecraftVersionUtil
-import xyz.alexcrea.cuanvil.dependency.economy.EconomyManager
-import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil
import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant
-import xyz.alexcrea.cuanvil.listener.AnvilCloseListener
-import xyz.alexcrea.cuanvil.listener.AnvilResultListener
import xyz.alexcrea.cuanvil.listener.ChatEventListener
-import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener
-import xyz.alexcrea.cuanvil.update.ModrinthUpdateChecker
import xyz.alexcrea.cuanvil.update.PluginSetDefault
-import xyz.alexcrea.cuanvil.update.UpdateHandler
-import xyz.alexcrea.cuanvil.util.MetricsUtil
+import xyz.alexcrea.cuanvil.update.Update_1_21
+import xyz.alexcrea.cuanvil.update.plugin.PluginUpdates
+import xyz.alexcrea.cuanvil.util.Metrics
import java.io.File
import java.io.FileReader
import java.util.logging.Level
@@ -32,11 +25,11 @@ import java.util.logging.Level
/**
* Bukkit/Spigot/Paper plugin to alter anvil feature
*/
-open class CustomAnvil : JavaPlugin() {
+class CustomAnvil : JavaPlugin() {
companion object {
- // pluginIDS
- private const val modrinthPluginID = "S75Ueiq9"
+ // bstats plugin id
+ private const val bstatsPluginId = 20923
// Permission string required to use the plugin's features
const val affectedByPluginPermission = "ca.affected"
@@ -50,18 +43,14 @@ open class CustomAnvil : JavaPlugin() {
// Permission string required to reload the config
const val commandReloadPermission = "ca.command.reload"
- // Permission string required to get diagnostic data
- const val diagnosticPermission = "ca.command.diagnostic"
-
// Permission string required to edit the plugin's config
const val editConfigPermission = "ca.config.edit"
-
// Command Name to reload the config
const val commandReloadName = "anvilconfigreload"
- // Config command name
- const val commandConfigName = "customanvilconfig"
+ // Test command name
+ const val commandTestName = "customanvilconfig"
// Current plugin instance
lateinit var instance: CustomAnvil
@@ -69,12 +58,10 @@ open class CustomAnvil : JavaPlugin() {
// Chat message listener
lateinit var chatListener: ChatEventListener
- var latestVer: String? = null
-
/**
* Logging handler
*/
- @JvmStatic fun log(message: String) {
+ fun log(message: String) {
if (ConfigOptions.debugLog) {
instance.logger.info(message)
}
@@ -89,26 +76,7 @@ open class CustomAnvil : JavaPlugin() {
}
}
- }
- // stop plugin if we do not force a dirty start (true by default)
- // Return true if start was stopped
- private fun tryDirtyStart(): Boolean {
- if(!ConfigHolder.DEFAULT_CONFIG.config.getBoolean("dirty_start", false)) {
- Bukkit.getPluginManager().disablePlugin(this)
- return true
- }
- return false
- }
-
- // stop plugin if we force a safe start (false by default)
- // Return true if start was stopped
- private fun trySafeStart(): Boolean {
- if(ConfigHolder.DEFAULT_CONFIG.config.getBoolean("safe_start", false)) {
- Bukkit.getPluginManager().disablePlugin(this)
- return true
- }
- return false
}
/**
@@ -116,74 +84,7 @@ open class CustomAnvil : JavaPlugin() {
*/
override fun onEnable() {
instance = this
- try {
- legacyCheck()
- } catch (e: Exception) {
- logger.log(Level.SEVERE, "error trying to check for legacy system", e)
- MetricsUtil.trackError(e)
- if(trySafeStart()) return
- }
- // Add commands
- try {
- prepareCommand()
- } catch (e: Exception) {
- logger.log(Level.SEVERE, "error trying to register commands", e)
- MetricsUtil.trackError(e)
- if(trySafeStart()) return
- }
-
- // Load default configuration
- try {
- if(!ConfigHolder.loadDefaultConfig())
- throw RuntimeException("Error loading configuration file")
- } catch (e: Exception) {
- logger.log(Level.SEVERE, "error occurred loading default configuration", e)
- MetricsUtil.trackError(e)
- if(tryDirtyStart()) return
- }
-
- // Load dependency
- try {
- DependencyManager.loadDependency()
- } catch (e: Exception) {
- logger.log(Level.SEVERE, "error loading dependency compatibility", e)
- MetricsUtil.trackError(e)
- if(tryDirtyStart()) return
- }
-
- // Register listeners
- try {
- registerListeners()
- } catch (e: Exception) {
- logger.log(Level.SEVERE, "error registering listeners", e)
- MetricsUtil.trackError(e)
- if(tryDirtyStart()) return
- }
-
- // Load metrics
- MetricsUtil.loadMetrics(this)
-
- // Load other thing later.
- // It is so other dependent plugins can implement there event listener before we fire them.
- DependencyManager.scheduler.scheduleGlobally(this) { loadEnchantmentSystemDirty() }
- }
-
- override fun onDisable() {
- MetricsUtil.shutdownMetrics()
- }
-
- private fun loadEnchantmentSystemDirty() {
- try {
- loadEnchantmentSystem()
- } catch (e: Exception) {
- logger.log(Level.SEVERE, "error initializing enchantment system", e)
- MetricsUtil.trackError(e)
- tryDirtyStart()
- }
- }
-
- private fun legacyCheck() {
// Disable old plugin name if exist
val potentialPlugin = Bukkit.getPluginManager().getPlugin("UnsafeEnchantsPlus")
if (potentialPlugin != null) {
@@ -192,43 +93,31 @@ open class CustomAnvil : JavaPlugin() {
logger.warning("Please note CustomAnvil is a more recent version of UnsafeEnchantsPlus")
}
- val isPaper = PlatformUtil.isPaper
- if(!isPaper) {
- logger.warning("It seems you are using spigot")
- logger.warning("Please take notice that spigot is less supported than paper and derivatives")
- if(MinecraftVersionUtil.isTooNewForSpigot) {
- logger.warning("If replace too expensive is not working this is likely because of spigot")
- logger.warning("As native nms is not supported for spigot starting 26.1")
- }
- }
+ // Add commands
+ prepareCommand()
- val loader = if(isPaper) "paper" else "spigot"
-
- val version = description.version
- val featured = if(version.contains("dev")) null else true
-
- ModrinthUpdateChecker(modrinthPluginID, loader, null)
- .setFeatured(featured)
- .setOnError {
- logger.log(Level.WARNING, "error trying to fetch latest update", it)
- }
- .checkVersion { latestVer: String? ->
- CustomAnvil.latestVer = latestVer
- if(latestVer == null || version.contains(latestVer)) return@checkVersion
-
- logger.warning("An update may be available: $latestVer")
- }
- }
-
- private fun registerListeners() {
- // Register chat listener
+ // Load chat listener
chatListener = ChatEventListener()
server.pluginManager.registerEvents(chatListener, this)
+ // Load default configuration
+ if (!ConfigHolder.loadDefaultConfig()) {
+ logger.log(Level.SEVERE,"could not load default config.")
+ return
+ }
+
+ // Load dependency
+ DependencyManager.loadDependency()
+
// Register anvil events
- server.pluginManager.registerEvents(PrepareAnvilListener(), this)
- server.pluginManager.registerEvents(AnvilResultListener(), this)
- server.pluginManager.registerEvents(AnvilCloseListener(DependencyManager.packetManager), this)
+ server.pluginManager.registerEvents(AnvilEventListener(DependencyManager.packetManager), this)
+
+ // Load metrics
+ Metrics(this, bstatsPluginId)
+
+ // Load other thing later.
+ // It is so other dependent plugins can implement there event listener before we fire them.
+ DependencyManager.scheduler.scheduleGlobally(this, {loadEnchantmentSystem()})
}
private fun loadEnchantmentSystem(){
@@ -241,13 +130,15 @@ open class CustomAnvil : JavaPlugin() {
// Load config
if (!ConfigHolder.loadNonDefaultConfig()) {
- logger.log(Level.SEVERE,"Plugin has an issue while trying to load non default config... exiting...")
- server.pluginManager.disablePlugin(this)
+ logger.log(Level.SEVERE,"could not load non default config.")
return
}
- // Handle minecraft and plugin updates
- UpdateHandler.handleUpdates()
+ // temporary: handle 1.21 update
+ Update_1_21.handleUpdate()
+
+ // plugin configuration updates
+ PluginUpdates.handlePluginUpdate()
// Register enchantment of compatible plugin and load configuration change.
DependencyManager.handleCompatibilityConfig()
@@ -260,11 +151,9 @@ open class CustomAnvil : JavaPlugin() {
MainConfigGui.getInstance().init(DependencyManager.packetManager)
GuiSharedConstant.loadConstants()
- // Prepare economy if possible
- EconomyManager.setupEconomy(this)
-
// Finally, re add default we may be missing
PluginSetDefault.reAddMissingDefault()
+
}
fun reloadResource(
@@ -314,10 +203,8 @@ open class CustomAnvil : JavaPlugin() {
var command = getCommand(commandReloadName)
command?.setExecutor(ReloadExecutor())
- command = getCommand(commandConfigName)
+ command = getCommand(commandTestName)
command?.setExecutor(EditConfigExecutor())
-
- CustomAnvilCommand(this)
}
}
diff --git a/src/main/kotlin/io/delilaheve/util/ConfigOptions.kt b/src/main/kotlin/io/delilaheve/util/ConfigOptions.kt
index 9dc85f9..37fdf5a 100644
--- a/src/main/kotlin/io/delilaheve/util/ConfigOptions.kt
+++ b/src/main/kotlin/io/delilaheve/util/ConfigOptions.kt
@@ -2,18 +2,9 @@ package io.delilaheve.util
import io.delilaheve.CustomAnvil
import io.delilaheve.util.EnchantmentUtil.enchantmentName
-import org.bukkit.NamespacedKey
-import org.bukkit.entity.HumanEntity
-import xyz.alexcrea.cuanvil.anvil.AnvilUseType
import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.config.WorkPenaltyType
-import xyz.alexcrea.cuanvil.config.WorkPenaltyType.WorkPenaltyPart
-import xyz.alexcrea.cuanvil.dependency.DependencyManager
-import xyz.alexcrea.cuanvil.dependency.economy.EconomyManager
import xyz.alexcrea.cuanvil.enchant.CAEnchantment
-import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil
-import java.math.BigDecimal
-import java.util.*
/**
* Config option accessors
@@ -24,9 +15,6 @@ object ConfigOptions {
// Path for config values
// ----------------------
- const val METRIC_TYPE = "metric_type"
- const val METRIC_COLLECT_ERROR = "metric_collect_errors"
-
const val CAP_ANVIL_COST = "limit_repair_cost"
const val MAX_ANVIL_COST = "limit_repair_value"
const val REMOVE_ANVIL_COST_LIMIT = "remove_repair_limit"
@@ -39,56 +27,27 @@ object ConfigOptions {
const val ITEM_RENAME_COST = "item_rename_cost"
const val SACRIFICE_ILLEGAL_COST = "sacrifice_illegal_enchant_cost"
- const val ADD_BOOK_ENCHANTMENT_AS_STORED_ENCHANTMENT = "add_book_enchantment_as_stored_enchantment"
// Color related config
const val ALLOW_COLOR_CODE = "allow_color_code"
const val ALLOW_HEXADECIMAL_COLOR = "allow_hexadecimal_color"
- const val ALLOW_MINIMESSAGE = "allow_minimessage"
const val PERMISSION_NEEDED_FOR_COLOR = "permission_needed_for_color"
const val USE_OF_COLOR_COST = "use_of_color_cost"
- const val PER_COLOR_CODE_PERMISSION = "per_color_code_permission"
+ const val WORK_PENALTY_TYPE = "work_penalty_type"
- // Work penalty config
- const val WORK_PENALTY_ROOT = "work_penalty"
- const val WORK_PENALTY_INCREASE = "shared_increase"
- const val WORK_PENALTY_ADDITIVE = "shared_additive"
- const val EXCLUSIVE_WORK_PENALTY_INCREASE = "exclusive_increase"
- const val EXCLUSIVE_WORK_PENALTY_ADDITIVE = "exclusive_additive"
-
- // Enchant limit config
- const val ENCHANT_COUNT_LIMIT_ROOT = "enchantment_count_limit"
- const val ENCHANT_COUNT_LIMIT_DEFAULT = "$ENCHANT_COUNT_LIMIT_ROOT.default"
- const val ENCHANT_COUNT_LIMIT_ITEMS = "$ENCHANT_COUNT_LIMIT_ROOT.items"
+ const val DEFAULT_LIMIT_PATH = "default_limit"
const val ENCHANT_LIMIT_ROOT = "enchant_limits"
const val ENCHANT_VALUES_ROOT = "enchant_values"
- // Dialog menu rename
- const val DIALOG_RENAME_ENABLED = "enable_dialog_rename"
- const val DIALOG_MAX_SIZE = "dialog_rename_max_size"
- const val DIALOG_RENAME_USE_PERMISSION = "permission_needed_for_dialog_rename"
- const val DIALOG_KEEP_USER_TEXT = "dialog_rename_keep_user_text"
-
- // Others
- const val DISABLE_MERGE_OVER_ROOT = "disable-merge-over"
-
- const val IMMUTABLE_ENCHANTMENT_LIST = "immutable_enchantments"
-
- // Monetary configs
- const val MONETARY_USAGE_ROOT = "monetary_cost"
- const val SHOULD_USE_MONEY = "$MONETARY_USAGE_ROOT.enabled"
- const val MONEY_CURRENCY = "$MONETARY_USAGE_ROOT.currency"
- const val MONETARY_MULTIPLIER_ROOT = "$MONETARY_USAGE_ROOT.multipliers"
-
// Keys for specific enchantment values
private const val KEY_BOOK = "book"
private const val KEY_ITEM = "item"
// Debug flag
- const val DEBUG_LOGGING = "debug_log"
- const val VERBOSE_DEBUG_LOGGING = "debug_log_verbose"
+ private const val DEBUG_LOGGING = "debug_log"
+ private const val VERBOSE_DEBUG_LOGGING = "debug_log_verbose"
// ----------------------
// Default config values
@@ -106,34 +65,19 @@ object ConfigOptions {
const val DEFAULT_ITEM_RENAME_COST = 1
const val DEFAULT_SACRIFICE_ILLEGAL_COST = 1
- const val DEFAULT_ADD_BOOK_ENCHANTMENT_AS_STORED_ENCHANTMENT = false
-
- const val DEFAULT_ENCHANT_COUNT_LIMIT = -1
// Color related config
const val DEFAULT_ALLOW_COLOR_CODE = false
const val DEFAULT_ALLOW_HEXADECIMAL_COLOR = false
- const val DEFAULT_ALLOW_MINIMESSAGE = false
const val DEFAULT_PERMISSION_NEEDED_FOR_COLOR = true
const val DEFAULT_USE_OF_COLOR_COST = 0
- const val DEFAULT_PER_COLOR_CODE_PERMISSION = false
-
- // Monetary configs
- const val DEFAULT_SHOULD_USE_MONEY = false
- const val DEFAULT_MONEY_CURRENCY = "default"
- const val DEFAULT_MONEY_MULTIPLIER = 1.0
+ const val DEFAULT_ENCHANT_LIMIT = 5
// Debug flag
private const val DEFAULT_DEBUG_LOG = false
private const val DEFAULT_VERBOSE_DEBUG_LOG = false
- // Dialog menu rename
- const val DEFAULT_DIALOG_RENAME_ENABLED = false
- const val DEFAULT_DIALOG_MAX_SIZE = 256
- const val DEFAULT_DIALOG_RENAME_USE_PERMISSION = false
- const val DEFAULT_DIALOG_KEEP_USER_TEXT = true
-
// -------------
// Config Ranges
// -------------
@@ -158,31 +102,14 @@ object ConfigOptions {
@JvmField
val USE_OF_COLOR_COST_RANGE = 0..1000
- @JvmField
- val DIALOG_MAX_SIZE_RANGE = 0..Int.MAX_VALUE
-
// Valid range for an enchantment limit
- const val ENCHANT_LIMIT = 255
-
- // Valid range for an enchantment count limit
@JvmField
- val ENCHANT_COUNT_LIMIT_RANGE = -1..255
+ val ENCHANT_LIMIT_RANGE = 1..255
- // --------------
- // Other defaults
- // --------------
// Default value for an enchantment multiplier
private const val DEFAULT_ENCHANT_VALUE = 0
- // Default max before merge disabled (negative mean enabled)
- const val DEFAULT_MAX_BEFORE_MERGE_DISABLED = -1
-
- // -----------
- // Permissions
- // -----------
- private const val RENAME_DIALOG_PERMISSION = "ca.rename.dialog"
-
// -------------
// Get methods
// -------------
@@ -277,16 +204,6 @@ object ConfigOptions {
?: DEFAULT_SACRIFICE_ILLEGAL_COST
}
- /**
- * Consider book enchantment as book stored enchantment
- */
- val addBookEnchantmentAsStoredEnchantment : Boolean
- get(){
- return ConfigHolder.DEFAULT_CONFIG
- .config
- .getBoolean(ADD_BOOK_ENCHANTMENT_AS_STORED_ENCHANTMENT, DEFAULT_ADD_BOOK_ENCHANTMENT_AS_STORED_ENCHANTMENT)
- }
-
/**
* Allow usage of color code
*/
@@ -307,23 +224,10 @@ object ConfigOptions {
.getBoolean(ALLOW_HEXADECIMAL_COLOR, DEFAULT_ALLOW_HEXADECIMAL_COLOR)
}
- /**
- * Allow usage of minimessage formating
- */
- val allowMinimessage: Boolean
- get() {
- return ConfigHolder.DEFAULT_CONFIG
- .config
- .getBoolean(ALLOW_MINIMESSAGE, DEFAULT_ALLOW_MINIMESSAGE)
- }
-
/**
* If one of the color component is enabled
*/
- val renameColorPossible: Boolean
- get() {
- return allowColorCode || allowHexadecimalColor || allowMinimessage
- }
+ val renameColorPossible: Boolean get() { return allowColorCode || allowHexadecimalColor }
/**
* If players need a permission to use color
@@ -335,16 +239,6 @@ object ConfigOptions {
.getBoolean(PERMISSION_NEEDED_FOR_COLOR, DEFAULT_PERMISSION_NEEDED_FOR_COLOR)
}
- /**
- * Should each color code require a permission
- */
- val usePerColorCodePermission: Boolean
- get() {
- return ConfigHolder.DEFAULT_CONFIG
- .config
- .getBoolean(PER_COLOR_CODE_PERMISSION, DEFAULT_PER_COLOR_CODE_PERMISSION)
- }
-
/**
* How many xp should use of color should cost
*/
@@ -358,77 +252,24 @@ object ConfigOptions {
}
/**
- * How work penalties should work
+ * How many xp should use of color should cost
*/
val workPenaltyType: WorkPenaltyType
get() {
- val penaltyMap = EnumMap(AnvilUseType::class.java)
-
- for (type in AnvilUseType.entries) {
- penaltyMap[type] = workPenaltyPart(type)
- }
-
- return WorkPenaltyType(penaltyMap)
+ return WorkPenaltyType.fromString(
+ ConfigHolder.DEFAULT_CONFIG
+ .config
+ .getString(WORK_PENALTY_TYPE));
}
/**
- * How work penalty should work
+ * Default enchantment limit
*/
- fun workPenaltyPart(type: AnvilUseType): WorkPenaltyPart {
- val config = ConfigHolder.DEFAULT_CONFIG.config
-
- // Find values
- val defaultPenalty = type.defaultPenalty
- val section = config.getConfigurationSection(type.path) ?: return defaultPenalty
-
- val penaltyIncrease = section.getBoolean(WORK_PENALTY_INCREASE, defaultPenalty.penaltyIncrease)
- val penaltyAdditive = section.getBoolean(WORK_PENALTY_ADDITIVE, defaultPenalty.penaltyAdditive)
- val exclusivePenaltyIncrease =
- section.getBoolean(EXCLUSIVE_WORK_PENALTY_INCREASE, defaultPenalty.exclusivePenaltyIncrease)
- val exclusivePenaltyAdditive =
- section.getBoolean(EXCLUSIVE_WORK_PENALTY_ADDITIVE, defaultPenalty.exclusivePenaltyAdditive)
-
- return WorkPenaltyPart(penaltyIncrease, penaltyAdditive, exclusivePenaltyIncrease, exclusivePenaltyAdditive)
- }
-
- /**
- * Get material enchantment count limit
- *
- * @return the current enchantment limit. -1 if none
- */
- fun getEnchantCountLimit(type: NamespacedKey): Int? {
- val limit = materialEnchantCountLimit(type)
-
- if(limit != null) return limit
- if(defaultEnchantCountLimit >= 0) return defaultEnchantCountLimit
-
- return DependencyManager.ecoEnchantCompatibility?.getEcoLevelLimit()
- }
-
- /**
- * Get the material enchantment count limit.
- *
- * @return The current enchantment limit. -1 if none
- */
- private fun materialEnchantCountLimit(type: NamespacedKey): Int? {
- val path = "$ENCHANT_COUNT_LIMIT_ITEMS.${type.key.lowercase()}"
- if(!ConfigHolder.DEFAULT_CONFIG.config.isInt(path))
- return null
-
- return ConfigHolder.DEFAULT_CONFIG.config
- .getInt(path)
- .takeIf { it in ENCHANT_COUNT_LIMIT_RANGE }
- }
- /**
- * User configured default enchantment count limit
- */
- val defaultEnchantCountLimit: Int
+ private val defaultEnchantLimit: Int
get() {
return ConfigHolder.DEFAULT_CONFIG
.config
- .getInt(ENCHANT_COUNT_LIMIT_DEFAULT, DEFAULT_ENCHANT_COUNT_LIMIT)
- .takeIf { it in ENCHANT_COUNT_LIMIT_RANGE }
- ?: DEFAULT_ENCHANT_COUNT_LIMIT
+ .getInt(DEFAULT_LIMIT_PATH, DEFAULT_ENCHANT_LIMIT)
}
/**
@@ -451,90 +292,36 @@ object ConfigOptions {
.getBoolean(VERBOSE_DEBUG_LOGGING, DEFAULT_VERBOSE_DEBUG_LOG)
}
- /**
- * Is the dialog menu for rename enabled
- */
- val doRenameDialog: Boolean
- get() {
- return ConfigHolder.DEFAULT_CONFIG
- .config
- .getBoolean(DIALOG_RENAME_ENABLED, DEFAULT_DIALOG_RENAME_ENABLED)
- }
-
- /**
- * Do the dialog menu require permission
- */
- val doRenameDialogUsePermission: Boolean
- get() {
- return ConfigHolder.DEFAULT_CONFIG
- .config
- .getBoolean(DIALOG_RENAME_USE_PERMISSION, DEFAULT_DIALOG_RENAME_USE_PERMISSION)
- }
-
- fun canUseDialogRename(player: HumanEntity): Boolean {
- if(!doRenameDialog || !AnvilRenameDialogUtil.anvilRenameDialog.canSendDialog()) return false
- if(doRenameDialogUsePermission && !player.hasPermission(RENAME_DIALOG_PERMISSION)) return false
-
- return true
- }
-
- /**
- * Do the dialog menu require permission
- */
- val renameDialogMaxSize: Int
- get() {
- return ConfigHolder.DEFAULT_CONFIG
- .config
- .getInt(DIALOG_MAX_SIZE, DEFAULT_DIALOG_MAX_SIZE)
- .takeIf { it in DIALOG_MAX_SIZE_RANGE }
- ?: Int.MAX_VALUE
- }
-
- /**
- * Should the text used for rename should be kept in the item's pdc
- */
- val shouldKeepRenameText: Boolean
- get() {
- return ConfigHolder.DEFAULT_CONFIG
- .config
- .getBoolean(DIALOG_KEEP_USER_TEXT, DEFAULT_DIALOG_KEEP_USER_TEXT)
- }
-
/**
* Get the given [enchantment]'s limit
*/
fun enchantLimit(enchantment: CAEnchantment): Int {
- val limit = rawEnchantLimit(enchantment)
- if(limit >= 0) return limit.coerceAtMost(ENCHANT_LIMIT)
-
- // get default
- return enchantment.defaultMaxLevel()
- }
-
- /**
- * Get the given [enchantment]'s limit
- */
- fun rawEnchantLimit(enchantment: CAEnchantment): Int {
- // Test namespace
- var limit = enchantLimit(enchantment.key.toString())
- if (limit >= 0) return limit
-
- // Test legacy (name only)
- limit = enchantLimit(enchantment.enchantmentName)
- if (limit >= 0) return limit
-
- // Default to negative
- return -1
+ return enchantLimit(enchantment.enchantmentName)
}
/**
* Get the given [enchantmentName]'s limit
*/
private fun enchantLimit(enchantmentName: String): Int {
+ val default = getDefaultLevel(enchantmentName)
val path = "${ENCHANT_LIMIT_ROOT}.$enchantmentName"
- return CustomAnvil.instance.config
- .getInt(path, -1)
+ return CustomAnvil.instance
+ .config
+ .getInt(path, default)
+ .takeIf { it in ENCHANT_LIMIT_RANGE }
+ ?: default
+ }
+
+ /**
+ * Get default value if enchantment do not exist on config
+ */
+ private fun getDefaultLevel(enchantmentName: String, // compatibility with 1.20.5. TODO better update system
+ ) : Int {
+ if(enchantmentName == "sweeping_edge"){
+ return enchantLimit("sweeping")
+ }
+ return defaultEnchantLimit
}
/**
@@ -545,17 +332,7 @@ object ConfigOptions {
enchantment: CAEnchantment,
isFromBook: Boolean
): Int {
- // Test namespace
- var limit = enchantmentValue(enchantment.key.toString(), isFromBook)
- if (limit != null) return limit
-
- // Test legacy (name only)
- limit = enchantmentValue(enchantment.enchantmentName, isFromBook)
- if (limit != null) return limit
-
- // get default (and test old legacy if present)
- return getDefaultValue(enchantment, isFromBook)
-
+ return enchantmentValue(enchantment.enchantmentName, isFromBook)
}
/**
@@ -565,115 +342,36 @@ object ConfigOptions {
private fun enchantmentValue(
enchantmentName: String,
isFromBook: Boolean
- ): Int? {
+ ): Int {
+ val default = getDefaultValue(enchantmentName, isFromBook)
+
val typeKey = if (isFromBook) KEY_BOOK else KEY_ITEM
val path = "${ENCHANT_VALUES_ROOT}.${enchantmentName}.$typeKey"
return CustomAnvil.instance
.config
- .getInt(path, DEFAULT_ENCHANT_VALUE - 1)
+ .getInt(path, default)
.takeIf { it >= DEFAULT_ENCHANT_VALUE }
+ ?: DEFAULT_ENCHANT_VALUE
}
/**
* Get default value if enchantment do not exist on config
*/
- private fun getDefaultValue(
- enchantment: CAEnchantment, // compatibility with 1.20.5. TODO better update system
- isFromBook: Boolean
- ): Int {
-
- val enchantmentName = enchantment.key.toString()
- if (enchantmentName == "minecraft:sweeping_edge") {
- var limit = enchantmentValue("minecraft:sweeping", isFromBook)
- if (limit != null) return limit
-
- // legacy name
- limit = enchantmentValue("sweeping", isFromBook)
- if (limit != null) return limit
+ private fun getDefaultValue(enchantmentName: String, // compatibility with 1.20.5. TODO better update system
+ isFromBook: Boolean) : Int {
+ if(enchantmentName == "sweeping_edge"){
+ return enchantmentValue("sweeping", isFromBook)
}
- val rarity = enchantment.defaultRarity()
- return if (isFromBook)
- rarity.bookValue
- else
- rarity.itemValue
- }
+ val enchantment = CAEnchantment.getByName(enchantmentName)
+ if(enchantment != null){
+ val rarity = enchantment.defaultRarity()
- /**
- * Get the given [enchantmentName]'s level before merge is disabled
- * a negative value would mean never disabled
- */
- fun maxBeforeMergeDisabled(enchantment: CAEnchantment): Int {
- val key = enchantment.key.toString()
- var value = maxBeforeMergeDisabled(key)
- if (value >= 0) return value
-
- // Legacy name
- val legacy = enchantment.enchantmentName
- value = maxBeforeMergeDisabled(legacy)
- if (value >= 0) return value
-
- if (key == "minecraft:sweeping_edge") {
- value = maxBeforeMergeDisabled("minecraft:sweeping")
- if (value >= 0) return value
-
- // legacy name of legacy enchantment name
- value = maxBeforeMergeDisabled("sweeping")
- if (value >= 0) return value
+ return if(isFromBook) rarity.bookValue
+ else rarity.itemValue
}
- return DEFAULT_MAX_BEFORE_MERGE_DISABLED
- }
-
- /**
- * Get the given [enchantmentName]'s level before merge is disabled
- * a negative value would mean never disabled
- */
- private fun maxBeforeMergeDisabled(enchantmentName: String): Int {
- // find if set
- val path = "${DISABLE_MERGE_OVER_ROOT}.$enchantmentName"
-
- return CustomAnvil.instance
- .config
- .getInt(path, -1)
- }
-
- fun isImmutable(key: NamespacedKey): Boolean {
- val immutables = ConfigHolder.DEFAULT_CONFIG.config.getStringList(IMMUTABLE_ENCHANTMENT_LIST)
-
- // We need to ignore case so can't just check "contain"
- for (ench in immutables) {
- if (ench.equals(key.toString(), ignoreCase = true) ||
- ench.equals(key.key, ignoreCase = true)
- )
- return true
- }
- return false
- }
-
- /*
- * Monetary configs (only for 1.21.6+)
- * Also require dialog rename
- */
- fun shouldUseMoney(player: HumanEntity): Boolean {
- return EconomyManager.economy?.initialized() == true &&
- canUseDialogRename(player) &&
- ConfigHolder.DEFAULT_CONFIG
- .config
- .getBoolean(SHOULD_USE_MONEY, DEFAULT_SHOULD_USE_MONEY)
- }
-
- val usedCurrency: String
- get() {
- return ConfigHolder.DEFAULT_CONFIG
- .config
- .getString(MONEY_CURRENCY, DEFAULT_MONEY_CURRENCY)!!
- }
-
- fun getMonetaryMultiplier(type: String): BigDecimal {
- return BigDecimal(ConfigHolder.DEFAULT_CONFIG
- .config
- .getDouble("$MONETARY_MULTIPLIER_ROOT.$type", DEFAULT_MONEY_MULTIPLIER))
+ return DEFAULT_ENCHANT_VALUE
}
}
diff --git a/src/main/kotlin/io/delilaheve/util/EnchantmentUtil.kt b/src/main/kotlin/io/delilaheve/util/EnchantmentUtil.kt
index af959f2..95bdd36 100644
--- a/src/main/kotlin/io/delilaheve/util/EnchantmentUtil.kt
+++ b/src/main/kotlin/io/delilaheve/util/EnchantmentUtil.kt
@@ -6,7 +6,6 @@ import org.bukkit.inventory.ItemStack
import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.group.ConflictType
-import xyz.alexcrea.cuanvil.util.MaterialUtil.customType
import kotlin.math.max
import kotlin.math.min
@@ -31,97 +30,60 @@ object EnchantmentUtil {
) = mutableMapOf().apply {
putAll(this@combineWith)
- CustomAnvil.verboseLog("Testing merge")
- val bypassFuse = player.hasPermission(CustomAnvil.bypassFusePermission)
- val bypassLevel = player.hasPermission(CustomAnvil.bypassLevelPermission)
+ other.forEach { (enchantment, level) ->
+ if(!enchantment.isAllowed(player)) return@forEach
- var maxEnchantCount = ConfigOptions.getEnchantCountLimit(item.customType)
- if(maxEnchantCount == null || maxEnchantCount < 0) maxEnchantCount = Int.MAX_VALUE
-
- val allowed = other.filter { (enchantment, _) -> enchantment.isAllowed(player) }
- val new = allowed.filter{ (enchantment, _) -> !containsKey(enchantment)}
- val old = allowed.filter{ (enchantment, _) -> containsKey(enchantment)}
-
- fun maxLevel(enchantment: CAEnchantment): Int {
- val max = if (bypassLevel) { 255 }
- else { ConfigOptions.enchantLimit(enchantment) }
-
- CustomAnvil.verboseLog("Max level of ${enchantment.key} is $max (bypassLevel is $bypassLevel)")
- return max
- }
-
- old.forEach { (enchantment, level) ->
// Get max level or 255 if player can bypass
- val maxLevel = maxLevel(enchantment)
+ val maxLevel = if (player.hasPermission(CustomAnvil.bypassLevelPermission))
+ { 255 } else
+ { ConfigOptions.enchantLimit(enchantment) }
+
val cappedLevel = min(level, maxLevel)
- val oldLevel = this[enchantment]!! // <- should not be null. (enchantment already in result list)
-
- // ... and they're not the same level
- if (oldLevel != cappedLevel) {
- // apply the greater of the two or left one if right is above max
- this[enchantment] = max(oldLevel, cappedLevel)
- }
- // ... and they're the same level
- else {
- // We test if it is allowed to merge at this level
- if(!bypassLevel){
- val maxBeforeDisabled = ConfigOptions.maxBeforeMergeDisabled(enchantment)
- if((maxBeforeDisabled > 0) && (oldLevel >= maxBeforeDisabled)) {
- CustomAnvil.verboseLog(
- "Reached max merge before disable for ${enchantment.key}: $oldLevel/$maxBeforeDisabled)")
- return@forEach
- }
+ // Enchantment not yet in result list
+ if (!containsKey(enchantment)) {
+ // Add the enchantment if it doesn't have conflicts, or if player is allowed to bypass enchantment restrictions
+ this[enchantment] = cappedLevel
+ val conflictType =
+ ConfigHolder.CONFLICT_HOLDER.conflictManager.isConflicting(this, item, enchantment)
+ if (!player.hasPermission(CustomAnvil.bypassFusePermission) &&
+ (conflictType != ConflictType.NO_CONFLICT)
+ ) {
+ CustomAnvil.verboseLog("Enchantment not yet in result list, but there is conflict (${enchantment.key}, conflict: $conflictType)")
+ this.remove(enchantment)
}
- // Now we increase the enchantment level by 1
- var newLevel = oldLevel + 1
- newLevel = max(min(newLevel, maxLevel), oldLevel)
- this[enchantment] = newLevel
}
-
- if(bypassFuse){
- CustomAnvil.verboseLog("Bypassed conflict check for ${enchantment.key}")
- } else {
- val conflictType = ConfigHolder.CONFLICT_HOLDER.conflictManager
- .isConflicting(this, item, enchantment)
+ // Enchantment already in result list
+ else {
+ val oldLevel = this[enchantment]!! // <- should not be null. (enchantment already in result list)
// ... and they are conflicting
- if(conflictType != ConflictType.NO_CONFLICT){
- CustomAnvil.verboseLog(
- "Enchantment already in result list, and they are conflicting (${enchantment.key}, conflict: $conflictType)")
- this[enchantment] = oldLevel
+ val conflictType =
+ ConfigHolder.CONFLICT_HOLDER.conflictManager.isConflicting(this, item, enchantment)
+ if ((conflictType != ConflictType.NO_CONFLICT)
+ && !player.hasPermission(CustomAnvil.bypassFusePermission)
+ ) {
+ CustomAnvil.verboseLog("Enchantment already in result list, and they are conflicting (${enchantment.key}, conflict: $conflictType)")
return@forEach
}
+
+ // ... and they're not the same level
+ if (oldLevel != cappedLevel) {
+ // apply the greater of the two or left one if right is above max
+ this[enchantment] = max(oldLevel, cappedLevel)
+
+ }
+ // ... and they're the same level
+ else {
+ // try to increase the enchantment level by 1
+ var newLevel = oldLevel + 1
+ newLevel = max(min(newLevel, maxLevel), oldLevel)
+ this[enchantment] = newLevel
+
+ }
}
}
-
- // Try to add new now
- new.forEach { (enchantment, level) ->
- // Get max level or 255 if player can bypass
- val maxLevel = maxLevel(enchantment)
- val cappedLevel = min(level, maxLevel)
-
- // Do not allow new enchantment if above maximum
- if(this.size >= maxEnchantCount) return@forEach
-
- // Add the enchantment if it doesn't have conflicts, or if player is allowed to bypass enchantment restrictions
- this[enchantment] = cappedLevel
- if(bypassFuse){
- CustomAnvil.verboseLog("Bypassed conflict check for ${enchantment.key}")
- return@forEach
- }
-
- val conflictType = ConfigHolder.CONFLICT_HOLDER.conflictManager
- .isConflicting(this, item, enchantment)
-
- if (conflictType != ConflictType.NO_CONFLICT) {
- CustomAnvil.verboseLog("Enchantment not yet in result list, but there is conflict (${enchantment.key}, conflict: $conflictType)")
- this.remove(enchantment)
- }
-
- }
-
}
}
diff --git a/src/main/kotlin/io/delilaheve/util/ItemUtil.kt b/src/main/kotlin/io/delilaheve/util/ItemUtil.kt
index 25698ad..a85af39 100644
--- a/src/main/kotlin/io/delilaheve/util/ItemUtil.kt
+++ b/src/main/kotlin/io/delilaheve/util/ItemUtil.kt
@@ -4,9 +4,6 @@ import org.bukkit.Material.ENCHANTED_BOOK
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.Damageable
import xyz.alexcrea.cuanvil.enchant.CAEnchantment
-import xyz.alexcrea.cuanvil.update.UpdateUtils
-import xyz.alexcrea.cuanvil.util.MaterialUtil.customType
-import xyz.alexcrea.cuanvil.util.MaxDamageCheckerUtil
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
@@ -38,13 +35,6 @@ object ItemUtil {
}
- private fun maxDamage(damageable: Damageable): Int {
- val ver = UpdateUtils.currentMinecraftVersion()
- if(ver.major <= 1 && ver.minor <= 20 && ver.patch < 5) return Integer.MAX_VALUE
-
- return MaxDamageCheckerUtil.getMaxDamage(damageable)
- }
-
/**
* Set this [ItemStack]s durability from a combination of the
* [first] and [second] item's durability values
@@ -64,9 +54,7 @@ object ItemUtil {
val secondDurability = durability - secondDamage
val combinedDurability = firstDurability + secondDurability
val newDurability = min(combinedDurability, durability)
-
- val maxDamage = maxDamage(it)
- it.damage = min(durability - newDurability, maxDamage)
+ it.damage = durability - newDurability
itemMeta = it
return true
}
@@ -102,5 +90,5 @@ object ItemUtil {
*/
fun ItemStack.canMergeWith(
other: ItemStack?
- ) = (other != null) && (customType == other.customType || (other.isEnchantedBook()))
+ ) = (other != null) && (type == other.type || (other.isEnchantedBook()))
}
diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilCost.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilCost.kt
deleted file mode 100644
index 710687c..0000000
--- a/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilCost.kt
+++ /dev/null
@@ -1,72 +0,0 @@
-package xyz.alexcrea.cuanvil.anvil
-
-import io.delilaheve.util.ConfigOptions
-import java.math.BigDecimal
-import kotlin.math.min
-import io.delilaheve.util.ConfigOptions.getMonetaryMultiplier as moneyMultiplier
-
-open class AnvilCost {
- private val isAlone: Boolean
- var valid = true // Get set as invalid if cost can be satisfied
- var isMonetary = false
-
- var generic = 0
- var enchantment = 0
- var repair = 0
- var rename = 0
- var lore = 0
- var illegalPenalty = 0
- var workPenalty = 0
- var recipe = 0
-
- constructor(generic: Int) {
- this.generic = generic
- isAlone = true
- }
-
- constructor() {
- isAlone = false
- }
-
- fun asXpCost(): Int {
- return generic + enchantment + repair + rename + lore + illegalPenalty + workPenalty + recipe
- }
-
- fun filteredXpCost(ignoreRules: Boolean = false): Int {
- val original = asXpCost()
-
- // Test repair cost limit
- return if (
- !ignoreRules &&
- !ConfigOptions.doRemoveCostLimit &&
- ConfigOptions.doCapCost
- ) {
- min(original, ConfigOptions.maxAnvilCost)
- } else {
- original
- }
- }
-
- open fun asMonetaryCost(): BigDecimal {
- // multiply by per use type multipliers
- return BigDecimal(generic)
- .add(BigDecimal(enchantment).multiply(moneyMultiplier("enchantment")))
- .add(BigDecimal(repair).multiply(moneyMultiplier("repair")))
- .add(BigDecimal(rename).multiply(moneyMultiplier("rename")))
- .add(BigDecimal(lore).multiply(moneyMultiplier("lore_edit")))
- .add(BigDecimal(enchantment).multiply(moneyMultiplier("enchantment")))
- .add(BigDecimal(illegalPenalty).multiply(moneyMultiplier("work_penalty")))
- .add(BigDecimal(workPenalty).multiply(moneyMultiplier("work_penalty")))
- .add(BigDecimal(recipe).multiply(moneyMultiplier("recipe")))
- .multiply(moneyMultiplier("global"))
- }
-}
-
-class CustomCraftCost(val rawCost: Int): AnvilCost() {
-
- override fun asMonetaryCost(): BigDecimal {
- return BigDecimal(rawCost)
- .multiply(moneyMultiplier("global"))
- }
-
-}
\ No newline at end of file
diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilMergeLogic.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilMergeLogic.kt
deleted file mode 100644
index 6b106fc..0000000
--- a/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilMergeLogic.kt
+++ /dev/null
@@ -1,331 +0,0 @@
-package xyz.alexcrea.cuanvil.anvil
-
-import io.delilaheve.CustomAnvil
-import io.delilaheve.util.ConfigOptions
-import io.delilaheve.util.EnchantmentUtil.combineWith
-import io.delilaheve.util.ItemUtil.findEnchantments
-import io.delilaheve.util.ItemUtil.isEnchantedBook
-import io.delilaheve.util.ItemUtil.repairFrom
-import io.delilaheve.util.ItemUtil.setEnchantmentsUnsafe
-import io.delilaheve.util.ItemUtil.unitRepair
-import org.bukkit.ChatColor
-import org.bukkit.Material
-import org.bukkit.entity.HumanEntity
-import org.bukkit.entity.Player
-import org.bukkit.inventory.AnvilInventory
-import org.bukkit.inventory.InventoryView
-import org.bukkit.inventory.ItemStack
-import org.bukkit.inventory.meta.ItemMeta
-import org.bukkit.persistence.PersistentDataType
-import xyz.alexcrea.cuanvil.dependency.DependencyManager
-import xyz.alexcrea.cuanvil.dialog.AnvilRenameDialog
-import xyz.alexcrea.cuanvil.enchant.CAEnchantment
-import xyz.alexcrea.cuanvil.recipe.AnvilCustomRecipe
-import xyz.alexcrea.cuanvil.util.CasedStringUtil
-import xyz.alexcrea.cuanvil.util.CustomRecipeUtil
-import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir
-import xyz.alexcrea.cuanvil.util.MiniMessageUtil
-import xyz.alexcrea.cuanvil.util.UnitRepairUtil.getRepair
-import xyz.alexcrea.cuanvil.util.anvil.AnvilColorUtil
-import xyz.alexcrea.cuanvil.util.anvil.AnvilLoreEditUtil
-import xyz.alexcrea.cuanvil.util.anvil.AnvilXpUtil
-import xyz.alexcrea.cuanvil.util.config.LoreEditType
-import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil
-
-object AnvilMergeLogic {
-
- open class AnvilResult {
- companion object {
- val EMPTY = AnvilResult(null, AnvilCost())
- }
-
- val item: ItemStack?
- val cost: AnvilCost
- val ignoreXpRules: Boolean
-
- constructor(item: ItemStack?, cost: AnvilCost, ignoreXpRules: Boolean = false) {
- this.item = item
- this.cost = cost
- this.ignoreXpRules = ignoreXpRules
- }
-
- fun isEmpty(): Boolean {
- return item == null
- }
- }
-
- class UnitRepairResult : AnvilResult {
- companion object {
- val EMPTY = UnitRepairResult(null, AnvilCost(), 0)
- }
-
- val repairAmount: Int
-
- constructor(item: ItemStack?, cost: AnvilCost, repairAmount: Int) : super(item, cost) {
- this.repairAmount = repairAmount
- }
- }
-
- class CustomCraftResult : AnvilResult {
- companion object {
- val EMPTY = CustomCraftResult(null, CustomCraftCost(0), 0, null)
- }
-
- val customCraftCost: CustomCraftCost
- val amount: Int
- val recipe: AnvilCustomRecipe?
-
- constructor(
- item: ItemStack?, cost: CustomCraftCost,
- amount: Int, recipe: AnvilCustomRecipe?
- ) : super(item, cost, true) {
- this.customCraftCost = cost
- this.amount = amount
- this.recipe = recipe
- }
- }
-
- class LoreEditResult : AnvilResult {
- companion object {
- val EMPTY = LoreEditResult(null, AnvilCost(), LoreEditType.APPEND_PAPER)
- }
-
- val type: LoreEditType
-
- constructor(item: ItemStack?, cost: AnvilCost, type: LoreEditType) : super(item, cost) {
- this.type = type
- }
- }
-
- fun doRenaming(
- view: InventoryView, //TODO use anvil view
- inventory: AnvilInventory,
- player: Player, first: ItemStack
- ): AnvilResult {
- val resultItem = DependencyManager.cloneItem(player, first)
- val cost = AnvilCost()
- cost.rename = handleRename(resultItem, inventory, player)
-
- // Test/stop if nothing changed.
- if (first == resultItem) {
- CustomAnvil.log("no right item, But input is same as output")
- return AnvilResult.EMPTY
- }
-
- cost.workPenalty = AnvilXpUtil.calculatePenalty(first, null, resultItem, AnvilUseType.RENAME_ONLY)
- val result =
- DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.RENAME_ONLY, cost)
-
- return AnvilResult(result, cost)
- }
-
- private fun processDialogPCD(meta: ItemMeta, player: HumanEntity) {
- val text = AnvilRenameDialogUtil.anvilRenameDialog.currentText(player)
- return processPCD(meta, player, text)
- }
-
- fun processPCD(meta: ItemMeta, player: HumanEntity, text: String?) {
- val keepDialog = ConfigOptions.canUseDialogRename(player) && ConfigOptions.shouldKeepRenameText
-
- val pdc = meta.persistentDataContainer
- if (!keepDialog)
- pdc.remove(AnvilRenameDialog.PCD_KEEP_RENAME_TEXT_KEY)
- else {
- if (text == null || text.isBlank())
- pdc.remove(AnvilRenameDialog.PCD_KEEP_RENAME_TEXT_KEY)
- else pdc.set(AnvilRenameDialog.PCD_KEEP_RENAME_TEXT_KEY, PersistentDataType.STRING, text)
- }
- }
-
- private fun handleRename(resultItem: ItemStack, inventory: AnvilInventory, player: HumanEntity): Int {
- // Can be null
- var renameText = ChatColor.stripColor(inventory.renameText)
-
- var sumCost = 0
- var useColor = false
- if (ConfigOptions.renameColorPossible && renameText != null) {
- val component = AnvilColorUtil.handleColor(
- renameText,
- AnvilColorUtil.renamePermission(player)
- )
-
- if (component != null) {
- renameText = MiniMessageUtil.legacy_mm.serialize(component)
-
- sumCost += ConfigOptions.useOfColorCost
- useColor = true
- }
- }
-
- // Rename item and add renaming cost
- resultItem.itemMeta?.let {
- val hasDisplayName = it.hasDisplayName()
- val displayName = if (!hasDisplayName) null
- else if (useColor) it.displayName
- else ChatColor.stripColor(it.displayName)
-
-
- if (!displayName.contentEquals(renameText) && !(displayName == null &&
- renameText == "" ||
- //TODO on recent paper check effective name instead
- renameText == CasedStringUtil.snakeToUpperSpacedCase(resultItem.type.name.lowercase())
- )
- ) {
- it.setDisplayName(renameText)
- processDialogPCD(it, player)
- resultItem.itemMeta = it
-
- sumCost += ConfigOptions.itemRenameCost
- }
-
- return sumCost
- }
- return 0
- }
-
- fun doMerge(
- view: InventoryView, //TODO use anvil view instead
- inventory: AnvilInventory,
- player: Player,
- first: ItemStack, second: ItemStack
- ): AnvilResult {
- val newEnchants = first.findEnchantments()
- .combineWith(second.findEnchantments(), first, player)
- var hasChanged = !isIdentical(first.findEnchantments(), newEnchants)
-
- val resultItem = DependencyManager.cloneItem(player, first)
- val cost = AnvilCost()
- if (hasChanged) {
- resultItem.setEnchantmentsUnsafe(newEnchants)
- // Calculate enchantment cost
- AnvilXpUtil.getRightValues(second, resultItem, cost)
- }
-
- // Calculate repair cost
- if (!first.isEnchantedBook() && !second.isEnchantedBook()) {
- // we only need to be concerned with repair when neither item is a book
- val repaired = resultItem.repairFrom(first, second)
- cost.repair = if (repaired) ConfigOptions.itemRepairCost else 0
- hasChanged = hasChanged || repaired
- }
-
- // Test/stop if nothing changed.
- if (!hasChanged) {
- CustomAnvil.log("Mergeable with second, But input is same as output")
- return AnvilResult.EMPTY
- }
- // As calculatePenalty edit result, we need to calculate penalty after checking equality
- cost.workPenalty = AnvilXpUtil.calculatePenalty(first, second, resultItem, AnvilUseType.MERGE)
- // Calculate rename cost
- cost.rename = handleRename(resultItem, inventory, player)
-
- val result =
- DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.MERGE, cost)
-
- return AnvilResult(result, cost)
- }
-
- private fun isIdentical(
- firstEnchants: MutableMap,
- resultEnchants: MutableMap
- ): Boolean {
- if (firstEnchants.size != resultEnchants.size) return false
- for (entry in resultEnchants) {
- if (firstEnchants.getOrDefault(entry.key, entry.value - 1) != entry.value) return false
- }
-
- return true
- }
-
- // return true if a custom recipe exist with these ingredients
- fun testCustomRecipe(
- view: InventoryView, //TODO use anvil view instead
- inventory: AnvilInventory,
- player: Player,
- first: ItemStack, second: ItemStack?
- ): CustomCraftResult {
- val recipe = CustomRecipeUtil.getCustomRecipe(first, second)
- CustomAnvil.verboseLog("custom recipe not null? ${recipe != null}")
- if (recipe == null) return CustomCraftResult.EMPTY
-
- val amount = CustomRecipeUtil.getCustomRecipeAmount(recipe, first, second)
-
- val resultItem: ItemStack = DependencyManager.cloneItem(player, recipe.resultItem!!)
- resultItem.amount *= amount
-
- // Maybe add an option on custom craft to ignore/not ignore penalty ??
- val xpCost = recipe.determineCost(amount, first, resultItem)
-
- val cost = CustomCraftCost(xpCost)
- // This is for displayed cost
- cost.recipe = if (recipe.removeExactLinearXp) AnvilXpUtil.calculateMinimumLevelForXp(xpCost)
- else AnvilXpUtil.calculateLevelForXp(xpCost)
-
- val result =
- DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.CUSTOM_CRAFT, cost)
- return CustomCraftResult(result, cost, amount, recipe)
- }
-
- fun testUnitRepair(
- view: InventoryView, //TODO use anvil view
- inventory: AnvilInventory,
- player: Player,
- first: ItemStack, second: ItemStack
- ): UnitRepairResult {
- val unitRepairAmount = first.getRepair(second) ?: return UnitRepairResult.EMPTY
-
- return testUnitRepair(view, inventory, player, first, second, unitRepairAmount)
- }
-
- fun testUnitRepair(
- view: InventoryView, //TODO use anvil view instead
- inventory: AnvilInventory,
- player: Player,
- first: ItemStack, second: ItemStack,
- unitRepairAmount: Double
- ): UnitRepairResult {
- val resultItem = DependencyManager.cloneItem(player, first)
- val cost = AnvilCost()
- cost.rename = handleRename(resultItem, inventory, player)
-
- val repairAmount = resultItem.unitRepair(second.amount, unitRepairAmount)
- if (repairAmount > 0)
- cost.repair = repairAmount * ConfigOptions.unitRepairCost
-
- // We do not care about right item penalty for unit repair
- cost.workPenalty = AnvilXpUtil.calculatePenalty(first, null, resultItem, AnvilUseType.UNIT_REPAIR)
-
- // Test/stop if nothing changed.
- if (first == resultItem) {
- CustomAnvil.log("unit repair, But input is same as output")
- return UnitRepairResult.EMPTY
- }
-
- val result =
- DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.UNIT_REPAIR, cost)
- return UnitRepairResult(result, cost, repairAmount)
- }
-
- fun testLoreEdit(
- player: Player,
- first: ItemStack, second: ItemStack
- ): LoreEditResult {
- val type = second.type
-
- val result = if (Material.WRITABLE_BOOK == type)
- AnvilLoreEditUtil.tryLoreEditByBook(player, first, second)
- else if (Material.PAPER == type)
- AnvilLoreEditUtil.tryLoreEditByPaper(player, first, second)
- else LoreEditResult.EMPTY
-
- if (result.isEmpty()) return result
-
- if (result.item!!.isAir || first == result.item) {
- CustomAnvil.log("lore edit, But input is same as output")
- return LoreEditResult.EMPTY
- }
-
- return result
- }
-
-}
\ No newline at end of file
diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilUseType.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilUseType.kt
deleted file mode 100644
index 67782f3..0000000
--- a/src/main/kotlin/xyz/alexcrea/cuanvil/anvil/AnvilUseType.kt
+++ /dev/null
@@ -1,67 +0,0 @@
-package xyz.alexcrea.cuanvil.anvil
-
-import org.bukkit.Material
-import xyz.alexcrea.cuanvil.config.WorkPenaltyType
-import xyz.alexcrea.cuanvil.util.anvil.AnvilUseTypeUtil
-
-enum class AnvilUseType(
- val typeName: String, val path: String,
- val defaultPenalty: WorkPenaltyType.WorkPenaltyPart,
- val displayName: String, val displayMat: Material
-) {
-
- RENAME_ONLY(
- "rename_only",
- WorkPenaltyType.WorkPenaltyPart(false, true),
- "Rename Only", Material.NAME_TAG
- ),
- MERGE(
- "merge",
- WorkPenaltyType.WorkPenaltyPart(true, true),
- "Merge", Material.ANVIL
- ),
- UNIT_REPAIR(
- "unit_repair",
- WorkPenaltyType.WorkPenaltyPart(true, true),
- "Unit Repair", Material.DIAMOND
- ),
- CUSTOM_CRAFT(
- "custom_craft",
- WorkPenaltyType.WorkPenaltyPart(false, false),
- "Custom Craft", Material.CRAFTING_TABLE
- ),
- LORE_EDIT_BOOK_APPEND(
- "lore_edit_book_append", "lore_edit.book_and_quil.append",
- WorkPenaltyType.WorkPenaltyPart(false, false),
- "Book Add", Material.WRITABLE_BOOK
- ),
- LORE_EDIT_BOOK_REMOVE(
- "lore_edit_book_remove", "lore_edit.book_and_quil.remove",
- WorkPenaltyType.WorkPenaltyPart(false, false),
- "Book Remove", Material.WRITABLE_BOOK
- ),
- LORE_EDIT_PAPER_APPEND(
- "lore_edit_paper_append", "lore_edit.paper.append_line",
- WorkPenaltyType.WorkPenaltyPart(false, false),
- "Paper Add", Material.WRITABLE_BOOK
- ),
- LORE_EDIT_PAPER_REMOVE(
- "lore_edit_paper_remove", "lore_edit.paper.remove_line",
- WorkPenaltyType.WorkPenaltyPart(false, false),
- "Paper Remove", Material.WRITABLE_BOOK
- ),
- ;
-
- constructor(
- typeName: String,
- defaultPenalty: WorkPenaltyType.WorkPenaltyPart,
- displayName: String, displayMat: Material
- ) :
- this(
- typeName,
- AnvilUseTypeUtil.defaultPath(typeName), // stupid util class
- defaultPenalty,
- displayName, displayMat
- )
-
-}
\ No newline at end of file
diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/CASubCommand.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/CASubCommand.kt
deleted file mode 100644
index 4c71c68..0000000
--- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/CASubCommand.kt
+++ /dev/null
@@ -1,46 +0,0 @@
-package xyz.alexcrea.cuanvil.command
-
-import org.bukkit.ChatColor
-import org.bukkit.command.Command
-import org.bukkit.command.CommandExecutor
-import org.bukkit.command.CommandSender
-
-abstract class CASubCommand: CommandExecutor {
-
- private var alreadySaid = false;
- override fun onCommand(
- sender: CommandSender,
- cmd: Command,
- cmdstr: String,
- args: Array
- ): Boolean {
- if(!alreadySaid){
- sender.sendMessage(ChatColor.RED.toString() +
- "Please not that this command will be replaced as a subcommand of `/customanvil` or `/ca`")
- alreadySaid = true
- }
-
- return executeCommand(sender, cmd, cmdstr, args)
- }
-
- abstract fun executeCommand(
- sender: CommandSender,
- cmd: Command,
- cmdstr: String,
- args: Array): Boolean
-
- open fun allowed(sender: CommandSender): Boolean {
- return true
- }
-
- open fun tabCompleter(
- sender: CommandSender,
- args: Array,
- list: MutableList) {
- }
-
- open fun description(): String {
- return "no description"
- }
-
-}
\ No newline at end of file
diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/CustomAnvilCommand.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/CustomAnvilCommand.kt
deleted file mode 100644
index e5e689e..0000000
--- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/CustomAnvilCommand.kt
+++ /dev/null
@@ -1,96 +0,0 @@
-package xyz.alexcrea.cuanvil.command
-
-import com.google.common.collect.ImmutableMap
-import io.delilaheve.CustomAnvil
-import org.bukkit.command.Command
-import org.bukkit.command.CommandExecutor
-import org.bukkit.command.CommandSender
-import org.bukkit.command.TabCompleter
-import xyz.alexcrea.cuanvil.util.MetricsUtil
-import java.util.ArrayList
-
-class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
-
- // Name of the generic command
- companion object {
- private const val genericCommandName = "customanvil"
- }
-
- private val editConfigCommand = EditConfigExecutor()
- private val helpCommand = HelpExecutor()
- private val commands = ImmutableMap.of(
- "gui", editConfigCommand,
- "reload", ReloadExecutor(),
- "diagnostic", DiagnosticExecutor(),
- "help", helpCommand,
- )
-
- init {
- val self = plugin.getCommand(genericCommandName)!!
- self.setExecutor(this)
- self.tabCompleter = this
-
- helpCommand.commands = commands
- }
-
- override fun onCommand(
- sender: CommandSender,
- cmd: Command,
- cmdstr: String,
- args: Array
- ): Boolean {
- // Find sub command to execute based on the provided command name
- val subcmd: CASubCommand?
- val newargs: Array
- if(args.isEmpty()) {
- subcmd = editConfigCommand
- newargs = args
- }else {
- subcmd = commands[args[0].lowercase()]
- newargs = args.copyOfRange(1, args.size)
- }
-
- if(subcmd == null || !subcmd.allowed(sender)) {
- sender.sendMessage("Invalid subcommand. run `$cmdstr help` to see available commands")
- return true
- }
-
- try {
- return subcmd.executeCommand(sender, cmd, cmdstr, newargs)
- } catch (e: Throwable) {
- MetricsUtil.trackError(e)
- sender.sendMessage("§cError running this command")
- return false
- }
- }
-
- override fun onTabComplete(
- sender: CommandSender,
- cmd: Command,
- cmdstr: String,
- args: Array
- ): MutableList {
- val result = ArrayList()
- if(args.size < 2) {
- for ((key, cmd) in commands) {
- if(!cmd.allowed(sender)) continue
- result.add(key)
- }
- } else {
- val subcmd = commands[args[0].lowercase()]
-
- if(subcmd != null) {
- val newArgs = args.copyOfRange(1, args.size)
- if(!subcmd.allowed(sender)) return result
-
- subcmd.tabCompleter(sender, newArgs, result)
- }
- }
-
- //assumed all provided tab completed string are lowercase
- return result.stream()
- .filter { it.startsWith(args[args.size - 1]) }
- .sorted()
- .toList()
- }
-}
diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/DiagnosticExecutor.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/DiagnosticExecutor.kt
deleted file mode 100644
index 053a3fc..0000000
--- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/DiagnosticExecutor.kt
+++ /dev/null
@@ -1,347 +0,0 @@
-package xyz.alexcrea.cuanvil.command
-
-import com.github.stefvanschie.inventoryframework.inventoryview.interface_.InventoryViewUtil
-import io.delilaheve.CustomAnvil
-import net.md_5.bungee.api.chat.ClickEvent
-import net.md_5.bungee.api.chat.HoverEvent
-import net.md_5.bungee.api.chat.TextComponent
-import net.md_5.bungee.api.chat.hover.content.Text
-import org.bukkit.Bukkit
-import org.bukkit.ChatColor
-import org.bukkit.Material
-import org.bukkit.command.Command
-import org.bukkit.command.CommandSender
-import org.bukkit.enchantments.Enchantment
-import org.bukkit.entity.HumanEntity
-import org.bukkit.entity.Player
-import org.bukkit.event.inventory.InventoryType
-import org.bukkit.event.inventory.PrepareAnvilEvent
-import org.bukkit.inventory.AnvilInventory
-import org.bukkit.inventory.InventoryView
-import org.bukkit.inventory.ItemStack
-import org.bukkit.inventory.meta.Damageable
-import org.bukkit.inventory.meta.EnchantmentStorageMeta
-import org.bukkit.plugin.Plugin
-import org.bukkit.plugin.RegisteredListener
-import xyz.alexcrea.cuanvil.dependency.DependencyManager
-import xyz.alexcrea.cuanvil.dependency.packet.NoPacketManager
-import xyz.alexcrea.cuanvil.dependency.packet.ProtocoLibWrapper
-import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry
-import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener
-import xyz.alexcrea.cuanvil.util.MetricsUtil
-import java.util.*
-import java.util.stream.Collectors
-
-
-class DiagnosticExecutor: CASubCommand() {
-
- companion object{
- private const val NO_DIAG_PERM = "You do not have permission to diagnostic this server"
-
- fun fetchNMSType(): String {
- val packetManager = DependencyManager.packetManager
- val packetManagerClass = packetManager.javaClass
-
- val className = packetManagerClass.name
- val result = if(className.contains("PaperPacket")) {
- "Paper"
- } else {
- when (packetManagerClass) {
- ProtocoLibWrapper::class.java -> "Protocolib"
- NoPacketManager::class.java -> "None"
- else -> "Version Specific"
- }
- }
-
-
- return "$result ${if(packetManager.canSetInstantBuild) '✅' else '❌'}"
- }
- }
-
- enum class DiagParams(val value: String) {
- OS_PRIVACY("os_privacy"),
- PLUGIN_PRIVACY("plugin_privacy"),
- NO_MERGE_TEST("no_merge_test"),
- FULL_ENCHANTMENT_DATA("full_enchantment_data"),
- INCLUDE_LAST_ERROR("include_last_error"),
- }
-
- private fun fetchParameters(args: Array): EnumSet {
- val result = EnumSet.noneOf(DiagParams::class.java)
- val argSet = HashSet()
-
- for (string in args) {
- argSet.add(string.lowercase())
- }
-
- for (param in DiagParams.entries) {
- if(argSet.contains(param.value))
- result.add(param)
- }
-
- return result
- }
-
- override fun tabCompleter(
- sender: CommandSender,
- args: Array,
- list: MutableList) {
- if(!allowed(sender)) return
-
- val map = fetchParameters(args)
- for (param in DiagParams.entries) {
- if(!map.contains(param))
- list.add(param.value)
- }
-
- }
-
- override fun executeCommand(
- sender: CommandSender,
- cmd: Command,
- cmdstr: String,
- args: Array
- ): Boolean {
- if (!allowed(sender)) {
- sender.sendMessage(NO_DIAG_PERM)
- return false
- }
-
- val stb = StringBuilder("```\n")
- val params = fetchParameters(args)
- var hasError = false
- try {
- diagnostic(sender, stb, params)
- } catch(e: Throwable){
- stb.append("\n\nError happened trying to get diagnostic data:\n")
- .append(e.message).append("\n")
- .append(e.stackTrace.joinToString("\n"))
- hasError = true
- e.printStackTrace()
- }
-
- stb.append("\n```")
-
- if (sender is HumanEntity) {
- if(hasError)
- sender.spigot().sendMessage(TextComponent(ChatColor.RED.toString() + "There was an error running the diagnostic"))
- val message = TextComponent(ChatColor.GREEN.toString() + "Click to copy diagnostic data")
-
- message.clickEvent = ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, stb.toString())
- message.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text("§7Click to copy"))
-
- sender.spigot().sendMessage(message);
- } else {
- sender.sendMessage(stb.toString());
- }
-
- return true
- }
-
- override fun allowed(sender: CommandSender): Boolean {
- return sender.hasPermission(CustomAnvil.diagnosticPermission)
- }
-
- fun diagnostic(sender: CommandSender, stb: StringBuilder, params: Set