, U> userManager;
+public abstract class NightDataPlugin extends NightPlugin {
@Override
protected void loadManagers() {
diff --git a/src/main/java/su/nightexpress/nightcore/NightPlugin.java b/src/main/java/su/nightexpress/nightcore/NightPlugin.java
index b4ca793..0a66023 100644
--- a/src/main/java/su/nightexpress/nightcore/NightPlugin.java
+++ b/src/main/java/su/nightexpress/nightcore/NightPlugin.java
@@ -163,6 +163,7 @@ public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin
this.getCommandManager().shutdown();
this.getLangManager().shutdown();
+ this.details = null; // Reset so it will use default ones on config read.
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/RootCommand.java b/src/main/java/su/nightexpress/nightcore/command/experimental/RootCommand.java
index 7661a12..6ed4218 100644
--- a/src/main/java/su/nightexpress/nightcore/command/experimental/RootCommand.java
+++ b/src/main/java/su/nightexpress/nightcore/command/experimental/RootCommand.java
@@ -65,7 +65,8 @@ public class RootCommand imple
this.node.getName(),
this.node.getAliases(),
this.node.getDescription(),
- this.node.getUsage()
+ this.node.getUsage(),
+ this.node.getPermission()
);
return CommandUtil.register(this.plugin, this.backend);
}
diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/argument/CommandArgument.java b/src/main/java/su/nightexpress/nightcore/command/experimental/argument/CommandArgument.java
index c3c5fa1..67627b6 100644
--- a/src/main/java/su/nightexpress/nightcore/command/experimental/argument/CommandArgument.java
+++ b/src/main/java/su/nightexpress/nightcore/command/experimental/argument/CommandArgument.java
@@ -7,9 +7,10 @@ import su.nightexpress.nightcore.command.experimental.TabContext;
import su.nightexpress.nightcore.command.experimental.builder.ArgumentBuilder;
import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.language.message.LangMessage;
+import su.nightexpress.nightcore.util.Lists;
import su.nightexpress.nightcore.util.Placeholders;
+import su.nightexpress.nightcore.util.text.NightMessage;
-import java.util.Collections;
import java.util.List;
import java.util.function.Function;
@@ -18,6 +19,7 @@ public class CommandArgument {
private final String name;
private final Function parser;
private final boolean required;
+ private final boolean complex;
private final String localized;
private final String permission;
private final Function> samples;
@@ -26,6 +28,7 @@ public class CommandArgument {
public CommandArgument(@NotNull String name,
@NotNull Function parser,
boolean required,
+ boolean complex,
@Nullable String localized,
@Nullable String permission,
@Nullable LangMessage failureMessage,
@@ -33,6 +36,7 @@ public class CommandArgument {
this.name = name.toLowerCase();
this.parser = parser;
this.required = required;
+ this.complex = complex;
this.samples = samples;
this.localized = this.getLocalized(localized);
this.permission = permission;
@@ -56,7 +60,7 @@ public class CommandArgument {
@NotNull
public List getSamples(@NotNull TabContext context) {
- return this.samples == null ? Collections.emptyList() : this.samples.apply(context);
+ return this.samples == null ? Lists.newList(NightMessage.asLegacy(this.getLocalized())) : this.samples.apply(context);
}
@NotNull
@@ -89,6 +93,10 @@ public class CommandArgument {
return required;
}
+ public boolean isComplex() {
+ return complex;
+ }
+
@NotNull
public String getLocalized() {
return this.localized == null ? this.name : this.localized;
diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/builder/ArgumentBuilder.java b/src/main/java/su/nightexpress/nightcore/command/experimental/builder/ArgumentBuilder.java
index b0c65e8..7935a32 100644
--- a/src/main/java/su/nightexpress/nightcore/command/experimental/builder/ArgumentBuilder.java
+++ b/src/main/java/su/nightexpress/nightcore/command/experimental/builder/ArgumentBuilder.java
@@ -14,14 +14,15 @@ import java.util.function.Function;
public class ArgumentBuilder {
- private final String name;
- private final Function parser;
+ protected final String name;
+ protected final Function parser;
- private boolean required;
- private String localized;
- private String permission;
- private Function> samples;
- private LangMessage failureMessage;
+ protected boolean required;
+ protected boolean complex;
+ protected String localized;
+ protected String permission;
+ protected Function> samples;
+ protected LangMessage failureMessage;
public ArgumentBuilder(@NotNull String name, @NotNull Function parser) {
this.name = name;
@@ -39,6 +40,12 @@ public class ArgumentBuilder {
return this;
}
+ @NotNull
+ public ArgumentBuilder complex() {
+ this.complex = true;
+ return this;
+ }
+
@NotNull
public ArgumentBuilder localized(@NotNull LangString localized) {
return this.localized(localized.getString());
@@ -80,6 +87,6 @@ public class ArgumentBuilder {
@NotNull
public CommandArgument build() {
- return new CommandArgument<>(this.name, this.parser, this.required, this.localized, this.permission, this.failureMessage, this.samples);
+ return new CommandArgument<>(this.name, this.parser, this.required, this.complex, this.localized, this.permission, this.failureMessage, this.samples);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/node/DirectNode.java b/src/main/java/su/nightexpress/nightcore/command/experimental/node/DirectNode.java
index 1e84e6e..dfce352 100644
--- a/src/main/java/su/nightexpress/nightcore/command/experimental/node/DirectNode.java
+++ b/src/main/java/su/nightexpress/nightcore/command/experimental/node/DirectNode.java
@@ -4,11 +4,11 @@ import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
-import su.nightexpress.nightcore.command.experimental.argument.CommandArgument;
import su.nightexpress.nightcore.command.experimental.CommandContext;
+import su.nightexpress.nightcore.command.experimental.TabContext;
+import su.nightexpress.nightcore.command.experimental.argument.CommandArgument;
import su.nightexpress.nightcore.command.experimental.argument.ParsedArgument;
import su.nightexpress.nightcore.command.experimental.argument.ParsedArguments;
-import su.nightexpress.nightcore.command.experimental.TabContext;
import su.nightexpress.nightcore.command.experimental.builder.DirectNodeBuilder;
import su.nightexpress.nightcore.command.experimental.flag.CommandFlag;
import su.nightexpress.nightcore.command.experimental.flag.ContentFlag;
@@ -16,6 +16,8 @@ import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.util.Placeholders;
import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
public class DirectNode extends CommandNode implements DirectExecutor {
@@ -68,7 +70,26 @@ public class DirectNode extends CommandNode implements DirectExecutor {
return false;
}
- String arg = args[index++];
+ String arg;
+ // must be last.
+ if (argument.isComplex()) {
+ /*StringBuilder builder = new StringBuilder();
+ for (int textIndex = index; textIndex < args.length; textIndex++) {
+ String text = args[textIndex];
+ if (text.charAt(0) == CommandFlag.PREFIX) break;
+
+ if (!builder.isEmpty()) builder.append(" ");
+ builder.append(text);
+
+ index++;
+ }*/
+ arg = /*builder.toString();*/Stream.of(args).skip(index).collect(Collectors.joining(" "));
+ }
+ else {
+ arg = args[index++];
+ }
+
+ //String
ParsedArgument> parsedArgument = argument.parse(arg);
if (parsedArgument == null) {
return context.sendFailure(argument.getFailureMessage()
@@ -131,6 +152,11 @@ public class DirectNode extends CommandNode implements DirectExecutor {
//System.out.println("index = " + index);
//System.out.println("arguments.size() = " + arguments.size());
if (index >= this.arguments.size()) {
+ if (!this.arguments.isEmpty()) {
+ CommandArgument> latestArgument = this.arguments.get(this.arguments.size() - 1);
+ if (latestArgument.isComplex()) return this.getArgumentSamples(latestArgument, context);
+ }
+
List samples = new ArrayList<>();
this.getFlags().forEach(commandFlag -> {
@@ -147,6 +173,10 @@ public class DirectNode extends CommandNode implements DirectExecutor {
}
CommandArgument> argument = this.arguments.get(index);
+ return this.getArgumentSamples(argument, context);
+ }
+
+ private List getArgumentSamples(@NotNull CommandArgument> argument, @NotNull TabContext context) {
if (!argument.hasPermission(context.getSender())) return Collections.emptyList();
//System.out.println("argument = " + argument);
diff --git a/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java b/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java
index 73bc77a..d3c1d8d 100644
--- a/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java
+++ b/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java
@@ -3,6 +3,7 @@ package su.nightexpress.nightcore.command.impl;
import org.bukkit.command.*;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.command.api.NightPluginCommand;
import su.nightexpress.nightcore.util.text.NightMessage;
@@ -17,8 +18,8 @@ public class WrappedCommand extends Command implements PluginIdentifiableCommand
protected final TabCompleter tabCompleter;
public WrappedCommand(@NotNull Plugin plugin, @NotNull NightPluginCommand command) {
- this(plugin, command, command, command.getAliases(), command.getDescription(), command.getUsage());
- this.setPermission(command.getPermission());
+ this(plugin, command, command, command.getAliases(), command.getDescription(), command.getUsage(), command.getPermission());
+ //this.setPermission(command.getPermission());
}
public WrappedCommand(@NotNull Plugin plugin,
@@ -26,12 +27,13 @@ public class WrappedCommand extends Command implements PluginIdentifiableCommand
@NotNull TabCompleter tabCompleter,
@NotNull String[] aliases,
@NotNull String description,
- @NotNull String usage) {
+ @NotNull String usage,
+ @Nullable String permission) {
/*super(aliases[0], description, usage, Arrays.asList(aliases));
this.plugin = plugin;
this.executor = executor;
this.tabCompleter = tabCompleter;*/
- this(plugin, executor, tabCompleter, aliases[0], aliases, description, usage);
+ this(plugin, executor, tabCompleter, aliases[0], aliases, description, usage, permission);
}
public WrappedCommand(@NotNull Plugin plugin,
@@ -40,11 +42,13 @@ public class WrappedCommand extends Command implements PluginIdentifiableCommand
@NotNull String name,
@NotNull String[] aliases,
@NotNull String description,
- @NotNull String usage) {
+ @NotNull String usage,
+ @Nullable String permission) {
super(name, NightMessage.clean(description), NightMessage.clean(usage), Arrays.asList(aliases));
this.plugin = plugin;
this.executor = executor;
this.tabCompleter = tabCompleter;
+ this.setPermission(permission);
}
@Override
diff --git a/src/main/java/su/nightexpress/nightcore/config/FileConfig.java b/src/main/java/su/nightexpress/nightcore/config/FileConfig.java
index 25538bb..e30029d 100644
--- a/src/main/java/su/nightexpress/nightcore/config/FileConfig.java
+++ b/src/main/java/su/nightexpress/nightcore/config/FileConfig.java
@@ -75,8 +75,7 @@ public class FileConfig extends YamlConfiguration {
File file = new File(plugin.getDataFolder() + filePath);
if (FileUtil.create(file)) {
- try {
- InputStream input = plugin.getClass().getResourceAsStream(filePath);
+ try (InputStream input = plugin.getClass().getResourceAsStream(filePath)) {
if (input != null) FileUtil.copy(input, file);
}
catch (Exception exception) {
@@ -244,7 +243,7 @@ public class FileConfig extends YamlConfiguration {
}
@NotNull
- public String @NotNull [] getStringArray(@NotNull String path, @NotNull String[] def) {
+ public String[] getStringArray(@NotNull String path, @NotNull String[] def) {
String str = this.getString(path);
return str == null ? def : str.split(",");
}
@@ -312,19 +311,20 @@ public class FileConfig extends YamlConfiguration {
public ItemStack getItem(@NotNull String path) {
if (!path.isEmpty() && !path.endsWith(".")) path = path + ".";
- Material material = Material.getMaterial(this.getString(path + "Material", "").toUpperCase());
- if (material == null || material == Material.AIR) return new ItemStack(Material.AIR);
+ Material material = BukkitThing.getMaterial(this.getString(path + "Material", BukkitThing.toString(Material.AIR)));
+ if (material == null || material.isAir()) return new ItemStack(Material.AIR);
ItemStack item = new ItemStack(material);
item.setAmount(this.getInt(path + "Amount", 1));
- String headSkin = this.getString(path + "SkinURL", "");
- if (!headSkin.isEmpty()) {
+ String headSkin = this.getString(path + "SkinURL");
+ if (headSkin != null) {
ItemUtil.setHeadSkin(item, headSkin);
}
else {
String headTexture = this.getString(path + "Head_Texture", "");
if (!headTexture.isEmpty()) {
+ Plugins.CORE.warn("'Head_Texture' itemstack option is deprecated and will be removed soon. Please, use 'SkinURL' option instead.");
ItemUtil.setSkullTexture(item, headTexture);
}
}
@@ -338,17 +338,17 @@ public class FileConfig extends YamlConfiguration {
}
String name = this.getString(path + "Name");
- meta.setDisplayName(name != null ? NightMessage.asLegacy(Colorizer.apply(name)) : null);
- meta.setLore(NightMessage.asLegacy(Colorizer.apply(this.getStringList(path + "Lore"))));
+ meta.setDisplayName(name != null ? NightMessage.asLegacy(name) : null);
+ meta.setLore(NightMessage.asLegacy(this.getStringList(path + "Lore")));
for (String sKey : this.getSection(path + "Enchants")) {
Enchantment enchantment = BukkitThing.getEnchantment(sKey);
if (enchantment == null) continue;
- int eLvl = this.getInt(path + "Enchants." + sKey);
- if (eLvl <= 0) continue;
+ int level = this.getInt(path + "Enchants." + sKey);
+ if (level <= 0) continue;
- meta.addEnchant(enchantment, eLvl, true);
+ meta.addEnchant(enchantment, level, true);
}
int model = this.getInt(path + "Custom_Model_Data");
diff --git a/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java b/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java
index 65502ac..39822d2 100644
--- a/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java
+++ b/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java
@@ -3,6 +3,8 @@ package su.nightexpress.nightcore.config;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
+import su.nightexpress.nightcore.NightDataPlugin;
+import su.nightexpress.nightcore.database.DatabaseConfig;
import su.nightexpress.nightcore.language.LangManager;
import su.nightexpress.nightcore.util.text.tag.Tags;
@@ -15,6 +17,8 @@ public class PluginDetails {
private final String[] commandAliases;
private final String language;
+ private DatabaseConfig databaseConfig;
+
private Class> configClass;
private Class> langClass;
private Class> permissionsClass;
@@ -33,7 +37,7 @@ public class PluginDetails {
@NotNull
public static PluginDetails create(@NotNull String name, @NotNull String[] commandAliases) {
- String prefix = Tags.LIGHT_YELLOW.enclose(Tags.BOLD.enclose(name)) + Tags.DARK_GRAY.enclose(" » ") + Tags.GRAY.getFullName();
+ String prefix = Tags.LIGHT_YELLOW.enclose(Tags.BOLD.enclose(name)) + Tags.DARK_GRAY.enclose(" » ") + Tags.GRAY.getBracketsName();
String language = Locale.getDefault().getLanguage();
return new PluginDetails(name, prefix, commandAliases, language);
@@ -64,7 +68,14 @@ public class PluginDetails {
"[Default is System Locale]")
.read(config);
+ DatabaseConfig dataConfig = null;
+ if (plugin instanceof NightDataPlugin>) {
+ plugin.info("Read database configuration...");
+ dataConfig = DatabaseConfig.read(plugin);
+ }
+
return new PluginDetails(pluginName, pluginPrefix, commandAliases, languageCode)
+ .setDatabaseConfig(dataConfig)
.setConfigClass(defaults.getConfigClass())
.setLangClass(defaults.getLangClass())
.setPermissionsClass(defaults.getPermissionsClass());
@@ -90,6 +101,17 @@ public class PluginDetails {
return language;
}
+ @Nullable
+ public DatabaseConfig getDatabaseConfig() {
+ return databaseConfig;
+ }
+
+ @NotNull
+ public PluginDetails setDatabaseConfig(@Nullable DatabaseConfig databaseConfig) {
+ this.databaseConfig = databaseConfig;
+ return this;
+ }
+
@Nullable
public Class> getConfigClass() {
return configClass;
diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java b/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java
index 0306945..f750178 100644
--- a/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java
+++ b/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java
@@ -2,16 +2,15 @@ package su.nightexpress.nightcore.core;
import su.nightexpress.nightcore.config.ConfigValue;
import su.nightexpress.nightcore.util.Placeholders;
-import su.nightexpress.nightcore.util.text.NightMessage;
+import su.nightexpress.nightcore.util.StringUtil;
+import su.nightexpress.nightcore.util.text.tag.Tags;
import su.nightexpress.nightcore.util.text.tag.impl.ColorTag;
import su.nightexpress.nightcore.util.wrapper.UniFormatter;
import java.awt.*;
import java.math.RoundingMode;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
-import java.util.stream.Collectors;
public class CoreConfig {
@@ -27,7 +26,7 @@ public class CoreConfig {
(cfg, path, id) -> {
try {
Color color = Color.decode(cfg.getString(path + "." + id, "#ffffff"));
- NightMessage.registerTag(new ColorTag(id, color));
+ Tags.registerTag(new ColorTag(id, color));
return color;
}
catch (Exception exception) {
@@ -64,7 +63,7 @@ public class CoreConfig {
public static final ConfigValue USER_CACHE_NAME_AND_UUID = ConfigValue.create("UserData.Cache.Names_And_UUIDs",
true,
"Sets whether or not plugin will cache player names and UUIDs.",
- "This will improve database performance when checking if user exists, but will increase memory usage.",
+ "This will improve database performance when checking if user exists, but will use more memory to store UUIDs and names.",
"[Default is true]");
public static final ConfigValue LEGACY_COLOR_SUPPORT = ConfigValue.create("Engine.Legacy_Color_Support",
@@ -82,9 +81,9 @@ public class CoreConfig {
"[Default is false]");
public static final ConfigValue NUMBER_FORMAT = ConfigValue.create("Engine.Number_Format",
- UniFormatter.of("#,###.##", RoundingMode.HALF_EVEN),
- "Control over how numerical data is formatted and rounded.",
- "Allowed modes: " + Arrays.stream(RoundingMode.values()).map(RoundingMode::name).map(String::toLowerCase).collect(Collectors.joining(", ")),
- "A tutorial can be found here: https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html"
+ UniFormatter.of("#,###.##", RoundingMode.HALF_EVEN),
+ "Control over how numerical data is formatted and rounded.",
+ "Allowed modes: " + StringUtil.inlineEnum(RoundingMode.class, ", "),
+ "A tutorial can be found here: https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html"
);
}
diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreLang.java b/src/main/java/su/nightexpress/nightcore/core/CoreLang.java
index af26645..5331d8c 100644
--- a/src/main/java/su/nightexpress/nightcore/core/CoreLang.java
+++ b/src/main/java/su/nightexpress/nightcore/core/CoreLang.java
@@ -1,6 +1,7 @@
package su.nightexpress.nightcore.core;
import net.md_5.bungee.api.chat.ClickEvent;
+import net.md_5.bungee.api.chat.HoverEvent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.dialog.Dialog;
import su.nightexpress.nightcore.language.entry.LangItem;
@@ -143,9 +144,8 @@ public class CoreLang {
"",
GRAY.enclose("Click " +
CLICK.enclose(
- ClickEvent.Action.RUN_COMMAND,
- HOVER.enclose(GREEN.enclose("[Here]"), GRAY.enclose("Click to cancel")),
- "/" + Dialog.EXIT
+ HOVER.enclose(GREEN.enclose("[Here]"), HoverEvent.Action.SHOW_TEXT, GRAY.enclose("Click to cancel")),
+ ClickEvent.Action.RUN_COMMAND, "/" + Dialog.EXIT
)
+ " to leave input mode."),
"");
diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreManager.java b/src/main/java/su/nightexpress/nightcore/core/CoreManager.java
index fd770d7..f78ff43 100644
--- a/src/main/java/su/nightexpress/nightcore/core/CoreManager.java
+++ b/src/main/java/su/nightexpress/nightcore/core/CoreManager.java
@@ -3,6 +3,7 @@ package su.nightexpress.nightcore.core;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCore;
import su.nightexpress.nightcore.core.listener.CoreListener;
+import su.nightexpress.nightcore.dialog.Dialog;
import su.nightexpress.nightcore.dialog.DialogListener;
import su.nightexpress.nightcore.manager.AbstractManager;
import su.nightexpress.nightcore.menu.MenuListener;
@@ -27,6 +28,9 @@ public class CoreManager extends AbstractManager {
menu.getOptions().setLastAutoRefresh(System.currentTimeMillis());
}
});
+
+ Dialog.checkTimeOut();
+
}).setSecondsInterval(1));
}
diff --git a/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java b/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java
index 0b40795..02b045c 100644
--- a/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java
+++ b/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java
@@ -17,8 +17,6 @@ public class CoreListener extends AbstractListener {
@EventHandler(priority = EventPriority.NORMAL)
public void onServiceRegisterEvent(ServiceRegisterEvent event) {
- //if (!Plugins.hasVault()) return;
-
if (Plugins.isLoaded(Plugins.VAULT)) {
VaultHook.onServiceRegisterEvent(event);
}
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java b/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java
index bcefc2e..2174c1a 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java
@@ -4,6 +4,8 @@ import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
+import su.nightexpress.nightcore.database.connection.MySQLConnector;
+import su.nightexpress.nightcore.database.connection.SQLiteConnector;
import java.sql.Connection;
import java.sql.SQLException;
@@ -11,13 +13,11 @@ import java.sql.SQLException;
public abstract class AbstractConnector {
protected final NightCorePlugin plugin;
- //protected final String url;
protected final HikariConfig config;
protected final HikariDataSource dataSource;
public AbstractConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
this.plugin = plugin;
- //this.url = getURL(config);
this.config = new HikariConfig();
this.config.setJdbcUrl(this.getURL(config));
@@ -28,6 +28,11 @@ public abstract class AbstractConnector {
this.dataSource = new HikariDataSource(this.config);
}
+ @NotNull
+ public static AbstractConnector create(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
+ return config.getStorageType() == DatabaseType.SQLITE ? new SQLiteConnector(plugin, config) : new MySQLConnector(plugin, config);
+ }
+
protected abstract String getURL(@NotNull DatabaseConfig config);
protected abstract void setupConfig(@NotNull DatabaseConfig config);
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java
index 7ae2f4a..0262c87 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java
@@ -5,16 +5,13 @@ import com.google.gson.GsonBuilder;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
-import su.nightexpress.nightcore.database.connection.MySQLConnector;
-import su.nightexpress.nightcore.database.connection.SQLiteConnector;
import su.nightexpress.nightcore.database.serialize.ItemStackSerializer;
import su.nightexpress.nightcore.database.sql.SQLColumn;
import su.nightexpress.nightcore.database.sql.SQLCondition;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import su.nightexpress.nightcore.database.sql.executor.*;
-import su.nightexpress.nightcore.manager.SimpleManager;
-import su.nightexpress.nightcore.util.wrapper.UniTask;
+import su.nightexpress.nightcore.manager.AbstractManager;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -25,57 +22,51 @@ import java.util.List;
import java.util.Optional;
import java.util.function.Function;
-public abstract class AbstractDataHandler extends SimpleManager
{
+public abstract class AbstractDataHandler
extends AbstractManager
{
protected final DatabaseConfig config;
protected final AbstractConnector connector;
protected final Gson gson;
- private UniTask syncTask;
- private UniTask saveTask;
-
public AbstractDataHandler(@NotNull P plugin) {
- this(plugin, DatabaseConfig.read(plugin));
+ this(plugin, getDataConfig(plugin));
}
public AbstractDataHandler(@NotNull P plugin, @NotNull DatabaseConfig config) {
super(plugin);
-
this.config = config;
- if (this.getDatabaseType() == DatabaseType.MYSQL) {
- this.connector = new MySQLConnector(plugin, config);
- }
- else {
- this.connector = new SQLiteConnector(plugin, config);
- }
+ this.connector = AbstractConnector.create(plugin, config);
this.gson = this.registerAdapters(new GsonBuilder().setPrettyPrinting()).create();
}
+ @NotNull
+ protected static DatabaseConfig getDataConfig(@NotNull NightCorePlugin plugin) {
+ DatabaseConfig dataConfig = plugin.getDetails().getDatabaseConfig();
+ if (dataConfig == null) {
+ plugin.warn("The plugin didn't have database configuration. Fixing it now...");
+ dataConfig = DatabaseConfig.read(plugin);
+ }
+ return dataConfig;
+ }
+
@Override
protected void onLoad() {
- if (this.getConfig().getSaveInterval() > 0) {
- this.saveTask = this.plugin.createAsyncTask(this::onSave)
- .setSecondsInterval(this.getConfig().getSaveInterval() * 60)
- .start();
+ if (this.config.getSaveInterval() > 0) {
+ this.addTask(this.plugin.createAsyncTask(this::onSave).setSecondsInterval(this.config.getSaveInterval() * 60));
}
- if (this.getConfig().getSyncInterval() > 0 && this.getDatabaseType() != DatabaseType.SQLITE) {
- this.syncTask = this.plugin.createAsyncTask(this::onSynchronize)
- .setSecondsInterval(this.getConfig().getSyncInterval())
- .start();
+ if (this.config.getSyncInterval() > 0 && this.getDatabaseType() != DatabaseType.SQLITE) {
+ this.addTask(this.plugin.createAsyncTask(this::onSynchronize).setSecondsInterval(this.config.getSyncInterval()));
this.plugin.info("Enabled data synchronization with " + config.getSyncInterval() + " seconds interval.");
}
- if (this.getConfig().isPurgeEnabled() && this.getConfig().getPurgePeriod() > 0) {
+ if (this.config.isPurgeEnabled() && this.config.getPurgePeriod() > 0) {
this.onPurge();
}
}
@Override
protected void onShutdown() {
- if (this.syncTask != null) this.syncTask.stop();
- if (this.saveTask != null) this.saveTask.stop();
- //this.onSynchronize();
this.onSave();
this.getConnector().close();
}
@@ -93,12 +84,12 @@ public abstract class AbstractDataHandler
extends Sim
@NotNull
public DatabaseType getDatabaseType() {
- return this.getConfig().getStorageType();
+ return this.config.getStorageType();
}
@NotNull
public String getTablePrefix() {
- return this.getConfig().getTablePrefix();
+ return this.config.getTablePrefix();
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
index 045a473..265d002 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
@@ -31,7 +31,7 @@ public abstract class AbstractUserDataHandler
, U ex
protected final Set existNames;
public AbstractUserDataHandler(@NotNull P plugin) {
- this(plugin, DatabaseConfig.read(plugin));
+ this(plugin, getDataConfig(plugin));
}
public AbstractUserDataHandler(@NotNull P plugin, @NotNull DatabaseConfig config) {
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
index a3992d4..4f532d1 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
@@ -13,21 +13,25 @@ import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
+import java.util.function.Supplier;
public abstract class AbstractUserManager, U extends DataUser> extends AbstractManager
{
- private final Map loadedById;
+ private final Map loadedById;
private final Map loadedByName;
+ private final Set scheduledSaves;
public AbstractUserManager(@NotNull P plugin) {
super(plugin);
this.loadedById = new ConcurrentHashMap<>();
this.loadedByName = new ConcurrentHashMap<>();
+ this.scheduledSaves = ConcurrentHashMap.newKeySet();
}
@Override
protected void onLoad() {
this.addListener(new UserListener<>(this.plugin));
+ this.addTask(this.plugin.createAsyncTask(this::saveScheduled).setTicksInterval(1));
}
@Override
@@ -35,6 +39,7 @@ public abstract class AbstractUserManager, U extend
this.getLoaded().forEach(this::save);
this.getLoadedByIdMap().clear();
this.getLoadedByNameMap().clear();
+ this.scheduledSaves.clear();
}
@NotNull
@@ -47,6 +52,11 @@ public abstract class AbstractUserManager
, U extend
});
}
+ public void saveScheduled() {
+ this.scheduledSaves.forEach(this::save);
+ this.scheduledSaves.clear();
+ }
+
@NotNull
public final U getUserData(@NotNull Player player) {
UUID uuid = player.getUniqueId();
@@ -109,36 +119,96 @@ public abstract class AbstractUserManager
, U extend
return CompletableFuture.supplyAsync(() -> this.getUserData(uuid));
}
+ /**
+ * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation in async CompletableFuture thread.
+ * @param name Name of a player.
+ */
+ public void manageUser(@NotNull String name, Consumer consumer) {
+ this.manageUser(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer);
+ }
+
+ /**
+ * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation in async CompletableFuture thread.
+ * @param playerId UUID of a player.
+ */
+ public void manageUser(@NotNull UUID playerId, Consumer consumer) {
+ this.manageUser(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer);
+ }
+
+ /**
+ * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation next tick in the main thread.
+ * @param name Name of a player.
+ */
+ public void manageUserSynchronized(@NotNull String name, Consumer consumer) {
+ this.manageUserSynchronized(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer);
+ }
+
+ /**
+ * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation next tick in the main thread.
+ * @param playerId UUID of a player.
+ */
+ public void manageUserSynchronized(@NotNull UUID playerId, Consumer consumer) {
+ this.manageUserSynchronized(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer);
+ }
+
+ private void manageUser(@NotNull Supplier loadedSupplier, @NotNull Supplier> fetchSupplier, @NotNull Consumer consumer) {
+ U user = loadedSupplier.get();
+ if (user != null) {
+ consumer.accept(user);
+ }
+ else fetchSupplier.get().thenAccept(consumer);
+ }
+
+ private void manageUserSynchronized(@NotNull Supplier loadedSupplier, @NotNull Supplier> fetchSupplier, @NotNull Consumer consumer) {
+ this.manageUser(loadedSupplier, fetchSupplier, user -> this.plugin.runTask(task -> consumer.accept(user)));
+ }
+
+ @Deprecated
public void getUserDataAndPerform(@NotNull String name, Consumer consumer) {
- U user = this.getLoaded(name);
+ this.manageUserSynchronized(name, consumer);
+ /*U user = this.getLoaded(name);
if (user != null) {
consumer.accept(user);
}
- else this.getUserDataAsync(name).thenAccept(user2 -> this.plugin.runTask(task -> consumer.accept(user2)));
+ else this.getUserDataAsync(name).thenAccept(user2 -> this.plugin.runTask(task -> consumer.accept(user2)));*/
}
+ @Deprecated
public void getUserDataAndPerform(@NotNull UUID uuid, Consumer consumer) {
- U user = this.getLoaded(uuid);
+ this.manageUserSynchronized(uuid, consumer);
+ /*U user = this.getLoaded(uuid);
if (user != null) {
consumer.accept(user);
}
- else this.getUserDataAsync(uuid).thenAccept(user2 -> this.plugin.runTask(task -> consumer.accept(user2)));
+ else this.getUserDataAsync(uuid).thenAccept(user2 -> this.plugin.runTask(task -> consumer.accept(user2)));*/
}
+ @Deprecated
public void getUserDataAndPerformAsync(@NotNull String name, Consumer consumer) {
- U user = this.getLoaded(name);
+ this.manageUser(name, consumer);
+ /*U user = this.getLoaded(name);
if (user != null) {
consumer.accept(user);
}
- else this.getUserDataAsync(name).thenAccept(consumer);
+ else this.getUserDataAsync(name).thenAccept(consumer);*/
}
+ @Deprecated
public void getUserDataAndPerformAsync(@NotNull UUID uuid, Consumer consumer) {
- U user = this.getLoaded(uuid);
+ this.manageUser(uuid, consumer);
+ /*U user = this.getLoaded(uuid);
if (user != null) {
consumer.accept(user);
}
- else this.getUserDataAsync(uuid).thenAccept(consumer);
+ else this.getUserDataAsync(uuid).thenAccept(consumer);*/
}
public final void unload(@NotNull Player player) {
@@ -158,7 +228,7 @@ public abstract class AbstractUserManager, U extend
user.setName(player.getName());
user.setLastOnline(System.currentTimeMillis());
}
- this.saveAsync(user);
+ this.scheduleSave(user);
this.cacheTemporary(user);
}
@@ -166,8 +236,13 @@ public abstract class AbstractUserManager
, U extend
this.plugin.getData().saveUser(user);
}
+ public void scheduleSave(@NotNull U user) {
+ this.scheduledSaves.add(user);
+ }
+
+ @Deprecated
public void saveAsync(@NotNull U user) {
- this.plugin.runTaskAsync(task -> this.save(user));
+ this.scheduleSave(user);
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java b/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java
index 5073026..bd9aab8 100644
--- a/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java
+++ b/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java
@@ -64,68 +64,72 @@ public class DatabaseConfig {
}
@NotNull
- public static DatabaseConfig read(@NotNull FileConfig cfg, @NotNull String defaultPrefix) {
- //FileConfig cfg = plugin.getConfig();
+ public static DatabaseConfig read(@NotNull FileConfig config, @NotNull String defaultPrefix) {
+ return read(config, defaultPrefix, "data.db");
+ }
+
+ @NotNull
+ public static DatabaseConfig read(@NotNull FileConfig config, @NotNull String defaultPrefix, @NotNull String defFileName) {
String path = "Database.";
DatabaseType databaseType = ConfigValue.create(path + "Type", DatabaseType.class, DatabaseType.SQLITE,
"Sets database type.",
"Available values: " + String.join(",", Stream.of(DatabaseType.values()).map(Enum::name).toList()))
- .read(cfg);
+ .read(config);
int saveInterval = ConfigValue.create(path + "Auto_Save_Interval", 20,
"Sets how often (in minutes) plugin data of online players will be saved to the database.",
"Set to '-1' to disable.")
- .read(cfg);
+ .read(config);
int syncInterval = ConfigValue.create(path + "Sync_Interval", -1,
"Sets how often (in seconds) plugin data will be fetched and loaded from the remote database.",
"Useless for " + DatabaseType.SQLITE.name() + ".",
"Set to '-1' to disable.")
- .read(cfg);
+ .read(config);
String tablePrefix = ConfigValue.create(path + "Table_Prefix", defaultPrefix,
"Custom prefix for plugin tables in database.")
- .read(cfg);
+ .read(config);
String mysqlUser = ConfigValue.create(path + "MySQL.Username", "root",
"Database user name.")
- .read(cfg);
+ .read(config);
String mysqlPassword = ConfigValue.create(path + "MySQL.Password", "root",
"Database password.")
- .read(cfg);
+ .read(config);
String mysqlHost = ConfigValue.create(path + "MySQL.Host", "localhost:3306",
"Database address. Like http://127.0.0.1:3306/")
- .read(cfg);
+ .read(config);
String mysqlBase = ConfigValue.create(path + "MySQL.Database", "minecraft",
"Name of the MySQL database where plugin will create tables.")
- .read(cfg);
+ .read(config);
String urlOptions = ConfigValue.create(path + "MySQL.Options",
"?allowPublicKeyRetrieval=true&useSSL=false",
"Connection options. Do not touch unless you know what you're doing."
- ).read(cfg);
+ ).read(config);
- String sqliteFilename = ConfigValue.create(path + "SQLite.FileName", "data.db",
+ String sqliteFilename = ConfigValue.create(path + "SQLite.FileName", defFileName,
"File name for the SQLite database file.",
"Actually it's a path to the file, so you can use directories here.")
- .read(cfg);
+ .read(config);
path = "Database.Purge.";
boolean purgeEnabled = ConfigValue.create(path + "Enabled", false,
"Enables the purge feature.",
"Purge will remove all records from the plugin tables that are 'old' enough.")
- .read(cfg);
+ .read(config);
int purgePeriod = ConfigValue.create(path + "For_Period", 60,
"Sets maximal 'age' for the database records before they will be purged.",
"This option may have different behavior depends on the plugin.",
"By default it's days of inactivity for the plugin users.")
- .read(cfg);
+ .read(config);
return new DatabaseConfig(
saveInterval, syncInterval,
diff --git a/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java b/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java
index 505d855..4f1a13a 100644
--- a/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java
+++ b/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java
@@ -44,6 +44,6 @@ public class UserListener
, U extends DataUser> exte
@EventHandler(priority = EventPriority.MONITOR)
public void onUserQuit(PlayerQuitEvent event) {
- this.plugin.getUserManager().unload(event.getPlayer());
+ this.userManager.unload(event.getPlayer());
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java
index 6d30178..17d3502 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java
@@ -41,7 +41,7 @@ public final class DeleteQueryExecutor extends SQLExecutor {
@Override
@NotNull
public Void execute(@NotNull AbstractConnector connector) {
- if (this.wheres.isEmpty()) return null;
+ //if (this.wheres.isEmpty()) return null;
String whereCols = this.wheres.stream()
.map(where -> where.getValue().getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
diff --git a/src/main/java/su/nightexpress/nightcore/dialog/Dialog.java b/src/main/java/su/nightexpress/nightcore/dialog/Dialog.java
index 9c50df7..5dc08ef 100644
--- a/src/main/java/su/nightexpress/nightcore/dialog/Dialog.java
+++ b/src/main/java/su/nightexpress/nightcore/dialog/Dialog.java
@@ -7,18 +7,22 @@ import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.menu.api.Menu;
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
-import su.nightexpress.nightcore.util.Colorizer;
+import su.nightexpress.nightcore.util.Placeholders;
+import su.nightexpress.nightcore.util.Players;
import su.nightexpress.nightcore.util.text.NightMessage;
-import su.nightexpress.nightcore.util.text.WrappedMessage;
-import su.nightexpress.nightcore.util.text.tag.Tags;
+import su.nightexpress.nightcore.util.text.TextRoot;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
+import static su.nightexpress.nightcore.util.text.tag.Tags.*;
+
public class Dialog {
private static final Map DIALOG_MAP = new ConcurrentHashMap<>();
+ private static final int DEFAULT_TIMEOUT = 60;
public static final String EXIT = "#exit";
public static final String VALUES = "#values";
@@ -28,11 +32,17 @@ public class Dialog {
private Menu lastMenu;
private List suggestions;
+ private long timeoutDate;
public Dialog(@NotNull Player player, @NotNull DialogHandler handler) {
this.player = player;
this.handler = handler;
this.suggestions = new ArrayList<>();
+ this.setTimeout(DEFAULT_TIMEOUT);
+ }
+
+ public boolean isTimedOut() {
+ return this.timeoutDate > 0 && System.currentTimeMillis() >= this.timeoutDate;
}
@NotNull
@@ -68,6 +78,14 @@ public class Dialog {
return this;
}
+ public long getTimeoutDate() {
+ return timeoutDate;
+ }
+
+ public void setTimeout(int timeout) {
+ this.timeoutDate = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
+ }
+
public void displaySuggestions(boolean autoRun, int page) {
List values = this.getSuggestions();
if (values.isEmpty()) return;
@@ -83,80 +101,83 @@ public class Dialog {
List items = values.stream().skip(skip).limit(perPage).toList();
ClickEvent.Action action = autoRun ? ClickEvent.Action.RUN_COMMAND : ClickEvent.Action.SUGGEST_COMMAND;
- NightMessage.Builder builder = NightMessage.builder();
- builder.append("=".repeat(8) + "[ ", Tags.ORANGE);
- builder.append("Value Helper", Tags.YELLOW);
- builder.append("] " + "=".repeat(8), Tags.ORANGE);
- builder.appendLineBreak();
+ StringBuilder builder = new StringBuilder()
+ .append(ORANGE.enclose("=".repeat(8) + "[ " + YELLOW.enclose("Value Helper") + " ]" + "=".repeat(8)))
+ .append(Placeholders.TAG_LINE_BREAK);
items.forEach(element -> {
- String value = element.charAt(0) == '/' ? element : '/' + element;
- builder.append("> ", Tags.DARK_GRAY);
- builder.append(element, Tags.GREEN)
- .showText(Tags.GRAY.enclose( "Click me to select " + Tags.CYAN.enclose(element) + "."))
- .clickEvent(action, value);
- builder.appendLineBreak();
+ String hoverHint = GRAY.enclose("Click me to select " + CYAN.enclose(element) + ".");
+ String clickCommand = element.charAt(0) == '/' ? element : '/' + element;
+
+ builder.append(DARK_GRAY.enclose("> ")).append(GREEN.enclose(HOVER.encloseHint(CLICK.encloseRun(element, clickCommand), hoverHint)));
+ builder.append(Placeholders.TAG_LINE_BREAK);
});
- builder.append("=".repeat(9) + " ", Tags.ORANGE);
+ builder.append(ORANGE.enclose("=".repeat(9))).append(" ");
if (isFirstPage) {
- builder.append("[<]", Tags.GRAY);
+ builder.append(GRAY.enclose("[<]"));
}
else {
- builder.append("[<]", Tags.LIGHT_RED)
- .showText(Tags.GRAY.enclose("Previous Page"))
- .runCommand("/" + VALUES + " " + (page - 1) + " " + autoRun);
+ builder.append(LIGHT_RED.enclose(HOVER.encloseHint(CLICK.encloseRun("[<]", "/" + VALUES + " " + (page - 1) + " " + autoRun), GRAY.enclose("Previous Page"))));
}
- builder.append(" " + page, Tags.YELLOW);
- builder.append("/", Tags.ORANGE);
- builder.append(pages + " ", Tags.YELLOW);
+ builder.append(YELLOW.enclose(" " + page));
+ builder.append(ORANGE.enclose("/"));
+ builder.append(YELLOW.enclose(pages + " "));
if (isLastPage) {
- builder.append("[>]", Tags.GRAY);
+ builder.append(GRAY.enclose("[>]"));
}
else {
- builder.append("[>]", Tags.LIGHT_RED)
- .showText(Tags.GRAY.enclose("Next Page"))
- .runCommand("/" + VALUES + " " + (page + 1) + " " + autoRun);
+ builder.append(LIGHT_RED.enclose(HOVER.encloseHint(CLICK.encloseRun("[>]", "/" + VALUES + " " + (page + 1) + " " + autoRun), GRAY.enclose("Next Page"))));
+
}
- builder.append(" " + "=".repeat(9), Tags.ORANGE);
- builder.send(this.getPlayer());
+ builder.append(ORANGE.enclose(" " + "=".repeat(9)));
+
+ Players.sendModernMessage(this.player, builder.toString());
}
@Deprecated
public void prompt(@NotNull String text) {
- this.sendInfo(CoreLang.EDITOR_INPUT_HEADER_MAIN.getMessage().toLegacy(), Colorizer.apply(text));
+ this.sendInfo(CoreLang.EDITOR_INPUT_HEADER_MAIN.getMessage().toLegacy(), NightMessage.asLegacy(text));
}
- public void prompt(@NotNull WrappedMessage text) {
+ public void prompt(@NotNull TextRoot text) {
this.info(CoreLang.EDITOR_INPUT_HEADER_MAIN.getMessage(), text);
}
@Deprecated
public void error(@NotNull String text) {
- this.sendInfo(CoreLang.EDITOR_INPUT_HEADER_ERROR.getMessage().toLegacy(), Colorizer.apply(text));
+ this.sendInfo(CoreLang.EDITOR_INPUT_HEADER_ERROR.getMessage().toLegacy(), NightMessage.asLegacy(text));
}
- public void error(@NotNull WrappedMessage text) {
+ public void error(@NotNull TextRoot text) {
this.info(CoreLang.EDITOR_INPUT_HEADER_ERROR.getMessage(), text);
}
- public void info(@NotNull WrappedMessage title, @NotNull WrappedMessage text) {
+ public void info(@NotNull TextRoot title, @NotNull TextRoot text) {
this.sendInfo(title.toLegacy(), text.toLegacy());
}
@Deprecated
public void info(@NotNull String title, @NotNull String text) {
- this.sendInfo(Colorizer.apply(title), Colorizer.apply(text));
+ this.sendInfo(NightMessage.asLegacy(title), NightMessage.asLegacy(text));
}
private void sendInfo(@NotNull String title, @NotNull String text) {
this.getPlayer().sendTitle(title, text, 20, Short.MAX_VALUE, 20);
}
+ public static void checkTimeOut() {
+ new HashSet<>(DIALOG_MAP.values()).forEach(dialog -> {
+ if (dialog.isTimedOut()) {
+ stop(dialog.player);
+ }
+ });
+ }
+
@NotNull
public static Dialog create(@NotNull Player player, @NotNull DialogHandler handler) {
Dialog dialog = new Dialog(player, handler)
diff --git a/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java b/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java
index c0770c7..f7199a3 100644
--- a/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java
+++ b/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java
@@ -9,15 +9,12 @@ import org.bukkit.event.player.PlayerQuitEvent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCore;
import su.nightexpress.nightcore.manager.AbstractListener;
-import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.NumberUtil;
import java.util.HashSet;
public class DialogListener extends AbstractListener {
- // TODO Timeout
-
public DialogListener(@NotNull NightCore plugin) {
super(plugin);
}
@@ -54,7 +51,7 @@ public class DialogListener extends AbstractListener {
event.setCancelled(true);
String raw = event.getMessage();
- String text = Colorizer.apply(raw.substring(1));
+ String text = raw.substring(1);
if (text.startsWith(Dialog.VALUES)) {
String[] split = text.split(" ");
int page = split.length >= 2 ? NumberUtil.getInteger(split[1], 0) : 0;
diff --git a/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java b/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java
index 23acd6c..b2fc097 100644
--- a/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java
+++ b/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java
@@ -3,9 +3,9 @@ package su.nightexpress.nightcore.dialog;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.NumberUtil;
import su.nightexpress.nightcore.util.StringUtil;
+import su.nightexpress.nightcore.util.text.NightMessage;
import su.nightexpress.nightcore.util.wrapper.UniDouble;
import su.nightexpress.nightcore.util.wrapper.UniInt;
@@ -21,8 +21,8 @@ public class WrappedInput {
public WrappedInput(@NotNull String text) {
this.text = text;
- this.textRaw = Colorizer.restrip(text); // TODO Modern formation, but keep colorizer to support legacy codes for other chat format plugins
- this.textColored = Colorizer.apply(text);
+ this.textRaw = NightMessage.stripAll(text);
+ this.textColored = NightMessage.asLegacy(text);
}
public int asInt() {
diff --git a/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java b/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java
index bf3fb7c..b6055ef 100644
--- a/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java
+++ b/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java
@@ -37,8 +37,8 @@ public class VaultHook {
@Nullable
private static T getProvider(@NotNull Class clazz) {
- RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(clazz);
- return rsp == null ? null : rsp.getProvider();
+ RegisteredServiceProvider provider = Bukkit.getServer().getServicesManager().getRegistration(clazz);
+ return provider == null ? null : provider.getProvider();
}
private static void setPermission() {
diff --git a/src/main/java/su/nightexpress/nightcore/language/LangAssets.java b/src/main/java/su/nightexpress/nightcore/language/LangAssets.java
index c03755c..d637555 100644
--- a/src/main/java/su/nightexpress/nightcore/language/LangAssets.java
+++ b/src/main/java/su/nightexpress/nightcore/language/LangAssets.java
@@ -102,7 +102,7 @@ public class LangAssets {
@NotNull
public static Optional getAsset(@NotNull String path) {
- return Optional.ofNullable(config.getString(path)).map(Colorizer::apply);
+ return Optional.ofNullable(config.getString(path));//.map(NightMessage::asLegacy);
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/language/LangManager.java b/src/main/java/su/nightexpress/nightcore/language/LangManager.java
index 44c7543..b5c9603 100644
--- a/src/main/java/su/nightexpress/nightcore/language/LangManager.java
+++ b/src/main/java/su/nightexpress/nightcore/language/LangManager.java
@@ -11,6 +11,7 @@ import su.nightexpress.nightcore.util.Reflex;
import su.nightexpress.nightcore.util.StringUtil;
import java.io.File;
+import java.io.InputStream;
public class LangManager extends SimpleManager {
@@ -41,7 +42,12 @@ public class LangManager extends SimpleManager {
filePath = "/" + filePath;
}
- return plugin.getClass().getResourceAsStream(filePath) != null;
+ try (InputStream inputStream = plugin.getClass().getResourceAsStream(filePath)) {
+ return inputStream != null;
+ }
+ catch (Exception ignored) {}
+
+ return false;
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java
index 03815a6..b0a8c09 100644
--- a/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java
+++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java
@@ -7,7 +7,7 @@ import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.util.ItemUtil;
import su.nightexpress.nightcore.util.Pair;
import su.nightexpress.nightcore.util.text.NightMessage;
-import su.nightexpress.nightcore.util.text.WrappedMessage;
+import su.nightexpress.nightcore.util.text.TextRoot;
import java.util.ArrayList;
import java.util.Arrays;
@@ -23,8 +23,8 @@ public class LangItem extends LangEntry>> {
private String localizedName;
private List localizedLore;
- private WrappedMessage wrappedName;
- private List wrappedLore;
+ private TextRoot wrappedName;
+ private List wrappedLore;
public LangItem(@NotNull String key, @NotNull String defaultName, @NotNull List defaultLore) {
super(key, defaultName);
@@ -62,7 +62,7 @@ public class LangItem extends LangEntry>> {
public void apply(@NotNull ItemStack item) {
ItemUtil.editMeta(item, meta -> {
meta.setDisplayName(this.getWrappedName().toLegacy());
- meta.setLore(this.getWrappedLore().stream().map(WrappedMessage::toLegacy).toList());
+ meta.setLore(this.getWrappedLore().stream().map(TextRoot::toLegacy).toList());
});
}
@@ -98,12 +98,12 @@ public class LangItem extends LangEntry>> {
}
@NotNull
- public WrappedMessage getWrappedName() {
+ public TextRoot getWrappedName() {
return wrappedName;
}
@NotNull
- public List getWrappedLore() {
+ public List getWrappedLore() {
return wrappedLore;
}
diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java
index 16adc86..9213ca7 100644
--- a/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java
+++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java
@@ -4,12 +4,12 @@ import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.util.text.NightMessage;
-import su.nightexpress.nightcore.util.text.WrappedMessage;
+import su.nightexpress.nightcore.util.text.TextRoot;
public class LangString extends LangEntry {
- private String string;
- private WrappedMessage message;
+ private String string;
+ private TextRoot message;
public LangString(@NotNull String path, @NotNull String defaultText) {
super(path, defaultText);
@@ -53,7 +53,7 @@ public class LangString extends LangEntry {
}
@NotNull
- public WrappedMessage getMessage() {
+ public TextRoot getMessage() {
return this.message;
}
diff --git a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java
index fa7193d..2c14b7a 100644
--- a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java
+++ b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java
@@ -1,9 +1,6 @@
package su.nightexpress.nightcore.language.message;
import me.clip.placeholderapi.PlaceholderAPI;
-import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.ComponentBuilder;
-import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Sound;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -11,15 +8,14 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.core.CoreConfig;
-import su.nightexpress.nightcore.language.tag.MessageDecorator;
+import su.nightexpress.nightcore.language.tag.MessageTag;
import su.nightexpress.nightcore.language.tag.MessageTags;
import su.nightexpress.nightcore.util.NumberUtil;
import su.nightexpress.nightcore.util.Placeholders;
import su.nightexpress.nightcore.util.Players;
import su.nightexpress.nightcore.util.StringUtil;
import su.nightexpress.nightcore.util.text.NightMessage;
-import su.nightexpress.nightcore.util.text.WrappedMessage;
-import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
+import su.nightexpress.nightcore.util.text.TextRoot;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
import su.nightexpress.nightcore.util.wrapper.UniSound;
@@ -33,7 +29,7 @@ public class LangMessage {
private final NightCorePlugin plugin;
private final String defaultText;
private final MessageOptions options;
- private final WrappedMessage message;
+ private final TextRoot message;
public LangMessage(@NotNull NightCorePlugin plugin, @NotNull String defaultText, @NotNull MessageOptions options) {
this(plugin, defaultText, options, null);
@@ -44,7 +40,7 @@ public class LangMessage {
this.defaultText = defaultText;
this.options = options;
this.message = NightMessage.from(prefix == null || !options.hasPrefix() ? defaultText : prefix + defaultText);
- if (CoreConfig.MODERN_TEXT_PRECOMPILE_LANG.get()) {
+ if (CoreConfig.MODERN_TEXT_PRECOMPILE_LANG.get() && options.getOutputType() != OutputType.TITLES) {
this.message.compile();
}
}
@@ -117,48 +113,31 @@ public class LangMessage {
Tag:
if (letter == Tag.OPEN_BRACKET && index != (length - 1)) {
- int indexEnd = string.indexOf(Tag.CLOSE_BRACKET, index);
+ int indexEnd = TextRoot.indexOfIgnoreEscaped(string, Tag.CLOSE_BRACKET, index);
if (indexEnd == -1) break Tag;
char next = string.charAt(index + 1);
if (next == Tag.CLOSE_BRACKET) break Tag;
- String leading = string.substring(index + 1);
- String brackets = string.substring(index + 1, indexEnd);
+ String bracketsContent = string.substring(index + 1, indexEnd);
- Tag tag = MessageTags.getTag(brackets);
+ String tagName = bracketsContent;
+ String tagContent = null;
- if (tag == null) {
- for (Tag registered : MessageTags.getTags()) {
- String tagName = registered.getName();
- if (leading.startsWith(tagName)) {
- char latest = leading.charAt(tagName.length());
-
- if (latest == Tag.CLOSE_BRACKET || registered instanceof DynamicTag) {
- tag = registered;
- break;
- }
- }
- }
- }
- if (!(tag instanceof MessageDecorator decorator)) break Tag;
-
- if (tag instanceof DynamicTag) {
- int prefixSize = tag.getName().length() + 1; // 1 for semicolon
-
- String content = StringUtil.parseQuotedContent(leading.substring(prefixSize));
- if (content == null) break Tag;
-
- decorator.apply(options, content);
-
- indexEnd = index + prefixSize + content.length() + 3; // 1 for close bracket, 2 for quotes
- }
- else {
- decorator.apply(options, leading);
+ // Check for content tags
+ int semicolonIndex = bracketsContent.indexOf(':');
+ if (semicolonIndex >= 0) {
+ tagName = bracketsContent.substring(0, semicolonIndex);
+ tagContent = TextRoot.stripQuotesSlash(bracketsContent.substring(semicolonIndex + 1));
}
- index = indexEnd;
- continue;
+ MessageTag tag = MessageTags.getTag(tagName);
+
+ if (tag != null) {
+ tag.apply(options, tagContent);
+ index = indexEnd;
+ continue;
+ }
}
builder.append(letter);
}
@@ -191,12 +170,12 @@ public class LangMessage {
}
@NotNull
- public WrappedMessage getMessage() {
+ public TextRoot getMessage() {
return this.message;
}
@NotNull
- public WrappedMessage getMessage(@NotNull CommandSender sender) {
+ public TextRoot getMessage(@NotNull CommandSender sender) {
if (!this.options.usePlaceholderAPI() || !(sender instanceof Player player)) return this.getMessage();
return this.message.copy().replace(line -> PlaceholderAPI.setPlaceholders(player, line));
@@ -217,8 +196,6 @@ public class LangMessage {
@NotNull
public LangMessage replace(@NotNull String var, @NotNull List replacer) {
- //String delimiter = CoreConfig.MODERN_TEXT_PRECOMPILE_LANG.get() ? "\n" : StandardTags.LINE_BREAK;
-
return this.replace(str -> str.replace(var, String.join(Placeholders.TAG_LINE_BREAK, replacer)));
}
@@ -232,26 +209,6 @@ public class LangMessage {
return copy;
}
- /*@NotNull
- public LangMessage replace(@NotNull Predicate predicate, @NotNull BiConsumer> replacer) {
- if (this.isEmpty()) return this;
-
- LangMessage msgCopy = new LangMessage(this);
- List replaced = new ArrayList<>();
- List text
-
- msgCopy.getText().forEach(line -> {
- if (predicate.test(line)) {
- replacer.accept(line, replaced);
- return;
- }
- replaced.add(line);
- });
- msgCopy.setText(replaced);
-
- return msgCopy;
- }*/
-
public boolean isDisabled() {
return this.options.getOutputType() == OutputType.NONE;
}
@@ -278,23 +235,13 @@ public class LangMessage {
if (sender instanceof Player player) {
if (this.options.getOutputType() == OutputType.ACTION_BAR) {
Players.sendActionBar(player, this.getMessage(player));
- //player.spigot().sendMessage(ChatMessageType.ACTION_BAR, this.getMessage(player).parseIfAbsent());
}
else if (this.options.getOutputType() == OutputType.TITLES) {
- ComponentBuilder titleBuilder = new ComponentBuilder();
- ComponentBuilder subBuilder = new ComponentBuilder();
- ComponentBuilder current = titleBuilder;
+ String[] split = this.getMessage(sender).getString().split(Placeholders.TAG_LINE_BREAK);
- for (BaseComponent component : this.getMessage(player).parseIfAbsent()) {
- if (component instanceof TextComponent textComponent && textComponent.getText().equals("\n")) {
- current = subBuilder;
- continue;
- }
- current.append(component);
- }
+ String title = NightMessage.asLegacy(split[0]);
+ String subtitle = split.length >= 2 ? NightMessage.asLegacy(split[1]) : "";
- String title = TextComponent.toLegacyText(titleBuilder.create());
- String subtitle = TextComponent.toLegacyText(subBuilder.create());
player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/MessageDecorator.java b/src/main/java/su/nightexpress/nightcore/language/tag/MessageDecorator.java
deleted file mode 100644
index edc6627..0000000
--- a/src/main/java/su/nightexpress/nightcore/language/tag/MessageDecorator.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package su.nightexpress.nightcore.language.tag;
-
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.language.message.MessageOptions;
-
-public interface MessageDecorator {
-
- void apply(@NotNull MessageOptions options, @NotNull String value);
-}
diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/MessageTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/MessageTag.java
new file mode 100644
index 0000000..7a12519
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/language/tag/MessageTag.java
@@ -0,0 +1,24 @@
+package su.nightexpress.nightcore.language.tag;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.language.message.MessageOptions;
+import su.nightexpress.nightcore.util.text.tag.api.Tag;
+
+public abstract class MessageTag extends Tag {
+
+ public MessageTag(@NotNull String name) {
+ super(name);
+ }
+
+ public MessageTag(@NotNull String name, @NotNull String[] aliases) {
+ super(name, aliases);
+ }
+
+ @NotNull
+ public String enclose(@NotNull String content) {
+ return brackets(this.getName() + ":\"" + content + "\"");
+ }
+
+ public abstract void apply(@NotNull MessageOptions options, @Nullable String tagContent);
+}
diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/MessageTags.java b/src/main/java/su/nightexpress/nightcore/language/tag/MessageTags.java
index e558142..fa60a58 100644
--- a/src/main/java/su/nightexpress/nightcore/language/tag/MessageTags.java
+++ b/src/main/java/su/nightexpress/nightcore/language/tag/MessageTags.java
@@ -2,10 +2,9 @@ package su.nightexpress.nightcore.language.tag;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.language.tag.impl.NoPrefixTag;
+import su.nightexpress.nightcore.language.tag.impl.OutputTag;
import su.nightexpress.nightcore.language.tag.impl.PlaceholderTag;
import su.nightexpress.nightcore.language.tag.impl.SoundTag;
-import su.nightexpress.nightcore.language.tag.impl.OutputTag;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
import java.util.Collection;
import java.util.HashMap;
@@ -13,7 +12,7 @@ import java.util.Map;
public class MessageTags {
- private static final Map TAG_MAP = new HashMap<>();
+ private static final Map REGISTRY = new HashMap<>();
public static final NoPrefixTag NO_PREFIX = new NoPrefixTag();
public static final OutputTag OUTPUT = new OutputTag();
@@ -24,25 +23,25 @@ public class MessageTags {
registerTags(NO_PREFIX, OUTPUT, SOUND, PLACEHOLDER);
}
- public static void registerTags(@NotNull Tag... tags) {
- for (Tag tag : tags) {
+ public static void registerTags(@NotNull MessageTag... tags) {
+ for (MessageTag tag : tags) {
registerTag(tag);
}
}
- public static void registerTag(@NotNull Tag tag, @NotNull String... aliases) {
- TAG_MAP.put(tag.getName(), tag);
+ public static void registerTag(@NotNull MessageTag tag, @NotNull String... aliases) {
+ REGISTRY.put(tag.getName(), tag);
for (String alias : aliases) {
- TAG_MAP.put(alias, tag);
+ REGISTRY.put(alias, tag);
}
}
@NotNull
- public static Collection getTags() {
- return TAG_MAP.values();
+ public static Collection getTags() {
+ return REGISTRY.values();
}
- public static Tag getTag(@NotNull String name) {
- return TAG_MAP.get(name.toLowerCase());
+ public static MessageTag getTag(@NotNull String name) {
+ return REGISTRY.get(name.toLowerCase());
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/NoPrefixTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/NoPrefixTag.java
index 594b1ee..03958cd 100644
--- a/src/main/java/su/nightexpress/nightcore/language/tag/impl/NoPrefixTag.java
+++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/NoPrefixTag.java
@@ -1,23 +1,18 @@
package su.nightexpress.nightcore.language.tag.impl;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.language.message.MessageOptions;
-import su.nightexpress.nightcore.language.tag.MessageDecorator;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
+import su.nightexpress.nightcore.language.tag.MessageTag;
-public class NoPrefixTag extends Tag implements MessageDecorator {
+public class NoPrefixTag extends MessageTag {
public NoPrefixTag() {
super("noprefix");
}
@Override
- public int getWeight() {
- return 0;
- }
-
- @Override
- public void apply(@NotNull MessageOptions options, @NotNull String value) {
+ public void apply(@NotNull MessageOptions options, @Nullable String tagContent) {
options.setHasPrefix(false);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java
index 44ebb8e..1f8f3a6 100644
--- a/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java
+++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java
@@ -1,39 +1,39 @@
package su.nightexpress.nightcore.language.tag.impl;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.language.message.MessageOptions;
import su.nightexpress.nightcore.language.message.OutputType;
-import su.nightexpress.nightcore.language.tag.MessageDecorator;
+import su.nightexpress.nightcore.language.tag.MessageTag;
import su.nightexpress.nightcore.util.NumberUtil;
import su.nightexpress.nightcore.util.StringUtil;
-import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
-public class OutputTag extends DynamicTag implements MessageDecorator {
+public class OutputTag extends MessageTag {
public OutputTag() {
super("output");
}
- @Override
- public int getWeight() {
- return 0;
- }
-
@NotNull
public String enclose(@NotNull OutputType type) {
String prefix = type.name().toLowerCase();
- return this.leading(null, prefix);
+
+ return this.enclose(prefix);
}
@NotNull
public String enclose(int fade, int stay) {
String prefix = OutputType.TITLES.name().toLowerCase();
- return this.leading(null, prefix + ":" + fade + ":" + stay + ":" + fade);
+ String content = prefix + ":" + fade + ":" + stay + ":" + fade;
+
+ return this.enclose(content);
}
@Override
- public void apply(@NotNull MessageOptions options, @NotNull String content) {
- String[] split = content.split(":");
+ public void apply(@NotNull MessageOptions options, @Nullable String tagContent) {
+ if (tagContent == null) return;
+
+ String[] split = tagContent.split(":");
OutputType outputType = StringUtil.getEnum(split[0], OutputType.class).orElse(OutputType.CHAT);
options.setOutputType(outputType);
diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/PlaceholderTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/PlaceholderTag.java
index 4894652..a9a3ddb 100644
--- a/src/main/java/su/nightexpress/nightcore/language/tag/impl/PlaceholderTag.java
+++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/PlaceholderTag.java
@@ -1,23 +1,18 @@
package su.nightexpress.nightcore.language.tag.impl;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.language.message.MessageOptions;
-import su.nightexpress.nightcore.language.tag.MessageDecorator;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
+import su.nightexpress.nightcore.language.tag.MessageTag;
-public class PlaceholderTag extends Tag implements MessageDecorator {
+public class PlaceholderTag extends MessageTag {
public PlaceholderTag() {
super("papi");
}
@Override
- public int getWeight() {
- return 0;
- }
-
- @Override
- public void apply(@NotNull MessageOptions options, @NotNull String value) {
+ public void apply(@NotNull MessageOptions options, @Nullable String tagContent) {
options.setUsePlaceholderAPI(true);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java
index 3f62b37..05637a7 100644
--- a/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java
+++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java
@@ -2,30 +2,27 @@ package su.nightexpress.nightcore.language.tag.impl;
import org.bukkit.Sound;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.language.message.MessageOptions;
-import su.nightexpress.nightcore.language.tag.MessageDecorator;
+import su.nightexpress.nightcore.language.tag.MessageTag;
import su.nightexpress.nightcore.util.StringUtil;
-import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
-public class SoundTag extends DynamicTag implements MessageDecorator {
+public class SoundTag extends MessageTag {
public SoundTag() {
super("sound");
}
- @Override
- public int getWeight() {
- return 0;
- }
-
@NotNull
public String enclose(@NotNull Sound sound) {
- return this.leading(null, sound.name().toLowerCase());
+ return this.enclose(sound.name().toLowerCase());
}
@Override
- public void apply(@NotNull MessageOptions options, @NotNull String value) {
- Sound sound = StringUtil.getEnum(value, Sound.class).orElse(null);
+ public void apply(@NotNull MessageOptions options, @Nullable String tagContent) {
+ if (tagContent == null) return;
+
+ Sound sound = StringUtil.getEnum(tagContent, Sound.class).orElse(null);
options.setSound(sound);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/menu/api/AutoFilled.java b/src/main/java/su/nightexpress/nightcore/menu/api/AutoFilled.java
index f8ddf8f..a231b17 100644
--- a/src/main/java/su/nightexpress/nightcore/menu/api/AutoFilled.java
+++ b/src/main/java/su/nightexpress/nightcore/menu/api/AutoFilled.java
@@ -23,14 +23,6 @@ public interface AutoFilled extends Menu {
void onAutoFill(@NotNull MenuViewer viewer, @NotNull AutoFill autoFill);
- /*@Deprecated int[] getAutoFillSlots();
-
- @Deprecated @NotNull List getAutoFills(@NotNull Player player);
-
- @Deprecated @NotNull ItemStack getAutoFillStack(@NotNull Player player, @NotNull I object);
-
- @Deprecated@NotNull ClickAction getAutoFillClick(@NotNull I object);*/
-
default void autoFill(@NotNull MenuViewer viewer) {
AutoFill autoFill = new AutoFill<>();
this.onAutoFill(viewer, autoFill);
diff --git a/src/main/java/su/nightexpress/nightcore/menu/impl/AbstractMenu.java b/src/main/java/su/nightexpress/nightcore/menu/impl/AbstractMenu.java
index 029b308..58390ca 100644
--- a/src/main/java/su/nightexpress/nightcore/menu/impl/AbstractMenu.java
+++ b/src/main/java/su/nightexpress/nightcore/menu/impl/AbstractMenu.java
@@ -104,7 +104,7 @@ public abstract class AbstractMenu implements Menu {
public void close(@NotNull Player player) {
Menu current = getMenu(player);
- if (current == this && player.getOpenInventory().getType() != InventoryType.CRAFTING) {
+ if (current == this && player.getOpenInventory().getType() != InventoryType.CRAFTING && player.getOpenInventory().getType() != InventoryType.CREATIVE) {
player.closeInventory();
}
else {
@@ -232,7 +232,7 @@ public abstract class AbstractMenu
implements Menu {
MenuViewer viewer = this.purgeViewer(player);
// Do not clear link if entered Editor, so it can reopen menu without data loss when done.
- if (viewer != null && this instanceof Linked> linked && linked.cleanOnClose() && !Dialog.contains(player)) {
+ if (viewer != null && this instanceof Linked> linked && (!linked.isLinkPersistent() && !Dialog.contains(player))) {
linked.getLink().clear(viewer);
}
diff --git a/src/main/java/su/nightexpress/nightcore/menu/impl/EditorMenu.java b/src/main/java/su/nightexpress/nightcore/menu/impl/EditorMenu.java
index 89c7f26..f265ffa 100644
--- a/src/main/java/su/nightexpress/nightcore/menu/impl/EditorMenu.java
+++ b/src/main/java/su/nightexpress/nightcore/menu/impl/EditorMenu.java
@@ -19,7 +19,7 @@ import su.nightexpress.nightcore.menu.link.Linked;
import su.nightexpress.nightcore.menu.link.ViewLink;
import su.nightexpress.nightcore.util.ItemReplacer;
import su.nightexpress.nightcore.util.ItemUtil;
-import su.nightexpress.nightcore.util.text.WrappedMessage;
+import su.nightexpress.nightcore.util.text.TextRoot;
import java.util.function.Consumer;
@@ -74,7 +74,7 @@ public abstract class EditorMenu
extends AbstractM
@NotNull
protected MenuItem addReturn(int slot, @NotNull EditorHandler handler) {
- ItemStack item = ItemUtil.getSkinHead("27548362a24c0fa8453e4d93e68c5969ddbde57bf6666c0319c1ed1e84d89065");
+ ItemStack item = ItemUtil.getSkinHead("be9ae7a4be65fcbaee65181389a2f7d47e2e326db59ea3eb789a92c85ea46");
return this.addItem(item, CoreLang.EDITOR_ITEM_RETURN, slot, handler);
}
@@ -84,10 +84,18 @@ public abstract class EditorMenu extends AbstractM
return this.addItem(item, locale, slot, handler);
}
- @NotNull
+ /*@NotNull
+ @Deprecated
protected MenuItem addExit(int... slots) {
+ //ItemStack item = ItemUtil.getSkinHead("27548362a24c0fa8453e4d93e68c5969ddbde57bf6666c0319c1ed1e84d89065");
+ //return this.addItem(item, CoreLang.EDITOR_ITEM_CLOSE, slots).setHandler(ItemHandler.forClose(this));
+ return this.addExit(slots[0]);
+ }*/
+
+ @NotNull
+ protected MenuItem addExit(int slot) {
ItemStack item = ItemUtil.getSkinHead("27548362a24c0fa8453e4d93e68c5969ddbde57bf6666c0319c1ed1e84d89065");
- return this.addItem(item, CoreLang.EDITOR_ITEM_CLOSE, slots).setHandler(ItemHandler.forClose(this));
+ return this.addItem(item, CoreLang.EDITOR_ITEM_CLOSE, slot, (viewer, event, obj) -> ItemHandler.forClose(this));
}
@NotNull
@@ -130,7 +138,7 @@ public abstract class EditorMenu
extends AbstractM
}
@NotNull
- public Dialog handleInput(@NotNull Player player, @NotNull WrappedMessage prompt, @NotNull DialogHandler handler) {
+ public Dialog handleInput(@NotNull Player player, @NotNull TextRoot prompt, @NotNull DialogHandler handler) {
this.runNextTick(player::closeInventory);
Dialog dialog = Dialog.create(player, handler);
diff --git a/src/main/java/su/nightexpress/nightcore/menu/item/ItemHandler.java b/src/main/java/su/nightexpress/nightcore/menu/item/ItemHandler.java
index 2fcfc5f..022356e 100644
--- a/src/main/java/su/nightexpress/nightcore/menu/item/ItemHandler.java
+++ b/src/main/java/su/nightexpress/nightcore/menu/item/ItemHandler.java
@@ -48,9 +48,9 @@ public class ItemHandler {
/**
* The main purpose of this method is to quickly create ItemHandler object for non-configurable GUIs.
*
- * Do NOT use this for items requires specific handler name.
+ * Do NOT use this for items requiring specific handler name.
* @param action Click action
- * @return ItemHandler with random UUID as a name.
+ * @return ItemHandler with a random UUID as a name.
*/
@NotNull
public static ItemHandler forClick(@NotNull ClickAction action) {
diff --git a/src/main/java/su/nightexpress/nightcore/menu/link/Linked.java b/src/main/java/su/nightexpress/nightcore/menu/link/Linked.java
index de2c41a..ba5c94c 100644
--- a/src/main/java/su/nightexpress/nightcore/menu/link/Linked.java
+++ b/src/main/java/su/nightexpress/nightcore/menu/link/Linked.java
@@ -17,8 +17,8 @@ public interface Linked extends Menu {
return this.getLink().get(player);
}
- default boolean cleanOnClose() {
- return true;
+ default boolean isLinkPersistent() {
+ return false;
}
default boolean open(@NotNull Player player, @NotNull T obj) {
diff --git a/src/main/java/su/nightexpress/nightcore/util/BukkitThing.java b/src/main/java/su/nightexpress/nightcore/util/BukkitThing.java
index e3a4ca8..c28a4b3 100644
--- a/src/main/java/su/nightexpress/nightcore/util/BukkitThing.java
+++ b/src/main/java/su/nightexpress/nightcore/util/BukkitThing.java
@@ -8,8 +8,10 @@ import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class BukkitThing {
@@ -30,6 +32,14 @@ public class BukkitThing {
return registry.stream().collect(Collectors.toSet());
}
+ @NotNull
+ public static List getNames(@NotNull Registry registry) {
+ if (Version.isBehind(Version.V1_20_R2)) {
+ return StreamSupport.stream(registry.spliterator(), false).map(BukkitThing::toString).toList();
+ }
+ return registry.stream().map(BukkitThing::toString).toList();
+ }
+
@NotNull
public static String toString(@NotNull Keyed keyed) {
return keyed.getKey().getKey();
@@ -50,6 +60,14 @@ public class BukkitThing {
return allFromRegistry(Registry.ENCHANTMENT);
}
+ @NotNull
+ public static Set getEffectTypes() {
+ if (Version.isBehind(Version.V1_20_R2)) {
+ return Stream.of(PotionEffectType.values()).collect(Collectors.toSet());
+ }
+ return allFromRegistry(Registry.EFFECT);
+ }
+
@Nullable
public static Enchantment getEnchantment(@NotNull String name) {
if (Version.isBehind(Version.V1_19_R3)) {
diff --git a/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java b/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java
index c5ea267..a06f4f7 100644
--- a/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java
+++ b/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java
@@ -75,7 +75,7 @@ public class CommandUtil {
@NotNull
public static Optional getCommand(@NotNull String name) {
return COMMAND_MAP.getCommands().stream()
- .filter(command -> command.getLabel().equalsIgnoreCase(name) || command.getAliases().contains(name))
+ .filter(command -> command.getName().equalsIgnoreCase(name) || command.getLabel().equalsIgnoreCase(name) || command.getAliases().contains(name))
.findFirst();
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java
index 31a58f1..11b3992 100644
--- a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java
+++ b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java
@@ -60,6 +60,7 @@ public class ItemUtil {
}
public static void setHeadSkin(@NotNull ItemStack item, @NotNull String urlData) {
+ if (urlData.isBlank()) return;
if (item.getType() != Material.PLAYER_HEAD) return;
if (!(item.getItemMeta() instanceof SkullMeta meta)) return;
diff --git a/src/main/java/su/nightexpress/nightcore/util/Lists.java b/src/main/java/su/nightexpress/nightcore/util/Lists.java
index c1f98b3..29a9fd3 100644
--- a/src/main/java/su/nightexpress/nightcore/util/Lists.java
+++ b/src/main/java/su/nightexpress/nightcore/util/Lists.java
@@ -115,17 +115,29 @@ public class Lists {
List goods = new ArrayList<>();
Result:
- for (String sub : results) {
- int lastIndex = -1;
+ for (String item : results) {
+ int itemLength = item.length();
+ if (input.length() > itemLength) continue;
+ int lastIndex = -1;
for (char letter : chars) {
- int index = sub.indexOf(letter, lastIndex == -1 ? 0 : lastIndex);
+ int nextIndex = lastIndex;
+
+ if (nextIndex < 0) {
+ nextIndex = 0;
+ }
+ else if (nextIndex < itemLength - 1) {
+ nextIndex++; // This fixes an issue, where method fails for similar characters in a row, like 'oo'.
+ }
+
+ int index = item.indexOf(letter, nextIndex);
if (index <= lastIndex) {
continue Result;
}
+
lastIndex = index;
}
- goods.add(sub);
+ goods.add(item);
}
return goods;
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/Placeholders.java b/src/main/java/su/nightexpress/nightcore/util/Placeholders.java
index 70eb798..d3c36f5 100644
--- a/src/main/java/su/nightexpress/nightcore/util/Placeholders.java
+++ b/src/main/java/su/nightexpress/nightcore/util/Placeholders.java
@@ -28,8 +28,8 @@ public class Placeholders {
public static final String GENERIC_AMOUNT = "%amount%";
public static final String GENERIC_ENTRY = "%entry%";
- public static final String TAG_NO_PREFIX = MessageTags.NO_PREFIX.getFullName();
- public static final String TAG_LINE_BREAK = Tags.LINE_BREAK.getFullName();
+ public static final String TAG_NO_PREFIX = MessageTags.NO_PREFIX.getBracketsName();
+ public static final String TAG_LINE_BREAK = Tags.LINE_BREAK.getBracketsName();
public static final String PLAYER_NAME = "%player_name%";
public static final String PLAYER_DISPLAY_NAME = "%player_display_name%";
diff --git a/src/main/java/su/nightexpress/nightcore/util/Players.java b/src/main/java/su/nightexpress/nightcore/util/Players.java
index 6b0689e..219b9b9 100644
--- a/src/main/java/su/nightexpress/nightcore/util/Players.java
+++ b/src/main/java/su/nightexpress/nightcore/util/Players.java
@@ -16,7 +16,7 @@ import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.integration.VaultHook;
import su.nightexpress.nightcore.util.message.NexParser;
import su.nightexpress.nightcore.util.text.NightMessage;
-import su.nightexpress.nightcore.util.text.WrappedMessage;
+import su.nightexpress.nightcore.util.text.TextRoot;
import java.util.*;
import java.util.function.Predicate;
@@ -155,7 +155,7 @@ public class Players {
sendActionBar(player, NightMessage.create(message));
}
- public static void sendActionBar(@NotNull Player player, @NotNull WrappedMessage message) {
+ public static void sendActionBar(@NotNull Player player, @NotNull TextRoot message) {
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, message.parseIfAbsent());
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/RankMap.java b/src/main/java/su/nightexpress/nightcore/util/RankMap.java
index 1d58b3a..0edc2df 100644
--- a/src/main/java/su/nightexpress/nightcore/util/RankMap.java
+++ b/src/main/java/su/nightexpress/nightcore/util/RankMap.java
@@ -71,13 +71,27 @@ public class RankMap {
Mode mode = ConfigValue.create(path + ".Mode", Mode.class, Mode.RANK,
"Available values: " + StringUtil.inlineEnum(Mode.class, ", "),
- "RANK = Get value by player's permission group. All 'Values' keys will represent permission group names.",
- "PERMISSION = Get value by player's permissions. All 'Values' keys will become as suffix for 'Permission_Prefix' setting."
+ "=".repeat(20) + " " + Mode.RANK.name() + " MODE " + "=".repeat(20),
+ "Get value by player's permission group. All keys in 'Values' list will represent permission group names.",
+ "If player has none of specified groups, the 'Default_Value' setting will be used then",
+ " Values:",
+ " vip: 1 # -> Player must be in 'vip' permission group.",
+ " gold: 2 # -> Player must be in 'gold' permission group.",
+ " emerald: 3 # -> Player must be in 'emerald' permission group.",
+ "",
+ "=".repeat(20) + " " + Mode.PERMISSION.name() + " MODE " + "=".repeat(20),
+ "Get value by player's permissions. All keys in 'Values' list will represent postfixes for the 'Permission_Prefix' setting (see below).",
+ "If player has none of specified permissions, the 'Default_Value' setting will be used then",
+ " Permission_Prefix: 'example.prefix.'",
+ " Values:",
+ " vip: 1 # -> Player must have 'example.prefix.vip' permission.",
+ " gold: 2 # -> Player must have 'example.prefix.gold' permission.",
+ " emerald: 3 # -> Player must have 'example.prefix.emerald' permission."
).read(cfg);
- String permissionPrefix = ConfigValue.create(path + ".Permission_Prefix", "sample.prefix.",
- "Sets permission prefix for the 'PERMISSION' mode.",
- "All 'Values' keys will be used to check if player has permission: + ."
+ String permissionPrefix = ConfigValue.create(path + ".Permission_Prefix",
+ "example.prefix.",
+ "Sets permission prefix for the '" + Mode.PERMISSION.name() + "' mode."
).read(cfg);
T fallback;
diff --git a/src/main/java/su/nightexpress/nightcore/util/StringUtil.java b/src/main/java/su/nightexpress/nightcore/util/StringUtil.java
index 09328b6..ad26cb0 100644
--- a/src/main/java/su/nightexpress/nightcore/util/StringUtil.java
+++ b/src/main/java/su/nightexpress/nightcore/util/StringUtil.java
@@ -102,7 +102,7 @@ public class StringUtil {
return buf.toString();
}
- @Nullable
+ /*@Nullable
public static String parseQuotedContent(@NotNull String string) {
char quote = string.charAt(0);
if (quote != '\'' && quote != '"') return null;
@@ -123,6 +123,29 @@ public class StringUtil {
if (indexEnd == -1) return null;
return string.substring(1, indexEnd);
+ }*/
+
+ @Nullable
+ public static String parseQuotedContent(@NotNull String string) {
+ char quote = string.charAt(0);
+ if (quote != '\'' && quote != '"') return null;
+ if (string.length() < 3) return null;
+
+ StringBuilder builder = new StringBuilder();
+
+ for (int index = 1; index < string.length(); index++) {
+ char letter = string.charAt(index);
+ if (letter == '\\') {
+ //index++;
+ continue;
+ }
+ if (letter == quote) {
+ break;
+ }
+ builder.append(letter);
+ }
+
+ return builder.toString();
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/util/regex/TimeoutCharSequence.java b/src/main/java/su/nightexpress/nightcore/util/regex/TimeoutCharSequence.java
index 290e876..31a36e0 100644
--- a/src/main/java/su/nightexpress/nightcore/util/regex/TimeoutCharSequence.java
+++ b/src/main/java/su/nightexpress/nightcore/util/regex/TimeoutCharSequence.java
@@ -28,11 +28,13 @@ public class TimeoutCharSequence implements CharSequence {
}
@Override
+ @NotNull
public CharSequence subSequence(int start, int end) {
return new TimeoutCharSequence(this.chars.subSequence(start, end), this.timeout);
}
@Override
+ @NotNull
public String toString() {
return this.chars.toString();
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/ComponentBuildable.java b/src/main/java/su/nightexpress/nightcore/util/text/ComponentBuildable.java
new file mode 100644
index 0000000..8122615
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/ComponentBuildable.java
@@ -0,0 +1,9 @@
+package su.nightexpress.nightcore.util.text;
+
+import net.md_5.bungee.api.chat.BaseComponent;
+import org.jetbrains.annotations.NotNull;
+
+public interface ComponentBuildable {
+
+ @NotNull BaseComponent toComponent();
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java b/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java
index e0d4982..fea94a3 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java
@@ -1,72 +1,51 @@
package su.nightexpress.nightcore.util.text;
import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.ComponentBuilder;
-import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.util.Colorizer;
-import su.nightexpress.nightcore.util.Pair;
import su.nightexpress.nightcore.util.Placeholders;
-import su.nightexpress.nightcore.util.regex.TimedMatcher;
-import su.nightexpress.nightcore.util.text.decoration.*;
-import su.nightexpress.nightcore.util.text.tag.*;
-import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
-import su.nightexpress.nightcore.util.text.tag.api.OrphanTag;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
-import su.nightexpress.nightcore.util.text.tag.impl.*;
+import su.nightexpress.nightcore.util.text.tag.TagPool;
-import java.awt.*;
+import java.util.ArrayList;
import java.util.List;
-import java.util.*;
public class NightMessage {
- private static final Map TAG_MAP = new HashMap<>();
-
- static {
- registerTags(
- Tags.BLACK, Tags.WHITE, Tags.GRAY, Tags.GREEN,
- Tags.YELLOW, Tags.ORANGE, Tags.RED,
- Tags.BLUE, Tags.CYAN, Tags.PURPLE, Tags.PINK,
-
- Tags.DARK_GRAY, Tags.LIGHT_GRAY, Tags.LIGHT_GREEN,
- Tags.LIGHT_YELLOW, Tags.LIGHT_ORANGE, Tags.LIGHT_RED,
- Tags.LIGHT_BLUE, Tags.LIGHT_CYAN, Tags.LIGHT_PURPLE, Tags.LIGHT_PINK
- );
-
- registerTags(Tags.BOLD, Tags.ITALIC, Tags.OBFUSCATED, Tags.STRIKETHROUGH, Tags.UNDERLINED);
-
- registerTags(
- Tags.FONT, Tags.HEX_COLOR, Tags.HEX_COLOR_SHORT, Tags.GRADIENT,
- Tags.HOVER, Tags.CLICK,
- Tags.LINE_BREAK, Tags.RESET,
- Tags.TRANSLATE
- );
+ @NotNull
+ public static TextRoot from(@NotNull String string) {
+ return from(string, TagPool.ALL);
}
@NotNull
- public static Collection getTags() {
- return TAG_MAP.values();
+ public static TextRoot from(@NotNull String string, @NotNull TagPool tagPool) {
+ return new TextRoot(string, tagPool);
}
- public static void registerTags(@NotNull Tag... tags) {
- for (Tag tag : tags) {
- registerTag(tag);
- }
+ /**
+ *
+ * @param string Text to deserialize.
+ * @return Precompiled TextRoot object.
+ */
+ @NotNull
+ public static TextRoot create(@NotNull String string) {
+ return create(string, TagPool.ALL);
}
- public static void registerTag(@NotNull Tag tag) {
- TAG_MAP.put(tag.getName(), tag);
- for (String alias : tag.getAliases()) {
- TAG_MAP.put(alias, tag);
- }
+ @NotNull
+ public static TextRoot create(@NotNull String string, @NotNull TagPool tagPool) {
+ return from(string, tagPool).compile();
}
- @Nullable
- public static Tag getTag(@NotNull String name) {
- return TAG_MAP.get(name.toLowerCase());
+
+
+ @NotNull
+ public static BaseComponent parse(@NotNull String string) {
+ return parse(string, TagPool.ALL);
+ }
+
+ @NotNull
+ public static BaseComponent parse(@NotNull String string, @NotNull TagPool tagPool) {
+ return from(string, tagPool).parseIfAbsent();
}
@NotNull
@@ -74,6 +53,11 @@ public class NightMessage {
return create(string, TagPool.NONE).toLegacy();
}
+ @NotNull
+ public static String stripAll(@NotNull String string) {
+ return Colorizer.strip(clean(string));
+ }
+
@NotNull
public static String asJson(@NotNull String string) {
return create(string).toJson();
@@ -84,6 +68,7 @@ public class NightMessage {
return create(string).toLegacy();
}
+ @Deprecated
public static BaseComponent asComponent(@NotNull String string) {
return create(string).toComponent();
}
@@ -99,285 +84,5 @@ public class NightMessage {
return list;
}
- /**
- *
- * @param string Text to deserialize.
- * @return Precompiled WrappedMessage object.
- */
- @NotNull
- public static WrappedMessage create(@NotNull String string) {
- return create(string, TagPool.ALL);
- }
- @NotNull
- public static WrappedMessage from(@NotNull String string) {
- return from(string, TagPool.ALL);
- }
-
- @NotNull
- public static WrappedMessage create(@NotNull String string, @NotNull TagPool tagPool) {
- return from(string, tagPool).compile();
- }
-
- @NotNull
- public static WrappedMessage from(@NotNull String string, @NotNull TagPool tagPool) {
- return new WrappedMessage(string, tagPool);
- }
-
- public static BaseComponent[] parse(@NotNull String string) {
- return parse(string, TagPool.ALL);
- }
-
- public static BaseComponent[] parse(@NotNull String string, @NotNull TagPool tagPool) {
- if (CoreConfig.LEGACY_COLOR_SUPPORT.get()) {
- TimedMatcher timedMatcher = TimedMatcher.create(Colorizer.PATTERN_HEX_LEGACY, string);
- Set rawCodes = new HashSet<>();
- while (timedMatcher.find()) {
- String hex = timedMatcher.getMatcher().group(1);
- rawCodes.add(hex);
- }
- for (String hex : rawCodes) {
- string = string.replace(hex, Tag.brackets(hex));
- }
- }
-
- List parts = new ArrayList<>();
-
- WrappedText currentText = new WrappedText();
- parts.add(currentText);
-
- Tag lastTag = null;
-
- int length = string.length();
- for (int index = 0; index < length; index++) {
- char letter = string.charAt(index);
-
- Tag:
- if (letter == Tag.OPEN_BRACKET && index != (length - 1)) {
- int indexEnd = string.indexOf(Tag.CLOSE_BRACKET, index);
- if (indexEnd == -1) break Tag;
-
- char next = string.charAt(index + 1);
- if (next == Tag.CLOSE_BRACKET) break Tag;
-
- boolean closeTag = false;
- if (next == Tag.CLOSE_MARK) {
- closeTag = true;
- index++;
- }
-
- String leading = string.substring(index + 1);
- String brackets = string.substring(index + 1, indexEnd);
-
- Tag tag = getTag(brackets);
- Decorator decorator = null;
- //System.out.println("brackets = " + brackets);
-
- if (tag == null) {
- for (Tag registered : getTags()) {
- String tagName = registered.getName();
- if (leading.startsWith(tagName)) {
- char latest = leading.charAt(tagName.length());
-
- if (latest == Tag.CLOSE_BRACKET || registered instanceof DecoratorParser) {
- tag = registered;
- break;
- }
- }
- }
- }
- //System.out.println("found tag = " + tag);
-
- //if (tag == null) break Tag;
- /*if (tag != null && !tagPool.isGoodTag(tag)) {
- break Tag;
- }*/
-
- if (!closeTag) {
- // If tag is variable like hex codes or hover/click events.
- if (tag instanceof DecoratorParser parser) {
- // If tag has no dynamic content, strip it to the next close bracket.
- if (!(tag instanceof DynamicTag)) {
- leading = brackets;
- }
- //System.out.println("tag = " + tag.getName());
- //System.out.println("content = " + leading);
- ParsedDecorator parsedDecorator = parser.parse(leading);
- if (parsedDecorator != null) {
- decorator = parsedDecorator.getDecorator();
- indexEnd = index + parsedDecorator.getLength() + 1; // 1 for close bracket
- }
- }
- else if (tag instanceof Decorator textDecorator) {
- decorator = textDecorator;
- }
- }
-
- if (tag != null) {
- if (tagPool.isGoodTag(tag)) {
- if (tag instanceof OrphanTag orphanTag) {
- if (currentText.getTextBuilder().isEmpty()) {
- currentText.getTextBuilder().append(orphanTag.getContent());
- }
- else {
- currentText = currentText.nested();
- currentText.setText(orphanTag.getContent());
- parts.add(currentText);
- }
- currentText = currentText.nested();
- parts.add(currentText);
- }
-
- // Создаем новую "часть текста" только если обнаружен новый тег после текста (но не других тегов).
- if (lastTag == null && !currentText.getTextBuilder().isEmpty()) {
- currentText = currentText.nested();
- parts.add(currentText);
- }
-
- if (closeTag) {
- currentText.removeLatestTag(tag);
- }
- else if (!(tag instanceof OrphanTag)) {
- currentText.addTag(tag, decorator);
- }
-
- lastTag = tag;
- }
- index = indexEnd;
- continue;
- }
-
- // Move cursor back to '/' of invalid closing tag.
- if (closeTag) {
- index--;
- }
- }
- currentText.getTextBuilder().append(letter);
- lastTag = null;
- }
-
- //System.out.println("parsedTexts = " + parts);
-
- parts.removeIf(wrappedText -> wrappedText.getText().isEmpty());
-
- fixGradients(parts);
-
- ComponentBuilder builder = new ComponentBuilder();
- for (WrappedText wrappedText : parts) {
- if (CoreConfig.LEGACY_COLOR_SUPPORT.get()) {
- wrappedText.setText(Colorizer.apply(wrappedText.getText()));
- }
- builder.append(wrappedText.toComponent(), ComponentBuilder.FormatRetention.NONE);
- }
-
- return builder.create();
- }
-
- // Fix gradient smoothness when multiple WrappedTexts have the same gradient colors, but different tag lists.
- private static void fixGradients(@NotNull List parts) {
- if (parts.size() < 2) return;
-
- List>> pairs = new ArrayList<>();
-
- Pair> currentList = null;
- GradientDecorator lastGradient = null;
- int lastIndex = -1;
-
- // Create a list of sequental parts with the same gradient.
- for (int index = 0; index < parts.size(); index++) {
- WrappedText text = parts.get(index);
- GradientDecorator gradient = (GradientDecorator) text.getDecorator(GradientTag.NAME);
-
- // Check for next list
- if (gradient != null) {
- boolean bigStep = (index - lastIndex) > 1;
- boolean sameGradient = lastGradient != null && gradient.isSimilar(lastGradient);
- boolean lastElement = (index == parts.size() - 1);
- if (bigStep || !sameGradient || lastElement) {
- if (currentList != null && currentList.getSecond().size() > 1) {
- pairs.add(currentList);
- }
- currentList = Pair.of(gradient, new ArrayList<>());
- }
- currentList.getSecond().add(text);
- }
- else if (currentList != null) {
- pairs.add(currentList);
- currentList = null;
- }
-
- lastGradient = gradient;
- lastIndex = index;
- }
- //System.out.println("pairs = " + pairs);
-
- // Recreate Gradient Decorator with shifted colors depends on text length.
- for (var pair : pairs) {
- GradientDecorator gradient = pair.getFirst();
- List texts = pair.getSecond();
-
- int length = texts.stream().mapToInt(text -> text.getText().length()).sum();
-
- Color[] colors = gradient.createGradient(length);
- int shift = 0;
-
- for (WrappedText text : texts) {
- if (shift >= colors.length) break;
-
- int textLength = text.getText().length();
-
- Color start = colors[shift];
- Color end = colors[textLength + shift - 1];
-
- GradientDecorator decorator = new GradientDecorator(start, end);
- text.getDecoratorMap().put(GradientTag.NAME, decorator);
-
- shift += textLength;
- }
- }
- }
-
- @NotNull
- public static Builder builder() {
- return new Builder();
- }
-
- public static class Builder {
-
- private final List texts;
-
- public Builder() {
- this.texts = new ArrayList<>();
- }
-
- public BaseComponent[] create() {
- ComponentBuilder builder = new ComponentBuilder();
- for (WrappedText wrappedText : this.texts) {
- builder.append(wrappedText.toComponent(), ComponentBuilder.FormatRetention.NONE);
- }
- return builder.create();
- }
-
- public void send(@NotNull CommandSender sender) {
- sender.spigot().sendMessage(this.create());
- }
-
- public Builder append(@NotNull WrappedText.Builder textBuilder) {
- this.texts.add(textBuilder.getText());
- return this;
- }
-
- public WrappedText.Builder append(@NotNull String text, @NotNull Tag... tags) {
- WrappedText.Builder builder = WrappedText.builder(text);
- this.texts.add(builder.getText());
- for (Tag tag : tags) {
- builder.tag(tag);
- }
- return builder;
- }
-
- public Builder appendLineBreak() {
- return this.append(WrappedText.builder("\n"));
- }
- }
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java b/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java
new file mode 100644
index 0000000..1972900
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java
@@ -0,0 +1,120 @@
+package su.nightexpress.nightcore.util.text;
+
+import net.md_5.bungee.api.chat.BaseComponent;
+import net.md_5.bungee.api.chat.ComponentBuilder;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator;
+import su.nightexpress.nightcore.util.text.tag.decorator.Decorator;
+import su.nightexpress.nightcore.util.text.tag.decorator.GradientColorDecorator;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class TextGroup implements ComponentBuildable {
+
+ private final String name;
+ private final List childrens;
+ private final Set decorators;
+
+ private ColorDecorator colorDecorator;
+ private TextGroup parent;
+
+ public TextGroup(@NotNull String name) {
+ this.name = name;
+ this.childrens = new ArrayList<>();
+ this.decorators = new HashSet<>();
+ }
+
+ @NotNull
+ public TextGroup createChildren(@NotNull String name) {
+ TextGroup group = new TextGroup(name);
+ group.parent = this;
+ group.colorDecorator = this.colorDecorator;
+ group.decorators.addAll(this.decorators);
+ this.childrens.add(group);
+ return group;
+ }
+
+ @NotNull
+ public TextNode createNode() {
+ TextNode node = new TextNode(this);
+ this.childrens.add(node);
+ return node;
+ }
+
+ public void addDecorator(@NotNull Decorator decorator) {
+ if (decorator instanceof ColorDecorator color) {
+ this.colorDecorator = color;
+ }
+ else {
+ this.decorators.add(decorator);
+ }
+ }
+
+ public void clearDecorators() {
+ this.colorDecorator = null;
+ this.decorators.clear();
+ }
+
+ @Override
+ @NotNull
+ public BaseComponent toComponent() {
+ ComponentBuilder builder = new ComponentBuilder();
+
+ // Gradient colors must be predefined based on text length.
+ // Text length is calculated from group's childrens that are TextNodes.
+ if (this.colorDecorator instanceof GradientColorDecorator gradientDecorator && !gradientDecorator.isCreated()) {
+ AtomicInteger length = new AtomicInteger(0);
+ this.countLength(this, length);
+
+ gradientDecorator.createGradient(length.get()); // This will create and store Color[] array.
+ }
+
+ this.childrens.forEach(child -> {
+ builder.append(child.toComponent());
+ });
+
+ return builder.build();
+ }
+
+ private void countLength(@NotNull TextGroup parent, @NotNull AtomicInteger length) {
+ for (ComponentBuildable buildable : parent.getChildrens()) {
+ if (buildable instanceof TextNode textNode) {
+ length.addAndGet(textNode.textLength());
+ }
+
+ if (buildable instanceof TextGroup textGroup && textGroup.getColor() == this.colorDecorator) {
+ this.countLength(textGroup, length);
+ }
+ }
+ }
+
+ @NotNull
+ public String getName() {
+ return name;
+ }
+
+ @Nullable
+ public TextGroup getParent() {
+ return parent;
+ }
+
+ @Nullable
+ public ColorDecorator getColor() {
+ return colorDecorator;
+ }
+
+ @NotNull
+ public Set getDecorators() {
+ return decorators;
+ }
+
+ @NotNull
+ public List getChildrens() {
+ return childrens;
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextNode.java b/src/main/java/su/nightexpress/nightcore/util/text/TextNode.java
new file mode 100644
index 0000000..44d1ae8
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/TextNode.java
@@ -0,0 +1,81 @@
+package su.nightexpress.nightcore.util.text;
+
+import net.md_5.bungee.api.chat.BaseComponent;
+import net.md_5.bungee.api.chat.TextComponent;
+import net.md_5.bungee.api.chat.TranslatableComponent;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.core.CoreConfig;
+import su.nightexpress.nightcore.util.Colorizer;
+import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator;
+
+public class TextNode implements ComponentBuildable {
+
+ private final StringBuilder textBuilder;
+ private final TextGroup parent;
+
+ private String translation;
+
+ public TextNode(@NotNull TextGroup parent) {
+ this.textBuilder = new StringBuilder();
+ this.parent = parent;
+ }
+
+ public void append(char letter) {
+ this.textBuilder.append(letter);
+ }
+
+ public void append(@NotNull String str) {
+ this.textBuilder.append(str);
+ }
+
+ public void setTranslation(@Nullable String translation) {
+ this.translation = translation;
+ }
+
+ @NotNull
+ public StringBuilder getTextBuilder() {
+ return textBuilder;
+ }
+
+ @NotNull
+ public TextGroup getParent() {
+ return parent;
+ }
+
+ public int textLength() {
+ int legnth = 0;
+ if (this.translation != null) return 1;
+ //if (this.textBuilder.toString().equals("\n")) return legnth; // Do not count length for line breaks.
+
+ for (int index = 0; index < this.textBuilder.length(); index++) {
+ char letter = this.textBuilder.charAt(index);
+ if (Character.isWhitespace(letter)) continue;
+
+ legnth++;
+ }
+ return legnth;
+ }
+
+ @Override
+ @NotNull
+ public BaseComponent toComponent() {
+ String text = this.textBuilder.toString();
+ if (CoreConfig.LEGACY_COLOR_SUPPORT.get()) {
+ text = Colorizer.legacy(text);
+ }
+
+ ColorDecorator colorDecorator = this.parent.getColor();
+ BaseComponent textComponent = this.translation == null ? new TextComponent(text) : new TranslatableComponent(this.translation);
+
+ if (colorDecorator != null) {
+ colorDecorator.decorate(textComponent);
+ }
+
+ this.parent.getDecorators().forEach(decorator -> {
+ decorator.decorate(textComponent);
+ });
+
+ return textComponent;
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java b/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java
new file mode 100644
index 0000000..b5c25f8
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java
@@ -0,0 +1,350 @@
+package su.nightexpress.nightcore.util.text;
+
+import net.md_5.bungee.api.chat.BaseComponent;
+import net.md_5.bungee.api.chat.TextComponent;
+import net.md_5.bungee.chat.ComponentSerializer;
+import org.bukkit.command.CommandSender;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.core.CoreConfig;
+import su.nightexpress.nightcore.util.Colorizer;
+import su.nightexpress.nightcore.util.regex.TimedMatcher;
+import su.nightexpress.nightcore.util.text.tag.TagPool;
+import su.nightexpress.nightcore.util.text.tag.Tags;
+import su.nightexpress.nightcore.util.text.tag.api.ContentTag;
+import su.nightexpress.nightcore.util.text.tag.api.PlaceholderTag;
+import su.nightexpress.nightcore.util.text.tag.api.Tag;
+import su.nightexpress.nightcore.util.text.tag.decorator.Decorator;
+import su.nightexpress.nightcore.util.text.tag.impl.ShortHexColorTag;
+import su.nightexpress.nightcore.util.text.tag.impl.ResetTag;
+import su.nightexpress.nightcore.util.text.tag.impl.TranslationTag;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.function.UnaryOperator;
+
+public class TextRoot {
+
+ public static final String ROOT_NAME = "root";
+
+ private final TagPool tagPool;
+
+ private String string;
+ private TextGroup rootGroup;
+ private TextGroup currentGroup;
+ private TextNode currentNode;
+
+ private BaseComponent component;
+
+ public TextRoot(@NotNull String string, @NotNull TagPool tagPool) {
+ this.tagPool = tagPool;
+ this.setString(string);
+ }
+
+ public void setString(@NotNull String string) {
+ if (CoreConfig.LEGACY_COLOR_SUPPORT.get()) {
+ TimedMatcher timedMatcher = TimedMatcher.create(Colorizer.PATTERN_HEX_LEGACY, string);
+ Set rawCodes = new HashSet<>();
+ while (timedMatcher.find()) {
+ String hex = timedMatcher.getMatcher().group(1);
+ rawCodes.add(hex);
+ }
+ for (String hex : rawCodes) {
+ string = string.replace(hex, Tag.brackets(hex));
+ }
+ }
+
+ this.string = string;
+ this.component = null;
+ }
+
+ @NotNull
+ public TextRoot copy() {
+ TextRoot copy = new TextRoot(this.string, this.tagPool);
+ if (this.component != null) {
+ copy.component = this.component.duplicate();
+ }
+ return copy;
+ }
+
+ @NotNull
+ public TextRoot compile() {
+ this.parseIfAbsent();
+ return this;
+ }
+
+ @NotNull
+ public TextRoot recompile() {
+ this.parse();
+ return this;
+ }
+
+ @NotNull
+ public String toLegacy() {
+ if (this.string.isBlank()) return "";
+
+ this.parseIfAbsent();
+
+ if (this.component instanceof TextComponent textComponent && textComponent.getText().isBlank() && textComponent.getExtra() == null) {
+ return "";
+ }
+
+ return TextComponent.toLegacyText(this.parseIfAbsent());
+ }
+
+ @NotNull
+ public String toJson() {
+ return ComponentSerializer.toString(this.parseIfAbsent());
+ }
+
+ @NotNull
+ @Deprecated
+ public BaseComponent toComponent() {
+ return this.parseIfAbsent();
+ //return TextComponent.fromArray(this.parseIfAbsent());
+ }
+
+ @NotNull
+ public TextRoot replace(@NotNull String what, @NotNull Object object) {
+ return this.replace(str -> str.replace(what, String.valueOf(object)));
+ }
+
+ @NotNull
+ public TextRoot replace(@NotNull UnaryOperator operator) {
+ this.setString(operator.apply(this.string));
+ return this;
+ }
+
+ public void send(@NotNull CommandSender... senders) {
+ this.parseIfAbsent();
+ for (CommandSender sender : senders) {
+ sender.spigot().sendMessage(this.component);
+ }
+ }
+
+ @NotNull
+ public TextGroup toParentGroup() {
+ this.currentGroup = this.currentGroup.getParent();
+ if (this.currentGroup == null) this.currentGroup = this.rootGroup;
+
+ return this.currentGroup;
+ }
+
+ @NotNull
+ public TextGroup toParentGroup(@NotNull String name) {
+ TextGroup lastGroup = this.currentGroup;
+
+ while (this.currentGroup != null && !this.currentGroup.getName().equalsIgnoreCase(name)) {
+ this.currentGroup = this.currentGroup.getParent();
+ }
+ if (this.currentGroup == null && lastGroup != null) {
+ this.currentGroup = lastGroup;
+ return this.currentGroup;
+ }
+
+ if (this.currentGroup != null) this.currentGroup = this.currentGroup.getParent();
+ if (this.currentGroup == null) this.currentGroup = this.rootGroup;
+
+ return this.currentGroup;
+ }
+
+ @NotNull
+ public TextNode currentNode() {
+ if (this.currentNode == null) this.currentNode = this.currentGroup.createNode();
+
+ return this.currentNode;
+ }
+
+ public BaseComponent parseIfAbsent() {
+ return this.component == null ? this.parse() : this.component;
+ }
+
+ @NotNull
+ public BaseComponent parse() {
+ this.rootGroup = new TextGroup(ROOT_NAME);
+ this.currentGroup = this.rootGroup;
+
+ int length = string.length();
+ for (int index = 0; index < length; index++) {
+ char letter = string.charAt(index);
+
+ Tag:
+ if (letter == Tag.OPEN_BRACKET && index != (length - 1)) {
+ int indexEnd = indexOfIgnoreEscaped(string, Tag.CLOSE_BRACKET, index);//string.indexOf(Tag.CLOSE_BRACKET, index);
+ //System.out.println("indexEnd = " + indexEnd);
+ if (indexEnd == -1) break Tag;
+
+ char next = string.charAt(index + 1);
+ if (next == Tag.CLOSE_BRACKET) break Tag;
+
+ boolean closeTag = false;
+ if (next == Tag.CLOSE_SLASH) {
+ closeTag = true;
+ index++;
+ }
+
+ String bracketsContent = string.substring(index + 1, indexEnd);
+ //System.out.println("bracketsContent = " + bracketsContent);
+
+ String tagName = bracketsContent;
+ String tagContent = null;
+
+ // Check for content tags
+ int semicolonIndex = bracketsContent.indexOf(':');
+ if (semicolonIndex >= 0) {
+ tagName = bracketsContent.substring(0, semicolonIndex);
+ tagContent = bracketsContent.substring(semicolonIndex + 1);
+ //System.out.println("tagName = " + tagName);
+ //System.out.println("tagContent = " + tagContent);
+ }
+ else if (tagName.startsWith(ShortHexColorTag.NAME)) {
+ tagName = ShortHexColorTag.NAME;
+ tagContent = bracketsContent;
+ }
+
+ Tag tag = Tags.getTag(tagName);
+ //System.out.println("found tag = " + tag);
+
+ if (tag != null) {
+ if (tagPool.isGoodTag(tag)) {
+ this.proceedTag(tag, closeTag, tagContent);
+ }
+ index = indexEnd;
+ continue;
+ }
+
+ // Move cursor back to '/' of invalid closing tag.
+ if (closeTag) {
+ index--;
+ }
+ }
+
+ this.currentNode().append(letter);
+ }
+
+ this.component = this.rootGroup.toComponent();
+
+ return this.component;
+ }
+
+ private void proceedTag(@NotNull Tag tag, boolean closeTag, @Nullable String tagContent) {
+ if (tag instanceof PlaceholderTag placeholderTag) {
+ if (!closeTag) {
+ this.currentNode().append(placeholderTag.getValue()); // Insert it to the current node as if it was a regular text.
+ }
+ return;
+ }
+ if (tag instanceof TranslationTag translationTag) {
+ if (tagContent != null) {
+ this.currentGroup.createNode().setTranslation(stripQuotesSlash(tagContent)); // Create a new node specially for translation text.
+ this.currentNode = null; // Reset current node so parser will create a new one after this one with translation.
+ }
+ return;
+ }
+
+ this.currentNode = null; // Reset current node because of current group change below.
+
+ if (closeTag) {
+ this.toParentGroup(tag.getName()); // Jump to the first parent group of closed tag (or root group if there is no parent for this tag).
+ return;
+ }
+
+ if (tag instanceof ResetTag) {
+ this.currentGroup = this.rootGroup; // Jump to the parent group for 'Reset' tag, so it will create new children groups without decorators on further parsing.
+ return;
+ }
+
+ this.currentGroup = this.currentGroup.createChildren(tag.getName()); // Create children tag group inside the current one.
+
+ Decorator decorator = null;
+
+ if (tag instanceof ContentTag contentTag && tagContent != null) {
+ decorator = contentTag.parse(tagContent);
+ }
+ else if (tag instanceof Decorator tagDecorator) {
+ decorator = tagDecorator;
+ }
+
+ if (decorator != null) {
+ this.currentGroup.addDecorator(decorator);
+ }
+ }
+
+ public String getString() {
+ return string;
+ }
+
+ public TextGroup getRootGroup() {
+ return rootGroup;
+ }
+
+ public BaseComponent getComponent() {
+ return component;
+ }
+
+ public static int indexOfIgnoreEscaped(@NotNull String string, char what, int from) {
+ int length = string.length();
+ if (from >= length) return -1;
+
+ Character foundQuote = null;
+ int quoteCount = 0;
+
+ for (int index = from; index < length; index++) {
+ char letter = string.charAt(index);
+ if (letter == '\\') {
+ index++;
+ continue;
+ }
+
+ if (letter == '\'' || letter == '"') {
+ quoteCount++;
+ if (foundQuote != null) {
+ if (foundQuote == letter) {
+ foundQuote = null;
+ }
+ }
+ else foundQuote = letter;
+ }
+
+ if (letter == what) {
+ if (foundQuote != null && quoteCount < 2) continue;
+ return index;
+ }
+ }
+
+ return -1;
+ }
+
+ @NotNull
+ public static String stripQuotesSlash(@NotNull String str) {
+ if (str.startsWith("\"") || str.startsWith("'")) {
+ str = str.substring(1);
+ }
+ if (str.endsWith("\"") || str.endsWith("'")) {
+ str = str.substring(0, str.length() - 1);
+ }
+ return str.replace("\\", "");
+ }
+
+ /*@NotNull
+ public static String substringOfQuotes(@NotNull String string) {
+ char quote = string.charAt(0);
+ if (quote != '\'' && quote != '"') return string;
+ if (string.length() < 3) return string;
+
+ //int indexEnd = -1;
+ for (int index = 1; index < string.length(); index++) {
+ char letter = string.charAt(index);
+ if (letter == '\\') {
+ index++;
+ continue;
+ }
+ if (letter == quote) {
+ return string.substring(1, index);
+ }
+ }
+ //if (indexEnd == -1) return string;
+
+ return string;//.substring(1, indexEnd);
+ }*/
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/WrappedMessage.java b/src/main/java/su/nightexpress/nightcore/util/text/WrappedMessage.java
deleted file mode 100644
index 6a2a19f..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/text/WrappedMessage.java
+++ /dev/null
@@ -1,138 +0,0 @@
-package su.nightexpress.nightcore.util.text;
-
-import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.TextComponent;
-import net.md_5.bungee.chat.ComponentSerializer;
-import org.bukkit.command.CommandSender;
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.text.tag.TagPool;
-
-import java.util.function.UnaryOperator;
-
-public class WrappedMessage {
-
- private final TagPool tagPool;
-
- private String string;
- private BaseComponent[] components;
-
- public WrappedMessage(@NotNull String string, @NotNull TagPool tagPool) {
- this.tagPool = tagPool;
- this.string = string;
- }
-
- @NotNull
- public WrappedMessage copy() {
- WrappedMessage copy = new WrappedMessage(this.string, this.tagPool);
- if (this.components != null) {
- BaseComponent[] components = new BaseComponent[this.components.length];
- for (int index = 0; index < components.length; index++) {
- components[index] = this.components[index].duplicate();
- }
- copy.components = components;
- }
- return copy;
- }
-
- @NotNull
- public WrappedMessage compile() {
- this.parseIfAbsent();
- return this;
- }
-
- @NotNull
- public WrappedMessage recompile() {
- this.parse();
- return this;
- }
-
- @NotNull
- public String toLegacy() {
- return TextComponent.toLegacyText(this.parseIfAbsent());
- }
-
- @NotNull
- public String toJson() {
- return ComponentSerializer.toString(this.parseIfAbsent());
- }
-
- @NotNull
- public BaseComponent toComponent() {
- return TextComponent.fromArray(this.parseIfAbsent());
- }
-
- @NotNull
- public WrappedMessage replace(@NotNull String what, @NotNull Object object) {
- return this.replace(str -> str.replace(what, String.valueOf(object)));
- //return this.replace(what, String.valueOf(object));
- }
-
- @NotNull
- public WrappedMessage replace(@NotNull UnaryOperator operator) {
- this.string = operator.apply(this.string);
- this.components = null;
- return this;
-
-
- /*if (this.components == null) {
- this.string = operator.apply(this.string);
- return this;
- }
-
- for (BaseComponent component : this.components) {
- if (component instanceof TextComponent textComponent) {
- textComponent.setText(operator.apply(textComponent.getText()));
- }
- }
- return this;*/
- }
-
- /*@NotNull
- public WrappedMessage replace(@NotNull String var, @NotNull String value) {
- if (this.components == null) {
- this.string = this.string.replace(var, value);
- return this;
- }
-
- WrappedMessage message = NightMessage.create(value);
-
- ComponentBuilder builder = new ComponentBuilder();
- for (BaseComponent component : this.components) {
- if (component instanceof TextComponent textComponent) {
- String text = textComponent.getText();
- String[] split = text.split(var);
-
- ComponentBuilder replacer = new ComponentBuilder();
- for (String part : split) {
- if (!replacer.getParts().isEmpty()) {
- replacer.append(message.parseIfAbsent());
- }
-
- TextComponent origin = new TextComponent(part);
- origin.copyFormatting(textComponent);
- replacer.append(origin);
- }
- builder.append(replacer.create());
- }
- else builder.append(component);
- }
-
- return this;
- }*/
-
- public void send(@NotNull CommandSender... senders) {
- this.parseIfAbsent();
- for (CommandSender sender : senders) {
- sender.spigot().sendMessage(this.components);
- }
- }
-
- public BaseComponent[] parseIfAbsent() {
- return this.components == null ? this.parse() : this.components;
- }
-
- public BaseComponent[] parse() {
- this.components = NightMessage.parse(this.string, this.tagPool);
- return this.components;
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/WrappedText.java b/src/main/java/su/nightexpress/nightcore/util/text/WrappedText.java
deleted file mode 100644
index 95e8209..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/text/WrappedText.java
+++ /dev/null
@@ -1,197 +0,0 @@
-package su.nightexpress.nightcore.util.text;
-
-import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.ClickEvent;
-import net.md_5.bungee.api.chat.TextComponent;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.text.decoration.*;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
-import su.nightexpress.nightcore.util.text.tag.Tags;
-import su.nightexpress.nightcore.util.text.tag.impl.ColorTag;
-import su.nightexpress.nightcore.util.text.tag.impl.FontStyleTag;
-
-import java.awt.*;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class WrappedText {
-
- private final StringBuilder textBuilder;
- private final List tags;
- private final Map decoratorMap;
-
- public WrappedText() {
- this.textBuilder = new StringBuilder();
- this.tags = new ArrayList<>();
- this.decoratorMap = new HashMap<>();
- }
-
- public WrappedText(@NotNull String text) {
- this();
- this.setText(text);
- }
-
- @NotNull
- public WrappedText nested() {
- WrappedText nested = new WrappedText();
- nested.getTags().addAll(this.getTags());
- nested.getDecoratorMap().putAll(this.getDecoratorMap());
- return nested;
- }
-
- @Nullable
- public Decorator getDecorator(@NotNull Tag tag) {
- return this.getDecorator(tag.getName());
- }
-
- @Nullable
- public Decorator getDecorator(@NotNull String tagName) {
- return this.getDecoratorMap().get(tagName.toLowerCase());
- }
-
- @NotNull
- public BaseComponent toComponent() {
- TextComponent component = new TextComponent(this.getText());
-
- for (Tag tag : this.getTags()) {
- Decorator decorator = this.getDecorator(tag);
- if (decorator == null) continue;
-
- decorator.decorate(component);
- }
-
- return component;
- }
-
- public void addTag(@NotNull Tag tag, @Nullable Decorator decorator) {
- //this.getTags().removeIf(tag::conflictsWith);
- this.getTags().removeIf(other -> other.getName().equals(tag.getName()));
- this.getTags().add(tag);
- if (decorator != null) {
- this.decoratorMap.put(tag.getName(), decorator);
- }
- }
-
- public void removeLatestTag(@NotNull Tag tag) {
- for (int indexTag = this.getTags().size() - 1; indexTag > -1; indexTag--) {
- Tag has = this.getTags().get(indexTag);
- if (has.getName().equalsIgnoreCase(tag.getName())) {
- this.getTags().remove(indexTag);
- this.getDecoratorMap().remove(tag.getName());
- break ;
- }
- }
- }
-
- public void removeTag(@NotNull Tag tag) {
- this.getTags().remove(tag);
- this.getDecoratorMap().remove(tag.getName());
- }
-
- @NotNull
- public List getTags() {
- return tags;
- }
-
- @NotNull
- public Map getDecoratorMap() {
- return decoratorMap;
- }
-
- @NotNull
- public StringBuilder getTextBuilder() {
- return textBuilder;
- }
-
- @NotNull
- public String getText() {
- return this.getTextBuilder().toString();
- }
-
- public void setText(@NotNull String text) {
- this.textBuilder.setLength(0);
- this.textBuilder.append(text);
- }
-
- @Override
- public String toString() {
- return "ParsedText{" +
- "tags=" + tags +
- ", text=" + textBuilder +
- '}';
- }
-
- @NotNull
- public static Builder builder(@NotNull String text) {
- return new Builder(new WrappedText(text));
- }
-
- public static class Builder {
-
- private final WrappedText text;
-
- public Builder(@NotNull WrappedText text) {
- this.text = text;
- }
-
- @NotNull
- public WrappedText getText() {
- return text;
- }
-
- @NotNull
- public Builder tag(@NotNull Tag tag) {
- return this.tag(tag, tag instanceof Decorator decorator ? decorator : null);
- }
-
- @NotNull
- public Builder tag(@NotNull Tag tag, @Nullable Decorator decorator) {
- this.getText().addTag(tag, decorator);
- return this;
- }
-
- public Builder color(@NotNull Color color) {
- return this.color(new ColorTag(color));
- }
-
- public Builder color(@NotNull ColorTag tag) {
- return this.tag(tag);
- }
-
- public Builder bold() {
- return style(Tags.BOLD);
- }
-
- public Builder style(@NotNull FontStyleTag tag) {
- return this.tag(tag);
- }
-
- public Builder gradient(@NotNull Color from, @NotNull Color to) {
- return this.tag(Tags.GRADIENT, new GradientDecorator(from, to));
- }
-
- public Builder showText(@NotNull String... text) {
- return this.tag(Tags.HOVER, new ShowTextDecorator(text));
- }
-
- public Builder showItem(@NotNull ItemStack itemStack) {
- return this.tag(Tags.HOVER, ShowItemDecorator.from(itemStack));
- }
-
- public Builder runCommand(@NotNull String value) {
- return this.clickEvent(ClickEvent.Action.RUN_COMMAND, value);
- }
-
- public Builder suggestCommand(@NotNull String value) {
- return this.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, value);
- }
-
- public Builder clickEvent(@NotNull ClickEvent.Action action, @NotNull String value) {
- return this.tag(Tags.CLICK, new ClickEventDecorator(action, value));
- }
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/DecoratorParser.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/DecoratorParser.java
deleted file mode 100644
index 7713fe2..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/DecoratorParser.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package su.nightexpress.nightcore.util.text.decoration;
-
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-public interface DecoratorParser {
-
- @Nullable ParsedDecorator parse(@NotNull String str);
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/GradientDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/GradientDecorator.java
deleted file mode 100644
index 3b49427..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/GradientDecorator.java
+++ /dev/null
@@ -1,79 +0,0 @@
-package su.nightexpress.nightcore.util.text.decoration;
-
-import net.md_5.bungee.api.ChatColor;
-import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.TextComponent;
-import org.jetbrains.annotations.NotNull;
-
-import java.awt.*;
-
-public class GradientDecorator implements Decorator {
-
- private final Color color;
- private final Color colorEnd;
-
- public GradientDecorator(@NotNull Color color, @NotNull Color colorEnd) {
- this.color = color;
- this.colorEnd = colorEnd;
- }
-
- public boolean isSimilar(@NotNull GradientDecorator other) {
- return this.getColor().equals(other.getColor()) && this.getColorEnd().equals(other.getColorEnd());
- }
-
- public Color getColor() {
- return color;
- }
-
- @NotNull
- public Color getColorEnd() {
- return colorEnd;
- }
-
- public Color[] createGradient(int length) {
- Color[] colors = new Color[length];
- for (int index = 0; index < length; index++) {
- double percent = (double) index / (double) length;
-
- int red = (int) (color.getRed() + percent * (colorEnd.getRed() - color.getRed()));
- int green = (int) (color.getGreen() + percent * (colorEnd.getGreen() - color.getGreen()));
- int blue = (int) (color.getBlue() + percent * (colorEnd.getBlue() - color.getBlue()));
-
- java.awt.Color color = new java.awt.Color(red, green, blue);
- colors[index] = color;
- }
- return colors;
- }
-
- /*@NotNull
- public List> gradient(@NotNull String string) {
- List> list = new ArrayList<>();
-
- Color[] colors = createGradient(string.length());
- char[] characters = string.toCharArray();
-
- for (int index = 0; index < characters.length; index++) {
- list.add(Pair.of(String.valueOf(characters[index]), colors[index]));
- }
-
- return list;
- }*/
-
- @Override
- public void decorate(@NotNull BaseComponent component) {
- if (!(component instanceof TextComponent textComponent)) return;
-
- String text = textComponent.getText();
-
- Color[] colors = createGradient(text.length());
- char[] characters = text.toCharArray();
-
- for (int index = 0; index < characters.length; index++) {
- TextComponent extra = new TextComponent(String.valueOf(characters[index]));
- extra.copyFormatting(textComponent);
- extra.setColor(ChatColor.of(colors[index]));
- textComponent.addExtra(extra);
- }
- textComponent.setText("");
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ParsedDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ParsedDecorator.java
deleted file mode 100644
index cf36a78..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ParsedDecorator.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package su.nightexpress.nightcore.util.text.decoration;
-
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.text.decoration.Decorator;
-
-public class ParsedDecorator {
-
- private final Decorator tag;
-
- private int length;
-
- public ParsedDecorator(@NotNull Decorator tag, int length) {
- this.tag = tag;
- this.length = length;
- }
-
- @NotNull
- public Decorator getDecorator() {
- return tag;
- }
-
- public void setLength(int length) {
- this.length = length;
- }
-
- public int getLength() {
- return length;
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/TagPool.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/TagPool.java
index 7f7a172..7ffe424 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/TagPool.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/TagPool.java
@@ -1,77 +1,67 @@
package su.nightexpress.nightcore.util.text.tag;
import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.Placeholders;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
+import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator;
+import su.nightexpress.nightcore.util.text.tag.impl.FontStyleTag;
+import su.nightexpress.nightcore.util.text.tag.impl.GradientTag;
+import su.nightexpress.nightcore.util.text.tag.impl.HexColorTag;
+import su.nightexpress.nightcore.util.text.tag.impl.ShortHexColorTag;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.function.Predicate;
public class TagPool {
- public static final TagPool ALL = new TagPool(Mode.BLACKLIST, Collections.emptySet());
- public static final TagPool NONE = new TagPool(Mode.WHITELIST, Collections.emptySet());
+ public static final TagPool ALL = new TagPool(tag -> true);
+ public static final TagPool NONE = new TagPool(tag -> false);
- private final Mode mode;
- private final Set tags;
+ public static final TagPool ALL_COLORS = new TagPool(
+ tag -> tag instanceof ColorDecorator ||
+ tag instanceof GradientTag ||
+ tag instanceof HexColorTag ||
+ tag instanceof ShortHexColorTag
+ );
- @NotNull
- public static TagPool whitelisted(@NotNull Tag... tags) {
- return create(Mode.WHITELIST, tags);
+ public static final TagPool ALL_COLORS_AND_STYLES = new TagPool(
+ tag -> tag instanceof ColorDecorator ||
+ tag instanceof GradientTag ||
+ tag instanceof HexColorTag ||
+ tag instanceof ShortHexColorTag ||
+ tag instanceof FontStyleTag
+ );
+
+ public static final TagPool BASE_COLORS = new TagPool(
+ tag -> tag instanceof ColorDecorator ||
+ tag instanceof HexColorTag ||
+ tag instanceof ShortHexColorTag
+ );
+
+ public static final TagPool BASE_COLORS_AND_STYLES = new TagPool(
+ tag -> tag instanceof ColorDecorator ||
+ tag instanceof HexColorTag ||
+ tag instanceof ShortHexColorTag ||
+ tag instanceof FontStyleTag
+ );
+
+ private Predicate predicate;
+
+ public TagPool(@NotNull Predicate predicate) {
+ this.predicate = predicate;
}
@NotNull
- public static TagPool blacklisted(@NotNull Tag... tags) {
- return create(Mode.BLACKLIST, tags);
+ public TagPool and(@NotNull Predicate more) {
+ this.predicate = this.predicate.and(more);
+ return this;
}
@NotNull
- public static TagPool create(@NotNull Mode mode, @NotNull Tag... tags) {
- return new TagPool(mode, Stream.of(tags).map(Tag::getName).collect(Collectors.toSet()));
- }
-
- public TagPool(@NotNull Mode mode, @NotNull Set tags) {
- this.mode = mode;
- this.tags = new HashSet<>(tags);
- }
-
- public enum Mode {
- WHITELIST, BLACKLIST
- }
-
- public boolean isWhitelist() {
- return this.getMode() == Mode.WHITELIST;
- }
-
- public boolean isBlacklist() {
- return this.getMode() == Mode.BLACKLIST;
+ public TagPool or(@NotNull Predicate more) {
+ this.predicate = this.predicate.or(more);
+ return this;
}
public boolean isGoodTag(@NotNull Tag tag) {
- return this.isGoodTag(tag.getName());
- }
-
- public boolean isGoodTag(@NotNull String name) {
- name = name.toLowerCase();
-
- if (this.isWhitelist()) {
- return this.getTags().contains(name) || this.getTags().contains(Placeholders.WILDCARD);
- }
- else {
- return !this.getTags().contains(name);
- }
- }
-
- @NotNull
- public Mode getMode() {
- return mode;
- }
-
- @NotNull
- public Set getTags() {
- return tags;
+ return this.predicate.test(tag);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java
index 82ac952..e2a1556 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java
@@ -1,18 +1,27 @@
package su.nightexpress.nightcore.util.text.tag;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.util.text.tag.api.Tag;
import su.nightexpress.nightcore.util.text.tag.impl.*;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
public class Tags {
- public static final ClickTag CLICK = new ClickTag();
- public static final FontTag FONT = new FontTag();
+ private static final Map REGISTRY = new HashMap<>();
+
public static final GradientTag GRADIENT = new GradientTag();
+ public static final LineBreakTag LINE_BREAK = new LineBreakTag();
+ public static final FontTag FONT = new FontTag();
+ public static final HoverTag HOVER = new HoverTag();
+ public static final ClickTag CLICK = new ClickTag();
+ public static final ResetTag RESET = new ResetTag();
public static final HexColorTag HEX_COLOR = new HexColorTag();
public static final ShortHexColorTag HEX_COLOR_SHORT = new ShortHexColorTag();
- public static final HoverTag HOVER = new HoverTag();
- public static final LineBreakTag LINE_BREAK = new LineBreakTag();
- public static final ResetTag RESET = new ResetTag();
- public static final TranslateTag TRANSLATE = new TranslateTag();
+ public static final TranslationTag TRANSLATE = new TranslationTag();
public static final FontStyleTag BOLD = new FontStyleTag("b", FontStyleTag.Style.BOLD);
public static final FontStyleTag ITALIC = new FontStyleTag("i", FontStyleTag.Style.ITALIC);
@@ -42,4 +51,44 @@ public class Tags {
public static final ColorTag LIGHT_CYAN = new ColorTag("lcyan", new String[]{"light_cyan"}, "#5edefd");
public static final ColorTag LIGHT_PURPLE = new ColorTag("lpurple", new String[]{"light_purple"}, "#e39fff");
public static final ColorTag LIGHT_PINK = new ColorTag("lpink", new String[]{"light_pink"}, "#fd8ddb");
+
+ static {
+ registerTags(
+ Tags.BLACK, Tags.WHITE, Tags.GRAY, Tags.GREEN,
+ Tags.YELLOW, Tags.ORANGE, Tags.RED,
+ Tags.BLUE, Tags.CYAN, Tags.PURPLE, Tags.PINK,
+
+ Tags.DARK_GRAY, Tags.LIGHT_GRAY, Tags.LIGHT_GREEN,
+ Tags.LIGHT_YELLOW, Tags.LIGHT_ORANGE, Tags.LIGHT_RED,
+ Tags.LIGHT_BLUE, Tags.LIGHT_CYAN, Tags.LIGHT_PURPLE, Tags.LIGHT_PINK
+ );
+
+ registerTags(Tags.BOLD, Tags.ITALIC, Tags.OBFUSCATED, Tags.STRIKETHROUGH, Tags.UNDERLINED);
+
+ registerTags(Tags.GRADIENT, Tags.LINE_BREAK, Tags.FONT, Tags.HOVER, Tags.CLICK,
+ Tags.RESET, Tags.HEX_COLOR, Tags.HEX_COLOR_SHORT, Tags.TRANSLATE);
+ }
+
+ @NotNull
+ public static Collection getTags() {
+ return REGISTRY.values();
+ }
+
+ public static void registerTags(@NotNull Tag... tags) {
+ for (Tag tag : tags) {
+ registerTag(tag);
+ }
+ }
+
+ public static void registerTag(@NotNull Tag tag) {
+ REGISTRY.put(tag.getName(), tag);
+ for (String alias : tag.getAliases()) {
+ REGISTRY.put(alias, tag);
+ }
+ }
+
+ @Nullable
+ public static Tag getTag(@NotNull String name) {
+ return REGISTRY.get(name.toLowerCase());
+ }
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ComplexTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ComplexTag.java
new file mode 100644
index 0000000..35d6f52
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ComplexTag.java
@@ -0,0 +1,27 @@
+package su.nightexpress.nightcore.util.text.tag.api;
+
+import org.jetbrains.annotations.NotNull;
+
+public class ComplexTag extends Tag {
+
+ public ComplexTag(@NotNull String name) {
+ super(name);
+ }
+
+ public ComplexTag(@NotNull String name, @NotNull String[] aliases) {
+ super(name, aliases);
+ }
+
+ @NotNull
+ protected String escapeQuotes(@NotNull String content) {
+ return content.replace("'", "\\'").replace("\"", "\\\"");
+ }
+
+ @NotNull
+ public String encloseContent(@NotNull String text, @NotNull String content) {
+ String tagOpen = brackets(this.getName() + ":" + content);
+ String tagClose = this.getClosingName();
+
+ return tagOpen + text + tagClose;
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java
index a9cba84..fac0523 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java
@@ -2,33 +2,10 @@ package su.nightexpress.nightcore.util.text.tag.api;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.text.decoration.DecoratorParser;
-import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator;
+import su.nightexpress.nightcore.util.text.tag.decorator.Decorator;
-public abstract class ContentTag extends DynamicTag implements DecoratorParser {
-
- public ContentTag(@NotNull String name) {
- super(name);
- }
-
- @Override
- @Nullable
- public final ParsedDecorator parse(@NotNull String str) {
- int tagLength = this.getName().length();
- String sub = str.substring(tagLength);
-
- if (sub.charAt(0) == ':') {
- sub = sub.substring(1);
- tagLength += 1;
- }
-
- ParsedDecorator decorator = this.onParse(sub);
- if (decorator != null) {
- decorator.setLength(decorator.getLength() + tagLength + 2); // 2 for quotes
- }
- return decorator;
- }
+public interface ContentTag {
@Nullable
- protected abstract ParsedDecorator onParse(@NotNull String sub);
+ Decorator parse(@NotNull String str);
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/DynamicTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/DynamicTag.java
deleted file mode 100644
index 7e06267..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/DynamicTag.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package su.nightexpress.nightcore.util.text.tag.api;
-
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-public abstract class DynamicTag extends Tag {
-
- public DynamicTag(@NotNull String name) {
- super(name);
- }
-
- @NotNull
- protected final String leading(@Nullable String prefix, @NotNull String content) {
- if (prefix != null) prefix += ":";
-
- StringBuilder builder = new StringBuilder();
- builder.append(this.getName()).append(":");
- if (prefix != null) {
- builder.append(prefix);
- }
- builder.append("'").append(content).append("'");
-
- return brackets(builder.toString());
- }
-
- @NotNull
- protected final String enclose(@Nullable String prefix, @NotNull String content, @NotNull String text) {
- return leading(prefix, content) + text + this.getClosingName();
- }
-
- /*@Nullable
- @Deprecated
- public static String parseQuotedContent(@NotNull String string) {
- char quote = string.charAt(0);
- if (quote != '\'' && quote != '"') return null;
-
- int indexEnd = -1;
- for (int index = 0; index < string.length(); index++) {
- if (index == (string.length() - 1) || index == 0) continue;
-
- char letter = string.charAt(index);
- if (letter == '\\') {
- index++;
- continue;
- }
- if (letter != quote) continue;
-
- char next = string.charAt(index + 1);
- if (next == Tag.CLOSE_BRACKET) {
- indexEnd = index;
- break;
- }
- }
- if (indexEnd == -1) return null;
-
- return string.substring(1, indexEnd);
- }*/
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/OrphanTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/PlaceholderTag.java
similarity index 60%
rename from src/main/java/su/nightexpress/nightcore/util/text/tag/api/OrphanTag.java
rename to src/main/java/su/nightexpress/nightcore/util/text/tag/api/PlaceholderTag.java
index 6eaef13..816001a 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/OrphanTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/PlaceholderTag.java
@@ -2,7 +2,7 @@ package su.nightexpress.nightcore.util.text.tag.api;
import org.jetbrains.annotations.NotNull;
-public interface OrphanTag {
+public interface PlaceholderTag {
- @NotNull String getContent();
+ @NotNull String getValue();
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/SimpleTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/SimpleTag.java
new file mode 100644
index 0000000..2fb3ccf
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/SimpleTag.java
@@ -0,0 +1,19 @@
+package su.nightexpress.nightcore.util.text.tag.api;
+
+import org.jetbrains.annotations.NotNull;
+
+public class SimpleTag extends Tag {
+
+ public SimpleTag(@NotNull String name) {
+ super(name);
+ }
+
+ public SimpleTag(@NotNull String name, @NotNull String[] aliases) {
+ super(name, aliases);
+ }
+
+ @NotNull
+ public String enclose(@NotNull String text) {
+ return this.getBracketsName() + text + this.getClosingName();
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java
index 37a85a9..7261a38 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java
@@ -2,14 +2,17 @@ package su.nightexpress.nightcore.util.text.tag.api;
import org.jetbrains.annotations.NotNull;
-public abstract class Tag {
+import java.util.HashSet;
+import java.util.Set;
+
+public class Tag {
public static final char OPEN_BRACKET = '<';
public static final char CLOSE_BRACKET = '>';
- public static final char CLOSE_MARK = '/';
+ public static final char CLOSE_SLASH = '/';
- protected final String name;
- protected final String[] aliases;
+ protected final String name;
+ protected final Set aliases;
public Tag(@NotNull String name) {
this(name, new String[0]);
@@ -17,7 +20,11 @@ public abstract class Tag {
public Tag(@NotNull String name, @NotNull String[] aliases) {
this.name = name.toLowerCase();
- this.aliases = aliases;
+ this.aliases = new HashSet<>();
+
+ for (String alias : aliases) {
+ this.aliases.add(alias.toLowerCase());
+ }
}
@NotNull
@@ -25,35 +32,40 @@ public abstract class Tag {
return OPEN_BRACKET + str + CLOSE_BRACKET;
}
- @NotNull
- public String getName() {
- return name;
- }
-
- @NotNull
- public String[] getAliases() {
- return aliases;
- }
-
- @NotNull
+ /*@NotNull
+ @Deprecated
public String enclose(@NotNull String text) {
- return this.getFullName() + text + this.getClosingName();
- }
-
- public abstract int getWeight();
+ return this.getBracketsName() + text + this.getClosingName();
+ }*/
@NotNull
+ @Deprecated
public final String getFullName() {
- return brackets(this.getName());
+ return this.getBracketsName();
}
@NotNull
public final String getClosingName() {
- return brackets(CLOSE_MARK + this.getName());
+ return brackets(CLOSE_SLASH + this.getName());
}
- public boolean conflictsWith(@NotNull Tag tag) {
- return tag.getName().equalsIgnoreCase(this.getName());
+ public final boolean isNamed(@NotNull String name) {
+ return this.name.equalsIgnoreCase(name) || this.aliases.contains(name.toLowerCase());
+ }
+
+ @NotNull
+ public final String getBracketsName() {
+ return brackets(this.getName());
+ }
+
+ @NotNull
+ public final String getName() {
+ return this.name;
+ }
+
+ @NotNull
+ public final Set getAliases() {
+ return this.aliases;
}
@Override
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ColorDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/BaseColorDecorator.java
similarity index 67%
rename from src/main/java/su/nightexpress/nightcore/util/text/decoration/ColorDecorator.java
rename to src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/BaseColorDecorator.java
index b8c3415..dbd43ed 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ColorDecorator.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/BaseColorDecorator.java
@@ -1,4 +1,4 @@
-package su.nightexpress.nightcore.util.text.decoration;
+package su.nightexpress.nightcore.util.text.tag.decorator;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
@@ -6,11 +6,11 @@ import org.jetbrains.annotations.NotNull;
import java.awt.*;
-public class ColorDecorator implements Decorator {
+public class BaseColorDecorator implements ColorDecorator {
private final Color color;
- public ColorDecorator(@NotNull Color color) {
+ public BaseColorDecorator(@NotNull Color color) {
this.color = color;
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ClickEventDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ClickDecorator.java
similarity index 67%
rename from src/main/java/su/nightexpress/nightcore/util/text/decoration/ClickEventDecorator.java
rename to src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ClickDecorator.java
index f21d1ef..55f4dd4 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ClickEventDecorator.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ClickDecorator.java
@@ -1,15 +1,15 @@
-package su.nightexpress.nightcore.util.text.decoration;
+package su.nightexpress.nightcore.util.text.tag.decorator;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import org.jetbrains.annotations.NotNull;
-public class ClickEventDecorator implements Decorator {
+public class ClickDecorator implements Decorator {
private final ClickEvent.Action action;
- private final String value;
+ private final String value;
- public ClickEventDecorator(@NotNull ClickEvent.Action action, @NotNull String value) {
+ public ClickDecorator(@NotNull ClickEvent.Action action, @NotNull String value) {
this.action = action;
this.value = value;
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ColorDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ColorDecorator.java
new file mode 100644
index 0000000..13fb43b
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ColorDecorator.java
@@ -0,0 +1,6 @@
+package su.nightexpress.nightcore.util.text.tag.decorator;
+
+public interface ColorDecorator extends Decorator {
+
+ // Exists just to clarify color decorators.
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/Decorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/Decorator.java
similarity index 74%
rename from src/main/java/su/nightexpress/nightcore/util/text/decoration/Decorator.java
rename to src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/Decorator.java
index d6912bf..6d59e55 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/Decorator.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/Decorator.java
@@ -1,4 +1,4 @@
-package su.nightexpress.nightcore.util.text.decoration;
+package su.nightexpress.nightcore.util.text.tag.decorator;
import net.md_5.bungee.api.chat.BaseComponent;
import org.jetbrains.annotations.NotNull;
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/FontDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/FontDecorator.java
similarity index 86%
rename from src/main/java/su/nightexpress/nightcore/util/text/decoration/FontDecorator.java
rename to src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/FontDecorator.java
index 2f8569a..eda59ba 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/FontDecorator.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/FontDecorator.java
@@ -1,4 +1,4 @@
-package su.nightexpress.nightcore.util.text.decoration;
+package su.nightexpress.nightcore.util.text.tag.decorator;
import net.md_5.bungee.api.chat.BaseComponent;
import org.jetbrains.annotations.NotNull;
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/GradientColorDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/GradientColorDecorator.java
new file mode 100644
index 0000000..0987895
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/GradientColorDecorator.java
@@ -0,0 +1,103 @@
+package su.nightexpress.nightcore.util.text.tag.decorator;
+
+import net.md_5.bungee.api.ChatColor;
+import net.md_5.bungee.api.chat.BaseComponent;
+import net.md_5.bungee.api.chat.TextComponent;
+import org.jetbrains.annotations.NotNull;
+
+import java.awt.*;
+
+public class GradientColorDecorator implements ColorDecorator {
+
+ private final Color color;
+ private final Color colorEnd;
+
+ private Color[] colors;
+ private int colorIndex;
+
+ public GradientColorDecorator(@NotNull Color color, @NotNull Color colorEnd) {
+ this.color = color;
+ this.colorEnd = colorEnd;
+ }
+
+ @NotNull
+ public Color getColor() {
+ return color;
+ }
+
+ @NotNull
+ public Color getColorEnd() {
+ return colorEnd;
+ }
+
+ public boolean isCreated() {
+ return this.colors != null && this.colors.length > 0;
+ }
+
+ public boolean hasNextColor() {
+ return this.isCreated() && this.colorIndex < this.colors.length;
+ }
+
+ public Color[] createGradient(int length) {
+ this.colors = new Color[length];
+ for (int index = 0; index < length; index++) {
+ double percent = (double) index / (double) length;
+
+ int red = (int) (color.getRed() + percent * (colorEnd.getRed() - color.getRed()));
+ int green = (int) (color.getGreen() + percent * (colorEnd.getGreen() - color.getGreen()));
+ int blue = (int) (color.getBlue() + percent * (colorEnd.getBlue() - color.getBlue()));
+
+ java.awt.Color color = new java.awt.Color(red, green, blue);
+ this.colors[index] = color;
+ }
+ return this.colors;
+ }
+
+ public Color[] getColors() {
+ return colors;
+ }
+
+ public Color nextColor() {
+ return this.colors[this.colorIndex++];
+ }
+
+ public Color getLatestcColor() {
+ return this.colors[this.colors.length - 1];
+ }
+
+ @Override
+ public void decorate(@NotNull BaseComponent component) {
+ if (component instanceof TextComponent textComponent) {
+ int length = 0;
+
+ //if (textComponent.getText().equals("\n")) return; // Do not 'spend' colors on line breaks.
+
+ for (char letter : textComponent.getText().toCharArray()) {
+ if (!Character.isWhitespace(letter)) length++;
+
+ textComponent.addExtra(new TextComponent(String.valueOf(letter)));
+ }
+
+ if (!this.isCreated()) {
+ this.createGradient(length);
+ }
+
+ textComponent.setText("");
+ textComponent.getExtra().forEach(extra -> {
+ if (extra instanceof TextComponent extraText && extraText.getText().isBlank()) return;
+
+ if (this.hasNextColor()) {
+ extra.setColor(ChatColor.of(this.nextColor()));
+ }
+ });
+
+ return;
+ }
+
+ if (!this.isCreated()) this.createGradient(1);
+
+ if (this.hasNextColor()) {
+ component.setColor(ChatColor.of(this.nextColor()));
+ }
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowItemDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowItemDecorator.java
similarity index 74%
rename from src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowItemDecorator.java
rename to src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowItemDecorator.java
index 9e3499b..7250692 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowItemDecorator.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowItemDecorator.java
@@ -1,31 +1,27 @@
-package su.nightexpress.nightcore.util.text.decoration;
+package su.nightexpress.nightcore.util.text.tag.decorator;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.ItemTag;
import net.md_5.bungee.api.chat.hover.content.Item;
+import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.util.BukkitThing;
import su.nightexpress.nightcore.util.ItemNbt;
-import su.nightexpress.nightcore.util.ItemUtil;
public class ShowItemDecorator implements Decorator {
- //private final ItemStack item;
private final String itemData;
public static ShowItemDecorator from(@NotNull ItemStack item) {
String content = ItemNbt.compress(item);
return new ShowItemDecorator(content == null ? BukkitThing.toString(item.getType()) : content);
- //this.item = item == null ? new ItemStack(Material.AIR) : new ItemStack(item);
- //this(ItemUtil.compress(item));
}
public ShowItemDecorator(@NotNull String string) {
- //this(ItemUtil.decompress(string));
this.itemData = string;
}
@@ -33,11 +29,10 @@ public class ShowItemDecorator implements Decorator {
public HoverEvent createEvent() {
ItemStack itemStack = null;
- Material material = Material.getMaterial(this.itemData.toUpperCase());
- if (material != null) {
- itemStack = new ItemStack(material);
+ try {
+ itemStack = Bukkit.getItemFactory().createItemStack(this.itemData);
}
- else {
+ catch (IllegalArgumentException exception) {
try {
itemStack = ItemNbt.decompress(this.itemData);
}
@@ -47,7 +42,7 @@ public class ShowItemDecorator implements Decorator {
}
if (itemStack == null) itemStack = new ItemStack(Material.AIR);
- String key = itemStack.getType().getKey().getKey();
+ String key = BukkitThing.toString(itemStack.getType());
ItemMeta meta = itemStack.getItemMeta();
Item item = new Item(key, itemStack.getAmount(), ItemTag.ofNbt(meta == null ? null : meta.getAsString()));
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowTextDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowTextDecorator.java
similarity index 83%
rename from src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowTextDecorator.java
rename to src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowTextDecorator.java
index 3d186e7..ea7f1ed 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowTextDecorator.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/decorator/ShowTextDecorator.java
@@ -1,12 +1,12 @@
-package su.nightexpress.nightcore.util.text.decoration;
+package su.nightexpress.nightcore.util.text.tag.decorator;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.hover.content.Text;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.util.Lists;
+import su.nightexpress.nightcore.util.Placeholders;
import su.nightexpress.nightcore.util.text.NightMessage;
-import su.nightexpress.nightcore.util.text.tag.Tags;
import java.util.List;
@@ -24,7 +24,7 @@ public class ShowTextDecorator implements Decorator {
@NotNull
public HoverEvent createEvent() {
- String fused = String.join(Tags.LINE_BREAK.getFullName(), this.text);
+ String fused = String.join(Placeholders.TAG_LINE_BREAK, this.text);
Text text = new Text(NightMessage.parse(fused));
return new HoverEvent(HoverEvent.Action.SHOW_TEXT, text);
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java
index 8282b36..60ad97c 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java
@@ -1,15 +1,15 @@
package su.nightexpress.nightcore.util.text.tag.impl;
import net.md_5.bungee.api.chat.ClickEvent;
+import net.md_5.bungee.api.chat.HoverEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.StringUtil;
-import su.nightexpress.nightcore.util.text.decoration.ClickEventDecorator;
-import su.nightexpress.nightcore.util.text.decoration.Decorator;
-import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator;
+import su.nightexpress.nightcore.util.text.TextRoot;
+import su.nightexpress.nightcore.util.text.tag.api.ComplexTag;
+import su.nightexpress.nightcore.util.text.tag.decorator.ClickDecorator;
import su.nightexpress.nightcore.util.text.tag.api.ContentTag;
-public class ClickTag extends ContentTag {
+public class ClickTag extends ComplexTag implements ContentTag {
public static final String NAME = "click";
@@ -17,23 +17,37 @@ public class ClickTag extends ContentTag {
super(NAME);
}
- @Override
- public int getWeight() {
- return 50;
+ @NotNull
+ public String encloseRun(@NotNull String text, @NotNull String command) {
+ return this.enclose(text, ClickEvent.Action.RUN_COMMAND, command);
}
@NotNull
- public String enclose(@NotNull ClickEvent.Action action, @NotNull String text, @NotNull String command) {
- String actionName = action.name().toLowerCase();
- return this.enclose(actionName, command, text);
+ @Deprecated
+ public String enclose(@NotNull ClickEvent.Action action, @NotNull String text, @NotNull String content) {
+ return this.enclose(text, action, content);
+ }
+
+ @NotNull
+ public String enclose(@NotNull String text, @NotNull ClickEvent.Action action, @NotNull String content) {
+ //content = content.replace("'", "\\'");
+
+ //String tagOpen = brackets(NAME + ":" + action.name().toLowerCase() + ":'" + content + "'");
+ //String tagClose = this.getClosingName();
+
+ //return tagOpen + text + tagClose;
+
+ String data = action.name().toLowerCase() + ":\"" + this.escapeQuotes(content) + "\"";
+
+ return this.encloseContent(text, data);
}
@Override
@Nullable
- public ParsedDecorator onParse(@NotNull String sub) {
+ public ClickDecorator parse(@NotNull String tagContent) {
ClickEvent.Action action = null;
for (ClickEvent.Action global : ClickEvent.Action.values()) {
- if (sub.startsWith(global.name().toLowerCase())) {
+ if (tagContent.startsWith(global.name().toLowerCase())) {
action = global;
break;
}
@@ -41,15 +55,10 @@ public class ClickTag extends ContentTag {
if (action == null) return null;
int prefixSize = action.name().toLowerCase().length() + 1; // 1 for ':', like "run_command:"
- sub = sub.substring(prefixSize);
+ tagContent = tagContent.substring(prefixSize);
- String content = StringUtil.parseQuotedContent(sub);
- if (content == null) return null;
+ String value = TextRoot.stripQuotesSlash(tagContent);
- int length = prefixSize + content.length();// + 2; // 2 for quotes
-
- Decorator decorator = new ClickEventDecorator(action, content);
-
- return new ParsedDecorator(decorator, length);
+ return new ClickDecorator(action, value);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java
index 174da4f..66dc434 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java
@@ -3,12 +3,12 @@ package su.nightexpress.nightcore.util.text.tag.impl;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.text.decoration.Decorator;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
+import su.nightexpress.nightcore.util.text.tag.api.SimpleTag;
+import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator;
import java.awt.*;
-public class ColorTag extends Tag implements Decorator {
+public class ColorTag extends SimpleTag implements ColorDecorator {
protected final Color color;
@@ -37,21 +37,11 @@ public class ColorTag extends Tag implements Decorator {
this.color = color;
}
- @Override
- public int getWeight() {
- return 10;
- }
-
@NotNull
public Color getColor() {
return color;
}
- @Override
- public boolean conflictsWith(@NotNull Tag tag) {
- return tag instanceof ColorTag;
- }
-
@Override
public void decorate(@NotNull BaseComponent component) {
component.setColor(ChatColor.of(this.getColor()));
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java
index 707deee..7da6a07 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java
@@ -2,10 +2,10 @@ package su.nightexpress.nightcore.util.text.tag.impl;
import net.md_5.bungee.api.chat.BaseComponent;
import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.text.decoration.Decorator;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
+import su.nightexpress.nightcore.util.text.tag.api.SimpleTag;
+import su.nightexpress.nightcore.util.text.tag.decorator.Decorator;
-public class FontStyleTag extends Tag implements Decorator {
+public class FontStyleTag extends SimpleTag implements Decorator {
public enum Style {
BOLD, ITALIC, UNDERLINED, STRIKETHROUGH, OBFUSCATED
@@ -18,11 +18,6 @@ public class FontStyleTag extends Tag implements Decorator {
this.style = style;
}
- @Override
- public int getWeight() {
- return 0;
- }
-
@NotNull
public Style getStyle() {
return style;
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java
index 3d17047..fbfa105 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java
@@ -2,32 +2,19 @@ package su.nightexpress.nightcore.util.text.tag.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.StringUtil;
-import su.nightexpress.nightcore.util.text.decoration.FontDecorator;
-import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator;
+import su.nightexpress.nightcore.util.text.tag.api.ComplexTag;
import su.nightexpress.nightcore.util.text.tag.api.ContentTag;
+import su.nightexpress.nightcore.util.text.tag.decorator.FontDecorator;
-public class FontTag extends ContentTag {
-
- public static final String NAME = "font";
+public class FontTag extends ComplexTag implements ContentTag {
public FontTag() {
- super(NAME);
+ super("font");
}
@Override
@Nullable
- public ParsedDecorator onParse(@NotNull String str) {
- String content = StringUtil.parseQuotedContent(str);
- if (content == null) return null;
-
- int length = content.length();// + 2; // 2 for quotes
-
- return new ParsedDecorator(new FontDecorator(content), length);
- }
-
- @Override
- public int getWeight() {
- return 0;
+ public FontDecorator parse(@NotNull String str) {
+ return new FontDecorator(str);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java
index 67b735a..73e75de 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java
@@ -2,14 +2,13 @@ package su.nightexpress.nightcore.util.text.tag.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.text.decoration.DecoratorParser;
-import su.nightexpress.nightcore.util.text.decoration.GradientDecorator;
-import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator;
+import su.nightexpress.nightcore.util.text.tag.decorator.GradientColorDecorator;
+import su.nightexpress.nightcore.util.text.tag.api.ContentTag;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
import java.awt.*;
-public class GradientTag extends Tag implements DecoratorParser {
+public class GradientTag extends Tag implements ContentTag {
public static final String NAME = "gradient";
@@ -17,34 +16,19 @@ public class GradientTag extends Tag implements DecoratorParser {
super(NAME);
}
- @Override
- public int getWeight() {
- return Integer.MAX_VALUE - 1;
- }
-
- @Override
- public boolean conflictsWith(@NotNull Tag tag) {
- return super.conflictsWith(tag) || tag instanceof ColorTag || tag instanceof ShortHexColorTag || tag instanceof HexColorTag;
- }
-
@Override
@Nullable
- public ParsedDecorator parse(@NotNull String content) {
- int tagLength = this.getName().length() + 1; // 1 for semicolon
- content = content.substring(tagLength);
-
+ public GradientColorDecorator parse(@NotNull String content) {
String[] split = content.split(":");
if (split.length < 2) return null;
String code1 = split[0];
String code2 = split[1];
- //if (!code1.startsWith("#")) code1 = "#" + code1;
- //if (!code2.startsWith("#")) code2 = "#" + code2;
- //if (code1.length() != 7 || code2.length() != 7) return null;
Color from;
Color to;
+ // TODO Support for named colors
try {
from = Color.decode(code1);
to = Color.decode(code2);
@@ -53,8 +37,6 @@ public class GradientTag extends Tag implements DecoratorParser {
return null;
}
- GradientDecorator decorator = new GradientDecorator(from, to);
-
- return new ParsedDecorator(decorator, 15 + tagLength); // x2 hex (7+7), +1 for semicolon between
+ return new GradientColorDecorator(from, to);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java
index 103adc1..84014e6 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java
@@ -2,12 +2,13 @@ package su.nightexpress.nightcore.util.text.tag.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.text.decoration.*;
+import su.nightexpress.nightcore.util.text.tag.decorator.BaseColorDecorator;
+import su.nightexpress.nightcore.util.text.tag.api.ContentTag;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
import java.awt.*;
-public class HexColorTag extends Tag implements DecoratorParser {
+public class HexColorTag extends Tag implements ContentTag {
public static final String NAME = "color";
@@ -15,27 +16,14 @@ public class HexColorTag extends Tag implements DecoratorParser {
super(NAME);
}
- @Override
- public int getWeight() {
- return 10;
- }
-
- @Override
- public boolean conflictsWith(@NotNull Tag tag) {
- return tag instanceof ColorTag || tag instanceof HexColorTag;
- }
-
@Override
@Nullable
- public ParsedDecorator parse(@NotNull String content) {
- int tagLength = this.getName().length() + 1; // 1 for semicolon
- content = content.substring(tagLength);
+ public BaseColorDecorator parse(@NotNull String tagContent) {
+ if (tagContent.length() < 7) return null;
try {
- Color color = Color.decode(content);
- ColorDecorator decorator = new ColorDecorator(color);
-
- return new ParsedDecorator(decorator, 7 + tagLength);
+ Color color = Color.decode(tagContent);
+ return new BaseColorDecorator(color);
}
catch (NumberFormatException exception) {
return null;
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java
index 614de74..51d3404 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java
@@ -3,14 +3,14 @@ package su.nightexpress.nightcore.util.text.tag.impl;
import net.md_5.bungee.api.chat.HoverEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.StringUtil;
-import su.nightexpress.nightcore.util.text.decoration.Decorator;
-import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator;
-import su.nightexpress.nightcore.util.text.decoration.ShowItemDecorator;
-import su.nightexpress.nightcore.util.text.decoration.ShowTextDecorator;
+import su.nightexpress.nightcore.util.text.TextRoot;
+import su.nightexpress.nightcore.util.text.tag.api.ComplexTag;
import su.nightexpress.nightcore.util.text.tag.api.ContentTag;
+import su.nightexpress.nightcore.util.text.tag.decorator.Decorator;
+import su.nightexpress.nightcore.util.text.tag.decorator.ShowItemDecorator;
+import su.nightexpress.nightcore.util.text.tag.decorator.ShowTextDecorator;
-public class HoverTag extends ContentTag {
+public class HoverTag extends ComplexTag implements ContentTag {
public static final String NAME = "hover";
@@ -18,32 +18,42 @@ public class HoverTag extends ContentTag {
super(NAME);
}
- @Override
- public int getWeight() {
- return 50;
- }
-
- /*@Override
- public boolean isDynamicSize() {
- return true;
- }*/
-
@NotNull
+ @Deprecated
public String enclose(@NotNull String text, @NotNull String hint) {
- return this.enclose(HoverEvent.Action.SHOW_TEXT, text, hint);
+ return this.encloseHint(text, hint);
}
@NotNull
- public String enclose(@NotNull HoverEvent.Action action, @NotNull String text, @NotNull String hint) {
- return this.enclose(action.name().toLowerCase(), hint, text);
+ @Deprecated
+ public String enclose(@NotNull HoverEvent.Action action, @NotNull String text, @NotNull String content) {
+ return this.enclose(text, action, content);
+ }
+
+ @NotNull
+ public String encloseHint(@NotNull String text, @NotNull String hint) {
+ return this.enclose(text, HoverEvent.Action.SHOW_TEXT, hint);
+ }
+
+ @NotNull
+ public String enclose(@NotNull String text, @NotNull HoverEvent.Action action, @NotNull String content) {
+ //content = content.replace("'", "\\'");
+
+ //String tagOpen = brackets(NAME + ":" + action.name().toLowerCase() + ":'" + content + "'");
+ //String tagClose = this.getClosingName();
+
+ String data = action.name().toLowerCase() + ":'" + this.escapeQuotes(content) + "'";
+ return this.encloseContent(text, data);
+
+ //return tagOpen + text + tagClose;
}
@Override
@Nullable
- public ParsedDecorator onParse(@NotNull String sub) {
+ public Decorator parse(@NotNull String tagContent) {
HoverEvent.Action action = null;
for (HoverEvent.Action global : HoverEvent.Action.values()) {
- if (sub.startsWith(global.name().toLowerCase())) {
+ if (tagContent.startsWith(global.name().toLowerCase())) {
action = global;
break;
}
@@ -51,30 +61,16 @@ public class HoverTag extends ContentTag {
if (action == null) return null;
int prefixSize = action.name().toLowerCase().length() + 1; // 1 for ':', like "show_text:"
- sub = sub.substring(prefixSize);
+ tagContent = tagContent.substring(prefixSize);
- String content = StringUtil.parseQuotedContent(sub);
- if (content == null) return null;
+ String value = TextRoot.stripQuotesSlash(tagContent);
- int length = prefixSize + content.length();// + 2; // 2 for quotes
-
- Decorator decorator;
if (action == HoverEvent.Action.SHOW_TEXT) {
- decorator = new ShowTextDecorator(content);
+ return new ShowTextDecorator(value);
}
- else if (action == HoverEvent.Action.SHOW_ITEM) {
- /*ItemStack item;
-
- Material material = Material.getMaterial(content.toUpperCase());
- if (material != null) {
- item = new ItemStack(material);
- }
- else item = ItemUtil.decompress(content);*/
-
- decorator = new ShowItemDecorator(content);
+ else if (action == HoverEvent.Action.SHOW_ITEM) {
+ return new ShowItemDecorator(value);
}
- else return null;
-
- return new ParsedDecorator(decorator, length);
+ return null;
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java
index 964e227..63fdbac 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java
@@ -1,23 +1,18 @@
package su.nightexpress.nightcore.util.text.tag.impl;
import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.text.tag.api.OrphanTag;
+import su.nightexpress.nightcore.util.text.tag.api.PlaceholderTag;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
-public class LineBreakTag extends Tag implements OrphanTag {
+public class LineBreakTag extends Tag implements PlaceholderTag {
public LineBreakTag() {
- super("br");
- }
-
- @Override
- public int getWeight() {
- return 0;
+ super("newline", new String[]{"br"});
}
@Override
@NotNull
- public String getContent() {
+ public String getValue() {
return "\n";
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java
index ece94e1..1093da9 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java
@@ -1,32 +1,13 @@
package su.nightexpress.nightcore.util.text.tag.impl;
-import net.md_5.bungee.api.chat.BaseComponent;
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.text.decoration.Decorator;
+import su.nightexpress.nightcore.util.text.tag.api.SimpleTag;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
-public class ResetTag extends Tag implements Decorator {
+public class ResetTag extends SimpleTag { // TODO Must be just Tag, SimpleTag for compatibility
+
+ public static final String NAME = "reset";
public ResetTag() {
- super("r");
- }
-
- @Override
- public int getWeight() {
- return Integer.MAX_VALUE;
- }
-
- @Override
- public void decorate(@NotNull BaseComponent component) {
- component.setColor(null);
- component.setBold(false);
- component.setItalic(false);
- component.setObfuscated(false);
- component.setUnderlined(false);
- component.setStrikethrough(false);
- component.setFont(null);
- component.setInsertion(null);
- component.setHoverEvent(null);
- component.setClickEvent(null);
+ super(NAME, new String[]{"r"});
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ShortHexColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ShortHexColorTag.java
index d711e6f..6acb2f7 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ShortHexColorTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ShortHexColorTag.java
@@ -2,41 +2,31 @@ package su.nightexpress.nightcore.util.text.tag.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.text.decoration.DecoratorParser;
-import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator;
+import su.nightexpress.nightcore.util.text.tag.decorator.BaseColorDecorator;
+import su.nightexpress.nightcore.util.text.tag.api.ContentTag;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
import java.awt.*;
-@Deprecated
-public class ShortHexColorTag extends Tag implements DecoratorParser {
+public class ShortHexColorTag extends Tag implements ContentTag {
+
+ public static final String NAME = "#";
public ShortHexColorTag() {
- super("#");
- }
-
- @Override
- public int getWeight() {
- return 10;
- }
-
- @Override
- public boolean conflictsWith(@NotNull Tag tag) {
- return super.conflictsWith(tag) || tag instanceof ColorTag || tag instanceof GradientTag;
+ super(NAME);
}
@Override
@Nullable
- public ParsedDecorator parse(@NotNull String content) {
- Color color;
+ public BaseColorDecorator parse(@NotNull String tagContent) {
+ if (tagContent.length() < 7) return null;
try {
- color = Color.decode(content);
+ Color color = Color.decode(tagContent);
+ return new BaseColorDecorator(color);
}
catch (NumberFormatException exception) {
return null;
}
-
- return new ParsedDecorator(new ColorTag(color), 7);
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/TranslateTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/TranslateTag.java
deleted file mode 100644
index 24d97d3..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/TranslateTag.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package su.nightexpress.nightcore.util.text.tag.impl;
-
-import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.TextComponent;
-import net.md_5.bungee.api.chat.TranslatableComponent;
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.text.decoration.Decorator;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
-
-public class TranslateTag extends Tag implements Decorator {
-
- public static final String NAME = "translate";
-
- public TranslateTag() {
- super(NAME, new String[]{"tr"});
- }
-
- @Override
- public int getWeight() {
- return Integer.MAX_VALUE - 10;
- }
-
- @Override
- public void decorate(@NotNull BaseComponent component) {
- if (!(component instanceof TextComponent textComponent)) return;
-
- String content = textComponent.getText();
- textComponent.setText("");
-
- TranslatableComponent translatableComponent = new TranslatableComponent(content);
- component.addExtra(translatableComponent);
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/TranslationTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/TranslationTag.java
new file mode 100644
index 0000000..9cb2c67
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/TranslationTag.java
@@ -0,0 +1,12 @@
+package su.nightexpress.nightcore.util.text.tag.impl;
+
+import su.nightexpress.nightcore.util.text.tag.api.Tag;
+
+public class TranslationTag extends Tag {
+
+ public static final String NAME = "translation";
+
+ public TranslationTag() {
+ super(NAME, new String[]{"tr", "lang"});
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java
index edcb0b1..8e1d2d2 100644
--- a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java
+++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java
@@ -9,9 +9,9 @@ public final class UniInt {
private final int minInclusive;
private final int maxInclusive;
- private UniInt(int var0, int var1) {
- this.minInclusive = var0;
- this.maxInclusive = var1;
+ private UniInt(int min, int max) {
+ this.minInclusive = min;
+ this.maxInclusive = max;
}
@NotNull
@@ -20,15 +20,15 @@ public final class UniInt {
}
@NotNull
- public static UniInt read(@NotNull FileConfig cfg, @NotNull String path) {
- int min = cfg.getInt(path + ".Min");
- int max = cfg.getInt(path + ".Max");
+ public static UniInt read(@NotNull FileConfig config, @NotNull String path) {
+ int min = config.getInt(path + ".Min");
+ int max = config.getInt(path + ".Max");
return of(min, max);
}
- public void write(@NotNull FileConfig cfg, @NotNull String path) {
- cfg.set(path + ".Min", this.getMinValue());
- cfg.set(path + ".Max", this.getMaxValue());
+ public void write(@NotNull FileConfig config, @NotNull String path) {
+ config.set(path + ".Min", this.getMinValue());
+ config.set(path + ".Max", this.getMaxValue());
}
public int roll() {
diff --git a/src/main/resources/lang/messages_cn.yml b/src/main/resources/lang/messages_cn.yml
new file mode 100644
index 0000000..15e5781
--- /dev/null
+++ b/src/main/resources/lang/messages_cn.yml
@@ -0,0 +1,111 @@
+Command:
+ Help:
+ List:
+ -
+ - "&b%name% &8- &7命令:"
+ - " "
+ - "&c<> &8- &7必需 &8| &a[] &8- &7可选"
+ - " "
+ - "%entry%"
+ - " "
+ Entry: " &d/%command_label% %command_usage% &8- &7%command_description%"
+ Desc: 显示帮助页面
+ CheckPerm:
+ Desc: 打印玩家权限信息
+ Usage:
+ Reload:
+ Desc: 重新加载插件
+ Done: "&7插件 &a已重新加载!"
+ Argument:
+ Type:
+ Required: "&c<%name%>"
+ Optional: "&e[%name%]"
+ Name:
+ Generic: 值
+ Type: 类型
+ Name: 名字
+ Player: 玩家
+ World: 世界
+ Amount: 数量
+ Material: 材料
+ ItemMaterial: 物品类型
+ BlockMaterial: 方块类型
+ Enchantment: 附魔
+ Flag:
+ Format: "&7[%name%]"
+Time:
+ Day: "%amount%天"
+ Hour: "%amount%小时"
+ Min: "%amount%分钟"
+ Sec: "%amount%秒"
+ Delimiter: " "
+Other:
+ "Yes": "&a是"
+ "No": "&c否"
+ Enabled: "&a已启用"
+ Disabled: "&c已禁用"
+ Any: 任何
+ None: 无
+ Never: 从不
+ OneTimed: 一次性的
+ Unlimited: 无限的
+ Infinity: ∞
+Error:
+ Invalid_Player: "&c找不到玩家"
+ Invalid_World: "&c无效的世界"
+ Invalid_Number: "&e%value% &c不是一个有效的数字"
+ NoPermission: "&c你没有权限这样做!"
+ Command:
+ NotYourself: "&c此命令不能用于你自己。"
+ PlayerOnly: "&c此命令仅适用于玩家。"
+ Usage:
+ -
+ - "&c错误: &7错误的参数!"
+ - "&c用法: &d/%command_label% %command_usage%"
+ - " "
+ ParseFlag: "&c无效的值 &e%value% &7对应标志 &d%name%"
+ ParseArgument: "&c无效的值 &e%value% &7对应参数 &d%name%"
+ Argument:
+ InvalidPlayer: "&c找不到玩家 &a%value%!"
+ InvalidWorld: "&c找不到世界 &b%value%!"
+ InvalidNumber: "&e%value% &c不是一个有效的数字!"
+ InvalidMaterial: "&b%value% &c不是一个有效的材料!"
+ InvalidEnchantment: "&b%value% &c不是一个有效的附魔!"
+ InvalidMaterial: "&c无效的材料!"
+ InvalidEnchantment: "&c无效的附魔!"
+Editor:
+ Action:
+ Exit:
+ -
+ - "&7点击 &a[这里] &7以退出输入模式"
+ - " "
+ Input:
+ Header:
+ Main: "&a输入模式"
+ Error: "&c错误"
+ Error:
+ NotInteger: "&7期望 &c整数 数字!"
+ Generic: "&7无效的值!"
+ Generic:
+ Close:
+ Name: "&c退出"
+ Lore: []
+ Return:
+ Name: "&7返回"
+ Lore: []
+ NextPage:
+ Name: "&7下一页"
+ Lore: []
+ PreviousPage:
+ Name: "&7上一页"
+ Lore: []
+Number:
+ Thousand: 千
+ Million: 百万
+ Billion: 十亿
+ Trillion: 万亿
+ Quadrillion: 亿亿
+Entry:
+ Good: "&a✔ &7%entry%"
+ Bad: "&c✘ &7%entry%"
+ Warn: "&7[&6!&7] &7%entry%"