把部分硬编码语言文件抽取到新的语言系统

This commit is contained in:
Izzel_Aliz 2018-04-28 22:56:16 +08:00
parent 20fcb3dfa0
commit 250d168c2e
24 changed files with 434 additions and 325 deletions

View File

@ -1,9 +1,11 @@
<component name="ProjectDictionaryState"> <component name="ProjectDictionaryState">
<dictionary name="csh20"> <dictionary name="csh20">
<words> <words>
<w>autoload</w>
<w>mvdw</w> <w>mvdw</w>
<w>papi</w> <w>papi</w>
<w>sendable</w> <w>sendable</w>
<w>tlib</w>
<w>unserialize</w> <w>unserialize</w>
<w>unserializer</w> <w>unserializer</w>
<w>yaml</w> <w>yaml</w>

View File

@ -8,6 +8,9 @@
<artifactId>TabooLib</artifactId> <artifactId>TabooLib</artifactId>
<version>3.832</version> <version>3.832</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build> <build>
<defaultGoal>clean install package</defaultGoal> <defaultGoal>clean install package</defaultGoal>
<resources> <resources>
@ -42,6 +45,7 @@
<artifactSet> <artifactSet>
<includes> <includes>
<include>com.ilummc.eagletdl</include> <include>com.ilummc.eagletdl</include>
<include>org.ow2.asm</include>
</includes> </includes>
</artifactSet> </artifactSet>
<createDependencyReducedPom>false</createDependencyReducedPom> <createDependencyReducedPom>false</createDependencyReducedPom>

View File

@ -1,11 +1,5 @@
package com.ilummc.tlib; package com.ilummc.tlib;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import org.bukkit.Bukkit;
import com.ilummc.tlib.annotations.Dependency; import com.ilummc.tlib.annotations.Dependency;
import com.ilummc.tlib.compat.PlaceholderHook; import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.config.TLibConfig; import com.ilummc.tlib.config.TLibConfig;
@ -14,21 +8,29 @@ import com.ilummc.tlib.inject.TConfigWatcher;
import com.ilummc.tlib.inject.TDependencyInjector; import com.ilummc.tlib.inject.TDependencyInjector;
import com.ilummc.tlib.inject.TPluginManager; import com.ilummc.tlib.inject.TPluginManager;
import com.ilummc.tlib.logger.TLogger; import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader; import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.IO;
import lombok.Getter; import lombok.Getter;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.ow2.asm:asm:6.1.1") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.ow2.asm:asm:6.1.1")
@Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0") @Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25")
public class TLib { public class TLib {
@Getter @Getter
private static TLib tLib; private static TLib tLib;
@Getter @Getter
private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE); private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE);
@Getter @Getter
@ -36,7 +38,7 @@ public class TLib {
@Getter @Getter
private TConfigWatcher configWatcher = new TConfigWatcher(); private TConfigWatcher configWatcher = new TConfigWatcher();
@Getter @Getter
private File libsFolder; private File libsFolder;
@ -44,33 +46,33 @@ public class TLib {
private YamlConfiguration internalLang; private YamlConfiguration internalLang;
private TLib() { private TLib() {
libsFolder = new File(Main.getInst().getDataFolder(), "/libs"); libsFolder = new File(Main.getInst().getDataFolder(), "/libs");
if (!libsFolder.exists()) { if (!libsFolder.exists()) {
libsFolder.mkdirs(); libsFolder.mkdirs();
} }
internalLang = YamlConfiguration.loadConfiguration(new InputStreamReader(TLib.class.getResourceAsStream("/internalLang.yml"))); try {
String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/internalLang.yml")), Charset.forName("utf-8"));
internalLang = new YamlConfiguration();
internalLang.loadFromString(yamlText);
} catch (IOException | InvalidConfigurationException ignored) {
}
} }
public static void init() { public static void init() {
tLib = new TLib(); tLib = new TLib();
TLoggerFilter.init(); TLoggerFilter.init();
TLocaleLoader.init(); TLocaleLoader.init();
PlaceholderHook.init(); PlaceholderHook.init();
TLocaleLoader.load(Main.getInst(), false);
TDependencyInjector.inject(Main.getInst(), tLib); TDependencyInjector.inject(Main.getInst(), tLib);
if (Bukkit.getPluginManager() instanceof TPluginManager) {
tLib.getLogger().info("注入成功");
} else {
tLib.getLogger().fatal("注入失败");
}
} }
public static void unload() { public static void unload() {
tLib.getConfigWatcher().unregisterAll(); tLib.getConfigWatcher().unregisterAll();
TDependencyInjector.eject(Main.getInst(), tLib); TDependencyInjector.eject(Main.getInst(), tLib);
} }
public static void injectPluginManager() { public static void injectPluginManager() {
try { try {
Field field = Bukkit.getServer().getClass().getDeclaredField("pluginManager"); Field field = Bukkit.getServer().getClass().getDeclaredField("pluginManager");
@ -78,5 +80,10 @@ public class TLib {
field.set(Bukkit.getServer(), new TPluginManager()); field.set(Bukkit.getServer(), new TPluginManager());
} catch (NoSuchFieldException | IllegalAccessException ignored) { } catch (NoSuchFieldException | IllegalAccessException ignored) {
} }
if (Bukkit.getPluginManager() instanceof TPluginManager) {
TLocale.Logger.info("TLIB.INJECTION-SUCCESS");
} else {
TLocale.Logger.fatal("TLIB.INJECTION-FAILED");
}
} }
} }

View File

@ -9,12 +9,6 @@ import com.ilummc.tlib.annotations.Config;
@Config(name = "tlib.yml", listenChanges = true, readOnly = false) @Config(name = "tlib.yml", listenChanges = true, readOnly = false)
public class TLibConfig { public class TLibConfig {
private String[] locale = {"zh_CN", "en_US"};
public String[] getLocale() {
return locale;
}
private boolean enablePlaceholderHookByDefault = false; private boolean enablePlaceholderHookByDefault = false;
public boolean isEnablePlaceholderHookByDefault() { public boolean isEnablePlaceholderHookByDefault() {

View File

@ -1,14 +1,13 @@
package com.ilummc.tlib.dependency; package com.ilummc.tlib.dependency;
import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;
import com.ilummc.eagletdl.EagletTask; import com.ilummc.eagletdl.EagletTask;
import com.ilummc.eagletdl.ProgressEvent; import com.ilummc.eagletdl.ProgressEvent;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;
public class TDependency { public class TDependency {
public static final String MAVEN_REPO = "http://repo.maven.apache.org/maven2"; public static final String MAVEN_REPO = "http://repo.maven.apache.org/maven2";
@ -54,7 +53,7 @@ public class TDependency {
private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) { private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) {
if (Main.getInst().getConfig().getBoolean("OFFLINE-MODE")) { if (Main.getInst().getConfig().getBoolean("OFFLINE-MODE")) {
TLib.getTLib().getLogger().warn("已启用离线模式, 将不会下载第三方依赖库"); TLocale.Logger.warn("DEPENDENCY.OFFLINE-DEPENDENCY-WARN");
return false; return false;
} }
AtomicBoolean failed = new AtomicBoolean(false); AtomicBoolean failed = new AtomicBoolean(false);
@ -63,22 +62,26 @@ public class TDependency {
.url(link) .url(link)
.file(target) .file(target)
.setThreads(getDownloadPoolSize()) .setThreads(getDownloadPoolSize())
.setOnError(event -> {}) .setOnError(event -> {
.setOnConnected(event -> TLib.getTLib().getLogger().info(" 正在下载 " + String.join(":", new String[]{groupId, artifactId, version}) + " 大小 " + ProgressEvent.format(event.getContentLength()))) })
.setOnProgress(event -> TLib.getTLib().getLogger().info(" 下载速度 " + event.getSpeedFormatted() + " 进度 " + event.getPercentageFormatted())) .setOnConnected(event -> TLocale.Logger.info("DEPENDENCY.DOWNLOAD-CONNECTED",
String.join(":", new String[]{groupId, artifactId, version}), ProgressEvent.format(event.getContentLength())))
.setOnProgress(event -> TLocale.Logger.info("DEPENDENCY.DOWNLOAD-PROGRESS",
event.getSpeedFormatted(), event.getPercentageFormatted()))
.setOnComplete(event -> { .setOnComplete(event -> {
if (event.isSuccess()) { if (event.isSuccess()) {
TLib.getTLib().getLogger().info(" 下载 " + String.join(":", new String[]{groupId, artifactId, version}) + " 完成"); TLocale.Logger.info("DEPENDENCY.DOWNLOAD-SUCCESS",
String.join(":", new String[]{groupId, artifactId, version}));
} else { } else {
failed.set(true); failed.set(true);
TLib.getTLib().getLogger().error(" 下载 " + String.join(":", new String[]{groupId, artifactId, version}) + " 失败"); TLocale.Logger.error("DEPENDENCY.DOWNLOAD-FAILED",
TLib.getTLib().getLogger().error(" 请手动下载 " + link + " 并重命名为 " + target.getName() + " 后放在 /TabooLib/libs 文件夹内"); String.join(":", new String[]{groupId, artifactId, version}), link, target.getName());
} }
}).start().waitUntil(); }).start().waitUntil();
return !failed.get(); return !failed.get();
} }
private static int getDownloadPoolSize() { private static int getDownloadPoolSize() {
return Main.getInst().getConfig().contains("DOWNLOAD-POOL-SIZE") ? Main.getInst().getConfig().getInt("DOWNLOAD-POOL-SIZE") : 4; return Main.getInst().getConfig().getInt("DOWNLOAD-POOL-SIZE", 4);
} }
} }

View File

@ -1,8 +1,8 @@
package com.ilummc.tlib.inject; package com.ilummc.tlib.inject;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.annotations.Config; import com.ilummc.tlib.annotations.Config;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.ConfigUtils;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -59,9 +59,9 @@ public class TConfigInjector {
if (!config.readOnly()) saveConfig(plugin, obj); if (!config.readOnly()) saveConfig(plugin, obj);
return obj; return obj;
} catch (NullPointerException e) { } catch (NullPointerException e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解"); TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName());
} catch (Exception e) { } catch (Exception e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败"); TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName());
} }
return null; return null;
} }
@ -75,13 +75,13 @@ public class TConfigInjector {
ConfigUtils.yamlToMap( ConfigUtils.yamlToMap(
Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz); Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz);
} catch (NullPointerException e) { } catch (NullPointerException e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解或文件不存在"); TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-FILE", plugin.toString(), clazz.getSimpleName());
return null; return null;
} catch (Exception e) { } catch (Exception e) {
try { try {
return clazz.newInstance(); return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e1) { } catch (InstantiationException | IllegalAccessException e1) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败"); TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName());
return null; return null;
} }
} }
@ -93,9 +93,9 @@ public class TConfigInjector {
Validate.notNull(config); Validate.notNull(config);
return ConfigUtils.objToConf(object).getValues(false); return ConfigUtils.objToConf(object).getValues(false);
} catch (NullPointerException e) { } catch (NullPointerException e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败:没有 @Config 注解"); TLocale.Logger.warn("CONFIG.SAVE-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName());
} catch (Exception e) { } catch (Exception e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败"); TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), object.getClass().getSimpleName());
} }
return null; return null;
} }

View File

@ -1,22 +1,18 @@
package com.ilummc.tlib.inject; package com.ilummc.tlib.inject;
import java.io.File; import com.ilummc.tlib.TLib;
import java.lang.reflect.Field; import com.ilummc.tlib.annotations.*;
import com.ilummc.tlib.dependency.TDependency;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.Ref;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import com.ilummc.tlib.TLib; import java.io.File;
import com.ilummc.tlib.annotations.Config; import java.lang.reflect.Field;
import com.ilummc.tlib.annotations.Dependencies;
import com.ilummc.tlib.annotations.Dependency;
import com.ilummc.tlib.annotations.Logger;
import com.ilummc.tlib.annotations.PluginInstance;
import com.ilummc.tlib.dependency.TDependency;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.Ref;
public class TDependencyInjector { public class TDependencyInjector {
@ -50,9 +46,9 @@ public class TDependencyInjector {
try { try {
field.setAccessible(true); field.setAccessible(true);
TConfigInjector.saveConfig(plugin, field.get(o)); TConfigInjector.saveConfig(plugin, field.get(o));
TLib.getTLib().getLogger().info("插件 " + plugin + " 的配置 " + config.name() + " 已保存"); TLocale.Logger.info("CONFIG.SAVE-SUCCESS", plugin.toString(), config.name());
} catch (Exception e) { } catch (Exception e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置 " + config.name() + " 保存失败"); TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), config.name());
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -67,10 +63,10 @@ public class TDependencyInjector {
field.setAccessible(true); field.setAccessible(true);
Object obj = TConfigInjector.loadConfig(plugin, field.getType()); Object obj = TConfigInjector.loadConfig(plugin, field.getType());
if (obj != null) { if (obj != null) {
TLib.getTLib().getLogger().info("插件 " + plugin.getName() + "" + config.name() + " 配置文件成功加载"); TLocale.Logger.info("CONFIG.LOAD-SUCCESS", plugin.toString(), config.name());
field.set(o, obj); field.set(o, obj);
if (config.listenChanges()) { if (config.listenChanges()) {
TLib.getTLib().getLogger().info("开始监听插件 " + plugin.getName() + "" + config.name() + " 配置文件"); TLocale.Logger.info("CONFIG.LISTEN-START", plugin.toString(), config.name());
TLib.getTLib().getConfigWatcher().addOnListen( TLib.getTLib().getConfigWatcher().addOnListen(
new File(plugin.getDataFolder(), config.name()), new File(plugin.getDataFolder(), config.name()),
obj, obj,
@ -81,9 +77,9 @@ public class TDependencyInjector {
f.setAccessible(true); f.setAccessible(true);
f.set(obj, f.get(newObj)); f.set(obj, f.get(newObj));
} }
TLib.getTLib().getLogger().info("插件 " + plugin.getName() + "" + config.name() + " 配置文件成功重载"); TLocale.Logger.info("CONFIG.RELOAD-SUCCESS", plugin.toString(), config.name());
} catch (Exception ignored) { } catch (Exception ignored) {
TLib.getTLib().getLogger().warn("插件 " + plugin.getName() + "" + config.name() + " 配置文件重载时发生错误"); TLocale.Logger.warn("CONFIG.RELOAD-FAIL", plugin.toString(), config.name());
} }
} }
); );
@ -105,6 +101,7 @@ public class TDependencyInjector {
if (!field.isAccessible()) if (!field.isAccessible())
field.setAccessible(true); field.setAccessible(true);
field.set(o, tLogger); field.set(o, tLogger);
TLoggerManager.setDefaultLogger(plugin, tLogger);
} }
} catch (Exception ignored2) { } catch (Exception ignored2) {
} }
@ -122,7 +119,7 @@ public class TDependencyInjector {
Plugin pl; Plugin pl;
if ((pl = Bukkit.getPluginManager().getPlugin(instance.value())) == null) { if ((pl = Bukkit.getPluginManager().getPlugin(instance.value())) == null) {
if (!TDependency.requestPlugin(instance.value())) { if (!TDependency.requestPlugin(instance.value())) {
TLib.getTLib().getLogger().warn(plugin.getName() + " 所需的依赖插件 " + instance.value() + " 自动加载失败"); TLocale.Logger.warn("PLUGIN-AUTOLOAD-FAIL", plugin.getName(), instance.value());
return; return;
} else { } else {
pl = Bukkit.getPluginManager().getPlugin(instance.value()); pl = Bukkit.getPluginManager().getPlugin(instance.value());
@ -149,24 +146,24 @@ public class TDependencyInjector {
} }
} }
if (dependencies.length != 0) { if (dependencies.length != 0) {
TLib.getTLib().getLogger().info("正在加载 " + plugin.getName() + " 插件所需的依赖"); TLocale.Logger.info("DEPENDENCY.LOADING-START", plugin.getName());
for (Dependency dependency : dependencies) { for (Dependency dependency : dependencies) {
if (dependency.type() == Dependency.Type.PLUGIN) { if (dependency.type() == Dependency.Type.PLUGIN) {
if (TDependency.requestPlugin(dependency.plugin())) { if (TDependency.requestPlugin(dependency.plugin())) {
TLib.getTLib().getLogger().info(" " + plugin.getName() + " 请求的插件 " + dependency.plugin() + " 加载成功。"); TLocale.Logger.info("DEPENDENCY.PLUGIN-LOAD-SUCCESS", plugin.getName(), dependency.plugin());
} else { } else {
TLib.getTLib().getLogger().warn(" " + plugin.getName() + " 请求的插件 " + dependency.plugin() + " 加载失败。"); TLocale.Logger.warn("DEPENDENCY.PLUGIN-LOAD-FAIL", plugin.getName(), dependency.plugin());
} }
} }
if (dependency.type() == Dependency.Type.LIBRARY) { if (dependency.type() == Dependency.Type.LIBRARY) {
if (TDependency.requestLib(dependency.maven(), dependency.mavenRepo(), dependency.url())) { if (TDependency.requestLib(dependency.maven(), dependency.mavenRepo(), dependency.url())) {
TLib.getTLib().getLogger().info(" " + plugin.getName() + " 请求的库文件 " + String.join(":", dependency.maven()) + " 加载成功。"); TLocale.Logger.info("DEPENDENCY.LIBRARY-LOAD-SUCCESS", plugin.getName(), String.join(":", dependency.maven()));
} else { } else {
TLib.getTLib().getLogger().warn(" " + plugin.getName() + " 请求的库文件 " + String.join(":", dependency.maven()) + " 加载失败。"); TLocale.Logger.warn("DEPENDENCY.LIBRARY-LOAD-FAIL", plugin.getName(), String.join(":", dependency.maven()));
} }
} }
} }
TLib.getTLib().getLogger().info("依赖加载完成"); TLocale.Logger.info("DEPENDENCY.LOAD-COMPLETE");
} }
} }

View File

@ -0,0 +1,25 @@
package com.ilummc.tlib.inject;
import com.ilummc.tlib.logger.TLogger;
import org.bukkit.plugin.Plugin;
import java.util.HashMap;
import java.util.Map;
public class TLoggerManager {
private static final Map<Plugin, TLogger> map = new HashMap<>();
public static void setDefaultLogger(Plugin plugin, TLogger logger) {
map.put(plugin, logger);
}
public static TLogger getLogger(Plugin plugin) {
TLogger logger = map.get(plugin);
if (logger == null) {
logger = TLogger.getUnformatted(plugin);
map.put(plugin, logger);
}
return logger;
}
}

View File

@ -1,15 +1,7 @@
package com.ilummc.tlib.inject; package com.ilummc.tlib.inject;
import java.io.File; import com.ilummc.tlib.resources.TLocale;
import java.lang.reflect.Field; import me.skymc.taboolib.Main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.SimpleCommandMap; import org.bukkit.command.SimpleCommandMap;
@ -18,17 +10,12 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.permissions.Permissible; import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.Permission; import org.bukkit.permissions.Permission;
import org.bukkit.plugin.EventExecutor; import org.bukkit.plugin.*;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.UnknownDependencyException;
import com.ilummc.tlib.TLib; import java.io.File;
import java.lang.reflect.Field;
import me.skymc.taboolib.Main; import java.util.*;
import java.util.regex.Pattern;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class TPluginManager implements PluginManager { public class TPluginManager implements PluginManager {
@ -68,14 +55,14 @@ public class TPluginManager implements PluginManager {
Field bukkitField = instance.getClass().getDeclaredField(bukkitName); Field bukkitField = instance.getClass().getDeclaredField(bukkitName);
Field thisFiled = this.getClass().getDeclaredField(bukkitName); Field thisFiled = this.getClass().getDeclaredField(bukkitName);
if (bukkitField == null || thisFiled == null) { if (bukkitField == null || thisFiled == null) {
TLib.getTLib().getLogger().warn("拷贝 " + bukkitName + " 对象失败"); TLocale.Logger.warn("MISC.FIELD-COPY-FAILED", bukkitName);
return; return;
} }
bukkitField.setAccessible(true); bukkitField.setAccessible(true);
thisFiled.setAccessible(true); thisFiled.setAccessible(true);
thisFiled.set(this, bukkitField.get(instance)); thisFiled.set(this, bukkitField.get(instance));
} catch (Exception ignored) { } catch (Exception e) {
TLib.getTLib().getLogger().error("拷贝 " + bukkitName + " 对象出错"); TLocale.Logger.error("MISC.FIELD-COPY-ERROR", bukkitName, e.toString());
} }
} }

View File

@ -1,19 +1,17 @@
package com.ilummc.tlib.logger; package com.ilummc.tlib.logger;
import com.ilummc.tlib.util.Strings;
import lombok.Getter;
import lombok.Setter;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import com.ilummc.tlib.util.Strings;
import lombok.Getter;
import lombok.Setter;
import me.skymc.taboolib.Main;
public class TLogger { public class TLogger {
public static final int VERBOSE = 0, FINEST = 1, FINE = 2, INFO = 3, WARN = 4, ERROR = 5, FATAL = 6; public static final int VERBOSE = 0, FINEST = 1, FINE = 2, INFO = 3, WARN = 4, ERROR = 5, FATAL = 6;
@Getter @Getter
private static TLogger globalLogger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE); private static TLogger globalLogger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE);
@Getter @Getter
@ -64,4 +62,9 @@ public class TLogger {
if (level <= FATAL) if (level <= FATAL)
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§4致命错误", "§4" + ChatColor.translateAlternateColorCodes('&', msg))); Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§4致命错误", "§4" + ChatColor.translateAlternateColorCodes('&', msg)));
} }
public static TLogger getUnformatted(Plugin plugin) {
return new TLogger("§8[§3§l{0}§8][§r{1}§8] §f{2}", plugin, TLogger.FINE);
}
} }

View File

@ -1,7 +1,9 @@
package com.ilummc.tlib.resources; package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
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 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;
@ -9,7 +11,7 @@ import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field; import java.lang.reflect.Field;
public final class TLocale { public class TLocale {
private TLocale() { private TLocale() {
throw new AssertionError(); throw new AssertionError();
@ -30,8 +32,8 @@ public final class TLocale {
TLocaleLoader.sendTo(getCallerPlugin(callerClass), path, sender, args); TLocaleLoader.sendTo(getCallerPlugin(callerClass), path, sender, args);
} }
private static String asString(String path, String[] args, Class<?> callerClass) { static String asString(String path, Class<?> callerClass, String... args) {
return TLocaleLoader.asString(getCallerPlugin(callerClass), path); return TLocaleLoader.asString(getCallerPlugin(callerClass), path, args);
} }
public static void sendToConsole(String path, String... args) { public static void sendToConsole(String path, String... args) {
@ -48,10 +50,10 @@ public final class TLocale {
public static String asString(String path, String... args) { public static String asString(String path, String... args) {
try { try {
return asString(path, args, Ref.getCallerClass(3).get()); return asString(path, Ref.getCallerClass(3).get(), args);
} catch (Exception e) { } catch (Exception e) {
TLib.getTLib().getLogger().error("语言文件获取失败: " + path); TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("FETCH-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error("原因: " + e.getMessage()); TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("LOCALE-ERROR-REASON"), e.getMessage()));
return "§4<" + path + "§4>"; return "§4<" + path + "§4>";
} }
} }
@ -59,4 +61,36 @@ public final class TLocale {
public static void reload() { public static void reload() {
Ref.getCallerClass(3).ifPresent(clazz -> TLocaleLoader.load(getCallerPlugin(clazz), false)); Ref.getCallerClass(3).ifPresent(clazz -> TLocaleLoader.load(getCallerPlugin(clazz), false));
} }
public static final class Logger extends TLocale {
public static void info(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).info(asString(path, clazz, args)));
}
public static void warn(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).warn(asString(path, clazz, args)));
}
public static void error(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).error(asString(path, clazz, args)));
}
public static void fatal(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).fatal(asString(path, clazz, args)));
}
public static void fine(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).fine(asString(path, clazz, args)));
}
public static void finest(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).finest(asString(path, clazz, args)));
}
public static void verbose(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).verbose(asString(path, clazz, args)));
}
}
} }

View File

@ -3,6 +3,7 @@ package com.ilummc.tlib.resources;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
import com.ilummc.tlib.resources.type.TLocaleText; import com.ilummc.tlib.resources.type.TLocaleText;
import com.ilummc.tlib.util.Strings;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
@ -37,30 +38,38 @@ class TLocaleInstance {
} }
}); });
} catch (Exception e) { } catch (Exception e) {
TLib.getTLib().getLogger().error("语言文件发送失败: " + path); TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SEND-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error("原因: " + e.getMessage()); TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("LOCALE-ERROR-REASON"), e.getMessage()));
} }
} }
String asString(String path) { String asString(String path, String... args) {
return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asString(); return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asString(args);
} }
void load(YamlConfiguration configuration) { void load(YamlConfiguration configuration) {
configuration.getKeys(false).forEach(s -> { configuration.getKeys(true).forEach(s -> {
Object object = configuration.get(s); Object object = configuration.get(s);
if (object instanceof ConfigurationSection) { if (object instanceof TLocaleSendable) {
loadRecursively(s, (ConfigurationSection) object);
} else if (object instanceof TLocaleSendable) {
map.put(s, Collections.singletonList((TLocaleSendable) object)); map.put(s, Collections.singletonList((TLocaleSendable) object));
} else if (object instanceof List && !((List) object).isEmpty()) { } else if (object instanceof List && !((List) object).isEmpty()) {
map.put(s, ((List<?>) object).stream().map(TO_SENDABLE).collect(Collectors.toList())); map.put(s, ((List<?>) object).stream().map(TO_SENDABLE).collect(Collectors.toList()));
} else { } else if (!(object instanceof ConfigurationSection)) {
map.put(s, Collections.singletonList(TLocaleText.of(String.valueOf(object)))); String str = String.valueOf(object);
map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSendable.getEmpty() : TLocaleText.of(str)));
} }
}); });
} }
int size() {
return map.size();
}
@Override
public String toString() {
return map.toString();
}
private static final Function<Object, TLocaleSendable> TO_SENDABLE = o -> { private static final Function<Object, TLocaleSendable> TO_SENDABLE = o -> {
if (o instanceof TLocaleSendable) { if (o instanceof TLocaleSendable) {
return ((TLocaleSendable) o); return ((TLocaleSendable) o);
@ -73,19 +82,4 @@ class TLocaleInstance {
private final Map<String, List<TLocaleSendable>> map = new HashMap<>(); private final Map<String, List<TLocaleSendable>> map = new HashMap<>();
private void loadRecursively(String path, ConfigurationSection section) {
section.getKeys(false).forEach(s -> {
Object object = section.get(path + "." + s);
if (object instanceof ConfigurationSection) {
loadRecursively(path + "." + s, (ConfigurationSection) object);
} else if (object instanceof TLocaleSendable) {
map.put(path + "." + s, Collections.singletonList((TLocaleSendable) object));
} else if (object instanceof List && !((List) object).isEmpty()) {
map.put(path + "." + s, ((List<?>) object).stream().map(TO_SENDABLE).collect(Collectors.toList()));
} else {
map.put(path + "." + s, Collections.singletonList(TLocaleText.of(String.valueOf(object))));
}
});
}
} }

View File

@ -6,7 +6,6 @@ import com.ilummc.tlib.resources.type.TLocaleTitle;
import com.ilummc.tlib.util.Strings; import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -14,8 +13,6 @@ import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
@ -35,8 +32,8 @@ public class TLocaleLoader {
} }
} }
static String asString(Plugin plugin, String path) { static String asString(Plugin plugin, String path, String... args) {
return map.get(plugin.getName()).asString(path); return map.get(plugin.getName()).asString(path, args);
} }
public static void init() { public static void init() {
@ -46,11 +43,11 @@ public class TLocaleLoader {
public static void load(Plugin plugin, boolean ignoreLoaded) { public static void load(Plugin plugin, boolean ignoreLoaded) {
try { try {
if ((!ignoreLoaded || !map.containsKey(plugin.getName())) && plugin == Main.getInst() || plugin.getDescription().getDepend().contains("TabooLib") || plugin.getDescription().getSoftDepend().contains("TabooLib")) { if ((!ignoreLoaded || !map.containsKey(plugin.getName())) && (plugin == Main.getInst() || plugin.getDescription().getDepend().contains("TabooLib") || plugin.getDescription().getSoftDepend().contains("TabooLib"))) {
InputStream inputStream = null; InputStream inputStream = null;
File file = null; File file = null;
String lang = null; String lang = null;
for (String s : TLib.getTLib().getConfig().getLocale()) { for (String s : Main.getInst().getConfig().getStringList("LOCALE.PRIORITY")) {
lang = s; lang = s;
file = new File(plugin.getDataFolder(), "/lang/" + s + ".yml"); file = new File(plugin.getDataFolder(), "/lang/" + s + ".yml");
if (file.exists()) { if (file.exists()) {
@ -67,10 +64,10 @@ public class TLocaleLoader {
if (!file.exists()) { if (!file.exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
file.createNewFile(); file.createNewFile();
saveResource(inputStream, file); plugin.saveResource("lang/" + lang + ".yml", true);
} }
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("TRY-LOADING-LANG"), plugin.getName(), lang)); TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("TRY-LOADING-LANG"), plugin.getName(), lang));
synchronized (TLocaleLoader.class) { {
YamlConfiguration configuration = ConfigUtils.loadYaml(plugin, file); YamlConfiguration configuration = ConfigUtils.loadYaml(plugin, file);
TLocaleInstance localeInstance = new TLocaleInstance(plugin); TLocaleInstance localeInstance = new TLocaleInstance(plugin);
localeInstance.load(configuration); localeInstance.load(configuration);
@ -84,19 +81,15 @@ public class TLocaleLoader {
TLocaleInstance localeInstance = new TLocaleInstance(plugin); TLocaleInstance localeInstance = new TLocaleInstance(plugin);
localeInstance.load(configuration); localeInstance.load(configuration);
map.put(plugin.getName(), localeInstance); map.put(plugin.getName(), localeInstance);
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"), plugin.getName(), finalLang)); TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"),
plugin.getName(), finalLang, String.valueOf(localeInstance.size())));
}); });
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"), plugin.getName(), lang)); TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"), plugin.getName(), lang));
} }
} catch (Exception e) { } catch (Exception e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("ERROR-LOADING-LANG"), plugin.getName(), e.toString())); TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("ERROR-LOADING-LANG"),
plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString()));
} }
} }
private static void saveResource(InputStream inputStream, File file) throws IOException {
byte[] data = FileUtils.read(inputStream);
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
fileOutputStream.write(data);
}
}
} }

View File

@ -3,22 +3,35 @@ package com.ilummc.tlib.resources;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
public interface TLocaleSendable { public interface TLocaleSendable {
static TLocaleSendable getEmpty(String path) { static TLocaleSendable getEmpty(String path) {
return new TLocaleSendable() { return new TLocaleSendable() {
@Override @Override
public void sendTo(CommandSender sender, String... args) { public void sendTo(CommandSender sender, String... args) {
sender.sendMessage("§4<" + path + "§4>"); sender.sendMessage("§4<" + path + "§4>");
} }
@Override @Override
public String asString(String... args) { public String asString(String... args) {
return "§4<" + path + "§4>"; return "§4<" + path + "§4>";
} }
}; };
} }
static TLocaleSendable getEmpty() {
return new TLocaleSendable() {
@Override
public void sendTo(CommandSender sender, String... args) {
}
@Override
public String asString(String... args) {
return "";
}
};
}
void sendTo(CommandSender sender, String... args); void sendTo(CommandSender sender, String... args);
String asString(String... args); String asString(String... args);
} }

View File

@ -1,26 +1,20 @@
package com.ilummc.tlib.resources.type; package com.ilummc.tlib.resources.type;
import java.util.Arrays; import com.google.common.collect.ImmutableList;
import java.util.List; import com.google.common.collect.ImmutableMap;
import java.util.Map; import com.google.common.collect.Maps;
import java.util.Objects; import com.ilummc.tlib.compat.PlaceholderHook;
import java.util.stream.Collectors; import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.util.Strings;
import javax.annotation.concurrent.Immutable; import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
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.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.configuration.serialization.SerializableAs;
import com.google.common.collect.ImmutableList; import javax.annotation.concurrent.Immutable;
import com.google.common.collect.ImmutableMap; import java.util.*;
import com.google.common.collect.Maps; import java.util.stream.Collectors;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.util.Strings;
@Immutable @Immutable
@SerializableAs("TEXT") @SerializableAs("TEXT")
@ -35,74 +29,78 @@ public class TLocaleText implements TLocaleSendable, ConfigurationSerializable {
this.usePlaceholder = usePlaceholder; this.usePlaceholder = usePlaceholder;
if (text instanceof String) { if (text instanceof String) {
this.text = text; this.text = text;
} } else if (text instanceof List) {
else if (text instanceof List) {
this.text = ImmutableList.copyOf(((List) text)); this.text = ImmutableList.copyOf(((List) text));
} } else {
else { throw new IllegalArgumentException("Param 'text' can only be an instance of String or List<String>");
throw new IllegalArgumentException("Param 'text' can only be an instance of String or String[] or List<String>");
} }
} }
private String replaceMsg(CommandSender sender, String s) { private String replaceMsg(CommandSender sender, String s) {
return usePlaceholder ? PlaceholderHook.replace(sender, s) : s; return usePlaceholder ? PlaceholderHook.replace(sender, s) : s;
} }
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 && objPapi.equals("true");
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 {
return new TLocaleText(ChatColor.translateAlternateColorCodes('&', Objects.toString(object)), papi);
}
}
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));
}
@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(replaceMsg(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(replaceMsg(sender, Strings.replaceWithOrder(String.valueOf(s), args))));
} }
} }
@Override @Override
public String asString(String... args) { public String asString(String... args) {
return Strings.replaceWithOrder((String) text, args); return Strings.replaceWithOrder(objectToString(text), 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();
}
} }
@Override @Override
public String toString() { public String toString() {
if (text instanceof String[]) { if (text instanceof String[]) {
return Arrays.toString((String[]) text); return Arrays.toString((String[]) text);
} else { } else {
return text.toString(); return text.toString();
} }
} }
@Override @Override
public Map<String, Object> serialize() { public Map<String, Object> serialize() {
if (usePlaceholder) { if (usePlaceholder) {
return Maps.newHashMap(ImmutableMap.of("text", text, "papi", true)); return Maps.newHashMap(ImmutableMap.of("text", text, "papi", true));
} }
return Maps.newHashMap(ImmutableMap.of("text", text)); return Maps.newHashMap(ImmutableMap.of("text", text));
} }
public static TLocaleText valueOf(Map<String, Object> map) {
if (map.containsKey("text")) {
Object object = map.get("text");
Object objPapi = map.getOrDefault("papi", TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault());
boolean papi = objPapi instanceof Boolean ? (boolean) objPapi : objPapi instanceof String && objPapi.equals("true");
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 {
return new TLocaleText(ChatColor.translateAlternateColorCodes('&', Objects.toString(object)), papi);
}
}
return new TLocaleText("§cError chat message loaded.", TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault());
}
public static TLocaleText of(String s) {
return new TLocaleText(ChatColor.translateAlternateColorCodes('&', s), TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault());
}
} }

View File

@ -1,23 +1,21 @@
package com.ilummc.tlib.resources.type; package com.ilummc.tlib.resources.type;
import java.util.HashMap; import com.google.common.collect.Maps;
import java.util.Map; import com.ilummc.tlib.TLib;
import com.ilummc.tlib.compat.PlaceholderHook;
import javax.annotation.concurrent.Immutable; import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.display.TitleUtils;
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.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.google.common.collect.Maps; import javax.annotation.concurrent.Immutable;
import com.ilummc.tlib.TLib; import java.util.HashMap;
import com.ilummc.tlib.compat.PlaceholderHook; import java.util.Map;
import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.display.TitleUtils;
/** /**
* @author Bkm016 * @author Bkm016
@ -27,66 +25,71 @@ import me.skymc.taboolib.display.TitleUtils;
@Immutable @Immutable
@SerializableAs("TITLE") @SerializableAs("TITLE")
public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable { public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable {
private final String title;
private final String subtitle;
private final int fadein;
private final int fadeout;
private final int stay;
private boolean usePlaceholder;
private TLocaleTitle(String title, String subString, int fadein, int fadeout, int stay, boolean usePlaceholder) {
this.title = title;
this.subtitle = subString;
this.fadein = fadein;
this.fadeout = fadeout;
this.stay = stay;
this.usePlaceholder = usePlaceholder;
}
@Override private final String title;
public void sendTo(CommandSender sender, String... args) { private final String subtitle;
if (sender instanceof Player) { private final int fadein;
TitleUtils.sendTitle((Player) sender, replaceText(sender, title), replaceText(sender, subtitle), fadein, stay, fadeout); private final int fadeout;
} else { private final int stay;
TLib.getTLib().getLogger().error("该语言类型只能发送给玩家");
}
}
@Override private boolean usePlaceholder;
public String asString(String... args) {
return Strings.replaceWithOrder(title, args);
}
@Override private TLocaleTitle(String title, String subString, int fadein, int fadeout, int stay, boolean usePlaceholder) {
public Map<String, Object> serialize() { this.title = title;
HashMap<String, Object> map = Maps.newHashMap(); this.subtitle = subString;
map.put("papi", usePlaceholder); this.fadein = fadein;
map.put("title", title); this.fadeout = fadeout;
map.put("subtitle", subtitle); this.stay = stay;
map.put("fadein", fadein); this.usePlaceholder = usePlaceholder;
map.put("fadeout", fadeout); }
map.put("stay", stay);
return map; public static TLocaleTitle valueOf(Map<String, Object> map) {
} TLocaleTitle title;
try {
public static TLocaleTitle valueOf(Map<String, Object> map) {
TLocaleTitle title;
try {
title = new TLocaleTitle( title = new TLocaleTitle(
(String) map.getOrDefault("title", ""), (String) map.getOrDefault("title", ""),
(String) map.getOrDefault("subtitle", ""), (String) map.getOrDefault("subtitle", ""),
(int) map.getOrDefault("fadein", 10), (int) map.getOrDefault("fadein", 10),
(int) map.getOrDefault("fadeout", 10), (int) map.getOrDefault("fadeout", 10),
(int) map.getOrDefault("stay", 20), (int) map.getOrDefault("stay", 20),
(boolean) map.getOrDefault("papi", TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault())); (boolean) map.getOrDefault("papi", TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault()));
} catch (Exception e) { } catch (Exception e) {
title = new TLocaleTitle("§4Load failed!", "§c" + e.getMessage(), 10, 20, 10, false); title = new TLocaleTitle("§4Load failed!", "§c" + e.getMessage(), 10, 20, 10, false);
} }
return title; return title;
} }
@Override
public void sendTo(CommandSender sender, String... args) {
if (sender instanceof Player) {
TitleUtils.sendTitle((Player) sender, replaceText(sender, title), replaceText(sender, subtitle), fadein, stay, fadeout);
} else {
TLocale.Logger.error("LOCALE.TITLE-SEND-TO-NON-PLAYER", asString(args));
}
}
@Override
public String asString(String... args) {
return Strings.replaceWithOrder("TITLE: [title: '" + title + "', subtitle: '" + subtitle + "', fadeIn: " + fadein + ", fadeOut: " + fadeout + "]", args);
}
@Override
public String toString() {
return asString();
}
@Override
public Map<String, Object> serialize() {
HashMap<String, Object> map = Maps.newHashMap();
map.put("papi", usePlaceholder);
map.put("title", title);
map.put("subtitle", subtitle);
map.put("fadein", fadein);
map.put("fadeout", fadeout);
map.put("stay", stay);
return map;
}
private String replaceText(CommandSender sender, String s) { private String replaceText(CommandSender sender, String s) {
return ChatColor.translateAlternateColorCodes('&', usePlaceholder ? PlaceholderHook.replace(sender, s) : s); return ChatColor.translateAlternateColorCodes('&', usePlaceholder ? PlaceholderHook.replace(sender, s) : s);
} }

View File

@ -22,7 +22,7 @@ public class Ref {
public static final int ACC_SYNTHETIC = 0x1000; public static final int ACC_SYNTHETIC = 0x1000;
public static List<Field> getDeclaredFields(Class<?> clazz) { public static List<Field> getDeclaredFields(Class<?> clazz) {
return getDeclaredFields(clazz, 0, false); return getDeclaredFields(clazz, 0, true);
} }
public static List<Field> getDeclaredFields(String clazz, int excludeModifiers, boolean cache) { public static List<Field> getDeclaredFields(String clazz, int excludeModifiers, boolean cache) {
@ -40,7 +40,6 @@ public class Ref {
if (clazz == TLib.class) if (clazz == TLib.class)
return Arrays.asList(clazz.getDeclaredFields()); return Arrays.asList(clazz.getDeclaredFields());
Class.forName("org.objectweb.asm.ClassVisitor");
List<Field> fields; List<Field> fields;
if ((fields = cachedFields.get(clazz.getName())) != null) return fields; if ((fields = cachedFields.get(clazz.getName())) != null) return fields;
ClassReader classReader = new ClassReader(clazz.getResourceAsStream("/" + clazz.getName().replace('.', '/') + ".class")); ClassReader classReader = new ClassReader(clazz.getResourceAsStream("/" + clazz.getName().replace('.', '/') + ".class"));
@ -55,8 +54,15 @@ public class Ref {
}).filter(Objects::nonNull).collect(Collectors.toList()); }).filter(Objects::nonNull).collect(Collectors.toList());
if (cache) cachedFields.putIfAbsent(clazz.getName(), fields); if (cache) cachedFields.putIfAbsent(clazz.getName(), fields);
return fields; return fields;
} catch (Exception e) { } catch (Exception | Error e) {
return Collections.emptyList(); try {
List<Field> list = Arrays.stream(clazz.getDeclaredFields())
.filter(field -> (field.getModifiers() & excludeModifiers) == 0).collect(Collectors.toList());
cachedFields.putIfAbsent(clazz.getName(), list);
return list;
} catch (Error err) {
return Collections.emptyList();
}
} }
} }

View File

@ -10,7 +10,7 @@ public class Strings {
* @return 替换好的字符串 * @return 替换好的字符串
*/ */
public static String replaceWithOrder(String template, String... args) { public static String replaceWithOrder(String template, String... args) {
if (args.length == 0) return template; if (args.length == 0 || template.length() == 0) return template;
char[] arr = template.toCharArray(); char[] arr = template.toCharArray();
StringBuilder stringBuilder = new StringBuilder(template.length()); StringBuilder stringBuilder = new StringBuilder(template.length());
for (int i = 0; i < arr.length; i++) { for (int i = 0; i < arr.length; i++) {

View File

@ -0,0 +1,4 @@
package com.ilummc.tlib.util.asm;
public class AsmClassTransformer {
}

View File

@ -1,17 +1,6 @@
package me.skymc.taboolib; package me.skymc.taboolib;
import java.io.File;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.skymc.taboolib.anvil.AnvilContainerAPI; import me.skymc.taboolib.anvil.AnvilContainerAPI;
@ -30,11 +19,7 @@ import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.inventory.speciaitem.SpecialItem; import me.skymc.taboolib.inventory.speciaitem.SpecialItem;
import me.skymc.taboolib.javashell.JavaShell; import me.skymc.taboolib.javashell.JavaShell;
import me.skymc.taboolib.listener.ListenerNetWork; import me.skymc.taboolib.listener.*;
import me.skymc.taboolib.listener.ListenerPlayerCommand;
import me.skymc.taboolib.listener.ListenerPlayerJump;
import me.skymc.taboolib.listener.ListenerPlayerQuit;
import me.skymc.taboolib.listener.ListenerPluginDisable;
import me.skymc.taboolib.message.ChatCatcher; import me.skymc.taboolib.message.ChatCatcher;
import me.skymc.taboolib.message.MsgUtils; import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.mysql.protect.MySQLConnection; import me.skymc.taboolib.mysql.protect.MySQLConnection;
@ -54,6 +39,15 @@ import me.skymc.tlm.TLM;
import me.skymc.tlm.command.TLMCommands; import me.skymc.tlm.command.TLMCommands;
import me.skymc.tlm.module.TabooLibraryModule; import me.skymc.tlm.module.TabooLibraryModule;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.util.Random;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class Main extends JavaPlugin implements Listener { public class Main extends JavaPlugin implements Listener {
@ -111,13 +105,12 @@ public class Main extends JavaPlugin implements Listener {
inst = this; inst = this;
disable = false; disable = false;
TLib.injectPluginManager();
// 载入配置 // 载入配置
saveDefaultConfig(); saveDefaultConfig();
// 加载依赖 // 加载依赖
TLib.init(); TLib.init();
TLib.injectPluginManager();
// 载入目录 // 载入目录
setupDataFolder(); setupDataFolder();

View File

@ -1,7 +1,7 @@
package me.skymc.taboolib.fileutils; package me.skymc.taboolib.fileutils;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
import com.ilummc.tlib.util.Ref; import com.ilummc.tlib.util.Ref;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
@ -14,11 +14,10 @@ import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.StringReader; import java.io.StringReader;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
@ -164,15 +163,17 @@ public class ConfigUtils {
} }
public static YamlConfiguration loadYaml(Plugin plugin, File file) { public static YamlConfiguration loadYaml(Plugin plugin, File file) {
YamlConfiguration yaml = new YamlConfiguration(); YamlConfiguration configuration = new YamlConfiguration();
try { try {
yaml = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(file), Charsets.UTF_8)); String yaml = Files.toString(file, Charset.forName("utf-8"));
configuration.loadFromString(yaml);
return configuration;
} catch (Exception e) { } catch (Exception e) {
TLib.getTLib().getLogger().error("配置文件载入失败!"); TLib.getTLib().getLogger().error("配置文件载入失败!");
TLib.getTLib().getLogger().error("插件: &4" + plugin.getName()); TLib.getTLib().getLogger().error("插件: &4" + plugin.getName());
TLib.getTLib().getLogger().error("文件: &4" + file); TLib.getTLib().getLogger().error("文件: &4" + file);
} }
return yaml; return configuration;
} }

View File

@ -24,6 +24,17 @@ OFFLINE-MODE: false
# 下载依赖时启用的线程数 # 下载依赖时启用的线程数
DOWNLOAD-POOL-SIZE: 4 DOWNLOAD-POOL-SIZE: 4
# 语言文件相关设置
LOCALE:
# 加载语言文件的顺序
PRIORITY:
- zh_CN
- en_US
# 默认是否启用语言文件中 PlaceholderAPI 的替换功能
# 关闭可提升性能
# 如果需要开启仍然可以在语言文件中加入 papi: true
USE_PAPI: false
# 是否启用更新检测 # 是否启用更新检测
UPDATE-CHECK: true UPDATE-CHECK: true

View File

@ -1,5 +1,8 @@
LANG-LOAD-FAIL: '语言文件加载失败' LANG-LOAD-FAIL: '语言文件加载失败'
TRY-LOADING-LANG: '插件 {0} 尝试加载 {1} .yml 作为语言文件' TRY-LOADING-LANG: '插件 {0} 尝试加载 {1} .yml 作为语言文件'
SUCCESS-LOADING-LANG: '成功加载 {0} 插件的 {1} 语言文件' SUCCESS-LOADING-LANG: '成功加载 {0} 插件的 {1} 语言文件,共 {2} 条'
ERROR-LOADING-LANG: '加载 {0} 插件的语言文件时发生异常:{1}' ERROR-LOADING-LANG: '加载 {0} 插件的语言文件时发生异常:{1}'
RELOADING-LANG: '正在重新载入 {0} 插件的语言文件' RELOADING-LANG: '正在重新载入 {0} 插件的语言文件'
FETCH-LOCALE-ERROR: '语言文件获取失败:{0}'
SEND-LOCALE-ERROR: '语言文件发送失败:{0}'
LOCALE-ERROR-REASON: '原因:{0}'

View File

@ -0,0 +1,34 @@
TLIB:
INJECTION-SUCCESS: '注入成功'
INJECTION-FAILED: '注入失败'
DEPENDENCY:
OFFLINE-DEPENDENCY-WARN: '已启用离线模式, 将不会下载第三方依赖库'
DOWNLOAD-CONNECTED: ' 正在下载 {0} 大小 {1}'
DOWNLOAD-PROGRESS: ' 下载速度 {0} 进度 {1}'
DOWNLOAD-SUCCESS: ' 下载 {0} 完成'
DOWNLOAD-FAILED:
- ' 下载 {0} 失败'
- ' 请手动下载 {1} 并重命名为 {2} 后放在 /TabooLib/libs 文件夹内'
PLUGIN-AUTOLOAD-FAIL: '{0} 所依赖的插件 {1} 尝试自动加载失败,请尝试手动下载'
PLUGIN-LOAD-SUCCESS: ' {0} 请求的插件 {1} 加载成功'
PLUGIN-LOAD-FAIL: ' {0} 请求的插件 {1} 加载失败'
LOADING-START: '正在加载 {0} 插件所需的依赖'
LIBRARY-LOAD-SUCCESS: ' {0} 请求的库文件 {1} 加载成功'
LIBRARY-LOAD-FAIL: ' {0} 请求的库文件 {1} 加载失败'
LOAD-COMPLETE: '依赖加载完成'
CONFIG:
LOAD-FAIL-NO-ANNOTATION: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解'
LOAD-FAIL: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解'
LOAD-FAIL-NO-FILE: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解或文件不存在'
LOAD-SUCCESS: '插件 {0} 的 {1} 配置文件成功加载'
SAVE-FAIL-NO-ANNOTATION: '插件 {0} 的配置类 {1} 序列化失败:没有 @Config 注解'
SAVE-FAIL: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解'
SAVE-SUCCESS: '插件 {0} 的配置 {1} 已保存'
RELOAD-SUCCESS: '插件 {0} 的配置 {1} 成功重载'
RELOAD-FAIL: '插件 {0} 的配置 {1} 成功重载'
LISTEN-START: '开始监听 {0} 插件的 {1} 配置文件'
LOCALE:
TITLE-SEND-TO-NON-PLAYER: '该语言类型只能发送给玩家:{0}'
MISC:
FIELD-COPY-FAILED: '拷贝 {0} 对象失败'
FIELD-COPY-ERROR: '拷贝 {0} 对象出错:{1}'