v2.6.2, better tags handling

This commit is contained in:
nulli0n committed 2024-06-09 16:15:51 +05:00
1 parent 34c4e34e1f
commit 2f9ba7d063
91 files changed
+1681 -1557

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>su.nightexpress.nightcore</groupId>
<artifactId>nightcore</artifactId>
<version>2.6.1</version>
<version>2.6.2</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
@@ -5,10 +5,7 @@ import su.nightexpress.nightcore.database.AbstractUserDataHandler;
import su.nightexpress.nightcore.database.AbstractUserManager;
import su.nightexpress.nightcore.database.DataUser;
public abstract class NightDataPlugin<U extends DataUser> extends NightPlugin /*implements UserDataHolder*/ {
//protected AbstractUserDataHandler<NexDataPlugin<U>, U> dataHandler;
//protected AbstractUserManager<NexDataPlugin<U>, U> userManager;
public abstract class NightDataPlugin<U extends DataUser> extends NightPlugin {
@Override
protected void loadManagers() {
@@ -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
@@ -65,7 +65,8 @@ public class RootCommand<P extends NightCorePlugin, S extends CommandNode> 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);
}
@@ -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<T> {
private final String name;
private final Function<String, T> parser;
private final boolean required;
private final boolean complex;
private final String localized;
private final String permission;
private final Function<TabContext, List<String>> samples;
@@ -26,6 +28,7 @@ public class CommandArgument<T> {
public CommandArgument(@NotNull String name,
@NotNull Function<String, T> parser,
boolean required,
boolean complex,
@Nullable String localized,
@Nullable String permission,
@Nullable LangMessage failureMessage,
@@ -33,6 +36,7 @@ public class CommandArgument<T> {
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<T> {
@NotNull
public List<String> 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<T> {
return required;
}
public boolean isComplex() {
return complex;
}
@NotNull
public String getLocalized() {
return this.localized == null ? this.name : this.localized;
@@ -14,14 +14,15 @@ import java.util.function.Function;
public class ArgumentBuilder<T> {
private final String name;
private final Function<String, T> parser;
protected final String name;
protected final Function<String, T> parser;
private boolean required;
private String localized;
private String permission;
private Function<TabContext, List<String>> samples;
private LangMessage failureMessage;
protected boolean required;
protected boolean complex;
protected String localized;
protected String permission;
protected Function<TabContext, List<String>> samples;
protected LangMessage failureMessage;
public ArgumentBuilder(@NotNull String name, @NotNull Function<String, T> parser) {
this.name = name;
@@ -39,6 +40,12 @@ public class ArgumentBuilder<T> {
return this;
}
@NotNull
public ArgumentBuilder<T> complex() {
this.complex = true;
return this;
}
@NotNull
public ArgumentBuilder<T> localized(@NotNull LangString localized) {
return this.localized(localized.getString());
@@ -80,6 +87,6 @@ public class ArgumentBuilder<T> {
@NotNull
public CommandArgument<T> 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);
}
}
@@ -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<String> 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<String> getArgumentSamples(@NotNull CommandArgument<?> argument, @NotNull TabContext context) {
if (!argument.hasPermission(context.getSender())) return Collections.emptyList();
//System.out.println("argument = " + argument);
@@ -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
@@ -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");
@@ -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;
@@ -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<Boolean> 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<Boolean> LEGACY_COLOR_SUPPORT = ConfigValue.create("Engine.Legacy_Color_Support",
@@ -82,9 +81,9 @@ public class CoreConfig {
"[Default is false]");
public static final ConfigValue<UniFormatter> 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"
);
}
@@ -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."),
"");
@@ -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<NightCore> {
menu.getOptions().setLastAutoRefresh(System.currentTimeMillis());
}
});
Dialog.checkTimeOut();
}).setSecondsInterval(1));
}
@@ -17,8 +17,6 @@ public class CoreListener extends AbstractListener<NightCore> {
@EventHandler(priority = EventPriority.NORMAL)
public void onServiceRegisterEvent(ServiceRegisterEvent event) {
//if (!Plugins.hasVault()) return;
if (Plugins.isLoaded(Plugins.VAULT)) {
VaultHook.onServiceRegisterEvent(event);
}
@@ -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);
@@ -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<P extends NightCorePlugin> extends SimpleManager<P> {
public abstract class AbstractDataHandler<P extends NightCorePlugin> extends AbstractManager<P> {
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<P extends NightCorePlugin> 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
@@ -31,7 +31,7 @@ public abstract class AbstractUserDataHandler<P extends NightDataPlugin<U>, U ex
protected final Set<String> existNames;
public AbstractUserDataHandler(@NotNull P plugin) {
this(plugin, DatabaseConfig.read(plugin));
this(plugin, getDataConfig(plugin));
}
public AbstractUserDataHandler(@NotNull P plugin, @NotNull DatabaseConfig config) {
@@ -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<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractManager<P> {
private final Map<UUID, U> loadedById;
private final Map<UUID, U> loadedById;
private final Map<String, U> loadedByName;
private final Set<U> 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<P extends NightDataPlugin<U>, 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<P extends NightDataPlugin<U>, 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<P extends NightDataPlugin<U>, U extend
return CompletableFuture.supplyAsync(() -> this.getUserData(uuid));
}
/**
* Performs an operation on the given user.<br>
* Runs immediately in the current thread if player is online or data is already loaded.<br>
* 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<U> consumer) {
this.manageUser(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer);
}
/**
* Performs an operation on the given user.<br>
* Runs immediately in the current thread if player is online or data is already loaded.<br>
* 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<U> consumer) {
this.manageUser(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer);
}
/**
* Performs an operation on the given user.<br>
* Runs immediately in the current thread if player is online or data is already loaded.<br>
* 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<U> consumer) {
this.manageUserSynchronized(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer);
}
/**
* Performs an operation on the given user.<br>
* Runs immediately in the current thread if player is online or data is already loaded.<br>
* 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<U> consumer) {
this.manageUserSynchronized(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer);
}
private void manageUser(@NotNull Supplier<U> loadedSupplier, @NotNull Supplier<CompletableFuture<U>> fetchSupplier, @NotNull Consumer<U> consumer) {
U user = loadedSupplier.get();
if (user != null) {
consumer.accept(user);
}
else fetchSupplier.get().thenAccept(consumer);
}
private void manageUserSynchronized(@NotNull Supplier<U> loadedSupplier, @NotNull Supplier<CompletableFuture<U>> fetchSupplier, @NotNull Consumer<U> consumer) {
this.manageUser(loadedSupplier, fetchSupplier, user -> this.plugin.runTask(task -> consumer.accept(user)));
}
@Deprecated
public void getUserDataAndPerform(@NotNull String name, Consumer<U> 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<U> 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<U> 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<U> 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<P extends NightDataPlugin<U>, 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<P extends NightDataPlugin<U>, 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
@@ -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,
@@ -44,6 +44,6 @@ public class UserListener<P extends NightDataPlugin<U>, U extends DataUser> exte
@EventHandler(priority = EventPriority.MONITOR)
public void onUserQuit(PlayerQuitEvent event) {
this.plugin.getUserManager().unload(event.getPlayer());
this.userManager.unload(event.getPlayer());
}
}
@@ -41,7 +41,7 @@ public final class DeleteQueryExecutor extends SQLExecutor<Void> {
@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() + " ?")
@@ -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<UUID, Dialog> 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<String> 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<String> values = this.getSuggestions();
if (values.isEmpty()) return;
@@ -83,80 +101,83 @@ public class Dialog {
List<String> 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)
@@ -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<NightCore> {
// TODO Timeout
public DialogListener(@NotNull NightCore plugin) {
super(plugin);
}
@@ -54,7 +51,7 @@ public class DialogListener extends AbstractListener<NightCore> {
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;
@@ -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() {
@@ -37,8 +37,8 @@ public class VaultHook {
@Nullable
private static <T> T getProvider(@NotNull Class<T> clazz) {
RegisteredServiceProvider<T> rsp = Bukkit.getServer().getServicesManager().getRegistration(clazz);
return rsp == null ? null : rsp.getProvider();
RegisteredServiceProvider<T> provider = Bukkit.getServer().getServicesManager().getRegistration(clazz);
return provider == null ? null : provider.getProvider();
}
private static void setPermission() {
@@ -102,7 +102,7 @@ public class LangAssets {
@NotNull
public static Optional<String> getAsset(@NotNull String path) {
return Optional.ofNullable(config.getString(path)).map(Colorizer::apply);
return Optional.ofNullable(config.getString(path));//.map(NightMessage::asLegacy);
}
@NotNull
@@ -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<NightCorePlugin> {
@@ -41,7 +42,12 @@ public class LangManager extends SimpleManager<NightCorePlugin> {
filePath = "/" + filePath;
}
return plugin.getClass().getResourceAsStream(filePath) != null;
try (InputStream inputStream = plugin.getClass().getResourceAsStream(filePath)) {
return inputStream != null;
}
catch (Exception ignored) {}
return false;
}
@NotNull
@@ -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<Pair<String, List<String>>> {
private String localizedName;
private List<String> localizedLore;
private WrappedMessage wrappedName;
private List<WrappedMessage> wrappedLore;
private TextRoot wrappedName;
private List<TextRoot> wrappedLore;
public LangItem(@NotNull String key, @NotNull String defaultName, @NotNull List<String> defaultLore) {
super(key, defaultName);
@@ -62,7 +62,7 @@ public class LangItem extends LangEntry<Pair<String, List<String>>> {
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<Pair<String, List<String>>> {
}
@NotNull
public WrappedMessage getWrappedName() {
public TextRoot getWrappedName() {
return wrappedName;
}
@NotNull
public List<WrappedMessage> getWrappedLore() {
public List<TextRoot> getWrappedLore() {
return wrappedLore;
}
@@ -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<String> {
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<String> {
}
@NotNull
public WrappedMessage getMessage() {
public TextRoot getMessage() {
return this.message;
}
@@ -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<String> 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<String> predicate, @NotNull BiConsumer<String, List<String>> replacer) {
if (this.isEmpty()) return this;
LangMessage msgCopy = new LangMessage(this);
List<String> replaced = new ArrayList<>();
List<String> 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]);
}
}
@@ -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);
}
@@ -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);
}
@@ -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<String, Tag> TAG_MAP = new HashMap<>();
private static final Map<String, MessageTag> 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<Tag> getTags() {
return TAG_MAP.values();
public static Collection<MessageTag> 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());
}
}
@@ -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);
}
}
@@ -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);
@@ -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);
}
}
@@ -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);
}
}
@@ -23,14 +23,6 @@ public interface AutoFilled<I> extends Menu {
void onAutoFill(@NotNull MenuViewer viewer, @NotNull AutoFill<I> autoFill);
/*@Deprecated int[] getAutoFillSlots();
@Deprecated @NotNull List<I> 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<I> autoFill = new AutoFill<>();
this.onAutoFill(viewer, autoFill);
@@ -104,7 +104,7 @@ public abstract class AbstractMenu<P extends NightCorePlugin> 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<P extends NightCorePlugin> 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);
}
@@ -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<P extends NightCorePlugin, T> extends AbstractM
@NotNull
protected MenuItem addReturn(int slot, @NotNull EditorHandler<T> 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<P extends NightCorePlugin, T> 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<P extends NightCorePlugin, T> 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);
@@ -48,9 +48,9 @@ public class ItemHandler {
/**
* The main purpose of this method is to quickly create ItemHandler object for non-configurable GUIs.
* <br><br>
* 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) {
@@ -17,8 +17,8 @@ public interface Linked<T> 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) {
@@ -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 <T extends Keyed> List<String> getNames(@NotNull Registry<T> 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<PotionEffectType> 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)) {
@@ -75,7 +75,7 @@ public class CommandUtil {
@NotNull
public static Optional<Command> 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();
}
@@ -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;
@@ -115,17 +115,29 @@ public class Lists {
List<String> 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;
}
@@ -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%";
@@ -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());
}
@@ -71,13 +71,27 @@ public class RankMap<T extends Number> {
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: <permission_prefix> + <key>."
String permissionPrefix = ConfigValue.create(path + ".Permission_Prefix",
"example.prefix.",
"Sets permission prefix for the '" + Mode.PERMISSION.name() + "' mode."
).read(cfg);
T fallback;
@@ -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
@@ -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();
}
@@ -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();
}
@@ -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<String, Tag> 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<Tag> 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<String> 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<WrappedText> 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<WrappedText> parts) {
if (parts.size() < 2) return;
List<Pair<GradientDecorator, List<WrappedText>>> pairs = new ArrayList<>();
Pair<GradientDecorator, List<WrappedText>> 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<WrappedText> 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<WrappedText> 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"));
}
}
}
@@ -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<ComponentBuildable> childrens;
private final Set<Decorator> 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<Decorator> getDecorators() {
return decorators;
}
@NotNull
public List<ComponentBuildable> getChildrens() {
return childrens;
}
}
@@ -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;
}
}
@@ -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<String> 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<String> 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);
}*/
}
@@ -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<String> 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;
}
}
@@ -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<Tag> tags;
private final Map<String, Decorator> 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<Tag> getTags() {
return tags;
}
@NotNull
public Map<String, Decorator> 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));
}
}
}
@@ -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);
}
@@ -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<Pair<String, Color>> gradient(@NotNull String string) {
List<Pair<String, Color>> 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("");
}
}
@@ -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;
}
}
@@ -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<String> 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<Tag> predicate;
public TagPool(@NotNull Predicate<Tag> predicate) {
this.predicate = predicate;
}
@NotNull
public static TagPool blacklisted(@NotNull Tag... tags) {
return create(Mode.BLACKLIST, tags);
public TagPool and(@NotNull Predicate<Tag> 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<String> 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<Tag> 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<String> getTags() {
return tags;
return this.predicate.test(tag);
}
}
@@ -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<String, Tag> 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<Tag> 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());
}
}
@@ -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;
}
}
@@ -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);
}
@@ -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);
}*/
}
@@ -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();
}
@@ -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();
}
}
@@ -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<String> 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<String> getAliases() {
return this.aliases;
}
@Override
@@ -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;
}
@@ -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;
}
@@ -0,0 +1,6 @@
package su.nightexpress.nightcore.util.text.tag.decorator;
public interface ColorDecorator extends Decorator {
// Exists just to clarify color decorators.
}
@@ -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;
@@ -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;
@@ -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()));
}
}
}
@@ -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()));
@@ -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);
@@ -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);
}
}
@@ -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()));
@@ -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;
@@ -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);
}
}
@@ -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);
}
}
@@ -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;
@@ -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;
}
}
@@ -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";
}
}
@@ -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"});
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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"});
}
}
@@ -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() {
+111
View File
@@ -0,0 +1,111 @@
Command:
Help:
List:
- <noprefix>
- "&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: <player>
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:
- <noprefix>
- "&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:
- <noprefix>
- "&7点击 <click:run_command:'/#exit'><hover:show_text:'&7点击以取消'>&a[这里]</hover></click> &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%"