1.21 cleanup and fix

also random cleanup
This commit is contained in:
alexcrea 2026-06-03 17:53:17 +02:00
parent 2241fbd720
commit f97e3c937d
Signed by: alexcrea
GPG key ID: E346CD16413450E3
31 changed files with 240 additions and 224 deletions

View file

@ -16,6 +16,7 @@ import org.bukkit.inventory.AnvilInventory
import org.bukkit.inventory.InventoryView import org.bukkit.inventory.InventoryView
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.ItemMeta import org.bukkit.inventory.meta.ItemMeta
import org.bukkit.inventory.view.AnvilView
import org.bukkit.persistence.PersistentDataType import org.bukkit.persistence.PersistentDataType
import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.dependency.DependencyManager
import xyz.alexcrea.cuanvil.dialog.AnvilRenameDialog import xyz.alexcrea.cuanvil.dialog.AnvilRenameDialog
@ -32,6 +33,7 @@ import xyz.alexcrea.cuanvil.util.anvil.AnvilXpUtil
import xyz.alexcrea.cuanvil.util.config.LoreEditType import xyz.alexcrea.cuanvil.util.config.LoreEditType
import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil
@Suppress("UnstableApiUsage")
object AnvilMergeLogic { object AnvilMergeLogic {
open class AnvilResult { open class AnvilResult {
@ -104,7 +106,7 @@ object AnvilMergeLogic {
): AnvilResult { ): AnvilResult {
val resultItem = DependencyManager.cloneItem(player, first) val resultItem = DependencyManager.cloneItem(player, first)
val cost = AnvilCost() val cost = AnvilCost()
cost.rename = handleRename(resultItem, inventory, player) cost.rename = handleRename(resultItem, view, player)
// Test/stop if nothing changed. // Test/stop if nothing changed.
if (first == resultItem) { if (first == resultItem) {
@ -137,9 +139,9 @@ object AnvilMergeLogic {
} }
} }
private fun handleRename(resultItem: ItemStack, inventory: AnvilInventory, player: HumanEntity): Int { private fun handleRename(resultItem: ItemStack, view: AnvilView, player: HumanEntity): Int {
// Can be null // Can be null
var renameText = ChatColor.stripColor(inventory.renameText) var renameText = ChatColor.stripColor(view.renameText)
var sumCost = 0 var sumCost = 0
var useColor = false var useColor = false
@ -217,7 +219,7 @@ object AnvilMergeLogic {
// As calculatePenalty edit result, we need to calculate penalty after checking equality // As calculatePenalty edit result, we need to calculate penalty after checking equality
cost.workPenalty = AnvilXpUtil.calculatePenalty(first, second, resultItem, AnvilUseType.MERGE) cost.workPenalty = AnvilXpUtil.calculatePenalty(first, second, resultItem, AnvilUseType.MERGE)
// Calculate rename cost // Calculate rename cost
cost.rename = handleRename(resultItem, inventory, player) cost.rename = handleRename(resultItem, view, player)
val result = val result =
DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.MERGE, cost) DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.MERGE, cost)
@ -286,7 +288,7 @@ object AnvilMergeLogic {
): UnitRepairResult { ): UnitRepairResult {
val resultItem = DependencyManager.cloneItem(player, first) val resultItem = DependencyManager.cloneItem(player, first)
val cost = AnvilCost() val cost = AnvilCost()
cost.rename = handleRename(resultItem, inventory, player) cost.rename = handleRename(resultItem, view, player)
val repairAmount = resultItem.unitRepair(second.amount, unitRepairAmount) val repairAmount = resultItem.unitRepair(second.amount, unitRepairAmount)
if (repairAmount > 0) if (repairAmount > 0)

View file

@ -5,7 +5,7 @@ import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
abstract class CASubCommand: CommandExecutor { abstract class CASubCommand : CommandExecutor {
private var alreadySaid = false; private var alreadySaid = false;
override fun onCommand( override fun onCommand(
@ -14,9 +14,11 @@ abstract class CASubCommand: CommandExecutor {
cmdstr: String, cmdstr: String,
args: Array<out String> args: Array<out String>
): Boolean { ): Boolean {
if(!alreadySaid){ if (!alreadySaid) {
sender.sendMessage(ChatColor.RED.toString() + sender.sendMessage(
"Please not that this command will be replaced as a subcommand of `/customanvil` or `/ca`") ChatColor.RED.toString() +
"Please not that this command will be replaced as a subcommand of `/customanvil` or `/ca`"
)
alreadySaid = true alreadySaid = true
} }
@ -27,7 +29,8 @@ abstract class CASubCommand: CommandExecutor {
sender: CommandSender, sender: CommandSender,
cmd: Command, cmd: Command,
cmdstr: String, cmdstr: String,
args: Array<out String>): Boolean args: Array<out String>
): Boolean
open fun allowed(sender: CommandSender): Boolean { open fun allowed(sender: CommandSender): Boolean {
return true return true
@ -36,7 +39,8 @@ abstract class CASubCommand: CommandExecutor {
open fun tabCompleter( open fun tabCompleter(
sender: CommandSender, sender: CommandSender,
args: Array<out String>, args: Array<out String>,
list: MutableList<String>) { list: MutableList<String>
) {
} }
open fun description(): String { open fun description(): String {

View file

@ -7,7 +7,6 @@ import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
import org.bukkit.command.TabCompleter import org.bukkit.command.TabCompleter
import xyz.alexcrea.cuanvil.util.MetricsUtil import xyz.alexcrea.cuanvil.util.MetricsUtil
import java.util.ArrayList
class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter { class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
@ -42,15 +41,15 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
// Find sub command to execute based on the provided command name // Find sub command to execute based on the provided command name
val subcmd: CASubCommand? val subcmd: CASubCommand?
val newargs: Array<out String> val newargs: Array<out String>
if(args.isEmpty()) { if (args.isEmpty()) {
subcmd = editConfigCommand subcmd = editConfigCommand
newargs = args newargs = args
}else { } else {
subcmd = commands[args[0].lowercase()] subcmd = commands[args[0].lowercase()]
newargs = args.copyOfRange(1, args.size) newargs = args.copyOfRange(1, args.size)
} }
if(subcmd == null || !subcmd.allowed(sender)) { if (subcmd == null || !subcmd.allowed(sender)) {
sender.sendMessage("Invalid subcommand. run `$cmdstr help` to see available commands") sender.sendMessage("Invalid subcommand. run `$cmdstr help` to see available commands")
return true return true
} }
@ -71,17 +70,17 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
args: Array<out String> args: Array<out String>
): MutableList<String> { ): MutableList<String> {
val result = ArrayList<String>() val result = ArrayList<String>()
if(args.size < 2) { if (args.size < 2) {
for ((key, cmd) in commands) { for ((key, cmd) in commands) {
if(!cmd.allowed(sender)) continue if (!cmd.allowed(sender)) continue
result.add(key) result.add(key)
} }
} else { } else {
val subcmd = commands[args[0].lowercase()] val subcmd = commands[args[0].lowercase()]
if(subcmd != null) { if (subcmd != null) {
val newArgs = args.copyOfRange(1, args.size) val newArgs = args.copyOfRange(1, args.size)
if(!subcmd.allowed(sender)) return result if (!subcmd.allowed(sender)) return result
subcmd.tabCompleter(sender, newArgs, result) subcmd.tabCompleter(sender, newArgs, result)
} }

View file

@ -31,9 +31,9 @@ import java.util.*
import java.util.stream.Collectors import java.util.stream.Collectors
class DiagnosticExecutor: CASubCommand() { class DiagnosticExecutor : CASubCommand() {
companion object{ companion object {
private const val NO_DIAG_PERM = "You do not have permission to diagnostic this server" private const val NO_DIAG_PERM = "You do not have permission to diagnostic this server"
fun fetchNMSType(): String { fun fetchNMSType(): String {
@ -41,7 +41,7 @@ class DiagnosticExecutor: CASubCommand() {
val packetManagerClass = packetManager.javaClass val packetManagerClass = packetManager.javaClass
val className = packetManagerClass.name val className = packetManagerClass.name
val result = if(className.contains("PaperPacket")) { val result = if (className.contains("PaperPacket")) {
"Paper" "Paper"
} else { } else {
when (packetManagerClass) { when (packetManagerClass) {
@ -52,7 +52,7 @@ class DiagnosticExecutor: CASubCommand() {
} }
return "$result ${if(packetManager.canSetInstantBuild) '✅' else '❌'}" return "$result ${if (packetManager.canSetInstantBuild) '✅' else '❌'}"
} }
} }
@ -73,7 +73,7 @@ class DiagnosticExecutor: CASubCommand() {
} }
for (param in DiagParams.entries) { for (param in DiagParams.entries) {
if(argSet.contains(param.value)) if (argSet.contains(param.value))
result.add(param) result.add(param)
} }
@ -83,12 +83,13 @@ class DiagnosticExecutor: CASubCommand() {
override fun tabCompleter( override fun tabCompleter(
sender: CommandSender, sender: CommandSender,
args: Array<out String>, args: Array<out String>,
list: MutableList<String>) { list: MutableList<String>
if(!allowed(sender)) return ) {
if (!allowed(sender)) return
val map = fetchParameters(args) val map = fetchParameters(args)
for (param in DiagParams.entries) { for (param in DiagParams.entries) {
if(!map.contains(param)) if (!map.contains(param))
list.add(param.value) list.add(param.value)
} }
@ -110,7 +111,7 @@ class DiagnosticExecutor: CASubCommand() {
var hasError = false var hasError = false
try { try {
diagnostic(sender, stb, params) diagnostic(sender, stb, params)
} catch(e: Throwable){ } catch (e: Throwable) {
stb.append("\n\nError happened trying to get diagnostic data:\n") stb.append("\n\nError happened trying to get diagnostic data:\n")
.append(e.message).append("\n") .append(e.message).append("\n")
.append(e.stackTrace.joinToString("\n")) .append(e.stackTrace.joinToString("\n"))
@ -121,8 +122,9 @@ class DiagnosticExecutor: CASubCommand() {
stb.append("\n```") stb.append("\n```")
if (sender is HumanEntity) { if (sender is HumanEntity) {
if(hasError) if (hasError)
sender.spigot().sendMessage(TextComponent(ChatColor.RED.toString() + "There was an error running the diagnostic")) 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") val message = TextComponent(ChatColor.GREEN.toString() + "Click to copy diagnostic data")
message.clickEvent = ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, stb.toString()) message.clickEvent = ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, stb.toString())
@ -140,41 +142,41 @@ class DiagnosticExecutor: CASubCommand() {
return sender.hasPermission(CustomAnvil.diagnosticPermission) return sender.hasPermission(CustomAnvil.diagnosticPermission)
} }
fun diagnostic(sender: CommandSender, stb: StringBuilder, params: Set<DiagParams>){ fun diagnostic(sender: CommandSender, stb: StringBuilder, params: Set<DiagParams>) {
stb.append("Server Info\n") stb.append("Server Info\n")
val version = CustomAnvil.instance.description.version val version = CustomAnvil.instance.description.version
stb.append("\nPlugin Version: ").append(version) stb.append("\nPlugin Version: ").append(version)
if(version.contains("dev")) stb.append(" (alpha)") if (version.contains("dev")) stb.append(" (alpha)")
stb.append("\nLatest Update: ").append(CustomAnvil.latestVer) stb.append("\nLatest Update: ").append(CustomAnvil.latestVer)
stb.append("\nServer Version: ").append(Bukkit.getVersion()).append(" (").append(Bukkit.getName()).append(')') stb.append("\nServer Version: ").append(Bukkit.getVersion()).append(" (").append(Bukkit.getName()).append(')')
stb.append("\nPlugin Enabled: ").append(if(CustomAnvil.instance.isEnabled) "Yes" else "No") stb.append("\nPlugin Enabled: ").append(if (CustomAnvil.instance.isEnabled) "Yes" else "No")
stb.append("\nNMS type: ").append(fetchNMSType()) stb.append("\nNMS type: ").append(fetchNMSType())
if(!params.contains(DiagParams.OS_PRIVACY)) { if (!params.contains(DiagParams.OS_PRIVACY)) {
stb.append("\nJava Version: ").append(System.getProperty("java.version")) stb.append("\nJava Version: ").append(System.getProperty("java.version"))
stb.append("\nOS: ").append(System.getProperty("os.name")).append(" ") stb.append("\nOS: ").append(System.getProperty("os.name")).append(" ")
.append(System.getProperty("os.version")) .append(System.getProperty("os.version"))
.append(System.getProperty("os.arch")) .append(System.getProperty("os.arch"))
} }
stb.append("\nHad detect error: ").append(if(MetricsUtil.lastError != null) "Yes" else "No") stb.append("\nHad detect error: ").append(if (MetricsUtil.lastError != null) "Yes" else "No")
if(!params.contains(DiagParams.PLUGIN_PRIVACY)) { if (!params.contains(DiagParams.PLUGIN_PRIVACY)) {
pluginListDiag(sender, stb) pluginListDiag(sender, stb)
} }
prepareAnvilListeners(stb) prepareAnvilListeners(stb)
if(!params.contains(DiagParams.NO_MERGE_TEST)){ if (!params.contains(DiagParams.NO_MERGE_TEST)) {
if(sender is Player) testMerge(sender, stb) if (sender is Player) testMerge(sender, stb)
} }
stb.append("\n\nEnchantments data:") stb.append("\n\nEnchantments data:")
partialEnchantmentData(stb) partialEnchantmentData(stb)
if(params.contains(DiagParams.FULL_ENCHANTMENT_DATA)){ if (params.contains(DiagParams.FULL_ENCHANTMENT_DATA)) {
fullEnchantmentData(stb) fullEnchantmentData(stb)
} }
if(params.contains(DiagParams.INCLUDE_LAST_ERROR)){ if (params.contains(DiagParams.INCLUDE_LAST_ERROR)) {
includeLastError(stb) includeLastError(stb)
} }
} }
@ -286,22 +288,22 @@ class DiagnosticExecutor: CASubCommand() {
val xp = invView.repairCost val xp = invView.repairCost
val maxXp = invView.maximumRepairCost val maxXp = invView.maximumRepairCost
val mergeResult = invView.getItem(2) val mergeResult = invView.getItem(2)
stb.append("\n${if(result == mergeResult) "E" else "Une"}xpected Result") stb.append("\n${if (result == mergeResult) "E" else "Une"}xpected Result")
PrepareAnvilListener().anvilCombineCheck(event) PrepareAnvilListener().anvilCombineCheck(event)
// Now we check if item and xp same // Now we check if item and xp same
stb.append("\nXP/Max XP: ") stb.append("\nXP/Max XP: ")
.append(if(invView.repairCost == xp) "Correct" else "Incorrect") .append(if (invView.repairCost == xp) "Correct" else "Incorrect")
.append("/") .append("/")
.append(if(invView.maximumRepairCost == maxXp) "Correct" else "Incorrect") .append(if (invView.maximumRepairCost == maxXp) "Correct" else "Incorrect")
.append(" (${invView.repairCost} $xp|${invView.maximumRepairCost} $maxXp)") .append(" (${invView.repairCost} $xp|${invView.maximumRepairCost} $maxXp)")
.append("\nMerge result: ") .append("\nMerge result: ")
.append(if(invView.getItem(2) == mergeResult) "Correct" else "Incorrect") .append(if (invView.getItem(2) == mergeResult) "Correct" else "Incorrect")
PrepareAnvilListener.IS_EMPTY_TEST = true PrepareAnvilListener.IS_EMPTY_TEST = true
Bukkit.getPluginManager().callEvent(event) Bukkit.getPluginManager().callEvent(event)
stb.append("\nNull result test: ") stb.append("\nNull result test: ")
.append(if(event.result == null) "Correct" else "Incorrect") .append(if (event.result == null) "Correct" else "Incorrect")
invView.setItem(0, null) invView.setItem(0, null)
invView.setItem(1, null) invView.setItem(1, null)
@ -323,11 +325,13 @@ class DiagnosticExecutor: CASubCommand() {
map[enchant.key.namespace] = map.getOrDefault(enchant.key.namespace, 0) + 1 map[enchant.key.namespace] = map.getOrDefault(enchant.key.namespace, 0) + 1
} }
stb.append("\nNamespaces: ${ stb.append(
"\nNamespaces: ${
map.entries.stream() map.entries.stream()
.map { (key, value) -> "$key ($value)" } .map { (key, value) -> "$key ($value)" }
.reduce { a, b -> "$a, $b" }.get() .reduce { a, b -> "$a, $b" }.get()
}") }"
)
} }
@ -337,7 +341,6 @@ class DiagnosticExecutor: CASubCommand() {
stb.append("\n\nLast stack trace: ${e.stackTraceToString()}") stb.append("\n\nLast stack trace: ${e.stackTraceToString()}")
} }
} }

View file

@ -8,19 +8,21 @@ import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui import xyz.alexcrea.cuanvil.gui.config.MainConfigGui
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions
class EditConfigExecutor: CASubCommand() { class EditConfigExecutor : CASubCommand() {
override fun executeCommand(sender: CommandSender, override fun executeCommand(
sender: CommandSender,
cmd: Command, cmd: Command,
cmdstr: String, cmdstr: String,
args: Array<out String>): Boolean { args: Array<out String>
): Boolean {
if (sender !is HumanEntity) return false if (sender !is HumanEntity) return false
if (!allowed(sender)) { if (!allowed(sender)) {
sender.sendMessage(GuiGlobalActions.NO_EDIT_PERM) sender.sendMessage(GuiGlobalActions.NO_EDIT_PERM)
return false return false
} }
if(PlatformUtil.isFolia){ if (PlatformUtil.isFolia) {
sender.sendMessage("§cIt look like you are using Folia. Sadly Custom Anvil do not support Config gui for Folia.") sender.sendMessage("§cIt look like you are using Folia. Sadly Custom Anvil do not support Config gui for Folia.")
sender.sendMessage("§eIt is may come in a future version.") sender.sendMessage("§eIt is may come in a future version.")
sender.sendMessage("") sender.sendMessage("")

View file

@ -4,18 +4,20 @@ import com.google.common.collect.ImmutableMap
import org.bukkit.command.Command import org.bukkit.command.Command
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
class HelpExecutor: CASubCommand() { class HelpExecutor : CASubCommand() {
lateinit var commands: ImmutableMap<String, CASubCommand> lateinit var commands: ImmutableMap<String, CASubCommand>
override fun executeCommand(sender: CommandSender, override fun executeCommand(
sender: CommandSender,
cmd: Command, cmd: Command,
cmdstr: String, cmdstr: String,
args: Array<out String>): Boolean { args: Array<out String>
): Boolean {
val stb = StringBuilder("List of available commands:") val stb = StringBuilder("List of available commands:")
for ((key, cmd) in commands) { for ((key, cmd) in commands) {
if(!cmd.allowed(sender)) continue if (!cmd.allowed(sender)) continue
stb.append("\n- $key: ").append(cmd.description()) stb.append("\n- $key: ").append(cmd.description())
} }

View file

@ -3,7 +3,6 @@ package xyz.alexcrea.cuanvil.command
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import org.bukkit.Bukkit import org.bukkit.Bukkit
import org.bukkit.command.Command import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
import xyz.alexcrea.cuanvil.api.event.CAConfigReadyEvent import xyz.alexcrea.cuanvil.api.event.CAConfigReadyEvent
import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.config.ConfigHolder
@ -13,10 +12,12 @@ import xyz.alexcrea.cuanvil.update.UpdateHandler
class ReloadExecutor : CASubCommand() { class ReloadExecutor : CASubCommand() {
override fun executeCommand(sender: CommandSender, override fun executeCommand(
sender: CommandSender,
cmd: Command, cmd: Command,
cmdstr: String, cmdstr: String,
args: Array<out String>): Boolean { args: Array<out String>
): Boolean {
if (!allowed(sender)) { if (!allowed(sender)) {
sender.sendMessage("§cYou do not have permission to reload the config") sender.sendMessage("§cYou do not have permission to reload the config")
return false return false

View file

@ -35,6 +35,7 @@ import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener.Companion.ANVIL_OUTPUT
import xyz.alexcrea.cuanvil.util.MetricsUtil.trackError import xyz.alexcrea.cuanvil.util.MetricsUtil.trackError
import java.util.logging.Level import java.util.logging.Level
@Suppress("UnstableApiUsage")
object DependencyManager { object DependencyManager {
lateinit var scheduler: TaskScheduler lateinit var scheduler: TaskScheduler
@ -103,7 +104,7 @@ object DependencyManager {
axPlayerWarpsCompatibility = AxPlayerWarpsDependency() axPlayerWarpsCompatibility = AxPlayerWarpsDependency()
} }
if (pluginManager.isPluginEnabled("ItemsAdder")){ if (pluginManager.isPluginEnabled("ItemsAdder")) {
val dependency = ItemsAdderDependency(pluginManager.getPlugin("ItemsAdder")!!) val dependency = ItemsAdderDependency(pluginManager.getPlugin("ItemsAdder")!!)
itemsAdderCompatibility = dependency itemsAdderCompatibility = dependency
genericDependencies.add(dependency) genericDependencies.add(dependency)
@ -116,9 +117,9 @@ object DependencyManager {
if (pluginManager.isPluginEnabled("ItemsAdder")) if (pluginManager.isPluginEnabled("ItemsAdder"))
genericDependencies.add(GenericPluginDependency(pluginManager.getPlugin("ItemsAdder")!!)) genericDependencies.add(GenericPluginDependency(pluginManager.getPlugin("ItemsAdder")!!))
if (pluginManager.isPluginEnabled("SuperEnchants")){ if (pluginManager.isPluginEnabled("SuperEnchants")) {
val compatibility = SuperEnchantDependency(pluginManager.getPlugin("SuperEnchants")!!) val compatibility = SuperEnchantDependency(pluginManager.getPlugin("SuperEnchants")!!)
if(compatibility.registerEnchantments()) if (compatibility.registerEnchantments())
genericDependencies.add(compatibility) genericDependencies.add(compatibility)
} }
@ -307,7 +308,7 @@ object DependencyManager {
private fun unsafeCloneItem(item: ItemStack): ItemStack { private fun unsafeCloneItem(item: ItemStack): ItemStack {
val cloned = itemsAdderCompatibility?.tryClone(item) val cloned = itemsAdderCompatibility?.tryClone(item)
if(cloned != null) return cloned if (cloned != null) return cloned
return item.clone() return item.clone()
} }

View file

@ -26,7 +26,9 @@ object MinecraftVersionUtil {
} }
} }
val isTooNewForSpigot: Boolean get() { val isTooNewForSpigot: Boolean
get() {
return UpdateUtils.currentMinecraftVersion().major != 1 return UpdateUtils.currentMinecraftVersion().major != 1
} }

View file

@ -64,11 +64,11 @@ class GenericExternGuiTester {
} }
// Try if were in another plugin anvil inventory // Try if were in another plugin anvil inventory
fun testIfGui(inventory: InventoryView): Boolean { fun testIfGui(view: InventoryView): Boolean {
// In case we are in a test environment // In case we are in a test environment
if(isInTest()) return false if(isInTest()) return false
val clazz = getContainerClass(inventory) ?: return false val clazz = getContainerClass(view) ?: return false
val clazzName = clazz.name val clazzName = clazz.name
if(!PlatformUtil.isPaper){ if(!PlatformUtil.isPaper){

View file

@ -3,7 +3,7 @@ package xyz.alexcrea.cuanvil.dependency.packet
import org.bukkit.Bukkit import org.bukkit.Bukkit
import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.dependency.DependencyManager
import xyz.alexcrea.cuanvil.dependency.MinecraftVersionUtil import xyz.alexcrea.cuanvil.dependency.MinecraftVersionUtil
import xyz.alexcrea.cuanvil.dependency.packet.versions.* import xyz.alexcrea.cuanvil.dependency.packet.versions.PaperPacketManager
import xyz.alexcrea.cuanvil.update.UpdateUtils import xyz.alexcrea.cuanvil.update.UpdateUtils
object PacketManagerSelector { object PacketManagerSelector {

View file

@ -21,6 +21,7 @@ import xyz.alexcrea.cuanvil.util.anvil.AnvilXpUtil
import java.util.logging.Level import java.util.logging.Level
import kotlin.reflect.KClass import kotlin.reflect.KClass
@Suppress("UnstableApiUsage")
class DisenchantmentDependency { class DisenchantmentDependency {
init { init {

View file

@ -30,28 +30,29 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin)
"disable_anvil, " + "disable_anvil, " +
"incompatible_vanilla_enchantments, " + "incompatible_vanilla_enchantments, " +
"incompatible_custom_enchantments and max_level " + "incompatible_custom_enchantments and max_level " +
"configuration values.") "configuration values."
)
} }
fun disableAnvilListener(){ fun disableAnvilListener() {
PrepareAnvilEvent.getHandlerList().unregister(this.enchantmentSquaredPlugin) PrepareAnvilEvent.getHandlerList().unregister(this.enchantmentSquaredPlugin)
// Find the anvil click event // Find the anvil click event
var toRemove: AnvilListener? = null var toRemove: AnvilListener? = null
for (registered in InventoryClickEvent.getHandlerList().registeredListeners) { for (registered in InventoryClickEvent.getHandlerList().registeredListeners) {
val listener = registered.listener val listener = registered.listener
if(listener is AnvilListener) { if (listener is AnvilListener) {
toRemove = listener toRemove = listener
break break
} }
} }
if(toRemove != null) if (toRemove != null)
InventoryClickEvent.getHandlerList().unregister(toRemove) InventoryClickEvent.getHandlerList().unregister(toRemove)
} }
fun registerEnchantments(){ fun registerEnchantments() {
CustomAnvil.instance.logger.info("Preparing Enchantment Squared compatibility...") CustomAnvil.instance.logger.info("Preparing Enchantment Squared compatibility...")
// Register enchantments // Register enchantments
@ -69,20 +70,21 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin)
fun getEnchantmentsSquared(item: ItemStack, enchantments: MutableMap<CAEnchantment, Int>) { fun getEnchantmentsSquared(item: ItemStack, enchantments: MutableMap<CAEnchantment, Int>) {
val customEnchants = CustomEnchantManager.getInstance().getItemsEnchantsFromPDC(item) val customEnchants = CustomEnchantManager.getInstance().getItemsEnchantsFromPDC(item)
customEnchants.forEach{ customEnchants.forEach { (enchantment, level) ->
(enchantment, level ) -> enchantments[getWrappedEnchant(enchantment)] = level enchantments[getWrappedEnchant(enchantment)] = level
} }
} }
fun getKeyFromEnchant(enchant: CustomEnchant): NamespacedKey{ fun getKeyFromEnchant(enchant: CustomEnchant): NamespacedKey {
return NamespacedKey.fromString(enchant.type.lowercase(Locale.getDefault()), this.enchantmentSquaredPlugin)!! return NamespacedKey.fromString(enchant.type.lowercase(Locale.getDefault()), this.enchantmentSquaredPlugin)!!
} }
private fun getWrappedEnchant(enchant: CustomEnchant): CAEnchantment { private fun getWrappedEnchant(enchant: CustomEnchant): CAEnchantment {
return CAEnchantment.getByKey(getKeyFromEnchant(enchant))!! return CAEnchantment.getByKey(getKeyFromEnchant(enchant))!!
} }
fun registerPluginConfiguration(){ fun registerPluginConfiguration() {
CustomAnvil.instance.logger.info("Preparing Enchantment Squared config...") CustomAnvil.instance.logger.info("Preparing Enchantment Squared config...")
// Prepare enchantments // Prepare enchantments
@ -99,7 +101,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin)
CustomAnvil.instance.logger.info("Enchantment Squared should now work as expected !") CustomAnvil.instance.logger.info("Enchantment Squared should now work as expected !")
} }
private fun writeMissingGroups(){ private fun writeMissingGroups() {
// Write group that do not exist on custom anvil. // Write group that do not exist on custom anvil.
val shield = IncludeGroup("shield") val shield = IncludeGroup("shield")
shield.addToPolicy(Material.SHIELD.key) shield.addToPolicy(Material.SHIELD.key)
@ -114,7 +116,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin)
MaterialGroupApi.addMaterialGroup(trinkets) MaterialGroupApi.addMaterialGroup(trinkets)
} }
private fun writeMaterialRestriction(esEnchantments: List<CAEnchantSquaredEnchantment>){ private fun writeMaterialRestriction(esEnchantments: List<CAEnchantSquaredEnchantment>) {
for (enchantment in esEnchantments) { for (enchantment in esEnchantments) {
val conflict = ConflictBuilder("restriction_${enchantment.key.key}", CustomAnvil.instance) val conflict = ConflictBuilder("restriction_${enchantment.key.key}", CustomAnvil.instance)
conflict.addEnchantment(enchantment) conflict.addEnchantment(enchantment)
@ -125,7 +127,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin)
// Get allowed groups // Get allowed groups
for (esGroup in enchantment.enchant.compatibleItems) { for (esGroup in enchantment.enchant.compatibleItems) {
val caGroup = esGroupToCAGroup(esGroup) val caGroup = esGroupToCAGroup(esGroup)
if(caGroup == null){ if (caGroup == null) {
CustomAnvil.instance.logger.info("Could not find equivalent custom anvil group for $esGroup") CustomAnvil.instance.logger.info("Could not find equivalent custom anvil group for $esGroup")
continue continue
} }
@ -136,7 +138,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin)
} }
} }
private fun writeEnchantmentConflicts(esEnchantments: List<CAEnchantSquaredEnchantment>){ private fun writeEnchantmentConflicts(esEnchantments: List<CAEnchantSquaredEnchantment>) {
val otherEnchants = ArrayList<CAEnchantment>() val otherEnchants = ArrayList<CAEnchantment>()
otherEnchants.addAll(CAEnchantmentRegistry.getInstance().values()) otherEnchants.addAll(CAEnchantmentRegistry.getInstance().values())
@ -145,14 +147,14 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin)
// find conflicting enchantment. // find conflicting enchantment.
for (otherEnchant in otherEnchants) { for (otherEnchant in otherEnchants) {
if(enchantment.enchant.conflictsWithEnchantment(otherEnchant.name)){ if (enchantment.enchant.conflictsWithEnchantment(otherEnchant.name)) {
writeConflict(enchantment, otherEnchant) writeConflict(enchantment, otherEnchant)
} }
} }
} }
} }
private fun writeConflict(enchantment1: CAEnchantment, enchantment2: CAEnchantment){ private fun writeConflict(enchantment1: CAEnchantment, enchantment2: CAEnchantment) {
val conflict = ConflictBuilder("${enchantment1.name}_with_${enchantment2.name}_conflict", CustomAnvil.instance) val conflict = ConflictBuilder("${enchantment1.name}_with_${enchantment2.name}_conflict", CustomAnvil.instance)
conflict.addEnchantment(enchantment1).addEnchantment(enchantment2) conflict.addEnchantment(enchantment1).addEnchantment(enchantment2)
@ -165,7 +167,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin)
* Transform an Enchantment Squared group to a Custom Anvil group * Transform an Enchantment Squared group to a Custom Anvil group
*/ */
private fun esGroupToCAGroup(esGroup: String): String? { private fun esGroupToCAGroup(esGroup: String): String? {
return when(esGroup){ return when (esGroup) {
"SWORDS" -> "swords" "SWORDS" -> "swords"
"BOWS" -> "bow" "BOWS" -> "bow"
"CROSSBOWS" -> "crossbow" "CROSSBOWS" -> "crossbow"

View file

@ -17,10 +17,10 @@ import java.lang.reflect.Constructor
import java.lang.reflect.Method import java.lang.reflect.Method
import su.nightexpress.excellentenchants.api.EnchantRegistry as V5EnchantRegistry import su.nightexpress.excellentenchants.api.EnchantRegistry as V5EnchantRegistry
import su.nightexpress.excellentenchants.enchantment.impl.universal.CurseOfFragilityEnchant as LegacyCurseOfFragilityEnchant import su.nightexpress.excellentenchants.enchantment.impl.universal.CurseOfFragilityEnchant as LegacyCurseOfFragilityEnchant
import su.nightexpress.excellentenchants.manager.listener.AnvilListener as V5AnvilListener
import su.nightexpress.excellentenchants.enchantment.listener.AnvilListener as PreV5AnvilListener import su.nightexpress.excellentenchants.enchantment.listener.AnvilListener as PreV5AnvilListener
import su.nightexpress.excellentenchants.enchantment.listener.EnchantAnvilListener as LegacyAnvilListener import su.nightexpress.excellentenchants.enchantment.listener.EnchantAnvilListener as LegacyAnvilListener
import su.nightexpress.excellentenchants.enchantment.registry.EnchantRegistry as LegacyEnchantRegistry import su.nightexpress.excellentenchants.enchantment.registry.EnchantRegistry as LegacyEnchantRegistry
import su.nightexpress.excellentenchants.manager.listener.AnvilListener as V5AnvilListener
import su.nightexpress.excellentenchants.registry.EnchantRegistry as PreV5EnchantRegistry import su.nightexpress.excellentenchants.registry.EnchantRegistry as PreV5EnchantRegistry
// I don't like that I need to support older version. if I could just drop older support it would be sooo nice // I don't like that I need to support older version. if I could just drop older support it would be sooo nice
@ -53,7 +53,7 @@ class ExcellentEnchantsDependency {
if (listenerVersion == null) { if (listenerVersion == null) {
CustomAnvil.instance.logger.severe("Found issue with listener of Excellent Enchants. compatiblity is broken. please contact CustomAnvil devs") CustomAnvil.instance.logger.severe("Found issue with listener of Excellent Enchants. compatiblity is broken. please contact CustomAnvil devs")
} else{ } else {
CustomAnvil.log("Support version: " + listenerVersion.name) CustomAnvil.log("Support version: " + listenerVersion.name)
} }
@ -173,6 +173,7 @@ class ExcellentEnchantsDependency {
ListenerVersion.V5, ListenerVersion.V5,
ListenerVersion.V5_4, ListenerVersion.V5_4,
-> this.usedAnvilListener = v5AnvilListener!! -> this.usedAnvilListener = v5AnvilListener!!
ListenerVersion.PRE_V5 -> this.usedAnvilListener = preV5AnvilListener!! ListenerVersion.PRE_V5 -> this.usedAnvilListener = preV5AnvilListener!!
ListenerVersion.LEGACY -> this.usedAnvilListener = legacyAnvilListener!! ListenerVersion.LEGACY -> this.usedAnvilListener = legacyAnvilListener!!
null -> {} null -> {}
@ -240,6 +241,7 @@ class ExcellentEnchantsDependency {
ListenerVersion.V5_3, ListenerVersion.V5_3,
ListenerVersion.V5_4, ListenerVersion.V5_4,
-> v5AnvilListener!!.onClickAnvil(event) -> v5AnvilListener!!.onClickAnvil(event)
ListenerVersion.PRE_V5 -> preV5AnvilListener!!.onClickAnvil(event) ListenerVersion.PRE_V5 -> preV5AnvilListener!!.onClickAnvil(event)
ListenerVersion.LEGACY -> legacyAnvilListener!!.onClickAnvil(event) ListenerVersion.LEGACY -> legacyAnvilListener!!.onClickAnvil(event)
null -> {} null -> {}

View file

@ -24,7 +24,7 @@ open class GenericPluginDependency(protected open val plugin: Plugin, private va
} }
} }
open fun fillPreAnvil(preAnvil: ArrayList<RegisteredListener>){ open fun fillPreAnvil(preAnvil: ArrayList<RegisteredListener>) {
// get PreAnvil and PostAnvil listeners // get PreAnvil and PostAnvil listeners
for (registeredListener in PrepareAnvilEvent.getHandlerList().registeredListeners) { for (registeredListener in PrepareAnvilEvent.getHandlerList().registeredListeners) {
@ -35,12 +35,13 @@ open class GenericPluginDependency(protected open val plugin: Plugin, private va
protected open fun fillPostAnvil( protected open fun fillPostAnvil(
postAnvil: ArrayList<RegisteredListener>, postAnvil: ArrayList<RegisteredListener>,
preAnvil: ArrayList<RegisteredListener>) { preAnvil: ArrayList<RegisteredListener>
) {
} }
open fun testPrepareAnvil(event: PrepareAnvilEvent): Boolean { open fun testPrepareAnvil(event: PrepareAnvilEvent): Boolean {
if(!testPrepare) return false if (!testPrepare) return false
val previousResult = event.result val previousResult = event.result
event.result = null event.result = null
@ -61,7 +62,7 @@ open class GenericPluginDependency(protected open val plugin: Plugin, private va
} }
open fun testAnvilResult(event: InventoryClickEvent): Boolean { open fun testAnvilResult(event: InventoryClickEvent): Boolean {
if(!testPrepare) return false if (!testPrepare) return false
for (registeredListener in postAnvil) { for (registeredListener in postAnvil) {
// We do not want error from another plugin to be our fault // We do not want error from another plugin to be our fault

View file

@ -13,6 +13,7 @@ import xyz.alexcrea.cuanvil.anvil.AnvilCost
import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener
import xyz.alexcrea.cuanvil.util.anvil.AnvilXpUtil import xyz.alexcrea.cuanvil.util.anvil.AnvilXpUtil
@Suppress("UnstableApiUsage")
class HavenBagsDependency { class HavenBagsDependency {
init { init {

View file

@ -17,19 +17,19 @@ class ItemsAdderDependency(plugin: Plugin) : GenericPluginDependency(plugin) {
} }
fun tryClone(item: ItemStack): ItemStack? { fun tryClone(item: ItemStack): ItemStack? {
if(!isLoaded) return null if (!isLoaded) return null
val customItem = CustomStack.byItemStack(item) ?: return null val customItem = CustomStack.byItemStack(item) ?: return null
return CustomStack.getInstance(customItem.namespacedID)?.itemStack return CustomStack.getInstance(customItem.namespacedID)?.itemStack
} }
fun fromKey(key: NamespacedKey): ItemStack? { fun fromKey(key: NamespacedKey): ItemStack? {
if(!isLoaded) return null if (!isLoaded) return null
return CustomStack.getInstance(key.toString())?.itemStack return CustomStack.getInstance(key.toString())?.itemStack
} }
fun getKey(item: ItemStack) : NamespacedKey? { fun getKey(item: ItemStack): NamespacedKey? {
if(!isLoaded) return null if (!isLoaded) return null
val customItem = CustomStack.byItemStack(item) ?: return null val customItem = CustomStack.byItemStack(item) ?: return null
return NamespacedKey.fromString(customItem.namespacedID) return NamespacedKey.fromString(customItem.namespacedID)

View file

@ -15,7 +15,7 @@ import xyz.alexcrea.cuanvil.enchant.bulk.SuperEnchantBulkOperation
import xyz.alexcrea.cuanvil.enchant.wrapped.CASuperEnchantEnchantment import xyz.alexcrea.cuanvil.enchant.wrapped.CASuperEnchantEnchantment
import java.util.logging.Level import java.util.logging.Level
class SuperEnchantDependency: GenericPluginDependency { class SuperEnchantDependency : GenericPluginDependency {
override val plugin: SuperEnchants override val plugin: SuperEnchants
lateinit var enchManager: EnchantManager lateinit var enchManager: EnchantManager
@ -25,11 +25,11 @@ class SuperEnchantDependency: GenericPluginDependency {
this.plugin = plugin as SuperEnchants this.plugin = plugin as SuperEnchants
} }
fun registerEnchantments(): Boolean{ fun registerEnchantments(): Boolean {
CustomAnvil.instance.logger.info("Preparing Super Enchant compatibility...") CustomAnvil.instance.logger.info("Preparing Super Enchant compatibility...")
val field = SuperEnchants::class.java.getDeclaredField("enchantManager") val field = SuperEnchants::class.java.getDeclaredField("enchantManager")
if(field == null) { if (field == null) {
CustomAnvil.instance.logger.log(Level.SEVERE, "Failed to initialize Super Enchant compatibility") CustomAnvil.instance.logger.log(Level.SEVERE, "Failed to initialize Super Enchant compatibility")
return false return false
} }
@ -67,7 +67,7 @@ class SuperEnchantDependency: GenericPluginDependency {
reload?.setExecutor(ReloadInterceptor(reload.executor)) reload?.setExecutor(ReloadInterceptor(reload.executor))
} }
inner class ReloadInterceptor(val other: CommandExecutor): CommandExecutor { inner class ReloadInterceptor(val other: CommandExecutor) : CommandExecutor {
override fun onCommand( override fun onCommand(
sender: CommandSender, sender: CommandSender,

View file

@ -5,7 +5,6 @@ import lol.hyper.toolstats.tools.ItemChecker
import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.Plugin import org.bukkit.plugin.Plugin
import org.bukkit.plugin.RegisteredListener
import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener
import java.lang.reflect.Method import java.lang.reflect.Method

View file

@ -18,18 +18,19 @@ class EnchantConflictGroup(
fun addEnchantment(enchant: CAEnchantment) { fun addEnchantment(enchant: CAEnchantment) {
enchantments.add(enchant) enchantments.add(enchant)
} }
fun addEnchantments(enchants: List<CAEnchantment>) { fun addEnchantments(enchants: List<CAEnchantment>) {
enchantments.addAll(enchants) enchantments.addAll(enchants)
} }
private fun canBypassByBeforeLevel(enchants: Map<CAEnchantment, Int>): Boolean { private fun canBypassByBeforeLevel(enchants: Map<CAEnchantment, Int>): Boolean {
// Either there no "conflict after" // Either there no "conflict after"
if(conflictsAfterLevel.isEmpty()) return false if (conflictsAfterLevel.isEmpty()) return false
// Or we check if any conflict after enchantment is true // Or we check if any conflict after enchantment is true
for (entry in conflictsAfterLevel) { for (entry in conflictsAfterLevel) {
val current = enchants.getOrDefault(entry.key, 0) val current = enchants.getOrDefault(entry.key, 0)
if(current > entry.value) if (current > entry.value)
return false return false
} }
@ -38,12 +39,12 @@ class EnchantConflictGroup(
private fun canBypassByAfterLevel(enchants: Map<CAEnchantment, Int>): Boolean { private fun canBypassByAfterLevel(enchants: Map<CAEnchantment, Int>): Boolean {
// Either there no "conflict after" // Either there no "conflict after"
if(conflictsBeforeLevel.isEmpty()) return false if (conflictsBeforeLevel.isEmpty()) return false
// Or we check if any conflict after enchantment is true // Or we check if any conflict after enchantment is true
for (entry in conflictsBeforeLevel) { for (entry in conflictsBeforeLevel) {
val current = enchants.getOrDefault(entry.key, 0) val current = enchants.getOrDefault(entry.key, 0)
if(current < entry.value) if (current < entry.value)
return false return false
} }
@ -64,7 +65,7 @@ class EnchantConflictGroup(
return true return true
// If empty we skip. else we // If empty we skip. else we
if(canBypassConflictByLevel(enchants)) if (canBypassConflictByLevel(enchants))
return true return true
// Count the amount of enchantment that are in the list // Count the amount of enchantment that are in the list
@ -102,7 +103,7 @@ class EnchantConflictGroup(
fun putConflictAfterLevel(enchantment: CAEnchantment, level: Int): Boolean { fun putConflictAfterLevel(enchantment: CAEnchantment, level: Int): Boolean {
return null != ( return null != (
if(level < 0) conflictsAfterLevel.remove(enchantment) if (level < 0) conflictsAfterLevel.remove(enchantment)
else conflictsAfterLevel.put(enchantment, level)) else conflictsAfterLevel.put(enchantment, level))
} }
@ -117,7 +118,7 @@ class EnchantConflictGroup(
fun putConflictsBeforeLevel(enchantment: CAEnchantment, level: Int): Boolean { fun putConflictsBeforeLevel(enchantment: CAEnchantment, level: Int): Boolean {
return null != ( return null != (
if(level < 0) conflictsBeforeLevel.remove(enchantment) if (level < 0) conflictsBeforeLevel.remove(enchantment)
else conflictsBeforeLevel.put(enchantment, level)) else conflictsBeforeLevel.put(enchantment, level))
} }

View file

@ -10,7 +10,6 @@ import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry
import xyz.alexcrea.cuanvil.util.MaterialUtil.customType import xyz.alexcrea.cuanvil.util.MaterialUtil.customType
import java.util.* import java.util.*
import kotlin.collections.set
class EnchantConflictManager { class EnchantConflictManager {
@ -66,7 +65,7 @@ class EnchantConflictManager {
val keys = config.getKeys(false) val keys = config.getKeys(false)
for (key in keys) { for (key in keys) {
val section = config.getConfigurationSection(key) val section = config.getConfigurationSection(key)
if(section == null) { if (section == null) {
warnBadKey(key) warnBadKey(key)
continue continue
} }
@ -140,8 +139,12 @@ class EnchantConflictManager {
return conflict return conflict
} }
private fun fetchConditionalRestriction(restrictions: MutableMap<CAEnchantment, Int>, section: ConfigurationSection?, conflictName: String) { private fun fetchConditionalRestriction(
if(section == null) return restrictions: MutableMap<CAEnchantment, Int>,
section: ConfigurationSection?,
conflictName: String
) {
if (section == null) return
for (enchantName in section.getKeys(false)) { for (enchantName in section.getKeys(false)) {
val enchants = getEnchantByIdentifier(enchantName) val enchants = getEnchantByIdentifier(enchantName)
if (enchants.isEmpty()) { if (enchants.isEmpty()) {
@ -150,7 +153,7 @@ class EnchantConflictManager {
} }
val value = section.getInt(enchantName, -1) val value = section.getInt(enchantName, -1)
if(value < 0) continue if (value < 0) continue
for (enchant in enchants) { for (enchant in enchants) {
val previous = restrictions.getOrDefault(enchant, value) val previous = restrictions.getOrDefault(enchant, value)

View file

@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.group package xyz.alexcrea.cuanvil.group
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import java.util.*
class ExcludeGroup(name: String) : AbstractMaterialGroup(name) { class ExcludeGroup(name: String) : AbstractMaterialGroup(name) {

View file

@ -1,8 +1,6 @@
package xyz.alexcrea.cuanvil.group package xyz.alexcrea.cuanvil.group
import org.bukkit.Material
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import java.util.*
class IncludeGroup(name: String) : AbstractMaterialGroup(name) { class IncludeGroup(name: String) : AbstractMaterialGroup(name) {
override fun createDefaultSet(): MutableSet<NamespacedKey> { override fun createDefaultSet(): MutableSet<NamespacedKey> {

View file

@ -41,7 +41,7 @@ class ItemGroupManager {
fun createGroup( fun createGroup(
config: ConfigurationSection, config: ConfigurationSection,
name: String name: String
): AbstractMaterialGroup{ ): AbstractMaterialGroup {
return createGroup(config, groupMap.keys, name) return createGroup(config, groupMap.keys, name)
} }
@ -110,10 +110,9 @@ class ItemGroupManager {
// Get other group or create it if not yet created // Get other group or create it if not yet created
val otherGroup = val otherGroup =
if (!groupMap.containsKey(groupName)) { if (!groupMap.containsKey(groupName)) {
if(!config.isConfigurationSection(groupName)) continue if (!config.isConfigurationSection(groupName)) continue
createGroup(config, keys, groupName) createGroup(config, keys, groupName)
} } else groupMap[groupName]!!
else groupMap[groupName]!!
// Avoid self reference or it will create an infinite loop // Avoid self reference or it will create an infinite loop
if (otherGroup.isReferencing(group)) { if (otherGroup.isReferencing(group)) {

View file

@ -4,7 +4,7 @@ import org.bukkit.NamespacedKey
import xyz.alexcrea.cuanvil.util.MaterialUtil import xyz.alexcrea.cuanvil.util.MaterialUtil
import xyz.alexcrea.cuanvil.util.NegativeSet import xyz.alexcrea.cuanvil.util.NegativeSet
class NegativeMaterialSet: NegativeSet<NamespacedKey>() { class NegativeMaterialSet : NegativeSet<NamespacedKey>() {
override fun iterator(): MutableIterator<NamespacedKey> { override fun iterator(): MutableIterator<NamespacedKey> {
val materials = MaterialUtil.getMaterials() val materials = MaterialUtil.getMaterials()

View file

@ -9,13 +9,14 @@ import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil
@Suppress("UnstableApiUsage")
class AnvilCloseListener(private val packetManager: PacketManager) : Listener { class AnvilCloseListener(private val packetManager: PacketManager) : Listener {
@EventHandler @EventHandler
fun onAnvilClose(event: InventoryCloseEvent){ fun onAnvilClose(event: InventoryCloseEvent) {
val player = event.player val player = event.player
if(event.view !is AnvilView) return if (event.view !is AnvilView) return
if(player is Player && GameMode.CREATIVE != player.gameMode){ if (player is Player && GameMode.CREATIVE != player.gameMode) {
packetManager.setInstantBuild(player, false) packetManager.setInstantBuild(player, false)
} }

View file

@ -11,10 +11,9 @@ import org.bukkit.event.EventHandler
import org.bukkit.event.Listener import org.bukkit.event.Listener
import org.bukkit.event.inventory.ClickType import org.bukkit.event.inventory.ClickType
import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.inventory.AnvilInventory
import org.bukkit.inventory.InventoryView
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.BookMeta import org.bukkit.inventory.meta.BookMeta
import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.anvil.AnvilCost
import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic
import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.AnvilResult import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.AnvilResult
@ -37,6 +36,7 @@ import java.util.*
import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.atomic.AtomicReference
import kotlin.math.min import kotlin.math.min
@Suppress("UnstableApiUsage")
class AnvilResultListener : Listener { class AnvilResultListener : Listener {
companion object { companion object {
@ -51,7 +51,7 @@ class AnvilResultListener : Listener {
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
fun anvilExtractionCheck(event: InventoryClickEvent) { fun anvilExtractionCheck(event: InventoryClickEvent) {
val player = event.whoClicked as? Player ?: return val player = event.whoClicked as? Player ?: return
val inventory = event.inventory as? AnvilInventory ?: return val view = event.view as? AnvilView ?: return
val view = event.view val view = event.view
if (event.rawSlot != ANVIL_OUTPUT_SLOT) { if (event.rawSlot != ANVIL_OUTPUT_SLOT) {
@ -59,17 +59,17 @@ class AnvilResultListener : Listener {
} }
// Test if the event should bypass custom anvil. // Test if the event should bypass custom anvil.
if (DependencyManager.tryClickAnvilResultBypass(event, inventory)) return if (DependencyManager.tryClickAnvilResultBypass(event, view)) return
if (!player.hasPermission(CustomAnvil.affectedByPluginPermission)) return if (!player.hasPermission(CustomAnvil.affectedByPluginPermission)) return
val output = inventory.getItem(ANVIL_OUTPUT_SLOT) ?: return val output = view.getItem(ANVIL_OUTPUT_SLOT) ?: return
val leftItem = inventory.getItem(ANVIL_INPUT_LEFT) ?: return val leftItem = view.getItem(ANVIL_INPUT_LEFT) ?: return
val rightItem = inventory.getItem(ANVIL_INPUT_RIGHT) val rightItem = view.getItem(ANVIL_INPUT_RIGHT)
// Deny by default. allow if working // Deny by default. allow if working
event.result = Event.Result.DENY event.result = Event.Result.DENY
if (GameMode.CREATIVE != player.gameMode && inventory.repairCost >= inventory.maximumRepairCost) { if (GameMode.CREATIVE != player.gameMode && view.repairCost >= view.maximumRepairCost) {
return return
} }
@ -77,14 +77,14 @@ class AnvilResultListener : Listener {
val customRecipeResult = AnvilMergeLogic.testCustomRecipe(view, inventory, player, leftItem, rightItem) val customRecipeResult = AnvilMergeLogic.testCustomRecipe(view, inventory, player, leftItem, rightItem)
if (!customRecipeResult.isEmpty()) { if (!customRecipeResult.isEmpty()) {
onCustomCraft( onCustomCraft(
event, player, inventory, event, player, view,
leftItem, rightItem, customRecipeResult leftItem, rightItem, customRecipeResult
) )
return return
} }
// Do not continue if there was no change // Do not continue if there was no change
if ((output == inventory.getItem(ANVIL_INPUT_LEFT))) { if ((output == view.getItem(ANVIL_INPUT_LEFT))) {
return return
} }
@ -94,7 +94,7 @@ class AnvilResultListener : Listener {
if (result.isEmpty()) return if (result.isEmpty()) return
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
null, 0, null, 0,
null, 0, null, 0,
result result
@ -108,7 +108,7 @@ class AnvilResultListener : Listener {
val result = AnvilMergeLogic.doMerge(view, inventory, player, leftItem, rightItem) val result = AnvilMergeLogic.doMerge(view, inventory, player, leftItem, rightItem)
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
null, 0, null, 0,
null, 0, null, 0,
result result
@ -123,7 +123,7 @@ class AnvilResultListener : Listener {
) )
if (!unitRepairResult.isEmpty()) { if (!unitRepairResult.isEmpty()) {
onUnitRepairExtract( onUnitRepairExtract(
rightItem, event, player, inventory, rightItem, event, player, view,
unitRepairResult unitRepairResult
) )
return return
@ -133,9 +133,9 @@ class AnvilResultListener : Listener {
val loreResult = AnvilMergeLogic.testLoreEdit(player, leftItem, rightItem) val loreResult = AnvilMergeLogic.testLoreEdit(player, leftItem, rightItem)
if (!loreResult.isEmpty()) { if (!loreResult.isEmpty()) {
if (loreResult.type.isBook) if (loreResult.type.isBook)
handleBookLoreEdit(event, inventory, player, leftItem, rightItem, loreResult) handleBookLoreEdit(event, view, player, leftItem, rightItem, loreResult)
else else
handlePaperLoreEdit(event, inventory, player, leftItem, rightItem, loreResult) handlePaperLoreEdit(event, view, player, leftItem, rightItem, loreResult)
return return
} }
} }
@ -143,7 +143,7 @@ class AnvilResultListener : Listener {
private fun onCustomCraft( private fun onCustomCraft(
event: InventoryClickEvent, event: InventoryClickEvent,
player: Player, player: Player,
inventory: AnvilInventory, view: AnvilView,
leftItem: ItemStack, leftItem: ItemStack,
rightItem: ItemStack?, rightItem: ItemStack?,
result: CustomCraftResult, result: CustomCraftResult,
@ -181,7 +181,7 @@ class AnvilResultListener : Listener {
if (event.click != ClickType.MIDDLE && if (event.click != ClickType.MIDDLE &&
!handleCustomCraftClick( !handleCustomCraftClick(
event, event,
inventory, view,
player, player,
leftItem, leftItem,
rightItem, rightItem,
@ -199,7 +199,7 @@ class AnvilResultListener : Listener {
private fun handleCustomCraftClick( private fun handleCustomCraftClick(
event: InventoryClickEvent, event: InventoryClickEvent,
inventory: AnvilInventory, player: Player, view: AnvilView, player: Player,
leftItem: ItemStack, rightItem: ItemStack?, leftItem: ItemStack, rightItem: ItemStack?,
result: CustomCraftResult result: CustomCraftResult
): Boolean { ): Boolean {
@ -211,11 +211,11 @@ class AnvilResultListener : Listener {
if (recipe.rightItem == null) return false// in case it changed if (recipe.rightItem == null) return false// in case it changed
rightItem.amount -= amount * recipe.rightItem!!.amount rightItem.amount -= amount * recipe.rightItem!!.amount
inventory.setItem(ANVIL_INPUT_RIGHT, rightItem) view.setItem(ANVIL_INPUT_RIGHT, rightItem)
} }
leftItem.amount -= amount * recipe.leftItem!!.amount leftItem.amount -= amount * recipe.leftItem!!.amount
inventory.setItem(ANVIL_INPUT_LEFT, leftItem) view.setItem(ANVIL_INPUT_LEFT, leftItem)
removeCustomCraftCost(player, result) removeCustomCraftCost(player, result)
@ -224,17 +224,15 @@ class AnvilResultListener : Listener {
CustomAnvil.verboseLog("new amount is $newAmount") CustomAnvil.verboseLog("new amount is $newAmount")
if (newAmount <= 0 || recipe.exactCount) { if (newAmount <= 0 || recipe.exactCount) {
inventory.setItem(ANVIL_OUTPUT_SLOT, null) view.setItem(ANVIL_OUTPUT_SLOT, null)
} else { } else {
val resultItem: ItemStack = recipe.resultItem!!.clone() val resultItem: ItemStack = recipe.resultItem!!.clone()
resultItem.amount *= newAmount resultItem.amount *= newAmount
val newXp = newAmount * newAmount val newXp = newAmount * newAmount
inventory.repairCost = newXp view.repairCost = newXp
event.view.setProperty(InventoryView.Property.REPAIR_COST, newXp) view.setItem(ANVIL_OUTPUT_SLOT, resultItem)
inventory.setItem(ANVIL_OUTPUT_SLOT, resultItem)
player.updateInventory() player.updateInventory()
} }
@ -291,7 +289,7 @@ class AnvilResultListener : Listener {
private fun extractAnvilResult( private fun extractAnvilResult(
event: InventoryClickEvent, event: InventoryClickEvent,
player: Player, player: Player,
inventory: AnvilInventory, view: AnvilView,
leftItem: ItemStack?, leftItem: ItemStack?,
leftRemoveCount: Int, leftRemoveCount: Int,
rightItem: ItemStack?, rightItem: ItemStack?,
@ -305,7 +303,7 @@ class AnvilResultListener : Listener {
event.isCancelled = true event.isCancelled = true
val cost = result.cost val cost = result.cost
processCost(inventory, player, cost) processCost(view, player, cost)
if (!cost.valid && player.gameMode != GameMode.CREATIVE) return false if (!cost.valid && player.gameMode != GameMode.CREATIVE) return false
// Where should we get the item // Where should we get the item
@ -318,12 +316,12 @@ class AnvilResultListener : Listener {
// We remove what should be removed // We remove what should be removed
if (leftItem != null) leftItem.amount -= leftRemoveCount if (leftItem != null) leftItem.amount -= leftRemoveCount
inventory.setItem(ANVIL_INPUT_LEFT, leftItem) view.setItem(ANVIL_INPUT_LEFT, leftItem)
if (rightItem != null) rightItem.amount -= rightRemoveCount if (rightItem != null) rightItem.amount -= rightRemoveCount
inventory.setItem(ANVIL_INPUT_RIGHT, rightItem) view.setItem(ANVIL_INPUT_RIGHT, rightItem)
inventory.setItem(ANVIL_OUTPUT_SLOT, null) view.setItem(ANVIL_OUTPUT_SLOT, null)
} }
@ -338,7 +336,7 @@ class AnvilResultListener : Listener {
return true return true
} }
private fun processCost(inventory: AnvilInventory, player: Player, cost: AnvilCost) { private fun processCost(view: AnvilView, player: Player, cost: AnvilCost) {
var sum = cost.repair var sum = cost.repair
if ( if (
@ -356,7 +354,7 @@ class AnvilResultListener : Listener {
if (!EconomyManager.economy!!.has(player, cost.asMonetaryCost())) if (!EconomyManager.economy!!.has(player, cost.asMonetaryCost()))
cost.valid = false cost.valid = false
} else { } else {
if ((inventory.maximumRepairCost <= sum) if ((view.maximumRepairCost <= sum)
|| (player.level < sum) || (player.level < sum)
) cost.valid = false ) cost.valid = false
} }
@ -366,12 +364,12 @@ class AnvilResultListener : Listener {
rightItem: ItemStack, rightItem: ItemStack,
event: InventoryClickEvent, event: InventoryClickEvent,
player: Player, player: Player,
inventory: AnvilInventory, view: AnvilView,
result: UnitRepairResult, result: UnitRepairResult,
) { ) {
// We give the item manually // We give the item manually
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
null, 0, null, 0,
rightItem, result.repairAmount, rightItem, result.repairAmount,
result result
@ -380,21 +378,21 @@ class AnvilResultListener : Listener {
private fun handleBookLoreEdit( private fun handleBookLoreEdit(
event: InventoryClickEvent, event: InventoryClickEvent,
inventory: AnvilInventory, view: AnvilView,
player: Player, player: Player,
leftItem: ItemStack, leftItem: ItemStack,
rightItem: ItemStack, rightItem: ItemStack,
result: LoreEditResult result: LoreEditResult
) { ) {
if (result.type.isAppend) if (result.type.isAppend)
handleBookLoreAppend(event, inventory, player, rightItem, result) handleBookLoreAppend(event, view, player, rightItem, result)
else else
handleBookLoreRemove(event, inventory, player, leftItem, rightItem, result) handleBookLoreRemove(event, view, player, leftItem, rightItem, result)
} }
private fun handleBookLoreAppend( private fun handleBookLoreAppend(
event: InventoryClickEvent, event: InventoryClickEvent,
inventory: AnvilInventory, view: AnvilView,
player: Player, player: Player,
rightItem: ItemStack, rightItem: ItemStack,
result: LoreEditResult result: LoreEditResult
@ -412,7 +410,7 @@ class AnvilResultListener : Listener {
} }
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
null, 0, null, 0,
clearedBook, 0, clearedBook, 0,
result result
@ -421,7 +419,7 @@ class AnvilResultListener : Listener {
private fun handleBookLoreRemove( private fun handleBookLoreRemove(
event: InventoryClickEvent, event: InventoryClickEvent,
inventory: AnvilInventory, view: AnvilView,
player: Player, player: Player,
leftItem: ItemStack, leftItem: ItemStack,
rightItem: ItemStack, rightItem: ItemStack,
@ -457,7 +455,7 @@ class AnvilResultListener : Listener {
} }
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
null, 0, null, 0,
rightCopy, 0, rightCopy, 0,
result result
@ -466,21 +464,21 @@ class AnvilResultListener : Listener {
private fun handlePaperLoreEdit( private fun handlePaperLoreEdit(
event: InventoryClickEvent, event: InventoryClickEvent,
inventory: AnvilInventory, view: AnvilView,
player: Player, player: Player,
leftItem: ItemStack, leftItem: ItemStack,
rightItem: ItemStack, rightItem: ItemStack,
result: LoreEditResult result: LoreEditResult
) { ) {
if (result.type.isAppend) if (result.type.isAppend)
handlePaperLoreAppend(event, inventory, player, rightItem, result) handlePaperLoreAppend(event, view, player, rightItem, result)
else else
handlePaperLoreRemove(event, inventory, player, leftItem, rightItem, result) handlePaperLoreRemove(event, view, player, leftItem, rightItem, result)
} }
private fun handlePaperLoreAppend( private fun handlePaperLoreAppend(
event: InventoryClickEvent, event: InventoryClickEvent,
inventory: AnvilInventory, view: AnvilView,
player: Player, player: Player,
rightItem: ItemStack, rightItem: ItemStack,
result: LoreEditResult result: LoreEditResult
@ -505,14 +503,14 @@ class AnvilResultListener : Listener {
if (rightItem.amount > 1) { if (rightItem.amount > 1) {
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
paperCopy, 0, paperCopy, 0,
rightItem, 1, rightItem, 1,
result result
) )
} else { } else {
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
null, 0, null, 0,
paperCopy, 0, paperCopy, 0,
result result
@ -522,7 +520,7 @@ class AnvilResultListener : Listener {
private fun handlePaperLoreRemove( private fun handlePaperLoreRemove(
event: InventoryClickEvent, event: InventoryClickEvent,
inventory: AnvilInventory, view: AnvilView,
player: Player, player: Player,
leftItem: ItemStack, leftItem: ItemStack,
rightItem: ItemStack, rightItem: ItemStack,
@ -557,14 +555,14 @@ class AnvilResultListener : Listener {
if (rightItem.amount > 1) { if (rightItem.amount > 1) {
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
rightClone, 0, rightClone, 0,
rightItem, 1, rightItem, 1,
result result
) )
} else { } else {
extractAnvilResult( extractAnvilResult(
event, player, inventory, event, player, view,
null, 0, null, 0,
rightClone, 0, rightClone, 0,
result result

View file

@ -41,9 +41,10 @@ class ChatEventListener : Listener {
// sync callback with default server thread // sync callback with default server thread
DependencyManager.scheduler.scheduleOnEntity( DependencyManager.scheduler.scheduleOnEntity(
CustomAnvil.instance, player, CustomAnvil.instance, player,
Runnable { {
eventCallback.accept(event.message) eventCallback.accept(event.message)
}, 0L) }, 0L
)
} }
} }

View file

@ -1,6 +1,5 @@
package xyz.alexcrea.cuanvil.listener package xyz.alexcrea.cuanvil.listener
import com.github.stefvanschie.inventoryframework.util.InventoryViewUtil
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import io.delilaheve.util.ConfigOptions import io.delilaheve.util.ConfigOptions
import io.delilaheve.util.ItemUtil.canMergeWith import io.delilaheve.util.ItemUtil.canMergeWith
@ -16,6 +15,7 @@ import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.EnchantmentStorageMeta import org.bukkit.inventory.meta.EnchantmentStorageMeta
import org.bukkit.inventory.meta.ItemMeta import org.bukkit.inventory.meta.ItemMeta
import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.anvil.AnvilCost
import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.AnvilResult import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.AnvilResult
import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.doMerge import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.doMerge
import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.doRenaming import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.doRenaming
@ -30,6 +30,7 @@ import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil
/** /**
* Listener for anvil events * Listener for anvil events
*/ */
@Suppress("UnstableApiUsage")
class PrepareAnvilListener : Listener { class PrepareAnvilListener : Listener {
companion object { companion object {
@ -48,24 +49,23 @@ class PrepareAnvilListener : Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
fun anvilCombineCheck(event: PrepareAnvilEvent) { fun anvilCombineCheck(event: PrepareAnvilEvent) {
val view = event.view val view = event.view
val inventory = event.inventory val player = view.player
val player = InventoryViewUtil.getInstance().getPlayer(view) if (player !is Player) return
if(player !is Player) return
tryRenameDialog(player, event) tryRenameDialog(player, event)
// Test if custom anvil is bypassed before immutability test // Test if custom anvil is bypassed before immutability test
if (DependencyManager.earlyTryEventPreAnvilBypass(event, player)) { if (DependencyManager.earlyTryEventPreAnvilBypass(event, player)) {
// even if we got bypassed we still want to set price // even if we got bypassed we still want to set price
AnvilXpUtil.setAnvilInvCost(inventory, view, player, AnvilCost(event.inventory.repairCost)) AnvilXpUtil.setAnvilInvCost(view, player, AnvilCost(view.repairCost))
return return
} }
val first = inventory.getItem(ANVIL_INPUT_LEFT) val first = view.getItem(ANVIL_INPUT_LEFT)
val second = inventory.getItem(ANVIL_INPUT_RIGHT) val second = view.getItem(ANVIL_INPUT_RIGHT)
if(IS_EMPTY_TEST) { if (IS_EMPTY_TEST) {
IS_EMPTY_TEST = false IS_EMPTY_TEST = false
applyResult(event, player, AnvilResult.EMPTY) applyResult(event, player, AnvilResult.EMPTY)
return return
@ -86,7 +86,7 @@ class PrepareAnvilListener : Listener {
// Test if the event should bypass custom anvil. // Test if the event should bypass custom anvil.
if (DependencyManager.tryEventPreAnvilBypass(event, player)) { if (DependencyManager.tryEventPreAnvilBypass(event, player)) {
// even if we got bypassed we still want to set price // even if we got bypassed we still want to set price
AnvilXpUtil.setAnvilInvCost(inventory, view, player, AnvilCost(event.inventory.repairCost)) AnvilXpUtil.setAnvilInvCost(view, player, AnvilCost(view.repairCost))
return return
} }
@ -100,9 +100,9 @@ class PrepareAnvilListener : Listener {
view: InventoryView, //TODO use anvil view view: InventoryView, //TODO use anvil view
inventory: AnvilInventory, inventory: AnvilInventory,
player: Player, player: Player,
first: ItemStack?, second: ItemStack?) : AnvilResult first: ItemStack?, second: ItemStack?
{ ): AnvilResult {
if(first == null) if (first == null)
return AnvilResult.EMPTY return AnvilResult.EMPTY
// Test custom recipe // Test custom recipe
@ -137,7 +137,7 @@ class PrepareAnvilListener : Listener {
player: HumanEntity, player: HumanEntity,
event: PrepareAnvilEvent event: PrepareAnvilEvent
) { ) {
if(!ConfigOptions.canUseDialogRename(player)) return if (!ConfigOptions.canUseDialogRename(player)) return
AnvilRenameDialogUtil.anvilRenameDialog.tryShowDialog(player, event) AnvilRenameDialogUtil.anvilRenameDialog.tryShowDialog(player, event)
} }
@ -171,11 +171,11 @@ class PrepareAnvilListener : Listener {
private fun applyResult(event: PrepareAnvilEvent, player: Player, result: AnvilResult) { private fun applyResult(event: PrepareAnvilEvent, player: Player, result: AnvilResult) {
event.result = result.item event.result = result.item
if(result.item == null) { if (result.item == null) {
AnvilXpUtil.onNoResult(player, event.view) AnvilXpUtil.onNoResult(player, event.view)
return return
} }
AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, result.cost, result.ignoreXpRules) AnvilXpUtil.setAnvilInvCost(event.view, player, result.cost, result.ignoreXpRules)
} }
} }

View file

@ -1,6 +1,5 @@
package xyz.alexcrea.cuanvil.util package xyz.alexcrea.cuanvil.util
import org.bukkit.Bukkit
import org.bukkit.Material import org.bukkit.Material
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack

View file

@ -9,10 +9,10 @@ import org.bukkit.GameMode
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import org.bukkit.entity.Player import org.bukkit.entity.Player
import org.bukkit.inventory.AnvilInventory
import org.bukkit.inventory.InventoryView import org.bukkit.inventory.InventoryView
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.Repairable import org.bukkit.inventory.meta.Repairable
import org.bukkit.inventory.view.AnvilView
import org.bukkit.persistence.PersistentDataType import org.bukkit.persistence.PersistentDataType
import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.anvil.AnvilCost
import xyz.alexcrea.cuanvil.anvil.AnvilUseType import xyz.alexcrea.cuanvil.anvil.AnvilUseType
@ -23,6 +23,7 @@ import xyz.alexcrea.cuanvil.group.ConflictType
import xyz.alexcrea.cuanvil.util.AnvilTitleUtil import xyz.alexcrea.cuanvil.util.AnvilTitleUtil
import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil
@Suppress("UnstableApiUsage")
object AnvilXpUtil { object AnvilXpUtil {
const val EXCLUSIVE_PENALTY_PREFIX = "repair_cost" const val EXCLUSIVE_PENALTY_PREFIX = "repair_cost"
@ -31,17 +32,16 @@ object AnvilXpUtil {
* Display the required cost (either as xp or as ) * Display the required cost (either as xp or as )
*/ */
fun setAnvilInvCost( fun setAnvilInvCost(
inventory: AnvilInventory, view: AnvilView,
view: InventoryView,
player: Player, player: Player,
cost: AnvilCost, cost: AnvilCost,
ignoreRules: Boolean = false ignoreRules: Boolean = false
) { ) {
if (ConfigOptions.shouldUseMoney(player)) { if (ConfigOptions.shouldUseMoney(player)) {
cost.isMonetary = true cost.isMonetary = true
setAnvilPrice(inventory, view, player, cost) setAnvilPrice(view, player, cost)
} else } else
setAnvilInvXp(inventory, view, player, cost.filteredXpCost(ignoreRules), ignoreRules) setAnvilInvXp(view, player, cost.filteredXpCost(ignoreRules), ignoreRules)
} }
fun maximumXpCost(ignoreRules: Boolean = false): Int { fun maximumXpCost(ignoreRules: Boolean = false): Int {
@ -56,8 +56,7 @@ object AnvilXpUtil {
* Display xp needed for the work on the anvil inventory * Display xp needed for the work on the anvil inventory
*/ */
private fun setAnvilInvXp( private fun setAnvilInvXp(
inventory: AnvilInventory, view: AnvilView,
view: InventoryView,
player: HumanEntity, player: HumanEntity,
anvilCost: Int, anvilCost: Int,
ignoreRules: Boolean = false ignoreRules: Boolean = false
@ -65,8 +64,8 @@ object AnvilXpUtil {
val maximumRepairCost = maximumXpCost(ignoreRules) val maximumRepairCost = maximumXpCost(ignoreRules)
// Try first just in case another plugin, or the test need this // Try first just in case another plugin, or the test need this
inventory.maximumRepairCost = maximumRepairCost view.maximumRepairCost = maximumRepairCost
inventory.repairCost = anvilCost view.repairCost = anvilCost
// TODO for 2.x.x use anvil view & set directly there // TODO for 2.x.x use anvil view & set directly there
/* Because Minecraft likes to have the final say in the repair cost displayed /* Because Minecraft likes to have the final say in the repair cost displayed
@ -76,16 +75,15 @@ object AnvilXpUtil {
CustomAnvil.instance, player CustomAnvil.instance, player
) { ) {
// retry after a tick // retry after a tick
inventory.maximumRepairCost = maximumRepairCost view.maximumRepairCost = maximumRepairCost
inventory.repairCost = anvilCost view.repairCost = anvilCost
// TODO for 2.x.x use anvil view & set directly there
if (player !is Player) return@scheduleOnEntity if (player !is Player) return@scheduleOnEntity
if (player.gameMode != GameMode.CREATIVE) { if (player.gameMode != GameMode.CREATIVE) {
val bypassToExpensive = (ConfigOptions.doReplaceTooExpensive) && val bypassToExpensive = (ConfigOptions.doReplaceTooExpensive) &&
(anvilCost >= 40) && (anvilCost >= 40) &&
anvilCost < inventory.maximumRepairCost anvilCost < view.maximumRepairCost
DependencyManager.packetManager.setInstantBuild(player, bypassToExpensive) DependencyManager.packetManager.setInstantBuild(player, bypassToExpensive)
} }
@ -98,8 +96,7 @@ object AnvilXpUtil {
* Display monetary cost needed for the work on the anvil inventory * Display monetary cost needed for the work on the anvil inventory
*/ */
private fun setAnvilPrice( private fun setAnvilPrice(
inventory: AnvilInventory, view: AnvilView,
view: InventoryView,
player: Player, player: Player,
cost: AnvilCost, cost: AnvilCost,
) { ) {
@ -117,22 +114,20 @@ object AnvilXpUtil {
CustomAnvil.instance CustomAnvil.instance
) )
clearAnvilXpCost(inventory, view, player) clearAnvilXpCost(view, player)
} }
private fun clearAnvilXpCost( private fun clearAnvilXpCost(
inventory: AnvilInventory, view: AnvilView,
view: InventoryView,
player: HumanEntity, player: HumanEntity,
) { ) {
// TODO for 2.x.x use anvil view & set directly there view.repairCost = 0
inventory.repairCost = 0
// retry after a tick // retry after a tick
DependencyManager.scheduler.scheduleOnEntity( DependencyManager.scheduler.scheduleOnEntity(
CustomAnvil.instance, player CustomAnvil.instance, player
) { ) {
inventory.repairCost = 0 view.repairCost = 0
if (player !is Player) return@scheduleOnEntity if (player !is Player) return@scheduleOnEntity
player.updateInventory() player.updateInventory()