Compare commits

...

17 commits

Author SHA1 Message Date
036f480113
update from v1.18.0 2026-07-10 15:50:50 +02:00
13892f73b8
update from v1.x.x 2026-07-10 15:42:18 +02:00
5a6962b1c4
remove legacy command 2026-07-10 15:41:32 +02:00
0e65575c2b
rebase on news update 2026-07-10 15:41:31 +02:00
04ed7ea0b5
prepare for v2 2026-07-10 15:41:30 +02:00
63a9b5b1c6
rebase on new update 2026-07-10 15:41:09 +02:00
e2bbd66abf
1.21 cleanup and fix
also random cleanup
2026-07-10 15:40:55 +02:00
109ef0c5df
fix from rebase 2026-07-10 15:40:41 +02:00
38cf25ef1a
progress on 1.21 transition 2026-07-10 15:38:21 +02:00
5ba1bb98cc
initial 1.21 transition 2026-07-10 15:37:45 +02:00
862f9914fa
update faststat
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
2026-07-10 15:25:13 +02:00
497a3e84bc
fix /ca enchant
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
2026-07-08 17:36:47 +02:00
d469171e4d
fix support for enchantedbook
Some checks are pending
Java CI with Gradle / build (push) Waiting to run
2026-07-08 14:44:20 +02:00
b9ff4bdc40
add support for enchantedbook 2026-07-08 14:04:26 +02:00
16e4f0a923
fix using durability for max damage
Some checks are pending
Java CI with Gradle / build (push) Waiting to run
2026-07-08 04:26:13 +02:00
403c990083
migrate configanvil to ca config 2026-07-08 04:26:13 +02:00
e61baba175
remove use of useInFuture 2026-07-08 04:26:12 +02:00
120 changed files with 594 additions and 2710 deletions

View file

@ -9,9 +9,9 @@ name: Java CI with Gradle
on: on:
push: push:
branches: [ "v1.x.x", "v2.x.x" ] branches: [ "v1.x.x", "v2.x.x", "v3.x.x" ]
pull_request: pull_request:
branches: [ "v1.x.x", "v2.x.x" ] branches: [ "v1.x.x", "v2.x.x", "v3.x.x" ]
release: release:
types: [published] types: [published]
@ -26,7 +26,7 @@ jobs:
contents: write contents: write
env: env:
MODRINTH_VERSIONS: '["1.18.x", "1.19.x", "1.20.x", "1.21.x", "26.1.x", "26.2.x"]' MODRINTH_VERSIONS: '["1.21.x", "26.1.x", "26.2.x"]'
MODRINTH_PLATFORMS: '["spigot", "paper", "purpur", "folia"]' MODRINTH_PLATFORMS: '["spigot", "paper", "purpur", "folia"]'
steps: steps:

View file

@ -40,6 +40,8 @@ Custom Items support is considered unstable. If you find issue please report it
- [Disenchantment](https://www.spigotmc.org/resources/disenchantment-1-21-1-1-20-6-new-book-splitting-mechanics.110741/) by H7KZ - [Disenchantment](https://www.spigotmc.org/resources/disenchantment-1-21-1-1-20-6-new-book-splitting-mechanics.110741/) by H7KZ
Partially use Custom Anvil maximum XP settings (>= 6.1.5) Partially use Custom Anvil maximum XP settings (>= 6.1.5)
- [EnchantedBook](https://modrinth.com/plugin/enchantedbook) by Minacle
- [HavenBags](https://www.spigotmc.org/resources/havenbags-shulker-like-player-bound-bags-1-17-1-21-4.110420/) by hyperdefined - [HavenBags](https://www.spigotmc.org/resources/havenbags-shulker-like-player-bound-bags-1-17-1-21-4.110420/) by hyperdefined
For bag upgrade and skin via anvil. (version >= 1.31.0) For bag upgrade and skin via anvil. (version >= 1.31.0)

View file

@ -73,10 +73,9 @@ See the [Compatibility list](https://github.com/alexcrea/CustomAnvil/blob/v1.x.x
One of the configurations allow displaying price about 40 and removing Too Expensive. \ One of the configurations allow displaying price about 40 and removing Too Expensive. \
By how the minecraft client work: price above 40 can only be displayed green, even if the player does not own enough experience level. By how the minecraft client work: price above 40 can only be displayed green, even if the player does not own enough experience level.
spigot version 1.18 to 1.21.11 do not need any ProtocoLib dependency. (26.1.0 or above requires it) \ You do not need Protocolib unless you are using spigot above in 26.1 or above \
Any recent paper version also are supported for this feature.
But you should wait for update for new version containing new enchantable item or new enchantments if any of this got added. But you should wait for update or announcement for new version containing new enchantable item or new enchantments.
Else it is, likely, fine to use the current version you are ussing on a new paper version
### For custom enchantment plugin developers ### For custom enchantment plugin developers
For information about the API, please refer to [the Wiki](https://github.com/alexcrea/CustomAnvil/wiki) \ For information about the API, please refer to [the Wiki](https://github.com/alexcrea/CustomAnvil/wiki) \

View file

@ -22,7 +22,7 @@ plugins {
} }
group = "xyz.alexcrea" group = "xyz.alexcrea"
version = "1.18.0" version = "2.0.0"
val isDevBuild = System.getenv("SMALL_COMMIT_HASH") != null val isDevBuild = System.getenv("SMALL_COMMIT_HASH") != null
val isPreRelease = System.getenv("IS_GITHUB_PRERELEASE") == "true" val isPreRelease = System.getenv("IS_GITHUB_PRERELEASE") == "true"
@ -55,10 +55,10 @@ val reobfNMS = providers.gradleProperty("subprojects.reobfnms")
dependencies { dependencies {
// Spigot api // Spigot api
compileOnly("org.spigotmc:spigot-api:1.18-R0.1-SNAPSHOT") compileOnly("org.spigotmc:spigot-api:1.21-R0.1-SNAPSHOT")
// fast stats // fast stats
implementation("dev.faststats.metrics:bukkit:0.27.0") implementation("dev.faststats.metrics:bukkit:0.27.2")
// minimessage // minimessage
implementation("net.kyori:adventure-text-minimessage:4.25.0") implementation("net.kyori:adventure-text-minimessage:4.25.0")

View file

@ -1,6 +0,0 @@
### Default Plugin's Configurations For 1.18 to 1.20.6
- [config.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/config.yml)
- [enchant_conflict.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/enchant_conflict.yml)
- [item_groups.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/item_groups.yml)
- [unit_repair_item.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/unit_repair_item.yml)
- [custom_recipes.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/custom_recipes.yml)

View file

@ -1,472 +0,0 @@
#
# It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
#
# What service of metric should custom anvil use
# Custom anvil collect generic information like server minecraft version, type, etc...
# It can also collect error information if error is happening (currently faststats only)
# It can also be disabled
# Please refer to README for public metric link
# Possible options: auto, bstat, faststats, disabled (auto by default)
metric_type: auto
# Allow to report errors made caused by this plugin (only for faststats)
# This allows me to fix potentials issue that I'm not aware of
# Accept true or false (true by default)
metric_collect_errors: true
# All anvil cost will be capped to limit_repair_value if enabled.
#
# In other words:
# For any anvil cost greater than limit_repair_value, Cost will be set to limit_repair_value.
limit_repair_cost: false
# Max cost value the Anvil can get to.
#
# Valid values include 0 to 1000.
# Cost will be displayed as "Too Expensive":
# - If Cost is above 39
# - And replace_too_expensive is disabled (false)
limit_repair_value: 39
# Whether the anvil's cost limit should be removed entirely.
#
# The anvil will still visually display "Too Expensive" if "replace_too_expensive" is disabled
# However, the action will be completable if xp requirement is meet.
remove_repair_limit: false
# Whenever anvil cost is above 39 should display the true price and not "Too Expensive".
#
# However, when bypassing "Too Expensive", anvil price will be displayed as Green.
# If the action is not completable, the cost will still be displayed as "Too expensive".
# That mean you also need to change other settings like remove_repair_limit or limit_repair_cost.
#
# Require ProtocoLib.
replace_too_expensive: false
# XP Level amount added to the anvil when the item is repaired by another item of the same type
#
# Valid values include 0 to 1000
item_repair_cost: 2
# XP Level amount added to the anvil when the item is renamed
#
# Valid values include 0 to 1000
item_rename_cost: 1
# XP Level amount added to the anvil when the item is repaired by an "unit"
# For example: a Diamond on a Diamond Sword
# What's considered unit for what can be edited on the unit repair configuration.
#
# Valid values include 0 to 1000
unit_repair_cost: 1
# XP Level amount added to the anvil when a sacrifice enchantment
# conflict with one of the left item enchantment
#
# Valid values include 0 to 1000
sacrifice_illegal_enchant_cost: 1
# Allow using color code and hexadecimal color.
#
# Color code are prefixed by "&" and hexadecimal color by "#".
# Color code will not be applied if it colors nothing. "&&" can be used to write "&".
# For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/
allow_color_code: false
allow_hexadecimal_color: false
allow_minimessage: false
# This enables restricting color code for player having specific permission
# It requires allow_color_code enabled for... obvious reasons
#
# For example: if player want to use "&aHello" it will be required that the player has
# the permission "ca.color.code.a" as he used the color code "a"
# In general permission to give to the player is "ca.color.code.[code]"
# where [code] is the color code you wish to allow the player
#
# It is kinda of useless when minimessage is supported as players would be able to bypass
# that using the equivalent minimessage tag
per_color_code_permission: false
# Toggle if color should only be applicable if the player a certain permission.
#
# permission are "ca.color.code" for use of color code and "ca.color.hex" for use of hexadecimal color.
permission_needed_for_color: true
# Xp cost if the player use color in the items name on rename.
#
# Valid values include 0 to 1000.
use_of_color_cost: 0
# Dialogue rename menu make use of dialog menu to allow bigger rename
# You can also change the maximum size and set it to -1 or less for maximum
#
# This feature only work on paper 1.21.7 or later
#
# At the moment only english is available for this menu... sorry !
#
# CustomAnvil use "ca.rename.dialog" when permission
enable_dialog_rename: false
dialog_rename_max_size: 256
permission_needed_for_dialog_rename: false
# This allows custom anvil to not "guess" the text used for rename but store it in the item
# It will make item stackable only and only if it had used the same rename text
#
# For practical reason. this only work when dialog rename is enabled
dialog_rename_keep_user_text: true
# Also count left item enchantments for the final price
include_left_enchantment_for_cost: false
# Override limits for specific enchants
#
# Enchantments not listed here will use the value of default_limit
#
# Overrides provided default from aqua_affinity to depth_strider won't change effect with extra levels
#
# Valid range of 0 - 255 for each enchantment
# -1 mean keep default
enchant_limits:
minecraft:aqua_affinity: 1
minecraft:binding_curse: 1
minecraft:channeling: 1
minecraft:flame: 1
minecraft:infinity: 1
minecraft:mending: 1
minecraft:multishot: 1
minecraft:silk_touch: 1
minecraft:vanishing_curse: 1
minecraft:depth_strider: 3 # anything more than 3 is treated as 3 by the game
minecraft:protection: 4
minecraft:fire_protection: 4
minecraft:blast_protection: 4
minecraft:projectile_protection: 4
minecraft:feather_falling: 4
minecraft:thorns: 3
minecraft:respiration: 3
minecraft:sharpness: 5
minecraft:smite: 5
minecraft:bane_of_arthropods: 5
minecraft:knockback: 2
minecraft:fire_aspect: 2
minecraft:looting: 3
minecraft:sweeping: 3
minecraft:sweeping_edge: 3
minecraft:efficiency: 5
minecraft:unbreaking: 3
minecraft:fortune: 3
minecraft:power: 5
minecraft:punch: 2
minecraft:luck_of_the_sea: 3
minecraft:lure: 3
minecraft:frost_walker: 2
minecraft:impaling: 5
minecraft:riptide: 3
minecraft:loyalty: 3
minecraft:piercing: 4
minecraft:quick_charge: 3
minecraft:soul_speed: 3
minecraft:swift_sneak: 3
# Multipliers used to calculate the enchantment's value in repair/combining
#
# Values here are pulled from the minecraft wiki:
# https://minecraft.wiki/w/Anvil_mechanics#Costs_for_combining_enchantments
#
# If an enchantment is missing values here, or is less than 0, it will default to 0
#
# Calculated as: [Enchantment lvl] * [multiplier]
#
# With default values protection 4 would have a value of 4 when
# coming from either a book (4 * 1) or an item (4 * 1)
enchant_values:
minecraft:aqua_affinity:
item: 4
book: 2
minecraft:bane_of_arthropods:
item: 2
book: 1
minecraft:binding_curse:
item: 8
book: 4
minecraft:blast_protection:
item: 4
book: 2
minecraft:channeling:
item: 8
book: 4
minecraft:depth_strider:
item: 4
book: 2
minecraft:efficiency:
item: 1
book: 1
minecraft:flame:
item: 4
book: 2
minecraft:feather_falling:
item: 2
book: 1
minecraft:fire_aspect:
item: 4
book: 2
minecraft:fire_protection:
item: 2
book: 1
minecraft:fortune:
item: 4
book: 2
minecraft:frost_walker:
item: 4
book: 2
minecraft:impaling:
item: 4
book: 2
minecraft:infinity:
item: 8
book: 4
minecraft:knockback:
item: 2
book: 1
minecraft:looting:
item: 4
book: 2
minecraft:loyalty:
item: 1
book: 1
minecraft:luck_of_the_sea:
item: 4
book: 2
minecraft:lure:
item: 4
book: 2
minecraft:mending:
item: 4
book: 2
minecraft:multishot:
item: 4
book: 2
minecraft:piercing:
item: 1
book: 1
minecraft:power:
item: 1
book: 1
minecraft:projectile_protection:
item: 2
book: 1
minecraft:protection:
item: 1
book: 1
minecraft:punch:
item: 4
book: 2
minecraft:quick_charge:
item: 2
book: 1
minecraft:respiration:
item: 4
book: 2
minecraft:riptide:
item: 4
book: 2
minecraft:silk_touch:
item: 8
book: 4
minecraft:sharpness:
item: 1
book: 1
minecraft:smite:
item: 2
book: 1
minecraft:soul_speed:
item: 8
book: 4
minecraft:swift_sneak:
item: 8
book: 4
minecraft:sweeping:
item: 4
book: 2
minecraft:sweeping_edge:
item: 4
book: 2
minecraft:thorns:
item: 8
book: 4
minecraft:unbreaking:
item: 2
book: 1
minecraft:vanishing_curse:
item: 8
book: 4
# Disable enchantment merging for level above the set value
# Enchantment merging is when, for example, 2 unbreaking II book combine to give sharpness III
# But Enchantment above this value can still be applied. following the previous example, we could still apply a unbreaking III book to a sword
# Even if disable-merge-over of unbreaking is set to 2
# -1 mean enchantment merge for this enchantment is not disabled. default to -1 if absent.
disable-merge-over:
# Sharpness is set to -1. it equivalent to it not being set to anything (and work as vanilla on default configuration)
minecraft:sharpness: -1
# If uncommented. 2 unbreaking II book would not give an unbreaking III book. but unbreaking III book can still be applied
#minecraft:unbreaking: 2
# The maximum number of enchantment an item can get. -1 for infinity
# Use eco enchant enchant_limit if present by default unless "default" is not equal to -1
enchantment_count_limit:
default: -1
# Limit for specific items. example bellow is an example with stick
# Per item enchantment limit override eco enchant enchant_limit and default limit
items:
stick: -1
# Settings for lore modification
lore_edit:
book_and_quil:
# Permission is ca.lore_edit.book
use_permission: true
append:
# If adding lore using book & quil is enabled
enabled: false
# Cost used every time
fixed_cost: 1
# Cost used for every lore line added
per_line_cost: 0
# Use left item vanilla cost penalty if any
shared_increase: false
# Increase shared left item cost penalty
shared_additive: false
# If adding the lore consume the book & quil
do_consume: false
# Allow using color code and hexadecimal color when editing lore via book & quil
#
# Color code are prefixed by "&" and hexadecimal color by "#"
# Color code will not be applied if it colors nothing. "&&" can be used to write "&"
# For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/
#
# Note that currently minimessage would disable hex code when adding color
allow_color_code: true
allow_hexadecimal_color: false
allow_minimessage: true
remove:
# If removing lore using book & quil is enabled
enabled: false
# Cost used every time
fixed_cost: 1
# Cost used for every lore line removed
per_line_cost: 0
# Use left item vanilla cost penalty if any
shared_increase: false
# Increase shared left item cost penalty
shared_additive: false
# If removing the lore consume the book & quil
do_consume: false
# Cost of replacing colors
remove_color_cost: 0
# Allowed some color and tags to be reverted to plain text
# Custom anvil will prioritise format that result is a smaller resulting text
# Note that not allowing certain format will lead to some lost of color or tags.
# If configuration are exact as append appending this book should result in the exact same color
#
# Color code will be prefixed by "&" and hexadecimal color by "#".
# If color code is allowed, "&" in the text will get converted to "&&"
# For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/
allow_color_code: true
allow_hexadecimal_color: false
allow_minimessage: true
paper:
# Permission is ca.lore_edit.paper
use_permission: true
# what order should the lines should get added/removed (start/end, if invalid or not present will be end)
order: end
append_line:
# If adding lore line using paper is enabled
enabled: false
# Cost used every time
fixed_cost: 1
# Use left item vanilla cost penalty if any
shared_increase: false
# Increase shared left item cost penalty
shared_additive: false
# If adding the lore line consume the paper
do_consume: false
# Allow using color code and hexadecimal color when editing lore via book & quil
#
# Color code are prefixed by "&" and hexadecimal color by "#"
# Color code will not be applied if it colors nothing. "&&" can be used to write "&"
# For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/
#
# Note that currently minimessage would disable hex code when adding color
allow_color_code: true
allow_hexadecimal_color: false
allow_minimessage: true
color_use_cost: 0
remove_line:
# If removing lore line using paper is enabled
enabled: false
# Cost used every time
fixed_cost: 1
# Use left item vanilla cost penalty if any
shared_increase: false
# Increase shared left item cost penalty
shared_additive: false
# If removing the lore line consume the paper
do_consume: false
# Cost of replacing colors
remove_color_cost: 0
# Allowed some color and tags to be reverted to plain text
# Custom anvil will prioritise format that result is a smaller resulting text
# Note that not allowing certain format will lead to some lost of color or tags.
# If configuration are exact as append appending this paper should result in the exact same color
#
# Color code will be prefixed by "&" and hexadecimal color by "#".
# If color code is allowed, "&" in the text will get converted to "&&"
# For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/
allow_color_code: true
allow_hexadecimal_color: false
allow_minimessage: true
# Allow to replace the xp cost by a monetary cost
# If enabled it will not be bound to the experience level limits
#
# It also requires to enable dialog rename (set "enable_dialog_rename: false" a bit higher)
# If dialog rename permission is enabled and player do not have the permission merge will fall back to vanilla xp cost
#
# If you are using custom craft I recommend using Linear Xp Cost with Exact Linear Xp as normal Xp Cost will act "weird"
# But Linear Xp will act as 1$ time global multiplier. In other word: like you expect
#
# As this feature require dialog rename, it can only be enabled starting with paper 1.21.6 and later
monetary_cost:
enabled: false
# If using vault unlocked this allow to specify what currency should be used for anvil usage
# default being the default currency
currency: default
# multiply the anvil cost by a value to allow to have price a big bigger than like 40
multipliers:
# global multipliers. all usage type will be multiplied by this value
global: 1.0
# usage specific type. it will only apply for specific xp "reason"
enchantment: 1.0 # related to enchantments level
repair: 1.0 # for repairing via unit repair (per unit)
rename: 1.0 # for renaming the item
lore_edit: 1.0 # for changing the lore of the item (only if lore edit is enabled)
work_penalty: 1.0 # for work penalty (aka use penalty)
recipe: 1.0 # for custom anvil recipe cost
# Whether to show debug logging
debug_log: false
# Whether to show verbose debug logging
debug_log_verbose: false
# Whether to show inside the console or require to run /ca debug get
display_debug_in_console: false
configVersion: 1.11.0

View file

@ -1,5 +0,0 @@
# ----------------------------------------------------
# This config file is to store custom craft
# It is recommended to use the in game config editor for this configuration.
# /customanvilconfig With ca.config.edit permission
# ----------------------------------------------------

View file

@ -1,247 +0,0 @@
#
# It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
#
# material conflicts
#
# If you want to edit this file:
# - A conflict will apply to every item except if in one of the notAffectedGroups group
# - the conflict will count only if the user try to combine at least as
# many conflicting enchantment as "maxEnchantmentBeforeConflict"
#
#
# ----------------------------------------------------
# These restriction are about not allowing enchantment
# on illegal items
# ----------------------------------------------------
restriction_aqua_affinity:
enchantments: [ minecraft:aqua_affinity ]
notAffectedGroups: [ enchanted_book, helmets ]
restriction_bane_of_arthropods:
enchantments: [ minecraft:bane_of_arthropods ]
notAffectedGroups: [ enchanted_book, melee_weapons ]
restriction_blast_protection:
enchantments: [ minecraft:blast_protection ]
notAffectedGroups: [ enchanted_book, armors ]
restriction_channeling:
enchantments: [ minecraft:channeling ]
notAffectedGroups: [ enchanted_book, trident ]
restriction_binding_curse:
enchantments: [ minecraft:binding_curse ]
notAffectedGroups: [ enchanted_book, wearable ]
restriction_vanishing_curse:
enchantments: [ minecraft:vanishing_curse ]
notAffectedGroups: [ enchanted_book, can_vanish ]
restriction_depth_strider:
enchantments: [ minecraft:depth_strider ]
notAffectedGroups: [ enchanted_book, boots ]
restriction_efficiency:
enchantments: [ minecraft:efficiency ]
notAffectedGroups: [ enchanted_book, tools, shears ]
restriction_feather_falling:
enchantments: [ minecraft:feather_falling ]
notAffectedGroups: [ enchanted_book, boots ]
restriction_fire_aspect:
enchantments: [ minecraft:fire_aspect ]
notAffectedGroups: [ enchanted_book, swords ]
restriction_fire_protection:
enchantments: [ minecraft:fire_protection ]
notAffectedGroups: [ enchanted_book, armors ]
restriction_flame:
enchantments: [ minecraft:flame ]
notAffectedGroups: [ enchanted_book, bow ]
restriction_fortune:
enchantments: [ minecraft:fortune ]
notAffectedGroups: [ enchanted_book, tools ]
restriction_frost_walker:
enchantments: [ minecraft:frost_walker ]
notAffectedGroups: [ enchanted_book, boots ]
restriction_impaling:
enchantments: [ minecraft:impaling ]
notAffectedGroups: [ enchanted_book, trident ]
restriction_infinity:
enchantments: [ minecraft:infinity ]
notAffectedGroups: [ enchanted_book, bow ]
restriction_knockback:
enchantments: [ minecraft:knockback ]
notAffectedGroups: [ enchanted_book, swords ]
restriction_looting:
enchantments: [ minecraft:looting ]
notAffectedGroups: [ enchanted_book, swords ]
restriction_loyalty:
enchantments: [ minecraft:loyalty ]
notAffectedGroups: [ enchanted_book, trident ]
restriction_luck_of_the_sea:
enchantments: [ minecraft:luck_of_the_sea ]
notAffectedGroups: [ enchanted_book, fishing_rod ]
restriction_lure:
enchantments: [ minecraft:lure ]
notAffectedGroups: [ enchanted_book, fishing_rod ]
restriction_mending:
enchantments: [ minecraft:mending ]
notAffectedGroups: [ enchanted_book, can_unbreak ]
restriction_minecraft_multishot:
enchantments: [ minecraft:multishot ]
notAffectedGroups: [ enchanted_book, crossbow ]
restriction_piercing:
enchantments: [ minecraft:piercing ]
notAffectedGroups: [ enchanted_book, crossbow ]
restriction_power:
enchantments: [ minecraft:power ]
notAffectedGroups: [ enchanted_book, bow ]
restriction_projectile_protection:
enchantments: [ minecraft:projectile_protection ]
notAffectedGroups: [ enchanted_book, armors ]
restriction_protection:
enchantments: [ minecraft:protection ]
notAffectedGroups: [ enchanted_book, armors ]
restriction_punch:
enchantments: [ minecraft:punch ]
notAffectedGroups: [ enchanted_book, bow ]
restriction_quick_charge:
enchantments: [ minecraft:quick_charge ]
notAffectedGroups: [ enchanted_book, crossbow ]
restriction_respiration:
enchantments: [ minecraft:respiration ]
notAffectedGroups: [ enchanted_book, helmets ]
restriction_riptide:
enchantments: [ minecraft:riptide ]
notAffectedGroups: [ enchanted_book, trident ]
restriction_sharpness:
enchantments: [ minecraft:sharpness ]
notAffectedGroups: [ enchanted_book, melee_weapons ]
restriction__silk_touch:
enchantments: [ minecraft:silk_touch ]
notAffectedGroups: [ enchanted_book, tools ]
restriction_smite:
enchantments: [ minecraft:smite ]
notAffectedGroups: [ enchanted_book, melee_weapons ]
restriction_soul_speed:
enchantments: [ minecraft:soul_speed ]
notAffectedGroups: [ enchanted_book, boots ]
restriction_sweeping_edge:
enchantments: [ minecraft:sweeping, minecraft:sweeping_edge ]
notAffectedGroups: [ enchanted_book, swords ]
# Do not exist in 1.18, that mean useInFuture will be set to true
# useInFuture set to true also mean it will not warn if there is an issue
restriction_swift_sneak:
useInFuture: true
enchantments: [ minecraft:swift_sneak ]
notAffectedGroups: [ enchanted_book, leggings ]
restriction_thorns:
enchantments: [ minecraft:thorns ]
notAffectedGroups: [ enchanted_book, armors ]
restriction__unbreaking:
enchantments: [ minecraft:unbreaking ]
notAffectedGroups: [ enchanted_book, can_unbreak ]
# ----------------------------------------------------
# Now we have conflicts about enchantment Incompatibility
# We just filtered what item enchantments can be applied
# notAffectedGroups is empty as we don't want anything to not respect theses rules
# maxEnchantmentBeforeConflict is set to 1 to only have 1 on those enchantment available
# ----------------------------------------------------
sword_enchant_conflict:
enchantments:
- minecraft:bane_of_arthropods
- minecraft:smite
- minecraft:sharpness
notAffectedGroups: [ ]
maxEnchantmentBeforeConflict: 1
protection_enchant_conflict:
enchantments:
- minecraft:blast_protection
- minecraft:fire_protection
- minecraft:projectile_protection
- minecraft:protection
notAffectedGroups: [ ]
maxEnchantmentBeforeConflict: 1
trident_conflict1:
enchantments:
- minecraft:channeling
- minecraft:riptide
notAffectedGroups: [ ]
maxEnchantmentBeforeConflict: 1
trident_conflict2:
enchantments:
- minecraft:loyalty
- minecraft:riptide
notAffectedGroups: [ ]
maxEnchantmentBeforeConflict: 1
boot_conflict:
enchantments:
- minecraft:depth_strider
- minecraft:frost_walker
notAffectedGroups: [ ]
maxEnchantmentBeforeConflict: 1
tool_conflict:
enchantments:
- minecraft:fortune
- minecraft:silk_touch
notAffectedGroups: [ ]
maxEnchantmentBeforeConflict: 1
bow_conflict:
enchantments:
- minecraft:mending
- minecraft:infinity
notAffectedGroups: [ ]
maxEnchantmentBeforeConflict: 1
crossbow_conflict:
enchantments:
- minecraft:multishot
- minecraft:piercing
notAffectedGroups: [ ]
maxEnchantmentBeforeConflict: 1
# ----------------------------------------------------
# Bellow is for custom conflicts.
# This is also where conflict create from the gui will be placed.
# ----------------------------------------------------

View file

@ -1,210 +0,0 @@
#
# It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
#
# Please note this config use spigot material names.
# It should match minecraft name in most case, maybe every case, but I can't be sure
# In case there an issue with material name, you can found them here:
# https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html
# An empty Exclude group exclude nothing, so it contain everything
everything:
type: exclude
# An empty include group will include nothing
nothing:
type: include
# This group is an example of a group including only stone and polished granite
example_include:
type: include
items:
- stone
- polished_granite
# This group contain everything except polished granite and elements of example_include
example_exclude:
type: exclude
items:
- polished_granite
groups:
- example_include
# Default configuration should be vanilla enchantment conflict group
# there may have error, if you find one you can fix it !
# https://minecraft.fandom.com/wiki/Enchanting
swords:
type: include
items:
- wooden_sword
- stone_sword
- iron_sword
- diamond_sword
- golden_sword
- netherite_sword
axes:
type: include
items:
- wooden_axe
- stone_axe
- iron_axe
- diamond_axe
- golden_axe
- netherite_axe
melee_weapons:
type: include
groups:
- swords
- axes
helmets:
type: include
items:
- leather_helmet
- chainmail_helmet
- iron_helmet
- diamond_helmet
- golden_helmet
- netherite_helmet
- turtle_helmet
chestplate:
type: include
items:
- leather_chestplate
- chainmail_chestplate
- iron_chestplate
- diamond_chestplate
- golden_chestplate
- netherite_chestplate
leggings:
type: include
items:
- leather_leggings
- chainmail_leggings
- iron_leggings
- diamond_leggings
- golden_leggings
- netherite_leggings
boots:
type: include
items:
- leather_boots
- chainmail_boots
- iron_boots
- diamond_boots
- golden_boots
- netherite_boots
armors:
type: include
groups:
- helmets
- chestplate
- leggings
- boots
wearable:
type: include
items:
- elytra
- carved_pumpkin
- skeleton_skull
- wither_skeleton_skull
- zombie_head
- player_head
- creeper_head
- dragon_head
# do not exist in 1.18 but exist in future update
- piglin_head
groups:
- armors
tools:
type: include
items:
- wooden_pickaxe
- stone_pickaxe
- iron_pickaxe
- diamond_pickaxe
- golden_pickaxe
- netherite_pickaxe
- wooden_shovel
- stone_shovel
- iron_shovel
- diamond_shovel
- golden_shovel
- netherite_shovel
- wooden_hoe
- stone_hoe
- iron_hoe
- diamond_hoe
- golden_hoe
- netherite_hoe
groups:
- axes
enchanted_book:
type: include
items:
- enchanted_book
trident:
type: include
items:
- trident
bow:
type: include
items:
- bow
crossbow:
type: include
items:
- crossbow
fishing_rod:
type: include
items:
- fishing_rod
shears:
type: include
items:
- shears
can_unbreak:
type: include
items:
- elytra
- flint_and_steel
- shield
- carrot_on_a_stick
- warped_fungus_on_a_stick
# do not exist in 1.18 but exist in future update
- brush
groups:
- melee_weapons
- tools
- armors
- trident
- bow
- crossbow
- fishing_rod
- shears
can_vanish:
type: include
items:
- compass
groups:
- wearable
- can_unbreak

View file

@ -1,190 +0,0 @@
#
# It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
#
# Unit repair configuration
#
# This configuration is to make custom unit repair
# A unit repair is, for example, a diamond to repair a diamond sword
# In vanilla, a unit repair 25% of object durability
# you can make a custom value here
#
# Item name should NOT combine caps and no caps (example: Stone)
# Default value if the config is an invalid value (value <= 0 )
# If value > 1 it will be treated as being = 1
default_repair_amount: 0.25
# You can add custom unit repair
# The example bellow make a shield repaired by 10% by sticks
#stick:
# shield: 0.10
# Vanilla unit repair group is bellow
diamond:
diamond_helmet: 0.25
diamond_chestplate: 0.25
diamond_leggings: 0.25
diamond_boots: 0.25
diamond_sword: 0.25
diamond_pickaxe: 0.25
diamond_axe: 0.25
diamond_shovel: 0.25
diamond_hoe: 0.25
netherite_ingot:
netherite_helmet: 0.25
netherite_chestplate: 0.25
netherite_leggings: 0.25
netherite_boots: 0.25
netherite_sword: 0.25
netherite_pickaxe: 0.25
netherite_axe: 0.25
netherite_shovel: 0.25
netherite_hoe: 0.25
gold_ingot:
golden_helmet: 0.25
golden_chestplate: 0.25
golden_leggings: 0.25
golden_boots: 0.25
golden_sword: 0.25
golden_pickaxe: 0.25
golden_axe: 0.25
golden_shovel: 0.25
golden_hoe: 0.25
iron_ingot:
iron_helmet: 0.25
iron_chestplate: 0.25
iron_leggings: 0.25
iron_boots: 0.25
iron_sword: 0.25
iron_pickaxe: 0.25
iron_axe: 0.25
iron_shovel: 0.25
iron_hoe: 0.25
cobblestone:
stone_sword: 0.25
stone_pickaxe: 0.25
stone_axe: 0.25
stone_shovel: 0.25
stone_hoe: 0.25
cobbled_deepslate:
stone_sword: 0.25
stone_pickaxe: 0.25
stone_axe: 0.25
stone_shovel: 0.25
stone_hoe: 0.25
blackstone:
stone_sword: 0.25
stone_pickaxe: 0.25
stone_axe: 0.25
stone_shovel: 0.25
stone_hoe: 0.25
leather:
leather_helmet: 0.25
leather_chestplate: 0.25
leather_leggings: 0.25
leather_boots: 0.25
phantom_membrane:
elytra: 0.25
scute:
turtle_helmet: 0.25
oak_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
spruce_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
birch_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
jungle_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
acacia_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
dark_oak_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
mangrove_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
cherry_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
bamboo_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
crimson_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25
warped_planks:
wooden_sword: 0.25
wooden_pickaxe: 0.25
wooden_axe: 0.25
wooden_shovel: 0.25
wooden_hoe: 0.25
shield: 0.25

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #
@ -275,10 +275,7 @@ restriction_sweeping_edge:
- enchanted_book - enchanted_book
- swords - swords
# Do not exist in 1.18, that mean useInFuture will be set to true
# useInFuture set to true also mean it will not warn if there is an issue
restriction_swift_sneak: restriction_swift_sneak:
useInFuture: true
enchantments: enchantments:
- minecraft:swift_sneak - minecraft:swift_sneak
notAffectedGroups: notAffectedGroups:

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #
@ -272,10 +272,7 @@ restriction_sweeping_edge:
- enchanted_book - enchanted_book
- swords - swords
# Do not exist in 1.18, that mean useInFuture will be set to true
# useInFuture set to true also mean it will not warn if there is an issue
restriction_swift_sneak: restriction_swift_sneak:
useInFuture: true
enchantments: enchantments:
- minecraft:swift_sneak - minecraft:swift_sneak
notAffectedGroups: notAffectedGroups:

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,5 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /ca config to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes !
# #

View file

@ -1,5 +1,4 @@
### Default Plugin's Configurations ### Default Plugin's Configurations
From 1.18 to 1.20.6 use [1.18 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.18) \
From 1.21 to 1.21.8 use [1.21 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21) \ From 1.21 to 1.21.8 use [1.21 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21) \
From 1.21.9 to 1.21.10 use [1.21.9 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21.9) \ From 1.21.9 to 1.21.10 use [1.21.9 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21.9) \
From 1.21.11 use [1.21.11 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21.11) From 1.21.11 use [1.21.11 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21.11)

View file

@ -6,7 +6,7 @@ signing.secretKeyRingFile=~/.gnupg/secring.gpg
kotlin.daemon.jvmargs=-Xmx8G kotlin.daemon.jvmargs=-Xmx8G
# list of nms # list of nms
subprojects.reobfnms=v1_17R1,v1_18R1,v1_18R2,v1_19R1,v1_19R2,v1_19R3,v1_20R1,v1_20R2,v1_20R3,v1_20R4,v1_21R1,v1_21R2,v1_21R3,v1_21R4,v1_21R5,v1_21R6,v1_21R7 subprojects.reobfnms=v1_21R1,v1_21R2,v1_21R3,v1_21R4,v1_21R5,v1_21R6,v1_21R7
# list of version for hangar release # list of version for hangar release
paperVersion=1.18-26.2 paperVersion=1.18-26.2

View file

@ -8,6 +8,6 @@ plugins {
// Imitate needed class and method to support legacy version of EcoEnchant // Imitate needed class and method to support legacy version of EcoEnchant
dependencies { dependencies {
// Spigot api // Spigot api
compileOnly("org.spigotmc:spigot-api:1.18-R0.1-SNAPSHOT") compileOnly("org.spigotmc:spigot-api:1.21-R0.1-SNAPSHOT")
} }

View file

@ -21,8 +21,8 @@ repositories {
// Set target version // Set target version
tasks.withType<JavaCompile>().configureEach { tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "16" sourceCompatibility = "21"
targetCompatibility = "16" targetCompatibility = "21"
options.encoding = "UTF-8" options.encoding = "UTF-8"
} }
@ -30,6 +30,6 @@ tasks.withType<JavaCompile>().configureEach {
kotlin { kotlin {
compilerOptions { compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_16) jvmTarget.set(JvmTarget.JVM_21)
} }
} }

View file

@ -21,8 +21,8 @@ repositories {
// Set target version // Set target version
tasks.withType<JavaCompile>().configureEach { tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "18" sourceCompatibility = "21"
targetCompatibility = "18" targetCompatibility = "21"
options.encoding = "UTF-8" options.encoding = "UTF-8"
} }
@ -30,6 +30,6 @@ tasks.withType<JavaCompile>().configureEach {
kotlin { kotlin {
compilerOptions { compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_18) jvmTarget.set(JvmTarget.JVM_21)
} }
} }

View file

@ -2,37 +2,19 @@ package xyz.alexcrea.cuanvil.dependency.datapack
import io.papermc.paper.datapack.Datapack import io.papermc.paper.datapack.Datapack
import org.bukkit.Bukkit import org.bukkit.Bukkit
import org.bukkit.packs.DataPack
import java.util.* import java.util.*
object DataPackTester { object DataPackTester {
val legacyNames: List<String>
get() = Bukkit.getDataPackManager().dataPacks
.stream().filter { obj -> obj.isEnabled }
.map { pack -> pack.key.key }
.toList()
val enabledPacks: List<String> val enabledPacks: List<String>
get() { get() {
try { return try {
// will throw error if do not exist Bukkit.getDatapackManager().enabledPacks
Bukkit::class.java.getDeclaredMethod("getDatapackManager")
return Bukkit.getDatapackManager().enabledPacks
.stream().map { obj: Datapack -> obj.name } .stream().map { obj: Datapack -> obj.name }
.toList() .toList()
} catch (e: NoSuchMethodException) { } catch (_: Exception){
try {
DataPack::class.java.getDeclaredMethod("getKey")
} catch (e: NoSuchMethodException) {
System.err.println("Could not find compatible datapack manager")
System.err.println("If you are using a datapack that should be compatible with CustomAnvil. It will not get detected...")
return emptyList()
}
return legacyNames
} catch (e: Exception){
// Assume cause UnimplementedOperationException on mock server // Assume cause UnimplementedOperationException on mock server
return Collections.emptyList() Collections.emptyList()
} }
} }
} }

View file

@ -18,8 +18,8 @@ import org.bukkit.craftbukkit.inventory.CraftInventoryView
import org.bukkit.craftbukkit.inventory.view.CraftAnvilView import org.bukkit.craftbukkit.inventory.view.CraftAnvilView
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import org.bukkit.event.inventory.PrepareAnvilEvent import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.InventoryView
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.view.AnvilView
import org.bukkit.persistence.PersistentDataType import org.bukkit.persistence.PersistentDataType
import org.bukkit.plugin.Plugin import org.bukkit.plugin.Plugin
import java.util.* import java.util.*
@ -121,7 +121,7 @@ class AnvilRenameDialogImpl(
} }
} }
private fun setResult(player: HumanEntity, view: InventoryView, result: String?) { private fun setResult(player: HumanEntity, view: AnvilView, result: String?) {
val defaultName = itemDefaultName(view.getItem(0)) val defaultName = itemDefaultName(view.getItem(0))
if (defaultName == result) { if (defaultName == result) {
setName(player, view, "", null) setName(player, view, "", null)
@ -129,7 +129,7 @@ class AnvilRenameDialogImpl(
} else setName(player, view, result, result) } else setName(player, view, result, result)
} }
private fun setName(player: HumanEntity, view: InventoryView, name: String?, rename: String?) { private fun setName(player: HumanEntity, view: AnvilView, name: String?, rename: String?) {
val menu = (containerField.get(view) as AnvilMenu) val menu = (containerField.get(view) as AnvilMenu)
val isSameName = menu.itemName == name val isSameName = menu.itemName == name
menu.itemName = rename menu.itemName = rename

View file

@ -2,17 +2,18 @@ package xyz.alexcrea.cuanvil.util
import io.papermc.paper.threadedregions.scheduler.ScheduledTask import io.papermc.paper.threadedregions.scheduler.ScheduledTask
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import org.bukkit.inventory.InventoryView import org.bukkit.inventory.view.AnvilView
import org.bukkit.plugin.Plugin import org.bukkit.plugin.Plugin
import xyz.alexcrea.cuanvil.dialog.AnvilRenameDialog import xyz.alexcrea.cuanvil.dialog.AnvilRenameDialog
import java.util.HashMap import java.util.HashMap
import java.util.UUID import java.util.UUID
@Suppress("UnstableApiUsage")
object AnvilTitleUtil { object AnvilTitleUtil {
private val runTaskMap = HashMap<UUID, ScheduledTask>() private val runTaskMap = HashMap<UUID, ScheduledTask>()
private fun actualRename(view: InventoryView, name: String, player: HumanEntity, anvilDialog: AnvilRenameDialog) { private fun actualRename(view: AnvilView, name: String, player: HumanEntity, anvilDialog: AnvilRenameDialog) {
runTaskMap.remove(player.uniqueId) runTaskMap.remove(player.uniqueId)
if (view.title == name) return if (view.title == name) return
@ -24,7 +25,7 @@ object AnvilTitleUtil {
// We don't want to rename instantly it is causing issue with rename text // We don't want to rename instantly it is causing issue with rename text
// especially as it can "override" current ui when it is rename ui time but rename ui also need some delay // especially as it can "override" current ui when it is rename ui time but rename ui also need some delay
fun rename(view: InventoryView, name: String, player: HumanEntity, anvilDialog: AnvilRenameDialog, plugin: Plugin) { fun rename(view: AnvilView, name: String, player: HumanEntity, anvilDialog: AnvilRenameDialog, plugin: Plugin) {
runTaskMap.remove(player.uniqueId)?.cancel() runTaskMap.remove(player.uniqueId)?.cancel()
val task = player.scheduler.runDelayed( val task = player.scheduler.runDelayed(

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.17.1-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "16"
targetCompatibility = "16"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_16)
}
}

View file

@ -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.v1_17_R1.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_17R1_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.18.1-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "17"
targetCompatibility = "17"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_17)
}
}

View file

@ -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.v1_18_R1.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_18R1_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.18.2-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "17"
targetCompatibility = "17"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_17)
}
}

View file

@ -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.v1_18_R2.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_18R2_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.19.2-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "17"
targetCompatibility = "17"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_17)
}
}

View file

@ -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.v1_19_R1.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_19R1_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.19.3-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "17"
targetCompatibility = "17"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_17)
}
}

View file

@ -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.v1_19_R2.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_19R2_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.19.4-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "17"
targetCompatibility = "17"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_17)
}
}

View file

@ -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.v1_19_R3.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_19R3_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.20.1-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "18"
targetCompatibility = "18"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_18)
}
}

View file

@ -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.v1_20_R1.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_20R1_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.20.2-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "18"
targetCompatibility = "18"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_18)
}
}

View file

@ -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.v1_20_R2.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_20R2_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.20.4-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "18"
targetCompatibility = "18"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2)
jvmTarget.set(JvmTarget.JVM_18)
}
}

View file

@ -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.v1_20_R3.entity.CraftPlayer
import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.dependency.packet.PacketManager
import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase
class V1_20R3_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)
}
}

View file

@ -1 +0,0 @@
.lastDeploymentsId

View file

@ -1,35 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = rootProject.group
version = rootProject.version
plugins {
id("io.papermc.paperweight.userdev")
}
dependencies {
implementation(project(":nms:nms-common"))
// Used for nms
paperweight.paperDevBundle("1.20.6-R0.1-SNAPSHOT")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
// Set target version
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "18"
targetCompatibility = "18"
options.encoding = "UTF-8"
}
kotlin {
compilerOptions {
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_0)
jvmTarget.set(JvmTarget.JVM_18)
}
}

View file

@ -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_20R4_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)
}
}

View file

@ -1,18 +0,0 @@
package xyz.alexcrea.cuanvil.util
import org.bukkit.inventory.meta.Damageable
// I LOVE support of old versions and needing to do modules like that
// That truly is my favorite activity
// TODO clean this one of legacy removal branch
object MaxDamageCheckerUtil {
/**
* @return max damage or int max if not set
*/
fun getMaxDamage(meta: Damageable): Int {
if(!meta.hasMaxDamage()) return Integer.MAX_VALUE
return meta.maxDamage
}
}

View file

@ -90,29 +90,6 @@ public class AnvilRecipeBuilder {
return this; return this;
} }
/**
* Get the xp level cost per craft. (default 0)
*
* @return The xp level cost per craft
* @deprecated use {@link #getLevelCostPerCraft() getLevelCostPerCraft} instead
*/
@Deprecated(since = "1.13.0")
public int getXpCostPerCraft() {
return getLevelCostPerCraft();
}
/**
* Sets the xp level cost per craft.
*
* @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) * Get the xp level cost per craft. (default 0)
* *

View file

@ -387,7 +387,7 @@ public class ConflictBuilder {
*/ */
protected void appendEnchantments(@NotNull EnchantConflictGroup conflict) { protected void appendEnchantments(@NotNull EnchantConflictGroup conflict) {
for (String enchantmentName : getEnchantmentNames()) { for (String enchantmentName : getEnchantmentNames()) {
if (appendEnchantments(conflict, EnchantmentApi.getListByName(enchantmentName)) == 0) { if (appendEnchantments(conflict, EnchantmentApi.getByName(enchantmentName)) == 0) {
CustomAnvil.instance.getLogger().warning("Could not find enchantment " + enchantmentName + " for conflict " + getName()); CustomAnvil.instance.getLogger().warning("Could not find enchantment " + enchantmentName + " for conflict " + getName());
ConflictAPI.logConflictOrigin(this); ConflictAPI.logConflictOrigin(this);
} }

View file

@ -128,31 +128,18 @@ public class EnchantmentApi {
* @return The custom anvil enchantment of this key. null if not found. * @return The custom anvil enchantment of this key. null if not found.
*/ */
@Nullable @Nullable
public static CAEnchantment getByKey(@NotNull NamespacedKey key) { public static CAEnchantment getByKey(@Nullable NamespacedKey key) {
return CAEnchantment.getByKey(key); return CAEnchantment.getByKey(key);
} }
/**
* Get by name an enchantment.
*
* @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. * Get list of enchantment using the provided name.
* *
* @param name The name used to fetch * @param name The name used to fetch
* @return List of custom anvil enchantments of this name. May be empty if not found. * @return List of custom anvil enchantments of this name. May be empty if not found.
*/ */
public static List<CAEnchantment> getListByName(@NotNull String name) { public static List<CAEnchantment> getByName(@NotNull String name) {
return CAEnchantment.getListByName(name); return CAEnchantment.getByName(name);
} }
/** /**

View file

@ -17,7 +17,7 @@ import org.jetbrains.annotations.NotNull;
* Most of the time you would likely need {@link CAPreAnvilBypassEvent} or {@link CAEarlyPreAnvilBypassEvent} * Most of the time you would likely need {@link CAPreAnvilBypassEvent} or {@link CAEarlyPreAnvilBypassEvent}
* for this event to be useful. * for this event to be useful.
* <p> * <p>
* There is also {@link CATreatAnvilResult2Event} that may be better for some use case. * There is also {@link CATreatAnvilResultEvent} that may be better for some use case.
*/ */
public class CAClickResultBypassEvent extends Event implements Cancellable { public class CAClickResultBypassEvent extends Event implements Cancellable {

View file

@ -15,7 +15,7 @@ import org.jetbrains.annotations.NotNull;
* <p> * <p>
* You should also use {@link CAClickResultBypassEvent} if you want to use this event for something useful. * You should also use {@link CAClickResultBypassEvent} if you want to use this event for something useful.
* <p> * <p>
* It is also recommended that you read about {@link CAPreAnvilBypassEvent} and {@link CATreatAnvilResult2Event} * It is also recommended that you read about {@link CAPreAnvilBypassEvent} and {@link CATreatAnvilResultEvent}
* as your use case may be more prone to use theses. * as your use case may be more prone to use theses.
*/ */
public class CAEarlyPreAnvilBypassEvent extends Event implements Cancellable { public class CAEarlyPreAnvilBypassEvent extends Event implements Cancellable {

View file

@ -18,7 +18,7 @@ import org.jetbrains.annotations.NotNull;
* <p> * <p>
* You should also use {@link CAClickResultBypassEvent} if you want to use this event for something useful. * You should also use {@link CAClickResultBypassEvent} if you want to use this event for something useful.
* <p> * <p>
* It is also recommended that you read about {@link CAEarlyPreAnvilBypassEvent} and {@link CATreatAnvilResult2Event} * It is also recommended that you read about {@link CAEarlyPreAnvilBypassEvent} and {@link CATreatAnvilResultEvent}
* as your use case may be more prone to use theses. * as your use case may be more prone to use theses.
*/ */
public class CAPreAnvilBypassEvent extends Event implements Cancellable { public class CAPreAnvilBypassEvent extends Event implements Cancellable {

View file

@ -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.
* <p>
* You may also want to check {@link CAClickResultBypassEvent},
* {@link CAPreAnvilBypassEvent}
* and {@link CAEarlyPreAnvilBypassEvent} for your use case
* <p>
* 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.
* <p>
* 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
* <p>
* 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
* <p>
* 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.
* <h3>Important note:</h3>
* the final price are re calculated on click for the following use case:
* <ul>
* <li>Custom craft</li>
* <li>Unit repair</li>
* <li>Lore edit</li>
* </ul>
* This value will be used as final price for:
* <li>Item merge</li>
* <li>Item rename</li>
* </ul>
*
* @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.
* <h3>Important note:</h3>
* the final price are re calculated on click for the following use case:
* <ul>
* <li>Custom craft</li>
* <li>Unit repair</li>
* <li>Lore edit</li>
* </ul>
* This value will be used as final price for:
* <li>Item merge</li>
* <li>Item rename</li>
* </ul>
*
* @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
*
* <h3>Important note:</h3>
* the final price are re calculated on click for the following use case:
* <ul>
* <li>Custom craft</li>
* <li>Unit repair</li>
* <li>Lore edit</li>
* </ul>
* This value will be used as final price for:
* <li>Item merge</li>
* <li>Item rename</li>
*
* @return the current anvil cost
*/
public AnvilCost getCost() {
return cost;
}
}

View file

@ -2,8 +2,8 @@ package xyz.alexcrea.cuanvil.api.event.listener;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.event.inventory.PrepareAnvilEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.view.AnvilView;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.anvil.AnvilCost; import xyz.alexcrea.cuanvil.anvil.AnvilCost;
@ -17,13 +17,9 @@ import xyz.alexcrea.cuanvil.anvil.AnvilUseType;
* {@link CAPreAnvilBypassEvent} * {@link CAPreAnvilBypassEvent}
* and {@link CAEarlyPreAnvilBypassEvent} for your use case * and {@link CAEarlyPreAnvilBypassEvent} for your use case
* <p> * <p>
* A null result will cancel this pre anvil event * A null result will cancel this 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") @SuppressWarnings({"unused", "UnstableApiUsage"})
@Deprecated(forRemoval = true, since = "1.17.0")
public class CATreatAnvilResultEvent extends Event { public class CATreatAnvilResultEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList(); private static final HandlerList HANDLERS = new HandlerList();
@ -38,31 +34,44 @@ public class CATreatAnvilResultEvent extends Event {
} }
@NotNull @NotNull
private final PrepareAnvilEvent event; private final AnvilView view;
private final AnvilUseType useType; private final AnvilUseType useType;
@Nullable
private final ItemStack left;
@Nullable
private final ItemStack right;
@Nullable @Nullable
private ItemStack result; private ItemStack result;
private final AnvilCost cost; private final AnvilCost cost;
public CATreatAnvilResultEvent(@NotNull PrepareAnvilEvent event, AnvilUseType useType, @Nullable ItemStack result, AnvilCost cost) { public CATreatAnvilResultEvent(
this.event = event; @NotNull AnvilView view,
AnvilUseType useType,
@Nullable ItemStack result,
AnvilCost cost) {
this.view = view;
this.useType = useType; this.useType = useType;
this.left = view.getItem(0);
this.right = view.getItem(1);
this.result = result; this.result = result;
this.cost = cost; this.cost = cost;
} }
/** /**
* Get the bukkit inventory click event causing to this event. * Get the bukkit inventory view.
* *
* @return The click event causing to this event. * @return The inventory view of this event.
*/ */
public @NotNull PrepareAnvilEvent getEvent() { public @NotNull AnvilView getView() {
return event; return view;
} }
/** /**
* Get the type of use source of the result. * Get the type of use source of the result.
* *
@ -72,6 +81,24 @@ public class CATreatAnvilResultEvent extends Event {
return useType; 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 * Get the current result
* <p> * <p>
@ -94,50 +121,6 @@ public class CATreatAnvilResultEvent extends Event {
this.result = result; this.result = result;
} }
/**
* Get the level cost displayed on the anvil.
* <h3>Important note:</h3>
* the final price are re calculated on click for the following use case:
* <ul>
* <li>Custom craft</li>
* <li>Unit repair</li>
* <li>Lore edit</li>
* </ul>
* This value will be used as final price for:
* <li>Item merge</li>
* <li>Item rename</li>
* </ul>
*
* @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.
* <h3>Important note:</h3>
* the final price are re calculated on click for the following use case:
* <ul>
* <li>Custom craft</li>
* <li>Unit repair</li>
* <li>Lore edit</li>
* </ul>
* This value will be used as final price for:
* <li>Item merge</li>
* <li>Item rename</li>
* </ul>
*
* @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 * Allow access to the current cost of the event
* Note that modifying this object will change the event resulting cost * Note that modifying this object will change the event resulting cost
@ -158,5 +141,4 @@ public class CATreatAnvilResultEvent extends Event {
public AnvilCost getCost() { public AnvilCost getCost() {
return cost; return cost;
} }
} }

View file

@ -230,29 +230,18 @@ public interface CAEnchantment {
* @param key The enchantment key * @param key The enchantment key
* @return Array of enchantment. * @return Array of enchantment.
*/ */
static @Nullable CAEnchantment getByKey(@NotNull NamespacedKey key){ static @Nullable CAEnchantment getByKey(@Nullable NamespacedKey key){
return CAEnchantmentRegistry.getInstance().getByKey(key); return CAEnchantmentRegistry.getInstance().getByKey(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")
static @Nullable CAEnchantment getByName(@NotNull String name){
return CAEnchantmentRegistry.getInstance().getByName(name);
}
/** /**
* Gets list of enchantment using the provided name. * Gets list of enchantment using the provided name.
*
* @param name Name to fetch. * @param name Name to fetch.
* @return List of registered enchantment. * @return List of registered enchantment.
*/ */
static List<CAEnchantment> getListByName(@NotNull String name){ static List<CAEnchantment> getByName(@NotNull String name){
return CAEnchantmentRegistry.getInstance().getListByName(name); return CAEnchantmentRegistry.getInstance().getByName(name);
} }
} }

View file

@ -151,26 +151,10 @@ public class CAEnchantmentRegistry {
* @return Registered enchantment. null if absent. * @return Registered enchantment. null if absent.
*/ */
@Nullable @Nullable
public CAEnchantment getByKey(@NotNull NamespacedKey key) { public CAEnchantment getByKey(@Nullable NamespacedKey key) {
return byKeyMap.get(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<CAEnchantment> enchantments = getListByName(name);
if (enchantments.isEmpty()) return null;
return enchantments.get(0);
}
/** /**
* Gets list of enchantment using the provided name. * Gets list of enchantment using the provided name.
* *
@ -178,7 +162,7 @@ public class CAEnchantmentRegistry {
* @return List of registered enchantment. * @return List of registered enchantment.
*/ */
@NotNull @NotNull
public List<CAEnchantment> getListByName(@NotNull String name) { public List<CAEnchantment> getByName(@NotNull String name) {
return byNameMap.getOrDefault(name, Collections.emptyList()); return byNameMap.getOrDefault(name, Collections.emptyList());
} }

View file

@ -1,6 +1,6 @@
package xyz.alexcrea.cuanvil.enchant; package xyz.alexcrea.cuanvil.enchant;
// because spigot (1.18) do not look like to provide access to enchantment rarity I need to do it myself... // because spigot (1.21) do not look like to provide access to enchantment rarity I need to do it myself...
public class EnchantmentRarity { public class EnchantmentRarity {
public static final EnchantmentRarity NO_RARITY = new EnchantmentRarity(0, 0); public static final EnchantmentRarity NO_RARITY = new EnchantmentRarity(0, 0);

View file

@ -141,10 +141,10 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui<CAEnchantme
meta.setDisplayName("§" + (isIn ? 'a' : 'c') + CasedStringUtil.snakeToUpperSpacedCase(name)); meta.setDisplayName("§" + (isIn ? 'a' : 'c') + CasedStringUtil.snakeToUpperSpacedCase(name));
if (isIn) { if (isIn) {
meta.addEnchant(Enchantment.DAMAGE_UNDEAD, 1, true); meta.addEnchant(Enchantment.SHARPNESS, 1, true);
meta.setLore(TRUE_LORE); meta.setLore(TRUE_LORE);
} else { } else {
meta.removeEnchant(Enchantment.DAMAGE_UNDEAD); meta.removeEnchant(Enchantment.SHARPNESS);
meta.setLore(FALSE_LORE); meta.setLore(FALSE_LORE);
} }
meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ENCHANTS); meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ENCHANTS);

View file

@ -112,10 +112,10 @@ public class GroupSelectSettingGui extends AbstractSettingGui {
meta.setDisplayName("§" + (isIn ? 'a' : 'c') + CasedStringUtil.snakeToUpperSpacedCase(name)); meta.setDisplayName("§" + (isIn ? 'a' : 'c') + CasedStringUtil.snakeToUpperSpacedCase(name));
if (isIn) { if (isIn) {
meta.addEnchant(Enchantment.DAMAGE_UNDEAD, 1, true); meta.addEnchant(Enchantment.SHARPNESS, 1, true);
meta.setLore(TRUE_LORE); meta.setLore(TRUE_LORE);
} else { } else {
meta.removeEnchant(Enchantment.DAMAGE_UNDEAD); meta.removeEnchant(Enchantment.SHARPNESS);
meta.setLore(FALSE_LORE); meta.setLore(FALSE_LORE);
} }
meta.addItemFlags(ItemFlag.values()); meta.addItemFlags(ItemFlag.values());

View file

@ -30,10 +30,11 @@ public class UpdateHandler {
new Version(1, 11, 0), PUpdate_1_11_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, 5), PUpdate_1_15_5::handleUpdate,
new Version(1, 15, 6), PUpdate_1_15_6::handleUpdate, new Version(1, 15, 6), PUpdate_1_15_6::handleUpdate,
new Version(1, 17, 7), PUpdate_1_17_7::handleUpdate new Version(1, 18, 0), PUpdate_1_18::handleUpdate
); );
private static final List<MCUpdate> mcUpdateMap = List.of( private static final List<MCUpdate> mcUpdateMap = List.of(
new Update_1_19(),
new Update_1_20_5(), new Update_1_20_5(),
new Update_1_21(), new Update_1_21(),
new Update_1_21_9(), new Update_1_21_9(),

View file

@ -0,0 +1,40 @@
package xyz.alexcrea.cuanvil.update.minecraft;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.update.Version;
import java.util.HashSet;
import java.util.Set;
import static xyz.alexcrea.cuanvil.update.UpdateUtils.addAbsentToList;
public class Update_1_19 extends MCUpdate {
public Update_1_19() {
super(new Version(1, 19));
}
@Override
protected void doUpdate() {
var tosave = new HashSet<ConfigHolder>();
updateName(tosave);
for (ConfigHolder holder : tosave) {
holder.saveToDisk(true);
}
}
public static void updateName(@NotNull Set<ConfigHolder> tosave) {
var conflict = ConfigHolder.CONFLICT_HOLDER.getConfig();
addAbsentToList(conflict, "restriction_swift_sneak.enchantments", "minecraft:swift_sneak");
addAbsentToList(conflict, "restriction_swift_sneak.notAffectedGroups", "leggings", "enchanted_book");
ConfigHolder.ITEM_GROUP_HOLDER.reload();
tosave.add(ConfigHolder.DEFAULT_CONFIG);
tosave.add(ConfigHolder.CONFLICT_HOLDER);
}
}

View file

@ -3,19 +3,20 @@ package xyz.alexcrea.cuanvil.update.plugin;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.update.UpdateUtils; import xyz.alexcrea.cuanvil.update.UpdateUtils;
import xyz.alexcrea.cuanvil.update.Version; import xyz.alexcrea.cuanvil.update.Version;
import xyz.alexcrea.cuanvil.update.minecraft.Update_1_19;
import xyz.alexcrea.cuanvil.update.minecraft.Update_1_20_5; import xyz.alexcrea.cuanvil.update.minecraft.Update_1_20_5;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.Set; import java.util.Set;
public class PUpdate_1_17_7 { public class PUpdate_1_18 {
public static void handleUpdate(@Nonnull Set<ConfigHolder> toSave) { public static void handleUpdate(@Nonnull Set<ConfigHolder> toSave) {
// fix only needed for 1.20.5 and above
Version current = UpdateUtils.currentMinecraftVersion(); Version current = UpdateUtils.currentMinecraftVersion();
if (new Version(1, 20, 5).greaterThan(current)) return; if (new Version(1, 19, 0).greaterThan(current)) return;
Update_1_19.updateName(toSave);
if (new Version(1, 20, 5).greaterThan(current)) return;
Update_1_20_5.updateName(toSave); Update_1_20_5.updateName(toSave);
} }
} }

View file

@ -145,7 +145,7 @@ open class CustomAnvil : JavaPlugin() {
// Add commands // Add commands
try { try {
prepareCommand() CustomAnvilCommand(this)
} catch (e: Exception) { } catch (e: Exception) {
logger.log(Level.SEVERE, "error trying to register commands", e) logger.log(Level.SEVERE, "error trying to register commands", e)
MetricsUtil.trackError(e) MetricsUtil.trackError(e)
@ -330,14 +330,4 @@ open class CustomAnvil : JavaPlugin() {
return yamlConfig return yamlConfig
} }
fun prepareCommand() {
var command = getCommand(commandReloadName)
command?.setExecutor(ReloadExecutor())
command = getCommand(commandConfigName)
command?.setExecutor(EditConfigExecutor())
CustomAnvilCommand(this)
}
} }

View file

@ -1,12 +1,11 @@
package io.delilaheve.util package io.delilaheve.util
import org.bukkit.Material
import org.bukkit.Material.ENCHANTED_BOOK import org.bukkit.Material.ENCHANTED_BOOK
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.Damageable import org.bukkit.inventory.meta.Damageable
import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.update.UpdateUtils import xyz.alexcrea.cuanvil.update.UpdateUtils
import xyz.alexcrea.cuanvil.util.MaterialUtil.customType import xyz.alexcrea.cuanvil.util.MaterialUtil.customType
import xyz.alexcrea.cuanvil.util.MaxDamageCheckerUtil
import kotlin.math.ceil import kotlin.math.ceil
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
@ -21,11 +20,11 @@ object ItemUtil {
*/ */
fun ItemStack.isEnchantedBook() = type == ENCHANTED_BOOK fun ItemStack.isEnchantedBook() = type == ENCHANTED_BOOK
private fun maxDamage(damageable: Damageable): Int { private fun maxDamage(type: Material, damageable: Damageable): Int {
val ver = UpdateUtils.currentMinecraftVersion() val ver = UpdateUtils.currentMinecraftVersion()
if(ver.major <= 1 && ver.minor <= 20 && ver.patch < 5) return Integer.MAX_VALUE if(ver.major <= 1 && ver.minor <= 20 && ver.patch < 5) return type.maxDurability.toInt()
return MaxDamageCheckerUtil.getMaxDamage(damageable) return if(damageable.hasMaxDamage()) damageable.maxDamage else type.maxDurability.toInt()
} }
/** /**
@ -37,24 +36,23 @@ object ItemUtil {
first: ItemStack, first: ItemStack,
second: ItemStack second: ItemStack
): Boolean { ): Boolean {
(itemMeta as? Damageable)?.let { val meta = itemMeta
val durability = type.maxDurability.toInt() if(meta !is Damageable) return false
val firstDamage = (first.itemMeta as? Damageable)?.damage ?: 0
if (firstDamage == 0) return false
val firstDurability = durability - firstDamage val maxDamage = maxDamage(type, meta)
val damage = (first.itemMeta as? Damageable)?.damage ?: 0
if (damage == 0) return false
val firstDurability = maxDamage - damage
val secondDamage = (second.itemMeta as? Damageable)?.damage ?: 0 val secondDamage = (second.itemMeta as? Damageable)?.damage ?: 0
val secondDurability = durability - secondDamage val secondDurability = maxDamage - secondDamage
val combinedDurability = firstDurability + secondDurability val combinedDurability = firstDurability + secondDurability
val newDurability = min(combinedDurability, durability) val newDurability = min(combinedDurability, maxDamage)
val maxDamage = maxDamage(it) meta.damage = min(maxDamage - newDurability, maxDamage)
it.damage = min(durability - newDurability, maxDamage) this.itemMeta = meta
itemMeta = it
return true return true
} }
return false
}
fun ItemStack.unitRepair( fun ItemStack.unitRepair(
unitAmount: Int, unitAmount: Int,

View file

@ -10,10 +10,9 @@ import org.bukkit.ChatColor
import org.bukkit.Material import org.bukkit.Material
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import org.bukkit.entity.Player import org.bukkit.entity.Player
import org.bukkit.inventory.AnvilInventory
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.api.EnchantmentApi import xyz.alexcrea.cuanvil.api.EnchantmentApi
import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.dependency.DependencyManager
@ -31,6 +30,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 {
@ -97,13 +97,12 @@ object AnvilMergeLogic {
} }
fun doRenaming( fun doRenaming(
view: InventoryView, //TODO use anvil view view: AnvilView,
inventory: AnvilInventory,
player: Player, first: ItemStack player: Player, first: ItemStack
): 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) {
@ -113,7 +112,7 @@ object AnvilMergeLogic {
cost.workPenalty = AnvilXpUtil.calculatePenalty(first, null, resultItem, AnvilUseType.RENAME_ONLY) cost.workPenalty = AnvilXpUtil.calculatePenalty(first, null, resultItem, AnvilUseType.RENAME_ONLY)
val result = val result =
DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.RENAME_ONLY, cost) DependencyManager.tryTreatAnvilResult(view, player, resultItem, AnvilUseType.RENAME_ONLY, cost)
return AnvilResult(result, cost) return AnvilResult(result, cost)
} }
@ -136,9 +135,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
@ -183,8 +182,7 @@ object AnvilMergeLogic {
} }
fun doMerge( fun doMerge(
view: InventoryView, //TODO use anvil view instead view: AnvilView,
inventory: AnvilInventory,
player: Player, player: Player,
first: ItemStack, second: ItemStack first: ItemStack, second: ItemStack
): AnvilResult { ): AnvilResult {
@ -219,10 +217,10 @@ 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, player, resultItem, AnvilUseType.MERGE, cost)
return AnvilResult(result, cost) return AnvilResult(result, cost)
} }
@ -241,8 +239,7 @@ object AnvilMergeLogic {
// return true if a custom recipe exist with these ingredients // return true if a custom recipe exist with these ingredients
fun testCustomRecipe( fun testCustomRecipe(
view: InventoryView, //TODO use anvil view instead view: AnvilView,
inventory: AnvilInventory,
player: Player, player: Player,
first: ItemStack, second: ItemStack? first: ItemStack, second: ItemStack?
): CustomCraftResult { ): CustomCraftResult {
@ -264,31 +261,29 @@ object AnvilMergeLogic {
else AnvilXpUtil.calculateLevelForXp(xpCost) else AnvilXpUtil.calculateLevelForXp(xpCost)
val result = val result =
DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.CUSTOM_CRAFT, cost) DependencyManager.tryTreatAnvilResult(view, player, resultItem, AnvilUseType.CUSTOM_CRAFT, cost)
return CustomCraftResult(result, cost, amount, recipe) return CustomCraftResult(result, cost, amount, recipe)
} }
fun testUnitRepair( fun testUnitRepair(
view: InventoryView, //TODO use anvil view view: AnvilView,
inventory: AnvilInventory,
player: Player, player: Player,
first: ItemStack, second: ItemStack first: ItemStack, second: ItemStack
): UnitRepairResult { ): UnitRepairResult {
val unitRepairAmount = first.getRepair(second) ?: return UnitRepairResult.EMPTY val unitRepairAmount = first.getRepair(second) ?: return UnitRepairResult.EMPTY
return testUnitRepair(view, inventory, player, first, second, unitRepairAmount) return testUnitRepair(view, player, first, second, unitRepairAmount)
} }
fun testUnitRepair( fun testUnitRepair(
view: InventoryView, //TODO use anvil view instead view: AnvilView,
inventory: AnvilInventory,
player: Player, player: Player,
first: ItemStack, second: ItemStack, first: ItemStack, second: ItemStack,
unitRepairAmount: Double unitRepairAmount: Double
): 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)
@ -304,7 +299,7 @@ object AnvilMergeLogic {
} }
val result = val result =
DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.UNIT_REPAIR, cost) DependencyManager.tryTreatAnvilResult(view, player, resultItem, AnvilUseType.UNIT_REPAIR, cost)
return UnitRepairResult(result, cost, repairAmount) return UnitRepairResult(result, cost, repairAmount)
} }

View file

@ -1,50 +1,29 @@
package xyz.alexcrea.cuanvil.command package xyz.alexcrea.cuanvil.command
import org.bukkit.ChatColor
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.enchant.CAEnchantmentRegistry import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry
abstract class CASubCommand: CommandExecutor { interface CASubCommand {
private var alreadySaid = false; fun executeCommand(
override fun onCommand(
sender: CommandSender, sender: CommandSender,
cmd: Command, cmd: Command,
cmdstr: String, cmdstr: String,
args: Array<out String> args: Array<out String>
): Boolean { ): 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) fun allowed(sender: CommandSender): Boolean
}
abstract fun executeCommand( fun tabCompleter(
sender: CommandSender,
cmd: Command,
cmdstr: String,
args: Array<out String>): Boolean
open fun allowed(sender: CommandSender): Boolean {
return true
}
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 { fun description(): String
return "no description"
}
protected fun allEnchantmentsByName(): Collection<String> { fun allEnchantmentsByName(): Collection<String> {
val names = mutableSetOf<String>() val names = mutableSetOf<String>()
for (enchantment in CAEnchantmentRegistry.getInstance().values()) { for (enchantment in CAEnchantmentRegistry.getInstance().values()) {
names.add(enchantment.name) names.add(enchantment.name)

View file

@ -46,17 +46,17 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
val subcmdStr: String val subcmdStr: String
val newargs: Array<out String> val newargs: Array<out String>
if(args.isEmpty()) { if (args.isEmpty()) {
subcmdStr = "config" subcmdStr = "config"
subcmd = editConfigCommand subcmd = editConfigCommand
newargs = args newargs = args
}else { } else {
subcmdStr = args[0].lowercase() subcmdStr = args[0].lowercase()
subcmd = commands[subcmdStr] subcmd = commands[subcmdStr]
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
} }
@ -77,18 +77,18 @@ 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
if("gui".contentEquals(key)) continue if("gui".contentEquals(key)) 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

@ -12,7 +12,7 @@ import org.bukkit.command.CommandSender
import org.bukkit.entity.Player import org.bukkit.entity.Player
import xyz.alexcrea.cuanvil.command.DiagnosticExecutor.Companion.NO_DIAG_PERM import xyz.alexcrea.cuanvil.command.DiagnosticExecutor.Companion.NO_DIAG_PERM
class DebugToggleExecutor : CASubCommand() { class DebugToggleExecutor : CASubCommand {
override fun description(): String { override fun description(): String {
return "Used to toggle debug logs and retrieve it" return "Used to toggle debug logs and retrieve it"

View file

@ -1,6 +1,5 @@
package xyz.alexcrea.cuanvil.command package xyz.alexcrea.cuanvil.command
import com.github.stefvanschie.inventoryframework.inventoryview.interface_.InventoryViewUtil
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import net.md_5.bungee.api.chat.ClickEvent import net.md_5.bungee.api.chat.ClickEvent
import net.md_5.bungee.api.chat.HoverEvent import net.md_5.bungee.api.chat.HoverEvent
@ -16,11 +15,10 @@ import org.bukkit.entity.HumanEntity
import org.bukkit.entity.Player import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryType import org.bukkit.event.inventory.InventoryType
import org.bukkit.event.inventory.PrepareAnvilEvent 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.ItemStack
import org.bukkit.inventory.meta.Damageable import org.bukkit.inventory.meta.Damageable
import org.bukkit.inventory.meta.EnchantmentStorageMeta import org.bukkit.inventory.meta.EnchantmentStorageMeta
import org.bukkit.inventory.view.AnvilView
import org.bukkit.plugin.Plugin import org.bukkit.plugin.Plugin
import org.bukkit.plugin.RegisteredListener import org.bukkit.plugin.RegisteredListener
import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.dependency.DependencyManager
@ -32,10 +30,9 @@ import xyz.alexcrea.cuanvil.util.MetricsUtil
import java.util.* import java.util.*
import java.util.stream.Collectors import java.util.stream.Collectors
class DiagnosticExecutor : CASubCommand {
class DiagnosticExecutor: CASubCommand() { companion object {
companion object{
const val NO_DIAG_PERM = "You do not have permission to diagnostic this server" const val NO_DIAG_PERM = "You do not have permission to diagnostic this server"
fun fetchNMSType(): String { fun fetchNMSType(): String {
@ -43,7 +40,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) {
@ -54,7 +51,7 @@ class DiagnosticExecutor: CASubCommand() {
} }
return "$result ${if(packetManager.canSetInstantBuild) '✅' else '❌'}" return "$result ${if (packetManager.canSetInstantBuild) '✅' else '❌'}"
} }
} }
@ -75,7 +72,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)
} }
@ -85,12 +82,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)
} }
@ -112,7 +110,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"))
@ -123,16 +121,17 @@ 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())
message.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text("§7Click to copy")) message.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text("§7Click to copy"))
sender.spigot().sendMessage(message); sender.spigot().sendMessage(message)
} else { } else {
sender.sendMessage(stb.toString()); sender.sendMessage(stb.toString())
} }
return true return true
@ -142,41 +141,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)
} }
} }
@ -193,11 +192,11 @@ class DiagnosticExecutor: CASubCommand() {
damagedSword.itemMeta = meta damagedSword.itemMeta = meta
meta = enchantedSword.itemMeta meta = enchantedSword.itemMeta
meta!!.addEnchant(Enchantment.DAMAGE_ALL, 1, true) meta!!.addEnchant(Enchantment.SHARPNESS, 1, true)
enchantedSword.itemMeta = meta enchantedSword.itemMeta = meta
meta = enchantedBook.itemMeta meta = enchantedBook.itemMeta
(meta as EnchantmentStorageMeta).addStoredEnchant(Enchantment.DAMAGE_ALL, 1, true) (meta as EnchantmentStorageMeta).addStoredEnchant(Enchantment.SHARPNESS, 1, true)
enchantedBook.itemMeta = meta enchantedBook.itemMeta = meta
stb.append("\n\nItem to Item repair:") stb.append("\n\nItem to Item repair:")
@ -262,54 +261,52 @@ class DiagnosticExecutor: CASubCommand() {
} }
fun simulateAnvil(player: Player, stb: StringBuilder, left: ItemStack?, right: ItemStack?, result: ItemStack?) { fun simulateAnvil(player: Player, stb: StringBuilder, left: ItemStack?, right: ItemStack?, result: ItemStack?) {
var invView: InventoryView var invView: AnvilView
var event: PrepareAnvilEvent var event: PrepareAnvilEvent
try { try {
val fakeInv = Bukkit.createInventory(player, InventoryType.ANVIL) val fakeInv = Bukkit.createInventory(player, InventoryType.ANVIL)
invView = player.openInventory(fakeInv)!! invView = player.openInventory(fakeInv)!! as AnvilView
event = PrepareAnvilEvent(invView, result) event = DependencyManager.createFakeEvent(invView, result)
} catch (e: Throwable) { } catch (_: Throwable) {
// Help // Help
val menuTypeClazz = Class.forName("org.bukkit.inventory.MenuType") val menuTypeClazz = Class.forName("org.bukkit.inventory.MenuType")
val anvilTypeField = menuTypeClazz.getField("ANVIL") val anvilTypeField = menuTypeClazz.getField("ANVIL")
val anvilType = anvilTypeField.get(null) val anvilType = anvilTypeField.get(null)
val createMethod = anvilType.javaClass.getMethod("create", HumanEntity::class.java) val createMethod = anvilType.javaClass.getMethod("create", HumanEntity::class.java)
invView = createMethod.invoke(anvilType, player) as InventoryView invView = createMethod.invoke(anvilType, player) as AnvilView
player.openInventory(invView) player.openInventory(invView)
val anvilViewClass = Class.forName("org.bukkit.inventory.view.AnvilView") val constructor = PrepareAnvilEvent::class.java.getConstructor(AnvilView::class.java, ItemStack::class.java)
val constructor = PrepareAnvilEvent::class.java.getConstructor(anvilViewClass, ItemStack::class.java)
event = constructor.newInstance(invView, result) event = constructor.newInstance(invView, result)
} }
val fakeInv = InventoryViewUtil.getInstance().getTopInventory(invView) as AnvilInventory invView.setItem(0, left)
fakeInv.setItem(0, left) invView.setItem(1, right)
fakeInv.setItem(1, right)
val xp = fakeInv.repairCost val xp = invView.repairCost
val maxXp = fakeInv.maximumRepairCost val maxXp = invView.maximumRepairCost
val mergeResult = fakeInv.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(fakeInv.repairCost == xp) "Correct" else "Incorrect") .append(if (invView.repairCost == xp) "Correct" else "Incorrect")
.append("/") .append("/")
.append(if(fakeInv.maximumRepairCost == maxXp) "Correct" else "Incorrect") .append(if (invView.maximumRepairCost == maxXp) "Correct" else "Incorrect")
.append(" (${fakeInv.repairCost} $xp|${fakeInv.maximumRepairCost} $maxXp)") .append(" (${invView.repairCost} $xp|${invView.maximumRepairCost} $maxXp)")
.append("\nMerge result: ") .append("\nMerge result: ")
.append(if(fakeInv.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")
fakeInv.setItem(0, null) invView.setItem(0, null)
fakeInv.setItem(1, null) invView.setItem(1, null)
fakeInv.setItem(2, null) invView.setItem(2, null)
player.closeInventory() player.closeInventory()
} }
@ -327,11 +324,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()
}") }"
)
} }
@ -341,7 +340,6 @@ class DiagnosticExecutor: CASubCommand() {
stb.append("\n\nLast stack trace: ${e.stackTraceToString()}") stb.append("\n\nLast stack trace: ${e.stackTraceToString()}")
} }
} }

View file

@ -14,7 +14,7 @@ import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions
import xyz.alexcrea.cuanvil.util.MaterialUtil.customType import xyz.alexcrea.cuanvil.util.MaterialUtil.customType
import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir
class EditConfigExecutor : CASubCommand() { class EditConfigExecutor : CASubCommand {
override fun allowed(sender: CommandSender): Boolean { override fun allowed(sender: CommandSender): Boolean {
return sender.hasPermission(CustomAnvil.editConfigPermission) return sender.hasPermission(CustomAnvil.editConfigPermission)
@ -72,7 +72,7 @@ class EditConfigExecutor : CASubCommand() {
return return
} }
} else { } else {
enchantToFilter = HashSet(EnchantmentApi.getListByName(args[1].lowercase())) enchantToFilter = HashSet(EnchantmentApi.getByName(args[1].lowercase()))
if (enchantToFilter.isEmpty()) { if (enchantToFilter.isEmpty()) {
sender.sendMessage("No enchantment found with the name \"${args[1]}\"") sender.sendMessage("No enchantment found with the name \"${args[1]}\"")

View file

@ -2,13 +2,17 @@ package xyz.alexcrea.cuanvil.command
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import io.delilaheve.util.ConfigOptions import io.delilaheve.util.ConfigOptions
import io.delilaheve.util.ItemUtil.isEnchantedBook
import org.bukkit.Material
import org.bukkit.NamespacedKey
import org.bukkit.command.Command import org.bukkit.command.Command
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import xyz.alexcrea.cuanvil.api.EnchantmentApi import xyz.alexcrea.cuanvil.api.EnchantmentApi
import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir
class EnchantExecutor : CASubCommand() { class EnchantExecutor : CASubCommand {
override fun allowed(sender: CommandSender): Boolean { override fun allowed(sender: CommandSender): Boolean {
@ -37,22 +41,18 @@ class EnchantExecutor : CASubCommand() {
sender.sendMessage("Missing enchantment parameter") sender.sendMessage("Missing enchantment parameter")
return true return true
} }
1 -> {
sender.sendMessage("Missing level parameter")
return true
}
} }
val enchants = EnchantmentApi.getListByName(args[0].lowercase()) val enchant = firstEnchantment(args[0])
if (enchants.isEmpty()) { if (enchant == null) {
sender.sendMessage("Enchantment not found: ${args[0]}") sender.sendMessage("Enchantment not found: ${args[0]}")
return true return true
} }
val enchant = enchants.iterator().next() val level = if (args.size > 1)
args[1].toIntOrNull()?.coerceIn(0, ConfigOptions.ENCHANT_LIMIT)
else 1
val level = args[1].toIntOrNull()?.coerceIn(0, ConfigOptions.ENCHANT_LIMIT)
if (level == null) { if (level == null) {
sender.sendMessage("Invalid number: ${args[1]}") sender.sendMessage("Invalid number: ${args[1]}")
return true return true
@ -66,8 +66,15 @@ class EnchantExecutor : CASubCommand() {
if (level == 0) { if (level == 0) {
enchant.removeFrom(inHand) enchant.removeFrom(inHand)
if (inHand.isEnchantedBook() && EnchantmentApi.getEnchantments(inHand).isEmpty())
inHand.type = Material.BOOK
sender.sendMessage("${enchant.prettyName} removed") sender.sendMessage("${enchant.prettyName} removed")
} else { } else {
if (Material.BOOK == inHand.type)
inHand.type = Material.ENCHANTED_BOOK
enchant.addEnchantmentUnsafe(inHand, level) enchant.addEnchantmentUnsafe(inHand, level)
sender.sendMessage("${enchant.prettyName} set to level $level") sender.sendMessage("${enchant.prettyName} set to level $level")
} }
@ -92,10 +99,8 @@ class EnchantExecutor : CASubCommand() {
sender: HumanEntity, sender: HumanEntity,
name: String name: String
): Collection<String> { ): Collection<String> {
val enchants = EnchantmentApi.getListByName(name.lowercase()) val enchant = firstEnchantment(name) ?: return listOf()
if (enchants.isEmpty()) return listOf()
val enchant = enchants.iterator().next()
val limit = ConfigOptions.enchantLimit(enchant) val limit = ConfigOptions.enchantLimit(enchant)
val result = mutableListOf<String>() val result = mutableListOf<String>()
@ -110,4 +115,12 @@ class EnchantExecutor : CASubCommand() {
return result return result
} }
private fun firstEnchantment(name: String): CAEnchantment? {
val enchants = EnchantmentApi.getByName(name.lowercase())
if (!enchants.isEmpty())
return enchants.iterator().next()
return EnchantmentApi.getByKey(NamespacedKey.fromString(name))
}
} }

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())
} }
@ -25,6 +27,17 @@ class HelpExecutor: CASubCommand() {
return true return true
} }
override fun allowed(sender: CommandSender): Boolean {
return true
}
override fun tabCompleter(
sender: CommandSender,
args: Array<out String>,
list: MutableList<String>
) {
}
override fun description(): String { override fun description(): String {
return "Help command" return "Help command"
} }

View file

@ -10,12 +10,14 @@ import xyz.alexcrea.cuanvil.dependency.DependencyManager
import xyz.alexcrea.cuanvil.gui.config.global.* import xyz.alexcrea.cuanvil.gui.config.global.*
import xyz.alexcrea.cuanvil.update.UpdateHandler 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
@ -38,6 +40,13 @@ class ReloadExecutor : CASubCommand() {
return sender.hasPermission(CustomAnvil.commandReloadPermission) return sender.hasPermission(CustomAnvil.commandReloadPermission)
} }
override fun tabCompleter(
sender: CommandSender,
args: Array<out String>,
list: MutableList<String>
) {
}
override fun description(): String { override fun description(): String {
return "Reload the configuration of this plugin" return "Reload the configuration of this plugin"
} }

View file

@ -1,6 +1,5 @@
package xyz.alexcrea.cuanvil.dependency package xyz.alexcrea.cuanvil.dependency
import com.maddoxh.superEnchants.SuperEnchants
import io.delilaheve.CustomAnvil import io.delilaheve.CustomAnvil
import net.kyori.adventure.text.Component import net.kyori.adventure.text.Component
import org.bukkit.Bukkit import org.bukkit.Bukkit
@ -10,16 +9,14 @@ import org.bukkit.entity.HumanEntity
import org.bukkit.entity.Player import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.PrepareAnvilEvent import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.AnvilInventory
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.InventoryView
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.anvil.AnvilCost
import xyz.alexcrea.cuanvil.anvil.AnvilUseType import xyz.alexcrea.cuanvil.anvil.AnvilUseType
import xyz.alexcrea.cuanvil.api.event.listener.CAClickResultBypassEvent import xyz.alexcrea.cuanvil.api.event.listener.CAClickResultBypassEvent
import xyz.alexcrea.cuanvil.api.event.listener.CAEarlyPreAnvilBypassEvent import xyz.alexcrea.cuanvil.api.event.listener.CAEarlyPreAnvilBypassEvent
import xyz.alexcrea.cuanvil.api.event.listener.CAPreAnvilBypassEvent import xyz.alexcrea.cuanvil.api.event.listener.CAPreAnvilBypassEvent
import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResult2Event import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResultEvent
import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.dependency.datapack.DataPackDependency import xyz.alexcrea.cuanvil.dependency.datapack.DataPackDependency
import xyz.alexcrea.cuanvil.dependency.gui.GenericExternGuiTester import xyz.alexcrea.cuanvil.dependency.gui.GenericExternGuiTester
@ -33,8 +30,10 @@ import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil
import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil.componentLore import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil.componentLore
import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener.Companion.ANVIL_OUTPUT_SLOT import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener.Companion.ANVIL_OUTPUT_SLOT
import xyz.alexcrea.cuanvil.util.MetricsUtil.trackError import xyz.alexcrea.cuanvil.util.MetricsUtil.trackError
import java.lang.reflect.Constructor
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 +102,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,12 +115,16 @@ 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")!! as SuperEnchants) val compatibility = SuperEnchantDependency(pluginManager.getPlugin("SuperEnchants")!!)
if(compatibility.registerEnchantments()) if (compatibility.registerEnchantments())
genericDependencies.add(compatibility) genericDependencies.add(compatibility)
} }
if (pluginManager.isPluginEnabled("EnchantedBook")) {
genericDependencies.add(EnchantedBookDependency(pluginManager.getPlugin("EnchantedBook")!!))
}
for (dependency in genericDependencies) for (dependency in genericDependencies)
dependency.redirectListeners() dependency.redirectListeners()
@ -164,11 +167,11 @@ object DependencyManager {
) )
} }
private fun logExceptionAndClear(target: CommandSender, inventory: Inventory, e: Exception) { private fun logExceptionAndClear(view: AnvilView, e: Exception) {
// Just in case to avoid illegal items // Just in case to avoid illegal items
inventory.setItem(ANVIL_OUTPUT_SLOT, null) view.setItem(ANVIL_OUTPUT_SLOT, null)
logException(target, e) logException(view.player, e)
} }
// Return true if should bypass (either by a dependency or error) // Return true if should bypass (either by a dependency or error)
@ -177,7 +180,7 @@ object DependencyManager {
try { try {
return earlyUnsafeTryEventPreAnvilBypass(event, player) return earlyUnsafeTryEventPreAnvilBypass(event, player)
} catch (e: Exception) { } catch (e: Exception) {
logExceptionAndClear(event.view.player, event.inventory, e) logExceptionAndClear(event.view, e)
return true return true
} }
} }
@ -203,7 +206,7 @@ object DependencyManager {
try { try {
return unsafeTryEventPreAnvilBypass(event, player) return unsafeTryEventPreAnvilBypass(event, player)
} catch (e: Exception) { } catch (e: Exception) {
logExceptionAndClear(event.view.player, event.inventory, e) logExceptionAndClear(event.view, e)
return true return true
} }
} }
@ -233,40 +236,39 @@ object DependencyManager {
// Return null if there was an issue // Return null if there was an issue
fun tryTreatAnvilResult( fun tryTreatAnvilResult(
view: InventoryView, view: AnvilView,
inventory: Inventory, // TODO REMOVE, use view instead on legacy removal
player: HumanEntity, player: HumanEntity,
result: ItemStack, result: ItemStack,
useType: AnvilUseType, useType: AnvilUseType,
cost: AnvilCost cost: AnvilCost
): ItemStack? { ): ItemStack? {
val treatEvent = CATreatAnvilResult2Event(view, inventory, useType, result, cost) val treatEvent = CATreatAnvilResultEvent(view, useType, result, cost)
try { try {
unsafeTryTreatAnvilResult(treatEvent) unsafeTryTreatAnvilResult(treatEvent)
return treatEvent.result return treatEvent.result
} catch (e: Exception) { } catch (e: Exception) {
logExceptionAndClear(player, inventory, e) logExceptionAndClear(view, e)
return null return null
} }
} }
private fun unsafeTryTreatAnvilResult(event: CATreatAnvilResult2Event) { private fun unsafeTryTreatAnvilResult(event: CATreatAnvilResultEvent) {
Bukkit.getPluginManager().callEvent(event) Bukkit.getPluginManager().callEvent(event)
excellentEnchantsCompatibility?.treatAnvilResult(event) excellentEnchantsCompatibility?.treatAnvilResult(event)
} }
// Return true if should bypass (either by a dependency or error) // Return true if should bypass (either by a dependency or error)
fun tryClickAnvilResultBypass(event: InventoryClickEvent, inventory: AnvilInventory): Boolean { fun tryClickAnvilResultBypass(event: InventoryClickEvent, view: AnvilView): Boolean {
try { try {
return unsafeTryClickAnvilResultBypass(event, inventory) return unsafeTryClickAnvilResultBypass(event, view)
} catch (e: Exception) { } catch (e: Exception) {
logExceptionAndClear(event.view.player, event.inventory, e) logExceptionAndClear(view, e)
return true return true
} }
} }
private fun unsafeTryClickAnvilResultBypass(event: InventoryClickEvent, inventory: AnvilInventory): Boolean { private fun unsafeTryClickAnvilResultBypass(event: InventoryClickEvent, view: AnvilView): Boolean {
// Run the event // Run the event
val bypassEvent = CAClickResultBypassEvent(event) val bypassEvent = CAClickResultBypassEvent(event)
Bukkit.getPluginManager().callEvent(bypassEvent) Bukkit.getPluginManager().callEvent(bypassEvent)
@ -274,10 +276,10 @@ object DependencyManager {
var bypass = bypassEvent.isCancelled var bypass = bypassEvent.isCancelled
// Test if disenchantment used event click // Test if disenchantment used event click
if (!bypass && (disenchantmentCompatibility?.testAnvilResult(event, inventory) == true)) bypass = true if (!bypass && (disenchantmentCompatibility?.testAnvilResult(event, view) == true)) bypass = true
// Test if haven bag used event click // Test if haven bag used event click
if (!bypass && (havenBagsCompatibility?.testAnvilResult(event, inventory) == true)) bypass = true if (!bypass && (havenBagsCompatibility?.testAnvilResult(event, view) == true)) bypass = true
// Test if disenchantment used event click // Test if disenchantment used event click
if (!bypass && (excellentEnchantsCompatibility?.testAnvilResult(event) == true)) bypass = true if (!bypass && (excellentEnchantsCompatibility?.testAnvilResult(event) == true)) bypass = true
@ -287,10 +289,10 @@ object DependencyManager {
} }
// Test if the inventory is a gui(version specific) // Test if the inventory is a gui(version specific)
if (!bypass && externGuiTester.testIfGui(event.view)) bypass = true if (!bypass && externGuiTester.testIfGui(view)) bypass = true
// Test if in an ax player warp rating gui // Test if in an ax player warp rating gui
if (!bypass && (axPlayerWarpsCompatibility?.testIfGui(event.view.player) == true)) bypass = true if (!bypass && (axPlayerWarpsCompatibility?.testIfGui(view.player) == true)) bypass = true
return bypass return bypass
} }
@ -307,7 +309,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()
} }
@ -328,4 +330,12 @@ object DependencyManager {
enchantmentSquaredCompatibility?.updateLore(item) enchantmentSquaredCompatibility?.updateLore(item)
} }
private val prepareAnvilConstructor =
PrepareAnvilEvent::class.java.constructors.first() as Constructor<PrepareAnvilEvent>
fun createFakeEvent(view: AnvilView, result: ItemStack?): PrepareAnvilEvent {
return prepareAnvilConstructor.newInstance(view, result)
}
} }

View file

@ -10,32 +10,6 @@ object MinecraftVersionUtil {
if (version.major != 1) return null if (version.major != 1) return null
return when (version.minor) { return when (version.minor) {
17 -> when (version.patch) {
0, 1 -> "1_17R1"
else -> null
}
18 -> when (version.patch) {
0, 1 -> "1_18R1"
2 -> "1_18R2"
else -> null
}
19 -> when (version.patch) {
0, 1, 2 -> "1_19R1"
3 -> "1_19R2"
4 -> "1_19R3"
else -> null
}
20 -> when (version.patch) {
0, 1 -> "1_20R1"
2 -> "1_20R2"
3, 4 -> "1_20R3"
5, 6 -> "1_20R4"
else -> null
}
21 -> when (version.patch) { 21 -> when (version.patch) {
0, 1 -> "1_21R1" 0, 1 -> "1_21R1"
2, 3 -> "1_21R2" 2, 3 -> "1_21R2"
@ -46,12 +20,15 @@ object MinecraftVersionUtil {
11 -> "1_21R7" 11 -> "1_21R7"
else -> null else -> null
} }
//TODO need to continue updating that for anvil gui test dependency....
else -> null else -> null
} }
} }
val isTooNewForSpigot: Boolean get() { val isTooNewForSpigot: Boolean
get() {
return UpdateUtils.currentMinecraftVersion().major != 1 return UpdateUtils.currentMinecraftVersion().major != 1
} }

View file

@ -1,3 +1,5 @@
@file:Suppress("DEPRECATION")
package xyz.alexcrea.cuanvil.dependency.economy package xyz.alexcrea.cuanvil.dependency.economy
import net.milkbowl.vault.economy.Economy import net.milkbowl.vault.economy.Economy

View file

@ -1,10 +1,11 @@
package xyz.alexcrea.cuanvil.dependency.gui package xyz.alexcrea.cuanvil.dependency.gui
import org.bukkit.inventory.InventoryView import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.dependency.MinecraftVersionUtil import xyz.alexcrea.cuanvil.dependency.MinecraftVersionUtil
import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil
import java.lang.reflect.Method import java.lang.reflect.Method
@Suppress("UnstableApiUsage")
class GenericExternGuiTester { class GenericExternGuiTester {
companion object { companion object {
@ -21,7 +22,7 @@ class GenericExternGuiTester {
var testedClass: String? = null var testedClass: String? = null
lateinit var getHandleMethod: Method lateinit var getHandleMethod: Method
private fun getContainerClass(view: InventoryView): Class<Any>? { private fun getContainerClass(view: AnvilView): Class<Any>? {
if(!testedClass.contentEquals(view.javaClass.name)) if(!testedClass.contentEquals(view.javaClass.name))
return null return null
@ -64,11 +65,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: AnvilView): 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

@ -12,8 +12,8 @@ import org.bukkit.entity.Player
import org.bukkit.event.Listener import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.PrepareAnvilEvent import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.AnvilInventory
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.view.AnvilView
import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.anvil.AnvilCost
import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener
import xyz.alexcrea.cuanvil.util.MetricsUtil.trackError import xyz.alexcrea.cuanvil.util.MetricsUtil.trackError
@ -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 {
@ -59,14 +60,14 @@ class DisenchantmentDependency {
DisenchantEvent.onEvent(event) DisenchantEvent.onEvent(event)
if (event.result != null) { if (event.result != null) {
CustomAnvil.log("Detected pre anvil item extract bypass.") CustomAnvil.log("Detected pre anvil item extract bypass.")
AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, AnvilCost(event.inventory.repairCost)) AnvilXpUtil.setAnvilInvCost(event.view, player, AnvilCost(event.view.repairCost))
return true return true
} }
ShatterEvent.onEvent(event) ShatterEvent.onEvent(event)
if (event.result != null) { if (event.result != null) {
CustomAnvil.log("Detected pre anvil split enchant bypass.") CustomAnvil.log("Detected pre anvil split enchant bypass.")
AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, AnvilCost(event.inventory.repairCost)) AnvilXpUtil.setAnvilInvCost(event.view, player, AnvilCost(event.view.repairCost))
return true return true
} }
@ -74,18 +75,18 @@ class DisenchantmentDependency {
return false return false
} }
fun testAnvilResult(event: InventoryClickEvent, inventory: AnvilInventory): Boolean { fun testAnvilResult(event: InventoryClickEvent, view: AnvilView): Boolean {
val previousResultSlot = inventory.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)?.clone() val previousResultSlot = view.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)?.clone()
// Test event if change the result // Test event if change the result
DisenchantClickEvent.onEvent(event) DisenchantClickEvent.onEvent(event)
if (!testAnvilInventoryChange(inventory, previousResultSlot) || event.isCancelled) { if (!testAnvilChange(view, previousResultSlot) || event.isCancelled) {
CustomAnvil.log("Detected anvil click item extract bypass.") CustomAnvil.log("Detected anvil click item extract bypass.")
return true return true
} }
ShatterClickEvent.onEvent(event) ShatterClickEvent.onEvent(event)
if (!testAnvilInventoryChange(inventory, previousResultSlot) || event.isCancelled) { if (!testAnvilChange(view, previousResultSlot) || event.isCancelled) {
CustomAnvil.log("Detected anvil click split enchant bypass.") CustomAnvil.log("Detected anvil click split enchant bypass.")
return true return true
} }
@ -93,8 +94,8 @@ class DisenchantmentDependency {
return false return false
} }
private fun testAnvilInventoryChange(inventory: AnvilInventory, previous: ItemStack?): Boolean { private fun testAnvilChange(view: AnvilView, previous: ItemStack?): Boolean {
val currentResult = inventory.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT) val currentResult = view.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)
return currentResult == previous return currentResult == previous
} }

View file

@ -0,0 +1,34 @@
package xyz.alexcrea.cuanvil.dependency.plugins
import org.bukkit.event.Event
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.inventory.view.AnvilView
import org.bukkit.plugin.Plugin
import xyz.alexcrea.cuanvil.dependency.DependencyManager
import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener.Companion.ANVIL_INPUT_LEFT
import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener.Companion.ANVIL_OUTPUT_SLOT
@Suppress("UnstableApiUsage")
class EnchantedBookDependency(plugin: Plugin) : GenericPluginDependency(plugin) {
override fun testAnvilResult(event: InventoryClickEvent): Boolean {
val view = event.view as? AnvilView ?: return false
val inv = event.inventory
//TODO use view here (v2)
val current = inv.getItem(ANVIL_OUTPUT_SLOT)
inv.setItem(ANVIL_OUTPUT_SLOT, null)
val fakeEvent = DependencyManager.createFakeEvent(view, null)
if (testPrepareAnvil(fakeEvent)) {
event.result = Event.Result.DEFAULT
inv.setItem(ANVIL_INPUT_LEFT, fakeEvent.result)
return true
}
inv.setItem(ANVIL_INPUT_LEFT, current)
return false
}
}

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

@ -8,19 +8,19 @@ import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.RegisteredListener import org.bukkit.plugin.RegisteredListener
import xyz.alexcrea.cuanvil.api.EnchantmentApi import xyz.alexcrea.cuanvil.api.EnchantmentApi
import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResult2Event import xyz.alexcrea.cuanvil.dependency.DependencyManager
import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResultEvent
import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEPreV5Enchantment import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEPreV5Enchantment
import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEV5Enchantment import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEV5Enchantment
import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEV5_4Enchantment import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEV5_4Enchantment
import xyz.alexcrea.cuanvil.enchant.wrapped.CALegacyEEEnchantment import xyz.alexcrea.cuanvil.enchant.wrapped.CALegacyEEEnchantment
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
@ -47,20 +47,20 @@ class ExcellentEnchantsDependency {
listenerVersion = value listenerVersion = value
break break
} catch (ignored: ClassNotFoundException) { } catch (_: ClassNotFoundException) {
} }
} }
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)
} }
var isModernCurseOfFragility = true var isModernCurseOfFragility = true
try { try {
Class.forName("su.nightexpress.excellentenchants.enchantment.universal.CurseOfFragilityEnchant") Class.forName("su.nightexpress.excellentenchants.enchantment.universal.CurseOfFragilityEnchant")
} catch (ignored: ClassNotFoundException) { } catch (_: ClassNotFoundException) {
isModernCurseOfFragility = false isModernCurseOfFragility = false
} }
@ -118,8 +118,6 @@ class ExcellentEnchantsDependency {
private lateinit var handleRechargeMethod: Method private lateinit var handleRechargeMethod: Method
private lateinit var handleCombineMethod: Method private lateinit var handleCombineMethod: Method
private val prepareAnvilConstructor = PrepareAnvilEvent::class.java.constructors.first() as Constructor<PrepareAnvilEvent>
fun redirectListeners() { fun redirectListeners() {
val toUnregister = ArrayList<RegisteredListener>() val toUnregister = ArrayList<RegisteredListener>()
// get required PrepareAnvilEvent listener // get required PrepareAnvilEvent listener
@ -173,6 +171,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 -> {}
@ -221,12 +220,12 @@ class ExcellentEnchantsDependency {
return handleRechargeMethod.invoke(this.usedAnvilListener, event, first, second) as Boolean return handleRechargeMethod.invoke(this.usedAnvilListener, event, first, second) as Boolean
} }
fun treatAnvilResult(event: CATreatAnvilResult2Event) { fun treatAnvilResult(event: CATreatAnvilResultEvent) {
val result = event.result ?: return val result = event.result ?: return
val first: ItemStack = treatInput(event.leftItem) val first: ItemStack = treatInput(event.leftItem)
val second: ItemStack = treatInput(event.rightItem) val second: ItemStack = treatInput(event.rightItem)
val fakeEvent = prepareAnvilConstructor.newInstance(event.view, result) val fakeEvent = DependencyManager.createFakeEvent(event.view, result)
handleCombineMethod.invoke(this.usedAnvilListener, fakeEvent, first, second, result) handleCombineMethod.invoke(this.usedAnvilListener, fakeEvent, first, second, result)
@ -240,6 +239,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

@ -4,7 +4,7 @@ import io.delilaheve.CustomAnvil
import org.bukkit.entity.Player import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.PrepareAnvilEvent import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.AnvilInventory import org.bukkit.inventory.view.AnvilView
import org.bukkit.plugin.RegisteredListener import org.bukkit.plugin.RegisteredListener
import valorless.havenbags.HavenBags import valorless.havenbags.HavenBags
import valorless.havenbags.features.BagSkin import valorless.havenbags.features.BagSkin
@ -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 {
@ -54,14 +55,14 @@ class HavenBagsDependency {
bagSkin.onPrepareAnvil(event) bagSkin.onPrepareAnvil(event)
if (event.result != null) { if (event.result != null) {
CustomAnvil.log("Detected pre anvil heaven bag anvil skin.") CustomAnvil.log("Detected pre anvil heaven bag anvil skin.")
AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, AnvilCost(event.inventory.repairCost)) AnvilXpUtil.setAnvilInvCost(event.view, player, AnvilCost(event.view.repairCost))
return true return true
} }
bagUpgrade.onPrepareAnvil(event) bagUpgrade.onPrepareAnvil(event)
if (event.result != null) { if (event.result != null) {
CustomAnvil.log("Detected pre anvil heaven bag anvil upgrade.") CustomAnvil.log("Detected pre anvil heaven bag anvil upgrade.")
AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, AnvilCost(event.inventory.repairCost)) AnvilXpUtil.setAnvilInvCost(event.view, player, AnvilCost(event.view.repairCost))
return true return true
} }
@ -69,8 +70,8 @@ class HavenBagsDependency {
return false return false
} }
fun testAnvilResult(event: InventoryClickEvent, inventory: AnvilInventory): Boolean { fun testAnvilResult(event: InventoryClickEvent, view: AnvilView): Boolean {
val result = inventory.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)?.clone() val result = view.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)?.clone()
if (HavenBags.IsBag(result)) { if (HavenBags.IsBag(result)) {
CustomAnvil.log("Detected anvil click haven bag bypass.") CustomAnvil.log("Detected anvil click haven bag bypass.")

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)

Some files were not shown because too many files have changed in this diff Show more