diff --git a/README.md b/README.md index 88fde83..2d86085 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,40 @@ -## About +# About ![](https://repo.nightexpressdev.com/api/badge/latest/releases/su/nightexpress/nightcore/nightcore?color=40c14a&name=nightcore&prefix=v) -**nightcore** is a lightweight all-in-one library-engine plugin that contains a lot of useful utilities, APIs, frameworks, wrappers and frequently used code. It was created to reduce amount of duplicated code in plugins, make plugin creation less annoying and more faster. All nightcore's features are thoroughly tested and highly optimized. The nightcore itself has no impact on server's performance, it doesn't handle or store any data. +**nightcore** is a lightweight library plugin that provides a wide set of utilities to make plugin development faster and more efficient. -All nightcore based plugins are clean and lightweight. There is no metrics, update checkers, data collectors, DRM systems or advertisements. +We always move forward and therefore use only **modern APIs** and features provided with Spigot/Paper updates. Say "no" to slow legacy code! -### Downloads & Documentation +There is **no impact** on server's performance, nightcore **doesn't** handle or store any data. + +All nightcore powered plugins are clean and lightweight. There is no metrics, update checkers, data collectors, DRM systems or advertisements. + +# Requirements +- **Java 21** or higher. + +# Downloads & Documentation - [Github Releases](https://github.com/nulli0n/nightcore-spigot/releases) - [Modrinth](https://modrinth.com/plugin/nightcore) - [Hangar](https://hangar.papermc.io/NightExpress/nightcore) - [Documentation](https://nightexpressdev.com/nightcore/) - [Developer API](https://nightexpressdev.com/nightcore/developer-api/) -## Donate -If you like my work or enjoy using my plugins, feel free to [Buy me a coffee](https://ko-fi.com/nightexpress) :) Thank you! 🧡 +# Plugins +Plugins powered by **nightcore**. + +- [EconomyBridge](https://nightexpressdev.com/economy-bridge/) +- [AdvancedDungeonArena](https://nightexpressdev.com/dungeon-arena/) +- [CoinsEngine](https://nightexpressdev.com/coinsengine/) +- [CombatPets](https://www.spigotmc.org/resources/100360/) +- [ExcellentClaims](https://www.spigotmc.org/resources/119848/) +- [ExcellentChallenges](https://www.spigotmc.org/resources/107283/) +- [ExcellentCrates](https://nightexpressdev.com/excellentcrates/) +- [ExcellentEnchants](https://www.spigotmc.org/resources/61693/) +- [ExcellentJobs](https://www.spigotmc.org/resources/114783/) +- [ExcellentShop](https://www.spigotmc.org/resources/50696/) +- [LootConomy](https://www.spigotmc.org/resources/83994/) +- [SkillMeUp](https://www.spigotmc.org/resources/93015/) +- [SunLight](https://www.spigotmc.org/resources/67733/) + +# Donate +If you like my work or enjoy using my plugins, feel free to [Buy me a coffee](https://ko-fi.com/nightexpress) :) Thank you! 🧡 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8888150..bc81c33 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ su.nightexpress.nightcore nightcore - 2.7.4 + 2.7.5 21 @@ -64,7 +64,7 @@ io.papermc.paper paper-api - 1.21.4-R0.1-SNAPSHOT + 1.21.5-R0.1-SNAPSHOT provided diff --git a/src/main/java/su/nightexpress/nightcore/NightCore.java b/src/main/java/su/nightexpress/nightcore/NightCore.java index 6c09b43..8c169bd 100644 --- a/src/main/java/su/nightexpress/nightcore/NightCore.java +++ b/src/main/java/su/nightexpress/nightcore/NightCore.java @@ -10,6 +10,7 @@ import su.nightexpress.nightcore.core.CorePerms; import su.nightexpress.nightcore.core.command.CoreCommands; import su.nightexpress.nightcore.integration.VaultHook; import su.nightexpress.nightcore.language.LangAssets; +import su.nightexpress.nightcore.ui.UIUtils; import su.nightexpress.nightcore.util.Plugins; import su.nightexpress.nightcore.util.TimeUtil; import su.nightexpress.nightcore.util.Version; @@ -45,6 +46,7 @@ public class NightCore extends NightPlugin implements ImprovedCommands { public void enable() { Tags.loadColorsFromFile(this); LangAssets.load(this); + UIUtils.load(this); this.loadIntegrations(); this.loadCommands(); this.info("Time zone set as " + TimeUtil.getTimeZone().getID()); @@ -59,6 +61,7 @@ public class NightCore extends NightPlugin implements ImprovedCommands { if (Plugins.hasVault()) { VaultHook.shutdown(); } + UIUtils.clear(); PlayerBlockTracker.shutdown(); LangAssets.shutdown(); } diff --git a/src/main/java/su/nightexpress/nightcore/api/event/PlayerOpenMenuEvent.java b/src/main/java/su/nightexpress/nightcore/api/event/PlayerOpenMenuEvent.java index 03c8419..428b7b2 100644 --- a/src/main/java/su/nightexpress/nightcore/api/event/PlayerOpenMenuEvent.java +++ b/src/main/java/su/nightexpress/nightcore/api/event/PlayerOpenMenuEvent.java @@ -7,6 +7,7 @@ import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.menu.api.Menu; +@Deprecated public class PlayerOpenMenuEvent extends Event implements Cancellable { public static final HandlerList HANDLER_LIST = new HandlerList(); diff --git a/src/main/java/su/nightexpress/nightcore/command/CommandFlag.java b/src/main/java/su/nightexpress/nightcore/command/CommandFlag.java index cac45fb..693ba63 100644 --- a/src/main/java/su/nightexpress/nightcore/command/CommandFlag.java +++ b/src/main/java/su/nightexpress/nightcore/command/CommandFlag.java @@ -3,7 +3,6 @@ package su.nightexpress.nightcore.command; import org.bukkit.Bukkit; import org.bukkit.World; import org.jetbrains.annotations.NotNull; -import su.nightexpress.nightcore.util.Colorizer; import su.nightexpress.nightcore.util.NumberUtil; import java.util.function.Function; @@ -33,7 +32,7 @@ public class CommandFlag { @NotNull public static CommandFlag textFlag(@NotNull String name) { - return new CommandFlag<>(name, Colorizer::apply); + return new CommandFlag<>(name, s -> s); } @NotNull diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/CommandContext.java b/src/main/java/su/nightexpress/nightcore/command/experimental/CommandContext.java index 082464b..cc0ba32 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/CommandContext.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/CommandContext.java @@ -7,7 +7,11 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.NightCorePlugin; import su.nightexpress.nightcore.core.CoreLang; +import su.nightexpress.nightcore.language.entry.LangText; import su.nightexpress.nightcore.language.message.LangMessage; +import su.nightexpress.nightcore.util.placeholder.Replacer; + +import java.util.function.Consumer; public class CommandContext { @@ -32,25 +36,45 @@ public class CommandContext { this.sender.sendMessage(string); } + @Deprecated public boolean sendSuccess(@NotNull String string) { this.send(string); return true; } + @Deprecated public boolean sendFailure(@NotNull String string) { this.send(string); return false; } - public void send(@NotNull LangMessage message) { - message.send(this.sender); + public void send(@NotNull LangText text) { + this.send(text, null); } + public void send(@NotNull LangText text, @Nullable Consumer consumer) { + this.send(text.getMessage(), consumer); + } + + public void send(@NotNull LangMessage message) { + this.send(message, null); + } + + public void send(@NotNull LangMessage message, @Nullable Consumer consumer) { + message.send(this.sender, consumer); + } + +// public void send(@NotNull LangMessage message) { +// message.send(this.sender); +// } + + @Deprecated public boolean sendSuccess(@NotNull LangMessage message) { this.send(message); return true; } + @Deprecated public boolean sendFailure(@NotNull LangMessage message) { this.send(message); return false; @@ -69,7 +93,7 @@ public class CommandContext { } public int getArgumentIndex() { - return argumentIndex; + return this.argumentIndex; } public void setArgumentIndex(int argumentIndex) { @@ -78,12 +102,12 @@ public class CommandContext { @NotNull public CommandSender getSender() { - return sender; + return this.sender; } @Nullable public Player getExecutor() { - return executor; + return this.executor; } @NotNull @@ -99,11 +123,11 @@ public class CommandContext { @NotNull public String getLabel() { - return label; + return this.label; } public String[] getArgs() { - return args; + return this.args; } public void errorPermission() { diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/RootCommand.java b/src/main/java/su/nightexpress/nightcore/command/experimental/RootCommand.java index 6ed4218..db7d65f 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/RootCommand.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/RootCommand.java @@ -81,11 +81,9 @@ public class RootCommand

imple } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (args.length == 0) return Collections.emptyList(); - //int index = 0;//args.length - 1; - //String input = args[index]; TabContext context = new TabContext(sender, label, args, 0); List samples = this.node.getTab(context); diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/TabContext.java b/src/main/java/su/nightexpress/nightcore/command/experimental/TabContext.java index c664a62..2e37040 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/TabContext.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/TabContext.java @@ -4,6 +4,11 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.command.experimental.argument.CommandArgument; +import su.nightexpress.nightcore.command.experimental.flag.CommandFlag; + +import java.util.HashMap; +import java.util.Map; public class TabContext { @@ -12,24 +17,71 @@ public class TabContext { private final String label; private final String[] args; - private int index; + private final Map argumentCache; + private final Map flagCache; - public TabContext(@NotNull CommandSender sender, @NotNull String label, String[] args, int index) { + private int lastCommandIndex; + + public TabContext(@NotNull CommandSender sender, @NotNull String label, String[] args, int lastCommandIndex) { this.sender = sender; this.player = sender instanceof Player user ? user : null; this.label = label; this.args = args; - this.index = index; + this.lastCommandIndex = lastCommandIndex; + + this.argumentCache = new HashMap<>(); + this.flagCache = new HashMap<>(); + } + + public int length() { + return this.args.length; + } + + public boolean hasCachedArgument(@NotNull CommandArgument argument) { + return this.argumentCache.containsKey(argument.getName()); + } + + public boolean hasCachedFlag(@NotNull CommandFlag flag) { + return this.flagCache.containsKey(flag.getName()); + } + + public void cacheArgument(@NotNull CommandArgument argument, @NotNull String value) { + this.argumentCache.put(argument.getName(), value); + } + + public void cacheFlag(@NotNull CommandFlag flag, @NotNull String value) { + this.flagCache.put(flag.getName(), value); + } + + public void appendArgumentCache(@NotNull CommandArgument argument, @NotNull String value) { + String cached = this.getCachedArgument(argument.getName()); + cached = cached == null ? value : cached + " " + value; + this.cacheArgument(argument, cached); + } + + @Nullable + public String getCachedArgument(@NotNull String name) { + return this.argumentCache.get(name.toLowerCase()); + } + + @Nullable + public String getCachedFlag(@NotNull String name) { + return this.flagCache.get(name.toLowerCase()); + } + + @NotNull + public String getArg(int index) { + return this.args[index]; } @NotNull public CommandSender getSender() { - return sender; + return this.sender; } @Nullable public Player getPlayer() { - return player; + return this.player; } @NotNull @@ -41,27 +93,48 @@ public class TabContext { @NotNull public String getLabel() { - return label; + return this.label; } @NotNull public String[] getArgs() { - return args; + return this.args; } + @Deprecated public int getIndex() { - return index; + return this.getLastCommandIndex(); } + @Deprecated public void setIndex(int index) { - this.index = index; + this.setLastCommandIndex(index); } + public int getLastCommandIndex() { + return this.lastCommandIndex; + } + + public void setLastCommandIndex(int index) { + this.lastCommandIndex = index; + } + + @Deprecated public String getAtIndex() { - return this.args[this.index]; + return this.args[this.lastCommandIndex]; } public String getInput() { return this.args[this.args.length - 1]; } + + @NotNull + public Map getArgumentCache() { + return this.argumentCache; + } + + @NotNull + public Map getFlagCache() { + return this.flagCache; + } } diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/argument/CommandArgument.java b/src/main/java/su/nightexpress/nightcore/command/experimental/argument/CommandArgument.java index 642d0b0..7d1f9be 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/argument/CommandArgument.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/argument/CommandArgument.java @@ -3,6 +3,7 @@ package su.nightexpress.nightcore.command.experimental.argument; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.NightCorePlugin; import su.nightexpress.nightcore.command.experimental.CommandContext; import su.nightexpress.nightcore.command.experimental.TabContext; import su.nightexpress.nightcore.command.experimental.builder.ArgumentBuilder; @@ -47,7 +48,6 @@ public class CommandArgument { @NotNull @Deprecated public static ArgumentBuilder builder(@NotNull String name, @NotNull Function parser) { -// return new ArgumentBuilder<>(name, parser); return builder(name, (string, context) -> parser.apply(string)); } @@ -83,26 +83,32 @@ public class CommandArgument { } @NotNull + @Deprecated public LangMessage getFailureMessage() { return this.failureMessage == null ? CoreLang.ERROR_COMMAND_PARSE_ARGUMENT.getMessage() : this.failureMessage; } + @NotNull + public LangMessage getFailureMessage(@NotNull NightCorePlugin plugin) { + return this.failureMessage == null ? CoreLang.ERROR_COMMAND_PARSE_ARGUMENT.getMessage(plugin) : this.failureMessage.setPrefix(plugin); + } + @NotNull public String getName() { - return name; + return this.name; } @NotNull public ArgumentParser getParser() { - return parser; + return this.parser; } public boolean isRequired() { - return required; + return this.required; } public boolean isComplex() { - return complex; + return this.complex; } @NotNull @@ -112,11 +118,11 @@ public class CommandArgument { @Nullable public String getPermission() { - return permission; + return this.permission; } @NotNull public Function> getSamples() { - return samples; + return this.samples; } } diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/impl/ReloadCommand.java b/src/main/java/su/nightexpress/nightcore/command/experimental/impl/ReloadCommand.java index 0459890..9c963fb 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/impl/ReloadCommand.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/impl/ReloadCommand.java @@ -27,6 +27,7 @@ public class ReloadCommand { public static boolean execute(@NotNull NightCorePlugin plugin, @NotNull CommandContext context, @NotNull ParsedArguments arguments) { plugin.reload(); - return context.sendSuccess(CoreLang.COMMAND_RELOAD_DONE.getMessage(plugin)); + context.send(CoreLang.COMMAND_RELOAD_DONE.getMessage(plugin)); + return true; } } diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/node/ChainedNode.java b/src/main/java/su/nightexpress/nightcore/command/experimental/node/ChainedNode.java index c05357b..78f91b5 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/node/ChainedNode.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/node/ChainedNode.java @@ -18,7 +18,8 @@ public class ChainedNode extends CommandNode { private final String localized; private final Map commandMap; - private NodeExecutor fallback; + + private NodeExecutor fallback; public ChainedNode(@NotNull NightCorePlugin plugin, @NotNull String name, @@ -50,21 +51,16 @@ public class ChainedNode extends CommandNode { @Override protected boolean onRun(@NotNull CommandContext context) { - //System.out.println("context.getArgs() = " + Arrays.toString(context.getArgs())); - if (context.getArgs().length == 0 || context.getArgumentIndex() >= context.getArgs().length) { + if (context.length() == 0 || context.getArgumentIndex() >= context.length()) { return this.onFallback(context); } String node = context.getArgs()[context.getArgumentIndex()]; - //System.out.println("node = " + node); - CommandNode children = this.getCommandMap().get(node); - //System.out.println("children = " + children); - //System.out.println("this.commandMap = " + this.commandMap); + CommandNode children = this.commandMap.get(node); if (children == null) { return this.onFallback(context); } - //System.out.println("children run"); context.setArgumentIndex(context.getArgumentIndex() + 1); return children.run(context); } @@ -83,8 +79,8 @@ public class ChainedNode extends CommandNode { private boolean sendCommandList(@NotNull CommandContext context) { CommandSender sender = context.getSender(); - return context.sendSuccess(CoreLang.COMMAND_HELP_LIST.getMessage() - .replace(Placeholders.GENERIC_NAME, this.getLocalized()) + context.send(CoreLang.COMMAND_HELP_LIST.getMessage(), replacer -> replacer + .replace(Placeholders.GENERIC_NAME, this.localized) .replace(Placeholders.GENERIC_ENTRY, list -> { this.getChildrens().stream().sorted(Comparator.comparing(CommandNode::getName)).forEach(children -> { if (!children.hasPermission(sender)) return; @@ -96,28 +92,27 @@ public class ChainedNode extends CommandNode { ); }); })); + + return true; } @Override @NotNull public List getTab(@NotNull TabContext context) { - //System.out.println("context.getArgs() = " + Arrays.toString(context.getArgs())); - //System.out.println("context.getIndex() = " + context.getIndex()); - if (context.getIndex() == context.getArgs().length - 1) { + int index = context.getLastCommandIndex(); + + if (index == context.length() - 1) { return this.getChildrens().stream().filter(node -> node.hasPermission(context.getSender())).map(CommandNode::getName).toList(); - //return new ArrayList<>(this.commandMap.keySet()); } - if (context.getIndex() >= context.getArgs().length) { + if (index >= context.length()) { return Collections.emptyList(); } - String node = context.getAtIndex(); - CommandNode children = this.getCommandMap().get(node); - if (children == null) { - return Collections.emptyList(); - } + String node = context.getArg(index); + CommandNode children = this.commandMap.get(node); + if (children == null) return Collections.emptyList(); - context.setIndex(context.getIndex() + 1); + context.setLastCommandIndex(index + 1); return children.getTab(context); } @@ -152,11 +147,11 @@ public class ChainedNode extends CommandNode { @NotNull public String getLocalized() { - return localized; + return this.localized; } @NotNull public Map getCommandMap() { - return commandMap; + return this.commandMap; } } diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/node/DirectNode.java b/src/main/java/su/nightexpress/nightcore/command/experimental/node/DirectNode.java index 3adcfc6..65acc98 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/node/DirectNode.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/node/DirectNode.java @@ -13,6 +13,7 @@ import su.nightexpress.nightcore.command.experimental.builder.DirectNodeBuilder; import su.nightexpress.nightcore.command.experimental.flag.CommandFlag; import su.nightexpress.nightcore.command.experimental.flag.ContentFlag; import su.nightexpress.nightcore.core.CoreLang; +import su.nightexpress.nightcore.util.Lists; import su.nightexpress.nightcore.util.Placeholders; import java.util.*; @@ -73,17 +74,7 @@ public class DirectNode extends CommandNode implements DirectExecutor { String arg; // must be last. if (argument.isComplex()) { - /*StringBuilder builder = new StringBuilder(); - for (int textIndex = index; textIndex < args.length; textIndex++) { - String text = args[textIndex]; - if (text.charAt(0) == CommandFlag.PREFIX) break; - - if (!builder.isEmpty()) builder.append(" "); - builder.append(text); - - index++; - }*/ - arg = /*builder.toString();*/Stream.of(args).skip(index).collect(Collectors.joining(" ")); + arg = Stream.of(args).skip(index).collect(Collectors.joining(" ")); } else { arg = args[index++]; @@ -92,20 +83,22 @@ public class DirectNode extends CommandNode implements DirectExecutor { //String ParsedArgument parsedArgument = argument.parse(arg, context); if (parsedArgument == null) { - return context.sendFailure(argument.getFailureMessage() + context.send(argument.getFailureMessage(this.plugin), replacer -> replacer .replace(Placeholders.GENERIC_VALUE, arg) .replace(Placeholders.GENERIC_NAME, argument.getLocalized()) ); + return false; } parsedArguments.add(argument, parsedArgument); } if (parsedArguments.getArgumentMap().size() < this.requiredArguments) { - return context.sendFailure(CoreLang.ERROR_COMMAND_USAGE.getMessage(this.plugin) + context.send(CoreLang.ERROR_COMMAND_USAGE.getMessage(this.plugin), replacer -> replacer .replace(Placeholders.COMMAND_LABEL, this.getNameWithParents()) .replace(Placeholders.COMMAND_USAGE, this.getUsage()) .replace(Placeholders.COMMAND_DESCRIPTION, this.getDescription())); + return false; } if (!this.flags.isEmpty() && index < args.length) { @@ -128,7 +121,7 @@ public class DirectNode extends CommandNode implements DirectExecutor { ParsedArgument parsed = contentFlag.parse(content, context); if (parsed == null) { - context.send(CoreLang.ERROR_COMMAND_PARSE_FLAG.getMessage() + context.send(CoreLang.ERROR_COMMAND_PARSE_FLAG.getMessage(this.plugin), replacer -> replacer .replace(Placeholders.GENERIC_VALUE, content) .replace(Placeholders.GENERIC_NAME, flag.getName()) ); @@ -151,32 +144,84 @@ public class DirectNode extends CommandNode implements DirectExecutor { public List getTab(@NotNull TabContext context) { if (this.isPlayerOnly() && context.getPlayer() == null) return Collections.emptyList(); - int index = context.getArgs().length - (context.getIndex() + 1); - //System.out.println("index = " + index); - //System.out.println("arguments.size() = " + arguments.size()); - if (index >= this.arguments.size()) { - if (!this.arguments.isEmpty()) { - CommandArgument latestArgument = this.arguments.get(this.arguments.size() - 1); - if (latestArgument.isComplex()) return this.getArgumentSamples(latestArgument, context); + int firstArgIndex = context.getLastCommandIndex(); + int tabLength = context.length(); + int argIndex = 0; + List samples = new ArrayList<>(); + + //System.out.println("firstArgIndex = " + firstArgIndex); + //System.out.println("context.getArgs() = " + Arrays.toString(context.getArgs())); + + for (int tabIndex = firstArgIndex; tabIndex < tabLength; tabIndex++) { + String tabValue = context.getArg(tabIndex); + boolean lastIndex = tabIndex == tabLength - 1; + + if (argIndex >= this.arguments.size()) { + if (!this.arguments.isEmpty()) { + CommandArgument lastArgument = this.arguments.getLast(); + if (lastArgument.isComplex()) { + if (lastIndex) samples = this.getArgumentSamples(lastArgument, context); + context.appendArgumentCache(lastArgument, tabValue); + } + } + + for (CommandFlag commandFlag : this.getFlags()) { + if (context.hasCachedFlag(commandFlag)) continue; + if (!commandFlag.hasPermission(context.getSender())) continue; + + if (lastIndex) { + if (commandFlag instanceof ContentFlag contentFlag) { + samples = Lists.newList(contentFlag.getSampled()); + } + else { + samples = Lists.newList(commandFlag.getPrefixed()); + } + } + context.cacheFlag(commandFlag, tabValue); + } } + else { + CommandArgument argument = this.arguments.get(argIndex++); - List samples = new ArrayList<>(); + context.cacheArgument(argument, tabValue); - this.getFlags().forEach(commandFlag -> { - if (!commandFlag.hasPermission(context.getSender())) return; - if (commandFlag instanceof ContentFlag contentFlag) { - samples.add(contentFlag.getSampled()); + if (lastIndex) { + samples = this.getArgumentSamples(argument, context); } - else { - samples.add(commandFlag.getPrefixed()); - } - }); - - return samples; + } } - CommandArgument argument = this.arguments.get(index); - return this.getArgumentSamples(argument, context); + //System.out.println("context.getArgumentData() = " + context.getArgumentData()); + //System.out.println("context.getFlagData() = " + context.getFlagData()); + + return samples; + +// int index = context.getArgs().length - (context.getIndex() + 1); +// //System.out.println("index = " + index); +// //System.out.println("arguments.size() = " + arguments.size()); +// if (index >= this.arguments.size()) { +// if (!this.arguments.isEmpty()) { +// CommandArgument lastArgument = this.arguments.getLast(); +// if (lastArgument.isComplex()) return this.getArgumentSamples(lastArgument, context); +// } +// +// List samples = new ArrayList<>(); +// +// this.getFlags().forEach(commandFlag -> { +// if (!commandFlag.hasPermission(context.getSender())) return; +// if (commandFlag instanceof ContentFlag contentFlag) { +// samples.add(contentFlag.getSampled()); +// } +// else { +// samples.add(commandFlag.getPrefixed()); +// } +// }); +// +// return samples; +// } +// +// CommandArgument argument = this.arguments.get(index); +// return this.getArgumentSamples(argument, context); } private List getArgumentSamples(@NotNull CommandArgument argument, @NotNull TabContext context) { diff --git a/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java b/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java index 1d0ecaf..f321663 100644 --- a/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java +++ b/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java @@ -387,38 +387,38 @@ public class ConfigValue { @NotNull public static ConfigValue> forMapById(@NotNull String path, - @NotNull BiFunction valReadFun, - @NotNull Consumer> defaultValue, - @Nullable String... description) { + @NotNull BiFunction valReadFun, + @NotNull Consumer> defaultValue, + @Nullable String... description) { //return forMap(path, String::toLowerCase, key -> key, valReadFun, defaultValue, description); return forMapById(path, (cfg, path2, id) -> valReadFun.apply(cfg, path2), defaultValue, description); } @NotNull public static ConfigValue> forMapById(@NotNull String path, - @NotNull ReadFunction valReadFun, - @NotNull Consumer> defaultValue, - @Nullable String... description) { + @NotNull ReadFunction valReadFun, + @NotNull Consumer> defaultValue, + @Nullable String... description) { return forMap(path, String::toLowerCase, key -> key, valReadFun, defaultValue, description); } @NotNull - public static , V extends Writeable> ConfigValue> forMapByEnum(@NotNull String path, - @NotNull Class clazz, - @NotNull BiFunction valReadFun, - @NotNull Consumer> defaultValue, - @Nullable String... description) { + public static , V> ConfigValue> forMapByEnum(@NotNull String path, + @NotNull Class clazz, + @NotNull BiFunction valReadFun, + @NotNull Consumer> defaultValue, + @Nullable String... description) { //return forMap(path, str -> StringUtil.getEnum(str, clazz).orElse(null), Enum::name, valReadFun, defaultValue, description); return forMapByEnum(path, clazz, (cfg, path2, id) -> valReadFun.apply(cfg, path2), defaultValue, description); } @NotNull - public static , V extends Writeable> ConfigValue> forMapByEnum(@NotNull String path, - @NotNull Class clazz, - @NotNull ReadFunction valReadFun, - @NotNull Consumer> defaultValue, - @Nullable String... description) { + public static , V> ConfigValue> forMapByEnum(@NotNull String path, + @NotNull Class clazz, + @NotNull ReadFunction valReadFun, + @NotNull Consumer> defaultValue, + @Nullable String... description) { return forMap(path, str -> StringUtil.getEnum(str, clazz).orElse(null), Enum::name, valReadFun, defaultValue, description); } diff --git a/src/main/java/su/nightexpress/nightcore/config/FileConfig.java b/src/main/java/su/nightexpress/nightcore/config/FileConfig.java index 4da52d9..ad39bf0 100644 --- a/src/main/java/su/nightexpress/nightcore/config/FileConfig.java +++ b/src/main/java/su/nightexpress/nightcore/config/FileConfig.java @@ -213,6 +213,7 @@ public class FileConfig extends YamlConfiguration { public String getString(@NotNull String path) { String str = super.getString(path); return str == null || str.isEmpty() ? null : str; +// return super.getString(path); } @Override diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java b/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java index ad816ca..9829ab1 100644 --- a/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java +++ b/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java @@ -13,6 +13,8 @@ import java.util.TimeZone; public class CoreConfig { + public static final String DIR_UI = "/ui/"; + @Deprecated public static final ConfigValue DATA_FIXER_ENABLED = ConfigValue.create("DataFixer.Enabled", false, diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreLang.java b/src/main/java/su/nightexpress/nightcore/core/CoreLang.java index b8ceac8..a8e4ebc 100644 --- a/src/main/java/su/nightexpress/nightcore/core/CoreLang.java +++ b/src/main/java/su/nightexpress/nightcore/core/CoreLang.java @@ -1,12 +1,12 @@ package su.nightexpress.nightcore.core; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.dialog.Dialog; import su.nightexpress.nightcore.language.entry.*; import su.nightexpress.nightcore.ui.dialog.DialogManager; import su.nightexpress.nightcore.ui.menu.click.ClickKey; +import su.nightexpress.nightcore.util.bridge.wrapper.ClickEventType; +import su.nightexpress.nightcore.util.bridge.wrapper.HoverEventType; import static su.nightexpress.nightcore.util.Placeholders.*; import static su.nightexpress.nightcore.util.text.tag.Tags.*; @@ -156,8 +156,8 @@ public class CoreLang { "", GRAY.enclose("Click " + CLICK.enclose( - HOVER.enclose(GREEN.enclose("[Here]"), HoverEvent.Action.SHOW_TEXT, GRAY.enclose("Click to cancel")), - ClickEvent.Action.RUN_COMMAND, "/" + Dialog.EXIT + HOVER.enclose(GREEN.enclose("[Here]"), HoverEventType.SHOW_TEXT, GRAY.enclose("Click to cancel")), + ClickEventType.RUN_COMMAND, "/" + Dialog.EXIT ) + " to leave input mode."), ""); @@ -172,8 +172,8 @@ public class CoreLang { TAG_NO_PREFIX, "", GRAY.enclose("Click " + - CLICK.encloseRun( - HOVER.encloseHint(GREEN.enclose("[Here]"), GRAY.enclose("Click to cancel.")), + CLICK.wrapRunCommand( + HOVER.wrapShowText(GREEN.enclose("[Here]"), GRAY.enclose("Click to cancel.")), "/" + DialogManager.EXIT ) + " to leave input mode."), diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java b/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java index 27b871b..b57cf68 100644 --- a/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java +++ b/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java @@ -341,7 +341,11 @@ public abstract class AbstractUserManager

items = values.stream().skip(skip).limit(perPage).toList(); - ClickEvent.Action action = autoRun ? ClickEvent.Action.RUN_COMMAND : ClickEvent.Action.SUGGEST_COMMAND; + ClickEventType action = autoRun ? ClickEventType.RUN_COMMAND : ClickEventType.SUGGEST_COMMAND; StringBuilder builder = new StringBuilder() .append(ORANGE.enclose("=".repeat(8) + "[ " + YELLOW.enclose("Value Helper") + " ]" + "=".repeat(8))) @@ -110,7 +110,7 @@ public class Dialog { String hoverHint = GRAY.enclose("Click me to select " + CYAN.enclose(element) + "."); String clickCommand = element.charAt(0) == '/' ? element : '/' + element; - builder.append(DARK_GRAY.enclose("> ")).append(GREEN.enclose(HOVER.encloseHint(CLICK.enclose(element, action, clickCommand), hoverHint))); + builder.append(DARK_GRAY.enclose("> ")).append(GREEN.enclose(HOVER.wrapShowText(CLICK.enclose(element, action, clickCommand), hoverHint))); builder.append(Placeholders.TAG_LINE_BREAK); }); @@ -120,7 +120,7 @@ public class Dialog { builder.append(GRAY.enclose("[<]")); } else { - builder.append(LIGHT_RED.enclose(HOVER.encloseHint(CLICK.encloseRun("[<]", "/" + VALUES + " " + (page - 1) + " " + autoRun), GRAY.enclose("Previous Page")))); + builder.append(LIGHT_RED.enclose(HOVER.wrapShowText(CLICK.wrapRunCommand("[<]", "/" + VALUES + " " + (page - 1) + " " + autoRun), GRAY.enclose("Previous Page")))); } builder.append(YELLOW.enclose(" " + page)); @@ -131,7 +131,7 @@ public class Dialog { builder.append(GRAY.enclose("[>]")); } else { - builder.append(LIGHT_RED.enclose(HOVER.encloseHint(CLICK.encloseRun("[>]", "/" + VALUES + " " + (page + 1) + " " + autoRun), GRAY.enclose("Next Page")))); + builder.append(LIGHT_RED.enclose(HOVER.wrapShowText(CLICK.wrapRunCommand("[>]", "/" + VALUES + " " + (page + 1) + " " + autoRun), GRAY.enclose("Next Page")))); } diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java index 11ebc7b..e807a35 100644 --- a/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java @@ -57,7 +57,7 @@ public class LangText extends LangEntry { @NotNull public LangMessage getMessage(@NotNull NightCorePlugin plugin) { - return this.message.setPrefix(plugin.getPrefix()); + return this.message.setPrefix(plugin); } public void setMessage(@NotNull LangMessage message) { diff --git a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java index 328871d..3bdd4db 100644 --- a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java +++ b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java @@ -8,13 +8,16 @@ import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.NightCorePlugin; import su.nightexpress.nightcore.language.tag.MessageTag; import su.nightexpress.nightcore.language.tag.MessageTags; -import su.nightexpress.nightcore.util.*; +import su.nightexpress.nightcore.util.NumberUtil; +import su.nightexpress.nightcore.util.Placeholders; +import su.nightexpress.nightcore.util.Players; +import su.nightexpress.nightcore.util.StringUtil; import su.nightexpress.nightcore.util.bukkit.NightSound; import su.nightexpress.nightcore.util.placeholder.Replacer; import su.nightexpress.nightcore.util.text.NightMessage; import su.nightexpress.nightcore.util.text.TextRoot; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.Tags; -import su.nightexpress.nightcore.util.text.tag.api.Tag; import java.util.ArrayList; import java.util.List; @@ -45,6 +48,11 @@ public class LangMessage { // } } + @NotNull + public LangMessage setPrefix(@NotNull NightCorePlugin plugin) { + return this.setPrefix(plugin.getPrefix()); + } + @NotNull public LangMessage setPrefix(@Nullable String prefix) { boolean init = this.message == null; @@ -124,12 +132,12 @@ public class LangMessage { char letter = string.charAt(index); Tag: - if (letter == Tag.OPEN_BRACKET && index != (length - 1)) { - int indexEnd = TextRoot.indexOfIgnoreEscaped(string, Tag.CLOSE_BRACKET, index); + if (letter == TagUtils.OPEN_BRACKET && index != (length - 1)) { + int indexEnd = TextRoot.indexOfIgnoreEscaped(string, TagUtils.CLOSE_BRACKET, index); if (indexEnd == -1) break Tag; char next = string.charAt(index + 1); - if (next == Tag.CLOSE_BRACKET) break Tag; + if (next == TagUtils.CLOSE_BRACKET) break Tag; String bracketsContent = string.substring(index + 1, indexEnd); @@ -140,7 +148,7 @@ public class LangMessage { int semicolonIndex = bracketsContent.indexOf(':'); if (semicolonIndex >= 0) { tagName = bracketsContent.substring(0, semicolonIndex); - tagContent = TextRoot.stripQuotesSlash(bracketsContent.substring(semicolonIndex + 1)); + tagContent = TagUtils.unquoted(bracketsContent.substring(semicolonIndex + 1)); } MessageTag tag = MessageTags.getTag(tagName); @@ -236,15 +244,10 @@ public class LangMessage { } public void broadcast() { -// if (this.isDisabled()) return; -// -// this.plugin.getServer().getOnlinePlayers().forEach(this::send); -// this.send(this.plugin.getServer().getConsoleSender()); -// - this.broadcast(replacer -> {}); + this.broadcast(null); } - public void broadcast(@NotNull Consumer consumer) { + public void broadcast(@Nullable Consumer consumer) { if (this.isDisabled()) return; Players.getOnline().forEach(player -> this.send(player, consumer)); @@ -253,34 +256,9 @@ public class LangMessage { public void send(@NotNull CommandSender sender) { this.send(sender, replacer -> {}); -// -// if (this.isDisabled()) return; -// -// if (this.options.getSound() != null && sender instanceof Player player) { -// UniSound.of(this.options.getSound()).play(player); -// } -// -// if (this.options.getOutputType() == OutputType.CHAT) { -// this.getMessage(sender).send(sender); -// return; -// } -// -// if (sender instanceof Player player) { -// if (this.options.getOutputType() == OutputType.ACTION_BAR) { -// Players.sendActionBar(player, this.getMessage(player)); -// } -// else if (this.options.getOutputType() == OutputType.TITLES) { -// String[] split = Tags.LINE_BREAK.split(this.getMessage(sender).getString()); -// -// String title = NightMessage.asLegacy(split[0]); -// String subtitle = split.length >= 2 ? NightMessage.asLegacy(split[1]) : ""; -// -// player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]); -// } -// } } - public void send(@NotNull CommandSender sender, @NotNull Consumer consumer) { + public void send(@NotNull CommandSender sender, @Nullable Consumer consumer) { if (this.isDisabled()) return; if (this.options.getSound() != null && sender instanceof Player player) { @@ -288,7 +266,7 @@ public class LangMessage { } Replacer replacer = new Replacer(); - consumer.accept(replacer); + if (consumer != null) consumer.accept(replacer); if (this.options.usePlaceholderAPI() && sender instanceof Player player) { replacer.replacePlaceholderAPI(player); } @@ -307,10 +285,11 @@ public class LangMessage { else if (this.options.getOutputType() == OutputType.TITLES) { String[] split = Tags.LINE_BREAK.split(message.getString()); - String title = NightMessage.asLegacy(split[0]); - String subtitle = split.length >= 2 ? NightMessage.asLegacy(split[1]) : ""; + String title = split[0];//NightMessage.asLegacy(split[0]); + String subtitle = split.length >= 2 ? split[1]/*NightMessage.asLegacy(split[1])*/ : ""; - player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]); + //player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]); + Players.sendTitle(player, title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]); } } } diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/MessageTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/MessageTag.java index 7a12519..f5a3fa3 100644 --- a/src/main/java/su/nightexpress/nightcore/language/tag/MessageTag.java +++ b/src/main/java/su/nightexpress/nightcore/language/tag/MessageTag.java @@ -3,6 +3,7 @@ package su.nightexpress.nightcore.language.tag; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.language.message.MessageOptions; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.api.Tag; public abstract class MessageTag extends Tag { @@ -16,8 +17,14 @@ public abstract class MessageTag extends Tag { } @NotNull + @Deprecated public String enclose(@NotNull String content) { - return brackets(this.getName() + ":\"" + content + "\""); + return this.wrap(content);//brackets(this.getName() + ":\"" + content + "\""); + } + + @NotNull + public String wrap(@NotNull String content) { + return TagUtils.brackets(this.getName() + TagUtils.SEMICOLON + TagUtils.quoted(content));// ":\"" + content + "\""); } public abstract void apply(@NotNull MessageOptions options, @Nullable String tagContent); diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java index 6f9bc9a..82f1067 100644 --- a/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java +++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java @@ -15,18 +15,35 @@ public class OutputTag extends MessageTag { } @NotNull + @Deprecated public String enclose(@NotNull OutputType type) { - String prefix = type.name().toLowerCase(); + //String prefix = type.name().toLowerCase(); - return this.enclose(prefix); + return this.wrap(type);//this.enclose(prefix); } @NotNull + @Deprecated public String enclose(int fade, int stay) { +// String prefix = OutputType.TITLES.name().toLowerCase(); +// String content = prefix + ":" + fade + ":" + stay + ":" + fade; + + return this.wrap(fade, stay);//this.enclose(content); + } + + @NotNull + public String wrap(@NotNull OutputType type) { + String prefix = type.name().toLowerCase(); + + return this.wrap(prefix); + } + + @NotNull + public String wrap(int fade, int stay) { String prefix = OutputType.TITLES.name().toLowerCase(); String content = prefix + ":" + fade + ":" + stay + ":" + fade; - return this.enclose(content); + return this.wrap(content); } @Override diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java index 6c11584..b213fcd 100644 --- a/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java +++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java @@ -14,13 +14,25 @@ public class SoundTag extends MessageTag { } @NotNull + @Deprecated public String enclose(@NotNull Sound sound) { + return this.wrap(sound);//this.enclose(NightSound.of(sound, 0.6F)); + } + + @NotNull + @Deprecated + public String enclose(@NotNull NightSound sound) { + return this.wrap(sound);//this.enclose(sound.serialize()); + } + + @NotNull + public String wrap(@NotNull Sound sound) { return this.enclose(NightSound.of(sound, 0.6F)); } @NotNull - public String enclose(@NotNull NightSound sound) { - return this.enclose(sound.serialize()); + public String wrap(@NotNull NightSound sound) { + return this.wrap(sound.serialize()); } @Override diff --git a/src/main/java/su/nightexpress/nightcore/ui/UIUtils.java b/src/main/java/su/nightexpress/nightcore/ui/UIUtils.java new file mode 100644 index 0000000..a0f8601 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/ui/UIUtils.java @@ -0,0 +1,25 @@ +package su.nightexpress.nightcore.ui; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCore; +import su.nightexpress.nightcore.ui.menu.confirmation.ConfirmMenu; +import su.nightexpress.nightcore.ui.menu.confirmation.Confirmation; + +public class UIUtils { + + private static ConfirmMenu confirmMenu; + + public static void load(@NotNull NightCore plugin) { + confirmMenu = new ConfirmMenu(plugin); + } + + public static void clear() { + confirmMenu.clear(); + confirmMenu = null; + } + + public static void openConfirmation(@NotNull Player player, @NotNull Confirmation confirmation) { + confirmMenu.open(player, confirmation); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/ui/dialog/DialogManager.java b/src/main/java/su/nightexpress/nightcore/ui/dialog/DialogManager.java index 86d8d63..0cab9e1 100644 --- a/src/main/java/su/nightexpress/nightcore/ui/dialog/DialogManager.java +++ b/src/main/java/su/nightexpress/nightcore/ui/dialog/DialogManager.java @@ -1,6 +1,5 @@ package su.nightexpress.nightcore.ui.dialog; -import net.md_5.bungee.api.chat.ClickEvent; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -10,7 +9,7 @@ import su.nightexpress.nightcore.ui.menu.MenuRegistry; import su.nightexpress.nightcore.ui.menu.MenuViewer; import su.nightexpress.nightcore.util.Placeholders; import su.nightexpress.nightcore.util.Players; -import su.nightexpress.nightcore.util.text.NightMessage; +import su.nightexpress.nightcore.util.bridge.wrapper.ClickEventType; import su.nightexpress.nightcore.util.time.TimeFormats; import java.util.*; @@ -49,10 +48,11 @@ public class DialogManager { private static void displayPrompt(@NotNull Dialog dialog, int fade) { Player player = dialog.getPlayer(); - String title = NightMessage.asLegacy(CoreLang.DIALOG_HEADER.getString().replace(Placeholders.GENERIC_TIME, TimeFormats.toLiteral(dialog.getLifetimeMillis()))); - String sub = NightMessage.asLegacy(dialog.getPrompt()); + String title = /*NightMessage.asLegacy(*/CoreLang.DIALOG_HEADER.getString().replace(Placeholders.GENERIC_TIME, TimeFormats.toLiteral(dialog.getLifetimeMillis())); + String sub = /*NightMessage.asLegacy(*/dialog.getPrompt(); - player.sendTitle(title, sub, fade, 40, 20); + //player.sendTitle(title, sub, fade, 40, 20); + Players.sendTitle(player, title, sub, fade, 40, 20); } public static boolean isInDialog(@NotNull Player player) { @@ -116,7 +116,7 @@ public class DialogManager { boolean isLastPage = page == pages; boolean isFirstPage = page == 1; List items = suggestions.stream().skip(skip).limit(perPage).toList(); - ClickEvent.Action action = autoRun ? ClickEvent.Action.RUN_COMMAND : ClickEvent.Action.SUGGEST_COMMAND; + ClickEventType action = autoRun ? ClickEventType.RUN_COMMAND : ClickEventType.SUGGEST_COMMAND; StringBuilder builder = new StringBuilder() .append(ORANGE.enclose("=".repeat(8) + "[ " + YELLOW.enclose("Value Helper") + " ]" + "=".repeat(8))) @@ -126,7 +126,7 @@ public class DialogManager { String hoverHint = GRAY.enclose("Click me to select " + CYAN.enclose(element) + "."); String clickCommand = element.charAt(0) == '/' ? element : '/' + element; - builder.append(DARK_GRAY.enclose("> ")).append(GREEN.enclose(HOVER.encloseHint(CLICK.enclose(element, action, clickCommand), hoverHint))); + builder.append(DARK_GRAY.enclose("> ")).append(GREEN.enclose(HOVER.wrapShowText(CLICK.wrap(element, action, clickCommand), hoverHint))); builder.append(Placeholders.TAG_LINE_BREAK); }); @@ -136,7 +136,7 @@ public class DialogManager { builder.append(GRAY.enclose("[<]")); } else { - builder.append(LIGHT_RED.enclose(HOVER.encloseHint(CLICK.encloseRun("[<]", "/" + VALUES + " " + (page - 1)), GRAY.enclose("Previous Page")))); + builder.append(LIGHT_RED.enclose(HOVER.wrapShowText(CLICK.wrapRunCommand("[<]", "/" + VALUES + " " + (page - 1)), GRAY.enclose("Previous Page")))); } builder.append(YELLOW.enclose(" " + page)); @@ -147,7 +147,7 @@ public class DialogManager { builder.append(GRAY.enclose("[>]")); } else { - builder.append(LIGHT_RED.enclose(HOVER.encloseHint(CLICK.encloseRun("[>]", "/" + VALUES + " " + (page + 1)), GRAY.enclose("Next Page")))); + builder.append(LIGHT_RED.enclose(HOVER.wrapShowText(CLICK.wrapRunCommand("[>]", "/" + VALUES + " " + (page + 1)), GRAY.enclose("Next Page")))); } diff --git a/src/main/java/su/nightexpress/nightcore/ui/menu/confirmation/ConfirmMenu.java b/src/main/java/su/nightexpress/nightcore/ui/menu/confirmation/ConfirmMenu.java new file mode 100644 index 0000000..aac5762 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/ui/menu/confirmation/ConfirmMenu.java @@ -0,0 +1,72 @@ +package su.nightexpress.nightcore.ui.menu.confirmation; + +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.MenuType; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.core.CoreConfig; +import su.nightexpress.nightcore.ui.menu.MenuViewer; +import su.nightexpress.nightcore.ui.menu.data.ConfigBased; +import su.nightexpress.nightcore.ui.menu.data.MenuLoader; +import su.nightexpress.nightcore.ui.menu.item.ItemHandler; +import su.nightexpress.nightcore.ui.menu.type.LinkedMenu; +import su.nightexpress.nightcore.util.Placeholders; +import su.nightexpress.nightcore.util.bukkit.NightItem; + +import static su.nightexpress.nightcore.util.text.tag.Tags.*; + +@SuppressWarnings("UnstableApiUsage") +public class ConfirmMenu extends LinkedMenu implements ConfigBased { + + public static final String FILE_NAME = "confirmation.yml"; + + private int iconSlot; + + public ConfirmMenu(@NotNull NightPlugin plugin) { + super(plugin, MenuType.HOPPER, BLACK.wrap("Are you sure?")); + + this.load(FileConfig.loadOrExtract(plugin, CoreConfig.DIR_UI, FILE_NAME)); + } + + @Override + protected void onPrepare(@NotNull MenuViewer viewer, @NotNull InventoryView view) { + Confirmation confirmation = this.getLink(viewer); + NightItem icon = confirmation.getIcon(); + if (icon != null) { + this.addItem(viewer, icon.toMenuItem().setSlots(this.iconSlot).setPriority(100)); + } + } + + @Override + protected void onReady(@NotNull MenuViewer viewer, @NotNull Inventory inventory) { + + } + + @Override + public void loadConfiguration(@NotNull FileConfig config, @NotNull MenuLoader loader) { + this.iconSlot = ConfigValue.create("Settings.IconSlot", 2).read(config); + + loader.addDefaultItem(NightItem.asCustomHead(Placeholders.SKIN_WRONG_MARK) + .setDisplayName(LIGHT_RED.wrap(BOLD.wrap("Cancel"))) + .toMenuItem() + .setPriority(10) + .setSlots(0) + .setHandler(new ItemHandler("decline", (viewer, event) -> { + this.getLink(viewer).handleReturn(viewer, event); + })) + ); + + loader.addDefaultItem(NightItem.asCustomHead(Placeholders.SKIN_CHECK_MARK) + .setDisplayName(LIGHT_GREEN.wrap(BOLD.wrap("Accept"))) + .toMenuItem() + .setPriority(10) + .setSlots(4) + .setHandler(new ItemHandler("accept", (viewer, event) -> { + this.getLink(viewer).handleAccept(viewer, event); + })) + ); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/ui/menu/confirmation/Confirmation.java b/src/main/java/su/nightexpress/nightcore/ui/menu/confirmation/Confirmation.java new file mode 100644 index 0000000..eaa1758 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/ui/menu/confirmation/Confirmation.java @@ -0,0 +1,86 @@ +package su.nightexpress.nightcore.ui.menu.confirmation; + +import org.bukkit.event.inventory.InventoryClickEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.ui.menu.MenuViewer; +import su.nightexpress.nightcore.ui.menu.item.ItemClick; +import su.nightexpress.nightcore.util.bukkit.NightItem; + +public class Confirmation { + + private final ItemClick onAccept; + private final ItemClick onReturn; + private final NightItem icon; + private final boolean returnOnAccept; + + public Confirmation(@Nullable ItemClick onAccept, @Nullable ItemClick onReturn, @Nullable NightItem icon, boolean returnOnAccept) { + this.onAccept = onAccept; + this.onReturn = onReturn; + this.icon = icon; + this.returnOnAccept = returnOnAccept; + } + + @NotNull + public static Builder builder() { + return new Builder(); + } + + public void handleAccept(@NotNull MenuViewer viewer, @NotNull InventoryClickEvent event) { + if (this.onAccept == null) return; + + this.onAccept.onClick(viewer, event); + + if (this.returnOnAccept) { + this.handleReturn(viewer, event); + } + } + + public void handleReturn(@NotNull MenuViewer viewer, @NotNull InventoryClickEvent event) { + if (this.onReturn == null) return; + + this.onReturn.onClick(viewer, event); + } + + @Nullable + public NightItem getIcon() { + return this.icon; + } + + public static class Builder { + + private ItemClick onAccept; + private ItemClick onReturn; + private NightItem icon; + private boolean returnOnAccept; + + @NotNull + public Confirmation build() { + return new Confirmation(this.onAccept, this.onReturn, this.icon, this.returnOnAccept); + } + + @NotNull + public Builder onAccept(@Nullable ItemClick onAccept) { + this.onAccept = onAccept; + return this; + } + + @NotNull + public Builder onReturn(@Nullable ItemClick onReturn) { + this.onReturn = onReturn; + return this; + } + + @NotNull + public Builder setIcon(@Nullable NightItem icon) { + this.icon = icon; + return this; + } + + @NotNull + public Builder returnOnAccept(boolean returnOnAccept) { + this.returnOnAccept = returnOnAccept; + return this; + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/ui/menu/data/LinkCache.java b/src/main/java/su/nightexpress/nightcore/ui/menu/data/LinkCache.java index 066f5cc..901dfd6 100644 --- a/src/main/java/su/nightexpress/nightcore/ui/menu/data/LinkCache.java +++ b/src/main/java/su/nightexpress/nightcore/ui/menu/data/LinkCache.java @@ -36,6 +36,10 @@ public class LinkCache { this.map.put(player.getUniqueId(), object); } + public boolean contains(@NotNull Player player) { + return this.map.containsKey(player.getUniqueId()); + } + public T get(@NotNull MenuViewer viewer) { return this.get(viewer.getPlayer()); } diff --git a/src/main/java/su/nightexpress/nightcore/ui/menu/data/Linked.java b/src/main/java/su/nightexpress/nightcore/ui/menu/data/Linked.java index f840833..44c0133 100644 --- a/src/main/java/su/nightexpress/nightcore/ui/menu/data/Linked.java +++ b/src/main/java/su/nightexpress/nightcore/ui/menu/data/Linked.java @@ -23,6 +23,8 @@ public interface Linked extends Menu { @NotNull LinkCache getCache(); + boolean isCached(@NotNull Player player); + T getLink(@NotNull MenuViewer viewer); T getLink(@NotNull Player player); diff --git a/src/main/java/su/nightexpress/nightcore/ui/menu/type/AbstractMenu.java b/src/main/java/su/nightexpress/nightcore/ui/menu/type/AbstractMenu.java index 9a7a428..da7d392 100644 --- a/src/main/java/su/nightexpress/nightcore/ui/menu/type/AbstractMenu.java +++ b/src/main/java/su/nightexpress/nightcore/ui/menu/type/AbstractMenu.java @@ -8,7 +8,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.MenuType; -import org.bukkit.inventory.view.builder.LocationInventoryViewBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.NightPlugin; @@ -25,7 +24,6 @@ import su.nightexpress.nightcore.ui.menu.item.MenuItem; import su.nightexpress.nightcore.util.Lists; import su.nightexpress.nightcore.util.Version; import su.nightexpress.nightcore.util.bukkit.NightItem; -import su.nightexpress.nightcore.util.text.NightMessage; import java.util.Comparator; import java.util.HashSet; @@ -141,33 +139,20 @@ public abstract class AbstractMenu

implements Menu { viewer.removeItems(); onViewSet.accept(viewer); - //String title = NightMessage.asLegacy(this.getTitle(viewer)); - InventoryView view = viewer.getView(); if (view == null || viewer.isRebuildMenu()) { - // Save cache so its not wiped by .openInventory call due to internal InventoryCloseEvent. if (view != null && this instanceof Linked linked) { linked.getCache().addAnchor(player); } - if (Version.isAtLeast(Version.MC_1_21_4)) { - var builder = this.menuType.typed().builder(); - // Stupid hack to bypass 9X3 (and probably other container-based) menu types to be bound to real container(s) at player's location. - if (builder instanceof LocationInventoryViewBuilder locationBuilder) { - locationBuilder.location(player.getEyeLocation()); - } - view = Version.software().createView(builder, this.getTitle(viewer), player); - } - else { - view = this.menuType.typed().create(player, NightMessage.asLegacy(this.getTitle(viewer))); - } + String title = this.getTitle(viewer); + view = Version.software().createView(this.menuType, title, player); viewer.assignInventory(view); player.openInventory(view); } else { view.getTopInventory().clear(); - //if (viewer.isUpdateTitle()) view.setTitle(NightMessage.asLegacy(this.getTitle(viewer))); } this.onPrepare(viewer, view); diff --git a/src/main/java/su/nightexpress/nightcore/ui/menu/type/LinkedMenu.java b/src/main/java/su/nightexpress/nightcore/ui/menu/type/LinkedMenu.java index 72fed9f..7e192b8 100644 --- a/src/main/java/su/nightexpress/nightcore/ui/menu/type/LinkedMenu.java +++ b/src/main/java/su/nightexpress/nightcore/ui/menu/type/LinkedMenu.java @@ -45,6 +45,11 @@ public abstract class LinkedMenu

extends AbstractMenu< return this.cache; } + @Override + public boolean isCached(@NotNull Player player) { + return this.cache.contains(player); + } + @Override public T getLink(@NotNull MenuViewer viewer) { return this.getLink(viewer.getPlayer()); @@ -62,6 +67,16 @@ public abstract class LinkedMenu

extends AbstractMenu< }; } + @Override + public void flush(@NotNull Player player, @NotNull Consumer consumer) { + if (!this.isCached(player)) { + this.plugin.warn("Null link reference in menu: " + player.getName() + " / " + this); + this.close(player); + return; + } + super.flush(player, consumer); + } + @Override public boolean open(@NotNull Player player, @NotNull T obj) { return this.open(player, obj, viewer -> {}); diff --git a/src/main/java/su/nightexpress/nightcore/util/Colorizer.java b/src/main/java/su/nightexpress/nightcore/util/Colorizer.java index e68301d..01cd61f 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Colorizer.java +++ b/src/main/java/su/nightexpress/nightcore/util/Colorizer.java @@ -3,7 +3,6 @@ package su.nightexpress.nightcore.util; import net.md_5.bungee.api.ChatColor; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.util.regex.TimedMatcher; -import su.nightexpress.nightcore.util.text.tag.api.Tag; import java.util.List; import java.util.Set; @@ -15,12 +14,10 @@ import java.util.stream.Collectors; public class Colorizer { @Deprecated public static final Pattern PATTERN_HEX = Pattern.compile("#([A-Fa-f0-9]{6})"); - //public static final Pattern PATTERN_HEX_LEGACY = Pattern.compile("(?:^|[^<])(#[A-Fa-f0-9]{6})(?:$|[^:>])"); - @Deprecated public static final Pattern PATTERN_GRADIENT = Pattern.compile("(.*?)"); @NotNull public static String apply(@NotNull String str) { - return hex(gradient(legacy(str))); + return hex(legacy(str)); } @NotNull @@ -62,63 +59,6 @@ public class Colorizer { return timedMatcher.getMatcher().appendTail(buffer).toString(); } - @Deprecated - private static ChatColor[] createGradient(@NotNull java.awt.Color start, @NotNull java.awt.Color end, int length) { - ChatColor[] colors = new ChatColor[length]; - for (int index = 0; index < length; index++) { - double percent = (double) index / (double) length; - - int red = (int) (start.getRed() + percent * (end.getRed() - start.getRed())); - int green = (int) (start.getGreen() + percent * (end.getGreen() - start.getGreen())); - int blue = (int) (start.getBlue() + percent * (end.getBlue() - start.getBlue())); - - java.awt.Color color = new java.awt.Color(red, green, blue); - colors[index] = ChatColor.of(color); - } - return colors; - } - - @NotNull - @Deprecated - public static String gradient(@NotNull String string) { - TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_GRADIENT, string); - //Matcher matcher = PATTERN_GRADIENT.matcher(string); - while (timedMatcher.find()) { - Matcher matcher = timedMatcher.getMatcher(); - String start = matcher.group(1); - String end = matcher.group(3); - String content = matcher.group(2); - - java.awt.Color colorStart = new java.awt.Color(Integer.parseInt(start, 16)); - java.awt.Color colorEnd = new java.awt.Color(Integer.parseInt(end, 16)); - ChatColor[] colors = createGradient(colorStart, colorEnd, strip(content).length()); - - StringBuilder gradiented = new StringBuilder(); - StringBuilder specialColors = new StringBuilder(); - char[] characters = content.toCharArray(); - int outIndex = 0; - for (int index = 0; index < characters.length; index++) { - if (characters[index] == ChatColor.COLOR_CHAR) { - if (index + 1 < characters.length) { - if (characters[index + 1] == 'r') { - specialColors.setLength(0); - } - else { - specialColors.append(characters[index]); - specialColors.append(characters[index + 1]); - } - index++; - } - else gradiented.append(colors[outIndex++]).append(specialColors).append(characters[index]); - } - else gradiented.append(colors[outIndex++]).append(specialColors).append(characters[index]); - } - - string = string.replace(matcher.group(0), gradiented.toString()); - } - return string; - } - @NotNull public static String plain(@NotNull String str) { return plainLegacy(plainHex(str)); @@ -148,47 +88,6 @@ public class Colorizer { return builder.toString();//tagPlainHex(builder.toString()); } - @NotNull - public static String tagPlainHex(@NotNull String str) { - StringBuilder builder = new StringBuilder(str); - - int index; - int lastIndex = 0; - - while ((index = builder.toString().indexOf("#", lastIndex)) >= 0) { - lastIndex = index + 1; - - //if (builder.length() < 7) break; - int lookup = index + 7; - if (builder.length() < lookup) break; - - Character prefix = index > 0 ? builder.charAt(index - 1) : null; - Character postfix = builder.length() > lookup ? builder.charAt(lookup) : null; - - - if (prefix != null && prefix == Tag.OPEN_BRACKET) continue; - if (postfix != null && postfix == Tag.CLOSE_BRACKET) continue; - if (prefix != null && postfix != null && prefix == ':' && postfix == ':') continue; - - //if (index > 0 && builder.charAt(index - 1) == Tag.OPEN_BRACKET) continue; - //if (builder.length() < index + 7) break; - //if (builder.length() > index + 7 && builder.charAt(index + 7) == Tag.CLOSE_BRACKET) continue; - - String sub = builder.substring(index, lookup); - try { - Integer.decode(sub); - } - catch (NumberFormatException exception) { - continue; - } - - builder.insert(index, Tag.OPEN_BRACKET); - builder.insert(index + 8, Tag.CLOSE_BRACKET); - } - - return builder.toString(); - } - @NotNull public static String strip(@NotNull String str) { String stripped = ChatColor.stripColor(str); diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java b/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java index 1109e59..dc02a11 100644 --- a/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java +++ b/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java @@ -11,114 +11,151 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.NightCore; -import su.nightexpress.nightcore.core.CoreConfig; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; +import java.util.*; public class ItemNbt { - private static final Class ITEM_STACK_CLASS = Reflex.getNMSClass("net.minecraft.world.item", "ItemStack"); - private static final Class COMPOUND_TAG_CLASS = Reflex.getNMSClass("net.minecraft.nbt", "CompoundTag", "NBTTagCompound"); - private static final Class NBT_IO_CLASS = Reflex.getNMSClass("net.minecraft.nbt", "NbtIo", "NBTCompressedStreamTools"); + private static final Class CLS_MINECRAFT_ITEM_STACK = Reflex.getNMSClass("net.minecraft.world.item", "ItemStack"); - private static final Class CRAFT_ITEM_STACK_CLASS = Reflex.getNMSClass(Version.CRAFTBUKKIT_PACKAGE + ".inventory", "CraftItemStack"); + private static final Class CLS_CRAFT_ITEM_STACK = Reflex.getNMSClass(Version.CRAFTBUKKIT_PACKAGE + ".inventory", "CraftItemStack"); - private static final Method CRAFT_ITEM_STACK_AS_NMS_COPY = Reflex.getMethod(CRAFT_ITEM_STACK_CLASS, "asNMSCopy", ItemStack.class); - private static final Method CRAFT_ITEM_STACK_AS_BUKKIT_COPY = Reflex.getMethod(CRAFT_ITEM_STACK_CLASS, "asBukkitCopy", ITEM_STACK_CLASS); + private static final Class CLS_TAG = Reflex.getNMSClass("net.minecraft.nbt", "Tag", "NBTBase"); + private static final Class CLS_COMPOUND_TAG = Reflex.getNMSClass("net.minecraft.nbt", "CompoundTag", "NBTTagCompound"); + private static final Class CLS_NBT_IO = Reflex.getNMSClass("net.minecraft.nbt", "NbtIo", "NBTCompressedStreamTools"); + private static final Class CLS_TAG_PARSER = Reflex.getNMSClass("net.minecraft.nbt", "TagParser", "MojangsonParser"); + private static final Class CLS_NBT_OPS = Reflex.getNMSClass("net.minecraft.nbt", "NbtOps", "DynamicOpsNBT"); - private static final Method NBT_IO_WRITE = Reflex.getMethod(NBT_IO_CLASS, "a", COMPOUND_TAG_CLASS, DataOutput.class); - private static final Method NBT_IO_READ = Reflex.getMethod(NBT_IO_CLASS, "a", DataInput.class); + private static final Class CLS_DATA_FIXERS = Reflex.getNMSClass("net.minecraft.util.datafix", "DataFixers", "DataConverterRegistry"); + private static final Class CLS_REFERENCES = Reflex.getNMSClass("net.minecraft.util.datafix.fixes", "References", "DataConverterTypes"); - private static final Class TAG_PARSER_CLASS = Reflex.getNMSClass("net.minecraft.nbt", "TagParser", "MojangsonParser"); - private static final Method PARSE_TAG = TAG_PARSER_CLASS == null ? null : Reflex.getMethod(TAG_PARSER_CLASS, "a", String.class); + private static Method mCraftItemStackAsNmsCopy; + private static Method mCraftItemStackAsBukkitCopy; - private static final Class DATA_FIXERS_CLASS = Reflex.getNMSClass("net.minecraft.util.datafix", "DataFixers", "DataConverterRegistry"); // DataFixers - private static final Method GET_DATA_FIXER = Reflex.getMethod(DATA_FIXERS_CLASS, "a"); - private static final Class NBT_OPS_CLASS = Reflex.getNMSClass("net.minecraft.nbt", "NbtOps", "DynamicOpsNBT"); // NbtOps - private static final Class REFERENCES_CLASS = Reflex.getNMSClass("net.minecraft.util.datafix.fixes", "References", "DataConverterTypes"); // References + private static Method mNbtIoWrite; + private static Method mNbtIoRead; + private static Method mTagParserParseTag; - private static final int DATA_FIXER_SOURCE_VERSION = 3700; // 1.20.4 - private static final int DATA_FXIER_TARGET_VERSION = 3953; // 1.21 - - private static DataFixer DATA_FIXER; - private static Object NBT_OPS_INSTANCE; - private static Object REFERENCE_ITEM_STACK; + private static int DATA_FIXER_SOURCE_VERSION; + private static int DATA_FXIER_TARGET_VERSION; + private static DataFixer dataFixer; + private static Object nbtOps; + private static Object itemStackReference; // For 1.20.6+ - private static Method MINECRAFT_SERVER_REGISTRY_ACCESS; - private static Method ITEM_STACK_PARSE_OPTIONAL; - private static Method ITEM_STACK_SAVE_OPTIONAL; + private static Method mItemStackParse; + private static Method mItemStackSave; // For 1.20.4 and below. - private static Constructor NBT_TAG_COMPOUND_NEW; - private static Method NMS_ITEM_OF; - private static Method NMS_SAVE; + private static Constructor conNewCompoundTag; + private static Method mMinecraftItemStackOf; + private static Method mMinecraftItemStackSave; - static { - if (GET_DATA_FIXER != null) { - DATA_FIXER = (DataFixer) Reflex.invokeMethod(GET_DATA_FIXER, DATA_FIXERS_CLASS); - } - if (NBT_OPS_CLASS != null) { - NBT_OPS_INSTANCE = Reflex.getFieldValue(NBT_OPS_CLASS, "a"); - } - if (REFERENCES_CLASS != null) { - REFERENCE_ITEM_STACK = Reflex.getFieldValue(REFERENCES_CLASS, "t"); - } - - if (Version.isAtLeast(Version.MC_1_20_6)) { - Class minecraftServerClass = Reflex.getNMSClass("net.minecraft.server", "MinecraftServer"); - Class holderLookupProviderClass = Reflex.getNMSClass("net.minecraft.core", "HolderLookup$a"); // Provider - - String registryAccessName = "bc"; - if (Version.isAtLeast(Version.MC_1_21_3)) registryAccessName = "ba"; - - MINECRAFT_SERVER_REGISTRY_ACCESS = Reflex.getMethod(minecraftServerClass, registryAccessName); - ITEM_STACK_PARSE_OPTIONAL = Reflex.getMethod(ITEM_STACK_CLASS, "a", holderLookupProviderClass, COMPOUND_TAG_CLASS); - ITEM_STACK_SAVE_OPTIONAL = Reflex.getMethod(ITEM_STACK_CLASS, "b", holderLookupProviderClass); - } - else { - NBT_TAG_COMPOUND_NEW = Reflex.getConstructor(COMPOUND_TAG_CLASS); - NMS_ITEM_OF = Reflex.getMethod(ITEM_STACK_CLASS, "a", COMPOUND_TAG_CLASS); - NMS_SAVE = Reflex.getMethod(ITEM_STACK_CLASS, "b", COMPOUND_TAG_CLASS); - } - } + // Base private static boolean useRegistry; private static Object registryAccess; + private static boolean loaded; - public static boolean load(@NotNull NightCore core) { - if (Version.isBehind(Version.MC_1_20_6)) return true; + public static void load(@NotNull NightCore core) { + if (CLS_CRAFT_ITEM_STACK == null) return; + if (CLS_MINECRAFT_ITEM_STACK == null) return; + if (CLS_NBT_IO == null) return; + if (CLS_NBT_OPS == null) return; + if (CLS_TAG_PARSER == null) return; + if (CLS_TAG == null) return; + if (CLS_COMPOUND_TAG == null) return; + if (CLS_DATA_FIXERS == null) return; + if (CLS_REFERENCES == null) return; - useRegistry = true; + // Load vital components for all versions. + mCraftItemStackAsNmsCopy = Reflex.getMethod(CLS_CRAFT_ITEM_STACK, "asNMSCopy", ItemStack.class); + mCraftItemStackAsBukkitCopy = Reflex.getMethod(CLS_CRAFT_ITEM_STACK, "asBukkitCopy", CLS_MINECRAFT_ITEM_STACK); - Class craftServerClass = Reflex.getNMSClass(Version.CRAFTBUKKIT_PACKAGE, "CraftServer"); - if (craftServerClass == null) { - core.error("Could not find 'CraftServer' class in craftbukkit package: '" + Version.CRAFTBUKKIT_PACKAGE + "'."); - return false; + if (mCraftItemStackAsNmsCopy == null || mCraftItemStackAsBukkitCopy == null) { + core.error("[Item NBT] Could not find CraftItemStack methods: #asNMSCopy, #asBukkitCopy."); + return; } - Method getServer = Reflex.getMethod(craftServerClass, "getServer"); - if (getServer == null || MINECRAFT_SERVER_REGISTRY_ACCESS == null) { - core.error("Could not find proper class(es) for ItemStack compression util."); - return false; + mNbtIoWrite = Reflex.getMethod(CLS_NBT_IO, "a", CLS_COMPOUND_TAG, DataOutput.class); + mNbtIoRead = Reflex.getMethod(CLS_NBT_IO, "a", DataInput.class); + mTagParserParseTag = Reflex.getMethod(CLS_TAG_PARSER, "a", String.class); + + if (mNbtIoWrite == null || mNbtIoRead == null || mTagParserParseTag == null) { + core.error("[Item NBT] Could not find NbtIo or TagParser methods."); + return; } - try { - Object craftServer = craftServerClass.cast(Bukkit.getServer()); - Object minecraftServer = getServer.invoke(craftServer); - registryAccess = MINECRAFT_SERVER_REGISTRY_ACCESS.invoke(minecraftServer); - return true; + // Load DataFixer components. + DATA_FIXER_SOURCE_VERSION = 3700; // 1.20.4 + DATA_FXIER_TARGET_VERSION = 4325; // 1.21.5 + + Method mGetDataFixer = Reflex.getMethod(CLS_DATA_FIXERS, "a"); + if (mGetDataFixer == null) { + core.error("[Item NBT] Could not load DataFixer components."); + return; } - catch (ReflectiveOperationException exception) { - exception.printStackTrace(); - return false; + + dataFixer = (DataFixer) Reflex.invokeMethod(mGetDataFixer, CLS_DATA_FIXERS); + nbtOps = Reflex.getFieldValue(CLS_NBT_OPS, "a"); + itemStackReference = Reflex.getFieldValue(CLS_REFERENCES, "t"); + + // Load version specific item parsers. + if (Version.isAtLeast(Version.MC_1_20_6)) { + useRegistry = true; + + Class clsCraftRegistry = Reflex.getNMSClass(Version.CRAFTBUKKIT_PACKAGE, "CraftRegistry"); + if (clsCraftRegistry == null) { + core.error("[Item NBT] Could not find CraftRegistry."); + return; + } + + Method mGetMinecraftRegistry = Reflex.getMethod(clsCraftRegistry, "getMinecraftRegistry"); + if (mGetMinecraftRegistry == null) { + core.error("[Item NBT] Could not find CraftRegistry#getMinecraftRegistry."); + return; + } + + registryAccess = Reflex.invokeMethod(mGetMinecraftRegistry, null); + if (registryAccess == null) { + core.error("[Item NBT] Registry Access is null."); + return; + } + + Class clsHolderLookupProvider = Reflex.getNMSClass("net.minecraft.core", "HolderLookup$a"); // HolderLookup.Provider + if (clsHolderLookupProvider == null) { + core.error("[Item NBT] Could not find MinecraftServer or HolderLookup#Provider."); + return; + } + + mItemStackParse = Reflex.getMethod(CLS_MINECRAFT_ITEM_STACK, "a", clsHolderLookupProvider, CLS_TAG); + mItemStackSave = Reflex.getMethod(CLS_MINECRAFT_ITEM_STACK, "a", clsHolderLookupProvider); + + if (mItemStackParse == null || mItemStackSave == null) { + core.error("[Item NBT] Could not find ItemStack#parse or ItemStack#save methods."); + return; + } + } + else { + conNewCompoundTag = Reflex.getConstructor(CLS_COMPOUND_TAG); + mMinecraftItemStackOf = Reflex.getMethod(CLS_MINECRAFT_ITEM_STACK, "a", CLS_COMPOUND_TAG); + mMinecraftItemStackSave = Reflex.getMethod(CLS_MINECRAFT_ITEM_STACK, "b", CLS_COMPOUND_TAG); + + if (conNewCompoundTag == null || mMinecraftItemStackOf == null || mMinecraftItemStackSave == null) { + core.error("[Item NBT] Could not find new CompoundTag() or ItemStack#of or ItemStack#save."); + return; + } + } + + loaded = true; + + if (!test()) { + core.error("[Item NBT] Compression test failed."); + loaded = false; } } @@ -139,131 +176,40 @@ public class ItemNbt { @Nullable public static String compress(@NotNull ItemStack item) { - if (CRAFT_ITEM_STACK_AS_NMS_COPY == null || NBT_IO_WRITE == null) { - return null; - } + Object compoundTag = toCompoundTag(item); + if (compoundTag == null) return null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream dataOutput = new DataOutputStream(outputStream); - try { - Object compoundTag; - Object itemStack = CRAFT_ITEM_STACK_AS_NMS_COPY.invoke(null, item); - - if (useRegistry) { - if (ITEM_STACK_SAVE_OPTIONAL == null) return null; - - compoundTag = ITEM_STACK_SAVE_OPTIONAL.invoke(itemStack, registryAccess); - } - else { - if (NBT_TAG_COMPOUND_NEW == null || NMS_SAVE == null) return null; - - compoundTag = NBT_TAG_COMPOUND_NEW.newInstance(); - NMS_SAVE.invoke(itemStack, compoundTag); - } - - NBT_IO_WRITE.invoke(null, compoundTag, dataOutput); - - return new BigInteger(1, outputStream.toByteArray()).toString(32); - } - catch (ReflectiveOperationException exception) { - exception.printStackTrace(); - return null; - } + Reflex.invokeMethod(mNbtIoWrite, null, compoundTag, dataOutput); + return new BigInteger(1, outputStream.toByteArray()).toString(32); } @Nullable public static ItemStack decompress(@NotNull String compressed) { - if (NBT_IO_READ == null || CRAFT_ITEM_STACK_AS_BUKKIT_COPY == null) { - throw new UnsupportedOperationException("Unsupported server version!"); - } + if (compressed.isBlank()) return null; ByteArrayInputStream inputStream = new ByteArrayInputStream(new BigInteger(compressed, 32).toByteArray()); - try { - Object compoundTag = NBT_IO_READ.invoke(null, new DataInputStream(inputStream)); - Object itemStack; + DataInputStream dataInput = new DataInputStream(inputStream); - if (Version.isAtLeast(Version.MC_1_20_6) && CoreConfig.DATA_FIXER_ENABLED.get()) { - @SuppressWarnings({"rawtypes", "unchecked"}) - Dynamic dynamic = new Dynamic<>((DynamicOps) NBT_OPS_INSTANCE, compoundTag); - compoundTag = DATA_FIXER.update((DSL.TypeReference) REFERENCE_ITEM_STACK, dynamic, DATA_FIXER_SOURCE_VERSION, DATA_FXIER_TARGET_VERSION).getValue(); - } - - if (useRegistry) { - if (ITEM_STACK_PARSE_OPTIONAL == null) return null; - - itemStack = ITEM_STACK_PARSE_OPTIONAL.invoke(null, registryAccess, compoundTag); - } - else { - if (NMS_ITEM_OF == null) return null; - - itemStack = NMS_ITEM_OF.invoke(null, compoundTag); - } - - return (ItemStack) CRAFT_ITEM_STACK_AS_BUKKIT_COPY.invoke(null, itemStack); - } - catch (ReflectiveOperationException exception) { - exception.printStackTrace(); - return null; - } + Object compoundTag = Reflex.invokeMethod(mNbtIoRead, null, dataInput); + return compoundTag == null ? null : fromCompoundTag(compoundTag); } @Nullable public static String getTagString(@NotNull ItemStack item) { - if (CRAFT_ITEM_STACK_AS_NMS_COPY == null) { - throw new UnsupportedOperationException("Unsupported server version!"); - } + Object compoundTag = toCompoundTag(item); + if (compoundTag == null) return null; - try { - Object compoundTag; - Object itemStack = CRAFT_ITEM_STACK_AS_NMS_COPY.invoke(null, item); - - if (useRegistry) { - if (ITEM_STACK_SAVE_OPTIONAL == null) return null; - - compoundTag = ITEM_STACK_SAVE_OPTIONAL.invoke(itemStack, registryAccess); - } - else { - if (NBT_TAG_COMPOUND_NEW == null || NMS_SAVE == null) return null; - - compoundTag = NBT_TAG_COMPOUND_NEW.newInstance(); - NMS_SAVE.invoke(itemStack, compoundTag); - } - - return compoundTag.toString(); - } - catch (ReflectiveOperationException exception) { - exception.printStackTrace(); - return null; - } + return compoundTag.toString(); } @Nullable public static ItemStack fromTagString(@NotNull String tagString) { - if (TAG_PARSER_CLASS == null || PARSE_TAG == null || CRAFT_ITEM_STACK_AS_BUKKIT_COPY == null) { - throw new UnsupportedOperationException("Unsupported server version!"); - } + if (tagString.isBlank() || tagString.equalsIgnoreCase("{}")) return null; - try { - Object compoundTag = Reflex.invokeMethod(PARSE_TAG, null, tagString); - Object itemStack; - - if (useRegistry) { - if (ITEM_STACK_PARSE_OPTIONAL == null) return null; - - itemStack = ITEM_STACK_PARSE_OPTIONAL.invoke(null, registryAccess, compoundTag); - } - else { - if (NMS_ITEM_OF == null) return null; - - itemStack = NMS_ITEM_OF.invoke(null, compoundTag); - } - - return (ItemStack) CRAFT_ITEM_STACK_AS_BUKKIT_COPY.invoke(null, itemStack); - } - catch (ReflectiveOperationException exception) { - exception.printStackTrace(); - return null; - } + Object compoundTag = Reflex.invokeMethod(mTagParserParseTag, null, tagString); + return compoundTag == null ? null : fromCompoundTag(compoundTag); } @NotNull @@ -280,4 +226,63 @@ public class ItemNbt { List items = list.stream().map(ItemNbt::decompress).filter(Objects::nonNull).toList(); return items.toArray(new ItemStack[list.size()]); } + + @NotNull + public static ItemStack getHoverEventItem(@NotNull String value) { + ItemStack itemStack = null; + + try { + itemStack = Bukkit.getItemFactory().createItemStack(value); + } + catch (IllegalArgumentException exception) { + try { + itemStack = ItemNbt.decompress(value); + } + catch (NumberFormatException ignored) { + + } + } + if (itemStack == null) itemStack = new ItemStack(Material.AIR); + + return itemStack; + } + + @Nullable + private static Object toCompoundTag(@NotNull ItemStack bukkitStack) { + if (!loaded) return null; + if (bukkitStack.getType().isAir() || bukkitStack.getAmount() <= 0) return null; + + Object nmsStack = Reflex.invokeMethod(mCraftItemStackAsNmsCopy, null, bukkitStack); + if (useRegistry) { + return Reflex.invokeMethod(mItemStackSave, nmsStack, registryAccess); + } + + Object compoundTag = Reflex.invokeConstructor(conNewCompoundTag); + Reflex.invokeMethod(mMinecraftItemStackSave, nmsStack, compoundTag); + return compoundTag; + } + + @Nullable + private static ItemStack fromCompoundTag(@NotNull Object tag) { + if (!loaded) return null; + + Object itemStack; + Object compoundTag = ItemNbt.applyDataFixer(tag); + + if (useRegistry) { + Optional optional = (Optional) Reflex.invokeMethod(mItemStackParse, null, registryAccess, compoundTag); + itemStack = Objects.requireNonNull(optional).orElse(null); + } + else { + itemStack = Reflex.invokeMethod(mMinecraftItemStackOf, null, compoundTag); + } + + return itemStack == null ? null : (ItemStack) Reflex.invokeMethod(mCraftItemStackAsBukkitCopy, null, itemStack); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static Object applyDataFixer(@NotNull Object compoundTag) { + Dynamic dynamic = new Dynamic<>((DynamicOps) nbtOps, compoundTag); + return dataFixer.update((DSL.TypeReference) itemStackReference, dynamic, DATA_FIXER_SOURCE_VERSION, DATA_FXIER_TARGET_VERSION).getValue(); + } } diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java b/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java index 53a6cbf..c18f2af 100644 --- a/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java +++ b/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java @@ -91,14 +91,18 @@ public class ItemReplacer { this.meta.setLore(this.packTrimmedLore()); } - if (this.isHideFlags()) { - ItemUtil.hideAttributes(this.meta, this.item.getType()); - } +// if (this.isHideFlags()) { +// ItemUtil.hideAttributes(this.meta, this.item.getType()); +// } if (this.hasItem()) { this.item.setItemMeta(this.meta); } + if (this.isHideFlags()) { + ItemUtil.hideAttributes(this.item); + } + this.replacer.clear(); } diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java index e99aa42..9df0836 100644 --- a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java +++ b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java @@ -32,19 +32,25 @@ public class ItemUtil { public static String getItemName(@NotNull ItemStack item) { ItemMeta meta = item.getItemMeta(); if (meta != null) { - if (Version.isAtLeast(Version.MC_1_21) && meta.hasItemName()) { - // MiniMessage.miniMessage().serialize(meta.itemName())); - return meta.getItemName(); - } - else if (meta.hasDisplayName()) { - // MiniMessage.miniMessage().serialize(meta.displayName())); - return meta.getDisplayName(); - } + String name = getItemName(meta); + if (name != null) return name; } return LangAssets.get(item.getType()); } + @Nullable + public static String getItemName(@NotNull ItemMeta meta) { + if (Version.isAtLeast(Version.MC_1_21) && meta.hasItemName()) { + return meta.getItemName(); + } + if (meta.hasDisplayName()) { + return meta.getDisplayName(); + } + + return null; + } + @NotNull public static String getSerializedName(@NotNull ItemStack item) { if (Version.isSpigot()) return getItemName(item); @@ -52,36 +58,73 @@ public class ItemUtil { ItemMeta meta = item.getItemMeta(); if (meta != null) { - if (Version.isAtLeast(Version.MC_1_21) && meta.hasItemName()) { - return MiniMessage.miniMessage().serialize(meta.itemName()); - } - else if (Version.isAtLeast(Version.MC_1_21_4) && meta.hasCustomName()) { - var customName = meta.customName(); - if (customName != null) { - return MiniMessage.miniMessage().serialize(customName); - } - } - else if (meta.hasDisplayName()) { - var displayName = meta.displayName(); - if (displayName != null) { - return MiniMessage.miniMessage().serialize(displayName); - } - } + String name = getSerializedName(meta); + if (name != null) return name; } return LangAssets.get(item.getType()); } + @Nullable + public static String getSerializedName(@NotNull ItemMeta meta) { + if (Version.isAtLeast(Version.MC_1_21) && meta.hasItemName()) { + return getSerializedItemName(meta); + } + + if (meta.hasDisplayName()) { + return getSerializedDisplayName(meta); + } + + return null; + } + + @Nullable + public static String getSerializedDisplayName(@NotNull ItemMeta meta) { + if (Version.isSpigot()) return getItemName(meta); + + var displayName = meta.hasDisplayName() ? meta.displayName() : null; + return displayName == null ? null : MiniMessage.miniMessage().serialize(displayName); + } + + @Nullable + public static String getSerializedItemName(@NotNull ItemMeta meta) { + if (Version.isSpigot()) return getItemName(meta); + if (Version.isBehind(Version.MC_1_21)) return null; + + return meta.hasItemName() ? MiniMessage.miniMessage().serialize(meta.itemName()) : null; + } + @NotNull public static List getSerializedLore(@NotNull ItemStack item) { - if (Version.isSpigot()) return getLore(item); if (!item.hasItemMeta()) return new ArrayList<>(); ItemMeta meta = item.getItemMeta(); - List lore = meta == null ? null : meta.lore(); - if (lore == null) return new ArrayList<>(); - return lore.stream().map(MiniMessage.miniMessage()::serialize).toList(); + return meta == null ? new ArrayList<>() : getSerializedLore(meta); + } + + @NotNull + public static List getSerializedLore(@NotNull ItemMeta meta) { + if (Version.isSpigot()) { + List lore = meta.getLore(); + return lore == null ? new ArrayList<>() : lore; + } + + List lore = meta.lore(); + + return lore == null ? new ArrayList<>() : lore.stream().map(MiniMessage.miniMessage()::serialize).toList(); + } + + public static void setDisplayName(@NotNull ItemMeta meta, @NotNull String name) { + Version.software().setDisplayName(meta, name); + } + + public static void setItemName(@NotNull ItemMeta meta, @NotNull String name) { + Version.software().setItemName(meta, name); + } + + public static void setLore(@NotNull ItemMeta meta, @NotNull List lore) { + Version.software().setLore(meta, lore); } public static void editMeta(@NotNull ItemStack item, @NotNull Consumer function) { @@ -100,18 +143,25 @@ public class ItemUtil { } public static void hideAttributes(@NotNull ItemStack itemStack) { + if (Version.isAtLeast(Version.MC_1_21_5)) { + Version.software().hideComponents(itemStack); + return; + } + editMeta(itemStack, meta -> hideAttributes(meta, itemStack.getType())); } - public static void hideAttributes(@NotNull ItemMeta meta, @NotNull Material material) { - if (Version.isAtLeast(Version.MC_1_20_6) && material.isItem()) { - EquipmentSlot slot = material.getEquipmentSlot(); - material.getDefaultAttributeModifiers(slot).forEach((attribute, modifier) -> { - var modifiers = meta.getAttributeModifiers() == null ? null : meta.getAttributeModifiers(attribute); - if (modifiers == null || modifiers.isEmpty()) { - meta.addAttributeModifier(attribute, modifier); - } - }); + private static void hideAttributes(@NotNull ItemMeta meta, @NotNull Material material) { + if (Version.isBehind(Version.MC_1_21_5) && Version.isAtLeast(Version.MC_1_20_6)) { + if (material.isItem()) { + EquipmentSlot slot = material.getEquipmentSlot(); + material.getDefaultAttributeModifiers(slot).forEach((attribute, modifier) -> { + var modifiers = meta.getAttributeModifiers() == null ? null : meta.getAttributeModifiers(attribute); + if (modifiers == null || modifiers.isEmpty()) { + meta.addAttributeModifier(attribute, modifier); + } + }); + } } meta.addItemFlags(ItemFlag.values()); @@ -171,33 +221,6 @@ public class ItemUtil { editMeta(item, SkullMeta.class, meta -> { meta.setOwnerProfile(createSkinProfile(urlData)); }); -// if (urlData.isBlank()) return; -// if (item.getType() != Material.PLAYER_HEAD) return; -// if (!(item.getItemMeta() instanceof SkullMeta meta)) return; -// -// String name = urlData.substring(0, 16); -// -// if (!urlData.startsWith(TEXTURES_HOST)) { -// urlData = TEXTURES_HOST + urlData; -// } -// -// try { -// UUID uuid = UUID.nameUUIDFromBytes(urlData.getBytes()); -// // If no name, then meta#getOwnerProfile will return 'null' (wtf?) -// // sometimes swtiching to "new" spigot api is a pain. -// // why the hell i have to dig into nms to learn that... -// PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); -// URL url = URI.create(urlData).toURL();//new URL(urlData); -// PlayerTextures textures = profile.getTextures(); -// -// textures.setSkin(url); -// profile.setTextures(textures); -// meta.setOwnerProfile(profile); -// item.setItemMeta(meta); -// } -// catch (Exception exception) { -// exception.printStackTrace(); -// } } @Nullable diff --git a/src/main/java/su/nightexpress/nightcore/util/Players.java b/src/main/java/su/nightexpress/nightcore/util/Players.java index 023f273..3f1cb01 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Players.java +++ b/src/main/java/su/nightexpress/nightcore/util/Players.java @@ -1,6 +1,5 @@ package su.nightexpress.nightcore.util; -import net.md_5.bungee.api.ChatMessageType; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; @@ -15,7 +14,10 @@ import su.nightexpress.nightcore.integration.VaultHook; import su.nightexpress.nightcore.util.text.NightMessage; import su.nightexpress.nightcore.util.text.TextRoot; -import java.util.*; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; import java.util.function.Predicate; import java.util.stream.Stream; @@ -55,17 +57,6 @@ public class Players { @Deprecated public static List playerNames(@Nullable Player viewer, boolean includeCustom) { return playerNames(viewer); -// -// Set names = new HashSet<>(); -// for (Player player : Bukkit.getServer().getOnlinePlayers()) { -// if (viewer != null && !viewer.canSee(player)) continue; -// -// names.add(player.getName()); -// if (includeCustom && CoreConfig.RESPECT_PLAYER_DISPLAYNAME.get()) { -// names.add(Colorizer.strip(player.getDisplayName())); -// } -// } -// return names.stream().sorted(String::compareTo).toList(); } @NotNull @@ -76,43 +67,6 @@ public class Players { @Nullable public static Player getPlayer(@NotNull String name) { return Bukkit.getServer().getPlayer(name); -// -// if (!CoreConfig.RESPECT_PLAYER_DISPLAYNAME.get()) { -// return Bukkit.getServer().getPlayer(nameOrNick); -// } -// -// Player found = Bukkit.getServer().getPlayerExact(nameOrNick); -// if (found != null) { -// return found; -// } -// -// String lowerName = nameOrNick.toLowerCase(); -// int lowerLength = lowerName.length(); -// int delta = Integer.MAX_VALUE; -// -// for (Player player : Bukkit.getServer().getOnlinePlayers()) { -// String nameReal = player.getName().toLowerCase(Locale.ENGLISH); -// String nameCustom = player.getDisplayName().toLowerCase(); -// -// int length; -// if (nameReal.startsWith(lowerName)) { -// length = player.getName().length(); -// } -// else if (nameCustom.startsWith(lowerName)) { -// length = player.getDisplayName().length(); -// } -// else continue; -// -// int curDelta = Math.abs(length - lowerLength); -// if (curDelta < delta) { -// found = player; -// delta = curDelta; -// } -// -// if (curDelta == 0) break; -// } -// -// return found; } public static boolean isBedrock(@NotNull Player player) { @@ -130,7 +84,7 @@ public class Players { @NotNull public static Set getPermissionGroups(@NotNull Player player) { - return Plugins.hasVault() && VaultHook.hasPermissions() ? VaultHook.getPermissionGroups(player) : Set.of(Placeholders.DEFAULT); + return Plugins.hasVault() && VaultHook.hasPermissions() ? VaultHook.getPermissionGroups(player) : Lists.newSet(Placeholders.DEFAULT); } @NotNull @@ -152,7 +106,12 @@ public class Players { } public static void sendActionBar(@NotNull Player player, @NotNull TextRoot message) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, message.parseIfAbsent()); + message.parseIfAbsent().sendActionBar(player); + //player.spigot().sendMessage(ChatMessageType.ACTION_BAR, message.parseIfAbsent()); + } + + public static void sendTitle(@NotNull Player player, @NotNull String title, @NotNull String subtitle, int fadeIn, int stay, int fadeOut) { + Version.software().sendTitles(player, title, subtitle, fadeIn, stay, fadeOut); } public static void dispatchCommands(@NotNull Player player, @NotNull String... commands) { @@ -176,9 +135,6 @@ public class Players { command = Placeholders.forPlayerWithPAPI(player).apply(command).trim(); -// if (Plugins.hasPlaceholderAPI()) { -// command = PlaceholderAPI.setPlaceholders(player, command); -// } Bukkit.dispatchCommand(sender, command); } diff --git a/src/main/java/su/nightexpress/nightcore/util/Reflex.java b/src/main/java/su/nightexpress/nightcore/util/Reflex.java index ff76293..2c17740 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Reflex.java +++ b/src/main/java/su/nightexpress/nightcore/util/Reflex.java @@ -12,18 +12,22 @@ import java.util.List; public class Reflex { + @Nullable public static Class getClass(@NotNull String path, @NotNull String name) { return getClass(path + "." + name); } + @Nullable public static Class getInnerClass(@NotNull String path, @NotNull String name) { return getClass(path + "$" + name); } + @Nullable public static Class getNMSClass(@NotNull String path, @NotNull String realName) { return getNMSClass(path, realName, null); } + @Nullable public static Class getNMSClass(@NotNull String path, @NotNull String realName, @Nullable String obfName) { Class byRealName = getClass(path + "." + realName, false); if (byRealName != null) { diff --git a/src/main/java/su/nightexpress/nightcore/util/Version.java b/src/main/java/su/nightexpress/nightcore/util/Version.java index fb33d39..9ae0f8e 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Version.java +++ b/src/main/java/su/nightexpress/nightcore/util/Version.java @@ -4,9 +4,9 @@ import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightCore; import su.nightexpress.nightcore.NightCorePlugin; -import su.nightexpress.nightcore.util.bridge.PaperBridge; +import su.nightexpress.nightcore.util.bridge.paper.PaperBridge; import su.nightexpress.nightcore.util.bridge.Software; -import su.nightexpress.nightcore.util.bridge.SpigotBridge; +import su.nightexpress.nightcore.util.bridge.spigot.SpigotBridge; import java.util.Comparator; import java.util.stream.Stream; @@ -23,6 +23,7 @@ public enum Version { MC_1_21_2("1.21.2", Status.OUTDATED), MC_1_21_3("1.21.3"), MC_1_21_4("1.21.4"), + MC_1_21_5("1.21.5"), UNKNOWN("Unknown"), ; @@ -60,19 +61,7 @@ public enum Version { software.initialize(core); core.info("Server version detected as " + bukkitName + " " + current.getLocalized() + ". Using " + software().getName() + "."); - loadComponents(core); - } - - private static void loadComponents(@NotNull NightCore core) { - boolean nbtLoad = ItemNbt.load(core); - if (!nbtLoad) { - core.error("Could not load Item NBT Compressor."); - return; - } - - if (!ItemNbt.test()) { - core.error("Failed test of Item NBT Compressor."); - } + ItemNbt.load(core); } public static void printCaution(@NotNull NightCorePlugin plugin) { diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/PaperBridge.java b/src/main/java/su/nightexpress/nightcore/util/bridge/PaperBridge.java deleted file mode 100644 index 0f113fe..0000000 --- a/src/main/java/su/nightexpress/nightcore/util/bridge/PaperBridge.java +++ /dev/null @@ -1,66 +0,0 @@ -package su.nightexpress.nightcore.util.bridge; - -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.serializer.json.JSONComponentSerializer; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.SimpleCommandMap; -import org.bukkit.entity.Player; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.view.builder.InventoryViewBuilder; -import org.jetbrains.annotations.NotNull; -import su.nightexpress.nightcore.NightCore; -import su.nightexpress.nightcore.util.text.NightMessage; - -import java.util.Map; - -@SuppressWarnings("UnstableApiUsage") -public class PaperBridge implements Software { - - @Override - @NotNull - public String getName() { - return "paper-bridge"; - } - - @Override - public boolean isSpigot() { - return false; - } - - @Override - public boolean isPaper() { - return true; - } - - @Override - public boolean initialize(@NotNull NightCore core) { - return true; - } - - @NotNull - @Override - public InventoryView createView(@NotNull InventoryViewBuilder builder, @NotNull String title, @NotNull Player player) { - Component component = JSONComponentSerializer.json().deserialize(NightMessage.asJson(title)); // TODO Direct NightMessage to component - - return builder.title(component).build(player); - } - - @Override - @NotNull - public SimpleCommandMap getCommandMap() { - return (SimpleCommandMap) Bukkit.getCommandMap(); - } - - @Override - @NotNull - public Map getKnownCommands(@NotNull SimpleCommandMap commandMap) { - return commandMap.getKnownCommands(); - } - - @SuppressWarnings("deprecation") - @Override - public int nextEntityId() { - return Bukkit.getUnsafe().nextEntityId(); - } -} diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/Software.java b/src/main/java/su/nightexpress/nightcore/util/bridge/Software.java index 95bb5ee..c9ece55 100644 --- a/src/main/java/su/nightexpress/nightcore/util/bridge/Software.java +++ b/src/main/java/su/nightexpress/nightcore/util/bridge/Software.java @@ -4,10 +4,15 @@ import org.bukkit.command.Command; import org.bukkit.command.SimpleCommandMap; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.view.builder.InventoryViewBuilder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.MenuType; +import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightCore; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; +import su.nightexpress.nightcore.util.text.ComponentBuildable; +import java.util.List; import java.util.Map; @SuppressWarnings("UnstableApiUsage") @@ -21,11 +26,30 @@ public interface Software { boolean isPaper(); - @NotNull InventoryView createView(@NotNull InventoryViewBuilder builder, @NotNull String title, @NotNull Player player); + int nextEntityId(); @NotNull SimpleCommandMap getCommandMap(); @NotNull Map getKnownCommands(@NotNull SimpleCommandMap commandMap); - int nextEntityId(); + @NotNull NightComponent textComponent(@NotNull String text); + + @NotNull NightComponent translateComponent(@NotNull String key); + + @NotNull NightComponent buildComponent(@NotNull List childrens); + + @NotNull InventoryView createView(@NotNull MenuType menuType, @NotNull String title, @NotNull Player player); + + + + void sendTitles(@NotNull Player player, @NotNull String title, @NotNull String subtitle, int fadeIn, int stay, int fadeOut); + + + void setDisplayName(@NotNull ItemMeta meta, @NotNull String name); + + void setItemName(@NotNull ItemMeta meta, @NotNull String name); + + void setLore(@NotNull ItemMeta meta, @NotNull List lore); + + void hideComponents(@NotNull ItemStack itemStack); } diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/paper/PaperBridge.java b/src/main/java/su/nightexpress/nightcore/util/bridge/paper/PaperBridge.java new file mode 100644 index 0000000..4e465be --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/bridge/paper/PaperBridge.java @@ -0,0 +1,157 @@ +package su.nightexpress.nightcore.util.bridge.paper; + +import io.papermc.paper.datacomponent.DataComponentType; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.TooltipDisplay; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.title.Title; +import net.kyori.adventure.util.Ticks; +import org.bukkit.Bukkit; +import org.bukkit.Registry; +import org.bukkit.command.Command; +import org.bukkit.command.SimpleCommandMap; +import org.bukkit.entity.Player; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.MenuType; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCore; +import su.nightexpress.nightcore.util.BukkitThing; +import su.nightexpress.nightcore.util.Lists; +import su.nightexpress.nightcore.util.Version; +import su.nightexpress.nightcore.util.bridge.Software; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; +import su.nightexpress.nightcore.util.text.ComponentBuildable; +import su.nightexpress.nightcore.util.text.NightMessage; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +@SuppressWarnings("UnstableApiUsage") +public class PaperBridge implements Software { + + private Set componentTypes; + + @Override + @NotNull + public String getName() { + return "paper-bridge"; + } + + @Override + public boolean isSpigot() { + return false; + } + + @Override + public boolean isPaper() { + return true; + } + + @Override + public boolean initialize(@NotNull NightCore core) { + if (Version.isAtLeast(Version.MC_1_21_5)) { + this.componentTypes = BukkitThing.allFromRegistry(Registry.DATA_COMPONENT_TYPE); + this.componentTypes.remove(DataComponentTypes.LORE); + this.componentTypes.remove(DataComponentTypes.ITEM_NAME); + this.componentTypes.remove(DataComponentTypes.ITEM_MODEL); + this.componentTypes.remove(DataComponentTypes.CUSTOM_NAME); + this.componentTypes.remove(DataComponentTypes.CUSTOM_MODEL_DATA); + this.componentTypes.remove(DataComponentTypes.TOOLTIP_DISPLAY); + this.componentTypes.remove(DataComponentTypes.TOOLTIP_STYLE); + } + + return true; + } + + @SuppressWarnings("deprecation") + @Override + public int nextEntityId() { + return Bukkit.getUnsafe().nextEntityId(); + } + + @Override + @NotNull + public SimpleCommandMap getCommandMap() { + return (SimpleCommandMap) Bukkit.getCommandMap(); + } + + @Override + @NotNull + public Map getKnownCommands(@NotNull SimpleCommandMap commandMap) { + return commandMap.getKnownCommands(); + } + + @Override + @NotNull + public PaperComponent textComponent(@NotNull String text) { + return PaperComponent.text(text); + } + + @Override + @NotNull + public PaperComponent translateComponent(@NotNull String key) { + return PaperComponent.translate(key); + } + + @Override + @NotNull + public PaperComponent buildComponent(@NotNull List childrens) { + return PaperComponent.builder(childrens); + } + + @NotNull + private static Component fromNightComponent(@NotNull String component) { + return fromNightComponent(NightMessage.parse(component)); + } + + @NotNull + private static Component fromNightComponent(@NotNull NightComponent component) { + return ((PaperComponent)component).getParent(); + } + + @Override + public void sendTitles(@NotNull Player player, @NotNull String title, @NotNull String subtitle, int fadeIn, int stay, int fadeOut) { + Component titleComp = fromNightComponent(title); + Component subComp = fromNightComponent(subtitle); + + Title.Times times = Title.Times.times(Ticks.duration(fadeIn), Ticks.duration(stay), Ticks.duration(fadeIn)); + Title titles = Title.title(titleComp, subComp, times); + + player.showTitle(titles); + } + + @Override + @NotNull + public InventoryView createView(@NotNull MenuType menuType, @NotNull String title, @NotNull Player player) { + if (Version.isAtLeast(Version.MC_1_21_4)) { + return menuType.typed().builder().title(fromNightComponent(title)).build(player); + } + else { + return menuType.typed().create(player, fromNightComponent(title)); + } + } + + @Override + public void setDisplayName(@NotNull ItemMeta meta, @NotNull String name) { + meta.displayName(fromNightComponent(name)); + } + + @Override + public void setItemName(@NotNull ItemMeta meta, @NotNull String name) { + meta.itemName(fromNightComponent(name)); + } + + @Override + public void setLore(@NotNull ItemMeta meta, @NotNull List lore) { + meta.lore(Lists.modify(lore, PaperBridge::fromNightComponent)); + } + + @Override + public void hideComponents(@NotNull ItemStack itemStack) { + TooltipDisplay tooltipDisplay = TooltipDisplay.tooltipDisplay().hiddenComponents(this.componentTypes).build(); + itemStack.setData(DataComponentTypes.TOOLTIP_DISPLAY, tooltipDisplay); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/paper/PaperComponent.java b/src/main/java/su/nightexpress/nightcore/util/bridge/paper/PaperComponent.java new file mode 100644 index 0000000..f5a98f6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/bridge/paper/PaperComponent.java @@ -0,0 +1,206 @@ +package su.nightexpress.nightcore.util.bridge.paper; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.format.TextColor; +import net.kyori.adventure.text.format.TextDecoration; +import net.kyori.adventure.text.serializer.json.JSONComponentSerializer; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.ItemNbt; +import su.nightexpress.nightcore.util.Lists; +import su.nightexpress.nightcore.util.bridge.wrapper.ClickEventType; +import su.nightexpress.nightcore.util.bridge.wrapper.HoverEventType; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; +import su.nightexpress.nightcore.util.text.ComponentBuildable; +import su.nightexpress.nightcore.util.text.NightMessage; + +import java.awt.*; +import java.util.List; + +public class PaperComponent implements NightComponent { + + private Component parent; + + public PaperComponent(@NotNull Component parent) { + this.parent = parent; + } + + @NotNull + public static PaperComponent text(@NotNull String text) { + return new PaperComponent(Component.text(text)); + } + + @NotNull + public static PaperComponent translate(@NotNull String key) { + return new PaperComponent(Component.translatable(key)); + } + + @NotNull + public static PaperComponent builder(@NotNull List childrens) { + // Force remove all decortaions, otherwise it'll be decorated by default (italic on items, etc). + var builder = Component.text().decorations(Lists.newSet(TextDecoration.values()), false); + + childrens.forEach(child -> { + PaperComponent childComponent = (PaperComponent) child.toComponent(); + builder.append(childComponent.parent); + }); + + return new PaperComponent(builder.build()); + } + + @NotNull + public Component getParent() { + return this.parent; + } + + @Override + @NotNull + public NightComponent duplicate() { + return new PaperComponent(Component.empty().append(this.parent).asComponent()); + } + + @Override + @NotNull + public String toJson() { + return JSONComponentSerializer.json().serialize(this.parent); + } + + @Override + @NotNull + public String toLegacy() { + return LegacyComponentSerializer.legacy('§').serialize(this.parent); + } + + @Override + public void send(@NotNull CommandSender sender) { + sender.sendMessage(this.parent); + } + + @Override + public void sendActionBar(@NotNull Player player) { + player.sendActionBar(this.parent); + } + + @Override + public boolean isEmpty() { + return this.parent instanceof TextComponent textComponent && textComponent.content().isEmpty() && textComponent.children().isEmpty(); + } + + @Override + public boolean isText() { + return this.parent instanceof TextComponent; + } + + @Override + @NotNull + public String getText() { + return this.parent instanceof TextComponent textComponent ? textComponent.content() : ""; + } + + @Override + @NotNull + public List getChildrens() { + return this.parent.children().stream().map(PaperComponent::new).toList(); + } + + @Override + public void setChildrens(@NotNull List childrens) { + this.parent = this.parent.children(childrens.stream().map(child -> ((PaperComponent)child).parent).toList()); + } + + @Override + public void addChildren(@NotNull NightComponent other) { + if (other instanceof PaperComponent paperComponent) { + this.parent = this.parent.append(paperComponent.parent); + } + } + + @Override + public void setText(@NotNull String text) { + if (this.parent instanceof TextComponent textComponent) { + this.parent = textComponent.content(text); + } + } + + @Override + public void setColor(@NotNull Color color) { + this.parent = this.parent.color(TextColor.color(color.getRed(), color.getGreen(), color.getBlue())); + } + + @Override + public void setClickEvent(@NotNull ClickEventType type, @NotNull String value) { + ClickEvent.Action action = switch (type) { + case COPY_TO_CLIPBOARD -> ClickEvent.Action.COPY_TO_CLIPBOARD; + case SUGGEST_COMMAND -> ClickEvent.Action.SUGGEST_COMMAND; + case RUN_COMMAND -> ClickEvent.Action.RUN_COMMAND; + case CHANGE_PAGE -> ClickEvent.Action.CHANGE_PAGE; + case OPEN_FILE -> ClickEvent.Action.OPEN_FILE; + case OPEN_URL -> ClickEvent.Action.OPEN_URL; + }; + + this.parent = this.parent.clickEvent(ClickEvent.clickEvent(action, value)); + } + + @Override + public void setHoverEvent(@NotNull HoverEventType type, @NotNull String value) { + HoverEvent event = null; + + switch (type) { + case SHOW_TEXT -> { + PaperComponent component = (PaperComponent) NightMessage.parse(value); + event = HoverEvent.showText(component.parent); + } + case SHOW_ITEM -> { + ItemStack itemStack = ItemNbt.getHoverEventItem(value); + event = itemStack.asHoverEvent(); + } + } + if (event == null) return; + + this.parent = this.parent.hoverEvent(event); + } + + @Override + public void setFont(@NotNull String font) { + this.parent = this.parent.font(Key.key(font)); + } + + @Override + public void setBold(boolean bold) { + this.parent = this.parent.decoration(TextDecoration.BOLD, bold); + } + + @Override + public void setItalic(boolean italic) { + this.parent = this.parent.decoration(TextDecoration.ITALIC, italic); + } + + @Override + public void setObfuscated(boolean obfuscated) { + this.parent = this.parent.decoration(TextDecoration.OBFUSCATED, obfuscated); + } + + @Override + public void setUnderlined(boolean underlined) { + this.parent = this.parent.decoration(TextDecoration.UNDERLINED, underlined); + } + + @Override + public void setStrikethrough(boolean strikethrough) { + this.parent = this.parent.decoration(TextDecoration.STRIKETHROUGH, strikethrough); + } + + @Override + public String toString() { + return "PaperComponent{" + + "parent=" + parent + + '}'; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/SpigotBridge.java b/src/main/java/su/nightexpress/nightcore/util/bridge/spigot/SpigotBridge.java similarity index 51% rename from src/main/java/su/nightexpress/nightcore/util/bridge/SpigotBridge.java rename to src/main/java/su/nightexpress/nightcore/util/bridge/spigot/SpigotBridge.java index f071b76..cfbbac5 100644 --- a/src/main/java/su/nightexpress/nightcore/util/bridge/SpigotBridge.java +++ b/src/main/java/su/nightexpress/nightcore/util/bridge/spigot/SpigotBridge.java @@ -1,22 +1,30 @@ -package su.nightexpress.nightcore.util.bridge; +package su.nightexpress.nightcore.util.bridge.spigot; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.SimpleCommandMap; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.view.builder.InventoryViewBuilder; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.MenuType; +import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightCore; +import su.nightexpress.nightcore.util.ItemUtil; import su.nightexpress.nightcore.util.Reflex; import su.nightexpress.nightcore.util.Version; +import su.nightexpress.nightcore.util.bridge.Software; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; +import su.nightexpress.nightcore.util.text.ComponentBuildable; import su.nightexpress.nightcore.util.text.NightMessage; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; -@SuppressWarnings("UnstableApiUsage") +@SuppressWarnings({"UnstableApiUsage", "deprecation"}) public class SpigotBridge implements Software { private static final String FIELD_COMMAND_MAP = "commandMap"; @@ -76,17 +84,14 @@ public class SpigotBridge implements Software { return false; } - @NotNull @Override - public InventoryView createView(@NotNull InventoryViewBuilder builder, @NotNull String title, @NotNull Player player) { - Reflex.setFieldValue(builder, "title", NightMessage.asLegacy(title)); - return builder.build(player);//menuType.typed().builder().title(title).build(player); + public int nextEntityId() { + return entityCounter.incrementAndGet(); } @NotNull @Override public SimpleCommandMap getCommandMap() { - //SimpleCommandMap commandMap = (SimpleCommandMap) Reflex.getFieldValue(Bukkit.getServer(), FIELD_COMMAND_MAP); if (commandMap == null) throw new IllegalStateException("Command map is null!"); return commandMap; @@ -101,7 +106,72 @@ public class SpigotBridge implements Software { } @Override - public int nextEntityId() { - return entityCounter.incrementAndGet(); + @NotNull + public NightComponent textComponent(@NotNull String text) { + return SpigotComponent.text(text); + } + + @Override + @NotNull + public NightComponent translateComponent(@NotNull String key) { + return SpigotComponent.translate(key); + } + + @Override + @NotNull + public NightComponent buildComponent(@NotNull List childrens) { + return SpigotComponent.builder(childrens); + } + + @Override + public void sendTitles(@NotNull Player player, @NotNull String title, @NotNull String subtitle, int fadeIn, int stay, int fadeOut) { + title = NightMessage.asLegacy(title); + subtitle = NightMessage.asLegacy(subtitle); + + player.sendTitle(title, subtitle, fadeIn, stay, fadeOut); + } + + @Override + @NotNull + public InventoryView createView(@NotNull MenuType menuType, @NotNull String title, @NotNull Player player) { + String legacy = NightMessage.asLegacy(title); + + if (Version.isAtLeast(Version.MC_1_21_4)) { + var builder = menuType.typed().builder(); + Reflex.setFieldValue(builder, "title", legacy); + return builder.build(player); + } + else { + return menuType.typed().create(player, legacy); + } + } + + @Override + public void setDisplayName(@NotNull ItemMeta meta, @NotNull String name) { + meta.setDisplayName(NightMessage.asLegacy(name)); + } + + @Override + public void setItemName(@NotNull ItemMeta meta, @NotNull String name) { + meta.setItemName(NightMessage.asLegacy(name)); + } + + @Override + public void setLore(@NotNull ItemMeta meta, @NotNull List lore) { + meta.setLore(NightMessage.asLegacy(lore)); + } + + @Override + public void hideComponents(@NotNull ItemStack itemStack) { + ItemUtil.editMeta(itemStack, meta -> { + meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + meta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE); + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + meta.addItemFlags(ItemFlag.HIDE_PLACED_ON); + meta.addItemFlags(ItemFlag.HIDE_DESTROYS); + meta.addItemFlags(ItemFlag.HIDE_DYE); + meta.addItemFlags(ItemFlag.HIDE_ARMOR_TRIM); + meta.addItemFlags(ItemFlag.valueOf("HIDE_ADDITIONAL_TOOLTIP")); + }); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/spigot/SpigotComponent.java b/src/main/java/su/nightexpress/nightcore/util/bridge/spigot/SpigotComponent.java new file mode 100644 index 0000000..f3f483f --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/bridge/spigot/SpigotComponent.java @@ -0,0 +1,223 @@ +package su.nightexpress.nightcore.util.bridge.spigot; + +import net.md_5.bungee.api.ChatColor; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.chat.*; +import net.md_5.bungee.api.chat.hover.content.Item; +import net.md_5.bungee.api.chat.hover.content.Text; +import net.md_5.bungee.chat.ComponentSerializer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.BukkitThing; +import su.nightexpress.nightcore.util.ItemNbt; +import su.nightexpress.nightcore.util.Version; +import su.nightexpress.nightcore.util.bridge.wrapper.ClickEventType; +import su.nightexpress.nightcore.util.bridge.wrapper.HoverEventType; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; +import su.nightexpress.nightcore.util.text.ComponentBuildable; +import su.nightexpress.nightcore.util.text.NightMessage; + +import java.awt.*; +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings("deprecation") +public class SpigotComponent implements NightComponent { + + private final BaseComponent parent; + + public SpigotComponent(BaseComponent parent) { + this.parent = parent; + } + + @NotNull + public static SpigotComponent text(@NotNull String text) { + return new SpigotComponent(new TextComponent(text)); + } + + @NotNull + public static SpigotComponent translate(@NotNull String key) { + return new SpigotComponent(new TranslatableComponent(key)); + } + + public static SpigotComponent builder(@NotNull List childrens) { + ComponentBuilder builder = new ComponentBuilder(); + + childrens.forEach(child -> { + SpigotComponent childComponent = (SpigotComponent) child.toComponent(); + builder.append(childComponent.parent); + }); + + return new SpigotComponent(build(builder)); + } + + private static BaseComponent build(@NotNull ComponentBuilder builder) { + if (Version.isAtLeast(Version.MC_1_20_6)) { + return builder.build(); + } + + TextComponent base = new TextComponent(); + if (!builder.getParts().isEmpty()) { + List cloned = new ArrayList<>(builder.getParts()); + cloned.replaceAll(BaseComponent::duplicate); + base.setExtra(cloned); + } + return base; + } + + @NotNull + public BaseComponent getParent() { + return this.parent; + } + + @Override + @NotNull + public NightComponent duplicate() { + return new SpigotComponent(this.parent.duplicate()); + } + + @Override + @NotNull + public String toJson() { + return ComponentSerializer.toString(this.parent); + } + + @Override + @NotNull + public String toLegacy() { + return TextComponent.toLegacyText(this.parent); + } + + @Override + public void send(@NotNull CommandSender sender) { + sender.spigot().sendMessage(this.parent); + } + + @Override + public void sendActionBar(@NotNull Player player) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, this.parent); + } + + @Override + public boolean isEmpty() { + return this.parent instanceof TextComponent textComponent && textComponent.getText().isBlank() && textComponent.getExtra() == null; + } + + @Override + public boolean isText() { + return this.parent instanceof TextComponent; + } + + @Override + @NotNull + public String getText() { + return this.parent instanceof TextComponent textComponent ? textComponent.getText() : ""; + } + + @Override + @NotNull + public List getChildrens() { + return this.parent.getExtra().stream().map(SpigotComponent::new).toList(); + } + + @Override + public void setChildrens(@NotNull List childrens) { + this.parent.setExtra(childrens.stream().map(child -> ((SpigotComponent)child).parent).toList()); + } + + @Override + public void addChildren(@NotNull NightComponent other) { + if (other instanceof SpigotComponent spigotComponent) { + this.parent.addExtra(spigotComponent.getParent()); + } + } + + @Override + public void setText(@NotNull String text) { + if (this.parent instanceof TextComponent textComponent) { + textComponent.setText(text); + } + } + + @Override + public void setColor(@NotNull Color color) { + this.parent.setColor(ChatColor.of(color)); + } + + @Override + public void setClickEvent(@NotNull ClickEventType type, @NotNull String value) { + ClickEvent.Action action = switch (type) { + case OPEN_URL -> ClickEvent.Action.OPEN_URL; + case OPEN_FILE -> ClickEvent.Action.OPEN_FILE; + case CHANGE_PAGE -> ClickEvent.Action.CHANGE_PAGE; + case RUN_COMMAND -> ClickEvent.Action.RUN_COMMAND; + case SUGGEST_COMMAND -> ClickEvent.Action.SUGGEST_COMMAND; + case COPY_TO_CLIPBOARD -> ClickEvent.Action.COPY_TO_CLIPBOARD; + }; + + this.parent.setClickEvent(new ClickEvent(action, value)); + } + + @Override + public void setHoverEvent(@NotNull HoverEventType type, @NotNull String value) { + switch (type) { + case SHOW_TEXT -> { + SpigotComponent component = (SpigotComponent) NightMessage.parse(value); + + Text text; + if (Version.isAtLeast(Version.MC_1_20_6)) { + text = new Text(component.parent); + } + else { + text = new Text(new ComponentBuilder().append(component.parent).create()); + } + + this.parent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, text)); + } + case SHOW_ITEM -> { + ItemStack itemStack = ItemNbt.getHoverEventItem(value); + + String key = BukkitThing.toString(itemStack.getType()); + ItemMeta meta = itemStack.getItemMeta(); + String nbt = meta == null ? "{}" : meta.getAsString(); + + Item item = new Item(key, itemStack.getAmount(), ItemTag.ofNbt(nbt)); + this.parent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, item)); + } + } + } + + @Override + public void setFont(@NotNull String font) { + this.parent.setFont(font); + } + + @Override + public void setBold(boolean bold) { + this.parent.setBold(bold); + } + + @Override + public void setItalic(boolean italic) { + this.parent.setItalic(italic); + } + + @Override + public void setObfuscated(boolean obfuscated) { + this.parent.setObfuscated(obfuscated); + } + + @Override + public void setUnderlined(boolean underlined) { + this.parent.setUnderlined(underlined); + } + + @Override + public void setStrikethrough(boolean strikethrough) { + this.parent.setStrikethrough(strikethrough); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/ClickEventType.java b/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/ClickEventType.java new file mode 100644 index 0000000..7c1fe49 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/ClickEventType.java @@ -0,0 +1,11 @@ +package su.nightexpress.nightcore.util.bridge.wrapper; + +public enum ClickEventType { + + OPEN_URL, + OPEN_FILE, + RUN_COMMAND, + SUGGEST_COMMAND, + CHANGE_PAGE, + COPY_TO_CLIPBOARD +} diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/HoverEventType.java b/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/HoverEventType.java new file mode 100644 index 0000000..70100bf --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/HoverEventType.java @@ -0,0 +1,8 @@ +package su.nightexpress.nightcore.util.bridge.wrapper; + +public enum HoverEventType { + + SHOW_TEXT, + SHOW_ITEM + //SHOW_ENTITY, +} diff --git a/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/NightComponent.java b/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/NightComponent.java new file mode 100644 index 0000000..4e1c140 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/bridge/wrapper/NightComponent.java @@ -0,0 +1,53 @@ +package su.nightexpress.nightcore.util.bridge.wrapper; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.awt.*; +import java.util.List; + +public interface NightComponent { + + @NotNull NightComponent duplicate(); + + @NotNull String toJson(); + + @NotNull String toLegacy(); + + void send(@NotNull CommandSender sender); + + void sendActionBar(@NotNull Player player); + + boolean isEmpty(); + + boolean isText(); + + @NotNull String getText(); + + @NotNull List getChildrens(); + + void setChildrens(@NotNull List childrens); + + void addChildren(@NotNull NightComponent other); + + void setText(@NotNull String text); + + void setColor(@NotNull Color color); + + void setClickEvent(@NotNull ClickEventType type, @NotNull String value); + + void setHoverEvent(@NotNull HoverEventType type, @NotNull String value); + + void setFont(@NotNull String font); + + void setBold(boolean bold); + + void setItalic(boolean italic); + + void setObfuscated(boolean obfuscated); + + void setUnderlined(boolean underlined); + + void setStrikethrough(boolean strikethrough); +} diff --git a/src/main/java/su/nightexpress/nightcore/util/bukkit/NightItem.java b/src/main/java/su/nightexpress/nightcore/util/bukkit/NightItem.java index f1a4749..1b2fb7d 100644 --- a/src/main/java/su/nightexpress/nightcore/util/bukkit/NightItem.java +++ b/src/main/java/su/nightexpress/nightcore/util/bukkit/NightItem.java @@ -127,7 +127,7 @@ public class NightItem implements Writeable { @NotNull public ItemStack getItemStack() { ItemStack stack = new ItemStack(this.itemStack); - this.meta.apply(stack, true); + this.meta.apply(stack/*, true*/); return stack; } diff --git a/src/main/java/su/nightexpress/nightcore/util/bukkit/NightMeta.java b/src/main/java/su/nightexpress/nightcore/util/bukkit/NightMeta.java index 6edfa5d..1bb7f93 100644 --- a/src/main/java/su/nightexpress/nightcore/util/bukkit/NightMeta.java +++ b/src/main/java/su/nightexpress/nightcore/util/bukkit/NightMeta.java @@ -14,11 +14,10 @@ import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.config.FileConfig; import su.nightexpress.nightcore.config.Writeable; import su.nightexpress.nightcore.core.CoreLang; -import su.nightexpress.nightcore.language.entry.LangUIButton; import su.nightexpress.nightcore.language.entry.LangItem; +import su.nightexpress.nightcore.language.entry.LangUIButton; import su.nightexpress.nightcore.util.*; import su.nightexpress.nightcore.util.placeholder.Replacer; -import su.nightexpress.nightcore.util.text.NightMessage; import java.nio.charset.StandardCharsets; import java.util.*; @@ -107,14 +106,14 @@ public class NightMeta implements Writeable { displayMeta.setSkullOwner(skullMeta.getOwnerProfile()); } - displayMeta.setDisplayName(meta.hasDisplayName() ? meta.getDisplayName() : null); - displayMeta.setLore(meta.getLore()); + displayMeta.setDisplayName(meta.hasDisplayName() ? ItemUtil.getSerializedDisplayName(meta)/*meta.getDisplayName()*/ : null); + displayMeta.setLore(ItemUtil.getSerializedLore(meta)); displayMeta.setEnchants(meta.getEnchants()); displayMeta.setUnbreakable(meta.isUnbreakable()); displayMeta.setSkinURL(ItemUtil.getHeadSkin(itemStack)); displayMeta.setModelData(meta.hasCustomModelData() ? meta.getCustomModelData() : null); if (Version.isAtLeast(Version.MC_1_21)) { - displayMeta.setItemName(meta.hasItemName() ? meta.getItemName() : null); + displayMeta.setItemName(meta.hasItemName() ? ItemUtil.getSerializedItemName(meta)/*meta.getItemName()*/ : null); displayMeta.setEnchantGlint((meta.hasEnchantmentGlintOverride() && meta.getEnchantmentGlintOverride())/* || meta.hasEnchants()*/); displayMeta.setHideTooltip(meta.isHideTooltip()); } @@ -253,19 +252,22 @@ public class NightMeta implements Writeable { config.set(path + ".Color", this.color == null ? null : color.getRed() + "," + color.getBlue() + "," + color.getGreen()); } - public void apply(@NotNull ItemStack itemStack, boolean legacy) { + public void apply(@NotNull ItemStack itemStack/*, boolean legacy*/) { ItemUtil.editMeta(itemStack, meta -> { if (this.displayName != null) { String name = this.replacer == null ? this.displayName : this.replacer.apply(this.displayName); - meta.setDisplayName(legacy ? NightMessage.asLegacy(name) : name); + ItemUtil.setDisplayName(meta, name); + //meta.setDisplayName(legacy ? NightMessage.asLegacy(name) : name); } if (this.itemName != null && Version.isAtLeast(Version.MC_1_21)) { String name = this.replacer == null ? this.itemName : this.replacer.apply(this.itemName); - meta.setItemName(name == null ? null : (legacy ? NightMessage.asLegacy(name) : name)); + ItemUtil.setItemName(meta, name); + //meta.setItemName(name == null ? null : (legacy ? NightMessage.asLegacy(name) : name)); } if (this.lore != null) { List lore = this.replacer == null ? this.lore : this.replacer.apply(this.lore); - meta.setLore(legacy ? NightMessage.asLegacy(this.addEmptyLines(lore)) : this.addEmptyLines(lore)); + ItemUtil.setLore(meta, this.addEmptyLines(lore)); + //meta.setLore(legacy ? NightMessage.asLegacy(this.addEmptyLines(lore)) : this.addEmptyLines(lore)); } if (this.modelData != null) { meta.setCustomModelData(this.modelData); @@ -277,9 +279,9 @@ public class NightMeta implements Writeable { meta.setUnbreakable(this.unbreakable); - if (this.hideComponents) { - ItemUtil.hideAttributes(meta, itemStack.getType()); - } +// if (this.hideComponents) { +// ItemUtil.hideAttributes(meta, itemStack.getType()); +// } if (Version.isAtLeast(Version.MC_1_21)) { if (this.enchantGlint) meta.setEnchantmentGlintOverride(true); @@ -306,6 +308,10 @@ public class NightMeta implements Writeable { } } }); + + if (this.hideComponents && !this.hideTooltip) { + ItemUtil.hideAttributes(itemStack); + } } @NotNull @@ -360,7 +366,7 @@ public class NightMeta implements Writeable { for (String entry : locale.getDescription()) { lore.add(CoreLang.EDITOR_BUTTON_DESCRIPTION.getString().replace(Placeholders.GENERIC_ENTRY, entry)); } - lore.add(Placeholders.EMPTY_IF_BELOW); + lore.add(Placeholders.EMPTY_IF_ABOVE); locale.getClickActions().forEach((key, action) -> { lore.add(CoreLang.EDITOR_BUTTON_CLICK_KEY.getString() diff --git a/src/main/java/su/nightexpress/nightcore/util/geodata/Cuboid.java b/src/main/java/su/nightexpress/nightcore/util/geodata/Cuboid.java new file mode 100644 index 0000000..97fe866 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/geodata/Cuboid.java @@ -0,0 +1,279 @@ +package su.nightexpress.nightcore.util.geodata; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.geodata.pos.BlockPos; +import su.nightexpress.nightcore.util.geodata.pos.ChunkPos; +import su.nightexpress.nightcore.util.geodata.pos.ExactPos; + +import java.util.*; +import java.util.stream.Collectors; + +public class Cuboid { + + private final BlockPos min; + private final BlockPos max; + private final BlockPos center; + + private final BlockPos minUp; + private final BlockPos maxDown; + + private final BlockPos zUp; + private final BlockPos zDown; + + private final BlockPos xDown; + private final BlockPos xUp; + + private final boolean empty; + + private final Set intersectingChunks; + + public Cuboid(@NotNull BlockPos min, @NotNull BlockPos max) { + int minX = Math.min(min.getX(), max.getX()); + int minY = Math.min(min.getY(), max.getY()); + int minZ = Math.min(min.getZ(), max.getZ()); + + int maxX = Math.max(min.getX(), max.getX()); + int maxY = Math.max(min.getY(), max.getY()); + int maxZ = Math.max(min.getZ(), max.getZ()); + + this.min = new BlockPos(minX, minY, minZ); + this.max = new BlockPos(maxX, maxY, maxZ); + + int cx = (int) (minX + (maxX - minX) / 2D); + int cy = (int) (minY + (maxY - minY) / 2D); + int cz = (int) (minZ + (maxZ - minZ) / 2D); + + this.center = new BlockPos(cx, cy, cz); + + this.empty = this.min.isEmpty() && this.max.isEmpty(); + + minUp = new BlockPos(this.min.getX(), this.max.getY(), this.min.getZ()); + maxDown = new BlockPos(this.max.getX(), this.min.getY(), this.max.getZ()); + + zUp = new BlockPos(this.min.getX(), this.max.getY(), this.max.getZ()); + zDown = new BlockPos(this.min.getX(), this.min.getY(), this.max.getZ()); + + xDown = new BlockPos(this.max.getX(), this.min.getY(), this.min.getZ()); + xUp = new BlockPos(this.max.getX(), this.max.getY(), this.min.getZ()); + + this.intersectingChunks = new HashSet<>(this.getIntersectingChunks()); + } + + public boolean isSimilar(@NotNull Cuboid other) { + if (this.isEmpty() || other.isEmpty()) return false; + + return this.min.equals(other.min) && this.max.equals(other.max); + } + + public boolean isEmpty() { + return this.empty; + } + + public boolean contains(@NotNull Location location) { + return this.contains(location, DimensionType._3D); + } + + public boolean contains(@NotNull Location location, @NotNull DimensionType type) { + return this.contains(BlockPos.from(location), type); + } + + public boolean contains(@NotNull ExactPos pos) { + return this.contains(pos.toBlockPos()); + } + + public boolean contains(@NotNull BlockPos pos) { + return this.contains(pos, DimensionType._3D); + } + + public boolean contains(@NotNull ChunkPos pos) { + return this.containsX(GeoUtils.shiftToCoord(pos.getX())) && this.containsZ(GeoUtils.shiftToCoord(pos.getZ())); + } + + public boolean contains(@NotNull BlockPos pos, @NotNull DimensionType type) { + if (!this.containsX(pos.getX())) return false; + if (!this.containsZ(pos.getZ())) return false; + + if (type == DimensionType._3D) { + return this.containsY(pos.getY()); + } + return true; + } + + public boolean containsX(int x) { + return x >= this.min.getX() && x <= this.max.getX(); + } + + public boolean containsY(int y) { + return y >= this.min.getY() && y <= this.max.getY(); + } + + public boolean containsZ(int z) { + return z >= this.min.getZ() && z <= this.max.getZ(); + } + + @NotNull + public List getBlocks(@NotNull World world) { + List blocks = new ArrayList<>(); + + for (int x = this.min.getX(); x <= this.max.getX(); x++) { + for (int y = this.min.getY(); y <= this.max.getY(); y++) { + for (int z = this.min.getZ(); z <= this.max.getZ(); z++) { + Block block = world.getBlockAt(x, y, z); + blocks.add(block); + } + } + } + + return blocks; + } + + @NotNull + public List getCorners() { + List list = new ArrayList<>(); + + list.add(this.min); + list.add(this.max); + list.add(minUp); + list.add(maxDown); + list.add(zUp); + list.add(zDown); + list.add(xUp); + list.add(xDown); + + return list; + } + + @NotNull + public List getCornerWiresY() { + List list = new ArrayList<>(); + + for (int y = this.min.getY() + 1; y < this.minUp.getY(); y++) { + list.add(new BlockPos(this.min.getX(), y, this.min.getZ())); + } + + for (int y = this.max.getY() - 1; y > this.maxDown.getY(); y--) { + list.add(new BlockPos(this.max.getX(), y, this.max.getZ())); + } + + for (int y = this.zDown.getY() + 1; y < this.zUp.getY(); y++) { + list.add(new BlockPos(this.zDown.getX(), y, this.zDown.getZ())); + } + + for (int y = this.xDown.getY() + 1; y < this.xUp.getY(); y++) { + list.add(new BlockPos(this.xDown.getX(), y, this.xDown.getZ())); + } + + return list; + } + + @NotNull + public List getCornerWiresX() { + List list = new ArrayList<>(); + + for (int x = this.min.getX() + 1; x < this.xDown.getX(); x++) { + list.add(new BlockPos(x, this.min.getY(), this.min.getZ())); + list.add(new BlockPos(x, this.minUp.getY(), this.minUp.getZ())); + } + for (int x = this.zDown.getX() + 1; x < this.max.getX(); x++) { + list.add(new BlockPos(x, this.zDown.getY(), this.zDown.getZ())); + list.add(new BlockPos(x, this.zUp.getY(), this.zUp.getZ())); + } + + return list; + } + + @NotNull + public List getCornerWiresZ() { + List list = new ArrayList<>(); + + for (int z = this.min.getZ() + 1; z < this.zDown.getZ(); z++) { + list.add(new BlockPos(this.min.getX(), this.min.getY(), z)); + list.add(new BlockPos(this.min.getX(), this.minUp.getY(), z)); + } + for (int z = this.xDown.getZ() + 1; z < this.max.getZ(); z++) { + list.add(new BlockPos(this.xDown.getX(), this.xDown.getY(), z)); + list.add(new BlockPos(this.xUp.getX(), this.xUp.getY(), z)); + } + + return list; + } + + public boolean isIntersectingWith(@NotNull Cuboid other) { + return this.isIntersectingWith(other, DimensionType._3D); + } + + public boolean isIntersectingWith(@NotNull Cuboid other, @NotNull DimensionType type) { + return other.includedIn(this, type) || this.includedIn(other, type); + } + + private boolean checkIntersect(float min1, float max1, float min2, float max2) { + return min1 <= max2 && max1 >= min2; + } + + public boolean includedIn(@NotNull Cuboid other, @NotNull DimensionType dimensionType) { + if (!this.checkIntersect(this.min.getX(), this.max.getX(), other.getMin().getX(), other.getMax().getX())) return false; + if (!this.checkIntersect(this.min.getZ(), this.max.getZ(), other.getMin().getZ(), other.getMax().getZ())) return false; + + if (dimensionType == DimensionType._3D) { + return this.checkIntersect(this.min.getY(), this.max.getY(), other.getMin().getY(), other.getMax().getY()); + } + + return true; + } + + @NotNull + public Set getIntersectingChunks(@NotNull World world) { + return this.getIntersectingChunkPositions().stream().map(pos -> pos.getChunk(world)).collect(Collectors.toSet()); + } + + @NotNull + public Set getIntersectingChunkPositions() { + return this.intersectingChunks; + } + + @NotNull + private Collection getIntersectingChunks() { + List chunks = new ArrayList<>(); + if (this.isEmpty()) return chunks; + + int minX = GeoUtils.shiftToChunk(this.min.getX()); + int maxX = GeoUtils.shiftToChunk(this.max.getX()); + int minZ = GeoUtils.shiftToChunk(this.min.getZ()); + int maxZ = GeoUtils.shiftToChunk(this.max.getZ()); + + for (int x = minX; x <= maxX; ++x) { + for (int z = minZ; z <= maxZ; ++z) { + chunks.add(new ChunkPos(x, z)); + } + } + + return chunks; + } + + @NotNull + public BlockPos getMin() { + return this.min; + } + + @NotNull + public BlockPos getMax() { + return this.max; + } + + @NotNull + public BlockPos getCenter() { + return this.center; + } + + public int getVolume() { + int xLength = this.max.getX() - this.min.getX() + 1; + int yLength = this.max.getY() - this.min.getY() + 1; + int zLength = this.max.getZ() - this.min.getZ() + 1; + + return xLength * zLength * yLength; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/geodata/DimensionType.java b/src/main/java/su/nightexpress/nightcore/util/geodata/DimensionType.java new file mode 100644 index 0000000..a59c359 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/geodata/DimensionType.java @@ -0,0 +1,6 @@ +package su.nightexpress.nightcore.util.geodata; + +public enum DimensionType { + _2D, + _3D +} diff --git a/src/main/java/su/nightexpress/nightcore/util/geodata/GeoUtils.java b/src/main/java/su/nightexpress/nightcore/util/geodata/GeoUtils.java new file mode 100644 index 0000000..f50f9e8 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/geodata/GeoUtils.java @@ -0,0 +1,12 @@ +package su.nightexpress.nightcore.util.geodata; + +public class GeoUtils { + + public static int shiftToChunk(int x) { + return x >> 4; + } + + public static int shiftToCoord(int chunkX) { + return chunkX << 4; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/geodata/BlockPos.java b/src/main/java/su/nightexpress/nightcore/util/geodata/pos/BlockPos.java similarity index 80% rename from src/main/java/su/nightexpress/nightcore/util/geodata/BlockPos.java rename to src/main/java/su/nightexpress/nightcore/util/geodata/pos/BlockPos.java index 9babd7c..bb0e501 100644 --- a/src/main/java/su/nightexpress/nightcore/util/geodata/BlockPos.java +++ b/src/main/java/su/nightexpress/nightcore/util/geodata/pos/BlockPos.java @@ -1,4 +1,4 @@ -package su.nightexpress.nightcore.util.geodata; +package su.nightexpress.nightcore.util.geodata.pos; import org.bukkit.Chunk; import org.bukkit.Location; @@ -6,11 +6,12 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.config.Writeable; import su.nightexpress.nightcore.util.NumberUtil; import java.util.Objects; -public class BlockPos { +public class BlockPos implements Writeable { private final int x,y,z; @@ -20,6 +21,36 @@ public class BlockPos { this.z = z; } + @NotNull + public static BlockPos read(@NotNull FileConfig config, @NotNull String path) { + String str = config.getString(path, ""); + return deserialize(str); + } + + @Override + public void write(@NotNull FileConfig config, @NotNull String path) { + config.set(path, this.serialize()); + } + + @NotNull + public String serialize() { + return this.x + "," + this.y + "," + this.z; + } + + @NotNull + public static BlockPos deserialize(@NotNull String str) { + String[] split = str.split(","); + if (split.length < 3) return empty(); + + int x = NumberUtil.getAnyInteger(split[0], 0); + int y = NumberUtil.getAnyInteger(split[1], 0); + int z = NumberUtil.getAnyInteger(split[2], 0); + + return new BlockPos(x, y, z); + } + + + public boolean isEmpty() { return this.x == 0 && this.y == 0 && this.z == 0; } @@ -40,50 +71,15 @@ public class BlockPos { } @NotNull - public static BlockPos read(@NotNull FileConfig config, @NotNull String path) { - String str = config.getString(path, ""); - return deserialize(str); + public static BlockPos from(@NotNull ExactPos pos) { + return new BlockPos((int) pos.getX(), (int) pos.getY(), (int) pos.getZ()); } - public void write(@NotNull FileConfig config, @NotNull String path) { - config.set(path, this.serialize()); - } + @NotNull - public static BlockPos deserialize(@NotNull String str) { - String[] split = str.split(","); - if (split.length < 3) return empty(); - - int x = NumberUtil.getAnyInteger(split[0], 0); - int y = NumberUtil.getAnyInteger(split[1], 0); - int z = NumberUtil.getAnyInteger(split[2], 0); - - return new BlockPos(x, y, z); - } - - @NotNull - public String serialize() { - return this.x + "," + this.y + "," + this.z; - } - - @NotNull - public BlockPos copy() { - return new BlockPos(this.x, this.y, this.z); - } - - @NotNull - public Chunk toChunk(@NotNull World world) { - int chunkX = this.x >> 4; - int chunkZ = this.z >> 4; - - return world.getChunkAt(chunkX, chunkZ); - } - - public boolean isChunkLoaded(@NotNull World world) { - int chunkX = this.x >> 4; - int chunkZ = this.z >> 4; - - return world.isChunkLoaded(chunkX, chunkZ); + public Block toBlock(@NotNull World world) { + return world.getBlockAt(this.x, this.y, this.z); } @NotNull @@ -91,6 +87,22 @@ public class BlockPos { return new Location(world, this.x, this.y, this.z); } + @NotNull + public ChunkPos toChunkPos() { + return ChunkPos.from(this); + } + + @NotNull + public Chunk toChunk(@NotNull World world) { + return this.toChunkPos().getChunk(world); + } + + public boolean isChunkLoaded(@NotNull World world) { + return this.toChunkPos().isLoaded(world); + } + + + public int getX() { return this.x; } @@ -103,6 +115,11 @@ public class BlockPos { return this.z; } + @NotNull + public BlockPos copy() { + return new BlockPos(this.x, this.y, this.z); + } + @Override public boolean equals(Object obj) { if (this == obj) return true; diff --git a/src/main/java/su/nightexpress/nightcore/util/geodata/ChunkPos.java b/src/main/java/su/nightexpress/nightcore/util/geodata/pos/ChunkPos.java similarity index 81% rename from src/main/java/su/nightexpress/nightcore/util/geodata/ChunkPos.java rename to src/main/java/su/nightexpress/nightcore/util/geodata/pos/ChunkPos.java index da378d6..0e9f057 100644 --- a/src/main/java/su/nightexpress/nightcore/util/geodata/ChunkPos.java +++ b/src/main/java/su/nightexpress/nightcore/util/geodata/pos/ChunkPos.java @@ -1,4 +1,4 @@ -package su.nightexpress.nightcore.util.geodata; +package su.nightexpress.nightcore.util.geodata.pos; import org.bukkit.Chunk; import org.bukkit.ChunkSnapshot; @@ -7,19 +7,50 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.config.Writeable; import su.nightexpress.nightcore.util.NumberUtil; +import su.nightexpress.nightcore.util.geodata.GeoUtils; import java.util.Objects; -public class ChunkPos { +public class ChunkPos implements Writeable { - private final int x,z; + private final int x; + private final int z; public ChunkPos(int x, int z) { this.x = x; this.z = z; } + @NotNull + public static ChunkPos read(@NotNull FileConfig config, @NotNull String path) { + return deserialize(String.valueOf(config.getString(path))); + } + + @Override + public void write(@NotNull FileConfig config, @NotNull String path) { + config.set(path, this.serialize()); + } + + @NotNull + public String serialize() { + return this.x + "," + this.z; + } + + @NotNull + public static ChunkPos deserialize(@NotNull String str) { + String[] split = str.split(","); + if (split.length < 2) return empty(); + + int x = NumberUtil.getAnyInteger(split[0], 0); + int z = NumberUtil.getAnyInteger(split[1], 0); + + return new ChunkPos(x, z); + } + + + @NotNull public static ChunkPos empty() { return new ChunkPos(0, 0); @@ -41,11 +72,8 @@ public class ChunkPos { } @NotNull - public static ChunkPos from(int x, int z) { - int chunkX = x >> 4; - int chunkZ = z >> 4; - - return new ChunkPos(chunkX, chunkZ); + public static ChunkPos from(@NotNull ExactPos blockPos) { + return from((int) blockPos.getX(), (int) blockPos.getZ()); } @NotNull @@ -59,25 +87,14 @@ public class ChunkPos { } @NotNull - public static ChunkPos read(@NotNull FileConfig config, @NotNull String path) { - String str = config.getString(path, ""); - return deserialize(str); + public static ChunkPos from(int x, int z) { + int chunkX = GeoUtils.shiftToChunk(x); + int chunkZ = GeoUtils.shiftToChunk(z); + + return new ChunkPos(chunkX, chunkZ); } - public void write(@NotNull FileConfig config, @NotNull String path) { - config.set(path, this.serialize()); - } - @NotNull - public static ChunkPos deserialize(@NotNull String str) { - String[] split = str.split(","); - if (split.length < 2) return empty(); - - int x = NumberUtil.getAnyInteger(split[0], 0); - int z = NumberUtil.getAnyInteger(split[1], 0); - - return new ChunkPos(x, z); - } public boolean isLoaded(@NotNull World world) { return world.isChunkLoaded(this.x, this.z); @@ -88,10 +105,6 @@ public class ChunkPos { return world.getChunkAt(this.x, this.z, false); } - @NotNull - public String serialize() { - return this.x + "," + this.z; - } @NotNull public ChunkPos copy() { @@ -99,11 +112,11 @@ public class ChunkPos { } public int getX() { - return x; + return this.x; } public int getZ() { - return z; + return this.z; } @Override diff --git a/src/main/java/su/nightexpress/nightcore/util/geodata/ExactPos.java b/src/main/java/su/nightexpress/nightcore/util/geodata/pos/ExactPos.java similarity index 78% rename from src/main/java/su/nightexpress/nightcore/util/geodata/ExactPos.java rename to src/main/java/su/nightexpress/nightcore/util/geodata/pos/ExactPos.java index 13612ac..ebfd867 100644 --- a/src/main/java/su/nightexpress/nightcore/util/geodata/ExactPos.java +++ b/src/main/java/su/nightexpress/nightcore/util/geodata/pos/ExactPos.java @@ -1,4 +1,4 @@ -package su.nightexpress.nightcore.util.geodata; +package su.nightexpress.nightcore.util.geodata.pos; import org.bukkit.Chunk; import org.bukkit.Location; @@ -6,11 +6,12 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.config.Writeable; import su.nightexpress.nightcore.util.NumberUtil; import java.util.Objects; -public class ExactPos { +public class ExactPos implements Writeable { private final double x,y,z; private final float yaw, pitch; @@ -23,8 +24,39 @@ public class ExactPos { this.pitch = pitch; } + @NotNull + public static ExactPos read(@NotNull FileConfig config, @NotNull String path) { + return deserialize(String.valueOf(config.getString(path))); + } + + @Override + public void write(@NotNull FileConfig config, @NotNull String path) { + config.set(path, this.serialize()); + } + + @NotNull + public String serialize() { + return this.x + "," + this.y + "," + this.z + "," + this.pitch + "," + this.yaw; + } + + @NotNull + public static ExactPos deserialize(@NotNull String str) { + String[] split = str.split(","); + if (split.length < 3) return empty(); + + double x = NumberUtil.getAnyDouble(split[0], 0); + double y = NumberUtil.getAnyDouble(split[1], 0); + double z = NumberUtil.getAnyDouble(split[2], 0); + float pitch = (float) NumberUtil.getAnyDouble(split[3], 0); + float yaw = (float) NumberUtil.getAnyDouble(split[4], 0); + + return new ExactPos(x, y, z, yaw, pitch); + } + + + public boolean isEmpty() { - return this.x == 0 && this.y == 0 && this.z == 0 && this.yaw == 0 && this.pitch == 0; + return this.x == 0 && this.y == 0 && this.z == 0 && this.pitch == 0 && this.yaw == 0; } @NotNull @@ -34,7 +66,7 @@ public class ExactPos { @NotNull public static ExactPos from(@NotNull Block block) { - return from(BlockPos.from(block)); + return new ExactPos(block.getX(), block.getY(), block.getZ(), 0F, 0F); } @NotNull @@ -47,48 +79,11 @@ public class ExactPos { return new ExactPos(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getYaw(), location.getPitch()); } - @NotNull - public static ExactPos read(@NotNull FileConfig cfg, @NotNull String path) { - String str = cfg.getString(path, ""); - return deserialize(str); - } - public void write(@NotNull FileConfig config, @NotNull String path) { - config.set(path, this.serialize()); - } @NotNull - public static ExactPos deserialize(@NotNull String str) { - String[] split = str.split(","); - if (split.length < 3) return empty(); - - int x = (int) NumberUtil.getAnyDouble(split[0], 0); - int y = (int) NumberUtil.getAnyDouble(split[1], 0); - int z = (int) NumberUtil.getAnyDouble(split[2], 0); - float pitch = (float) NumberUtil.getAnyDouble(split[3], 0); - float yaw = (float) NumberUtil.getAnyDouble(split[4], 0); - - return new ExactPos(x, y, z, yaw, pitch); - } - - @NotNull - public String serialize() { - return this.x + "," + this.y + "," + this.z + "," + this.pitch + "," + this.yaw; - } - - @NotNull - public Chunk toChunk(@NotNull World world) { - int chunkX = (int) this.x >> 4; - int chunkZ = (int) this.z >> 4; - - return world.getChunkAt(chunkX, chunkZ); - } - - public boolean isChunkLoaded(@NotNull World world) { - int chunkX = (int) this.x >> 4; - int chunkZ = (int) this.z >> 4; - - return world.isChunkLoaded(chunkX, chunkZ); + public Block toBlock(@NotNull World world) { + return this.toBlockPos().toBlock(world); } @NotNull @@ -99,16 +94,27 @@ public class ExactPos { return location; } - @NotNull - public ExactPos copy() { - return new ExactPos(this.x, this.y, this.z, this.yaw, this.pitch); - } - @NotNull public BlockPos toBlockPos() { return new BlockPos((int) this.x, (int) this.y, (int) this.z); } + @NotNull + public ChunkPos toChunkPos() { + return ChunkPos.from(this); + } + + @NotNull + public Chunk toChunk(@NotNull World world) { + return this.toChunkPos().getChunk(world); + } + + public boolean isChunkLoaded(@NotNull World world) { + return this.toChunkPos().isLoaded(world); + } + + + public double getX() { return this.x; } @@ -129,6 +135,11 @@ public class ExactPos { return this.pitch; } + @NotNull + public ExactPos copy() { + return new ExactPos(this.x, this.y, this.z, this.yaw, this.pitch); + } + @Override public boolean equals(Object obj) { if (this == obj) return true; diff --git a/src/main/java/su/nightexpress/nightcore/util/text/ComponentBuildable.java b/src/main/java/su/nightexpress/nightcore/util/text/ComponentBuildable.java index 8122615..faba2a1 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/ComponentBuildable.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/ComponentBuildable.java @@ -1,9 +1,9 @@ package su.nightexpress.nightcore.util.text; -import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; public interface ComponentBuildable { - @NotNull BaseComponent toComponent(); + @NotNull NightComponent toComponent(); } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java b/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java index a04c0ea..c1c6c19 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java @@ -1,8 +1,8 @@ package su.nightexpress.nightcore.util.text; -import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.util.Colorizer; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import su.nightexpress.nightcore.util.text.tag.TagPool; import su.nightexpress.nightcore.util.text.tag.Tags; @@ -39,23 +39,25 @@ public class NightMessage { @NotNull - public static BaseComponent parse(@NotNull String string) { + public static NightComponent parse(@NotNull String string) { return parse(string, TagPool.ALL); } @NotNull - public static BaseComponent parse(@NotNull String string, @NotNull TagPool tagPool) { + public static NightComponent parse(@NotNull String string, @NotNull TagPool tagPool) { return from(string, tagPool).parseIfAbsent(); } @NotNull + @Deprecated public static String clean(@NotNull String string) { return create(string, TagPool.NONE).toLegacy(); } @NotNull + @Deprecated public static String stripAll(@NotNull String string) { return Colorizer.strip(clean(string)); } @@ -92,7 +94,7 @@ public class NightMessage { } @Deprecated - public static BaseComponent asComponent(@NotNull String string) { + public static NightComponent asComponent(@NotNull String string) { return create(string).toComponent(); } @@ -106,6 +108,4 @@ public class NightMessage { } return list; } - - } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java b/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java index 9cd7062..bbb8ca8 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java @@ -1,16 +1,17 @@ package su.nightexpress.nightcore.util.text; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ComponentBuilder; -import net.md_5.bungee.api.chat.TextComponent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.util.Version; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator; import su.nightexpress.nightcore.util.text.tag.decorator.Decorator; import su.nightexpress.nightcore.util.text.tag.decorator.GradientColorDecorator; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; public class TextGroup implements ComponentBuildable { @@ -61,8 +62,8 @@ public class TextGroup implements ComponentBuildable { @Override @NotNull - public BaseComponent toComponent() { - ComponentBuilder builder = new ComponentBuilder(); + public NightComponent toComponent() { + //ComponentBuilder builder = new ComponentBuilder(); // Gradient colors must be predefined based on text length. // Text length is calculated from group's childrens that are TextNodes. @@ -73,29 +74,31 @@ public class TextGroup implements ComponentBuildable { gradientDecorator.createGradient(length.get()); // This will create and store Color[] array. } - this.childrens.forEach(child -> { - BaseComponent childComponent = child.toComponent(); - //if (!TextRoot.isEmpty(childComponent)) { - builder.append(childComponent); - //} - }); + return Version.software().buildComponent(this.childrens); - return this.build(builder); +// this.childrens.forEach(child -> { +// BaseComponent childComponent = child.toComponent(); +// //if (!TextRoot.isEmpty(childComponent)) { +// builder.append(childComponent); +// //} +// }); +// +// return this.build(builder); } - private BaseComponent build(@NotNull ComponentBuilder builder) { - if (Version.isAtLeast(Version.MC_1_20_6)) { - return builder.build(); - } - - TextComponent base = new TextComponent(); - if (!builder.getParts().isEmpty()) { - List cloned = new ArrayList<>(builder.getParts()); - cloned.replaceAll(BaseComponent::duplicate); - base.setExtra(cloned); - } - return base; - } +// private BaseComponent build(@NotNull ComponentBuilder builder) { +// if (Version.isAtLeast(Version.MC_1_20_6)) { +// return builder.build(); +// } +// +// TextComponent base = new TextComponent(); +// if (!builder.getParts().isEmpty()) { +// List cloned = new ArrayList<>(builder.getParts()); +// cloned.replaceAll(BaseComponent::duplicate); +// base.setExtra(cloned); +// } +// return base; +// } private void countLength(@NotNull TextGroup parent, @NotNull AtomicInteger length) { for (ComponentBuildable buildable : parent.getChildrens()) { diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextNode.java b/src/main/java/su/nightexpress/nightcore/util/text/TextNode.java index cb9b38d..7b5aaa5 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/TextNode.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/TextNode.java @@ -1,12 +1,9 @@ package su.nightexpress.nightcore.util.text; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.api.chat.TranslatableComponent; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import su.nightexpress.nightcore.core.CoreConfig; -import su.nightexpress.nightcore.util.Colorizer; +import su.nightexpress.nightcore.util.Version; +import su.nightexpress.nightcore.util.bridge.Software; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator; public class TextNode implements ComponentBuildable { @@ -14,7 +11,7 @@ public class TextNode implements ComponentBuildable { private final StringBuilder textBuilder; private final TextGroup parent; - private String translation; + private boolean translation; public TextNode(@NotNull TextGroup parent) { this.textBuilder = new StringBuilder(); @@ -29,7 +26,7 @@ public class TextNode implements ComponentBuildable { this.textBuilder.append(str); } - public void setTranslation(@Nullable String translation) { + public void setTranslation(boolean translation) { this.translation = translation; } @@ -44,28 +41,29 @@ public class TextNode implements ComponentBuildable { } public int textLength() { - int legnth = 0; - if (this.translation != null) return 1; + if (this.translation) return 1; + int legnth = 0; for (int index = 0; index < this.textBuilder.length(); index++) { char letter = this.textBuilder.charAt(index); if (Character.isWhitespace(letter)) continue; legnth++; } + return legnth; } @Override @NotNull - public BaseComponent toComponent() { + public NightComponent toComponent() { String text = this.textBuilder.toString(); - if (CoreConfig.LEGACY_COLOR_SUPPORT.get()) { - text = Colorizer.legacy(text); - } ColorDecorator colorDecorator = this.parent.getColor(); - BaseComponent textComponent = this.translation == null ? new TextComponent(text) : new TranslatableComponent(this.translation); + Software software = Version.software(); + + //BaseComponent textComponent = this.translation == null ? new TextComponent(text) : new TranslatableComponent(this.translation); + NightComponent textComponent = this.translation ? software.translateComponent(text) : software.textComponent(text); if (colorDecorator != null) { colorDecorator.decorate(textComponent); diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java b/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java index 95e5097..9bae5e5 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java @@ -1,14 +1,13 @@ package su.nightexpress.nightcore.util.text; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.chat.ComponentSerializer; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.core.CoreConfig; import su.nightexpress.nightcore.util.Colorizer; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import su.nightexpress.nightcore.util.text.tag.TagPool; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.Tags; import su.nightexpress.nightcore.util.text.tag.api.ContentTag; import su.nightexpress.nightcore.util.text.tag.api.PlaceholderTag; @@ -27,12 +26,12 @@ public class TextRoot { private final TagPool tagPool; - private String string; + private String string; private TextGroup rootGroup; private TextGroup currentGroup; - private TextNode currentNode; + private TextNode currentNode; - private BaseComponent component; + private NightComponent component; public TextRoot(@NotNull String string, @NotNull TagPool tagPool) { this.tagPool = tagPool; @@ -41,7 +40,8 @@ public class TextRoot { public void setString(@NotNull String string) { if (CoreConfig.LEGACY_COLOR_SUPPORT.get()) { - string = Colorizer.tagPlainHex(Colorizer.plain(string)); + string = TagUtils.tagPlainHex(Colorizer.plain(string)); + string = TagUtils.replaceLegacyColors(string); } this.string = string; @@ -73,19 +73,22 @@ public class TextRoot { public String toLegacy() { this.parseIfAbsent(); - if (this.string.isBlank() || isEmpty(this.component)) return ""; + //if (this.string.isBlank() || isEmpty(this.component)) return ""; + if (this.string.isBlank() || this.component.isEmpty()) return ""; - return TextComponent.toLegacyText(this.parseIfAbsent()); + return this.component.toLegacy(); + //return TextComponent.toLegacyText(this.parseIfAbsent()); } @NotNull public String toJson() { - return ComponentSerializer.toString(this.parseIfAbsent()); + return this.parseIfAbsent().toJson(); + //return ComponentSerializer.toString(this.parseIfAbsent()); } @NotNull @Deprecated - public BaseComponent toComponent() { + public NightComponent toComponent() { return this.parseIfAbsent(); //return TextComponent.fromArray(this.parseIfAbsent()); } @@ -105,7 +108,8 @@ public class TextRoot { public void send(@NotNull CommandSender... senders) { this.parseIfAbsent(); for (CommandSender sender : senders) { - sender.spigot().sendMessage(this.component); + this.component.send(sender); + //sender.spigot().sendMessage(this.component); } } @@ -142,7 +146,7 @@ public class TextRoot { return this.currentNode; } - public BaseComponent parseIfAbsent() { + public NightComponent parseIfAbsent() { return this.component == null ? this.parse() : this.component; } @@ -151,7 +155,7 @@ public class TextRoot { } @NotNull - public BaseComponent parse() { + public NightComponent parse() { this.rootGroup = new TextGroup(ROOT_NAME); this.currentGroup = this.rootGroup; @@ -182,16 +186,16 @@ public class TextRoot { char letter = string.charAt(index); Tag: - if (letter == Tag.OPEN_BRACKET && index != (length - 1)) { - int indexEnd = indexOfIgnoreEscaped(string, Tag.CLOSE_BRACKET, index);//string.indexOf(Tag.CLOSE_BRACKET, index); + if (letter == TagUtils.OPEN_BRACKET && index != (length - 1)) { + int indexEnd = indexOfIgnoreEscaped(string, TagUtils.CLOSE_BRACKET, index);//string.indexOf(Tag.CLOSE_BRACKET, index); //System.out.println("indexEnd = " + indexEnd); if (indexEnd == -1) break Tag; char next = string.charAt(index + 1); - if (next == Tag.CLOSE_BRACKET) break Tag; + if (next == TagUtils.CLOSE_BRACKET) break Tag; boolean closeTag = false; - if (next == Tag.CLOSE_SLASH) { + if (next == TagUtils.CLOSE_SLASH) { closeTag = true; index++; } @@ -203,7 +207,7 @@ public class TextRoot { String tagContent = null; // Check for content tags - int semicolonIndex = bracketsContent.indexOf(':'); + int semicolonIndex = bracketsContent.indexOf(TagUtils.SEMICOLON); if (semicolonIndex >= 0) { tagName = bracketsContent.substring(0, semicolonIndex); tagContent = bracketsContent.substring(semicolonIndex + 1); @@ -245,15 +249,21 @@ public class TextRoot { } private void proceedTag(@NotNull Tag tag, boolean closeTag, @Nullable String tagContent) { + if (closeTag && !tag.isCloseable()) return; + if (tag instanceof PlaceholderTag placeholderTag) { - if (!closeTag) { + //if (!closeTag) { this.currentNode().append(placeholderTag.getValue()); // Insert it to the current node as if it was a regular text. - } + //} return; } - if (tag instanceof TranslationTag translationTag) { + if (tag instanceof TranslationTag) { if (tagContent != null) { - this.currentGroup.createNode().setTranslation(stripQuotesSlash(tagContent)); // Create a new node specially for translation text. + // Create a new node exclusively for translation text. + TextNode node = this.currentGroup.createNode(); + node.append(TagUtils.unquoted(tagContent)); + node.setTranslation(true); + //this.currentGroup.createNode().setTranslation(TagUtils.unquoted(tagContent)); this.currentNode = null; // Reset current node so parser will create a new one after this one with translation. } return; @@ -296,13 +306,13 @@ public class TextRoot { return rootGroup; } - public BaseComponent getComponent() { + public NightComponent getComponent() { return component; } - public static boolean isEmpty(@NotNull BaseComponent component) { - return component instanceof TextComponent textComponent && textComponent.getText().isBlank() && textComponent.getExtra() == null; - } +// public static boolean isEmpty(@NotNull BaseComponent component) { +// return component instanceof TextComponent textComponent && textComponent.getText().isBlank() && textComponent.getExtra() == null; +// } public static int indexOfIgnoreEscaped(@NotNull String string, char what, int from) { int length = string.length(); @@ -337,17 +347,6 @@ public class TextRoot { return -1; } - @NotNull - public static String stripQuotesSlash(@NotNull String str) { - if (str.startsWith("\"") || str.startsWith("'")) { - str = str.substring(1); - } - if (str.endsWith("\"") || str.endsWith("'")) { - str = str.substring(0, str.length() - 1); - } - return str.replace("\\", ""); - } - /*@NotNull public static String substringOfQuotes(@NotNull String string) { char quote = string.charAt(0); diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/TagUtils.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/TagUtils.java index f7afa7b..34321ac 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/TagUtils.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/TagUtils.java @@ -1,11 +1,92 @@ package su.nightexpress.nightcore.util.text.tag; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.placeholder.Replacer; +import su.nightexpress.nightcore.util.text.tag.api.Tag; +import su.nightexpress.nightcore.util.text.tag.color.MinecraftColors; import java.awt.*; public class TagUtils { + public static final char OPEN_BRACKET = '<'; + public static final char CLOSE_BRACKET = '>'; + public static final char CLOSE_SLASH = '/'; + public static final char SEMICOLON = ':'; + public static final char QUOTE = '\''; + public static final char DOUBLE_QUOTE = '"'; + + private static final Replacer LEGACY_REPLACER = Replacer.create() + .replace("&0", () -> Tags.HEX_COLOR.open(MinecraftColors.BLACK.getHex())) + .replace("&1", () -> Tags.HEX_COLOR.open(MinecraftColors.DARK_BLUE.getHex())) + .replace("&2", () -> Tags.HEX_COLOR.open(MinecraftColors.DARK_GREEN.getHex())) + .replace("&3", () -> Tags.HEX_COLOR.open(MinecraftColors.DARK_AQUA.getHex())) + .replace("&4", () -> Tags.HEX_COLOR.open(MinecraftColors.DARK_RED.getHex())) + .replace("&5", () -> Tags.HEX_COLOR.open(MinecraftColors.DARK_PURPLE.getHex())) + .replace("&6", () -> Tags.HEX_COLOR.open(MinecraftColors.GOLD.getHex())) + .replace("&7", () -> Tags.HEX_COLOR.open(MinecraftColors.GRAY.getHex())) + .replace("&8", () -> Tags.HEX_COLOR.open(MinecraftColors.DARK_GRAY.getHex())) + .replace("&9", () -> Tags.HEX_COLOR.open(MinecraftColors.BLUE.getHex())) + .replace("&a", () -> Tags.HEX_COLOR.open(MinecraftColors.GREEN.getHex())) + .replace("&b", () -> Tags.HEX_COLOR.open(MinecraftColors.AQUA.getHex())) + .replace("&c", () -> Tags.HEX_COLOR.open(MinecraftColors.RED.getHex())) + .replace("&d", () -> Tags.HEX_COLOR.open(MinecraftColors.LIGHT_PURPLE.getHex())) + .replace("&e", () -> Tags.HEX_COLOR.open(MinecraftColors.YELLOW.getHex())) + .replace("&f", () -> Tags.HEX_COLOR.open(MinecraftColors.WHITE.getHex())) + .replace("&k", Tags.OBFUSCATED::getBracketsName) + .replace("&l", Tags.BOLD::getBracketsName) + .replace("&m", Tags.STRIKETHROUGH::getBracketsName) + .replace("&n", Tags.UNDERLINED::getBracketsName) + .replace("&o", Tags.ITALIC::getBracketsName) + .replace("&r", Tags.RESET::getBracketsName); + + @NotNull + public static String replaceLegacyColors(@NotNull String string) { + return LEGACY_REPLACER.apply(string); + } + + @NotNull + public static String brackets(@NotNull String str) { + return OPEN_BRACKET + str + CLOSE_BRACKET; + } + + @NotNull + public static String closedBrackets(@NotNull String str) { + return brackets(CLOSE_SLASH + str); + } + + @NotNull + public static String wrapContent(@NotNull Tag tag, @NotNull String string, @NotNull String content) { + String tagOpen = TagUtils.brackets(tag.getName() + SEMICOLON + content); + String tagClose = tag.getClosingName(); + + return tagOpen + string + tagClose; + } + + @NotNull + public static String quoted(@NotNull String content) { + return DOUBLE_QUOTE + escapeQuotes(content) + DOUBLE_QUOTE; + } + + @NotNull + public static String unquoted(@NotNull String str) { + String dQuote = String.valueOf(DOUBLE_QUOTE); + String sQuote = String.valueOf(QUOTE); + + if (str.startsWith(dQuote) || str.startsWith(sQuote)) { + str = str.substring(1); + } + if (str.endsWith(dQuote) || str.endsWith(sQuote)) { + str = str.substring(0, str.length() - 1); + } + return str.replace("\\", ""); + } + + @NotNull + public static String escapeQuotes(@NotNull String content) { + return content.replace(String.valueOf(QUOTE), "\\'").replace(String.valueOf(DOUBLE_QUOTE), "\\\""); + } + @NotNull public static Color colorFromHexString(@NotNull String string) { return colorFromHexString(string, Color.WHITE); @@ -28,4 +109,39 @@ public class TagUtils { public static String colorToHexString(@NotNull Color color) { return "#" + Integer.toHexString(color.getRGB()).substring(2); } + + @NotNull + public static String tagPlainHex(@NotNull String str) { + StringBuilder builder = new StringBuilder(str); + + int index; + int lastIndex = 0; + + while ((index = builder.toString().indexOf("#", lastIndex)) >= 0) { + lastIndex = index + 1; + + int lookup = index + 7; + if (builder.length() < lookup) break; + + Character prefix = index > 0 ? builder.charAt(index - 1) : null; + Character postfix = builder.length() > lookup ? builder.charAt(lookup) : null; + + if (prefix != null && prefix == OPEN_BRACKET) continue; // Already wrapped in a tag, ignore. + if (postfix != null && postfix == CLOSE_BRACKET) continue; // Already wrapped in a tag, ignore. + if (prefix != null && postfix != null && prefix == SEMICOLON && postfix == SEMICOLON) continue; // Inside gradient, ignore. + + String sub = builder.substring(index, lookup); + try { + Integer.decode(sub); + } + catch (NumberFormatException exception) { + continue; + } + + builder.insert(index, OPEN_BRACKET); + builder.insert(index + 8, CLOSE_BRACKET); + } + + return builder.toString(); + } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java index 130c873..602e5ae 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java @@ -5,6 +5,7 @@ import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.NightCore; import su.nightexpress.nightcore.config.FileConfig; import su.nightexpress.nightcore.util.text.tag.api.Tag; +import su.nightexpress.nightcore.util.text.tag.color.MinecraftColors; import su.nightexpress.nightcore.util.text.tag.impl.*; import java.awt.*; @@ -83,13 +84,13 @@ public class Tags { registerTags(Tags.GRADIENT, Tags.LINE_BREAK, Tags.FONT, Tags.HOVER, Tags.CLICK, Tags.RESET, Tags.HEX_COLOR, Tags.HEX_COLOR_SHORT, Tags.TRANSLATE); - registerTag(new ColorTag("dark_blue", "#0000AA")); - registerTag(new ColorTag("dark_green", "#00AA00")); - registerTag(new ColorTag("dark_aqua", "#00AAAA")); - registerTag(new ColorTag("dark_red", "#AA0000")); - registerTag(new ColorTag("dark_purple", "#AA00AA")); - registerTag(new ColorTag("gold", "#FFAA00")); - registerTag(new ColorTag("aqua", "#55FFFF")); + registerTag(MinecraftColors.DARK_BLUE); + registerTag(MinecraftColors.DARK_GREEN); + registerTag(MinecraftColors.DARK_AQUA); + registerTag(MinecraftColors.DARK_RED); + registerTag(MinecraftColors.DARK_PURPLE); + registerTag(MinecraftColors.GOLD); + registerTag(MinecraftColors.AQUA); } public static void loadColorsFromFile(@NotNull NightCore core) { @@ -100,7 +101,7 @@ public class Tags { if (!(tag instanceof ColorTag colorTag)) return; for (String alias : colorTag.getAliases()) { - config.set(COLORS_PATH + "." + alias, colorTag.toHexString()); + config.set(COLORS_PATH + "." + alias, colorTag.getHex()); } }); } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ComplexTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ComplexTag.java index 35d6f52..483c7cf 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ComplexTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ComplexTag.java @@ -1,7 +1,9 @@ package su.nightexpress.nightcore.util.text.tag.api; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.tag.TagUtils; +@Deprecated public class ComplexTag extends Tag { public ComplexTag(@NotNull String name) { @@ -14,14 +16,16 @@ public class ComplexTag extends Tag { @NotNull protected String escapeQuotes(@NotNull String content) { - return content.replace("'", "\\'").replace("\"", "\\\""); + return TagUtils.escapeQuotes(content); + //return content.replace("'", "\\'").replace("\"", "\\\""); } @NotNull public String encloseContent(@NotNull String text, @NotNull String content) { - String tagOpen = brackets(this.getName() + ":" + content); - String tagClose = this.getClosingName(); - - return tagOpen + text + tagClose; + return TagUtils.wrapContent(this, text, content); +// String tagOpen = brackets(this.getName() + ":" + content); +// String tagClose = this.getClosingName(); +// +// return tagOpen + text + tagClose; } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/SimpleTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/SimpleTag.java index 2fb3ccf..4534d34 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/SimpleTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/SimpleTag.java @@ -2,6 +2,7 @@ package su.nightexpress.nightcore.util.text.tag.api; import org.jetbrains.annotations.NotNull; +@Deprecated public class SimpleTag extends Tag { public SimpleTag(@NotNull String name) { @@ -13,7 +14,13 @@ public class SimpleTag extends Tag { } @NotNull + @Deprecated public String enclose(@NotNull String text) { + return this.wrap(text);//this.getBracketsName() + text + this.getClosingName(); + } + + @NotNull + public String wrap(@NotNull String text) { return this.getBracketsName() + text + this.getClosingName(); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java index 6982fa3..e4c6679 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java @@ -1,15 +1,16 @@ package su.nightexpress.nightcore.util.text.tag.api; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import java.util.HashSet; import java.util.Set; public class Tag { - public static final char OPEN_BRACKET = '<'; - public static final char CLOSE_BRACKET = '>'; - public static final char CLOSE_SLASH = '/'; + @Deprecated public static final char OPEN_BRACKET = '<'; + @Deprecated public static final char CLOSE_BRACKET = '>'; + @Deprecated public static final char CLOSE_SLASH = '/'; protected final String name; protected final Set aliases; @@ -28,14 +29,21 @@ public class Tag { this.aliases.add(this.name); } - @NotNull - public static String brackets(@NotNull String str) { - return OPEN_BRACKET + str + CLOSE_BRACKET; + public boolean isCloseable() { + return true; } @NotNull + @Deprecated + public static String brackets(@NotNull String str) { + return TagUtils.brackets(str); + //return OPEN_BRACKET + str + CLOSE_BRACKET; + } + + @NotNull + @Deprecated public static String closedBrackets(@NotNull String str) { - return brackets(CLOSE_SLASH + str); + return TagUtils.closedBrackets(str);//brackets(CLOSE_SLASH + str); } /*@NotNull diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/color/MinecraftColors.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/color/MinecraftColors.java new file mode 100644 index 0000000..7506655 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/color/MinecraftColors.java @@ -0,0 +1,24 @@ +package su.nightexpress.nightcore.util.text.tag.color; + +import su.nightexpress.nightcore.util.text.tag.impl.ColorTag; + +public class MinecraftColors { + + public static final ColorTag BLACK = new ColorTag("black", "#000000"); + public static final ColorTag DARK_BLUE = new ColorTag("dark_blue", "#0000AA"); + public static final ColorTag DARK_GREEN = new ColorTag("dark_green", "#00AA00"); + public static final ColorTag DARK_AQUA = new ColorTag("dark_aqua", "#00AAAA"); + public static final ColorTag DARK_RED = new ColorTag("dark_red", "#AA0000"); + public static final ColorTag DARK_PURPLE = new ColorTag("dark_purple", "#AA00AA"); + public static final ColorTag GOLD = new ColorTag("gold", "#FFAA00"); + public static final ColorTag GRAY = new ColorTag("gray", "#AAAAAA"); + public static final ColorTag DARK_GRAY = new ColorTag("dark_gray", "#555555"); + public static final ColorTag BLUE = new ColorTag("blue", "#5555FF"); + public static final ColorTag GREEN = new ColorTag("green", "#55FF55"); + public static final ColorTag AQUA = new ColorTag("aqua", "#55FFFF"); + public static final ColorTag RED = new ColorTag("red", "#FF5555"); + public static final ColorTag LIGHT_PURPLE = new ColorTag("light_purple", "#FF55FF"); + public static final ColorTag YELLOW = new ColorTag("yellow", "#FFFF55"); + public static final ColorTag WHITE = new ColorTag("white", "#FFFFFF"); + +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/BaseColorDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/BaseColorDecorator.java index dbd43ed..00d2f4d 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/BaseColorDecorator.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/BaseColorDecorator.java @@ -1,8 +1,7 @@ package su.nightexpress.nightcore.util.text.tag.decorator; -import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import java.awt.*; @@ -15,7 +14,8 @@ public class BaseColorDecorator implements ColorDecorator { } @Override - public void decorate(@NotNull BaseComponent component) { - component.setColor(ChatColor.of(this.color)); + public void decorate(@NotNull NightComponent component) { + component.setColor(this.color); + //component.setColor(ChatColor.of(this.color)); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ClickDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ClickDecorator.java index 55f4dd4..1ad542f 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ClickDecorator.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ClickDecorator.java @@ -1,26 +1,27 @@ package su.nightexpress.nightcore.util.text.tag.decorator; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.bridge.wrapper.ClickEventType; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; public class ClickDecorator implements Decorator { - private final ClickEvent.Action action; + private final ClickEventType action; private final String value; - public ClickDecorator(@NotNull ClickEvent.Action action, @NotNull String value) { + public ClickDecorator(@NotNull ClickEventType action, @NotNull String value) { this.action = action; this.value = value; } - @NotNull - public ClickEvent createEvent() { - return new ClickEvent(this.action, this.value); - } +// @NotNull +// public ClickEvent createEvent() { +// return new ClickEvent(this.action, this.value); +// } @Override - public void decorate(@NotNull BaseComponent component) { - component.setClickEvent(this.createEvent()); + public void decorate(@NotNull NightComponent component) { + component.setClickEvent(this.action, this.value); + //component.setClickEvent(this.createEvent()); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/Decorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/Decorator.java index 6d59e55..82e5f7c 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/Decorator.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/Decorator.java @@ -1,9 +1,9 @@ package su.nightexpress.nightcore.util.text.tag.decorator; -import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; public interface Decorator { - void decorate(@NotNull BaseComponent component); + void decorate(@NotNull NightComponent component); } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/FontDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/FontDecorator.java index eda59ba..d8f4023 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/FontDecorator.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/FontDecorator.java @@ -1,7 +1,7 @@ package su.nightexpress.nightcore.util.text.tag.decorator; -import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; public class FontDecorator implements Decorator { @@ -12,7 +12,7 @@ public class FontDecorator implements Decorator { } @Override - public void decorate(@NotNull BaseComponent component) { + public void decorate(@NotNull NightComponent component) { component.setFont(this.font); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/GradientColorDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/GradientColorDecorator.java index 0987895..49bcf02 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/GradientColorDecorator.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/GradientColorDecorator.java @@ -1,11 +1,12 @@ package su.nightexpress.nightcore.util.text.tag.decorator; -import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.Version; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import java.awt.*; +import java.util.ArrayList; +import java.util.List; public class GradientColorDecorator implements ColorDecorator { @@ -66,30 +67,31 @@ public class GradientColorDecorator implements ColorDecorator { } @Override - public void decorate(@NotNull BaseComponent component) { - if (component instanceof TextComponent textComponent) { + public void decorate(@NotNull NightComponent component) { + if (component.isText()) { int length = 0; - //if (textComponent.getText().equals("\n")) return; // Do not 'spend' colors on line breaks. + List childrens = new ArrayList<>(); - for (char letter : textComponent.getText().toCharArray()) { + for (char letter : component.getText().toCharArray()) { if (!Character.isWhitespace(letter)) length++; - textComponent.addExtra(new TextComponent(String.valueOf(letter))); + childrens.add(Version.software().textComponent(String.valueOf(letter))); } if (!this.isCreated()) { this.createGradient(length); } - textComponent.setText(""); - textComponent.getExtra().forEach(extra -> { - if (extra instanceof TextComponent extraText && extraText.getText().isBlank()) return; + component.setText(""); + childrens.forEach(extra -> { + if (extra.isText() && extra.getText().isBlank()) return; if (this.hasNextColor()) { - extra.setColor(ChatColor.of(this.nextColor())); + extra.setColor(this.nextColor()); } }); + component.setChildrens(childrens); return; } @@ -97,7 +99,7 @@ public class GradientColorDecorator implements ColorDecorator { if (!this.isCreated()) this.createGradient(1); if (this.hasNextColor()) { - component.setColor(ChatColor.of(this.nextColor())); + component.setColor(this.nextColor()); } } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowItemDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowItemDecorator.java index d90feeb..021e8c9 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowItemDecorator.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowItemDecorator.java @@ -1,16 +1,11 @@ package su.nightexpress.nightcore.util.text.tag.decorator; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.ItemTag; -import net.md_5.bungee.api.chat.hover.content.Item; -import org.bukkit.Bukkit; -import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.util.BukkitThing; import su.nightexpress.nightcore.util.ItemNbt; +import su.nightexpress.nightcore.util.bridge.wrapper.HoverEventType; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; public class ShowItemDecorator implements Decorator { @@ -25,34 +20,35 @@ public class ShowItemDecorator implements Decorator { this.itemData = string; } - @NotNull - public HoverEvent createEvent() { - ItemStack itemStack = null; - - try { - itemStack = Bukkit.getItemFactory().createItemStack(this.itemData); - } - catch (IllegalArgumentException exception) { - try { - itemStack = ItemNbt.decompress(this.itemData); - } - catch (NumberFormatException ignored) { - - } - } - if (itemStack == null) itemStack = new ItemStack(Material.AIR); - - String key = BukkitThing.toString(itemStack.getType()); - ItemMeta meta = itemStack.getItemMeta(); - String nbt = meta == null ? "{}" : meta.getAsString(); - - Item item = new Item(key, itemStack.getAmount(), ItemTag.ofNbt(nbt)); - - return new HoverEvent(HoverEvent.Action.SHOW_ITEM, item); - } +// @NotNull +// public HoverEvent createEvent() { +// ItemStack itemStack = null; +// +// try { +// itemStack = Bukkit.getItemFactory().createItemStack(this.itemData); +// } +// catch (IllegalArgumentException exception) { +// try { +// itemStack = ItemNbt.decompress(this.itemData); +// } +// catch (NumberFormatException ignored) { +// +// } +// } +// if (itemStack == null) itemStack = new ItemStack(Material.AIR); +// +// String key = BukkitThing.toString(itemStack.getType()); +// ItemMeta meta = itemStack.getItemMeta(); +// String nbt = meta == null ? "{}" : meta.getAsString(); +// +// Item item = new Item(key, itemStack.getAmount(), ItemTag.ofNbt(nbt)); +// +// return new HoverEvent(HoverEvent.Action.SHOW_ITEM, item); +// } @Override - public void decorate(@NotNull BaseComponent component) { - component.setHoverEvent(this.createEvent()); + public void decorate(@NotNull NightComponent component) { + component.setHoverEvent(HoverEventType.SHOW_ITEM, this.itemData); + //component.setHoverEvent(this.createEvent()); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowTextDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowTextDecorator.java index 19b9777..3206105 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowTextDecorator.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowTextDecorator.java @@ -1,14 +1,10 @@ package su.nightexpress.nightcore.util.text.tag.decorator; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ComponentBuilder; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.hover.content.Text; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.util.Lists; import su.nightexpress.nightcore.util.Placeholders; -import su.nightexpress.nightcore.util.Version; -import su.nightexpress.nightcore.util.text.NightMessage; +import su.nightexpress.nightcore.util.bridge.wrapper.HoverEventType; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import java.util.List; @@ -24,24 +20,25 @@ public class ShowTextDecorator implements Decorator { this.text = text; } - @NotNull - public HoverEvent createEvent() { - String fused = String.join(Placeholders.TAG_LINE_BREAK, this.text); - BaseComponent component = NightMessage.parse(fused); - - Text text; - if (Version.isAtLeast(Version.MC_1_20_6)) { - text = new Text(component); - } - else { - text = new Text(new ComponentBuilder().append(component).create()); - } - - return new HoverEvent(HoverEvent.Action.SHOW_TEXT, text); - } +// @NotNull +// public HoverEvent createEvent() { +// String fused = String.join(Placeholders.TAG_LINE_BREAK, this.text); +// BaseComponent component = NightMessage.parse(fused); +// +// Text text; +// if (Version.isAtLeast(Version.MC_1_20_6)) { +// text = new Text(component); +// } +// else { +// text = new Text(new ComponentBuilder().append(component).create()); +// } +// +// return new HoverEvent(HoverEvent.Action.SHOW_TEXT, text); +// } @Override - public void decorate(@NotNull BaseComponent component) { - component.setHoverEvent(this.createEvent()); + public void decorate(@NotNull NightComponent component) { + component.setHoverEvent(HoverEventType.SHOW_TEXT, String.join(Placeholders.TAG_LINE_BREAK, this.text)); + //component.setHoverEvent(this.createEvent()); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java index 60ad97c..273e0c9 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java @@ -1,15 +1,14 @@ package su.nightexpress.nightcore.util.text.tag.impl; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import su.nightexpress.nightcore.util.text.TextRoot; -import su.nightexpress.nightcore.util.text.tag.api.ComplexTag; -import su.nightexpress.nightcore.util.text.tag.decorator.ClickDecorator; +import su.nightexpress.nightcore.util.bridge.wrapper.ClickEventType; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.api.ContentTag; +import su.nightexpress.nightcore.util.text.tag.api.Tag; +import su.nightexpress.nightcore.util.text.tag.decorator.ClickDecorator; -public class ClickTag extends ComplexTag implements ContentTag { +public class ClickTag extends Tag implements ContentTag { public static final String NAME = "click"; @@ -18,35 +17,54 @@ public class ClickTag extends ComplexTag implements ContentTag { } @NotNull + @Deprecated public String encloseRun(@NotNull String text, @NotNull String command) { - return this.enclose(text, ClickEvent.Action.RUN_COMMAND, command); + return this.wrapRunCommand(text, command); + //return this.enclose(text, ClickEventType.RUN_COMMAND, command); } +// @NotNull +// @Deprecated +// public String enclose(@NotNull ClickEventType action, @NotNull String text, @NotNull String content) { +// return this.enclose(text, action, content); +// } + @NotNull @Deprecated - public String enclose(@NotNull ClickEvent.Action action, @NotNull String text, @NotNull String content) { - return this.enclose(text, action, content); + public String enclose(@NotNull String text, @NotNull ClickEventType action, @NotNull String content) { +// String data = action.name().toLowerCase() + TagUtils.SEMICOLON + TagUtils.quotedContent(content); +// +// return TagUtils.wrapContent(this, text, data); + return this.wrap(text, action, content); } @NotNull - public String enclose(@NotNull String text, @NotNull ClickEvent.Action action, @NotNull String content) { - //content = content.replace("'", "\\'"); + public String wrapRunCommand(@NotNull String string, @NotNull String command) { + return this.enclose(string, ClickEventType.RUN_COMMAND, command); + } - //String tagOpen = brackets(NAME + ":" + action.name().toLowerCase() + ":'" + content + "'"); - //String tagClose = this.getClosingName(); + @NotNull + public String wrapSuggestCommand(@NotNull String string, @NotNull String command) { + return this.enclose(string, ClickEventType.SUGGEST_COMMAND, command); + } - //return tagOpen + text + tagClose; + @NotNull + public String wrapOpenRUL(@NotNull String string, @NotNull String url) { + return this.enclose(string, ClickEventType.OPEN_URL, url); + } - String data = action.name().toLowerCase() + ":\"" + this.escapeQuotes(content) + "\""; + @NotNull + public String wrap(@NotNull String string, @NotNull ClickEventType type, @NotNull String content) { + String data = type.name().toLowerCase() + TagUtils.SEMICOLON + TagUtils.quoted(content); - return this.encloseContent(text, data); + return TagUtils.wrapContent(this, string, data); } @Override @Nullable public ClickDecorator parse(@NotNull String tagContent) { - ClickEvent.Action action = null; - for (ClickEvent.Action global : ClickEvent.Action.values()) { + ClickEventType action = null; + for (ClickEventType global : ClickEventType.values()) { if (tagContent.startsWith(global.name().toLowerCase())) { action = global; break; @@ -57,7 +75,7 @@ public class ClickTag extends ComplexTag implements ContentTag { int prefixSize = action.name().toLowerCase().length() + 1; // 1 for ':', like "run_command:" tagContent = tagContent.substring(prefixSize); - String value = TextRoot.stripQuotesSlash(tagContent); + String value = TagUtils.unquoted(tagContent); return new ClickDecorator(action, value); } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java index 8c1f36d..702e311 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java @@ -1,8 +1,7 @@ package su.nightexpress.nightcore.util.text.tag.impl; -import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.api.SimpleTag; import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator; @@ -11,7 +10,7 @@ import java.awt.*; public class ColorTag extends SimpleTag implements ColorDecorator { - protected final Color color; + private final Color color; public ColorTag(@NotNull String name, @NotNull String hex) { this(name, new String[0], hex); @@ -21,10 +20,12 @@ public class ColorTag extends SimpleTag implements ColorDecorator { this(name, aliases, TagUtils.colorFromHexString(hex)); } + @Deprecated public ColorTag(@NotNull Color color) { this(color, new String[0]); } + @Deprecated public ColorTag(@NotNull Color color, @NotNull String[] aliases) { this(TagUtils.colorToHexString(color).substring(1), aliases, color); } @@ -40,23 +41,36 @@ public class ColorTag extends SimpleTag implements ColorDecorator { @NotNull public Color getColor() { - return color; + return this.color; } @NotNull - public String encloseHex(@NotNull String text) { - String hex = this.toHexString(); + public String getHex() { + return TagUtils.colorToHexString(this.color); + } - return brackets(hex) + text + closedBrackets(hex); + @NotNull + @Deprecated + public String wrapHex(@NotNull String string) { + String hex = this.getHex(); + + return TagUtils.brackets(hex) + string + TagUtils.closedBrackets(hex); } @Override - public void decorate(@NotNull BaseComponent component) { - component.setColor(ChatColor.of(this.getColor())); + public void decorate(@NotNull NightComponent component) { + component.setColor(this.color); } @NotNull + @Deprecated + public String encloseHex(@NotNull String string) { + return this.wrapHex(string); + } + + @NotNull + @Deprecated public String toHexString() { - return TagUtils.colorToHexString(this.color); + return this.getHex();//TagUtils.colorToHexString(this.color); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java index da45a1c..d27aa07 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java @@ -1,7 +1,7 @@ package su.nightexpress.nightcore.util.text.tag.impl; -import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.bridge.wrapper.NightComponent; import su.nightexpress.nightcore.util.text.tag.api.SimpleTag; import su.nightexpress.nightcore.util.text.tag.decorator.Decorator; @@ -39,7 +39,7 @@ public class FontStyleTag extends SimpleTag implements Decorator { } @Override - public void decorate(@NotNull BaseComponent component) { + public void decorate(@NotNull NightComponent component) { switch (this.style) { case BOLD -> component.setBold(!this.inverted); case ITALIC -> component.setItalic(!this.inverted); diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java index fbfa105..b1022fc 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java @@ -2,11 +2,12 @@ package su.nightexpress.nightcore.util.text.tag.impl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import su.nightexpress.nightcore.util.text.tag.api.ComplexTag; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.api.ContentTag; +import su.nightexpress.nightcore.util.text.tag.api.Tag; import su.nightexpress.nightcore.util.text.tag.decorator.FontDecorator; -public class FontTag extends ComplexTag implements ContentTag { +public class FontTag extends Tag implements ContentTag { public FontTag() { super("font"); @@ -17,4 +18,9 @@ public class FontTag extends ComplexTag implements ContentTag { public FontDecorator parse(@NotNull String str) { return new FontDecorator(str); } + + @NotNull + public String wrap(@NotNull String text, @NotNull String fontName) { + return TagUtils.wrapContent(this, text, fontName); + } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java index cc6fcc4..cab58bc 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java @@ -18,17 +18,27 @@ public class GradientTag extends Tag implements ContentTag { } @NotNull + @Deprecated public String enclose(@NotNull String hexStart, @NotNull String hexEnd, @NotNull String text) { - String tagOpen = brackets(this.getName() + ":" + hexStart + ":" + hexEnd); +// String tagOpen = brackets(this.getName() + ":" + hexStart + ":" + hexEnd); +// String tagClose = this.getClosingName(); +// +// return tagOpen + text + tagClose; + return this.wrap(text, hexStart, hexEnd); + } + + @NotNull + public String wrap(@NotNull String string, @NotNull String fromHex, @NotNull String toHex) { + String tagOpen = TagUtils.brackets(this.getName() + TagUtils.SEMICOLON + fromHex + TagUtils.SEMICOLON + toHex); String tagClose = this.getClosingName(); - return tagOpen + text + tagClose; + return tagOpen + string + tagClose; } @Override @Nullable public GradientColorDecorator parse(@NotNull String content) { - String[] split = content.split(":"); + String[] split = content.split(String.valueOf(TagUtils.SEMICOLON)); if (split.length < 2) return null; String code1 = split[0]; diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java index 202de4f..0ae6549 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java @@ -18,8 +18,24 @@ public class HexColorTag extends Tag implements ContentTag { } @NotNull + @Deprecated public String enclose(@NotNull String text, @NotNull String hex) { - return brackets(this.name + ":" + hex) + text + closedBrackets(this.name); + return this.wrap(text, hex);//brackets(this.name + ":" + hex) + text + closedBrackets(this.name); + } + + @NotNull + public String open(@NotNull String hex) { + return TagUtils.brackets(this.name + TagUtils.SEMICOLON + hex); + } + + @NotNull + public String wrap(@NotNull String string, @NotNull Color color) { + return this.wrap(string, TagUtils.colorToHexString(color)); + } + + @NotNull + public String wrap(@NotNull String string, @NotNull String hex) { + return this.open(hex) + string + TagUtils.closedBrackets(this.name); } @Override @@ -28,14 +44,9 @@ public class HexColorTag extends Tag implements ContentTag { if (tagContent.length() < 7) return null; Color color = TagUtils.colorFromHexString(tagContent); - return new BaseColorDecorator(color); -// try { -// Color color = Color.decode(tagContent); -// return new BaseColorDecorator(color); -// } -// catch (NumberFormatException exception) { -// return null; -// } + // TODO Named colors support + + return new BaseColorDecorator(color); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java index c6c9c9a..2b99a96 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java @@ -1,16 +1,18 @@ package su.nightexpress.nightcore.util.text.tag.impl; -import net.md_5.bungee.api.chat.HoverEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import su.nightexpress.nightcore.util.text.TextRoot; -import su.nightexpress.nightcore.util.text.tag.api.ComplexTag; +import su.nightexpress.nightcore.util.ItemNbt; +import su.nightexpress.nightcore.util.bridge.wrapper.HoverEventType; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.api.ContentTag; +import su.nightexpress.nightcore.util.text.tag.api.Tag; import su.nightexpress.nightcore.util.text.tag.decorator.Decorator; import su.nightexpress.nightcore.util.text.tag.decorator.ShowItemDecorator; import su.nightexpress.nightcore.util.text.tag.decorator.ShowTextDecorator; -public class HoverTag extends ComplexTag implements ContentTag { +public class HoverTag extends Tag implements ContentTag { public static final String NAME = "hover"; @@ -26,26 +28,44 @@ public class HoverTag extends ComplexTag implements ContentTag { @NotNull @Deprecated - public String enclose(@NotNull HoverEvent.Action action, @NotNull String text, @NotNull String content) { + public String enclose(@NotNull HoverEventType action, @NotNull String text, @NotNull String content) { return this.enclose(text, action, content); } @NotNull + @Deprecated public String encloseHint(@NotNull String text, @NotNull String hint) { - return this.enclose(text, HoverEvent.Action.SHOW_TEXT, hint); + return this.wrap(text, HoverEventType.SHOW_TEXT, hint); } @NotNull - public String enclose(@NotNull String text, @NotNull HoverEvent.Action action, @NotNull String content) { - String data = action.name().toLowerCase() + ":'" + this.escapeQuotes(content) + "'"; - return this.encloseContent(text, data); + @Deprecated + public String enclose(@NotNull String text, @NotNull HoverEventType action, @NotNull String content) { + //String data = action.name().toLowerCase() + TagUtils.SEMICOLON + TagUtils.quoted(content); + return this.wrap(text, action, content);//TagUtils.wrapContent(this, text, data); + } + + @NotNull + public String wrapShowText(@NotNull String string, @NotNull String text) { + return this.enclose(string, HoverEventType.SHOW_TEXT, text); + } + + @NotNull + public String wrapShowItem(@NotNull String string, @NotNull ItemStack itemStack) { + return this.enclose(string, HoverEventType.SHOW_ITEM, String.valueOf(ItemNbt.compress(itemStack))); + } + + @NotNull + public String wrap(@NotNull String string, @NotNull HoverEventType type, @NotNull String content) { + String data = type.name().toLowerCase() + TagUtils.SEMICOLON + TagUtils.quoted(content); + return TagUtils.wrapContent(this, string, data); } @Override @Nullable public Decorator parse(@NotNull String tagContent) { - HoverEvent.Action action = null; - for (HoverEvent.Action global : HoverEvent.Action.values()) { + HoverEventType action = null; + for (HoverEventType global : HoverEventType.values()) { if (tagContent.startsWith(global.name().toLowerCase())) { action = global; break; @@ -56,12 +76,12 @@ public class HoverTag extends ComplexTag implements ContentTag { int prefixSize = action.name().toLowerCase().length() + 1; // 1 for ':', like "show_text:" tagContent = tagContent.substring(prefixSize); - String value = TextRoot.stripQuotesSlash(tagContent); + String value = TagUtils.unquoted(tagContent); - if (action == HoverEvent.Action.SHOW_TEXT) { + if (action == HoverEventType.SHOW_TEXT) { return new ShowTextDecorator(value); } - else if (action == HoverEvent.Action.SHOW_ITEM) { + else if (action == HoverEventType.SHOW_ITEM) { return new ShowItemDecorator(value); } return null; diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java index f8a02ec..cc6a1f2 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java @@ -1,6 +1,7 @@ package su.nightexpress.nightcore.util.text.tag.impl; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.api.PlaceholderTag; import su.nightexpress.nightcore.util.text.tag.api.Tag; @@ -10,6 +11,11 @@ public class LineBreakTag extends Tag implements PlaceholderTag { super("newline", new String[]{"br"}); } + @Override + public boolean isCloseable() { + return false; + } + @Override @NotNull public String getValue() { @@ -18,7 +24,7 @@ public class LineBreakTag extends Tag implements PlaceholderTag { public String[] split(@NotNull String string) { for (String alias : this.getAliases()) { - string = string.replace(brackets(alias), "\n"); + string = string.replace(TagUtils.brackets(alias), "\n"); } return string.split("\n"); } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java index edd48a4..fee0563 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java @@ -1,12 +1,17 @@ package su.nightexpress.nightcore.util.text.tag.impl; -import su.nightexpress.nightcore.util.text.tag.api.SimpleTag; +import su.nightexpress.nightcore.util.text.tag.api.Tag; -public class ResetTag extends SimpleTag { // TODO Must be just Tag, SimpleTag for compatibility +public class ResetTag extends Tag { public static final String NAME = "reset"; public ResetTag() { super(NAME, new String[]{"r"}); } + + @Override + public boolean isCloseable() { + return false; + } } diff --git a/src/main/java/su/nightexpress/nightcore/util/time/TimeFormats.java b/src/main/java/su/nightexpress/nightcore/util/time/TimeFormats.java index f3387c0..dd47a89 100644 --- a/src/main/java/su/nightexpress/nightcore/util/time/TimeFormats.java +++ b/src/main/java/su/nightexpress/nightcore/util/time/TimeFormats.java @@ -12,7 +12,8 @@ import java.util.concurrent.TimeUnit; public class TimeFormats { - private static final DateTimeFormatter DIGITAL_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss"); + private static final DateTimeFormatter DIGITAL_FULL_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss"); + private static final DateTimeFormatter DIGITAL_SHORT_FORMATTER = DateTimeFormatter.ofPattern("mm:ss"); @NotNull public static String formatDuration(long until, @NotNull TimeFormatType formatType) { @@ -35,7 +36,12 @@ public class TimeFormats { @NotNull public static String toDigital(long millis) { - return TimeUtil.getLocalTimeOf(millis).format(DIGITAL_FORMATTER); + return toFormat(millis, DIGITAL_FULL_FORMATTER); + } + + @NotNull + public static String toDigitalShort(long millis) { + return toFormat(millis, DIGITAL_SHORT_FORMATTER); } @NotNull @@ -45,6 +51,11 @@ public class TimeFormats { return whole > 0 ? String.valueOf(whole) : NumberUtil.format(millis / 1000D); } + @NotNull + public static String toFormat(long millis, @NotNull DateTimeFormatter formatter) { + return TimeUtil.getLocalTimeOf(millis).format(formatter); + } + @NotNull public static String toLiteral(long millis) { TimeUnit[] units = {TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS}; @@ -61,7 +72,7 @@ public class TimeFormats { long converted = unit.convert(millis, TimeUnit.MILLISECONDS); long result = scale != 0 ? converted % scale : converted; - if (result > 0) { + if (result > 0 || (millis <= 1000L && unit == TimeUnit.SECONDS)) { if (!str.isEmpty()) { str.append(delimiter); } diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniDouble.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniDouble.java index 158bf03..688da16 100644 --- a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniDouble.java +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniDouble.java @@ -2,9 +2,10 @@ package su.nightexpress.nightcore.util.wrapper; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.config.Writeable; import su.nightexpress.nightcore.util.random.Rnd; -public final class UniDouble { +public final class UniDouble implements Writeable { private final double minInclusive; private final double maxInclusive; @@ -26,9 +27,10 @@ public final class UniDouble { return of(min, max); } - public void write(@NotNull FileConfig cfg, @NotNull String path) { - cfg.set(path + ".Min", this.getMinValue()); - cfg.set(path + ".Max", this.getMaxValue()); + @Override + public void write(@NotNull FileConfig config, @NotNull String path) { + config.set(path + ".Min", this.getMinValue()); + config.set(path + ".Max", this.getMaxValue()); } @NotNull diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java index 8e1d2d2..0e458ea 100644 --- a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java @@ -2,9 +2,10 @@ package su.nightexpress.nightcore.util.wrapper; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.config.Writeable; import su.nightexpress.nightcore.util.random.Rnd; -public final class UniInt { +public final class UniInt implements Writeable { private final int minInclusive; private final int maxInclusive; @@ -26,6 +27,7 @@ public final class UniInt { return of(min, max); } + @Override public void write(@NotNull FileConfig config, @NotNull String path) { config.set(path + ".Min", this.getMinValue()); config.set(path + ".Max", this.getMaxValue()); diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniParticle.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniParticle.java index 011af28..95eb227 100644 --- a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniParticle.java +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniParticle.java @@ -7,11 +7,12 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.config.Writeable; import su.nightexpress.nightcore.util.BukkitThing; import su.nightexpress.nightcore.util.StringUtil; import su.nightexpress.nightcore.util.Version; -public class UniParticle { +public class UniParticle implements Writeable { private final Particle particle; private Object data; @@ -113,6 +114,7 @@ public class UniParticle { return UniParticle.of(particle, data); } + @Override public void write(@NotNull FileConfig config, @NotNull String path) { config.set(path + ".Name", this.isEmpty() ? "null" : this.getParticle().name());