1
mirror of https://github.com/CarmJos/EasyPlugin.git synced 2026-06-05 00:58:17 +08:00

Compare commits

..

17 Commits

Author SHA1 Message Date
carm 437d0ffb32 feat(utils): 独立基本类到单独项目中,便于使用。 2022-12-13 00:29:20 +08:00
carm d9b0689e63 feat(color): 添加清理颜色代码的方法 2022-11-28 16:12:01 +08:00
carm 62e7370622 feat(color): 继续完善渐变色解析。 2022-11-28 15:52:04 +08:00
carm 3d52d5db15 chore: 修改格式以便阅读 2022-11-27 23:32:39 +08:00
carm 9ad80b4916 feat(color): 为ColorParser支持RGB渐变颜色代码。 2022-11-27 22:58:00 +08:00
carm 9cff646226 docs(color): 添加ColorParser的Javadoc 2022-11-27 22:56:46 +08:00
carm 479f4592d1 feat(color): 为ColorParser支持RGB渐变颜色代码。 2022-11-27 22:53:33 +08:00
carm d2b3224b61 Merge pull request #7 from RedCarl/master
feat(color): ColorParser RGB gradient color support.
2022-11-27 21:10:58 +08:00
carm 7c72d910d9 feat(main): 在主类添加 supplySync、supplyAsync 操作方法。 2022-11-27 21:09:40 +08:00
RedCarl c822678043 ColorParser Update. 2022-11-10 23:27:24 +08:00
carm 98d9854d6f build(deps): 改用 spigot-api 2022-09-14 23:57:12 +08:00
carm 47b811dc33 feat(cooldown): 添加便捷的冷却时间工具类 2022-09-14 23:10:02 +08:00
carm 0b6e1ad3e4 feat(cooldown): 添加便捷的冷却时间工具类 2022-09-14 23:08:06 +08:00
carm 6863c02611 feat(gui): GUI原生物品配置读取 2022-09-11 23:25:17 +08:00
carm 7fc0663e89 feat(command): 允许子指令不处理报错,统一交由父CommandHandler处理。 2022-08-25 02:35:24 +08:00
carm b0c8091cb7 feat(command): 允许子指令不处理报错,统一交由父CommandHandler处理。 2022-08-25 02:34:24 +08:00
carm 8f03c2a1b3 feat(command): 为子命令提供父命令处理器的泛型,便于统一调用方法 2022-08-25 01:52:04 +08:00
25 changed files with 562 additions and 96 deletions
+7 -1
View File
@@ -36,8 +36,14 @@
### 主要部分 (`/base`)
- Utils [`easyplugin-utils`](base/utils)
- 通用工具类模块,该模块中的内容支持在Bungee、Bukkit使用。
- 本模块提供
- `ColorParser` 支持RGB颜色与RGB渐变色的颜色解析器。
- `EasyCooldown` 快速创造一个冷却时间的管理器。
- `JarResourceUtils` 快速读取Jar包内容的工具类。
- Main [`easyplugin-main`](base/main)
- 主要接口模块,提供了方便的插件入口类与相关工具类。
- 主要接口模块,提供了方便的插件入口类与相关工具类。
- Command [`easyplugin-command`](base/command)
- 指令接口模块,便于快速进行子指令的实现,并提供单独的TabComplete方法。
- 随本项目提供了 `SimpleCompleter` 类,用于快速创建补全的内容列表。
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -11,13 +11,14 @@ import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
@SuppressWarnings("UnusedReturnValue")
public abstract class CommandHandler implements TabExecutor, NamedExecutor {
protected final @NotNull JavaPlugin plugin;
protected final @NotNull String cmd;
protected final @NotNull List<String> aliases;
protected final @NotNull Map<String, SubCommand> registeredCommands = new HashMap<>();
protected final @NotNull Map<String, SubCommand<?>> registeredCommands = new HashMap<>();
protected final @NotNull Map<String, CommandHandler> registeredHandlers = new HashMap<>();
protected final @NotNull Map<String, String> aliasesMap = new HashMap<>();
@@ -36,13 +37,18 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
this.aliases = Arrays.asList(aliases);
}
public abstract void noArgs(CommandSender sender);
public abstract Void noArgs(CommandSender sender);
public void unknownCommand(CommandSender sender, String[] args) {
noArgs(sender);
public Void unknownCommand(CommandSender sender, String[] args) {
return noArgs(sender);
}
public abstract void noPermission(CommandSender sender);
public abstract Void noPermission(CommandSender sender);
public Void onException(CommandSender sender, SubCommand<?> cmd, Exception ex) {
sender.sendMessage("Error occurred when executing " + cmd.getName() + ": " + ex.getLocalizedMessage());
return null;
}
@Override
public @NotNull List<String> getAliases() {
@@ -54,7 +60,7 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
return this.cmd;
}
public void registerSubCommand(SubCommand command) {
public void registerSubCommand(SubCommand<?> command) {
String name = command.getName().toLowerCase();
this.registeredCommands.put(name, command);
command.getAliases().forEach(alias -> this.aliasesMap.put(alias.toLowerCase(), name));
@@ -82,16 +88,18 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
}
}
SubCommand subCommand = getSubCommand(input);
if (subCommand == null) {
SubCommand<?> sub = getSubCommand(input);
if (sub == null) {
this.unknownCommand(sender, args);
} else if (!subCommand.hasPermission(sender)) {
} else if (!sub.hasPermission(sender)) {
this.noPermission(sender);
} else {
try {
subCommand.execute(this.plugin, sender, this.shortenArgs(args));
} catch (ArrayIndexOutOfBoundsException var9) {
sub.execute(this.plugin, sender, this.shortenArgs(args));
} catch (ArrayIndexOutOfBoundsException ex) {
this.unknownCommand(sender, args);
} catch (Exception ex) {
this.onException(sender, sub, ex);
}
}
@@ -117,9 +125,9 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
return handler.onTabComplete(sender, command, alias, this.shortenArgs(args));
}
SubCommand subCommand = getSubCommand(input);
if (subCommand != null && subCommand.hasPermission(sender)) {
return subCommand.tabComplete(this.plugin, sender, this.shortenArgs(args));
SubCommand<?> sub = getSubCommand(input);
if (sub != null && sub.hasPermission(sender)) {
return sub.tabComplete(this.plugin, sender, this.shortenArgs(args));
}
return Collections.emptyList();
@@ -144,8 +152,8 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
else return this.registeredHandlers.get(nameFromAlias);
}
protected @Nullable SubCommand getSubCommand(@NotNull String name) {
SubCommand fromName = this.registeredCommands.get(name);
protected @Nullable SubCommand<?> getSubCommand(@NotNull String name) {
SubCommand<?> fromName = this.registeredCommands.get(name);
if (fromName != null) return fromName;
String nameFromAlias = this.aliasesMap.get(name);
@@ -2,37 +2,46 @@ package cc.carm.lib.easyplugin.command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@SuppressWarnings("UnusedReturnValue")
public abstract class SubCommand implements NamedExecutor {
public abstract class SubCommand<C extends CommandHandler> implements NamedExecutor {
private final @NotNull C parent;
private final String name;
private final List<String> aliases;
public SubCommand(String name, String... aliases) {
public SubCommand(@NotNull C parent, String name, String... aliases) {
this.parent = parent;
this.name = name;
this.aliases = Arrays.asList(aliases);
}
public @NotNull C getParent() {
return parent;
}
@Override
public String getName() {
return this.name;
}
@Override
@Unmodifiable
public List<String> getAliases() {
return this.aliases;
}
public abstract Void execute(JavaPlugin plugin, CommandSender sender, String[] args);
public abstract Void execute(JavaPlugin plugin, CommandSender sender, String[] args) throws Exception;
public List<String> tabComplete(JavaPlugin plugin, CommandSender sender, String[] args) {
return Collections.emptyList();
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -2,11 +2,14 @@ package cc.carm.lib.easyplugin.gui.configuration;
import cc.carm.lib.easyplugin.gui.GUI;
import cc.carm.lib.easyplugin.gui.GUIItem;
import cc.carm.lib.easyplugin.utils.ColorParser;
import cc.carm.lib.easyplugin.utils.ItemStackFactory;
import cc.carm.lib.easyplugin.utils.MessageUtils;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -15,6 +18,8 @@ import java.util.stream.Collectors;
public class GUIItemConfiguration {
@Nullable ItemStack original;
@NotNull Material type;
int amount;
int data;
@@ -28,6 +33,15 @@ public class GUIItemConfiguration {
@Nullable String name, @NotNull List<String> lore,
@NotNull List<GUIActionConfiguration> actions,
@NotNull List<Integer> slots) {
this(null, type, amount, data, name, lore, actions, slots);
}
public GUIItemConfiguration(@Nullable ItemStack original,
@NotNull Material type, int amount, int data,
@Nullable String name, @NotNull List<String> lore,
@NotNull List<GUIActionConfiguration> actions,
@NotNull List<Integer> slots) {
this.original = original;
this.type = type;
this.amount = amount;
this.data = data;
@@ -38,22 +52,58 @@ public class GUIItemConfiguration {
}
public void setupItems(Player player, GUI gui) {
ItemStackFactory icon = new ItemStackFactory(this.type, this.amount, this.data);
if (this.name != null) icon.setDisplayName(this.name);
icon.setLore(MessageUtils.setPlaceholders(player, this.lore));
ItemStack itemStack;
if (original != null) {
ItemStack tmp = original.clone();
ItemMeta originalMeta = original.getItemMeta();
if (originalMeta != null) {
if (originalMeta.hasDisplayName()) {
originalMeta.setDisplayName(parseText(player, originalMeta.getDisplayName()));
}
if (originalMeta.getLore() != null) {
originalMeta.setLore(parseTexts(player, originalMeta.getLore()));
}
GUIItem item = new GUIItem(icon.toItemStack());
}
tmp.setItemMeta(originalMeta);
itemStack = tmp;
} else {
ItemStackFactory icon = new ItemStackFactory(this.type, this.amount, this.data);
if (this.name != null) {
icon.setDisplayName(parseText(player, this.name));
}
if (!this.lore.isEmpty()) {
icon.setLore(parseTexts(player, this.lore));
}
itemStack = icon.toItemStack();
}
GUIItem item = new GUIItem(itemStack);
this.actions.stream().map(GUIActionConfiguration::toClickAction).forEach(item::addClickAction);
this.slots.forEach(slot -> gui.setItem(slot, item));
}
private List<String> parseTexts(Player player, List<String> lore) {
return ColorParser.parse(MessageUtils.setPlaceholders(player, lore));
}
@NotNull
private String parseText(Player player, @NotNull String name) {
return ColorParser.parse(MessageUtils.setPlaceholders(player, name));
}
public @NotNull Map<String, Object> serialize() {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
if (original != null) map.put("original", original);
else {
map.put("type", this.type.name());
if (this.data != 0) map.put("data", this.data);
}
map.put("type", this.type.name());
if (this.name != null) map.put("name", this.name);
if (this.amount != 1) map.put("amount", this.amount);
if (this.data != 0) map.put("data", this.data);
if (!this.lore.isEmpty()) map.put("lore", this.lore);
if (this.slots.size() > 1) {
map.put("slots", this.slots);
@@ -69,6 +119,10 @@ public class GUIItemConfiguration {
@Nullable
public static GUIItemConfiguration readFrom(@Nullable ConfigurationSection itemSection) {
if (itemSection == null) return null;
ItemStack original = null;
if (itemSection.contains("original")) original = itemSection.getItemStack("original");
String material = Optional.ofNullable(itemSection.getString("type")).orElse("STONE");
Material type = Optional.ofNullable(Material.matchMaterial(material)).orElse(Material.STONE);
int data = itemSection.getInt("data", 0);
@@ -88,7 +142,7 @@ public class GUIItemConfiguration {
}
return new GUIItemConfiguration(
type, amount, data, name, lore, actions,
original, type, amount, data, name, lore, actions,
slots.size() > 0 ? slots : Collections.singletonList(slot)
);
}
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+9 -2
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -22,7 +22,7 @@
<packaging>jar</packaging>
<name>EasyPlugin-Main</name>
<description>轻松插件主要接口模块,包含便的插件入口类与相关工具类。</description>
<description>轻松插件主要接口模块,包含便的插件入口类与相关工具类。</description>
<url>https://github.com/CarmJos/EasyPlugin</url>
<developers>
@@ -53,6 +53,13 @@
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>easyplugin-utils</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
@@ -22,6 +22,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public abstract class EasyPlugin extends JavaPlugin {
@@ -145,6 +146,32 @@ public abstract class EasyPlugin extends JavaPlugin {
if (isDebugging()) print("&8[DEBUG] &r", messages);
}
/**
* 在主线程执行操作,并支持获取其结果。
*
* @param <T> 结果类型
* @param action 需要执行的内容
* @return CompletableFuture
*/
public @NotNull <T> CompletableFuture<T> supplySync(@NotNull Supplier<T> action) {
CompletableFuture<T> future = new CompletableFuture<>();
getScheduler().run(() -> future.complete(action.get()));
return future;
}
/**
* 在异步线程中执行一个操作,并获取操作的结果。
*
* @param <T> 事件类型
* @param action 需要执行的内容
* @return CompletableFuture
*/
public @NotNull <T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> action) {
CompletableFuture<T> future = new CompletableFuture<>();
getScheduler().runAsync(() -> future.complete(action.get()));
return future;
}
/**
* 在主线程唤起一个事件,并支持获取事件的结果。
*
@@ -153,12 +180,10 @@ public abstract class EasyPlugin extends JavaPlugin {
* @return CompletableFuture
*/
public @NotNull <T extends Event> CompletableFuture<T> callSync(T event) {
CompletableFuture<T> future = new CompletableFuture<>();
getScheduler().run(() -> {
return supplySync(() -> {
Bukkit.getPluginManager().callEvent(event);
future.complete(event);
return event;
});
return future;
}
/**
@@ -169,12 +194,10 @@ public abstract class EasyPlugin extends JavaPlugin {
* @return CompletableFuture
*/
public @NotNull <T extends Event> CompletableFuture<T> callAsync(T event) {
CompletableFuture<T> future = new CompletableFuture<>();
getScheduler().runAsync(() -> {
return supplyAsync(() -> {
Bukkit.getPluginManager().callEvent(event);
future.complete(event);
return event;
});
return future;
}
protected void setMessageProvider(@NotNull EasyPluginMessageProvider provider) {
@@ -1,44 +0,0 @@
package cc.carm.lib.easyplugin.utils;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ColorParser {
public static final Pattern HEX_PATTERN = Pattern.compile("&\\(&?#([\\da-fA-F]{6})\\)");
public static String parse(String text) {
return parseBaseColor(parseHexColor(text));
}
public static String[] parse(String... texts) {
return parse(Arrays.asList(texts)).toArray(new String[0]);
}
public static List<String> parse(List<String> texts) {
return texts.stream().map(ColorParser::parse).collect(Collectors.toList());
}
public static String parseBaseColor(final String text) {
return text.replaceAll("&", "§").replace("§§", "&");
}
public static String parseHexColor(String text) {
Matcher matcher = HEX_PATTERN.matcher(text);
while (matcher.find()) {
text = matcher.replaceFirst(buildHexColor(matcher.group(1)).toLowerCase());
matcher.reset(text);
}
return text;
}
private static String buildHexColor(String hexCode) {
return Arrays.stream(hexCode.split(""))
.map(s -> '§' + s)
.collect(Collectors.joining("", '§' + "x", ""));
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+51
View File
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${project.jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<artifactId>easyplugin-utils</artifactId>
<name>EasyPlugin-Utils</name>
<description>轻松插件工具类模块,该模块中的内容支持在Bungee、Bukkit使用。</description>
<url>https://github.com/CarmJos/EasyPlugin</url>
<developers>
<developer>
<id>CarmJos</id>
<name>Carm Jos</name>
<email>carm@carm.cc</email>
<url>https://www.carm.cc</url>
</developer>
</developers>
<licenses>
<license>
<name>The MIT License</name>
<url>https://opensource.org/licenses/MIT</url>
</license>
</licenses>
<issueManagement>
<system>GitHub Issues</system>
<url>https://github.com/CarmJos/EasyPlugin/issues</url>
</issueManagement>
<ciManagement>
<system>GitHub Actions</system>
<url>https://github.com/CarmJos/EasyPlugin/actions/workflows/maven.yml</url>
</ciManagement>
</project>
@@ -0,0 +1,208 @@
package cc.carm.lib.easyplugin.utils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* 颜色解析器。
* <br> 普通颜色 格式 {@code &+颜色代码 },如 {@literal &c} 、{@literal &a}
* <br> RGB颜色(版本需要≥1.14) 格式 {@code &(#XXXXXX) },如 {@literal &(#aaaaaa)}
* <br> 渐变RBG颜色(版本需要≥1.14) 格式 {@code &<#XXXXXX>FOOBAR&<#XXXXXX> }
* <p> 注意:当使用渐变RGB颜色时,普通颜色代码与RGB颜色代码将失效。
*/
public class ColorParser {
public static final Pattern HEX_PATTERN = Pattern.compile("&\\(&?#([\\da-fA-F]{6})\\)");
public static final Pattern GRADIENT_PATTERN = Pattern.compile("&<&?#([\\da-fA-F]{6})>");
public static final Pattern COLOR_PATTERN = Pattern.compile("([&§][0-9a-fA-FrRxX])+"); // 会影响颜色的代码
public static final Pattern FORMAT_PATTERN = Pattern.compile("([&§][0-9a-fA-Fk-oK-OrRxX])+"); // MC可用的格式化代码
/**
* 清除一条消息中的全部颜色代码 (包括RGB颜色代码与渐变颜色代码)
*
* @param text 源消息内容
* @return 清理颜色后的消息
*/
public static @NotNull String clear(@NotNull String text) {
text = HEX_PATTERN.matcher(text).replaceAll("");
text = GRADIENT_PATTERN.matcher(text).replaceAll("");
text = COLOR_PATTERN.matcher(text).replaceAll("");
return text;
}
/**
* 对一条消息进行颜色解析,包括普通颜色代码、RGB颜色代码与RBG渐变代码。
*
* @param text 源消息内容
* @return 解析后的消息
*/
public static @NotNull String parse(@NotNull String text) {
return parseBaseColor(parseGradientColor(parseHexColor(text)));
}
/**
* 对多条消息进行颜色解析,包括普通颜色代码、RGB颜色代码与RBG渐变代码。
*
* @param texts 源消息内容
* @return 解析后的消息
*/
public static @NotNull String[] parse(@NotNull String... texts) {
return parse(Arrays.asList(texts)).toArray(new String[0]);
}
/**
* 对多条消息进行颜色解析,包括普通颜色代码、RGB颜色代码与RBG渐变代码。
*
* @param texts 源消息内容
* @return 解析后的消息
*/
public static @NotNull List<String> parse(@NotNull Collection<String> texts) {
return texts.stream().map(ColorParser::parse).collect(Collectors.toList());
}
/**
* 解析消息中的基本颜色代码格式 {@code &+颜色代码 },如 {@literal &c} 、{@literal &a}
*
* @param text 消息内容
* @return RGB处理后的消息
* @see net.md_5.bungee.api.ChatColor
*/
public static String parseBaseColor(final String text) {
return text.replaceAll("&", "§").replace("§§", "&");
}
/**
* 解析消息中的RGB颜色代码(版本需要≥1.14) 格式 {@code &(#XXXXXX) },如 {@literal &(#aaaaaa)}
*
* @param text 消息内容
* @return RGB处理后的消息
*/
public static String parseHexColor(String text) {
Matcher matcher = HEX_PATTERN.matcher(text);
while (matcher.find()) {
text = matcher.replaceFirst(buildHexColor(matcher.group(1)).toLowerCase());
matcher.reset(text);
}
return text;
}
/**
* 对一条消息进行RGB渐变处理(版本需要≥1.14),格式 {@code &<#XXXXXX>FOOBAR&<#XXXXXX> }。
*
* @param text 消息内容
* @return RGB渐变处理后的消息
*/
public static @NotNull String parseGradientColor(@NotNull String text) {
List<String> colors = new ArrayList<>();
Matcher matcher = ColorParser.GRADIENT_PATTERN.matcher(text);
while (matcher.find()) colors.add(matcher.group(1));
if (colors.isEmpty()) return text; // 无渐变颜色,直接跳出
String[] parts = ColorParser.GRADIENT_PATTERN.split(text);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
String startHex = i - 1 >= 0 && colors.size() > i - 1 ? colors.get(i - 1) : null; // 本条消息的起始颜色
String endHex = colors.size() > i ? colors.get(i) : null; // 本条消息的结束颜色
builder.append(gradientText(parts[i], startHex, endHex));
}
return builder.toString();
}
public static @NotNull String gradientText(@NotNull String text,
@Nullable Color startColor, @Nullable Color endColor) {
Objects.requireNonNull(text, "Text to be gradient should not be null!");
if (startColor == null || endColor == null || text.isEmpty()) {
// 起始颜色有任一为空,则不进行渐变上色。
// 若有起始颜色,则代表其跟在某个渐变之后,应当添加"&r"阻断前面的渐变。
return (startColor != null ? "&r" : "") + text;
}
// 用于记录消息中特殊格式的位置
// 在渐变中,允许使用格式字符与颜色字符来改变其中某个字的颜色/格式,以支持更多形式内容。
LinkedHashMap<Integer, String> extraFormats = new LinkedHashMap<>();
Matcher matcher = ColorParser.FORMAT_PATTERN.matcher(text);
while (matcher.find()) {
extraFormats.put(matcher.start(), matcher.group());
text = matcher.replaceFirst("");
matcher.reset(text);
}
if (text.length() == 1) {
// 当只有一个实际字符时,无需进行渐变计算,直接返回 中间颜色+起始格式(如果有)+消息 即可。
return colorText(text, extraFormats.get(0), buildHexColor(mediumHex(startColor, endColor)));
}
String[] characters = text.split("");
int step = characters.length; // 变换次数
// 决定每种颜色变换的方向
int rDirection = startColor.getRed() < endColor.getRed() ? 1 : -1;
int gDirection = startColor.getGreen() < endColor.getGreen() ? 1 : -1;
int bDirection = startColor.getBlue() < endColor.getBlue() ? 1 : -1;
// 决定每种颜色每次变换的度
int rStep = Math.abs(startColor.getRed() - endColor.getRed()) / (step - 1);
int gStep = Math.abs(startColor.getGreen() - endColor.getGreen()) / (step - 1);
int bStep = Math.abs(startColor.getBlue() - endColor.getBlue()) / (step - 1);
String[] hexes = IntStream.range(0, step).mapToObj(i -> colorToHex(
startColor.getRed() + rStep * i * rDirection,
startColor.getGreen() + gStep * i * gDirection,
startColor.getBlue() + bStep * i * bDirection
)).toArray(String[]::new);
return IntStream.range(0, characters.length)
.mapToObj(i -> colorText(characters[i], extraFormats.get(i), buildHexColor(hexes[i])))
.collect(Collectors.joining());
}
protected static String gradientText(@NotNull String text, @Nullable String startHex, @Nullable String endHex) {
return gradientText(text,
startHex == null ? null : Color.decode("0x" + startHex),
endHex == null ? null : Color.decode("0x" + endHex)
);
}
private static String mediumHex(@NotNull Color start, @NotNull Color end) {
return colorToHex(
Math.abs(start.getRed() - end.getRed()) / 2,
Math.abs(start.getGreen() - end.getGreen()) / 2,
Math.abs(start.getBlue() - end.getBlue()) / 2
);
}
private static String colorText(String message, @Nullable String format, @Nullable String color) {
if (format != null && COLOR_PATTERN.matcher(format).find()) {
// format中存在影响颜色的内容,则当前消息的颜色会被覆盖。
// 为了减少最终消息的长度,故直接返回键入的FORMAT和对应消息的内容。
return format + message;
}
return (color == null ? "" : color) + (format == null ? "" : parseBaseColor(format)) + message;
}
protected static String colorToHex(Color color) {
return colorToHex(color.getRed(), color.getGreen(), color.getBlue());
}
protected static String colorToHex(int r, int g, int b) {
// 将R、G、B转换为16进制(若非2位则补0)输出
return String.format("%02X%02X%02X", r, g, b);
}
protected static String buildHexColor(String hexCode) {
return Arrays.stream(hexCode.split("")).map(s -> '§' + s)
.collect(Collectors.joining("", '§' + "x", ""));
}
}
@@ -0,0 +1,93 @@
package cc.carm.lib.easyplugin.utils;
import org.jetbrains.annotations.NotNull;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* <a href="https://gist.github.com/CarmJos/402cb5aad0ec14ab25c2fa0d21571703">Easy cooldown time utils.</a>
*
* @param <P> Cooldown key provider
* @param <K> Cooldown key
* @author CarmJos
*/
public class EasyCooldown<P, K> {
protected final NumberFormat numberFormatter;
protected final @NotNull Map<K, Long> cooldown = new HashMap<>();
protected final @NotNull Function<P, K> providerToKey;
protected long defaultDuration;
public EasyCooldown(@NotNull Function<P, K> providerToKey) {
this(defaultFormatter(), providerToKey, 1000L);
}
public EasyCooldown(@NotNull NumberFormat numberFormatter,
@NotNull Function<P, K> providerToKey) {
this(numberFormatter, providerToKey, 1000L);
}
public EasyCooldown(@NotNull NumberFormat numberFormatter,
@NotNull Function<P, K> providerToKey,
long defaultDuration) {
this.numberFormatter = numberFormatter;
this.providerToKey = providerToKey;
this.defaultDuration = defaultDuration;
}
public long getCooldown(@NotNull P provider) {
Long time = this.cooldown.get(this.providerToKey.apply(provider));
if (time == null || time < 0) return 0;
long duration = getDuration(provider);
if (duration <= 0) return 0;
long past = System.currentTimeMillis() - time;
return duration - past;
}
public @NotNull String getCooldownSeconds(@NotNull P provider) {
return formatSeconds(getCooldown(provider));
}
public void updateTime(@NotNull P provider) {
this.cooldown.put(this.providerToKey.apply(provider), System.currentTimeMillis());
}
public void clear(@NotNull P provider) {
clearCooldown(this.providerToKey.apply(provider));
}
public void clearCooldown(@NotNull K key) {
this.cooldown.remove(key);
}
public boolean isCoolingDown(@NotNull P provider) {
return getCooldown(provider) > 0;
}
public long getDuration(@NotNull P provider) {
return this.defaultDuration;
}
public @NotNull String formatSeconds(long cooldownMillis) {
return numberFormatter.format((double) cooldownMillis / 1000D);
}
public static NumberFormat createFormatter(@NotNull Consumer<NumberFormat> consumer) {
NumberFormat format = NumberFormat.getInstance();
consumer.accept(format);
return format;
}
public static NumberFormat defaultFormatter() {
return createFormatter((f) -> f.setMaximumFractionDigits(2));
}
}
@@ -0,0 +1,50 @@
import cc.carm.lib.easyplugin.utils.ColorParser;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import static cc.carm.lib.easyplugin.utils.ColorParser.*;
public class ColorParseTest {
@Test
public void test() {
System.out.println(" ");
System.out.println(parseGradientColor("&<#AAAAAA>我真的&<#BBBBBB>爱死&<#111111>你&<#FFFFFF>"));
// 测试穿插
System.out.println(parse("&<#AAAAAA>&l我&r真&b的&<#BBBBBB>&o爱死&<#111111>你&<#FFFFFF>了&r"));
System.out.println(parse("&<#AAAAAA>&l我&r真&(#666666)的&<#BBBBBB>&o爱死&<#111111>你&<#FFFFFF>了&r"));
System.out.println(parse("&r正常的颜色理应&c&l不受影响&r。"));
System.out.println(clear("&f测试&<#AAAAAA>清理颜色代码&<#111111> &&这样应该&(#666666)不被影响 &f。"));
}
@Test
public void formatReadTest() {
LinkedHashMap<Integer, String> formats = new LinkedHashMap<>();
String text = "&k&l &m&1我&k爱你爱你爱你&o吗?";
Matcher matcher = ColorParser.FORMAT_PATTERN.matcher(text);
while (matcher.find()) {
String code = matcher.group();
formats.put(matcher.start(), code);
text = matcher.replaceFirst("");
matcher.reset(text);
}
formats.forEach((index, code) -> System.out.println(index + " -> " + code));
String[] parts = text.split("");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
String format = formats.get(i);
if (format != null) builder.append(ColorParser.parseBaseColor(format));
builder.append(parts[i]);
}
System.out.println(builder);
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.13</version>
<version>1.4.18</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+3 -2
View File
@@ -15,8 +15,9 @@
<groupId>cc.carm.lib</groupId>
<artifactId>easyplugin-parent</artifactId>
<packaging>pom</packaging>
<version>1.4.13</version>
<version>1.4.18</version>
<modules>
<module>base/utils</module>
<module>base/main</module>
<module>base/conf</module>
@@ -106,7 +107,7 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<artifactId>spigot-api</artifactId>
<version>1.13.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>