This commit is contained in:
坏黑 2018-05-12 16:53:02 +08:00
parent 4cc3ce4fc8
commit 3de2fe5f2a
26 changed files with 425 additions and 215 deletions

View File

@ -1,17 +1,21 @@
package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.bungee.api.ChatColor;
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 org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class TLocale {
@ -73,11 +77,38 @@ public class TLocale {
pluginField.setAccessible(true);
return (JavaPlugin) pluginField.get(callerClass.getClassLoader());
} catch (Exception ignored) {
TLib.getTLib().getLogger().error("无效的语言文件发送形式: &4" + callerClass.getName());
TLocale.Logger.error("LOCALE.CALLER-PLUGIN-NOT-FOUND", callerClass.getName());
}
return (JavaPlugin) Main.getInst();
}
public static final class Translate extends TLocale {
public static boolean isPlaceholderUseDefault() {
return Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false);
}
public static boolean isPlaceholderPluginEnabled() {
return Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null && Bukkit.getPluginManager().getPlugin("PlaceholderAPI").isEnabled();
}
public static String setColored(String args) {
return ChatColor.translateAlternateColorCodes('&', args);
}
public static List<String> setColored(List<String> args) {
return args.stream().map(var -> ChatColor.translateAlternateColorCodes('&', var)).collect(Collectors.toList());
}
public static String setPlaceholders(CommandSender sender, String args) {
return isPlaceholderPluginEnabled() ? sender instanceof Player ? PlaceholderAPI.setPlaceholders((Player) sender, args) : args : args;
}
public static List<String> setPlaceholders(CommandSender sender, List<String> args) {
return isPlaceholderPluginEnabled() ? sender instanceof Player ? PlaceholderAPI.setPlaceholders((Player) sender, args) : args : args;
}
}
public static final class Logger extends TLocale {
public static void info(String path, String... args) {

View File

@ -15,6 +15,8 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -22,9 +24,9 @@ import java.util.stream.Collectors;
@SuppressWarnings("rawtypes")
class TLocaleInstance {
private final Map<String, List<TLocaleSendable>> map = new HashMap<>();
private final Map<String, List<TLocaleSerialize>> map = new ConcurrentHashMap<>();
private final Plugin plugin;
private int updateNodes;
private final AtomicInteger updateNodes = new AtomicInteger();
TLocaleInstance(Plugin plugin) {
this.plugin = plugin;
@ -39,7 +41,7 @@ class TLocaleInstance {
return map.size();
}
public Map<String, List<TLocaleSendable>> getMap() {
public Map<String, List<TLocaleSerialize>> getMap() {
return map;
}
@ -48,16 +50,16 @@ class TLocaleInstance {
}
public int getUpdateNodes() {
return updateNodes;
return updateNodes.get();
}
public void sendTo(String path, CommandSender sender, String... args) {
try {
map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).forEach(sendable -> {
map.getOrDefault(path, ImmutableList.of(TLocaleSerialize.getEmpty(path))).forEach(tSender -> {
if (Bukkit.isPrimaryThread()) {
sendable.sendTo(sender, args);
tSender.sendTo(sender, args);
} else {
Bukkit.getScheduler().runTask(plugin, () -> sendable.sendTo(sender, args));
Bukkit.getScheduler().runTask(plugin, () -> tSender.sendTo(sender, args));
}
});
} catch (Exception | Error e) {
@ -68,35 +70,37 @@ class TLocaleInstance {
}
public String asString(String path, String... args) {
return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asString(args);
return map.getOrDefault(path, ImmutableList.of(TLocaleSerialize.getEmpty(path))).get(0).asString(args);
}
public List<String> asStringList(String path, String... args) {
return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asStringList(args);
return map.getOrDefault(path, ImmutableList.of(TLocaleSerialize.getEmpty(path))).get(0).asStringList(args);
}
public void load(YamlConfiguration configuration) {
updateNodes = 0;
updateNodes.set(0);
configuration.getKeys(true).forEach(s -> {
boolean isCover = false;
Object object = configuration.get(s);
if (object instanceof TLocaleSendable) {
isCover = map.put(s, Collections.singletonList((TLocaleSendable) object)) != null;
if (object instanceof TLocaleSerialize) {
isCover = map.put(s, Collections.singletonList((TLocaleSerialize) object)) != null;
} else if (object instanceof List && !((List) object).isEmpty()) {
isCover = map.put(s, ((List<?>) object).stream().map(TO_SENDABLE).collect(Collectors.toList())) != null;
isCover = map.put(s, ((List<?>) object).stream().map(TO_SERIALIZE).collect(Collectors.toList())) != null;
} else if (!(object instanceof ConfigurationSection)) {
String str = String.valueOf(object);
isCover = map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSendable.getEmpty() : TLocaleText.of(str))) != null;
isCover = map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSerialize.getEmpty() : TLocaleText.of(str))) != null;
}
if (isCover) {
updateNodes++;
updateNodes.getAndIncrement();
}
});
}
private static final Function<Object, TLocaleSendable> TO_SENDABLE = o -> {
if (o instanceof TLocaleSendable) {
return ((TLocaleSendable) o);
private static final Function<Object, TLocaleSerialize> TO_SERIALIZE = o -> {
if (o instanceof TLocaleSerialize) {
return ((TLocaleSerialize) o);
} else if (o instanceof List) {
return TLocaleText.of(((List) o));
} else if (o instanceof String) {
return TLocaleText.of(((String) o));
} else {

View File

@ -112,7 +112,7 @@ public class TLocaleLoader {
}
private static boolean isVersionOutOfDate(YamlConfiguration configuration, YamlConfiguration configurationAtSteam) {
return (configurationAtSteam != null && configurationAtSteam.contains("VERSION") && configuration.contains("VERSION")) && NumberUtils.getDouble(configurationAtSteam.get("VERSION").toString()) > NumberUtils.getDouble(configuration.get("VERSION").toString());
return configurationAtSteam != null && configurationAtSteam.getDouble("VERSION", 0) > configuration.getDouble("VERSION", 0);
}
private static File getLocaleFile(Plugin plugin) {

View File

@ -1,45 +0,0 @@
package com.ilummc.tlib.resources;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
public interface TLocaleSendable {
static TLocaleSendable getEmpty() {
return (sender, args) -> {
// Empty
};
}
static TLocaleSendable getEmpty(String path) {
return new TLocaleSendable() {
@Override
public void sendTo(CommandSender sender, String... args) {
sender.sendMessage("§4<" + path + "§4>");
}
@Override
public String asString(String... args) {
return "§4<" + path + "§4>";
}
@Override
public List<String> asStringList(String... args) {
return Collections.singletonList("§4<" + path + "§4>");
}
};
}
void sendTo(CommandSender sender, String... args);
default String asString(String... args) {
return "";
}
default List<String> asStringList(String... args) {
return Collections.emptyList();
}
}

View File

@ -0,0 +1,37 @@
package com.ilummc.tlib.resources;
import org.bukkit.command.CommandSender;
import java.util.List;
/**
* @Author sky
* @Since 2018-05-12 13:58
*/
public interface TLocaleSender {
/**
* 发送信息
*
* @param sender 发送目标
* @param args 参数
*/
void sendTo(CommandSender sender, String... args);
/**
* 获取文本
*
* @param args 参数
* @return 文本
*/
String asString(String... args);
/**
* 获取文本集合
*
* @param args 参数
* @return 文本集合
*/
List<String> asStringList(String... args);
}

View File

@ -0,0 +1,84 @@
package com.ilummc.tlib.resources;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @Author sky
* @Since 2018-05-12 14:01
*/
public abstract class TLocaleSerialize implements TLocaleSender, ConfigurationSerializable {
public static boolean isPlaceholderEnabled(Map<String, Object> map) {
Object placeholderObject = map.getOrDefault("papi", TLocale.Translate.isPlaceholderUseDefault());
return placeholderObject instanceof Boolean ? (boolean) placeholderObject : placeholderObject instanceof String && "true".equals(placeholderObject);
}
public static String getStringOrDefault(Map<String, Object> map, String path, String def) {
Object var = map.getOrDefault(path, def);
return var instanceof String ? (String) var : def;
}
public static Integer getIntegerOrDefault(Map<String, Object> map, String path, Integer def) {
Object var = map.getOrDefault(path, def);
return var instanceof Integer ? (Integer) var : def;
}
public static Double getDoubleOrDefault(Map<String, Object> map, String path, Double def) {
Object var = map.getOrDefault(path, def);
return var instanceof Double ? (Double) var : def;
}
static TLocaleSerialize getEmpty() {
return new TLocaleSerialize() {
@Override
public void sendTo(CommandSender sender, String... args) {
}
@Override
public Map<String, Object> serialize() {
return null;
}
};
}
static TLocaleSerialize getEmpty(String path) {
return new TLocaleSerialize() {
@Override
public Map<String, Object> serialize() {
return null;
}
@Override
public void sendTo(CommandSender sender, String... args) {
sender.sendMessage("§4<" + path + "§4>");
}
@Override
public String asString(String... args) {
return "§4<" + path + "§4>";
}
@Override
public List<String> asStringList(String... args) {
return Collections.singletonList("§4<" + path + "§4>");
}
};
}
@Override
public String asString(String... args) {
return "";
}
@Override
public List<String> asStringList(String... args) {
return Collections.emptyList();
}
}

View File

@ -3,12 +3,11 @@ package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.nms.ActionBar;
import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
@ -17,7 +16,7 @@ import java.util.Map;
@Immutable
@SerializableAs("ACTION")
public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializable {
public class TLocaleActionBar extends TLocaleSerialize {
private final String text;
private final boolean papi;
@ -29,8 +28,7 @@ public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializa
public static TLocaleActionBar valueOf(Map<String, Object> map) {
String text = ChatColor.translateAlternateColorCodes('&', String.valueOf(map.getOrDefault("text", "Empty Action bar message.")));
boolean papi = (boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false));
return new TLocaleActionBar(text, papi);
return new TLocaleActionBar(text, isPlaceholderEnabled(map));
}
@Override

View File

@ -7,13 +7,11 @@ import com.ilummc.tlib.TLib;
import com.ilummc.tlib.bungee.api.chat.*;
import com.ilummc.tlib.bungee.chat.ComponentSerializer;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocaleSendable;
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.jsonformatter.JSONFormatter;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
@ -25,7 +23,7 @@ import java.util.stream.Collectors;
@ThreadSafe
@SerializableAs("JSON")
public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
public class TLocaleJson extends TLocaleSerialize {
private static final Pattern pattern = Pattern.compile("<([^<>]*)?@([^<>]*)>");
private final List<BaseComponent[]> components;
@ -39,7 +37,6 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
}
public static TLocaleJson valueOf(Map<String, Object> map) {
boolean papi = (boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false));
List<String> textList = getTextList(map.getOrDefault("text", "Empty Node"));
Object argsObj = map.get("args");
if (argsObj instanceof Map) {
@ -61,7 +58,7 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
String node = split.length > 1 ? split[1] : split[0];
if (section.containsKey(node)) {
Map<String, Object> arg = (Map<String, Object>) section.get(node);
text = ChatColor.translateAlternateColorCodes('&', String.valueOf(arg.getOrDefault("text", text)));
text = TLocale.Translate.setColored(String.valueOf(arg.getOrDefault("text", text)));
BaseComponent[] component = TextComponent.fromLegacyText(text);
arg.forEach((key, value) -> {
if ("suggest".equalsIgnoreCase(key)) {
@ -69,7 +66,7 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
} else if ("command".equalsIgnoreCase(key) || "commands".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value))));
} else if ("hover".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', String.valueOf(value))).create())));
Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(TLocale.Translate.setColored(String.valueOf(value))).create())));
}
});
builder.addAll(Arrays.asList(component));
@ -83,16 +80,16 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
}
return builder.toArray(new BaseComponent[0]);
}).collect(Collectors.toList());
return new TLocaleJson(collect, papi, map);
return new TLocaleJson(collect, isPlaceholderEnabled(map), map);
}
return new TLocaleJson(textList.stream().map(TextComponent::fromLegacyText).collect(Collectors.toList()), papi, map);
return new TLocaleJson(textList.stream().map(TextComponent::fromLegacyText).collect(Collectors.toList()), isPlaceholderEnabled(map), map);
}
private static List<String> getTextList(Object textObj) {
if (textObj instanceof List) {
return ((List<?>) textObj).stream().map(Object::toString).map(s -> ChatColor.translateAlternateColorCodes('&', s)).collect(Collectors.toList());
return ((List<?>) textObj).stream().map(Object::toString).map(s -> TLocale.Translate.setColored(s)).collect(Collectors.toList());
} else if (textObj instanceof String) {
return Lists.newArrayList(ChatColor.translateAlternateColorCodes('&', (String) textObj));
return Lists.newArrayList(TLocale.Translate.setColored((String) textObj));
} else {
return Collections.emptyList();
}

View File

@ -1,10 +1,9 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps;
import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.resources.TLocaleSerialize;
import me.skymc.taboolib.sound.SoundPack;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
@ -20,7 +19,7 @@ import java.util.stream.Collectors;
*/
@Immutable
@SerializableAs("ACTION")
public class TLocaleSound implements TLocaleSendable, ConfigurationSerializable {
public class TLocaleSound extends TLocaleSerialize {
private final List<SoundPack> soundPacks;

View File

@ -4,12 +4,11 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import javax.annotation.concurrent.Immutable;
@ -19,7 +18,7 @@ import java.util.stream.Collectors;
@Immutable
@SerializableAs("TEXT")
@SuppressWarnings({"unchecked", "rawtypes"})
public class TLocaleText implements TLocaleSendable, ConfigurationSerializable {
public class TLocaleText extends TLocaleSerialize {
private final Object text;
private final boolean usePlaceholder;
@ -35,64 +34,46 @@ public class TLocaleText implements TLocaleSendable, ConfigurationSerializable {
}
}
private String replaceMsg(CommandSender sender, String s) {
return usePlaceholder ? PlaceholderHook.replace(sender, s) : s;
public static TLocaleText of(String s) {
return new TLocaleText(TLocale.Translate.setColored(s), TLocale.Translate.isPlaceholderUseDefault());
}
public static TLocaleText of(List<String> s) {
return new TLocaleText(TLocale.Translate.setColored(s), TLocale.Translate.isPlaceholderUseDefault());
}
public static TLocaleText valueOf(Map<String, Object> map) {
if (map.containsKey("text")) {
Object object = map.get("text");
Object objPapi = map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false));
boolean papi = objPapi instanceof Boolean ? (boolean) objPapi : objPapi instanceof String && "true".equals(objPapi);
if (object instanceof List) {
return new TLocaleText(((List<String>) object).stream()
.map(s -> ChatColor.translateAlternateColorCodes('&', s))
.collect(Collectors.toList()), papi);
} else if (object instanceof String[]) {
return new TLocaleText(Arrays.stream(((String[]) object))
.map(s -> ChatColor.translateAlternateColorCodes('&', s))
.collect(Collectors.toList()), papi);
if (object instanceof String[]) {
return new TLocaleText(Arrays.stream(((String[]) object)).collect(Collectors.toList()), isPlaceholderEnabled(map));
} else {
return new TLocaleText(ChatColor.translateAlternateColorCodes('&', Objects.toString(object)), papi);
return new TLocaleText(Objects.toString(object), isPlaceholderEnabled(map));
}
}
return new TLocaleText("§cError chat message loaded.", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false));
}
public static TLocaleText of(String s) {
return new TLocaleText(ChatColor.translateAlternateColorCodes('&', s), Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false));
return new TLocaleText("§cError chat message loaded.", TLocale.Translate.isPlaceholderUseDefault());
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (text instanceof String) {
sender.sendMessage(replaceMsg(sender, Strings.replaceWithOrder((String) text, args)));
sender.sendMessage(replaceText(sender, Strings.replaceWithOrder((String) text, args)));
} else if (text instanceof List) {
((List) text).forEach(s -> sender.sendMessage(replaceMsg(sender, Strings.replaceWithOrder(String.valueOf(s), args))));
((List) text).forEach(s -> sender.sendMessage(replaceText(sender, Strings.replaceWithOrder(String.valueOf(s), args))));
}
}
@Override
public String asString(String... args) {
return Strings.replaceWithOrder(objectToString(text), args);
return Strings.replaceWithOrder(TLocale.Translate.setColored(objectToString(text)), args);
}
@Override
public List<String> asStringList(String... args) {
if (text instanceof String) {
return Collections.singletonList(((String) text));
if (text instanceof List) {
return ((List<String>) text).stream().map(x -> "list: " + Strings.replaceWithOrder(TLocale.Translate.setColored(x), args)).collect(Collectors.toList());
} else {
return ((List<String>) text);
}
}
private String objectToString(Object text) {
if (text instanceof String) {
return ((String) text);
} else {
StringJoiner joiner = new StringJoiner("\n");
((List<String>) text).forEach(joiner::add);
return joiner.toString();
return Collections.singletonList(asString(args));
}
}
@ -107,9 +88,20 @@ public class TLocaleText implements TLocaleSendable, ConfigurationSerializable {
@Override
public Map<String, Object> serialize() {
if (usePlaceholder) {
return Maps.newHashMap(ImmutableMap.of("text", text, "papi", true));
return usePlaceholder ? Maps.newHashMap(ImmutableMap.of("text", text, "papi", true)) : Maps.newHashMap(ImmutableMap.of("text", text));
}
private String replaceText(CommandSender sender, String args) {
return usePlaceholder ? TLocale.Translate.setPlaceholders(sender, args) : TLocale.Translate.setColored(args);
}
private String objectToString(Object text) {
if (text instanceof String) {
return ((String) text);
} else {
StringJoiner joiner = new StringJoiner("\n");
((List<String>) text).forEach(joiner::add);
return joiner.toString();
}
return Maps.newHashMap(ImmutableMap.of("text", text));
}
}

View File

@ -1,15 +1,11 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.display.TitleUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
@ -24,7 +20,7 @@ import java.util.Map;
@Immutable
@SerializableAs("TITLE")
public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable {
public class TLocaleTitle extends TLocaleSerialize {
private final String title;
private final String subtitle;
@ -47,12 +43,12 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable
TLocaleTitle title;
try {
title = new TLocaleTitle(
(String) map.getOrDefault("title", ""),
(String) map.getOrDefault("subtitle", ""),
(int) map.getOrDefault("fadein", 10),
(int) map.getOrDefault("fadeout", 10),
(int) map.getOrDefault("stay", 20),
(boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false)));
getStringOrDefault(map, "title", ""),
getStringOrDefault(map, "subtitle", ""),
getIntegerOrDefault(map, "fadein", 10),
getIntegerOrDefault(map, "fadeout", 10),
getIntegerOrDefault(map, "stay", 10),
isPlaceholderEnabled(map));
} catch (Exception e) {
title = new TLocaleTitle("Empty Title message.", e.getMessage(), 10, 20, 10, false);
}
@ -70,7 +66,7 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable
@Override
public String asString(String... args) {
return Strings.replaceWithOrder("TITLE: [title: '" + title + "', subtitle: '" + subtitle + "', fadeIn: " + fadein + ", fadeOut: " + fadeout + "]", args);
return Strings.replaceWithOrder(Strings.replaceWithOrder("TITLE: [title: ''{0}'', subtitle: ''{1}'', fadeIn: {2}, fadeOut: {3}]", title, subtitle, fadein, fadeout), args);
}
@Override
@ -90,7 +86,7 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable
return map;
}
private String replaceText(CommandSender sender, String s) {
return ChatColor.translateAlternateColorCodes('&', usePlaceholder ? PlaceholderHook.replace(sender, s) : s);
private String replaceText(CommandSender sender, String args) {
return usePlaceholder ? TLocale.Translate.setPlaceholders(sender, args) : TLocale.Translate.setColored(args);
}
}

View File

@ -27,4 +27,16 @@ public class Strings {
}
return stringBuilder.toString();
}
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;
}
}

View File

@ -24,6 +24,7 @@ import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.mysql.protect.MySQLConnection;
import me.skymc.taboolib.nms.item.DabItemUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.packet.PacketUtils;
import me.skymc.taboolib.permission.PermissionUtils;
import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.taboolib.sign.SignUtils;
@ -223,12 +224,10 @@ public class Main extends JavaPlugin implements Listener {
TimeCycleManager.load();
// 启动脚本
JavaShell.javaShellSetup();
// 载入语言文件
exampleLanguage2 = new Language2("Language2", this);
// 注册脚本
SkriptHandler.getInst();
// 注册昵称
TagAPI.inst();
// 载入语言文件
exampleLanguage2 = new Language2("Language2", this);
// 启动数据库储存方法
if (getStorageType() == StorageType.SQL) {
@ -253,6 +252,9 @@ public class Main extends JavaPlugin implements Listener {
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
new SupportPlaceholder(getInst(), "taboolib").hook();
}
if (PacketUtils.isProtocolLibEnabled()) {
TagAPI.inst();
}
// 载入 SpecialItem 接口
SpecialItem.getInst().loadItems();
// 载入 TLM 接口

View File

@ -1,8 +1,6 @@
package me.skymc.taboolib.anvil;
import com.ilummc.tlib.util.asm.AsmClassTransformer;
import me.skymc.taboolib.nms.NMSUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
/**

View File

@ -46,7 +46,7 @@ public class AnvilContainerAPI implements Listener {
meta.setDisplayName(str);
item.setItemMeta(meta);
p.getOpenInventory().setItem(0, item);
p.getOpenInventory().getTopInventory().setItem(0, item);
p.playSound(p.getLocation(), Sound.BLOCK_ANVIL_PLACE, 1, 1);
}

View File

@ -106,10 +106,41 @@ public class TabooLibMainCommand extends BaseMainCommand {
return new CommandArgument[0];
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new InfoCommand(sender, args);
}
});
}
@CommandRegister(priority = 3.1)
void infoList() {
registerSubCommand(new BaseSubCommand() {
@Override
public String getLabel() {
return "itemList";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[0];
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new ItemListCommand(sender, args);
}
@Override
public boolean ignoredLabel() {
return false;
}
});
}

View File

@ -19,7 +19,7 @@ public class InfoCommand extends SubCommand {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.INFO.INVALID-ITEM");
} else {
NBTItem nbt = new NBTItem(player.getItemInHand());
TLocale.sendTo(sender, "COMAMNDS.TABOOLIB.INFO.ITEM-INFO",
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.INFO.ITEM-INFO",
player.getItemInHand().getType().name(),
ItemUtils.getCustomName(player.getItemInHand()),
player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability(),

View File

@ -27,12 +27,11 @@ public class TagDeleteCommand extends SubCommand {
return;
}
TagManager.getInst().removeData(player);
TagManager.getInst().unloadData(player);
TagAPI.removePlayerDisplayName(player);
if (sender instanceof Player) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-DELETE", args[1]);
}
}
}

View File

@ -34,13 +34,19 @@ public class ListenerSoundsCommand implements Listener {
SoundLibraryHolder holder = new SoundLibraryHolder(page, search);
Inventory inventory = Bukkit.createInventory(holder, 54, TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.TITLE", String.valueOf(page)));
List<Sound> soundFilter = Arrays.stream(Sound.values()).filter(sound -> search == null || sound.name().contains(search.toUpperCase())).collect(Collectors.toList());
List<String> soundLore = TLocale.asStringList("COMMANDS.TABOOLIB.SOUNDS.MENU.LORE");
int loop = 0;
for (Sound sound : soundFilter) {
if (loop >= (page - 1) * 28) {
if (loop < page * 28) {
int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28));
inventory.setItem(slot, getSoundItem(sound.name()));
ItemStack item = new ItemStack(Material.MAP);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("§f§n" + sound);
meta.setLore(soundLore);
item.setItemMeta(meta);
inventory.setItem(slot, item);
holder.SOUNDS_DATA.put(slot, sound);
} else {
break;
@ -62,15 +68,6 @@ public class ListenerSoundsCommand implements Listener {
player.openInventory(inventory);
}
private static ItemStack getSoundItem(String sound) {
ItemStack item = new ItemStack(Material.MAP);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("§f§n" + sound);
meta.setLore(TLocale.asStringList("COMMANDS.TABOOLIB.SOUNDS.MENU.LORE"));
item.setItemMeta(meta);
return item;
}
@EventHandler
public void inventoryClick(InventoryClickEvent e) {
if (e.getInventory().getHolder() instanceof SoundLibraryHolder) {

View File

@ -1,22 +1,49 @@
package me.skymc.taboolib.display;
import com.ilummc.tlib.nms.ActionBar;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.nms.NMSUtils;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
/**
* @author Bkm016
* @since 2018-04-26
*/
public class ActionUtils {
private static Class<?> Packet = NMSUtils.getNMSClass("Packet");
private static Class<?> ChatComponentText = NMSUtils.getNMSClass("ChatComponentText");
private static Class<?> ChatMessageType = NMSUtils.getNMSClass("ChatMessageType");
private static Class<?> PacketPlayOutChat = NMSUtils.getNMSClass("PacketPlayOutChat");
private static Class<?> IChatBaseComponent = NMSUtils.getNMSClass("IChatBaseComponent");
public static void send(Player player, String action) {
if (player == null) {
return;
}
try {
ActionBar.sendActionBar(player, action);
} catch (Throwable ignored) {
Object ab = ChatComponentText.getConstructor(String.class).newInstance(action);
Constructor<?> ac;
Object abPacket;
if (TabooLib.getVerint() > 11100) {
ac = PacketPlayOutChat.getConstructor(IChatBaseComponent, ChatMessageType);
abPacket = ac.newInstance(ab, ChatMessageType.getMethod("a", Byte.TYPE).invoke(null, (byte) 2));
} else {
ac = PacketPlayOutChat.getConstructor(IChatBaseComponent, Byte.TYPE);
abPacket = ac.newInstance(ab, (byte) 2);
}
sendPacket(player, abPacket);
} catch (Exception ignored) {
}
}
}
private static void sendPacket(Player player, Object packet) {
try {
Object handle = player.getClass().getMethod("getHandle", new Class[0]).invoke(player);
Object playerConnection = handle.getClass().getField("playerConnection").get(handle);
playerConnection.getClass().getMethod("sendPacket", Packet).invoke(playerConnection, packet);
} catch (Exception ignored) {
}
}
}

View File

@ -2,13 +2,31 @@ package me.skymc.taboolib.packet;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import com.google.common.base.Preconditions;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
/**
* @author sky
*/
public class PacketUtils {
public static void checkProtocolLib() {
Preconditions.checkArgument(isProtocolLibEnabled(), "Plugin \"ProtocolLib\" cannot found!");
}
public static boolean isProtocolLibEnabled() {
return Bukkit.getPluginManager().getPlugin("ProtocolLib") != null && Bukkit.getPluginManager().getPlugin("ProtocolLib").isEnabled();
}
public static ProtocolManager getManager() {
return ProtocolLibrary.getProtocolManager();
}
public static void sendPacketEntityStatus(Entity entity, EntityStatus status, Player... players) {
PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA);
packet.getIntegers().write(0, entity.getEntityId());

View File

@ -31,7 +31,7 @@ public class ArrayUtils {
public static String[] removeFirst(String[] args) {
if (args.length <= 1) {
return null;
return new String[0];
}
List<String> list = asList(args);
list.remove(0);

View File

@ -135,6 +135,7 @@ public class TagAPI implements Listener {
AsyncPlayerReceiveNameTagEvent newEvent = new AsyncPlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, getPlayerDisplayName(namedPlayer), UUID.fromString(builtUUID.toString()));
Bukkit.getServer().getPluginManager().callEvent(newEvent);
updatePlayerTag(namedPlayer, newEvent);
return new WrappedGameProfile(newEvent.getUUID(), newEvent.getTag().substring(0, Math.min(newEvent.getTag().length(), 16)));
}
@ -147,4 +148,14 @@ public class TagAPI implements Listener {
public void onQuit(PlayerQuitEvent event) {
entityIdMap.remove(event.getPlayer().getEntityId());
}
private static void updatePlayerTag(Player namedPlayer, AsyncPlayerReceiveNameTagEvent newEvent) {
TagManager.PlayerData playerData = TagManager.getInst().getPlayerData(namedPlayer);
if (playerData.isEmpty()) {
return;
}
TagManager.getInst().unloadData(namedPlayer);
playerData.setName(newEvent.getTag());
TagManager.getInst().uploadData(namedPlayer);
}
}

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.team;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -11,6 +12,7 @@ import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import java.util.HashMap;
import java.util.UUID;
/**
* @author sky
@ -20,7 +22,7 @@ public class TagManager implements Listener {
private static TagManager inst;
private HashMap<String, PlayerData> playerdata = new HashMap<>();
private HashMap<UUID, PlayerData> playerData = new HashMap<>();
private TagManager() {
Bukkit.getPluginManager().registerEvents(this, Main.getInst());
@ -35,8 +37,8 @@ public class TagManager implements Listener {
return inst;
}
public HashMap<String, PlayerData> getPlayerdata() {
return playerdata;
public HashMap<UUID, PlayerData> getPlayerData() {
return playerData;
}
/**
@ -87,52 +89,44 @@ public class TagManager implements Listener {
* @param player 玩家
* @return {@link PlayerData}
*/
private PlayerData getPlayerData(Player player) {
return playerdata.computeIfAbsent(player.getName(), k -> new PlayerData(player.getName()));
public PlayerData getPlayerData(Player player) {
return playerData.computeIfAbsent(player.getUniqueId(), k -> new PlayerData(player));
}
/**
* 删除该玩家的称号数据
* 注销称号数据
*
* @param player
* @param targetPlayer
*/
public void removeData(Player player) {
playerdata.remove(player.getName());
for (Player _player : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = _player.getScoreboard();
if (scoreboard != null) {
Team team = scoreboard.getTeam(player.getName());
if (team != null) {
team.unregister();
}
public void unloadData(Player targetPlayer) {
PlayerData data = getPlayerData(targetPlayer);
for (Player player : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = getScoreboard(player);
Team team = scoreboard.getTeam(data.getName());
if (team != null) {
team.unregister();
}
}
data.reset();
}
/**
* 将该玩家的数据向服务器所有玩家更新
*
* @param player 玩家
* @param targetPlayer 玩家
*/
public void uploadData(Player player) {
PlayerData data = getPlayerData(player);
public void uploadData(Player targetPlayer) {
PlayerData data = getPlayerData(targetPlayer);
String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix();
String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix();
// 如果没有称号数据
if (prefix.isEmpty() && suffix.isEmpty()) {
unloadData(targetPlayer);
return;
}
for (Player _player : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = _player.getScoreboard();
if (scoreboard == null) {
_player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
Team team = scoreboard.getTeam(player.getName());
if (team == null) {
team = scoreboard.registerNewTeam(player.getName());
team.addEntry(player.getName());
}
for (Player player : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = getScoreboard(player);
Team team = getTeam(scoreboard, data);
team.setPrefix(prefix);
team.setSuffix(suffix);
}
@ -141,28 +135,19 @@ public class TagManager implements Listener {
/**
* 下载服务器内的称号数据到该玩家
*
* @param player 玩家
* @param targetPlayer 玩家
*/
public void downloadData(Player player) {
Scoreboard scoreboard = player.getScoreboard();
if (scoreboard == null) {
player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
for (Player _player : Bukkit.getOnlinePlayers()) {
PlayerData data = getPlayerData(_player);
public void downloadData(Player targetPlayer) {
Scoreboard scoreboard = getScoreboard(targetPlayer);
for (Player player : Bukkit.getOnlinePlayers()) {
PlayerData data = getPlayerData(player);
String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix();
String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix();
// 如果没有称号数据
if (prefix.isEmpty() && suffix.isEmpty()) {
continue;
}
Team team = scoreboard.getTeam(_player.getName());
if (team == null) {
team = scoreboard.registerNewTeam(_player.getName());
team.addEntry(_player.getName());
}
Team team = getTeam(scoreboard, data);
team.setPrefix(prefix);
team.setSuffix(suffix);
}
@ -175,25 +160,52 @@ public class TagManager implements Listener {
@EventHandler
public void onQuit(PlayerQuitEvent e) {
removeData(e.getPlayer());
unloadData(e.getPlayer());
}
private Scoreboard getScoreboard(Player player) {
Scoreboard scoreboard = player.getScoreboard();
if (scoreboard == null) {
player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
return scoreboard;
}
private Team getTeam(Scoreboard scoreboard, PlayerData data) {
Team team = scoreboard.getTeam(data.getName());
if (team == null) {
team = scoreboard.registerNewTeam(data.getName());
team.addEntry(data.getName());
}
return team;
}
static class PlayerData {
private UUID uuid;
private String name;
private String prefix;
private String suffix;
public PlayerData(String name) {
this.name = name;
public PlayerData(Player player) {
this.uuid = player.getUniqueId();
this.name = player.getName();
this.prefix = "";
this.suffix = "";
}
public UUID getUuid() {
return uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrefix() {
return prefix;
}
@ -209,5 +221,14 @@ public class TagManager implements Listener {
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public boolean isEmpty() {
return Strings.isEmpty(suffix) && Strings.isEmpty(prefix);
}
public void reset() {
prefix = "";
suffix = "";
}
}
}

View File

@ -161,7 +161,7 @@ public class TLMInvCommand extends SubCommand {
}
// 覆盖背包
moduleInventorySave.pasteInventory(player, args[2], args.length > 4 ? args[3] : "null");
moduleInventorySave.pasteInventory(player, args[2], args.length > 4 ? args[4] : "null");
// 如果是玩家
if (sender instanceof Player) {

View File

@ -32,6 +32,7 @@ CONFIG:
LOCALE:
TITLE-SEND-TO-NON-PLAYER: '该语言类型只能发送给玩家:{0}'
PLUGIN-NOT-FOUND: '无效的语言文件发送形式: &4{0}'
MISC:
FIELD-COPY-FAILED: '拷贝 {0} 对象失败'