From 5843e0be042b14563ecf7e60cf74fb9cb3fffc3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Sun, 27 May 2018 21:15:29 +0800 Subject: [PATCH] =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0=E8=87=B3?= =?UTF-8?q?=204.06=20=E6=96=B0=E5=A2=9E=EF=BC=9ATLocale=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20BOOK=20=E7=B1=BB=E5=9E=8B=EF=BC=8C=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E5=8F=91=E9=80=81=E4=B9=A6=E6=9C=AC=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=EF=BC=88=E4=BB=A3=E6=9B=BF=20Language2=EF=BC=89=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=EF=BC=9ATLocale=20=E6=96=B0=E5=A2=9E=20BAR=20?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=EF=BC=8C=E7=94=A8=E4=BA=8E=E5=8F=91=E9=80=81?= =?UTF-8?q?=20Bossbar=EF=BC=88=E9=9C=80=E8=A6=81=20BossBarAPI=EF=BC=89=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=EF=BC=9ATLocale#Tellraw=20=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E7=94=A8=E4=BA=8E=E5=8F=91=E9=80=81=E5=8E=9F=E5=A7=8B=20json?= =?UTF-8?q?=20=E4=BF=A1=E6=81=AF=20=E6=96=B0=E5=A2=9E=EF=BC=9ATellrawJson?= =?UTF-8?q?=20=E5=B7=A5=E5=85=B7=E7=94=A8=E4=BA=8E=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E5=8E=9F=E5=A7=8B=20json=20=E4=BF=A1=E6=81=AF=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=EF=BC=9AVariableFormatter=20=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E7=94=A8=E4=BA=8E=E5=8F=98=E9=87=8F=E8=AF=86=E5=88=AB=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=EF=BC=9AArrayUtils=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E4=BF=AE=E6=94=B9=E6=96=B9=E6=B3=95=20?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=EF=BC=9ALanguage2Book=20=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E5=A4=B1=E6=95=88=E9=97=AE=E9=A2=98=20=E8=B0=83=E6=95=B4?= =?UTF-8?q?=EF=BC=9AJsonFormatter=20=E5=B7=A5=E5=85=B7=E5=B7=B2=E8=BF=87?= =?UTF-8?q?=E6=97=B6=EF=BC=8C=E4=B8=8D=E5=86=8D=E7=BB=B4=E6=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 从该版本起不再对 1.7.10 版本进行支持与维护,任何在 1.7.10 版本内出现的问题不再修复。 1.7.10 稳定版:v3.832 --- pom.xml | 9 +- .../tlib/bungee/chat/ComponentSerializer.java | 1 + .../com/ilummc/tlib/resources/TLocale.java | 30 +- .../ilummc/tlib/resources/TLocaleLoader.java | 2 + .../tlib/resources/type/TLocaleBook.java | 91 ++++++ .../tlib/resources/type/TLocaleBossBar.java | 95 ++++++ .../tlib/resources/type/TLocaleJson.java | 88 ++++- .../java/com/ilummc/tlib/util/Strings.java | 22 +- .../bookformatter/BookReflection.java | 63 ++-- .../bookformatter/action/ClickAction.java | 6 +- .../bookformatter/action/HoverAction.java | 10 +- .../bookformatter/builder/BookBuilder.java | 17 +- .../bookformatter/builder/PageBuilder.java | 28 +- .../bookformatter/builder/TextBuilder.java | 5 +- .../taboolib/json/tellraw/TellrawJson.java | 133 ++++++++ .../taboolib/jsonformatter/JSONFormatter.java | 14 +- .../jsonformatter/hover/ShowItemEvent.java | 117 +++---- .../listener/ListenerPlayerCommand.java | 48 +-- .../java/me/skymc/taboolib/nms/NMSUtil18.java | 4 +- .../java/me/skymc/taboolib/nms/NMSUtil19.java | 304 +++++++++--------- .../java/me/skymc/taboolib/nms/NMSUtils.java | 3 + .../me/skymc/taboolib/player/PlayerUtils.java | 100 +++--- .../me/skymc/taboolib/string/ArrayUtils.java | 111 +++++-- .../taboolib/string/VariableFormatter.java | 113 +++++++ .../string/language2/value/Language2Book.java | 139 ++++---- src/main/resources/lang/zh_CN.yml | 4 + src/main/resources/plugin.yml | 2 +- 27 files changed, 1095 insertions(+), 464 deletions(-) create mode 100644 src/main/java/com/ilummc/tlib/resources/type/TLocaleBook.java create mode 100644 src/main/java/com/ilummc/tlib/resources/type/TLocaleBossBar.java create mode 100644 src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java create mode 100644 src/main/java/me/skymc/taboolib/string/VariableFormatter.java diff --git a/pom.xml b/pom.xml index 4aaeaa4..e1ec024 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.skymc TabooLib - 4.05 + 4.06 UTF-8 @@ -176,6 +176,13 @@ system ${basedir}/libs/Vault.jar + + bossbar + bossbar + 1 + system + ${basedir}/libs/BossBarAPI.jar + \ No newline at end of file diff --git a/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java b/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java index b6165db..6d19961 100644 --- a/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java +++ b/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java @@ -6,6 +6,7 @@ import com.ilummc.tlib.bungee.api.chat.TextComponent; import com.ilummc.tlib.bungee.api.chat.TranslatableComponent; import java.lang.reflect.Type; +import java.util.Arrays; import java.util.HashSet; /** diff --git a/src/main/java/com/ilummc/tlib/resources/TLocale.java b/src/main/java/com/ilummc/tlib/resources/TLocale.java index b2dc858..9747a35 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocale.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocale.java @@ -2,20 +2,30 @@ package com.ilummc.tlib.resources; import com.ilummc.tlib.TLib; import com.ilummc.tlib.bungee.api.ChatColor; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; import com.ilummc.tlib.inject.TLoggerManager; import com.ilummc.tlib.util.Ref; import com.ilummc.tlib.util.Strings; import me.clip.placeholderapi.PlaceholderAPI; import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; +import me.skymc.taboolib.nms.NMSUtil19; +import me.skymc.taboolib.nms.NMSUtils; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +/** + * @author IzzelAliz + */ public class TLocale { private TLocale() { @@ -128,4 +138,22 @@ public class TLocale { } } + public static class Tellraw extends TLocale { + + private static final Field playerConnection = NMSUtils.getFieldSilent(NMSUtil19.class_EntityPlayer, "playerConnection"); + private static final Method sendPacket = NMSUtils.getMethodSilent(NMSUtil19.class_PlayerConnection, "sendPacket", NMSUtil19.class_Packet); + private static final Constructor PacketPlayOutChat = NMSUtils.getConstructorSilent(NMSUtil19.class_PacketPlayOutChat, NMSUtil19.class_IChatBaseComponent); + + public static void send(CommandSender sender, String rawMessage) { + if (sender instanceof Player) { + try { + sendPacket.invoke(playerConnection.get(NMSUtils.getHandle(sender)), PacketPlayOutChat.newInstance(rawMessage)); + } catch (Exception e) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + sender.getName() + " " + rawMessage); + } + } else { + sender.sendMessage(TextComponent.toLegacyText(ComponentSerializer.parse(rawMessage))); + } + } + } } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java index 2aef0c0..98f9a99 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java @@ -30,8 +30,10 @@ public class TLocaleLoader { public static void init() { ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT"); ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON"); + ConfigurationSerialization.registerClass(TLocaleBook.class, "BOOK"); ConfigurationSerialization.registerClass(TLocaleSound.class, "SOUND"); ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE"); + ConfigurationSerialization.registerClass(TLocaleBossBar.class, "BAR"); ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION"); } diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleBook.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleBook.java new file mode 100644 index 0000000..978eb27 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleBook.java @@ -0,0 +1,91 @@ +package com.ilummc.tlib.resources.type; + +import com.google.common.collect.Maps; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; +import com.ilummc.tlib.resources.TLocale; +import com.ilummc.tlib.resources.TLocaleSerialize; +import com.ilummc.tlib.util.Strings; +import me.skymc.taboolib.Main; +import me.skymc.taboolib.bookformatter.BookFormatter; +import me.skymc.taboolib.bookformatter.builder.BookBuilder; +import me.skymc.taboolib.json.tellraw.TellrawJson; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import javax.annotation.concurrent.ThreadSafe; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @Author sky + * @Since 2018-05-27 0:05 + */ +@ThreadSafe +@SerializableAs("BOOK") +public class TLocaleBook extends TLocaleSerialize { + + /* + BookTest: + - ==: BOOK + pages: + 0: + - '第一页内容' + - '[ <变量1@page-1> ]' + 1: + - '第二页内容' + - '[ <变量2@page-2> ]' + args: + page-1: + hover: '展示内容1' + command: '/say %player_name% NB1' + page-2: + hover: '展示内容2' + suggest: '/say %player_name% NB2' + */ + + private final List pages; + private final Map map; + private final boolean papi; + + public TLocaleBook(List pages, Map map, boolean papi) { + this.pages = pages; + this.map = map; + this.papi = papi; + } + + @Override + public Map serialize() { + return Maps.newHashMap(map); + } + + @Override + public void sendTo(CommandSender sender, String... args) { + if (!(sender instanceof Player)) { + return; + } + new BukkitRunnable() { + @Override + public void run() { + BookBuilder bookBuilder = BookFormatter.writtenBook(); + pages.stream().map(jsonPage -> papi ? TLocale.Translate.setPlaceholders(sender, Strings.replaceWithOrder(jsonPage.toRawMessage(), args)) : TLocale.Translate.setColored(Strings.replaceWithOrder(jsonPage.toRawMessage(), args))).map(ComponentSerializer::parse).forEach(bookBuilder::addPages); + new BukkitRunnable() { + @Override + public void run() { + BookFormatter.forceOpen((Player) sender, bookBuilder.build()); + } + }.runTask(Main.getInst()); + } + }.runTaskAsynchronously(Main.getInst()); + } + + public static TLocaleBook valueOf(Map map) { + Map pages = map.containsKey("pages") ? (Map) map.get("pages") : new HashMap<>(); + Map section = map.containsKey("args") ? (Map) map.get("args") : new HashMap<>(); + List pageJsonList = pages.values().stream().map(page -> TLocaleJson.formatJson(section, page, TellrawJson.create())).collect(Collectors.toList()); + return new TLocaleBook(pageJsonList, map, isPlaceholderEnabled(map)); + } +} diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleBossBar.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleBossBar.java new file mode 100644 index 0000000..62261ca --- /dev/null +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleBossBar.java @@ -0,0 +1,95 @@ +package com.ilummc.tlib.resources.type; + +import com.ilummc.tlib.resources.TLocale; +import com.ilummc.tlib.resources.TLocaleSerialize; +import com.ilummc.tlib.util.Strings; +import me.skymc.taboolib.other.NumberUtils; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.entity.Player; +import org.inventivetalent.bossbar.BossBar; +import org.inventivetalent.bossbar.BossBarAPI; + +import javax.annotation.concurrent.ThreadSafe; +import java.util.Map; + +/** + * @Author sky + * @Since 2018-05-27 18:52 + */ +@ThreadSafe +@SerializableAs("BAR") +public class TLocaleBossBar extends TLocaleSerialize { + + /* + BossBar: + - ==: BAR + text: 'BossBar 血条公告' + color: BLUE + style: NOTCHED_20 + progress: 1.0 + timeout: 20 + timeout-interval: 2 + */ + + private final String text; + private final BossBarAPI.Color color; + private final BossBarAPI.Style style; + private final float progress; + private final int timeout; + private final int timeoutInterval; + private final boolean papi; + + public TLocaleBossBar(String text, BossBarAPI.Color color, BossBarAPI.Style style, float progress, int timeout, int timeoutInterval, boolean papi) { + this.text = text; + this.color = color; + this.style = style; + this.progress = progress; + this.timeout = timeout; + this.timeoutInterval = timeoutInterval; + this.papi = papi; + } + + @Override + public void sendTo(CommandSender sender, String... args) { + if (Bukkit.getPluginManager().getPlugin("BossBarAPI") == null) { + TLocale.Logger.error("LOCALE.BAR-PLUGIN-NOT-FOUND"); + return; + } + if (sender instanceof Player) { + TextComponent textComponent = new TextComponent(papi ? TLocale.Translate.setPlaceholders(sender, Strings.replaceWithOrder(text, args)) : TLocale.Translate.setColored(Strings.replaceWithOrder(text, args))); + BossBar bossBar = BossBarAPI.addBar((Player) sender, textComponent, color, style, progress, timeout, timeoutInterval); + } else { + sender.sendMessage(text); + } + } + + @Override + public Map serialize() { + return null; + } + + public static TLocaleBossBar valueOf(Map map) { + return new TLocaleBossBar(map.getOrDefault("text", "§4* Invalid Text*").toString(), getColor(String.valueOf(map.get("color"))), getStyle(String.valueOf(map.get("style"))), (float) NumberUtils.getDouble(String.valueOf(map.getOrDefault("progress", 1))), NumberUtils.getInteger(String.valueOf(map.getOrDefault("timeout", 20))), NumberUtils.getInteger(String.valueOf(map.getOrDefault("timeout-interval", 2))), isPlaceholderEnabled(map)); + } + + private static BossBarAPI.Color getColor(String color) { + try { + return BossBarAPI.Color.valueOf(color); + } catch (Exception e) { + TLocale.Logger.error("LOCALE.BAR-STYLE-IDENTIFICATION-FAILED", e.toString()); + return BossBarAPI.Color.WHITE; + } + } + + private static BossBarAPI.Style getStyle(String style) { + try { + return BossBarAPI.Style.valueOf(style); + } catch (Exception e) { + TLocale.Logger.error("LOCALE.BAR-COLOR-IDENTIFICATION-FAILED", e.toString()); + return BossBarAPI.Style.NOTCHED_20; + } + } +} diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java index 4cc689b..2a14974 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java @@ -10,10 +10,12 @@ import com.ilummc.tlib.compat.PlaceholderHook; import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocaleSerialize; import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.jsonformatter.JSONFormatter; +import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.json.tellraw.TellrawJson; +import me.skymc.taboolib.other.NumberUtils; +import me.skymc.taboolib.string.VariableFormatter; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.SerializableAs; -import org.bukkit.entity.Player; import javax.annotation.concurrent.ThreadSafe; import java.util.*; @@ -21,6 +23,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; + @ThreadSafe @SerializableAs("JSON") public class TLocaleJson extends TLocaleSerialize { @@ -72,11 +75,11 @@ public class TLocaleJson extends TLocaleSerialize { // 可能有很多个 BaseComponent,于是为每个 component 单独设置各种事件 BaseComponent[] component = TextComponent.fromLegacyText(text); arg.forEach((key, value) -> { - if ("suggest".equalsIgnoreCase(key)) { + if (key.equalsIgnoreCase("suggest")) { Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value)))); - } else if ("command".equalsIgnoreCase(key) || "commands".equalsIgnoreCase(key)) { + } else if (key.equalsIgnoreCase("command") || "commands".equalsIgnoreCase(key)) { Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value)))); - } else if ("hover".equalsIgnoreCase(key)) { + } else if (key.equalsIgnoreCase("hover")) { Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(TLocale.Translate.setColored(String.valueOf(value))).create()))); } }); @@ -101,7 +104,7 @@ public class TLocaleJson extends TLocaleSerialize { private static List getTextList(Object textObj) { if (textObj instanceof List) { - return ((List) textObj).stream().map(Object::toString).map(s -> TLocale.Translate.setColored(s)).collect(Collectors.toList()); + return ((List) textObj).stream().map(Object::toString).map(TLocale.Translate::setColored).collect(Collectors.toList()); } else if (textObj instanceof String) { return Lists.newArrayList(TLocale.Translate.setColored((String) textObj)); } else { @@ -125,11 +128,11 @@ public class TLocaleJson extends TLocaleSerialize { } private void sendRawMessage(CommandSender sender, BaseComponent[] components) { - if (sender instanceof Player) { - JSONFormatter.sendRawMessage((Player) sender, ComponentSerializer.toString(components)); - } else { - sender.sendMessage(TextComponent.toLegacyText(components)); - } + TLocale.Tellraw.send(sender, ComponentSerializer.toString(components)); + } + + private List replace(List component, CommandSender sender, String... args) { + return component.stream().map(c -> replace(c, sender, args)).collect(Collectors.toList()); } private BaseComponent[] replace(BaseComponent[] component, CommandSender sender, String... args) { @@ -140,10 +143,6 @@ public class TLocaleJson extends TLocaleSerialize { return components; } - private List replace(List component, CommandSender sender, String... args) { - return component.stream().map(c -> replace(c, sender, args)).collect(Collectors.toList()); - } - private BaseComponent replace(BaseComponent component, CommandSender sender, String... args) { if (component.getClickEvent() != null) { ClickEvent clickEvent = new ClickEvent(component.getClickEvent().getAction(), replace(sender, component.getClickEvent().getValue(), args)); @@ -166,4 +165,63 @@ public class TLocaleJson extends TLocaleSerialize { String s = Strings.replaceWithOrder(text, args); return papi ? PlaceholderHook.replace(sender, s) : s; } + + public static TellrawJson formatJson(Map section, Object textObject, TellrawJson pageJson) { + List textList = textObject instanceof List ? (List) textObject : Collections.singletonList(String.valueOf(textObject)); + // 遍历本页文本 + for (int i = 0; i < textList.size(); i++) { + // 捕捉变量 + for (VariableFormatter.Variable variable : new VariableFormatter(textList.get(i), pattern).find().getVariableList()) { + // 如果是变量 + if (variable.isVariable()) { + String[] split = variable.getText().split("@"); + // @ 前面的字符串 + String text = split.length > 1 ? split[0] : "§4* Invalid Text *"; + // @ 后面的节点名 + String node = split.length > 1 ? split[1] : null; + // 处理变量 + formatNode(section, pageJson, text, node); + } else { + pageJson.append(variable.getText()); + } + } + if (i + 1 < textList.size()) { + pageJson.newLine(); + } + } + return pageJson; + } + + private static void formatNode(Map section, TellrawJson pageJson, String text, String node) { + if (section.containsKey(node)) { + try { + Map args = (Map) section.get(node); + // 文本 + pageJson.append(args.getOrDefault("text", text).toString()); + // 功能 + if (args.containsKey("item")) { + pageJson.hoverItem(ItemUtils.getCacheItem(args.get("item").toString())); + } + if (args.containsKey("hover")) { + pageJson.hoverText(args.get("hover").toString()); + } + if (args.containsKey("suggest")) { + pageJson.clickSuggest(args.get("suggest").toString()); + } + if (args.containsKey("command")) { + pageJson.clickCommand(args.get("command").toString()); + } + if (args.containsKey("page")) { + pageJson.clickChangePage(NumberUtils.getInteger(args.get("page").toString())); + } + if (args.containsKey("url")) { + pageJson.clickOpenURL(args.get("url").toString()); + } + } catch (Exception e) { + TLocale.Logger.error("LOCALE.BOOK-ARGUMENTS-IDENTIFICATION-FAILED", e.toString()); + } + } else { + pageJson.append("§4* Invalid Argument *"); + } + } } diff --git a/src/main/java/com/ilummc/tlib/util/Strings.java b/src/main/java/com/ilummc/tlib/util/Strings.java index e454212..40207d0 100644 --- a/src/main/java/com/ilummc/tlib/util/Strings.java +++ b/src/main/java/com/ilummc/tlib/util/Strings.java @@ -2,6 +2,14 @@ package com.ilummc.tlib.util; public class Strings { + public static boolean isBlank(String var) { + return var == null || var.trim().isEmpty(); + } + + public static boolean isEmpty(CharSequence var) { + return var == null || var.length() == 0; + } + /** * 优化过的 String#replace,比默认快了大概 5 倍 * @@ -28,15 +36,13 @@ public class Strings { return stringBuilder.toString(); } + // ********************************* + // + // Deprecated + // + // ********************************* + public static String replaceWithOrder(String template, String... args) { return replaceWithOrder(template, (Object[]) args); } - - public static boolean isBlank(String var) { - return var == null || var.trim().isEmpty(); - } - - public static boolean isEmpty(CharSequence var) { - return var == null || var.length() == 0; - } } diff --git a/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java b/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java index 5cbf36c..b090544 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java @@ -1,8 +1,10 @@ package me.skymc.taboolib.bookformatter; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.chat.ComponentSerializer; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; +import com.ilummc.tlib.logger.TLogger; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -12,6 +14,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -31,11 +34,13 @@ public final class BookReflection { private static final Method craftPlayerGetHandle; - //This method takes an enum that represents the player's hand only in versions >= 1.9 - //In the other versions it only takes the nms item + /* + This method takes an enum that represents the player's hand only in versions >= 1.9 + In the other versions it only takes the nms item + */ private static final Method entityPlayerOpenBook; - //only version >= 1.9 + // only version >= 1.9 private static final Object[] hands; //Older versions @@ -115,18 +120,22 @@ public final class BookReflection { * @param meta the book meta to change * @param components the pages of the book */ - @SuppressWarnings("unchecked")//reflections = unchecked warnings - public static void setPages(BookMeta meta, BaseComponent[][] components) { + public static void setPages(BookMeta meta, BaseComponent[]... components) { + List pages = null; try { - List pages = (List) craftMetaBookField.get(meta); - pages.clear(); - for (BaseComponent[] c : components) { - final String json = ComponentSerializer.toString(c); - //System.out.println("page:" + json); //Debug - pages.add(chatSerializerA.invoke(null, json)); - } + pages = (List) craftMetaBookField.get(meta); } catch (Exception e) { - throw new UnsupportedVersionException(e); + TLogger.getGlobalLogger().error("Error while executing reflections, failed to get bookmeta (version: " + BookReflection.version + ")"); + return; + } + pages.clear(); + for (BaseComponent[] c : components) { + try { + pages.add(chatSerializerA.invoke(null, ComponentSerializer.toString(c))); + } catch (Exception e) { + TLogger.getGlobalLogger().error("Error while executing reflections, submit to developers the following log (version: " + BookReflection.version + ")"); + e.printStackTrace(); + } } } @@ -136,17 +145,21 @@ public final class BookReflection { * @param meta the book meta to change * @param components the pages of the book */ - @SuppressWarnings("unchecked")//reflections = unchecked warnings - public static void addPages(BookMeta meta, BaseComponent[][] components) { + public static void addPages(BookMeta meta, BaseComponent[]... components) { + List pages = null; try { - List pages = (List) craftMetaBookField.get(meta); - for (BaseComponent[] c : components) { - final String json = ComponentSerializer.toString(c); - //System.out.println("page:" + json); //Debug - pages.add(chatSerializerA.invoke(null, json)); - } + pages = (List) craftMetaBookField.get(meta); } catch (Exception e) { - throw new UnsupportedVersionException(e); + TLogger.getGlobalLogger().error("Error while executing reflections, failed to get bookmeta (version: " + BookReflection.version + ")"); + return; + } + for (BaseComponent[] c : components) { + try { + pages.add(chatSerializerA.invoke(null, ComponentSerializer.toString(c))); + } catch (Exception e) { + TLogger.getGlobalLogger().error("Error while executing reflections, submit to developers the following log (version: " + BookReflection.version + ")"); + e.printStackTrace(); + } } } diff --git a/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java b/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java index 70c7003..428c447 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java @@ -1,6 +1,6 @@ package me.skymc.taboolib.bookformatter.action; -import net.md_5.bungee.api.chat.ClickEvent; +import com.ilummc.tlib.bungee.api.chat.ClickEvent; /** * @author sky @@ -86,12 +86,12 @@ public interface ClickAction { @Override public ClickEvent.Action action() { - return null; + return action; } @Override public String value() { - return null; + return value; } } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java b/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java index b45d86d..48bad9f 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java @@ -1,10 +1,10 @@ package me.skymc.taboolib.bookformatter.action; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.HoverEvent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; import me.skymc.taboolib.bookformatter.BookAchievement; import me.skymc.taboolib.bookformatter.BookReflection; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Achievement; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; @@ -157,12 +157,12 @@ public interface HoverAction { @Override public HoverEvent.Action action() { - return null; + return action; } @Override public BaseComponent[] value() { - return new BaseComponent[0]; + return value; } } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bookformatter/builder/BookBuilder.java b/src/main/java/me/skymc/taboolib/bookformatter/builder/BookBuilder.java index 3c639ed..d79d6f5 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/builder/BookBuilder.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/builder/BookBuilder.java @@ -1,7 +1,7 @@ package me.skymc.taboolib.bookformatter.builder; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; import me.skymc.taboolib.bookformatter.BookReflection; -import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; @@ -125,4 +125,19 @@ public class BookBuilder { book.setItemMeta(meta); return book; } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + + public BookMeta getMeta() { + return meta; + } + + public ItemStack getBook() { + return book; + } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java b/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java index 73e7ced..f95e033 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java @@ -1,7 +1,7 @@ package me.skymc.taboolib.bookformatter.builder; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; +import com.ilummc.tlib.bungee.api.chat.*; +import me.skymc.taboolib.string.ArrayUtils; import java.util.ArrayList; import java.util.Arrays; @@ -14,7 +14,7 @@ import java.util.List; */ public class PageBuilder { - private List text = new ArrayList<>(); + private BaseComponent[] text = TextComponent.fromLegacyText(""); /** * Adds a simple black-colored text to the page @@ -22,7 +22,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(String text) { - this.text.add(TextBuilder.of(text).build()); + Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.text = ArrayUtils.arrayAppend(this.text, component)); return this; } @@ -32,7 +32,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(BaseComponent component) { - this.text.add(component); + this.text = ArrayUtils.arrayAppend(this.text, component); return this; } @@ -42,17 +42,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(BaseComponent... components) { - this.text.addAll(Arrays.asList(components)); - return this; - } - - /** - * Adds one or more components to the page - * @param components the components to add - * @return the PageBuilder's calling instance - */ - public PageBuilder add(Collection components) { - this.text.addAll(components); + Arrays.stream(components).forEach(component -> this.text = ArrayUtils.arrayAppend(this.text, component)); return this; } @@ -61,8 +51,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder newLine() { - this.text.add(new TextComponent("\n")); - return this; + return add("\n"); } /** @@ -78,10 +67,9 @@ public class PageBuilder { * @return an array of BaseComponents representing the page */ public BaseComponent[] build() { - return text.toArray(new BaseComponent[0]); + return text; } - /** * Creates a new PageBuilder instance wih the parameter as the initial text * @param text the initial text of the page diff --git a/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java b/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java index c670f24..34a271c 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java @@ -1,11 +1,8 @@ package me.skymc.taboolib.bookformatter.builder; +import com.ilummc.tlib.bungee.api.chat.*; import me.skymc.taboolib.bookformatter.action.ClickAction; import me.skymc.taboolib.bookformatter.action.HoverAction; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; /** * @author sky diff --git a/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java b/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java new file mode 100644 index 0000000..15d3caf --- /dev/null +++ b/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java @@ -0,0 +1,133 @@ +package me.skymc.taboolib.json.tellraw; + +import com.ilummc.tlib.bungee.api.chat.*; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; +import com.ilummc.tlib.logger.TLogger; +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.methods.ReflectionUtils; +import me.skymc.taboolib.nms.NMSUtils; +import me.skymc.taboolib.other.NumberUtils; +import me.skymc.taboolib.string.ArrayUtils; +import me.skymc.taboolib.string.VariableFormatter; +import org.bukkit.command.CommandSender; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * @Author sky + * @Since 2018-05-26 14:42json + */ +public class TellrawJson { + + private BaseComponent[] components = TextComponent.fromLegacyText(""); + private final Class craftItemStackClazz = NMSUtils.getOBCClass("inventory.CraftItemStack"); + private final Class nmsItemStackClazz = NMSUtils.getNMSClass("ItemStack"); + private final Class nbtTagCompoundClazz = NMSUtils.getNMSClass("NBTTagCompound"); + private final String INVALID_ITEM = "{id:stone,tag:{display:{Name:§c* Invalid ItemStack *}}}"; + + TellrawJson() { + } + + public static TellrawJson create() { + return new TellrawJson(); + } + + public String toRawMessage() { + return ComponentSerializer.toString(components); + } + + public String toLegacyText() { + return TextComponent.toLegacyText(components); + } + + public TellrawJson newLine() { + return append("\n"); + } + + public TellrawJson append(String text) { + Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.components = ArrayUtils.arrayAppend(this.components, component)); + return this; + } + + public TellrawJson hoverText(String text) { + getLatestComponent().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(text).create())); + return this; + } + + public TellrawJson hoverItem(ItemStack itemStack) { + getLatestComponent().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ComponentBuilder(getItemComponent(itemStack)).create())); + return this; + } + + public TellrawJson clickCommand(String command) { + getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command)); + return this; + } + + public TellrawJson clickSuggest(String command) { + getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command)); + return this; + } + + public TellrawJson clickOpenURL(String url) { + getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url)); + return this; + } + + public TellrawJson clickChangePage(int page) { + getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, String.valueOf(page))); + return this; + } + + public void send(CommandSender sender) { + TLocale.Tellraw.send(sender, toRawMessage()); + } + + public String getItemComponent(ItemStack itemStack) { + try { + Method asNMSCopyMethod = ReflectionUtils.getMethod(craftItemStackClazz, "asNMSCopy", ItemStack.class); + Method saveNmsItemStackMethod = ReflectionUtils.getMethod(nmsItemStackClazz, "save", nbtTagCompoundClazz); + Object nmsNbtTagCompoundObj = nbtTagCompoundClazz.newInstance(); + Object nmsItemStackObj = asNMSCopyMethod.invoke(null, itemStack); + return saveNmsItemStackMethod.invoke(nmsItemStackObj, nmsNbtTagCompoundObj).toString(); + } catch (Throwable t) { + TLogger.getGlobalLogger().error("failed to serialize itemstack to nms item: " + t.toString()); + return INVALID_ITEM; + } + } + + // ********************************* + // + // Private Methods + // + // ********************************* + + private BaseComponent getLatestComponent() { + return components[components.length - 1]; + } + + private void setLatestComponent(BaseComponent component) { + components[components.length - 1] = component; + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public BaseComponent[] getComponents() { + return components; + } + + public void setComponents(BaseComponent[] components) { + this.components = components; + } + +} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java index b6ddeac..6ac0c21 100644 --- a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java +++ b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java @@ -1,5 +1,6 @@ package me.skymc.taboolib.jsonformatter; +import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.json.JSONArray; import me.skymc.taboolib.json.JSONObject; import me.skymc.taboolib.jsonformatter.click.ClickEvent; @@ -15,17 +16,14 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; +/** + * @author Unknown + */ +@Deprecated public class JSONFormatter { public static void sendRawMessage(Player player, String message) { - try { - Object entityplayer = NMSUtils.getHandle(player); - Object ppco = ppc.get(entityplayer); - Object packet = ppocc.newInstance(message); - sp.invoke(ppco, packet); - } catch (Exception e) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + message); - } + TLocale.Tellraw.send(player, message); } private JSONArray ja = new JSONArray(); diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java index 863294c..54e02a5 100644 --- a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java +++ b/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java @@ -3,6 +3,7 @@ package me.skymc.taboolib.jsonformatter.hover; import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.json.JSONObject; +import me.skymc.taboolib.json.tellraw.TellrawJson; import me.skymc.taboolib.nms.item.DabItemUtils; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; @@ -13,64 +14,68 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -public class ShowItemEvent extends HoverEvent{ - - private JSONObject object = new JSONObject(); - - public Object getItemTag(ItemStack item) { - try { - return DabItemUtils.getInstance().getTag(DabItemUtils.getInstance().getNMSCopy(item)); - } catch (Exception e) { - return null; - } - } - - @SuppressWarnings("deprecation") - public ShowItemEvent(ItemStack is){ - try{ - object.put("action", "show_item"); - StringBuilder tag = new StringBuilder(); - Object itemTag = getItemTag(is); - if (itemTag != null) { +public class ShowItemEvent extends HoverEvent { + + private JSONObject object = new JSONObject(); + + public Object getItemTag(ItemStack item) { + try { + return DabItemUtils.getInstance().getTag(DabItemUtils.getInstance().getNMSCopy(item)); + } catch (Exception e) { + return null; + } + } + + @SuppressWarnings("deprecation") + public ShowItemEvent(ItemStack is) { + if (TabooLib.getVerint() > 10700) { + try { + object.put("action", "show_item"); + object.put("value", TellrawJson.create().getItemComponent(is)); + } catch (Exception ignored) { + } + } + try { + object.put("action", "show_item"); + StringBuilder tag = new StringBuilder(); + Object itemTag = getItemTag(is); + if (itemTag != null) { tag.append(",tag:").append(itemTag); - } - else { - ItemMeta im = is.getItemMeta(); - List lore = im.hasLore() ? im.getLore() : new ArrayList<>(); - Map enchants = is.getItemMeta().getEnchants(); + } else { + ItemMeta im = is.getItemMeta(); + List lore = im.hasLore() ? im.getLore() : new ArrayList<>(); + Map enchants = is.getItemMeta().getEnchants(); tag.append(",tag:{display:{Name:").append(enchants.size() > 0 ? "§b§o" : "§f").append(ItemUtils.getCustomName(is)); - if (lore.size() > 0) { - tag.append(",Lore:["); - for (String s : lore){ + if (lore.size() > 0) { + tag.append(",Lore:["); + for (String s : lore) { tag.append("\"").append(s).append("\","); - } - tag.delete(tag.length() - 1, tag.length()); - tag.append("]"); - } - tag.append("}"); - if (enchants.size() > 0) { - if(tag.length() > 6) { - tag.append(","); - } - tag.append("ench:["); - for (Entry e : enchants.entrySet()) { + } + tag.delete(tag.length() - 1, tag.length()); + tag.append("]"); + } + tag.append("}"); + if (enchants.size() > 0) { + if (tag.length() > 6) { + tag.append(","); + } + tag.append("ench:["); + for (Entry e : enchants.entrySet()) { tag.append("{id:").append(e.getKey().getId()).append(",lvl:").append(e.getValue()).append("},"); - } - tag.delete(tag.length() - 1, tag.length()); - tag.append("]"); - } - tag.append("}"); - } - - object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}"); - } catch(Exception e) { - e.printStackTrace(); - } - } - - @Override - public JSONObject getEvent(){ - return object; - } - + } + tag.delete(tag.length() - 1, tag.length()); + tag.append("]"); + } + tag.append("}"); + } + object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}"); + } catch (Exception ignored) { + } + } + + @Override + public JSONObject getEvent() { + return object; + } + } diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java index 603f4ce..7b07bf3 100644 --- a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java +++ b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java @@ -14,29 +14,29 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.server.ServerCommandEvent; public class ListenerPlayerCommand implements Listener { - - @EventHandler - public void cmd(ServerCommandEvent e) { - if ("savefile".equals(e.getCommand())) { - if (TabooLib.getVerint() > 10700) { - e.setCancelled(true); - } + + @EventHandler + public void cmd(ServerCommandEvent e) { + if ("savefile".equals(e.getCommand())) { + if (TabooLib.getVerint() > 10700) { + e.setCancelled(true); + } Bukkit.getScheduler().runTask(Main.getInst(), DataUtils::saveAllCaches); - Bukkit.getScheduler().runTask(Main.getInst(), () -> PlayerDataManager.saveAllCaches(true, false)); - } - } - - @SuppressWarnings("deprecation") - @EventHandler - public void cmd(PlayerCommandPreprocessEvent e) { - if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) { - e.setCancelled(true); - - NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand()); - nbti.setInteger("Unbreakable", 1); - e.getPlayer().setItemInHand(nbti.getItem()); - - MsgUtils.send(e.getPlayer(), "Success!"); - } - } + Bukkit.getScheduler().runTask(Main.getInst(), () -> PlayerDataManager.saveAllCaches(true, false)); + } + } + + @SuppressWarnings("deprecation") + @EventHandler + public void cmd(PlayerCommandPreprocessEvent e) { + if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) { + e.setCancelled(true); + + NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand()); + nbti.setInteger("Unbreakable", 1); + e.getPlayer().setItemInHand(nbti.getItem()); + + MsgUtils.send(e.getPlayer(), "Success!"); + } + } } diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java index 849d117..fcdf616 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java @@ -20,8 +20,10 @@ import java.util.List; import java.util.Map; import java.util.UUID; +/** + * @author Unknown + */ @SuppressWarnings({"rawtypes", "unchecked"}) -@Deprecated public class NMSUtil18 { protected static boolean failed = false; diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java index db241bc..7177ddd 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java @@ -22,17 +22,19 @@ import java.lang.reflect.Method; import java.util.*; import java.util.logging.Level; -@SuppressWarnings({ "rawtypes", "unchecked" }) -@Deprecated +/** + * @author Unknown + */ +@SuppressWarnings({"rawtypes", "unchecked"}) public class NMSUtil19 { - + protected static boolean failed = false; protected static boolean legacy = false; protected static String versionPrefix = ""; protected final static int NBT_TYPE_COMPOUND = 10; - protected final static int NBT_TYPE_INT_ARRAY= 11; + protected final static int NBT_TYPE_INT_ARRAY = 11; protected final static int NBT_TYPE_DOUBLE = 6; protected final static int NBT_TYPE_FLOAT = 5; protected final static int NBT_TYPE_STRING = 8; @@ -40,91 +42,91 @@ public class NMSUtil19 { protected static int WITHER_SKULL_TYPE = 66; protected static int FIREWORK_TYPE = 76; - protected static Class class_Block; - protected static Class class_ItemStack; - protected static Class class_NBTBase; - protected static Class class_NBTTagCompound; - protected static Class class_NBTTagList; - protected static Class class_NBTTagByte; - protected static Class class_NBTTagDouble; - protected static Class class_NBTTagFloat; - protected static Class class_NBTTagInt; - protected static Class class_NBTTagLong; - protected static Class class_NBTTagShort; - protected static Class class_NBTTagString; - protected static Class class_CraftTask; - protected static Class class_CraftInventoryCustom; - protected static Class class_CraftItemStack; - protected static Class class_CraftBlockState; - protected static Class class_CraftLivingEntity; - protected static Class class_CraftWorld; - protected static Class class_Consumer; - protected static Class class_Entity; - protected static Class class_EntityCreature; - protected static Class class_EntityLiving; - protected static Class class_EntityHuman; - protected static Class class_DataWatcher; - protected static Class class_DamageSource; - protected static Class class_EntityDamageSource; - protected static Class class_World; - protected static Class class_WorldServer; - protected static Class class_Packet; + public static Class class_Block; + public static Class class_ItemStack; + public static Class class_NBTBase; + public static Class class_NBTTagCompound; + public static Class class_NBTTagList; + public static Class class_NBTTagByte; + public static Class class_NBTTagDouble; + public static Class class_NBTTagFloat; + public static Class class_NBTTagInt; + public static Class class_NBTTagLong; + public static Class class_NBTTagShort; + public static Class class_NBTTagString; + public static Class class_CraftTask; + public static Class class_CraftInventoryCustom; + public static Class class_CraftItemStack; + public static Class class_CraftBlockState; + public static Class class_CraftLivingEntity; + public static Class class_CraftWorld; + public static Class class_Consumer; + public static Class class_Entity; + public static Class class_EntityCreature; + public static Class class_EntityLiving; + public static Class class_EntityHuman; + public static Class class_DataWatcher; + public static Class class_DamageSource; + public static Class class_EntityDamageSource; + public static Class class_World; + public static Class class_WorldServer; + public static Class class_Packet; protected static Class class_EnumSkyBlock; - protected static Class class_EntityPainting; - protected static Class class_EntityItemFrame; - protected static Class class_EntityMinecartRideable; - protected static Class class_EntityTNTPrimed; - protected static Class class_AxisAlignedBB; - protected static Class class_PathPoint; - protected static Class class_PathEntity; - protected static Class class_EntityFirework; - protected static Class class_CraftSkull; - protected static Class class_CraftBanner; - protected static Class class_CraftMetaSkull; - protected static Class class_CraftMetaBanner; - protected static Class class_GameProfile; - protected static Class class_GameProfileProperty; - protected static Class class_BlockPosition; - protected static Class class_NBTCompressedStreamTools; - protected static Class class_TileEntity; - protected static Class class_TileEntitySign; - protected static Class class_TileEntityContainer; - protected static Class class_ChestLock; + public static Class class_EntityPainting; + public static Class class_EntityItemFrame; + public static Class class_EntityMinecartRideable; + public static Class class_EntityTNTPrimed; + public static Class class_AxisAlignedBB; + public static Class class_PathPoint; + public static Class class_PathEntity; + public static Class class_EntityFirework; + public static Class class_CraftSkull; + public static Class class_CraftBanner; + public static Class class_CraftMetaSkull; + public static Class class_CraftMetaBanner; + public static Class class_GameProfile; + public static Class class_GameProfileProperty; + public static Class class_BlockPosition; + public static Class class_NBTCompressedStreamTools; + public static Class class_TileEntity; + public static Class class_TileEntitySign; + public static Class class_TileEntityContainer; + public static Class class_ChestLock; protected static Class class_EnumDirection; - protected static Class class_EntityHorse; - protected static Class class_EntityWitherSkull; - protected static Class class_PacketPlayOutAttachEntity; - protected static Class class_PacketPlayOutEntityDestroy; - protected static Class class_PacketPlayOutSpawnEntity; - protected static Class class_PacketPlayOutSpawnEntityLiving; - protected static Class class_PacketPlayOutEntityMetadata; - protected static Class class_PacketPlayOutEntityStatus; - protected static Class class_PacketPlayOutCustomSoundEffect; - protected static Class class_PacketPlayOutExperience; - protected static Class class_PacketPlayOutAnimation; - protected static Class class_PacketPlayOutBlockBreakAnimation; + public static Class class_EntityHorse; + public static Class class_EntityWitherSkull; + public static Class class_PacketPlayOutAttachEntity; + public static Class class_PacketPlayOutEntityDestroy; + public static Class class_PacketPlayOutSpawnEntity; + public static Class class_PacketPlayOutSpawnEntityLiving; + public static Class class_PacketPlayOutEntityMetadata; + public static Class class_PacketPlayOutEntityStatus; + public static Class class_PacketPlayOutCustomSoundEffect; + public static Class class_PacketPlayOutExperience; + public static Class class_PacketPlayOutAnimation; + public static Class class_PacketPlayOutBlockBreakAnimation; protected static Enum enum_SoundCategory_PLAYERS; protected static Class class_EnumSoundCategory; - protected static Class class_EntityFallingBlock; - protected static Class class_EntityArmorStand; - protected static Class class_EntityPlayer; - protected static Class class_PlayerConnection; - protected static Class class_Chunk; - protected static Class class_CraftPlayer; - protected static Class class_CraftChunk; - protected static Class class_CraftEntity; - protected static Class class_EntityProjectile; - protected static Class class_EntityFireball; - protected static Class class_EntityArrow; - protected static Class class_CraftArrow; - protected static Class class_MinecraftServer; - protected static Class class_CraftServer; - protected static Class class_DataWatcherObject; - protected static Class class_PacketPlayOutChat; + public static Class class_EntityFallingBlock; + public static Class class_EntityArmorStand; + public static Class class_EntityPlayer; + public static Class class_PlayerConnection; + public static Class class_Chunk; + public static Class class_CraftPlayer; + public static Class class_CraftChunk; + public static Class class_CraftEntity; + public static Class class_EntityProjectile; + public static Class class_EntityFireball; + public static Class class_EntityArrow; + public static Class class_CraftArrow; + public static Class class_MinecraftServer; + public static Class class_CraftServer; + public static Class class_DataWatcherObject; + public static Class class_PacketPlayOutChat; protected static Class class_ChatMessageType; protected static Enum enum_ChatMessageType_GAME_INFO; - protected static Class class_ChatComponentText; - protected static Class class_IChatBaseComponent; + public static Class class_ChatComponentText; + public static Class class_IChatBaseComponent; protected static Method class_NBTTagList_addMethod; protected static Method class_NBTTagList_getMethod; @@ -275,8 +277,7 @@ public class NMSUtil19 { protected static Field class_Entity_moveStrafingField; protected static Field class_Entity_moveForwardField; - static - { + static { // Find classes Bukkit hides from us. :-D // Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach. String className = Bukkit.getServer().getClass().getName(); @@ -312,8 +313,8 @@ public class NMSUtil19 { class_Packet = fixBukkitClass("net.minecraft.server.Packet"); class_World = fixBukkitClass("net.minecraft.server.World"); class_WorldServer = fixBukkitClass("net.minecraft.server.WorldServer"); - class_EnumSkyBlock = (Class)fixBukkitClass("net.minecraft.server.EnumSkyBlock"); - class_EnumSoundCategory = (Class)fixBukkitClass("net.minecraft.server.SoundCategory"); + class_EnumSkyBlock = (Class) fixBukkitClass("net.minecraft.server.EnumSkyBlock"); + class_EnumSoundCategory = (Class) fixBukkitClass("net.minecraft.server.SoundCategory"); enum_SoundCategory_PLAYERS = Enum.valueOf(class_EnumSoundCategory, "PLAYERS"); class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting"); class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature"); @@ -394,7 +395,7 @@ public class NMSUtil19 { class_EntityPlayer_setResourcePackMethod = class_EntityPlayer.getMethod("setResourcePack", String.class, String.class); class_CraftServer_getServerMethod = class_CraftServer.getMethod("getServer"); class_MinecraftServer_getResourcePackMethod = class_MinecraftServer.getMethod("getResourcePack"); - + class_CraftInventoryCustom_constructor = class_CraftInventoryCustom.getConstructor(InventoryHolder.class, Integer.TYPE, String.class); class_EntityFireworkConstructor = class_EntityFirework.getConstructor(class_World, Double.TYPE, Double.TYPE, Double.TYPE, class_ItemStack); class_PacketSpawnEntityConstructor = class_PacketPlayOutSpawnEntity.getConstructor(class_Entity, Integer.TYPE); @@ -478,10 +479,10 @@ public class NMSUtil19 { class_Chunk_doneField.setAccessible(true); class_CraftItemStack_getHandleField = class_CraftItemStack.getDeclaredField("handle"); class_CraftItemStack_getHandleField.setAccessible(true); - + class_MemorySection_mapField = MemorySection.class.getDeclaredField("map"); class_MemorySection_mapField.setAccessible(true); - + class_TileEntityContainer = fixBukkitClass("net.minecraft.server.TileEntityContainer"); class_ChestLock = fixBukkitClass("net.minecraft.server.ChestLock"); class_Entity_getBoundingBox = class_Entity.getMethod("getBoundingBox"); @@ -508,7 +509,7 @@ public class NMSUtil19 { class_CraftBanner_setPatternsMethod = class_CraftBanner.getMethod("setPatterns", List.class); class_CraftBanner_setBaseColorMethod = class_CraftBanner.getMethod("setBaseColor", DyeColor.class); - class_EnumDirection = (Class)fixBukkitClass("net.minecraft.server.EnumDirection"); + class_EnumDirection = (Class) fixBukkitClass("net.minecraft.server.EnumDirection"); class_BlockPosition_Constructor = class_BlockPosition.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE); class_EntityPaintingConstructor = class_EntityPainting.getConstructor(class_World, class_BlockPosition, class_EnumDirection); class_EntityItemFrameConstructor = class_EntityItemFrame.getConstructor(class_World, class_BlockPosition, class_EnumDirection); @@ -603,7 +604,7 @@ public class NMSUtil19 { class_ChatComponentText_constructor = class_ChatComponentText.getConstructor(String.class); // 1.12 specific - class_ChatMessageType = (Class)fixBukkitClass("net.minecraft.server.ChatMessageType"); + class_ChatMessageType = (Class) fixBukkitClass("net.minecraft.server.ChatMessageType"); enum_ChatMessageType_GAME_INFO = Enum.valueOf(class_ChatMessageType, "GAME_INFO"); class_PacketPlayOutChat_constructor = class_PacketPlayOutChat.getConstructor(class_IChatBaseComponent, class_ChatMessageType); @@ -771,8 +772,7 @@ public class NMSUtil19 { Bukkit.getLogger().log(Level.WARNING, "An error occurred, setting arrow lifespan will not work", ex); class_EntityArrow_lifeField = null; } - if (class_EntityArrow_lifeField != null) - { + if (class_EntityArrow_lifeField != null) { class_EntityArrow_lifeField.setAccessible(true); } @@ -874,8 +874,7 @@ public class NMSUtil19 { // 1.10 and earlier legacy = true; } - } - catch (Throwable ex) { + } catch (Throwable ex) { failed = true; Bukkit.getLogger().log(Level.SEVERE, "An unexpected error occurred initializing Magic", ex); } @@ -884,7 +883,7 @@ public class NMSUtil19 { public static boolean getFailed() { return failed; } - + public static boolean isLegacy() { return legacy; } @@ -994,7 +993,7 @@ public class NMSUtil19 { Object chunkHandle = getHandle(chunk); boolean done = false; try { - done = (Boolean)class_Chunk_doneField.get(chunkHandle); + done = (Boolean) class_Chunk_doneField.get(chunkHandle); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1021,11 +1020,11 @@ public class NMSUtil19 { return handle; } - protected static void sendPacket(Server server, Location source, Collection players, Object packet) throws Exception { + protected static void sendPacket(Server server, Location source, Collection players, Object packet) throws Exception { players = ((players != null && players.size() > 0) ? players : server.getOnlinePlayers()); int viewDistance = Bukkit.getServer().getViewDistance() * 16; - int viewDistanceSquared = viewDistance * viewDistance; + int viewDistanceSquared = viewDistance * viewDistance; World sourceWorld = source.getWorld(); for (Player player : players) { Location location = player.getLocation(); @@ -1045,31 +1044,29 @@ public class NMSUtil19 { Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet); sendPacketMethod.invoke(connection, packet); } - - public static int getFacing(BlockFace direction) - { + + public static int getFacing(BlockFace direction) { int dir; switch (direction) { - case SOUTH: - default: - dir = 0; - break; - case WEST: - dir = 1; - break; - case NORTH: - dir = 2; - break; - case EAST: - dir = 3; - break; + case SOUTH: + default: + dir = 0; + break; + case WEST: + dir = 1; + break; + case NORTH: + dir = 2; + break; + case EAST: + dir = 3; + break; } - + return dir; } - public static Entity getBukkitEntity(Object entity) - { + public static Entity getBukkitEntity(Object entity) { if (entity == null) { return null; } @@ -1079,7 +1076,7 @@ public class NMSUtil19 { if (!(bukkitEntity instanceof Entity)) { return null; } - return (Entity)bukkitEntity; + return (Entity) bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); } @@ -1197,7 +1194,7 @@ public class NMSUtil19 { } Boolean result = false; try { - result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); + result = (Boolean) class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1267,7 +1264,7 @@ public class NMSUtil19 { } String meta = null; try { - meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); + meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1280,7 +1277,7 @@ public class NMSUtil19 { } String meta = null; try { - meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); + meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1293,7 +1290,7 @@ public class NMSUtil19 { } Byte meta = null; try { - meta = (Byte)class_NBTTagCompound_getByteMethod.invoke(node, tag); + meta = (Byte) class_NBTTagCompound_getByteMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1306,7 +1303,7 @@ public class NMSUtil19 { } Integer meta = null; try { - meta = (Integer)class_NBTTagCompound_getIntMethod.invoke(node, tag); + meta = (Integer) class_NBTTagCompound_getIntMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1319,7 +1316,7 @@ public class NMSUtil19 { } Boolean meta = null; try { - meta = (Boolean)class_NBTTagCompound_getBooleanMethod.invoke(node, tag); + meta = (Boolean) class_NBTTagCompound_getBooleanMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1327,7 +1324,7 @@ public class NMSUtil19 { } public static void setMeta(Object node, String tag, String value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1342,7 +1339,7 @@ public class NMSUtil19 { } public static void setMetaLong(Object node, String tag, long value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1353,7 +1350,7 @@ public class NMSUtil19 { } public static void setMetaBoolean(Object node, String tag, boolean value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1364,7 +1361,7 @@ public class NMSUtil19 { } public static void setMetaDouble(Object node, String tag, double value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1375,7 +1372,7 @@ public class NMSUtil19 { } public static void setMetaInt(Object node, String tag, int value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1386,7 +1383,7 @@ public class NMSUtil19 { } public static void removeMeta(Object node, String tag) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1453,7 +1450,7 @@ public class NMSUtil19 { ex.printStackTrace(); return false; } - + return true; } @@ -1471,7 +1468,7 @@ public class NMSUtil19 { if (tagObject == null) { return null; } - meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); + meta = (String) class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1578,7 +1575,7 @@ public class NMSUtil19 { } catch (Throwable ignored) { } - + return unbreakableFlag != null && unbreakableFlag; } @@ -1646,7 +1643,7 @@ public class NMSUtil19 { Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks); Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled"); - result = (Boolean)cancelledField.get(explosion); + result = (Boolean) cancelledField.get(explosion); } catch (Throwable ex) { ex.printStackTrace(); result = false; @@ -1665,7 +1662,7 @@ public class NMSUtil19 { public static void makeUnplaceable(ItemStack itemStack) { setMeta(itemStack, "unplaceable", "true"); } - + public static void removeUnplaceable(ItemStack itemStack) { removeMeta(itemStack, "unplaceable"); } @@ -1743,7 +1740,7 @@ public class NMSUtil19 { } else { nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag); } - item = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); + item = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); } catch (Exception ex) { ex.printStackTrace(); } @@ -1753,7 +1750,7 @@ public class NMSUtil19 { public static ItemStack[] getItems(Object rootTag, String tagName) { try { Object itemList = class_NBTTagCompound_getListMethod.invoke(rootTag, tagName, NBT_TYPE_COMPOUND); - Integer size = (Integer)class_NBTTagList_sizeMethod.invoke(itemList); + Integer size = (Integer) class_NBTTagList_sizeMethod.invoke(itemList); ItemStack[] items = new ItemStack[size]; for (int i = 0; i < size; i++) { try { @@ -1823,10 +1820,10 @@ public class NMSUtil19 { class_TileEntity_saveMethod.invoke(tileEntity, entityData); Object itemList = class_NBTTagCompound_getListMethod.invoke(entityData, "Items", NBT_TYPE_COMPOUND); if (itemList != null) { - List items = (List)class_NBTTagList_list.get(itemList); + List items = (List) class_NBTTagList_list.get(itemList); items.clear(); } - class_NBTTagCompound_removeMethod.invoke(entityData,"Item"); + class_NBTTagCompound_removeMethod.invoke(entityData, "Item"); class_TileEntity_loadMethod.invoke(tileEntity, entityData); class_TileEntity_updateMethod.invoke(tileEntity); } @@ -1871,9 +1868,9 @@ public class NMSUtil19 { } try { Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE); - Double x = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 0); - Double y = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 1); - Double z = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 2); + Double x = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 0); + Double y = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 1); + Double z = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 2); if (x != null && y != null && z != null) { return new Vector(x, y, z); } @@ -1886,7 +1883,7 @@ public class NMSUtil19 { public static Entity getEntity(World world, UUID uuid) { try { Object worldHandle = getHandle(world); - final Map entityMap = (Map)class_WorldServer_entitiesByUUIDField.get(worldHandle); + final Map entityMap = (Map) class_WorldServer_entitiesByUUIDField.get(worldHandle); if (entityMap != null) { Object nmsEntity = entityMap.get(uuid); if (nmsEntity != null) { @@ -1906,9 +1903,8 @@ public class NMSUtil19 { ex.printStackTrace(); } } - - public static void playCustomSound(Player player, Location location, String sound, float volume, float pitch) - { + + public static void playCustomSound(Player player, Location location, String sound, float volume, float pitch) { try { Object packet = class_PacketPlayOutCustomSoundEffect_Constructor.newInstance(sound, enum_SoundCategory_PLAYERS, location.getX(), location.getY(), location.getZ(), volume, pitch); sendPacket(player, packet); @@ -1917,17 +1913,15 @@ public class NMSUtil19 { } } - public static Map getMap(ConfigurationSection section) - { + public static Map getMap(ConfigurationSection section) { if (section == null) { return null; } - if (section instanceof MemorySection) - { + if (section instanceof MemorySection) { try { Object mapObject = class_MemorySection_mapField.get(section); if (mapObject instanceof Map) { - return (Map)mapObject; + return (Map) mapObject; } } catch (Exception ex) { ex.printStackTrace(); @@ -1940,7 +1934,7 @@ public class NMSUtil19 { for (String key : keys) { map.put(key, section.get(key)); } - + return map; } @@ -1956,7 +1950,7 @@ public class NMSUtil19 { if (handle == null) { return false; } - return (Boolean)class_ItemStack_isEmptyMethod.invoke(handle); + return (Boolean) class_ItemStack_isEmptyMethod.invoke(handle); } catch (Throwable ex) { ex.printStackTrace(); } diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java index 7ec6521..88995c3 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java @@ -7,6 +7,9 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +/** + * @author Unknown + */ public class NMSUtils { public static Class c = getOBCClass("block.CraftBlock"); diff --git a/src/main/java/me/skymc/taboolib/player/PlayerUtils.java b/src/main/java/me/skymc/taboolib/player/PlayerUtils.java index 76ce71e..bc2a665 100644 --- a/src/main/java/me/skymc/taboolib/player/PlayerUtils.java +++ b/src/main/java/me/skymc/taboolib/player/PlayerUtils.java @@ -8,54 +8,56 @@ import org.bukkit.inventory.ItemStack; import java.util.HashSet; -@SuppressWarnings("deprecation") +/** + * @author sky + */ public class PlayerUtils { - - /** - * 获取目标方块 - * - * @param player 玩家 - * @param max 最大视野 - * @return - */ - public static Block getTargetBlock(Player player, int max) { - HashSet Byte = new HashSet<>(); - Byte.add((byte) 0); - return player.getTargetBlock(Byte, max); - } - - /** - * 重写数据 - * - * @param player 玩家 - * @param scoreboard 是否清理计分板 - */ - public static void resetData(Player player, boolean scoreboard) { - if (player.isDead()) { - player.spigot().respawn(); - } - player.closeInventory(); - player.setGameMode(GameMode.SURVIVAL); - player.getInventory().setArmorContents(new ItemStack[4]); - player.getInventory().setContents(new ItemStack[0]); - player.setAllowFlight(false); - player.setFlying(false); - player.setExp(0.0F); - player.setLevel(0); - player.setSneaking(false); - player.setSprinting(false); - player.setFoodLevel(20); - player.setSaturation(10.0F); - player.setExhaustion(0.0F); - player.setMaxHealth(20.0D); - player.setHealth(20.0D); - player.setFireTicks(0); - player.setItemOnCursor(null); - player.getActivePotionEffects().clear(); - player.getEnderChest().clear(); - player.updateInventory(); - if (scoreboard) { - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - } + + /** + * 获取目标方块 + * + * @param player 玩家 + * @param max 最大视野 + * @return + */ + public static Block getTargetBlock(Player player, int max) { + HashSet bytes = new HashSet<>(); + bytes.add((byte) 0); + return player.getTargetBlock(bytes, max); + } + + /** + * 重写数据 + * + * @param player 玩家 + * @param scoreboard 是否清理计分板 + */ + public static void resetData(Player player, boolean scoreboard) { + if (player.isDead()) { + player.spigot().respawn(); + } + player.closeInventory(); + player.setGameMode(GameMode.SURVIVAL); + player.getInventory().setArmorContents(new ItemStack[4]); + player.getInventory().setContents(new ItemStack[0]); + player.setAllowFlight(false); + player.setFlying(false); + player.setExp(0.0F); + player.setLevel(0); + player.setSneaking(false); + player.setSprinting(false); + player.setFoodLevel(20); + player.setSaturation(10.0F); + player.setExhaustion(0.0F); + player.setMaxHealth(20.0D); + player.setHealth(20.0D); + player.setFireTicks(0); + player.setItemOnCursor(null); + player.getActivePotionEffects().clear(); + player.getEnderChest().clear(); + player.updateInventory(); + if (scoreboard) { + player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + } } diff --git a/src/main/java/me/skymc/taboolib/string/ArrayUtils.java b/src/main/java/me/skymc/taboolib/string/ArrayUtils.java index 561c282..86bc5fe 100644 --- a/src/main/java/me/skymc/taboolib/string/ArrayUtils.java +++ b/src/main/java/me/skymc/taboolib/string/ArrayUtils.java @@ -1,5 +1,10 @@ package me.skymc.taboolib.string; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -11,34 +16,80 @@ import java.util.stream.IntStream; * @since 2018-04-16 */ public class ArrayUtils { - - public static List asList(T... args) { - List list = new ArrayList<>(); - Collections.addAll(list, args); - return list; - } - - public static String[] addFirst(String[] args, String... value) { - if (args.length < 1) { - return value; - } - List list = asList(args); - for (int i = value.length - 1 ; i >= 0 ; i--) { - list.add(0, value[i]); - } - return list.toArray(new String[0]); - } - - public static String[] removeFirst(String[] args) { - if (args.length <= 1) { - return new String[0]; - } - List list = asList(args); - list.remove(0); - return list.toArray(new String[0]); - } - - public static String arrayJoin(String[] args, int start) { - return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim(); - } + + public static String arrayJoin(String[] args, int start) { + return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim(); + } + + @SafeVarargs + public static List asList(T... args) { + List list = new ArrayList<>(); + Collections.addAll(list, args); + return list; + } + + public static T[] arrayAppend(T[] array, T obj) { + T[] arrayNew = arrayExpand(array, 1); + arrayNew[array.length] = obj; + return arrayNew; + } + + public static T[] arrayAddFirst(T[] array, T obj) { + T[] arrayNew = arrayExpandAtFirst(array, 1); + arrayNew[0] = obj; + return arrayNew; + } + + @SuppressWarnings("SuspiciousSystemArraycopy") + public static T arrayExpand(T oldArray, int expand) { + int length = Array.getLength(oldArray); + Object newArray = Array.newInstance(oldArray.getClass().getComponentType(), length + expand); + System.arraycopy(oldArray, 0, newArray, 0, length); + return (T) newArray; + } + + @SuppressWarnings("SuspiciousSystemArraycopy") + public static T arrayExpandAtFirst(T oldArray, int expand) { + int length = Array.getLength(oldArray); + Object newArray = Array.newInstance(oldArray.getClass().getComponentType(), length + expand); + System.arraycopy(oldArray, 0, newArray, expand, length); + return (T) newArray; + } + + public static T cloneAsByte(T obj) throws Exception { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); + objectOutputStream.writeObject(obj); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); + ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); + return (T) objectInputStream.readObject(); + } + + // ********************************* + // + // Deprecated + // + // ********************************* + + @Deprecated + public static String[] addFirst(String[] args, String... value) { + if (args.length < 1) { + return value; + } + List list = asList(args); + for (int i = value.length - 1; i >= 0; i--) { + list.add(0, value[i]); + } + return list.toArray(new String[0]); + } + + @Deprecated + public static String[] removeFirst(String[] args) { + if (args.length <= 1) { + return new String[0]; + } + List list = asList(args); + list.remove(0); + return list.toArray(new String[0]); + } } diff --git a/src/main/java/me/skymc/taboolib/string/VariableFormatter.java b/src/main/java/me/skymc/taboolib/string/VariableFormatter.java new file mode 100644 index 0000000..84567e0 --- /dev/null +++ b/src/main/java/me/skymc/taboolib/string/VariableFormatter.java @@ -0,0 +1,113 @@ +package me.skymc.taboolib.string; + +import com.ilummc.tlib.util.Strings; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @Author sky + * @Since 2018-05-27 11:33 + */ +public class VariableFormatter { + + private Pattern pattern; + private String text; + private String textOrigin; + private List variableList = new ArrayList<>(); + + public VariableFormatter(String text) { + this(text, "<([^<>]+)>"); + } + + public VariableFormatter(String text, String regex) { + this(text, Pattern.compile(regex)); + } + + public VariableFormatter(String text, Pattern pattern) { + this.text = text; + this.textOrigin = text; + this.pattern = pattern; + } + + public VariableFormatter reset() { + text = textOrigin; + variableList.clear(); + return this; + } + + public VariableFormatter find() { + reset(); + Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + String group = matcher.group(); + String[] textOther = text.split(group); + String textLeft = text.indexOf(group) > 0 ? textOther[0] : null; + String textRight = textOther.length >= 2 ? text.substring(text.indexOf(group) + group.length()) : null; + if (textLeft != null) { + variableList.add(new Variable(textLeft, false)); + } + variableList.add(new Variable(group.substring(1, group.length() - 1), true)); + if (textRight != null && !pattern.matcher(textRight).find()) { + variableList.add(new Variable(textRight, false)); + } else { + text = String.valueOf(textRight); + } + } + if (variableList.size() == 0) { + variableList.add(new Variable(text, false)); + } + return this; + } + + @Override + public String toString() { + return Strings.replaceWithOrder("VariableFormatter'{'pattern={0}, text=''{1}'', textOrigin=''{2}'', variableList={3}'}'", pattern, text, textOrigin, variableList); + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public String getText() { + return text; + } + + public List getVariableList() { + return variableList; + } + + // ********************************* + // + // Public classes + // + // ********************************* + + public static class Variable { + + private final String text; + private final boolean variable; + + public Variable(String text, boolean variable) { + this.text = text; + this.variable = variable; + } + + public String getText() { + return text; + } + + public boolean isVariable() { + return variable; + } + + @Override + public String toString() { + return Strings.replaceWithOrder("Variable'{'text=''{0}'', variable={1}'}'", text, variable); + } + } +} diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java index 5eb7a67..f2118a3 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java @@ -1,5 +1,9 @@ package me.skymc.taboolib.string.language2.value; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.ClickEvent; +import com.ilummc.tlib.bungee.api.chat.HoverEvent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; import me.skymc.taboolib.bookformatter.BookFormatter; import me.skymc.taboolib.bookformatter.action.ClickAction; import me.skymc.taboolib.bookformatter.action.HoverAction; @@ -8,6 +12,7 @@ import me.skymc.taboolib.bookformatter.builder.PageBuilder; import me.skymc.taboolib.bookformatter.builder.TextBuilder; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.other.NumberUtils; +import me.skymc.taboolib.string.VariableFormatter; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; @@ -21,7 +26,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; -import java.util.regex.Matcher; import java.util.regex.Pattern; /** @@ -52,17 +56,15 @@ public class Language2Book implements Language2Line { // 变量 this.player = player; this.value = format.getLanguage2Value(); - - // 获取书本设置 + this.book = BookFormatter.writtenBook(); + // 设置 formatOptions(list); - // 书本 - book = BookFormatter.writtenBook(); // 内容 PageBuilder page = new PageBuilder(); // 遍历内容 for (String line : list) { // 翻页 - if ("[page]".equals(line)) { + if (line.equals("[page]")) { book.addPages(page.build()); page = new PageBuilder(); } @@ -70,57 +72,50 @@ public class Language2Book implements Language2Line { else if (line.startsWith("@option")) { break; } else { - Matcher matcher = pattern.matcher(line); - boolean find = false; - while (matcher.find()) { - find = true; - String optionName = matcher.group(1); - String optionFullName = "<@" + matcher.group(1) + ">"; - // 判断设置是否存在 - if (!options.containsKey(optionName)) { - page.add("§4[]"); - } else { - String[] line_split = line.split(optionFullName); - try { - // 单独一行 - if (line_split.length == 0) { - page.add(options.get(optionName).build()).endLine(); - } else { - // 前段 - page.add(line_split[0]); - // 变量 - page.add(options.get(optionName).build()); - // 后段 - if (line_split.length >= 2) { - // 获取文本 - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < line_split.length; i++) { - sb.append(line_split[i]).append(optionFullName); - } - // 更改文本 - line = sb.substring(0, sb.length() - optionFullName.length()); - // 如果后段还有变量 - if (!pattern.matcher(line).find()) { - page.add(line_split[1]).endLine(); - } - } else { - page.endLine(); - } + for (VariableFormatter.Variable variable : new VariableFormatter(line, pattern).find().getVariableList()) { + if (variable.isVariable()) { + String node = variable.getText().substring(1); + if (!options.containsKey(node)) { + page.add("§4[]"); + } else { + TextBuilder builder = options.get(node); + BaseComponent component = new TextComponent(builder.getText()); + if (builder.getHover() != null) { + component.setHoverEvent(new HoverEvent(builder.getHover().action(), builder.getHover().value())); } - } catch (Exception e) { - page.add("§4[]"); + if (builder.getClick() != null) { + component.setClickEvent(new ClickEvent(builder.getClick().action(), builder.getClick().value())); + } + page.add(component); } + } else { + page.add(variable.getText()); } } - if (!find) { - page.add(line).endLine(); - } + page.newLine(); } } // 结尾 book.addPages(page.build()); } + + @Override + public void send(Player player) { + BookFormatter.forceOpen(player, book.build()); + } + + @Override + public void console() { + Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + public static Pattern getPattern() { return pattern; } @@ -141,6 +136,46 @@ public class Language2Book implements Language2Line { return book; } + // ********************************* + // + // Private Methods + // + // ********************************* + + private List> getBookPages(List source) { + List> list = new ArrayList<>(); + for (String line : removeOption(source)) { + if (line.equalsIgnoreCase("[page]")) { + list.add(new ArrayList<>()); + } else { + getLatestList(list).add(line); + } + } + return list; + } + + public List getLatestList(List> list) { + if (list.size() == 0) { + List newList = new ArrayList<>(); + list.add(newList); + return newList; + } else { + return list.get(list.size() - 1); + } + } + + public List removeOption(List source) { + List list = new ArrayList<>(); + for (String line : source) { + if (!line.contains("@option")) { + list.add(line); + } else { + return list; + } + } + return list; + } + private void formatOptions(List list) { // 获取书本设置 HashMap> _options = getOptions(list); @@ -204,14 +239,4 @@ public class Language2Book implements Language2Line { options_source.put(optionName, option); return options_source; } - - @Override - public void send(Player player) { - BookFormatter.forceOpen(player, book.build()); - } - - @Override - public void console() { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); - } } diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 3e8ddbf..2f4ae64 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -57,6 +57,10 @@ NOTIFY: LOCALE: TITLE-SEND-TO-NON-PLAYER: '该语言类型只能发送给玩家:{0}' PLUGIN-NOT-FOUND: '无效的语言文件发送形式: &4{0}' + BOOK-ARGUMENTS-IDENTIFICATION-FAILED: 'TlocaleBook 的变量识别失败: {0}' + BAR-COLOR-IDENTIFICATION-FAILED: 'TLocaleBossBar 的颜色识别失败: {0}' + BAR-STYLE-IDENTIFICATION-FAILED: 'TLocaleBossBar 的类型识别失败: {0}' + BAR-PLUGIN-NOT-FOUND: 'TLocaleBossBar 的依赖插件 BossBarAPI 不存在' MISC: FIELD-COPY-FAILED: '拷贝 {0} 对象失败' diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index f51358c..e683e5f 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -25,4 +25,4 @@ commands: aliases: [tlm] depend: [Vault] -softdepend: [PlaceholderAPI, Skript, TabooCode, MassiveLag] \ No newline at end of file +softdepend: [PlaceholderAPI, Skript, MassiveLag] \ No newline at end of file