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; package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
import com.ilummc.tlib.bungee.api.ChatColor;
import com.ilummc.tlib.inject.TLoggerManager; import com.ilummc.tlib.inject.TLoggerManager;
import com.ilummc.tlib.util.Ref; import com.ilummc.tlib.util.Ref;
import com.ilummc.tlib.util.Strings; import com.ilummc.tlib.util.Strings;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
public class TLocale { public class TLocale {
@ -73,11 +77,38 @@ public class TLocale {
pluginField.setAccessible(true); pluginField.setAccessible(true);
return (JavaPlugin) pluginField.get(callerClass.getClassLoader()); return (JavaPlugin) pluginField.get(callerClass.getClassLoader());
} catch (Exception ignored) { } catch (Exception ignored) {
TLib.getTLib().getLogger().error("无效的语言文件发送形式: &4" + callerClass.getName()); TLocale.Logger.error("LOCALE.CALLER-PLUGIN-NOT-FOUND", callerClass.getName());
} }
return (JavaPlugin) Main.getInst(); 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 final class Logger extends TLocale {
public static void info(String path, String... args) { 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.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -22,9 +24,9 @@ import java.util.stream.Collectors;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
class TLocaleInstance { 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 final Plugin plugin;
private int updateNodes; private final AtomicInteger updateNodes = new AtomicInteger();
TLocaleInstance(Plugin plugin) { TLocaleInstance(Plugin plugin) {
this.plugin = plugin; this.plugin = plugin;
@ -39,7 +41,7 @@ class TLocaleInstance {
return map.size(); return map.size();
} }
public Map<String, List<TLocaleSendable>> getMap() { public Map<String, List<TLocaleSerialize>> getMap() {
return map; return map;
} }
@ -48,16 +50,16 @@ class TLocaleInstance {
} }
public int getUpdateNodes() { public int getUpdateNodes() {
return updateNodes; return updateNodes.get();
} }
public void sendTo(String path, CommandSender sender, String... args) { public void sendTo(String path, CommandSender sender, String... args) {
try { try {
map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).forEach(sendable -> { map.getOrDefault(path, ImmutableList.of(TLocaleSerialize.getEmpty(path))).forEach(tSender -> {
if (Bukkit.isPrimaryThread()) { if (Bukkit.isPrimaryThread()) {
sendable.sendTo(sender, args); tSender.sendTo(sender, args);
} else { } else {
Bukkit.getScheduler().runTask(plugin, () -> sendable.sendTo(sender, args)); Bukkit.getScheduler().runTask(plugin, () -> tSender.sendTo(sender, args));
} }
}); });
} catch (Exception | Error e) { } catch (Exception | Error e) {
@ -68,35 +70,37 @@ class TLocaleInstance {
} }
public String asString(String path, String... args) { 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) { 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) { public void load(YamlConfiguration configuration) {
updateNodes = 0; updateNodes.set(0);
configuration.getKeys(true).forEach(s -> { configuration.getKeys(true).forEach(s -> {
boolean isCover = false; boolean isCover = false;
Object object = configuration.get(s); Object object = configuration.get(s);
if (object instanceof TLocaleSendable) { if (object instanceof TLocaleSerialize) {
isCover = map.put(s, Collections.singletonList((TLocaleSendable) object)) != null; isCover = map.put(s, Collections.singletonList((TLocaleSerialize) object)) != null;
} else if (object instanceof List && !((List) object).isEmpty()) { } 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)) { } else if (!(object instanceof ConfigurationSection)) {
String str = String.valueOf(object); 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) { if (isCover) {
updateNodes++; updateNodes.getAndIncrement();
} }
}); });
} }
private static final Function<Object, TLocaleSendable> TO_SENDABLE = o -> { private static final Function<Object, TLocaleSerialize> TO_SERIALIZE = o -> {
if (o instanceof TLocaleSendable) { if (o instanceof TLocaleSerialize) {
return ((TLocaleSendable) o); return ((TLocaleSerialize) o);
} else if (o instanceof List) {
return TLocaleText.of(((List) o));
} else if (o instanceof String) { } else if (o instanceof String) {
return TLocaleText.of(((String) o)); return TLocaleText.of(((String) o));
} else { } else {

View File

@ -112,7 +112,7 @@ public class TLocaleLoader {
} }
private static boolean isVersionOutOfDate(YamlConfiguration configuration, YamlConfiguration configurationAtSteam) { 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) { 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.google.common.collect.Maps;
import com.ilummc.tlib.compat.PlaceholderHook; import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.nms.ActionBar; 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 com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -17,7 +16,7 @@ import java.util.Map;
@Immutable @Immutable
@SerializableAs("ACTION") @SerializableAs("ACTION")
public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializable { public class TLocaleActionBar extends TLocaleSerialize {
private final String text; private final String text;
private final boolean papi; private final boolean papi;
@ -29,8 +28,7 @@ public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializa
public static TLocaleActionBar valueOf(Map<String, Object> map) { public static TLocaleActionBar valueOf(Map<String, Object> map) {
String text = ChatColor.translateAlternateColorCodes('&', String.valueOf(map.getOrDefault("text", "Empty Action bar message."))); 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, isPlaceholderEnabled(map));
return new TLocaleActionBar(text, papi);
} }
@Override @Override

View File

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

View File

@ -1,10 +1,9 @@
package com.ilummc.tlib.resources.type; package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps; 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 me.skymc.taboolib.sound.SoundPack;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -20,7 +19,7 @@ import java.util.stream.Collectors;
*/ */
@Immutable @Immutable
@SerializableAs("ACTION") @SerializableAs("ACTION")
public class TLocaleSound implements TLocaleSendable, ConfigurationSerializable { public class TLocaleSound extends TLocaleSerialize {
private final List<SoundPack> soundPacks; 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.ImmutableMap;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.ilummc.tlib.compat.PlaceholderHook; 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 com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.configuration.serialization.SerializableAs;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
@ -19,7 +18,7 @@ import java.util.stream.Collectors;
@Immutable @Immutable
@SerializableAs("TEXT") @SerializableAs("TEXT")
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
public class TLocaleText implements TLocaleSendable, ConfigurationSerializable { public class TLocaleText extends TLocaleSerialize {
private final Object text; private final Object text;
private final boolean usePlaceholder; private final boolean usePlaceholder;
@ -35,64 +34,46 @@ public class TLocaleText implements TLocaleSendable, ConfigurationSerializable {
} }
} }
private String replaceMsg(CommandSender sender, String s) { public static TLocaleText of(String s) {
return usePlaceholder ? PlaceholderHook.replace(sender, s) : 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) { public static TLocaleText valueOf(Map<String, Object> map) {
if (map.containsKey("text")) { if (map.containsKey("text")) {
Object object = map.get("text"); Object object = map.get("text");
Object objPapi = map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false)); if (object instanceof String[]) {
boolean papi = objPapi instanceof Boolean ? (boolean) objPapi : objPapi instanceof String && "true".equals(objPapi); return new TLocaleText(Arrays.stream(((String[]) object)).collect(Collectors.toList()), isPlaceholderEnabled(map));
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);
} else { } 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)); return new TLocaleText("§cError chat message loaded.", TLocale.Translate.isPlaceholderUseDefault());
}
public static TLocaleText of(String s) {
return new TLocaleText(ChatColor.translateAlternateColorCodes('&', s), Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false));
} }
@Override @Override
public void sendTo(CommandSender sender, String... args) { public void sendTo(CommandSender sender, String... args) {
if (text instanceof String) { 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) { } 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 @Override
public String asString(String... args) { public String asString(String... args) {
return Strings.replaceWithOrder(objectToString(text), args); return Strings.replaceWithOrder(TLocale.Translate.setColored(objectToString(text)), args);
} }
@Override @Override
public List<String> asStringList(String... args) { public List<String> asStringList(String... args) {
if (text instanceof String) { if (text instanceof List) {
return Collections.singletonList(((String) text)); return ((List<String>) text).stream().map(x -> "list: " + Strings.replaceWithOrder(TLocale.Translate.setColored(x), args)).collect(Collectors.toList());
} else { } else {
return ((List<String>) text); return Collections.singletonList(asString(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();
} }
} }
@ -107,9 +88,20 @@ public class TLocaleText implements TLocaleSendable, ConfigurationSerializable {
@Override @Override
public Map<String, Object> serialize() { public Map<String, Object> serialize() {
if (usePlaceholder) { return usePlaceholder ? Maps.newHashMap(ImmutableMap.of("text", text, "papi", true)) : Maps.newHashMap(ImmutableMap.of("text", text));
return Maps.newHashMap(ImmutableMap.of("text", text, "papi", true)); }
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; package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocale; 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 com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.display.TitleUtils; import me.skymc.taboolib.display.TitleUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -24,7 +20,7 @@ import java.util.Map;
@Immutable @Immutable
@SerializableAs("TITLE") @SerializableAs("TITLE")
public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable { public class TLocaleTitle extends TLocaleSerialize {
private final String title; private final String title;
private final String subtitle; private final String subtitle;
@ -47,12 +43,12 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable
TLocaleTitle title; TLocaleTitle title;
try { try {
title = new TLocaleTitle( title = new TLocaleTitle(
(String) map.getOrDefault("title", ""), getStringOrDefault(map, "title", ""),
(String) map.getOrDefault("subtitle", ""), getStringOrDefault(map, "subtitle", ""),
(int) map.getOrDefault("fadein", 10), getIntegerOrDefault(map, "fadein", 10),
(int) map.getOrDefault("fadeout", 10), getIntegerOrDefault(map, "fadeout", 10),
(int) map.getOrDefault("stay", 20), getIntegerOrDefault(map, "stay", 10),
(boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false))); isPlaceholderEnabled(map));
} catch (Exception e) { } catch (Exception e) {
title = new TLocaleTitle("Empty Title message.", e.getMessage(), 10, 20, 10, false); title = new TLocaleTitle("Empty Title message.", e.getMessage(), 10, 20, 10, false);
} }
@ -70,7 +66,7 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable
@Override @Override
public String asString(String... args) { 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 @Override
@ -90,7 +86,7 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable
return map; return map;
} }
private String replaceText(CommandSender sender, String s) { private String replaceText(CommandSender sender, String args) {
return ChatColor.translateAlternateColorCodes('&', usePlaceholder ? PlaceholderHook.replace(sender, s) : s); return usePlaceholder ? TLocale.Translate.setPlaceholders(sender, args) : TLocale.Translate.setColored(args);
} }
} }

View File

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

View File

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

View File

@ -46,7 +46,7 @@ public class AnvilContainerAPI implements Listener {
meta.setDisplayName(str); meta.setDisplayName(str);
item.setItemMeta(meta); item.setItemMeta(meta);
p.getOpenInventory().setItem(0, item); p.getOpenInventory().getTopInventory().setItem(0, item);
p.playSound(p.getLocation(), Sound.BLOCK_ANVIL_PLACE, 1, 1); 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]; 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 @Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new ItemListCommand(sender, 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"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.INFO.INVALID-ITEM");
} else { } else {
NBTItem nbt = new NBTItem(player.getItemInHand()); 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(), player.getItemInHand().getType().name(),
ItemUtils.getCustomName(player.getItemInHand()), ItemUtils.getCustomName(player.getItemInHand()),
player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability(), player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability(),

View File

@ -27,12 +27,11 @@ public class TagDeleteCommand extends SubCommand {
return; return;
} }
TagManager.getInst().removeData(player); TagManager.getInst().unloadData(player);
TagAPI.removePlayerDisplayName(player); TagAPI.removePlayerDisplayName(player);
if (sender instanceof Player) { if (sender instanceof Player) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-DELETE", args[1]); 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); SoundLibraryHolder holder = new SoundLibraryHolder(page, search);
Inventory inventory = Bukkit.createInventory(holder, 54, TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.TITLE", String.valueOf(page))); 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<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; int loop = 0;
for (Sound sound : soundFilter) { for (Sound sound : soundFilter) {
if (loop >= (page - 1) * 28) { if (loop >= (page - 1) * 28) {
if (loop < page * 28) { if (loop < page * 28) {
int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 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); holder.SOUNDS_DATA.put(slot, sound);
} else { } else {
break; break;
@ -62,15 +68,6 @@ public class ListenerSoundsCommand implements Listener {
player.openInventory(inventory); 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 @EventHandler
public void inventoryClick(InventoryClickEvent e) { public void inventoryClick(InventoryClickEvent e) {
if (e.getInventory().getHolder() instanceof SoundLibraryHolder) { if (e.getInventory().getHolder() instanceof SoundLibraryHolder) {

View File

@ -1,22 +1,49 @@
package me.skymc.taboolib.display; 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 org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
/** /**
* @author Bkm016 * @author Bkm016
* @since 2018-04-26 * @since 2018-04-26
*/ */
public class ActionUtils { 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) { public static void send(Player player, String action) {
if (player == null) { if (player == null) {
return; return;
} }
try { try {
ActionBar.sendActionBar(player, action); Object ab = ChatComponentText.getConstructor(String.class).newInstance(action);
} catch (Throwable ignored) { 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.PacketType;
import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher; 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.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
/**
* @author sky
*/
public class PacketUtils { 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) { public static void sendPacketEntityStatus(Entity entity, EntityStatus status, Player... players) {
PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA);
packet.getIntegers().write(0, entity.getEntityId()); packet.getIntegers().write(0, entity.getEntityId());

View File

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

View File

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