From cf60deda92544971745013422c0ce00bf517443f Mon Sep 17 00:00:00 2001 From: Veyronity Date: Mon, 25 May 2026 19:57:00 +0300 Subject: [PATCH 1/2] Fix bugs, remove unnecessary protections, generally cleanup code --- build.gradle | 29 -- .../ArmorStandEditorPlugin.java | 132 ++------- .../rypofalem/armorstandeditor/CommandEx.java | 212 ++++++-------- .../rypofalem/armorstandeditor/Debug.java | 8 +- .../armorstandeditor/PlayerEditor.java | 205 ++++++------- .../armorstandeditor/PlayerEditorManager.java | 277 ++++++++---------- .../rypofalem/armorstandeditor/Scheduler.java | 28 -- .../armorstandeditor/SharedUtil.java | 39 +++ .../armorstandeditor/TabCompleter.java | 8 +- .../armorstandeditor/UpdateChecker.java | 2 +- .../armorstandeditor/menu/EquipmentMenu.java | 18 +- .../rypofalem/armorstandeditor/menu/Menu.java | 12 +- .../menu/PresetArmorPosesMenu.java | 19 +- .../armorstandeditor/menu/SizeMenu.java | 107 ++++--- .../modes/AdjustmentMode.java | 2 +- .../armorstandeditor/modes/Axis.java | 2 +- .../protections/BentoBoxProtection.java | 100 ------- .../protections/BoltProtection.java | 39 --- .../protections/GriefDefenderProtection.java | 60 ---- .../protections/LandsProtection.java | 93 ------ .../protections/PlotSquaredProtection.java | 79 ----- .../protections/SkyblockProtection.java | 55 ---- .../protections/TownyProtection.java | 31 +- .../protections/itemAdderProtection.java | 56 ---- 24 files changed, 448 insertions(+), 1165 deletions(-) create mode 100644 src/main/java/io/github/rypofalem/armorstandeditor/SharedUtil.java delete mode 100644 src/main/java/io/github/rypofalem/armorstandeditor/protections/BentoBoxProtection.java delete mode 100644 src/main/java/io/github/rypofalem/armorstandeditor/protections/BoltProtection.java delete mode 100644 src/main/java/io/github/rypofalem/armorstandeditor/protections/GriefDefenderProtection.java delete mode 100644 src/main/java/io/github/rypofalem/armorstandeditor/protections/LandsProtection.java delete mode 100644 src/main/java/io/github/rypofalem/armorstandeditor/protections/PlotSquaredProtection.java delete mode 100644 src/main/java/io/github/rypofalem/armorstandeditor/protections/SkyblockProtection.java delete mode 100644 src/main/java/io/github/rypofalem/armorstandeditor/protections/itemAdderProtection.java diff --git a/build.gradle b/build.gradle index add9627b0..34e348996 100644 --- a/build.gradle +++ b/build.gradle @@ -80,41 +80,12 @@ dependencies { // WorldGuard compileOnly "com.sk89q.worldguard:worldguard-bukkit:7.1.0-SNAPSHOT" - // PlotSquared - compileOnly("com.intellectualsites.plotsquared:plotsquared-core:7.5.12") { - exclude group: "net.kyori" - } - compileOnly("com.intellectualsites.plotsquared:plotsquared-bukkit:7.5.12") { - exclude group: "net.kyori" - } - // Towny compileOnly "com.palmergames.bukkit.towny:towny:0.102.0.13" - // SuperiorSkyblock - compileOnly "com.bgsoftware:SuperiorSkyblockAPI:2025.2.1" - - // GriefDefender - compileOnly("com.griefdefender:api:2.1.1-SNAPSHOT") { - exclude group: "net.kyori" - } - - // Lands - compileOnly "com.github.angeschossen:LandsAPI:7.25.4" - - // Bentobox (compileOnly to avoid bundling) - compileOnly "world.bentobox:bentobox:2.7.0-SNAPSHOT" - - // ItemAdder - compileOnly "com.github.LoneDev6:api-itemsadder:3.6.1" - // CoreProtect compileOnly "net.coreprotect:coreprotect:23.2" - // Bolt - compileOnly "org.popcraft:bolt-bukkit:1.1.33" - compileOnly "org.popcraft:bolt-common:1.2.86" - // Lombok compileOnly "org.projectlombok:lombok:1.18.44" annotationProcessor "org.projectlombok:lombok:1.18.44" diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/ArmorStandEditorPlugin.java b/src/main/java/io/github/rypofalem/armorstandeditor/ArmorStandEditorPlugin.java index 49fb80689..c5a19e2e0 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/ArmorStandEditorPlugin.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/ArmorStandEditorPlugin.java @@ -27,6 +27,7 @@ import io.github.rypofalem.armorstandeditor.Metrics.SimplePie; import io.papermc.lib.PaperLib; +import lombok.Getter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; @@ -41,25 +42,22 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.components.CustomModelDataComponent; import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.Team; import java.io.File; import java.util.*; import java.util.logging.Level; -import static net.kyori.adventure.text.format.NamedTextColor.RED; - public class ArmorStandEditorPlugin extends JavaPlugin { //!!! DO NOT REMOVE THESE UNDER ANY CIRCUMSTANCES - Required for BStats and UpdateChecker !!! private static final int PLUGIN_ID = 12668; //Used for BStats Metrics - public final Debug debug = new Debug(this); private NamespacedKey iconKey; private static ArmorStandEditorPlugin instance; + @Getter private Language lang; + @Getter private CoreProtectExtension coreProtectExtension; //Server Version Detection: Paper or Spigot and Invalid NMS Version @@ -83,6 +81,7 @@ public class ArmorStandEditorPlugin extends JavaPlugin { double updateCheckerInterval; //Edit Tool Information + @Getter Material editTool; String toolType; int editToolData = Integer.MIN_VALUE; @@ -94,13 +93,17 @@ public class ArmorStandEditorPlugin extends JavaPlugin { List editToolLore = null; boolean enablePerWorld = false; List allowedWorldList = null; + @Getter double maxScaleValue; + @Getter double minScaleValue; + @Getter double maxResetRange; //Custom Data Model Support - Readded boolean allowCustomModelData = false; // FIX: renamed from customModelDataInt and retyped to int — it was float but used as an integer throughout + @Getter int customModelDataValue; //GUI Settings @@ -119,13 +122,6 @@ public class ArmorStandEditorPlugin extends JavaPlugin { boolean allowedToRetrieveOwnPlayerHead = false; boolean adminOnlyNotifications = false; - //Glow Entity Colors - public Scoreboard scoreboard; - public Team team; - List asTeams = new ArrayList<>(); - String lockedTeam = "ASLocked"; - String inUseTeam = "AS-InUse"; - //Blocked Names boolean enableBlockedNames = false; List blockedNames = new ArrayList<>(); @@ -133,6 +129,7 @@ public class ArmorStandEditorPlugin extends JavaPlugin { //Debugging Options.... Not Exposed globally boolean debugFlag; + @Getter private Scheduler scheduler; public ArmorStandEditorPlugin() { @@ -143,9 +140,6 @@ public ArmorStandEditorPlugin() { public void onEnable() { scheduler = new Scheduler(this); - if (!getHasFolia()) - scoreboard = Objects.requireNonNull(this.getServer().getScoreboardManager()).getMainScoreboard(); - //START --- Load Messages in Console getLogger().info("======= ArmorStandEditor ======="); getLogger().info("Plugin Version: v" + ASE_VERSION); @@ -168,15 +162,6 @@ public void onEnable() { getLogger().log(Level.INFO, "Paper/Folia Present? {0}", hasPaper); } - if (!hasFolia) { - scoreboard = Objects.requireNonNull(this.getServer().getScoreboardManager()).getMainScoreboard(); - registerScoreboards(scoreboard); - if (!asTeams.contains(lockedTeam)) asTeams.add(lockedTeam); - if (!asTeams.contains(inUseTeam)) asTeams.add(inUseTeam); - } else { - runWarningsFolia(); - } - //Run the update checker if enabled in config if (getRunTheUpdateChecker()) { new UpdateChecker(this).checkForUpdates(); @@ -245,42 +230,6 @@ private void doVersionCheck() { } } - //Implement Glow Effects for Wolfstorm/ArmorStandEditor-Issues#5 - Add Disable Slots with Different Glow than Default - private void registerScoreboards(Scoreboard scoreboard) { - getLogger().info("Registering Scoreboards required for Glowing Effects"); - - if (scoreboard.getTeam(inUseTeam) == null) { - scoreboard.registerNewTeam(inUseTeam); - } else { - getLogger().info("Scoreboard for AS-InUse Already exists. Continuing to load"); - } - - if (scoreboard.getTeam(lockedTeam) == null) { - scoreboard.registerNewTeam(lockedTeam); - scoreboard.getTeam(lockedTeam).color(RED); - } else { - getLogger().info("Scoreboard for ASLocked Already exists. Continuing to load"); - } - } - - private void unregisterScoreboards(Scoreboard scoreboard) { - getLogger().info("Removing Scoreboards required for Glowing Effects when Disabling Slots..."); - - team = scoreboard.getTeam(lockedTeam); - if (team != null) { - team.unregister(); - } else { - getLogger().severe("Team Already Appears to be removed. Please do not do this manually!"); - } - - team = scoreboard.getTeam(inUseTeam); - if (team != null) { - team.unregister(); - } else { - getLogger().severe("Team Already Appears to be removed. Please do not do this manually!"); - } - } - private void updateConfig(String folder, String config) { if (!new File(getDataFolder() + File.separator + folder + config).exists()) { saveResource(folder + config, false); @@ -294,11 +243,6 @@ public void onDisable() { player.closeInventory(InventoryCloseEvent.Reason.DISCONNECT); } } - - if (!hasFolia) { - scoreboard = Objects.requireNonNull(this.getServer().getScoreboardManager()).getMainScoreboard(); - unregisterScoreboards(scoreboard); - } } public String getNmsVersion() { @@ -325,37 +269,19 @@ public boolean getHasFolia() { } } - public String getMinecraftVersion() { - return this.nmsVersion; - } - // FIX: all getters now return cached fields instead of re-reading config on every call public boolean getArmorStandVisibility() { return armorStandVisibility; } public boolean getItemFrameVisibility() { return invisibleItemFrames; } - public Language getLang() { return lang; } - - public double getMaxResetRange() { return maxResetRange; } - - public Material getEditTool() { return this.editTool; } - public boolean getRunTheUpdateChecker() { return runTheUpdateChecker; } public boolean getDefaultGravity() { return defaultGravity; } - // FIX: renamed from getallowedToRetrieveOwnPlayerHead (lowercase 'a' violated naming convention) public boolean getAllowedToRetrieveOwnPlayerHead() { return allowedToRetrieveOwnPlayerHead; } public boolean getAdminOnlyNotifications() { return adminOnlyNotifications; } - public double getMinScaleValue() { return minScaleValue; } - - public double getMaxScaleValue() { return maxScaleValue; } - - // FIX: renamed to match field rename from customModelDataInt -> customModelDataValue - public int getCustomModelDataValue() { return customModelDataValue; } - public boolean isEditTool(ItemStack itemStk) { if (itemStk == null || editTool != itemStk.getType()) return false; @@ -365,9 +291,7 @@ public boolean isEditTool(ItemStack itemStk) { if (requireToolData && !hasMatchingDurability(itemMeta)) return false; if (requireToolName && !hasMatchingName(itemMeta)) return false; if (requireToolLore && !hasMatchingLore(itemMeta)) return false; - if (allowCustomModelData && !hasMatchingCustomModelData(itemMeta)) return false; - - return true; + return !allowCustomModelData || hasMatchingCustomModelData(itemMeta); } private boolean hasMatchingDurability(ItemMeta itemMeta) { @@ -384,14 +308,15 @@ private boolean hasMatchingName(ItemMeta itemMeta) { private boolean hasMatchingLore(ItemMeta itemMeta) { if (editToolLore == null) return true; List itemLore = itemMeta.lore(); - return itemLore != null && itemLore.equals((List) editToolLore); + return itemLore != null && itemLore.equals(editToolLore); } + @SuppressWarnings("UnstableApiUsage") private boolean hasMatchingCustomModelData(ItemMeta itemMeta) { if (customModelDataValue == 0) return true; CustomModelDataComponent component = itemMeta.getCustomModelDataComponent(); if (component.getFloats().isEmpty()) return true; - // FIX: was comparing float to float with ==; now both sides are cast to int for reliable equality + return component.getFloats().getFirst().intValue() == customModelDataValue; } @@ -411,7 +336,7 @@ public void loadConfigValues() { runTheUpdateChecker = getConfig().getBoolean("runTheUpdateChecker", true); opUpdateNotification = getConfig().getBoolean("opUpdateNotification", true); updateCheckerInterval = getConfig().getDouble("updateCheckerInterval", 24); - allowedToRetrieveOwnPlayerHead = getConfig().getBoolean("allowedToRetrieveOwnPlayerHead", true); + allowedToRetrieveOwnPlayerHead = getConfig().getBoolean("allowedToRetrieveOwnPlayerHead", false); adminOnlyNotifications = getConfig().getBoolean("adminOnlyNotifications", true); armorStandVisibility = getConfig().getBoolean("armorStandVisibility", true); requireToolData = getConfig().getBoolean("requireToolData", false); @@ -455,7 +380,8 @@ private void loadConditionalConfig() { editToolLore = getConfig().getList("toolLore", null); } - if (enablePerWorld = getConfig().getBoolean("enablePerWorldSupport", false)) { + enablePerWorld = getConfig().getBoolean("enablePerWorldSupport", false); + if (enablePerWorld) { allowedWorldList = getConfig().getList("allowed-worlds", null); if (allowedWorldList != null && !allowedWorldList.isEmpty() && allowedWorldList.getFirst().equals("*")) { allowedWorldList = getServer().getWorlds().stream().map(World::getName).toList(); @@ -473,22 +399,11 @@ private void loadConditionalConfig() { debugFlag = getConfig().getBoolean("debugFlag", false); if (debugFlag) { - getServer().getLogger().log(Level.INFO, "[ArmorStandEditor-Debug] Debug Mode ENABLED! Use for testing only."); + getLogger().log(Level.INFO, "[ArmorStandEditor-Debug] Debug Mode ENABLED! Use for testing only."); } } public void performReload() { - // FIX: was fetching scoreboard twice and adding teams without duplicate checks - if (!hasFolia) { - scoreboard = Objects.requireNonNull(this.getServer().getScoreboardManager()).getMainScoreboard(); - unregisterScoreboards(scoreboard); - registerScoreboards(scoreboard); - if (!asTeams.contains(lockedTeam)) asTeams.add(lockedTeam); - if (!asTeams.contains(inUseTeam)) asTeams.add(inUseTeam); - } else { - runWarningsFolia(); - } - reloadConfig(); loadConfigValues(); } @@ -548,10 +463,6 @@ private void getMetrics() { metrics.addCustomChart(new SimplePie("allowCustomModelData", () -> String.valueOf(getConfig().getBoolean("allowCustomModelData")))); } - private void runWarningsFolia() { - getLogger().warning("Scoreboards currently do not work on Folia. Scoreboard Coloring will not work"); - } - public NamespacedKey getIconKey() { if (iconKey == null) iconKey = new NamespacedKey(this, "command_icon"); return iconKey; @@ -564,13 +475,4 @@ public boolean isDebug() { public String getASEVersion() { return ASE_VERSION; } - - public Scheduler getScheduler() { - return scheduler; - } - - public CoreProtectExtension getCoreProtectExtension() { - return coreProtectExtension; - } - } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java b/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java index 7192ff8e7..d35ecf62d 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java @@ -28,11 +28,14 @@ import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.Sound; import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; import org.bukkit.command.*; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; @@ -42,46 +45,42 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.scoreboard.Team; import org.bukkit.util.EulerAngle; +import org.jetbrains.annotations.NotNull; +import java.util.Arrays; import java.util.List; import java.util.Objects; -import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.AQUA; -import static net.kyori.adventure.text.format.NamedTextColor.YELLOW; - public class CommandEx implements CommandExecutor { - ArmorStandEditorPlugin plugin; - final Component listMode = text("/ase mode <" + Util.getEnumList(EditMode.class) + ">", YELLOW); - final Component listAxis = text("/ase axis <" + Util.getEnumList(Axis.class) + ">", YELLOW); - final Component listAdjustment = text("/ase adj <" + Util.getEnumList(AdjustmentMode.class) + ">", YELLOW); - final Component resetWithinRange = text("/ase resetWithinRange ", YELLOW); - final Component give = text("/ase give", YELLOW); - final Component listSlot = text("/ase slot <1-9>", YELLOW); - final Component help = text("/ase help or /ase ?", YELLOW); - final Component version = text("/ase version", YELLOW); - final Component update = text("/ase update", YELLOW); - final Component reload = text("/ase reload", YELLOW); - final Component givePlayerHead = text("/ase playerhead", YELLOW); - final Component getArmorStats = text("/ase stats", YELLOW); - Debug debug; + private final ArmorStandEditorPlugin plugin; + private final Component listMode = Component.text("/ase mode <" + Util.getEnumList(EditMode.class) + ">", NamedTextColor.YELLOW); + private final Component listAxis = Component.text("/ase axis <" + Util.getEnumList(Axis.class) + ">", NamedTextColor.YELLOW); + private final Component listAdjustment = Component.text("/ase adj <" + Util.getEnumList(AdjustmentMode.class) + ">", NamedTextColor.YELLOW); + private final Component resetWithinRange = Component.text("/ase resetWithinRange ", NamedTextColor.YELLOW); + private final Component give = Component.text("/ase give", NamedTextColor.YELLOW); + private final Component listSlot = Component.text("/ase slot <1-9>", NamedTextColor.YELLOW); + private final Component help = Component.text("/ase help or /ase ?", NamedTextColor.YELLOW); + private final Component version = Component.text("/ase version", NamedTextColor.YELLOW); + private final Component update = Component.text("/ase update", NamedTextColor.YELLOW); + private final Component reload = Component.text("/ase reload", NamedTextColor.YELLOW); + private final Component givePlayerHead = Component.text("/ase playerhead", NamedTextColor.YELLOW); + private final Component getArmorStats = Component.text("/ase stats", NamedTextColor.YELLOW); public CommandEx(ArmorStandEditorPlugin armorStandEditorPlugin) { this.plugin = armorStandEditorPlugin; - this.debug = plugin.debug; } @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String @NotNull[] args) { - if (sender instanceof ConsoleCommandSender) { //Fix to Support #267 - debug.log("Sender is CONSOLE!"); + if (!(sender instanceof Player player)) { //Fix to Support #267 + Debug.log("Sender is CONSOLE!"); if (args.length == 0) { sender.sendMessage(version); sender.sendMessage(help); sender.sendMessage(reload); - return true; } else { switch (args[0].toLowerCase()) { case "reload" -> commandReloadConsole(sender); @@ -89,19 +88,15 @@ public boolean onCommand(CommandSender sender, Command command, String label, St case "version" -> commandVersionConsole(sender); default -> sender.sendMessage(plugin.getLang().getMessage("noconsolecom", "warn")); } - return true; } - + return true; } - if (sender instanceof Player player && !getPermissionBasic(player)) { - debug.log("Sender is Player but asedit.basic is" + getPermissionBasic(player)); + if (!getPermissionBasic(player)) { + Debug.log("Sender is Player but asedit.basic is" + getPermissionBasic(player)); sender.sendMessage(plugin.getLang().getMessage("nopermoption", "warn", "basic")); - return true; } else { - Player player = (Player) sender; - - debug.log("Sender is Player and asedit.basic is " + getPermissionBasic(player)); + Debug.log("Sender is Player and asedit.basic is " + getPermissionBasic(player)); if (args.length == 0) { player.sendMessage(listMode); player.sendMessage(listAxis); @@ -143,14 +138,15 @@ public boolean onCommand(CommandSender sender, Command command, String label, St player.sendMessage(getArmorStats); } } - return true; } + return true; } // Implemented to fix: // https://github.com/Wolfieheart/ArmorStandEditor-Issues/issues/35 & // https://github.com/Wolfieheart/ArmorStandEditor-Issues/issues/30 - See Remarks OTHER + @SuppressWarnings("UnstableApiUsage") private void commandGive(Player player) { if (player.hasPermission("asedit.give")) { ItemStack stack = new ItemStack(plugin.getEditTool()); @@ -172,10 +168,15 @@ private void commandGive(Player player) { private void commandResetWithinRange(Player player, String[] args) { + if (args.length == 1) { + player.sendMessage(resetWithinRange); + return; + } + if (player.hasPermission("asedit.reset.withinRange")) { - debug.log(" Player '" + player.getName() + "' is resetting armor stands within range."); + Debug.log(" Player '" + player.getName() + "' is resetting armor stands within range."); double range = Double.parseDouble(args[1]); - debug.log(" Range Chosen: " + range); + Debug.log(" Range Chosen: " + range); if (range > plugin.getMaxResetRange()) { player.sendMessage(plugin.getLang().getMessage("resetwithinrangeexceed", "warn")); @@ -191,12 +192,11 @@ private void commandResetWithinRange(Player player, String[] args) { } private void commandGivePlayerHead(Player player) { - if (player.hasPermission("asedit.head") || plugin.getAllowedToRetrieveOwnPlayerHead()) { - debug.log("Creating a player head for the OfflinePlayer '" + player.getName() + "'"); - OfflinePlayer offlinePlayer = player.getPlayer(); + if (player.hasPermission("asedit.head") && plugin.getAllowedToRetrieveOwnPlayerHead()) { + Debug.log("Creating a player head for the Player '" + player.getName() + "'"); ItemStack item = new ItemStack(Material.PLAYER_HEAD, 1); SkullMeta meta = (SkullMeta) item.getItemMeta(); - meta.setOwningPlayer(offlinePlayer); + meta.setOwningPlayer(player); item.setItemMeta(meta); player.getInventory().addItem(item); player.sendMessage(plugin.getLang().getMessage("playerhead", "info")); @@ -216,7 +216,7 @@ private void commandSlot(Player player, String[] args) { try { byte slot = (byte) (Byte.parseByte(args[1]) - 0b1); if (slot >= 0 && slot < 9) { - debug.log("Player has chosen slot: " + slot); + Debug.log("Player has chosen slot: " + slot); plugin.editorManager.getPlayerEditor(player.getUniqueId()).setCopySlot(slot); } else { player.sendMessage(listSlot); @@ -229,7 +229,7 @@ private void commandSlot(Player player, String[] args) { } private void commandAdj(Player player, String[] args) { - if (args.length <= 1) { + if (args.length == 0) { player.sendMessage(plugin.getLang().getMessage("noadjcom", "warn")); player.sendMessage(listAdjustment); } @@ -246,7 +246,7 @@ private void commandAdj(Player player, String[] args) { } private void commandAxis(Player player, String[] args) { - if (args.length <= 1) { + if (args.length == 0) { player.sendMessage(plugin.getLang().getMessage("noaxiscom", "warn")); player.sendMessage(listAxis); } @@ -254,7 +254,7 @@ private void commandAxis(Player player, String[] args) { if (args.length > 1) { for (Axis axis : Axis.values()) { if (axis.toString().toLowerCase().contentEquals(args[1].toLowerCase())) { - debug.log("Player '" + player.getName() + "' sets the axis to " + axis); + Debug.log("Player '" + player.getName() + "' sets the axis to " + axis); plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAxis(axis); return; } @@ -264,7 +264,7 @@ private void commandAxis(Player player, String[] args) { } private void commandMode(Player player, String[] args) { - if (args.length <= 1) { + if (args.length == 1) { player.sendMessage(plugin.getLang().getMessage("nomodecom", "warn")); player.sendMessage(listMode); return; // early return lets us drop the second `if` entirely @@ -276,7 +276,7 @@ private void commandMode(Player player, String[] args) { if (!isVisibilityAllowed(player, args[1])) return; plugin.editorManager.getPlayerEditor(player.getUniqueId()).setMode(matched); - debug.log("Player '" + player.getName() + "' chose the mode: " + matched); + Debug.log("Player '" + player.getName() + "' chose the mode: " + matched); } private void commandHelp(Player player) { @@ -302,45 +302,45 @@ private void commandHelpConsole(CommandSender sender) { private void commandUpdate(Player player) { if (!(checkPermission(player, "update", true))) return; - debug.log("Current ArmorStandEditor Version is: " + ArmorStandEditorPlugin.ASE_VERSION); + Debug.log("Current ArmorStandEditor Version is: " + ArmorStandEditorPlugin.ASE_VERSION); if (plugin.getRunTheUpdateChecker()) { - debug.log("Plugin is on Server: Paper/Spigot or a fork thereof."); + Debug.log("Plugin is on Server: Paper/Spigot or a fork thereof."); new UpdateChecker(plugin).checkForUpdatesAndNotify(player); } else { - player.sendMessage(text("[ArmorStandEditor] Update Checker is not enabled on this server.", YELLOW)); + player.sendMessage(Component.text("[ArmorStandEditor] Update Checker is not enabled on this server.", NamedTextColor.YELLOW)); } } private void commandVersion(Player player) { - debug.log("Player '" + player.getName() + "' permission check for asedit.update: " + getPermissionUpdate(player)); - if (!(getPermissionUpdate(player))) return; + Debug.log("Player '" + player.getName() + "' permission check for asedit.update: " + getPermissionUpdate(player)); + if (!getPermissionUpdate(player)) return; String verString = plugin.getASEVersion(); - player.sendMessage(text("[ArmorStandEditor] Version: " + verString, YELLOW)); + player.sendMessage(Component.text("[ArmorStandEditor] Version: " + verString, NamedTextColor.YELLOW)); } private void commandVersionConsole(CommandSender sender) { String verString = plugin.getASEVersion(); - sender.sendMessage(text("[ArmorStandEditor] Version: " + verString, YELLOW)); + sender.sendMessage(Component.text("[ArmorStandEditor] Version: " + verString, NamedTextColor.YELLOW)); } private void commandReload(Player player) { - debug.log("Player '" + player.getName() + "' permission check for asedit.reload: " + getPermissionReload(player)); + Debug.log("Player '" + player.getName() + "' permission check for asedit.reload: " + getPermissionReload(player)); if (!(getPermissionReload(player))) return; - debug.log("Performing reload of config.yml"); + Debug.log("Performing reload of config.yml"); plugin.performReload(); player.sendMessage(plugin.getLang().getMessage("reloaded", "")); } private void commandReloadConsole(CommandSender sender) { - debug.log("Console has decided to reload the plugin...."); + Debug.log("Console has decided to reload the plugin...."); plugin.performReload(); sender.sendMessage(plugin.getLang().getMessage("reloaded", "info")); } private void commandStats(Player player) { - debug.log("Player '" + player.getName() + "' permission check for asedit.stats: " + getPermissionStats(player)); + Debug.log("Player '" + player.getName() + "' permission check for asedit.stats: " + getPermissionStats(player)); if (getPermissionStats(player)) { for (Entity e : player.getNearbyEntities(1, 1, 1)) { @@ -380,32 +380,23 @@ private boolean getPermissionReload(Player player) { return checkPermission(player, "reload", false); } - private boolean getPermissionPlayerHead(Player player) { - return checkPermission(player, "head", false); - } - private boolean getPermissionStats(Player player) { return checkPermission(player, "stats", false); } - private boolean getPermissionResetWithinRange(Player player) { - return checkPermission(player, "reset.withinRange", false); - } - - /* * Helper Functions for Stats */ private Component label(String label, Object value) { - return text(label + ": ", YELLOW) - .append(text(String.valueOf(value), AQUA)); + return Component.text(label + ": ", NamedTextColor.YELLOW) + .append(Component.text(String.valueOf(value), NamedTextColor.AQUA)); } private void sendArmorStandStats(Player player, ArmorStand as) { PoseData pose = PoseData.from(as); Location loc = as.getLocation(); - player.sendMessage(text("----------- Armor Stand Statistics -----------", YELLOW)); + player.sendMessage(Component.text("----------- Armor Stand Statistics -----------", NamedTextColor.YELLOW)); player.sendMessage(plugin.getLang().getMessage("stats")); sendPose(player, "Head", pose.head()); @@ -420,17 +411,17 @@ private void sendArmorStandStats(Player player, ArmorStand as) { sendPhysics(player, as); sendSizeInfo(player, as); - player.sendMessage(text("----------------------------------------------", YELLOW)); + player.sendMessage(Component.text("----------------------------------------------", NamedTextColor.YELLOW)); } private void sendPose(Player player, String name, EulerAngle angle) { player.sendMessage( - text(name + ": ", YELLOW) - .append(text( + Component.text(name + ": ", NamedTextColor.YELLOW) + .append(Component.text( round(angle.getX()) + " / " + round(angle.getY()) + " / " + round(angle.getZ()), - AQUA)) + NamedTextColor.AQUA)) ); } @@ -438,32 +429,26 @@ private double round(double radians) { return Math.rint(Math.toDegrees(radians)); } - private void sendSizeInfo(Player player, ArmorStand as) { + TextComponent.Builder builder = Component.text(); + if (isScaleSupported()) { - double scale = Objects.requireNonNull(as.getAttribute(Attribute.SCALE)).getBaseValue(); + AttributeInstance attributeInstance = as.getAttribute(Attribute.SCALE); + double scale = attributeInstance != null ? attributeInstance.getBaseValue() : 0; player.sendMessage( - text("Size: ", YELLOW) - .append(text(scale + "/" + plugin.getMaxScaleValue(), AQUA)) - .append(text(". ", YELLOW)) - .append(label("Is Glowing", as.isGlowing())) - .append(text(". ", YELLOW)) - .append(label("Is Locked", isLocked(as))) - .append(text(". ", YELLOW)) - .append(label("Is InUse", isInUse(as))) - ); - return; + Component.text("Size: ", NamedTextColor.YELLOW) + .append(Component.text(scale + "/" + plugin.getMaxScaleValue(), NamedTextColor.AQUA)) + .append(Component.text(". ", NamedTextColor.YELLOW))); + } else { + builder.append(label("Is Small", as.isSmall())); } - player.sendMessage( - label("Is Small", as.isSmall()) - .append(text(". ", YELLOW)) - .append(label("Is Glowing", as.isGlowing())) - .append(text(". ", YELLOW)) - .append(label("Is Locked", isLocked(as))) - .append(text(". ", YELLOW)) - .append(label("Is InUse", isInUse(as))) - ); + builder.append(label("Is Glowing", as.isGlowing())) + .append(Component.text(". ", NamedTextColor.YELLOW)) + .append(label("Is Locked", SharedUtil.isLocked(as))) + .append(Component.text(". ", NamedTextColor.YELLOW)) + .append(label("Is InUse", SharedUtil.isInUse(as.getUniqueId()))); + player.sendMessage(builder.build()); } private boolean isScaleSupported() { @@ -471,35 +456,22 @@ private boolean isScaleSupported() { .isNewerThanOrEquals(MinecraftVersion.MINECRAFT_1_20_4); } - private boolean isLocked(ArmorStand as) { - return plugin.scoreboard - .getTeam(plugin.lockedTeam) - .hasEntry(as.getUniqueId().toString()); - } - - private boolean isInUse(ArmorStand as) { - return plugin.scoreboard - .getTeam(plugin.inUseTeam) - .hasEntry(as.getUniqueId().toString()); - } - private void sendCoordinates(Player player, Location loc) { - player.sendMessage( - text("Coordinates: ", YELLOW) - .append(text( + player.sendMessage(Component.text("Coordinates: ", NamedTextColor.YELLOW) + .append(Component.text( "X: " + loc.getX() + " / Y: " + loc.getY() + " / Z: " + loc.getZ(), - AQUA)) + NamedTextColor.AQUA)) ); } private void sendVisibility(Player player, ArmorStand as) { player.sendMessage( label("Is Visible", as.isVisible()) - .append(text(". ", YELLOW)) + .append(Component.text(". ", NamedTextColor.YELLOW)) .append(label("Arms Visible", as.hasArms())) - .append(text(". ", YELLOW)) + .append(Component.text(". ", NamedTextColor.YELLOW)) .append(label("Base Plate Visible", as.hasBasePlate())) ); } @@ -507,18 +479,18 @@ private void sendVisibility(Player player, ArmorStand as) { private void sendPhysics(Player player, ArmorStand as) { player.sendMessage( label("Is Vulnerable", as.isInvulnerable()) - .append(text(". ", YELLOW)) + .append(Component.text(". ", NamedTextColor.YELLOW)) .append(label("Affected by Gravity", as.hasGravity())) ); } private record PoseData( - EulerAngle head, - EulerAngle body, - EulerAngle rightArm, - EulerAngle leftArm, - EulerAngle rightLeg, - EulerAngle leftLeg + EulerAngle head, + EulerAngle body, + EulerAngle rightArm, + EulerAngle leftArm, + EulerAngle rightLeg, + EulerAngle leftLeg ) { static PoseData from(ArmorStand as) { return new PoseData( @@ -532,8 +504,6 @@ static PoseData from(ArmorStand as) { } } - - /** * Returns the EditMode whose name matches the given argument (case-insensitive), * or null if none matches. @@ -551,9 +521,9 @@ private EditMode findMatchingMode(String arg) { */ private boolean isVisibilityAllowed(Player player, String arg) { if (arg.equals("invisible")) - return checkPermission(player, "togglearmorstandvisibility", true) || plugin.getArmorStandVisibility(); + return checkPermission(player, "togglearmorstandvisibility", true) && plugin.getArmorStandVisibility(); if (arg.equals("itemframe")) - return checkPermission(player, "toggleitemframevisibility", true) || plugin.getItemFrameVisibility(); + return checkPermission(player, "toggleitemframevisibility", true) && plugin.getItemFrameVisibility(); return true; } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/Debug.java b/src/main/java/io/github/rypofalem/armorstandeditor/Debug.java index 285d4fe2a..288f421d5 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/Debug.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/Debug.java @@ -4,13 +4,9 @@ import java.util.logging.Level; public class Debug { - private final ArmorStandEditorPlugin plugin; + private static final ArmorStandEditorPlugin plugin = ArmorStandEditorPlugin.instance(); - public Debug(ArmorStandEditorPlugin plugin) { - this.plugin = plugin; - } - - public void log(String msg) { + public static void log(String msg) { if (plugin.isDebug()) { plugin.getLogger().log(Level.INFO, "[ArmorStandEditor-Debug] {0}", msg); } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditor.java b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditor.java index b84d6d8ff..ee79d343b 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditor.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditor.java @@ -32,7 +32,6 @@ import io.github.rypofalem.armorstandeditor.utils.Util; import io.github.rypofalem.armorstandeditor.utils.VersionUtil; -import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; import org.bukkit.GameMode; @@ -47,7 +46,6 @@ import org.bukkit.inventory.EquipmentSlot; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.bukkit.scoreboard.Team; import org.bukkit.util.EulerAngle; import java.util.ArrayList; @@ -55,39 +53,34 @@ public class PlayerEditor { public ArmorStandEditorPlugin plugin; - private Scheduler scheduler; + private final Scheduler scheduler; - private Debug debug; - Team team; - private UUID uuid; + private final UUID uuid; UUID armorStandInUseId; - UUID armorStandID; - EditMode eMode; - AdjustmentMode adjMode; - CopySlots copySlots; - Axis axis; + private EditMode eMode; + private AdjustmentMode adjMode; + private final CopySlots copySlots; + private Axis axis; double eulerAngleChange; double degreeAngleChange; double movChange; - Menu chestMenu; - ArmorStand target; - ArrayList targetList = null; - ArrayList armorStandInRange = null; + private final Menu chestMenu; + private ArmorStand target; + private ArrayList targetList = null; //NEW: ItemFrame Stuff - ItemFrame frameTarget; - ArrayList frameTargetList = null; + private ItemFrame frameTarget; + private ArrayList frameTargetList = null; int targetIndex = 0; int frameTargetIndex = 0; EquipmentMenu equipMenu; PresetArmorPosesMenu presetPoseMenu; SizeMenu sizeModificationMenu; - long lastCancelled = 0; + private long lastCancelled = 0; public PlayerEditor(UUID uuid, ArmorStandEditorPlugin plugin) { this.uuid = uuid; this.plugin = plugin; - this.debug = plugin.debug; this.scheduler = plugin.getScheduler(); eMode = EditMode.NONE; @@ -102,13 +95,13 @@ public PlayerEditor(UUID uuid, ArmorStandEditorPlugin plugin) { public void setMode(EditMode editMode) { this.eMode = editMode; - debug.log("EditMode is: " + editMode.toString().toLowerCase()); + Debug.log("EditMode is: " + editMode.toString().toLowerCase()); sendMessage("setmode", editMode.toString().toLowerCase()); } public void setAxis(Axis axis) { this.axis = axis; - debug.log("Axis is: " + axis.toString().toLowerCase()); + Debug.log("Axis is: " + axis.toString().toLowerCase()); sendMessage("setaxis", axis.toString().toLowerCase()); } @@ -122,13 +115,13 @@ public void setAdjMode(AdjustmentMode adjMode) { movChange = getManager().fineMov; } degreeAngleChange = eulerAngleChange / Math.PI * 180; - debug.log("AdjMode is: " + adjMode.toString().toLowerCase()); + Debug.log("AdjMode is: " + adjMode.toString().toLowerCase()); sendMessage("setadj", adjMode.toString().toLowerCase()); } public void setCopySlot(byte slot) { copySlots.changeSlots(slot); - debug.log("Copy Slot set to: " + (slot + 1)); + Debug.log("Copy Slot set to: " + (slot + 1)); sendMessage("setslot", String.valueOf((slot + 1))); } @@ -206,11 +199,12 @@ public void editArmorStand(ArmorStand armorStand) { break; } - } else return; + } } public void editItemFrame(ItemFrame itemFrame) { - if (getPlayer().hasPermission("asedit.toggleitemframevisibility") || plugin.invisibleItemFrames) { + if (getPlayer().hasPermission("asedit.toggleitemframevisibility") && plugin.invisibleItemFrames) { + itemFrame = attemptTarget(itemFrame); switch (eMode) { case ITEMFRAME: toggleItemFrameVisible(itemFrame); @@ -223,45 +217,31 @@ public void editItemFrame(ItemFrame itemFrame) { sendMessage("nomodeif", null); break; } - } else return; + } } private void openEquipment(ArmorStand armorStand) { if (!getPlayer().hasPermission("asedit.equipment")) return; armorStandInUseId = armorStand.getUniqueId(); - // Dont allow Editing the ArmorStand if the Stand is on the AS-InUse Team - // Means No 2 Players can edit the Equipment at the same time - if (!plugin.hasFolia) { - team = plugin.scoreboard.getTeam(plugin.inUseTeam); - - debug.log("Is ArmorStand currently in use by another player?: " + team.hasEntry(armorStandInUseId.toString())); - - if (!team.hasEntry(armorStandInUseId.toString())) { - debug.log("ArmorStand Not on a Team and Player '" + getPlayer().displayName() + "' has triggered to Open the Equipment Menu, Adding to In Use Team"); - team.addEntry(armorStandInUseId.toString()); - getPlayer().closeInventory(); - equipMenu = new EquipmentMenu(this, armorStand); - equipMenu.openMenu(); - } else { - sendMessage("asinuse", "warn"); - } - } else { - if (!PlayerEditorManager.foliaInUse.contains(armorStandInUseId)) { - debug.log("ArmorStand Not locked and Player '" + getPlayer().displayName() + "' has triggered to Open the Equipment Menu. Folia."); - getPlayer().closeInventory(); - PlayerEditorManager.foliaInUse.add(armorStandInUseId); - equipMenu = new EquipmentMenu(this, armorStand); - equipMenu.openMenu(); - } else { - sendMessage("asinuse", "warn"); - } + if (SharedUtil.isInUse(armorStandInUseId)) { + sendMessage("asinuse", "warn"); + return; } + if (SharedUtil.isLocked(armorStand)) { + sendMessage("target", null); // Armorstand locked + return; + } + Debug.log("ArmorStand Not locked and Player '" + getPlayer().displayName() + "' has triggered to Open the Equipment Menu."); + + getPlayer().closeInventory(); + equipMenu = new EquipmentMenu(this, armorStand); + equipMenu.openMenu(); } private void choosePreset(ArmorStand armorStand) { if (!getPlayer().hasPermission("asedit.basic")) return; - debug.log("Player '" + getPlayer().displayName() + "' has triggered the Preset Poses Menu"); + Debug.log("Player '" + getPlayer().displayName() + "' has triggered the Preset Poses Menu"); getPlayer().closeInventory(); presetPoseMenu = new PresetArmorPosesMenu(this, armorStand); presetPoseMenu.openMenu(); @@ -274,14 +254,13 @@ private void chooseSize(ArmorStand armorStand) { } else { if (VersionUtil.fromString(plugin.getNmsVersion()).isNewerThanOrEquals(MinecraftVersion.MINECRAFT_1_20_4)) { //NOTE: New Sizing Menu ONLY WORKS IN 1.21.3 and HIGHER - debug.log("Player '" + getPlayer().displayName() + "' has triggered the AS Attribute Size Menu"); + Debug.log("Player '" + getPlayer().displayName() + "' has triggered the AS Attribute Size Menu"); getPlayer().closeInventory(); sizeModificationMenu = new SizeMenu(this, armorStand); sizeModificationMenu.openMenu(); } else { armorStand.setSmall(!armorStand.isSmall()); } - } } @@ -334,7 +313,7 @@ private void move(ArmorStand armorStand) { loc.add(0, 0, movChange); break; } - debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", near player " + getPlayer().displayName()); + Debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", near player " + getPlayer().displayName()); scheduler.teleport(armorStand, loc); } @@ -352,7 +331,7 @@ private void reverseMove(ArmorStand armorStand) { loc.subtract(0, 0, movChange); break; } - debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", near player " + getPlayer().displayName()); + Debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", near player " + getPlayer().displayName()); scheduler.teleport(armorStand, loc); } @@ -361,7 +340,7 @@ private void rotate(ArmorStand armorStand) { Location loc = armorStand.getLocation(); float yaw = loc.getYaw(); loc.setYaw((yaw + 180 + (float) degreeAngleChange) % 360 - 180); - debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", near player " + getPlayer().displayName()); + Debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", near player " + getPlayer().displayName()); scheduler.teleport(armorStand, loc); } @@ -370,14 +349,14 @@ private void reverseRotate(ArmorStand armorStand) { Location loc = armorStand.getLocation(); float yaw = loc.getYaw(); loc.setYaw((yaw + 180 - (float) degreeAngleChange) % 360 - 180); - debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", near player " + getPlayer().displayName()); + Debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", near player " + getPlayer().displayName()); scheduler.teleport(armorStand, loc); } private void copy(ArmorStand armorStand) { if (getPlayer().hasPermission("asedit.copy")) { copySlots.copyDataToSlot(armorStand); - debug.log("ArmorStand Items, Stats and Attributes has been copied to " + (copySlots.currentSlot + 1) + ", near player " + getPlayer().displayName()); + Debug.log("ArmorStand Items, Stats and Attributes has been copied to " + (copySlots.currentSlot + 1) + ", near player " + getPlayer().displayName()); sendMessage("copied", "" + (copySlots.currentSlot + 1)); setMode(EditMode.PASTE); } else { @@ -389,7 +368,7 @@ private void copy(ArmorStand armorStand) { private void paste(ArmorStand armorStand) { if (getPlayer().hasPermission("asedit.paste")) { ArmorStandData data = copySlots.getDataToPaste(); - debug.log("Pasting ArmorStand Attributes and Settings from: " + (copySlots.currentSlot + 1) + ", near player " + getPlayer().displayName()); + Debug.log("Pasting ArmorStand Attributes and Settings from: " + (copySlots.currentSlot + 1) + ", near player " + getPlayer().displayName()); if (data == null) return; armorStand.setHeadPose(data.headPos); armorStand.setBodyPose(data.bodyPos); @@ -427,7 +406,7 @@ private void paste(ArmorStand armorStand) { private void resetPosition(ArmorStand armorStand) { if (getPlayer().hasPermission("asedit.reset")) { - debug.log("Resetting ArmorStand near the Player " + getPlayer().displayName()); + Debug.log("Resetting ArmorStand near the Player " + getPlayer().displayName()); armorStand.setHeadPose(new EulerAngle(0, 0, 0)); armorStand.setBodyPose(new EulerAngle(0, 0, 0)); armorStand.setLeftArmPose(new EulerAngle(0, 0, 0)); @@ -443,46 +422,37 @@ private void toggleDisableSlots(ArmorStand armorStand) { if (!getPlayer().hasPermission("asedit.disableSlots")) { sendMessage("nopermoption", "warn", "disableslots"); } else { - debug.log("Remove DisabledSlots on ArmorStand near the Player " + getPlayer().displayName()); + Debug.log("Remove DisabledSlots on ArmorStand near the Player " + getPlayer().displayName()); if (armorStand.hasEquipmentLock(EquipmentSlot.HAND, ArmorStand.LockType.REMOVING_OR_CHANGING)) { //Adds a lock to every slot or removes it - team = plugin.getHasFolia() ? null : plugin.scoreboard.getTeam(plugin.lockedTeam); - armorStandID = armorStand.getUniqueId(); + armorStandInUseId = armorStand.getUniqueId(); for (final EquipmentSlot slot : EquipmentSlot.values()) { // UNLOCKED armorStand.removeEquipmentLock(slot, ArmorStand.LockType.REMOVING_OR_CHANGING); armorStand.removeEquipmentLock(slot, ArmorStand.LockType.ADDING); } - getPlayer().playSound(getPlayer().getLocation(), Sound.ENTITY_ITEM_BREAK, SoundCategory.PLAYERS, 1.0f, 1.0f); - - if (team != null) { - team.removeEntry(armorStandID.toString()); - armorStand.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 50, 1, false, false)); //300 Ticks = 15 seconds - } - + SharedUtil.setLocked(armorStand, false); + getPlayer().playSound(getPlayer().getLocation(), Sound.ENTITY_ITEM_BREAK, SoundCategory.PLAYERS, 1.0f, 1.0f); + armorStand.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 50, 1, false, false)); //300 Ticks = 15 seconds } else { - debug.log("Adding DisabledSlots on ArmorStand near the Player " + getPlayer().displayName()); + Debug.log("Adding DisabledSlots on ArmorStand near the Player " + getPlayer().displayName()); for (final EquipmentSlot slot : EquipmentSlot.values()) { //LOCKED armorStand.addEquipmentLock(slot, ArmorStand.LockType.REMOVING_OR_CHANGING); armorStand.addEquipmentLock(slot, ArmorStand.LockType.ADDING); } + SharedUtil.setLocked(armorStand, true); getPlayer().playSound(getPlayer().getLocation(), Sound.ITEM_ARMOR_EQUIP_WOLF, SoundCategory.PLAYERS, 1.0f, 1.0f); - - if (team != null) { - team.addEntry(armorStandID.toString()); - armorStand.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 50, 1, false, false)); //300 Ticks = 15 seconds - } + armorStand.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 50, 1, false, false)); //300 Ticks = 15 seconds } sendMessage("disabledslots", null); } - } private void toggleInvulnerability(ArmorStand armorStand) { //See NewFeature-Request #256 for more info if (getPlayer().hasPermission("asedit.toggleInvulnerability")) { - debug.log("Making an ArmorStand vulnerable/invulnerable (set armorStand.isInvulnerable() = '" + !armorStand.isInvulnerable() + "') near player: " + getPlayer().displayName()); + Debug.log("Making an ArmorStand vulnerable/invulnerable (set armorStand.isInvulnerable() = '" + !armorStand.isInvulnerable() + "') near player: " + getPlayer().displayName()); armorStand.setInvulnerable(!armorStand.isInvulnerable()); sendMessage("toggleinvulnerability", String.valueOf(armorStand.isInvulnerable())); } else { @@ -493,7 +463,7 @@ private void toggleInvulnerability(ArmorStand armorStand) { //See NewFeature-Req private void toggleGravity(ArmorStand armorStand) { if (getPlayer().hasPermission("asedit.togglegravity")) { - debug.log("Toggling the Gravity of an ArmorStand near player: " + getPlayer().displayName()); + Debug.log("Toggling the Gravity of an ArmorStand near player: " + getPlayer().displayName()); armorStand.setGravity(!armorStand.hasGravity()); sendMessage("setgravity", String.valueOf(armorStand.hasGravity()));//Fix for Wolfst0rm/ArmorStandEditor-Issues#6: Translation of On/Off Keys are broken } else { @@ -501,19 +471,18 @@ private void toggleGravity(ArmorStand armorStand) { } } - void togglePlate(ArmorStand armorStand) { + private void togglePlate(ArmorStand armorStand) { if (getPlayer().hasPermission("asedit.togglebaseplate")) { - debug.log("Toggling the Baseplate of an ArmorStand near player: " + getPlayer().displayName()); + Debug.log("Toggling the Baseplate of an ArmorStand near player: " + getPlayer().displayName()); armorStand.setBasePlate(!armorStand.hasBasePlate()); } else { sendMessage("nopermoption", "warn", "baseplate"); } - } - void toggleGlowing(ArmorStand armorStand) { + private void toggleGlowing(ArmorStand armorStand) { if (getPlayer().hasPermission("asedit.togglearmorstandglow")) { - debug.log("Toggling the Glowing Ability of an ArmorStand near player: " + getPlayer().displayName()); + Debug.log("Toggling the Glowing Ability of an ArmorStand near player: " + getPlayer().displayName()); //Will only make it glow white - Not something we can do like with Locking. Do not request this! armorStand.setGlowing(!armorStand.isGlowing()); } else { @@ -521,27 +490,27 @@ void toggleGlowing(ArmorStand armorStand) { } } - void toggleArms(ArmorStand armorStand) { + private void toggleArms(ArmorStand armorStand) { if (getPlayer().hasPermission("asedit.togglearms")) { - debug.log("Toggling the Showing of Arms of an ArmorStand near player: " + getPlayer().displayName()); + Debug.log("Toggling the Showing of Arms of an ArmorStand near player: " + getPlayer().displayName()); armorStand.setArms(!armorStand.hasArms()); } else { sendMessage("nopermoption", "warn", "showarms"); } } - void toggleVisible(ArmorStand armorStand) { - if (getPlayer().hasPermission("asedit.togglearmorstandvisibility") || plugin.getArmorStandVisibility()) { - debug.log("Toggling the Visiblity of an ArmorStand near player: " + getPlayer().displayName()); + private void toggleVisible(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.togglearmorstandvisibility") && plugin.getArmorStandVisibility()) { + Debug.log("Toggling the Visiblity of an ArmorStand near player: " + getPlayer().displayName()); armorStand.setVisible(!armorStand.isVisible()); } else { //Throw No Permission Message sendMessage("nopermoption", "warn", "armorstandvisibility"); } } - void toggleItemFrameVisible(ItemFrame itemFrame) { - if (getPlayer().hasPermission("asedit.toggleitemframevisibility") || plugin.invisibleItemFrames) { //Option to use perms or Config - debug.log("Toggling the Visibility of an ItemFrame near player: " + getPlayer().displayName()); + private void toggleItemFrameVisible(ItemFrame itemFrame) { + if (getPlayer().hasPermission("asedit.toggleitemframevisibility") && plugin.invisibleItemFrames) { //Option to use perms or Config + Debug.log("Toggling the Visibility of an ItemFrame near player: " + getPlayer().displayName()); itemFrame.setVisible(!itemFrame.isVisible()); } else { sendMessage("nopermoption", "warn", "itemframevisibility"); @@ -554,7 +523,7 @@ void resetArmorStandsWithinRange(Location playerLocation, double range) { return; } - debug.log("Resetting ArmorStands within range of " + range + " near player: " + getPlayer().displayName()); + Debug.log("Resetting ArmorStands within range of " + range + " near player: " + getPlayer().displayName()); int resetCount = 0; for (Entity entity : playerLocation.getWorld().getNearbyEntities(playerLocation, range, range, range)) { @@ -585,10 +554,9 @@ void resetArmorStandsWithinRange(Location playerLocation, double range) { } } - debug.log("Reset " + resetCount + " armor stands within range"); + Debug.log("Reset " + resetCount + " armor stands within range"); } - void cycleAxis(int i) { int index = axis.ordinal(); index += i; @@ -633,7 +601,6 @@ private EulerAngle subEulerAngle(EulerAngle angle) { return angle; } - public void setTarget(ArrayList armorStands) { if (armorStands == null || armorStands.isEmpty()) { target = null; @@ -646,9 +613,10 @@ public void setTarget(ArrayList armorStands) { sendMessage("target", null); } else { boolean same = targetList.size() == armorStands.size(); - if (same) for (ArmorStand as : armorStands) { - same = targetList.contains(as); - if (!same) break; + if (same) + for (ArmorStand as : armorStands) { + same = targetList.contains(as); + if (!same) break; } if (same) { @@ -667,23 +635,23 @@ public void setTarget(ArrayList armorStands) { } } - public void setFrameTarget(ArrayList itemFrames) { if (itemFrames == null || itemFrames.isEmpty()) { frameTarget = null; frameTargetList = null; sendMessage("notarget", "itemframe"); } else { - if (frameTargetList == null) { frameTargetList = itemFrames; frameTargetIndex = 0; sendMessage("frametarget", null); } else { boolean same = frameTargetList.size() == itemFrames.size(); - if (same) for (final ItemFrame itemf : itemFrames) { - same = frameTargetList.contains(itemf); - if (!same) break; + if (same) { + for (final ItemFrame frame : itemFrames) { + same = frameTargetList.contains(frame); + if (!same) break; + } } if (same) { @@ -699,8 +667,7 @@ public void setFrameTarget(ArrayList itemFrames) { } } - - ArmorStand attemptTarget(ArmorStand armorStand) { + private ArmorStand attemptTarget(ArmorStand armorStand) { if (target == null || !target.isValid() || target.getWorld() != getPlayer().getWorld() @@ -710,15 +677,26 @@ ArmorStand attemptTarget(ArmorStand armorStand) { return armorStand; } + private ItemFrame attemptTarget(ItemFrame itemFrame) { + if (frameTarget == null + || !frameTarget.isValid() + || frameTarget.getWorld() != getPlayer().getWorld() + || frameTarget.getLocation().distanceSquared(getPlayer().getLocation()) > 100) + return itemFrame; + itemFrame = frameTarget; + return itemFrame; + } + void sendMessage(String path, String format, String option) { Component message = plugin.getLang().getMessage(path, format, option); Player player = plugin.getServer().getPlayer(getUUID()); + if (player == null) return; if (plugin.sendToActionBar) { - if (ArmorStandEditorPlugin.instance().getHasPaper() || ArmorStandEditorPlugin.instance().getHasFolia()) { //Paper and Spigot having the same Interaction for sendToActionBar - Audience.audience(player).sendActionBar(message); + if (plugin.getHasPaper() || plugin.getHasFolia()) { //Paper and Spigot having the same Interaction for sendToActionBar + player.sendActionBar(message); } } else { - Audience.audience(player).sendMessage(message); + player.sendMessage(message); } } @@ -739,10 +717,6 @@ public Player getPlayer() { return plugin.getServer().getPlayer(getUUID()); } - public Scheduler getScheduler() { - return scheduler; - } - public UUID getUUID() { return uuid; } @@ -769,5 +743,4 @@ public void run() { chestMenu.openMenu(); } } - } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java index 6a6a5150f..1aa5f5499 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java @@ -24,9 +24,11 @@ import io.github.rypofalem.armorstandeditor.utils.Util; import io.papermc.lib.PaperLib; +import lombok.Getter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; @@ -36,7 +38,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityPlaceEvent; import org.bukkit.event.inventory.InventoryClickEvent; @@ -47,58 +48,43 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; -import org.bukkit.scoreboard.Team; import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Set; import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -import static net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacy; -import static net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText; //Manages PlayerEditors and Player Events related to editing armorstands public class PlayerEditorManager implements Listener { + private final ArmorStandEditorPlugin plugin; + private final HashMap players; + private final Scheduler scheduler; - private Debug debug; - private ArmorStandEditorPlugin plugin; - private HashMap players; - private Scheduler scheduler; - + @Getter private ASEHolder menuHolder = new ASEHolder(); //Inventory holder that owns the main ase menu inventories for the plugin + @Getter private ASEHolder equipmentHolder = new ASEHolder(); //Inventory holder that owns the equipment menu + @Getter private ASEHolder presetHolder = new ASEHolder(); //Inventory Holder that owns the PresetArmorStand Post Menu + @Getter private ASEHolder sizeMenuHolder = new ASEHolder(); //Inventory Holder that owns the PresetArmorStand Post Menu - double coarseAdj; double fineAdj; double coarseMov; double fineMov; - private boolean ignoreNextInteract = false; - private TickCounter counter; - private Integer noSize = 0; - Team team; - static final Set foliaInUse = ConcurrentHashMap.newKeySet(); + private final TickCounter counter; // Instantiate protections used to determine whether a player may edit an armor stand or item frame private final List protections = List.of( - new GriefDefenderProtection(), - new LandsProtection(), - new PlotSquaredProtection(), - new SkyblockProtection(), new TownyProtection(), - new WorldGuardProtection(), - new itemAdderProtection(), - new BoltProtection(), - new BentoBoxProtection()); + new WorldGuardProtection() + ); PlayerEditorManager(ArmorStandEditorPlugin plugin) { this.plugin = plugin; - this.debug = plugin.debug; this.scheduler = plugin.getScheduler(); players = new HashMap<>(); @@ -111,14 +97,15 @@ public class PlayerEditorManager implements Listener { } @EventHandler(priority = EventPriority.LOWEST) - void onArmorStandSpawn(EntityPlaceEvent event) { + public void onArmorStandSpawn(EntityPlaceEvent event) { if (!(event.getEntity() instanceof ArmorStand armorStand)) return; - debug.log("Entity being spawned is an ArmorStand"); + Debug.log("Entity being spawned is an ArmorStand"); Player player = event.getPlayer(); + if (player == null) return; Location location = player.getLocation(); - debug.log("Player " + player.getName() + Debug.log("Player " + player.getName() + " is placing an ArmorStand at (approx) X: " + Math.round(location.getX()) + ", Y: " + Math.round(location.getY()) + ", Z: " + Math.round(location.getZ()) @@ -128,38 +115,40 @@ void onArmorStandSpawn(EntityPlaceEvent event) { } @EventHandler(priority = EventPriority.LOWEST) - void onArmorStandDamage(EntityDamageByEntityEvent event) { - if (!(event.getDamager() instanceof Player)) return; - Player player = (Player) event.getDamager(); + public void onArmorStandDamage(EntityDamageByEntityEvent event) { + if (!(event.getDamager() instanceof Player player)) return; if (!plugin.isEditTool(player.getInventory().getItemInMainHand())) return; if (!((event.getEntity() instanceof ArmorStand) || event.getEntity() instanceof ItemFrame)) { event.setCancelled(true); - debug.log("Open Menu Called for Player: " + player.getName()); + Debug.log("Open Menu Called for Player: " + player.getName()); getPlayerEditor(player.getUniqueId()).openMenu(); return; } if (event.getEntity() instanceof ArmorStand armorStand) { - debug.log("Player '" + player.getName() + "' has left clicked the ArmorStand"); + Debug.log("Player '" + player.getName() + "' has left clicked the ArmorStand"); getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); event.setCancelled(true); - if (canEdit(player, armorStand)) applyLeftTool(player, armorStand); + if (canEdit(player, armorStand)) { + applyLeftTool(player, armorStand); + } } else if (event.getEntity() instanceof ItemFrame itemf) { - debug.log(" Player '" + player.getName() + "' has right clicked on an ItemFrame"); + Debug.log(" Player '" + player.getName() + "' has right clicked on an ItemFrame"); getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); event.setCancelled(true); - if (canEdit(player, itemf)) applyLeftTool(player, itemf); + if (canEdit(player, itemf)) { + applyLeftTool(player, itemf); + } } } @EventHandler(priority = EventPriority.LOWEST) - void onArmorStandInteract(PlayerInteractAtEntityEvent event) { - if (ignoreNextInteract) return; + public void onArmorStandInteract(PlayerInteractAtEntityEvent event) { if (event.getHand() != EquipmentSlot.HAND) return; Player player = event.getPlayer(); if (!((event.getRightClicked() instanceof ArmorStand) || event.getRightClicked() instanceof ItemFrame)) return; if (event.getRightClicked() instanceof ArmorStand as) { - debug.log("Player '" + player.getName() + "' has right clicked on an ArmorStand"); + Debug.log("Player '" + player.getName() + "' has right clicked on an ArmorStand"); if (!canEdit(player, as)) return; if (plugin.isEditTool(player.getInventory().getItemInMainHand())) { getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); @@ -172,36 +161,33 @@ void onArmorStandInteract(PlayerInteractAtEntityEvent event) { //Attempt rename if (player.getInventory().getItemInMainHand().getType() == Material.NAME_TAG && player.hasPermission("asedit.rename")) { ItemStack nameTag = player.getInventory().getItemInMainHand(); - Component getName; + Component name; ItemMeta meta = nameTag.getItemMeta(); - if (meta != null && meta.hasDisplayName()) { - // The display name is stored as a raw MiniMessage string, so parse it into a Component - Component displayName = MiniMessage.miniMessage().deserialize( - plainText().serialize(meta.displayName())); - if (!player.hasPermission("asedit.rename.color")) { - getName = Component.text(plainText().serialize(displayName)); + if (meta != null && meta.hasCustomName()) { + Component displayName = meta.customName(); + if (!player.hasPermission("asedit.rename.color") && displayName != null) { + name = Component.text(PlainTextComponentSerializer.plainText().serialize(displayName)); } else { - getName = displayName; + name = displayName; } } else { - getName = null; + name = null; } - if (getName == null) { - as.setCustomName(null); + if (name == null) { + as.customName(null); as.setCustomNameVisible(false); event.setCancelled(true); } else { event.setCancelled(true); - if ((player.getGameMode() != GameMode.CREATIVE)) { + if (player.getGameMode() != GameMode.CREATIVE) { nameTag.subtract(1); } - // minecraft will set the name after this event even if the event is cancelled. + // Minecraft will set the name after this event even if the event is cancelled. // change it 1 tick later to apply formatting without it being overwritten - final Component finalgetName = getName; scheduler.runForEntity(as, () -> { - as.customName(finalgetName); + as.customName(name); as.setCustomNameVisible(true); }); } @@ -217,9 +203,11 @@ void onArmorStandInteract(PlayerInteractAtEntityEvent event) { return; } + // TODO: Check dupe if (player.getInventory().getItemInMainHand().getType().equals(Material.GLOW_INK_SAC) //attempt glowing && player.hasPermission("asedit.basic") - && plugin.glowItemFrames && player.isSneaking()) { + && plugin.glowItemFrames && player.isSneaking() + ) { ItemStack glowSacs = player.getInventory().getItemInMainHand(); ItemStack contents = null; @@ -232,9 +220,7 @@ void onArmorStandInteract(PlayerInteractAtEntityEvent event) { BlockFace facing = itemFrame.getFacing(); if (player.getGameMode() != GameMode.CREATIVE) { - if (glowSacs.getAmount() > 1) { - glowSacs.setAmount(glowSacs.getAmount() - 1); - } else glowSacs = new ItemStack(Material.AIR); + glowSacs.subtract(1); } itemFrame.remove(); @@ -244,32 +230,30 @@ void onArmorStandInteract(PlayerInteractAtEntityEvent event) { glowFrame.setItem(contents); glowFrame.setRotation(rotation); } - } } } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - void onArmorStandBreak(EntityDamageByEntityEvent event) { // Fixes issue #309 + public void onArmorStandBreak(EntityDamageByEntityEvent event) { // Fixes issue #309 if (!(event.getDamager() instanceof Player)) return; // If the damager is not a player, ignore. - if (!(event.getEntity() instanceof ArmorStand)) return; // If the damaged entity is not an ArmorStand, ignore. - - if (event.getEntity() instanceof ArmorStand entityAS) { - // Check if the ArmorStand is invulnerable and if the damager is a player. - if (entityAS.isInvulnerable() && event.getDamager() instanceof Player p) { - // Check if the player is in Creative mode. - if (p.getGameMode() == GameMode.CREATIVE) { - // If the player is in Creative mode and the ArmorStand is invulnerable, - // cancel the event to prevent breaking the ArmorStand. - p.sendMessage(plugin.getLang().getMessage("unabledestroycreative")); - event.setCancelled(true); // Cancel the event to prevent ArmorStand destruction. - } + if (!(event.getEntity() instanceof ArmorStand stand)) return; // If the damaged entity is not an ArmorStand, ignore. + + // Check if the ArmorStand is invulnerable and if the damager is a player. + if (stand.isInvulnerable() && event.getDamager() instanceof Player player) { + // Check if the player is in Creative mode. + if (player.getGameMode() == GameMode.CREATIVE) { + // If the player is in Creative mode and the ArmorStand is invulnerable, + // cancel the event to prevent breaking the ArmorStand. + player.sendMessage(plugin.getLang().getMessage("unabledestroycreative")); + event.setCancelled(true); } } - if (event.getEntity() instanceof ArmorStand entityAS && entityAS.isDead()) { - event.getEntity().customName(Component.empty()); - event.getEntity().setCustomNameVisible(false); + + if (stand.isDead()) { + stand.customName(null); + stand.setCustomNameVisible(false); event.setCancelled(false); } } @@ -277,7 +261,7 @@ void onArmorStandBreak(EntityDamageByEntityEvent event) { // Fixes issue #309 @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onSwitchHands(PlayerSwapHandItemsEvent event) { Player player = event.getPlayer(); - debug.log("PlayerSwapHandItemsEvent trigger for Player: " + player.getName()); + Debug.log("PlayerSwapHandItemsEvent trigger for Player: " + player.getName()); // Ignore if the off-hand item is not the edit tool if (!plugin.isEditTool(event.getOffHandItem())) return; @@ -290,19 +274,19 @@ public void onSwitchHands(PlayerSwapHandItemsEvent event) { PlayerEditor editor = getPlayerEditor(player.getUniqueId()); // Handle double target - if (!isEmpty(asTargets) && !isEmpty(frameTargets)) { + if (!asTargets.isEmpty() && !frameTargets.isEmpty()) { editor.sendMessage("doubletarget", "warn"); return; } // Handle single target: ArmorStand - if (!isEmpty(asTargets)) { + if (!asTargets.isEmpty()) { editor.setTarget(asTargets); return; } // Handle single target: ItemFrame - if (!isEmpty(frameTargets)) { + if (!frameTargets.isEmpty()) { editor.setFrameTarget(frameTargets); return; } @@ -311,7 +295,7 @@ public void onSwitchHands(PlayerSwapHandItemsEvent event) { editor.sendMessage("nodoubletarget", "warn"); } - private ArrayList getTargets(Player player) { + private @NotNull ArrayList getTargets(Player player) { Location eyeLaser = player.getEyeLocation(); Vector direction = player.getLocation().getDirection(); ArrayList armorStands = new ArrayList<>(); @@ -321,7 +305,7 @@ private ArrayList getTargets(Player player) { double RANGE = 10; double LASERRADIUS = .3; List nearbyEntities = player.getNearbyEntities(RANGE, RANGE, RANGE); - if (nearbyEntities.isEmpty()) return null; + if (nearbyEntities.isEmpty()) return armorStands; for (double i = 0; i < RANGE; i += STEPSIZE) { List nearby = (List) player.getWorld().getNearbyEntities(eyeLaser, LASERRADIUS, LASERRADIUS, LASERRADIUS); @@ -342,7 +326,7 @@ private ArrayList getTargets(Player player) { return armorStands; } - private ArrayList getFrameTargets(Player player) { + private @NotNull ArrayList getFrameTargets(Player player) { Location eyeLaser = player.getEyeLocation(); Vector direction = player.getLocation().getDirection(); ArrayList itemFrames = new ArrayList<>(); @@ -353,7 +337,7 @@ private ArrayList getFrameTargets(Player player) { double LASERRADIUS = .3; List nearbyEntities = player.getNearbyEntities(RANGE, RANGE, RANGE); - if (nearbyEntities.isEmpty()) return null; + if (nearbyEntities.isEmpty()) return itemFrames; for (double i = 0; i < RANGE; i += STEPSIZE) { List nearby = (List) player.getWorld().getNearbyEntities(eyeLaser, LASERRADIUS, LASERRADIUS, LASERRADIUS); @@ -378,8 +362,9 @@ private ArrayList getFrameTargets(Player player) { boolean canEdit(Player player, Entity entity) { // Check if the entity has a blocked name - if(entity.customName() != null && plugin.enableBlockedNames) { - String name = plainText().serialize(entity.customName()); + Component component = entity.customName(); + if (component != null && plugin.enableBlockedNames) { + String name = PlainTextComponentSerializer.plainText().serialize(component); if (plugin.blockedNames.stream().anyMatch(name::equalsIgnoreCase)) { return false; } @@ -389,39 +374,38 @@ boolean canEdit(Player player, Entity entity) { return protections.stream().allMatch(protection -> protection.checkPermission(entity, player)); } - void applyLeftTool(Player player, ArmorStand as) { - debug.log("Applying Left Tool on ArmorStand for Player: " + player.getName()); + private void applyLeftTool(Player player, ArmorStand as) { + Debug.log("Applying Left Tool on ArmorStand for Player: " + player.getName()); getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); getPlayerEditor(player.getUniqueId()).editArmorStand(as); } - void applyLeftTool(Player player, ItemFrame itemf) { - debug.log("Applying Left Tool on ItemFrame for Player: " + player.getName()); + private void applyLeftTool(Player player, ItemFrame itemf) { + Debug.log("Applying Left Tool on ItemFrame for Player: " + player.getName()); getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); getPlayerEditor(player.getUniqueId()).editItemFrame(itemf); } - void applyRightTool(Player player, ItemFrame itemf) { - debug.log("Applying Right Tool on ItemFrame for Player: " + player.getName()); + private void applyRightTool(Player player, ItemFrame itemf) { + Debug.log("Applying Right Tool on ItemFrame for Player: " + player.getName()); getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); getPlayerEditor(player.getUniqueId()).editItemFrame(itemf); } - void applyRightTool(Player player, ArmorStand as) { - debug.log("Applying Right Tool on ArmorStand for Player: " + player.getName()); + private void applyRightTool(Player player, ArmorStand as) { + Debug.log("Applying Right Tool on ArmorStand for Player: " + player.getName()); getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); getPlayerEditor(player.getUniqueId()).reverseEditArmorStand(as); } @EventHandler(priority = EventPriority.LOWEST) - void onRightClickTool(PlayerInteractEvent e) { - if (!(e.getAction() == Action.LEFT_CLICK_AIR - || e.getAction() == Action.RIGHT_CLICK_AIR - || e.getAction() == Action.LEFT_CLICK_BLOCK - || e.getAction() == Action.RIGHT_CLICK_BLOCK)) return; + public void onRightClickTool(PlayerInteractEvent event) { + if (!(event.getAction().isLeftClick() || event.getAction().isRightClick())) { + return; + } - debug.log("Ran on Right Click Tool Event."); - Player player = e.getPlayer(); + Debug.log("Ran on Right Click Tool Event."); + Player player = event.getPlayer(); if (!plugin.isEditTool(player.getInventory().getItemInMainHand())) return; if (plugin.requireSneaking && !player.isSneaking()) return; @@ -429,40 +413,39 @@ void onRightClickTool(PlayerInteractEvent e) { if (plugin.enablePerWorld && (!plugin.allowedWorldList.contains(player.getWorld().getName()))) { //Implementation for Per World ASE getPlayerEditor(player.getUniqueId()).sendMessage("notincorrectworld", "warn"); - e.setCancelled(true); + event.setCancelled(true); return; } - e.setCancelled(true); - debug.log("Open Menu Called for Player: " + player.getName()); + event.setCancelled(true); + Debug.log("Open Menu Called for Player: " + player.getName()); getPlayerEditor(player.getUniqueId()).openMenu(); } @EventHandler(priority = EventPriority.NORMAL) - void onScrollNCrouch(PlayerItemHeldEvent e) { - Player player = e.getPlayer(); + public void onScrollNCrouch(PlayerItemHeldEvent event) { + Player player = event.getPlayer(); if (!player.isSneaking()) return; - if (!plugin.isEditTool(player.getInventory().getItem(e.getPreviousSlot()))) return; + if (!plugin.isEditTool(player.getInventory().getItem(event.getPreviousSlot()))) return; - e.setCancelled(true); - if (e.getNewSlot() == e.getPreviousSlot() + 1 || (e.getNewSlot() == 0 && e.getPreviousSlot() == 8)) { + event.setCancelled(true); + if (event.getNewSlot() == event.getPreviousSlot() + 1 || (event.getNewSlot() == 0 && event.getPreviousSlot() == 8)) { getPlayerEditor(player.getUniqueId()).cycleAxis(1); - } else if (e.getNewSlot() == e.getPreviousSlot() - 1 || (e.getNewSlot() == 8 && e.getPreviousSlot() == 0)) { + } else if (event.getNewSlot() == event.getPreviousSlot() - 1 || (event.getNewSlot() == 8 && event.getPreviousSlot() == 0)) { getPlayerEditor(player.getUniqueId()).cycleAxis(-1); } } @EventHandler(priority = EventPriority.LOWEST) - void onPlayerMenuSelect(InventoryClickEvent e) { - final InventoryHolder holder = PaperLib.getHolder(e.getInventory(), false).getHolder(); + public void onPlayerMenuSelect(InventoryClickEvent event) { + final InventoryHolder holder = PaperLib.getHolder(event.getInventory(), false).getHolder(); - if (holder == null) return; if (!(holder instanceof ASEHolder)) return; if (holder == menuHolder) { - e.setCancelled(true); - ItemStack item = e.getCurrentItem(); + event.setCancelled(true); + ItemStack item = event.getCurrentItem(); if (item != null && item.hasItemMeta()) { - Player player = (Player) e.getWhoClicked(); + Player player = (Player) event.getWhoClicked(); String command = item.getItemMeta().getPersistentDataContainer().get(plugin.getIconKey(), PersistentDataType.STRING); if (command == null || command.equals("ase ")) { // Therefore user has clicked a black pane getPlayerEditor(player.getUniqueId()).sendMessage("blackGlassClick", ""); @@ -475,19 +458,19 @@ void onPlayerMenuSelect(InventoryClickEvent e) { } } if (holder == equipmentHolder) { - ItemStack item = e.getCurrentItem(); + ItemStack item = event.getCurrentItem(); if (item == null) return; if (item.getItemMeta() == null) return; if (item.getItemMeta().getPersistentDataContainer().has(plugin.getIconKey(), PersistentDataType.STRING)) { - e.setCancelled(true); + event.setCancelled(true); } } if (holder == presetHolder) { - e.setCancelled(true); - ItemStack item = e.getCurrentItem(); + event.setCancelled(true); + ItemStack item = event.getCurrentItem(); if (item != null && item.hasItemMeta()) { - Player player = (Player) e.getWhoClicked(); + Player player = (Player) event.getWhoClicked(); String itemName = item.getPersistentDataContainer().get(plugin.getIconKey(), PersistentDataType.STRING); PlayerEditor pe = players.get(player.getUniqueId()); pe.presetPoseMenu.handlePresetPose(itemName, player); @@ -496,10 +479,10 @@ void onPlayerMenuSelect(InventoryClickEvent e) { } if (holder == sizeMenuHolder) { - e.setCancelled(true); - ItemStack item = e.getCurrentItem(); + event.setCancelled(true); + ItemStack item = event.getCurrentItem(); if (item != null && item.hasItemMeta()) { - Player player = (Player) e.getWhoClicked(); + Player player = (Player) event.getWhoClicked(); String itemName = item.getPersistentDataContainer().get(plugin.getIconKey(), PersistentDataType.STRING); PlayerEditor pe = players.get(player.getUniqueId()); pe.sizeModificationMenu.handleAttributeScaling(itemName, player); @@ -510,37 +493,29 @@ void onPlayerMenuSelect(InventoryClickEvent e) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - void onPlayerMenuClose(InventoryCloseEvent e) { - final InventoryHolder holder = PaperLib.getHolder(e.getInventory(), false).getHolder(); + public void onPlayerMenuClose(InventoryCloseEvent event) { + final InventoryHolder holder = PaperLib.getHolder(event.getInventory(), false).getHolder(); - if (holder == null) return; if (!(holder instanceof ASEHolder)) return; if (holder == equipmentHolder) { - PlayerEditor pe = players.get(e.getPlayer().getUniqueId()); + PlayerEditor pe = players.get(event.getPlayer().getUniqueId()); pe.equipMenu.equipArmorstand(); // Remove the In Use Lock - if (!plugin.getHasFolia()) { - team = plugin.scoreboard.getTeam(plugin.inUseTeam); - if (team != null) { - team.removeEntry(pe.armorStandInUseId.toString()); - } - } else { - foliaInUse.remove(pe.armorStandInUseId); - } + SharedUtil.setInUse(pe.armorStandInUseId, false); } } @EventHandler(priority = EventPriority.MONITOR) - void onPlayerLogOut(PlayerQuitEvent e) { - removePlayerEditor(e.getPlayer().getUniqueId()); + public void onPlayerLogOut(PlayerQuitEvent event) { + removePlayerEditor(event.getPlayer().getUniqueId()); } public PlayerEditor getPlayerEditor(UUID uuid) { return players.containsKey(uuid) ? players.get(uuid) : addPlayerEditor(uuid); } - PlayerEditor addPlayerEditor(UUID uuid) { + private PlayerEditor addPlayerEditor(UUID uuid) { PlayerEditor pe = new PlayerEditor(uuid, plugin); players.put(uuid, pe); return pe; @@ -550,32 +525,12 @@ private void removePlayerEditor(UUID uuid) { players.remove(uuid); } - public ASEHolder getMenuHolder() { - return menuHolder; - } - - public ASEHolder getEquipmentHolder() { - return equipmentHolder; - } - - public ASEHolder getSizeMenuHolder() { - return sizeMenuHolder; - } - - public ASEHolder getPresetHolder() { - return presetHolder; - } - long getTime() { return counter.ticks; } - private boolean isEmpty(List list) { - return list.isEmpty(); - } - - class TickCounter implements Runnable { + static class TickCounter implements Runnable { long ticks = 0; //I am optimistic @Override diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/Scheduler.java b/src/main/java/io/github/rypofalem/armorstandeditor/Scheduler.java index e98b42e63..4c235bce3 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/Scheduler.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/Scheduler.java @@ -3,7 +3,6 @@ import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; /** @@ -11,7 +10,6 @@ * Handles runTask, runTaskLater, runTaskTimer, entity-based and location-based tasks safely. */ public class Scheduler { - private final Plugin plugin; private final boolean isFolia; @@ -57,14 +55,6 @@ public void runTaskTimer(Runnable task, long delayTicks, long periodTicks) { } } - /** Recursive helper for Folia repeating tasks */ - private void scheduleRepeating(Runnable task, long periodTicks) { - Bukkit.getGlobalRegionScheduler().run(plugin, _ -> { - task.run(); - scheduleRepeating(task, periodTicks); - }); - } - /** Teleport an entity safely */ public void teleport(Entity entity, Location location) { if (isFolia) { @@ -83,24 +73,6 @@ public void runForEntity(Entity entity, Runnable task) { } } - public void dropItem(Location location, ItemStack item) { - Runnable task = () -> location.getWorld().dropItemNaturally(location, item); - if (isFolia) { - Bukkit.getRegionScheduler().run(plugin, location, _ -> task.run()); - } else { - task.run(); - } - } - - /** Run a task at a specific location (region-safe) */ - public void runAtLocation(Location location, Runnable task) { - if (isFolia) { - Bukkit.getRegionScheduler().run(plugin, location, _ -> task.run()); - } else { - runTask(task); - } - } - /** Run an async task (Paper only, Folia falls back to region scheduler) */ public void runAsync(Runnable task) { if (isFolia) { diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/SharedUtil.java b/src/main/java/io/github/rypofalem/armorstandeditor/SharedUtil.java new file mode 100644 index 000000000..4460b4054 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/SharedUtil.java @@ -0,0 +1,39 @@ +package io.github.rypofalem.armorstandeditor; + +import org.bukkit.NamespacedKey; +import org.bukkit.entity.ArmorStand; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; + +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public class SharedUtil { + private static final ArmorStandEditorPlugin plugin = ArmorStandEditorPlugin.instance(); + private static final Set IN_USE = ConcurrentHashMap.newKeySet(); + private static final NamespacedKey LOCK_KEY = new NamespacedKey(plugin, "locked"); + + public static boolean isLocked(ArmorStand stand) { + Boolean lock = stand.getPersistentDataContainer().get(LOCK_KEY, PersistentDataType.BOOLEAN); + + return lock != null && lock; + } + + public static void setLocked(ArmorStand stand, boolean value) { + PersistentDataContainer pdc = stand.getPersistentDataContainer(); + pdc.set(LOCK_KEY, PersistentDataType.BOOLEAN, value); + } + + public static boolean isInUse(UUID stand) { + return IN_USE.contains(stand); + } + + public static void setInUse(UUID stand, boolean value) { + if (value) { + IN_USE.add(stand); + } else { + IN_USE.remove(stand); + } + } +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/TabCompleter.java b/src/main/java/io/github/rypofalem/armorstandeditor/TabCompleter.java index 67815c8cd..37c33619c 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/TabCompleter.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/TabCompleter.java @@ -3,17 +3,17 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class TabCompleter implements org.bukkit.command.TabCompleter { - - private ArmorStandEditorPlugin plugin = ArmorStandEditorPlugin.instance(); + private final ArmorStandEditorPlugin plugin = ArmorStandEditorPlugin.instance(); @Override - public List onTabComplete(CommandSender sender, Command command, String label, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String @NotNull[] args) { if (!(sender instanceof Player player)) return Collections.emptyList(); if (!isCommandValid(command.getName())) return Collections.emptyList(); @@ -27,7 +27,7 @@ public List onTabComplete(CommandSender sender, Command command, String if (getPermissionReload(player)) argList.add("reload"); if (getPermissionStats(player)) argList.add("stats"); if (getPermissionResetWithinRange(player)) argList.add("resetwithinrange"); - if (getPermissionPlayerHead(player) || plugin.getAllowedToRetrieveOwnPlayerHead()) + if (getPermissionPlayerHead(player) && plugin.getAllowedToRetrieveOwnPlayerHead()) argList.add("playerhead"); } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/UpdateChecker.java b/src/main/java/io/github/rypofalem/armorstandeditor/UpdateChecker.java index d130de89a..1c3749e94 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/UpdateChecker.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/UpdateChecker.java @@ -105,7 +105,7 @@ private boolean fetchLatestVersion() { } catch (Exception exception) { plugin.getLogger().warning("Failed to get the latest version from Hangar. Please check your internet connection."); - plugin.debug.log("Error while checking for updates: " + exception.getMessage()); + Debug.log("Error while checking for updates: " + exception.getMessage()); return false; } } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/menu/EquipmentMenu.java b/src/main/java/io/github/rypofalem/armorstandeditor/menu/EquipmentMenu.java index 62ce36642..f20aa193c 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/menu/EquipmentMenu.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/menu/EquipmentMenu.java @@ -43,7 +43,6 @@ public class EquipmentMenu { Inventory menuInv; - private final Debug debug; private final PlayerEditor pe; private final ArmorStand armorstand; ItemStack helmet; @@ -63,7 +62,6 @@ public class EquipmentMenu { public EquipmentMenu(PlayerEditor pe, ArmorStand as) { this.pe = pe; this.armorstand = as; - this.debug = pe.plugin.debug; //noinspection ConstantConditions coreProtectExtension = pe.plugin.getCoreProtectExtension(); @@ -142,7 +140,7 @@ public void openMenu() { pe.getPlayer().closeInventory(); if (pe.getPlayer().hasPermission("asedit.equipment")) { fillInventory(); - debug.log("Player '" + pe.getPlayer().getName() + "' has opened the Equipment Menu."); + Debug.log("Player '" + pe.getPlayer().getName() + "' has opened the Equipment Menu."); pe.getPlayer().openInventory(menuInv); } } @@ -168,39 +166,39 @@ public void equipArmorstand() { @SuppressWarnings("java:S2209") private void checkForChanges() { - debug.log("Equipping ArmorStand and checking changes."); + Debug.log("Equipping ArmorStand and checking changes."); Player player = pe.getPlayer(); ItemStack[] oldArray = new ItemStack[]{oldHelmet, oldChest, oldPants, oldBoots, oldRightHand, oldLeftHand}; ItemStack[] newArray = new ItemStack[]{helmet, chest, pants, boots, rightHand, leftHand}; boolean change = false; if (hasChanged(oldHelmet, helmet)) { - debug.log("Helmet changed from " + oldHelmet + " to " + helmet); + Debug.log("Helmet changed from " + oldHelmet + " to " + helmet); oldHelmet = helmet; change = true; } if (hasChanged(oldChest, chest)) { - debug.log("Chest changed from " + oldChest + " to " + chest); + Debug.log("Chest changed from " + oldChest + " to " + chest); oldChest = chest; change = true; } if (hasChanged(oldPants, pants)) { - debug.log("Pants changed from " + oldPants + " to " + pants); + Debug.log("Pants changed from " + oldPants + " to " + pants); oldPants = pants; change = true; } if (hasChanged(oldBoots, boots)) { - debug.log("Boots changed from " + oldBoots + " to " + boots); + Debug.log("Boots changed from " + oldBoots + " to " + boots); oldBoots = boots; change = true; } if (hasChanged(oldRightHand, rightHand)) { - debug.log("R-Hand changed from " + oldRightHand + " to " + rightHand); + Debug.log("R-Hand changed from " + oldRightHand + " to " + rightHand); oldRightHand = rightHand; change = true; } if (hasChanged(oldLeftHand, leftHand)) { - debug.log("L-Hand changed from " + oldLeftHand + " to " + leftHand); + Debug.log("L-Hand changed from " + oldLeftHand + " to " + leftHand); oldLeftHand = leftHand; change = true; } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/menu/Menu.java b/src/main/java/io/github/rypofalem/armorstandeditor/menu/Menu.java index 719bd6c48..c74e392d0 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/menu/Menu.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/menu/Menu.java @@ -38,19 +38,16 @@ public class Menu { private final Inventory menuInv; private final PlayerEditor pe; - Component name; - private Debug debug; public Menu(PlayerEditor pe) { this.pe = pe; - this.debug = pe.plugin.debug; - name = pe.plugin.getLang().getMessage("mainmenutitle", "menutitle"); + Component name = pe.plugin.getLang().getMessage("mainmenutitle", "menutitle"); menuInv = Bukkit.createInventory(pe.getManager().getMenuHolder(), 54, name); fillInventory(); } + @SuppressWarnings("UnstableApiUsage") private void fillInventory() { - menuInv.clear(); ItemStack xAxis; @@ -235,7 +232,7 @@ private void fillInventory() { "paste", "mode paste"); } - if (pe.getPlayer().hasPermission("asedit.head") || pe.plugin.getAllowedToRetrieveOwnPlayerHead()) { + if (pe.getPlayer().hasPermission("asedit.head") && pe.plugin.getAllowedToRetrieveOwnPlayerHead()) { playerHead = createIcon(ItemStack.of(Material.PLAYER_HEAD), "playerheadmenu", "playerhead"); @@ -270,6 +267,7 @@ private ItemStack createIcon(ItemStack icon, String path, String command) { return createIcon(icon, path, command, null); } + @SuppressWarnings("UnstableApiUsage") private ItemStack createIcon(ItemStack icon, String path, String command, String option) { if (!command.isEmpty()) { @@ -302,7 +300,7 @@ private Component getIconDescription(String path, String option) { public void openMenu() { if (pe.getPlayer().hasPermission("asedit.basic")) { fillInventory(); - debug.log("Player '" + pe.getPlayer().getName() + "' has opened the Main ASE Menu"); + Debug.log("Player '" + pe.getPlayer().getName() + "' has opened the Main ASE Menu"); pe.getPlayer().openInventory(menuInv); } } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/menu/PresetArmorPosesMenu.java b/src/main/java/io/github/rypofalem/armorstandeditor/menu/PresetArmorPosesMenu.java index 7d7876c31..353b530d2 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/menu/PresetArmorPosesMenu.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/menu/PresetArmorPosesMenu.java @@ -41,23 +41,20 @@ public class PresetArmorPosesMenu { - Inventory menuInv; - private Debug debug; + private final Inventory menuInv; private final PlayerEditor pe; public ArmorStandEditorPlugin plugin; - private ArmorStand armorStand; - Component name; + private final ArmorStand armorStand; - Sound soundToUse = Sound.BLOCK_COMPARATOR_CLICK; - Location playerLocation; - Integer volumePitch = 1; + private final Sound soundToUse = Sound.BLOCK_COMPARATOR_CLICK; + private Location playerLocation; + private final int volumePitch = 1; public PresetArmorPosesMenu(PlayerEditor pe, ArmorStand as) { this.pe = pe; this.armorStand = as; this.plugin = pe.plugin; - this.debug = pe.plugin.debug; - name = plugin.getLang().getMessage("presettitle", "menutitle"); + Component name = plugin.getLang().getMessage("presettitle", "menutitle"); menuInv = Bukkit.createInventory(pe.getManager().getPresetHolder(), 36, name); } @@ -122,7 +119,7 @@ private Component getIconDescription(String path) { public void openMenu() { if (pe.getPlayer().hasPermission("asedit.basic")) { fillInventory(); - debug.log("Player '" + pe.getPlayer().getName() + "' has opened the armorStand Preset Menu"); + Debug.log("Player '" + pe.getPlayer().getName() + "' has opened the armorStand Preset Menu"); pe.getPlayer().openInventory(menuInv); } } @@ -133,7 +130,7 @@ public void handlePresetPose(String itemName, Player player) { playerLocation = player.getLocation(); - debug.log("Player '" + player.getName() + "' has chosen the Preset AS Pose '" + itemName + "'"); + Debug.log("Player '" + player.getName() + "' has chosen the Preset AS Pose '" + itemName + "'"); //Do the Preset switch (itemName) { diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/menu/SizeMenu.java b/src/main/java/io/github/rypofalem/armorstandeditor/menu/SizeMenu.java index fa369c1e5..b75c26168 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/menu/SizeMenu.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/menu/SizeMenu.java @@ -24,18 +24,15 @@ public class SizeMenu extends ASEHolder { public ArmorStandEditorPlugin plugin; - Inventory menuInv; - private Debug debug; - private PlayerEditor pe; - private ArmorStand as; - static Component name; + private final Inventory menuInv; + private final PlayerEditor pe; + private final ArmorStand as; public SizeMenu(PlayerEditor pe, ArmorStand as) { this.pe = pe; this.as = as; - this.debug = pe.plugin.debug; this.plugin = pe.plugin; - name = pe.plugin.getLang().getMessage("sizeMenu", "menutitle"); + Component name = pe.plugin.getLang().getMessage("sizeMenu", "menutitle"); menuInv = Bukkit.createInventory(pe.getManager().getSizeMenuHolder(), 27, name); } @@ -68,28 +65,24 @@ private void fillInventory() { menuInv.setContents(items); } - private ItemStack createIcon(ItemStack icon, String path) { - return createIcon(icon, path, null); - } - @SuppressWarnings("UnstableApiUsage") - private ItemStack createIcon(ItemStack icon, String path, String option) { - icon.setData(DataComponentTypes.CUSTOM_NAME, getIconName(path, option)); + private ItemStack createIcon(ItemStack icon, String path) { + icon.setData(DataComponentTypes.CUSTOM_NAME, getIconName(path)); icon.editPersistentDataContainer(pdc -> pdc.set(pe.plugin.getIconKey(), PersistentDataType.STRING, path)); - icon.setData(DataComponentTypes.LORE, ItemLore.lore().addLine(getIconDescription(path, option)).build()); + icon.setData(DataComponentTypes.LORE, ItemLore.lore().addLine(getIconDescription(path)).build()); icon.setData(DataComponentTypes.TOOLTIP_DISPLAY, TooltipDisplay.tooltipDisplay() .addHiddenComponents(DataComponentTypes.ATTRIBUTE_MODIFIERS).build()); return icon; } - private Component getIconName(String path, String option) { - return pe.plugin.getLang().getMessage(path, "iconname", option); + private Component getIconName(String path) { + return pe.plugin.getLang().getMessage(path, "iconname"); } - private Component getIconDescription(String path, String option) { - return pe.plugin.getLang().getMessage(path + ".description", "icondescription", option); + private Component getIconDescription(String path) { + return pe.plugin.getLang().getMessage(path + ".description", "icondescription"); } @@ -152,7 +145,7 @@ private void playChimeSound(Player player) { } private void setArmorStandScale(Player player, String itemName, double scaleValue) { - debug.log("Setting the Scale of the ArmorStand"); + Debug.log("Setting the Scale of the ArmorStand"); double currentScaleValue = 0; double newScaleValue; @@ -161,51 +154,57 @@ private void setArmorStandScale(Player player, String itemName, double scaleValu if (!player.hasPermission("asedit.togglesize")) return; // Basically go from 0 directly to ItemSize - if (itemName.equals("scale1") || itemName.equals("scale2") || itemName.equals("scale3") - || itemName.equals("scale4") || itemName.equals("scale5") || itemName.equals("scale6") - || itemName.equals("scale7") || itemName.equals("scale8") || itemName.equals("scale9") - || itemName.equals("scale10")) { - newScaleValue = currentScaleValue + scaleValue; - debug.log("Result of the scale Calculation: " + newScaleValue); - - if (newScaleValue > plugin.getMaxScaleValue()) { - pe.getPlayer().sendMessage(plugin.getLang().getMessage("scalemaxwarn", "warn")); - } else if (newScaleValue < plugin.getMinScaleValue()) { - pe.getPlayer().sendMessage(plugin.getLang().getMessage("scaleminwarn", "warn")); - } else { - as.getAttribute(Attribute.SCALE).setBaseValue(newScaleValue); + switch (itemName) { + case "scale1", "scale2", "scale3", "scale4", "scale5", "scale6", "scale7", "scale8", "scale9", + "scale10" -> { + newScaleValue = currentScaleValue + scaleValue; + Debug.log("Result of the scale Calculation: " + newScaleValue); + + if (newScaleValue > plugin.getMaxScaleValue()) { + pe.getPlayer().sendMessage(plugin.getLang().getMessage("scalemaxwarn", "warn")); + } else if (newScaleValue < plugin.getMinScaleValue()) { + pe.getPlayer().sendMessage(plugin.getLang().getMessage("scaleminwarn", "warn")); + } else { + as.getAttribute(Attribute.SCALE).setBaseValue(newScaleValue); + } + + // Add either 0.1 or 0.5 to the current } + case "scaleadd12", "scaleadd110" -> { + currentScaleValue = as.getAttribute(Attribute.SCALE).getBaseValue(); //Get the current Value - // Add either 0.1 or 0.5 to the current - } else if (itemName.equals("scaleadd12") || itemName.equals("scaleadd110")) { - currentScaleValue = as.getAttribute(Attribute.SCALE).getBaseValue(); //Get the current Value - newScaleValue = currentScaleValue + scaleValue; // Add for increments - debug.log("Result of the scale Calculation: " + newScaleValue); - if (newScaleValue > plugin.getMaxScaleValue()) { - pe.getPlayer().sendMessage(plugin.getLang().getMessage("scalemaxwarn", "warn")); - return; + newScaleValue = currentScaleValue + scaleValue; // Add for increments + + Debug.log("Result of the scale Calculation: " + newScaleValue); + if (newScaleValue > plugin.getMaxScaleValue()) { + pe.getPlayer().sendMessage(plugin.getLang().getMessage("scalemaxwarn", "warn")); + return; + } + as.getAttribute(Attribute.SCALE).setBaseValue(newScaleValue); + //Subtract either 0.1 or 0.5 from the current } - as.getAttribute(Attribute.SCALE).setBaseValue(newScaleValue); - //Subtract either 0.1 or 0.5 from the current - } else if (itemName.equals("scaleremove12") || itemName.equals("scaleremove110")) { - currentScaleValue = as.getAttribute(Attribute.SCALE).getBaseValue(); - newScaleValue = currentScaleValue - scaleValue; // Subtract for decrements - debug.log("Result of the scale Calculation: " + newScaleValue); - if (newScaleValue < plugin.getMinScaleValue()) { - pe.getPlayer().sendMessage(plugin.getLang().getMessage("scaleminwarn", "warn")); - return; + case "scaleremove12", "scaleremove110" -> { + currentScaleValue = as.getAttribute(Attribute.SCALE).getBaseValue(); + newScaleValue = currentScaleValue - scaleValue; // Subtract for decrements + + Debug.log("Result of the scale Calculation: " + newScaleValue); + if (newScaleValue < plugin.getMinScaleValue()) { + pe.getPlayer().sendMessage(plugin.getLang().getMessage("scaleminwarn", "warn")); + return; + } + as.getAttribute(Attribute.SCALE).setBaseValue(newScaleValue); + } + case "reset" -> { + newScaleValue = 1.0; + as.getAttribute(Attribute.SCALE).setBaseValue(newScaleValue); } - as.getAttribute(Attribute.SCALE).setBaseValue(newScaleValue); - } else if (itemName.equals("reset")) { // Set it back to 1 - newScaleValue = 1.0; - as.getAttribute(Attribute.SCALE).setBaseValue(newScaleValue); } } public void openMenu() { if (pe.getPlayer().hasPermission("asedit.togglesize")) { fillInventory(); - debug.log("Player '" + pe.getPlayer().getName() + "' has opened the Sizing Attribute Menu"); + Debug.log("Player '" + pe.getPlayer().getName() + "' has opened the Sizing Attribute Menu"); pe.getPlayer().openInventory(menuInv); } } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/modes/AdjustmentMode.java b/src/main/java/io/github/rypofalem/armorstandeditor/modes/AdjustmentMode.java index 0e0f1386c..a4ed051a4 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/modes/AdjustmentMode.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/modes/AdjustmentMode.java @@ -22,7 +22,7 @@ public enum AdjustmentMode { COARSE("Coarse"), FINE("Fine"); - private String name; + private final String name; AdjustmentMode(String name) { this.name = name; diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/modes/Axis.java b/src/main/java/io/github/rypofalem/armorstandeditor/modes/Axis.java index a6301e628..805752f17 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/modes/Axis.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/modes/Axis.java @@ -22,7 +22,7 @@ public enum Axis { X("X"), Y("Y"), Z("Z"); - String name; + private final String name; Axis(String name) { this.name = name; diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/protections/BentoBoxProtection.java b/src/main/java/io/github/rypofalem/armorstandeditor/protections/BentoBoxProtection.java deleted file mode 100644 index 5529a8198..000000000 --- a/src/main/java/io/github/rypofalem/armorstandeditor/protections/BentoBoxProtection.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016-2023 RypoFalem - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.github.rypofalem.armorstandeditor.protections; - -import io.github.rypofalem.armorstandeditor.ArmorStandEditorPlugin; - -import io.github.rypofalem.armorstandeditor.Debug; -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.user.User; -import world.bentobox.bentobox.database.objects.Island; -import world.bentobox.bentobox.lists.Flags; -import world.bentobox.bentobox.managers.AddonsManager; -import world.bentobox.bentobox.managers.IslandsManager; - -import org.bukkit.Bukkit; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import java.util.Optional; - -public class BentoBoxProtection implements Protection { - - private final boolean bentoEnabled; - private boolean bSkyBlockEnabled; - private boolean aOneBlockEnabled; - - public BentoBoxProtection() { - bentoEnabled = Bukkit.getPluginManager().isPluginEnabled("BentoBox"); - } - - @Override - public boolean checkPermission(Block block, Player player) { - if (!bentoEnabled || player.isOp() || - player.hasPermission("asedit.ignoreProtection.bentobox") || - player.hasPermission("bentobox.admin")) return true; - - BentoBox myBento = BentoBox.getInstance(); - if (myBento == null) return true; - - IslandsManager islandsManager = myBento.getIslandsManager(); - AddonsManager addonsManager = myBento.getAddonsManager(); - - bSkyBlockEnabled = addonsManager.getAddonByName("BSkyblock").isPresent(); - aOneBlockEnabled = addonsManager.getAddonByName("AOneBlock").isPresent(); - - logDebugAddonInfo(); // Extracted — no longer adds nesting here - - if (!bSkyBlockEnabled && !aOneBlockEnabled) return true; - - return checkIslandPermission(block, player, islandsManager); // Extracted - } - - /** - * Logs which BentoBox addon is active when debug mode is on. - */ - private void logDebugAddonInfo() { - if (!ArmorStandEditorPlugin.instance().isDebug()) return; - - Debug logger = ArmorStandEditorPlugin.instance().debug; - - if (bSkyBlockEnabled && !aOneBlockEnabled) { - logger.log("BentoBox Protection for ASE is looking at: BSkyBlock."); - } else if (aOneBlockEnabled && !bSkyBlockEnabled) { - logger.log("BentoBox Protection for ASE is looking at: AOneBlock."); - } else if (!bSkyBlockEnabled) { - logger.log("BentoBox Protection is currently not using anything. This will automatically allow edits."); - } - } - - /** - * Checks whether the player has permission to edit on the island at the given block location. - */ - private boolean checkIslandPermission(Block block, Player player, IslandsManager islandsManager) { - Optional islandOptional = islandsManager.getIslandAt(block.getLocation()); - if (islandOptional.isEmpty()) return true; - if (islandsManager.hasIsland(block.getWorld(), player.getUniqueId())) return true; - - Island theIsland = islandOptional.get(); - if (theIsland.getRank(player.getUniqueId()) == 400) return true; - - return theIsland.isAllowed(User.getInstance(player), Flags.BREAK_BLOCKS); - } -} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/protections/BoltProtection.java b/src/main/java/io/github/rypofalem/armorstandeditor/protections/BoltProtection.java deleted file mode 100644 index f6f534702..000000000 --- a/src/main/java/io/github/rypofalem/armorstandeditor/protections/BoltProtection.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.rypofalem.armorstandeditor.protections; - -import io.github.rypofalem.armorstandeditor.ArmorStandEditorPlugin; -import io.github.rypofalem.armorstandeditor.Debug; -import org.bukkit.Bukkit; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.popcraft.bolt.BoltAPI; - -public class BoltProtection implements Protection { - - // Protection class for Bolt entity protections - // https://modrinth.com/plugin/bolt - - private final boolean boltenabled; - private Debug debug; - private ArmorStandEditorPlugin plugin; - - public BoltProtection() { - boltenabled = Bukkit.getPluginManager().isPluginEnabled("Bolt"); - this.plugin = ArmorStandEditorPlugin.instance(); - this.debug = new Debug(plugin); - debug.log("Initialized Bolt Protection for ASE. Bolt Protection is " + (boltenabled ? "enabled." : "disabled.")); - } - - @Override - public boolean checkPermission(Entity entity, Player player) { - if (!boltenabled || player.isOp() || player.hasPermission("asedit.ignoreProtection.bolt")) return true; - debug.log("Checking Bolt Protection for player " + player.getName() + " on entity " + entity.getUniqueId()); - - //Failsafe: Only use the API if the plugin is enabled, otherwise it will throw an error - BoltAPI boltAPI = Bukkit.getServer().getServicesManager().load(BoltAPI.class); - if(boltAPI == null) return true; - if (!boltAPI.isProtected(entity)) return true; - - return boltAPI.canAccess(entity, player, "interact"); - } - -} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/protections/GriefDefenderProtection.java b/src/main/java/io/github/rypofalem/armorstandeditor/protections/GriefDefenderProtection.java deleted file mode 100644 index d0f40fd68..000000000 --- a/src/main/java/io/github/rypofalem/armorstandeditor/protections/GriefDefenderProtection.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016-2023 RypoFalem - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.github.rypofalem.armorstandeditor.protections; - -import com.griefdefender.api.GriefDefender; -import com.griefdefender.api.claim.Claim; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import static com.griefdefender.api.claim.TrustTypes.BUILDER; - - -public class GriefDefenderProtection implements Protection { - - private final boolean gdEnabled; - - public GriefDefenderProtection() { - gdEnabled = Bukkit.getPluginManager().isPluginEnabled("GriefDefender"); - } - - @Override - public boolean checkPermission(Block block, Player player) { - if (!gdEnabled) return true; - if (player.isOp()) return true; - if (player.hasPermission("asedit.ignoreProtection.griefDefender")) return true; - if (player.hasPermission("griefdefender.admin.bypass.border-check")) return true; - - Location blockLoc = block.getLocation(); - if (GriefDefender.getCore().getClaimAt(blockLoc) != null) { - Claim landClaim = GriefDefender.getCore().getClaimAt(blockLoc); - - if (landClaim == null || landClaim.isWilderness() || landClaim.isAdminClaim()) { - return true; - } else - return (!landClaim.isBasicClaim() || landClaim.isUserTrusted(player.getUniqueId(), BUILDER) || landClaim.allowEdit(player.getUniqueId())); - } else { - return true; - } - } -} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/protections/LandsProtection.java b/src/main/java/io/github/rypofalem/armorstandeditor/protections/LandsProtection.java deleted file mode 100644 index 59eb33bd5..000000000 --- a/src/main/java/io/github/rypofalem/armorstandeditor/protections/LandsProtection.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016-2023 RypoFalem - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package io.github.rypofalem.armorstandeditor.protections; - -import io.github.rypofalem.armorstandeditor.ArmorStandEditorPlugin; - -import me.angeschossen.lands.api.LandsIntegration; -import me.angeschossen.lands.api.land.Area; -import me.angeschossen.lands.api.land.LandWorld; -import me.angeschossen.lands.api.player.LandPlayer; -import me.angeschossen.lands.api.role.Role; - -import org.bukkit.Bukkit; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import java.util.UUID; - -import static me.angeschossen.lands.api.flags.type.Flags.*; - -public class LandsProtection implements Protection { - private final boolean landsEnabled; - private LandsIntegration landsAPI; - - public LandsProtection() { - landsEnabled = Bukkit.getPluginManager().isPluginEnabled("Lands"); - - if (landsEnabled) - landsAPI = LandsIntegration.of(ArmorStandEditorPlugin.instance()); - } - - @Override - public boolean checkPermission(Block block, Player player) { - if (!landsEnabled || player.hasPermission("asedit.ignoreProtection.lands") || player.isOp()) return true; - - //Get the players UUID - UUID playerUUID = player.getUniqueId(); - LandPlayer landPlayer = landsAPI.getLandPlayer(playerUUID); - - //Get the world the play is in - LandWorld landWorld = landsAPI.getWorld(player.getWorld()); - - if (landWorld != null) { - - //Prep to do check for ClaimedArea - Area landAreaOfAS = landsAPI.getArea(block.getLocation()); - Area landAreaOfPlayer = landsAPI.getArea(player.getLocation()); - - if (landAreaOfAS != null) { //Block is in a Claimed Area - if (landAreaOfPlayer == landAreaOfAS) { - - //Get Visitor Role for the Area of the AS - Role visitorRole = landAreaOfAS.getVisitorRole(); - - //If Player is a Visitor - Dont allow Edits - if (landAreaOfAS.getRole(playerUUID) == visitorRole) return false; - - // If Player is Trusted OR Player is Owner of the Area/Claim, Allow Edits - if (landAreaOfAS.isTrusted(playerUUID) || landAreaOfAS.getOwnerUID() == landPlayer.getUID()) return true; - else if (landAreaOfAS.hasRoleFlag(playerUUID, BLOCK_BREAK) || - landAreaOfAS.hasRoleFlag(playerUUID, BLOCK_PLACE) || - landAreaOfAS.hasRoleFlag(playerUUID, INTERACT_CONTAINER) || - landAreaOfAS.hasRoleFlag(playerUUID, INTERACT_GENERAL)) { - - return true; - } else { // Any other case, dont allow edits - return false; - } - } else return false; //If the land areas are different - } else { //If the AS is in the Wilderness - return true; - } - } else { //if the ArmorStand is in a world - return true; - } - } -} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/protections/PlotSquaredProtection.java b/src/main/java/io/github/rypofalem/armorstandeditor/protections/PlotSquaredProtection.java deleted file mode 100644 index 4474be560..000000000 --- a/src/main/java/io/github/rypofalem/armorstandeditor/protections/PlotSquaredProtection.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016-2023 RypoFalem - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package io.github.rypofalem.armorstandeditor.protections; - -import com.plotsquared.core.PlotAPI; -import com.plotsquared.core.location.Location; -import com.plotsquared.core.player.PlotPlayer; -import com.plotsquared.core.plot.Plot; -import com.plotsquared.core.plot.PlotArea; -import com.sk89q.worldedit.math.BlockVector3; - -import org.bukkit.Bukkit; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import java.util.UUID; - -public class PlotSquaredProtection implements Protection { - - private final boolean psEnabled; - private PlotAPI plotAPI; - - public PlotSquaredProtection() { - psEnabled = Bukkit.getPluginManager().isPluginEnabled("PlotSquared"); - - if (!psEnabled) return; - } - - public boolean checkPermission(Block block, Player player) { - if (!psEnabled) return true; - if (player.isOp()) return true; - if (player.hasPermission("asedit.ignoreProtection.plotSquared")) return true; - if (plotAPI == null) plotAPI = new PlotAPI(); - - //Get the Location of the Plot - Location plotLocation = Location.at(block.getWorld().getName(), BlockVector3.at(block.getX(), block.getY(), block.getZ())); - - //Get the Area of the PLot - PlotArea area = plotLocation.getPlotArea(); - - //If the Area is not a Plot, then we assume its a road, we return if a player can build on roads or not - if (area == null) return true; - - //Get the Plot - Plot plot = area.getPlot(plotLocation); - - //Rerun the Area check - if (plot == null) - return player.hasPermission("plots.admin.build.road"); - - //Get the Player - PlotPlayer plotPlayer = plotAPI.wrapPlayer(player.getUniqueId()); - - if (plotPlayer == null) return true; - - //Get the UUID of the PlotPlayer - UUID uuid = plotPlayer.getUUID(); - - //Return if they are added to the plot or if they are OP and have the Permission to build anywhere - return plot.isAdded(uuid) || plotPlayer.hasPermission("plots.admin.build.other"); - - } -} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/protections/SkyblockProtection.java b/src/main/java/io/github/rypofalem/armorstandeditor/protections/SkyblockProtection.java deleted file mode 100644 index 30f52eca2..000000000 --- a/src/main/java/io/github/rypofalem/armorstandeditor/protections/SkyblockProtection.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016-2023 RypoFalem - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package io.github.rypofalem.armorstandeditor.protections; - -import com.bgsoftware.superiorskyblock.api.SuperiorSkyblockAPI; -import com.bgsoftware.superiorskyblock.api.island.Island; -import com.bgsoftware.superiorskyblock.api.wrappers.SuperiorPlayer; - -import org.bukkit.Bukkit; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -public class SkyblockProtection implements Protection { - private final boolean skyblockEnabled; - - public SkyblockProtection() { - //NOTE FROM AUTHOR: I know there are many plugins that have Skyblock. I am using SuperiorSkyBlock2 as an Example! - //IF YOU WANT YOUR SKYBLOCK ADDED, PLEASE SUBMIT A FEATURE REQUEST! - - skyblockEnabled = Bukkit.getPluginManager().isPluginEnabled("SuperiorSkyblock2"); - if (!skyblockEnabled) return; - } - - public boolean checkPermission(Block block, Player player) { - if (!skyblockEnabled) return true; - if (player.isOp()) return true; - if (player.hasPermission("asedit.ignoreProtection.skyblock")) return true; //Add Additional Permission - - SuperiorPlayer sp = SuperiorSkyblockAPI.getPlayer(player); - - //GET ISLAND FOR A GIVEN LOCATION - Island island = SuperiorSkyblockAPI.getIslandAt(sp.getLocation()); - if (island == null) { - return true; - } else { - return island.isMember(sp) || island.isCoop(sp) || sp.hasBypassModeEnabled(); - } - } -} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/protections/TownyProtection.java b/src/main/java/io/github/rypofalem/armorstandeditor/protections/TownyProtection.java index 329d7f85d..09c4eb4e3 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/protections/TownyProtection.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/protections/TownyProtection.java @@ -19,31 +19,24 @@ package io.github.rypofalem.armorstandeditor.protections; import io.github.rypofalem.armorstandeditor.ArmorStandEditorPlugin; -import io.github.rypofalem.armorstandeditor.Debug; import com.palmergames.bukkit.towny.event.executors.TownyActionEventExecutor; -import com.palmergames.bukkit.towny.TownyAPI; +import com.palmergames.bukkit.towny.TownyAPI; -import io.github.rypofalem.armorstandeditor.ArmorStandEditorPlugin; import io.github.rypofalem.armorstandeditor.Debug; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - +import org.bukkit.entity.*; //FIX for https://github.com/Wolfieheart/ArmorStandEditor-Issues/issues/15 public class TownyProtection implements Protection { private final boolean tEnabled; - private Debug debug; - private ArmorStandEditorPlugin plugin; + private final ArmorStandEditorPlugin plugin; public TownyProtection() { plugin = ArmorStandEditorPlugin.instance(); - debug = plugin.debug; tEnabled = Bukkit.getPluginManager().isPluginEnabled("Towny"); } @@ -56,25 +49,27 @@ public boolean checkPermission(Entity entity, Player player) { TownyAPI towny = TownyAPI.getInstance(); Location playerLoc = player.getLocation(); - // --- Get ArmorStand on the Block -- - if (!(entity instanceof ArmorStand entityOnBlock)) { - debug.log("No ArmorStand has been found therefore we will continue as intended"); - return true; - } + Material material; + if (entity instanceof ArmorStand) { + material = Material.ARMOR_STAND; + Debug.log("Editing ArmorStand: " + entity.getUniqueId()); + } else if (entity instanceof ItemFrame) { + material = entity instanceof GlowItemFrame ? Material.GLOW_ITEM_FRAME : Material.ITEM_FRAME; + Debug.log("Editing ItemFrame: " + entity.getUniqueId()); + } else return true; - debug.log("Editing ArmorStand: " + entityOnBlock.getUniqueId()); // --- wilderness checks --- if (towny.isWilderness(playerLoc)) { if (player.hasPermission("asedit.townyProtection.canEditInWild")) { - debug.log("User '" + player.getDisplayName() + "' is in the Wilderness and has the permission asedit.townyProtection.canEditInWild set to TRUE. Edits are allowed!"); + Debug.log("User '" + player.getName() + "' is in the Wilderness and has the permission asedit.townyProtection.canEditInWild set to TRUE. Edits are allowed!"); return true; } else { player.sendMessage(plugin.getLang().getMessage("townyNoWildEdit", "warn")); return false; } } - return TownyActionEventExecutor.canBuild(player, entityOnBlock.getLocation(), Material.ARMOR_STAND); + return TownyActionEventExecutor.canBuild(player, entity.getLocation(), material); } } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/protections/itemAdderProtection.java b/src/main/java/io/github/rypofalem/armorstandeditor/protections/itemAdderProtection.java deleted file mode 100644 index d9fe10ede..000000000 --- a/src/main/java/io/github/rypofalem/armorstandeditor/protections/itemAdderProtection.java +++ /dev/null @@ -1,56 +0,0 @@ -package io.github.rypofalem.armorstandeditor.protections; - -import io.github.rypofalem.armorstandeditor.ArmorStandEditorPlugin; - -import dev.lone.itemsadder.api.CustomFurniture; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import java.util.Collection; - -public class itemAdderProtection implements Protection { - private final boolean itmaddEnabled; - ArmorStandEditorPlugin plugin; - Collection entities; - ArmorStand as; - - public itemAdderProtection() { - itmaddEnabled = Bukkit.getPluginManager().isPluginEnabled("Itemadder"); - if (!itmaddEnabled) return; - } - - - @Override - public boolean checkPermission(Block block, Player player) { - if (!itmaddEnabled) return true; - if (player.isOp()) return true; - if (player.hasPermission("asedit.ignoreProtection.itemAdder")) return true; - - //Get the ArmorSTand Closest to the player at that point - World world = block.getWorld(); - entities = world.getNearbyEntities(player.getLocation(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ()); - - for (Entity e : entities) { - if (e instanceof ArmorStand stand) { - as = stand; - break; - } - } - - if (plugin.isEditTool(player.getInventory().getItemInMainHand())) { - if (CustomFurniture.byAlreadySpawned(as) == null) { - return true; - } else { - player.sendMessage(plugin.getLang().getMessage("editUsingItemAdder")); - return false; - } - } else { - return true; - } - } -} From f98913ebd5fa298481ea7f9df4e1ab207e9364dd Mon Sep 17 00:00:00 2001 From: Veyronity Date: Wed, 27 May 2026 10:22:37 +0300 Subject: [PATCH 2/2] Final cleanup --- .../rypofalem/armorstandeditor/CommandEx.java | 34 +++++++++---------- .../armorstandeditor/PlayerEditorManager.java | 2 -- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java b/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java index d35ecf62d..3b4609ff9 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java @@ -229,42 +229,40 @@ private void commandSlot(Player player, String[] args) { } private void commandAdj(Player player, String[] args) { - if (args.length == 0) { + if (args.length <= 1) { player.sendMessage(plugin.getLang().getMessage("noadjcom", "warn")); player.sendMessage(listAdjustment); + return; } - if (args.length > 1) { - for (AdjustmentMode adj : AdjustmentMode.values()) { - if (adj.toString().toLowerCase().contentEquals(args[1].toLowerCase())) { - plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAdjMode(adj); - return; - } + for (AdjustmentMode adj : AdjustmentMode.values()) { + if (adj.toString().toLowerCase().contentEquals(args[1].toLowerCase())) { + plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAdjMode(adj); + return; } - player.sendMessage(listAdjustment); } + player.sendMessage(listAdjustment); } private void commandAxis(Player player, String[] args) { - if (args.length == 0) { + if (args.length <= 1) { player.sendMessage(plugin.getLang().getMessage("noaxiscom", "warn")); player.sendMessage(listAxis); + return; } - if (args.length > 1) { - for (Axis axis : Axis.values()) { - if (axis.toString().toLowerCase().contentEquals(args[1].toLowerCase())) { - Debug.log("Player '" + player.getName() + "' sets the axis to " + axis); - plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAxis(axis); - return; - } + for (Axis axis : Axis.values()) { + if (axis.toString().toLowerCase().contentEquals(args[1].toLowerCase())) { + Debug.log("Player '" + player.getName() + "' sets the axis to " + axis); + plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAxis(axis); + return; } - player.sendMessage(listAxis); } + player.sendMessage(listAxis); } private void commandMode(Player player, String[] args) { - if (args.length == 1) { + if (args.length <= 1) { player.sendMessage(plugin.getLang().getMessage("nomodecom", "warn")); player.sendMessage(listMode); return; // early return lets us drop the second `if` entirely diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java index 1aa5f5499..1884de252 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java @@ -203,12 +203,10 @@ public void onArmorStandInteract(PlayerInteractAtEntityEvent event) { return; } - // TODO: Check dupe if (player.getInventory().getItemInMainHand().getType().equals(Material.GLOW_INK_SAC) //attempt glowing && player.hasPermission("asedit.basic") && plugin.glowItemFrames && player.isSneaking() ) { - ItemStack glowSacs = player.getInventory().getItemInMainHand(); ItemStack contents = null; Rotation rotation = null;