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

Compare commits

..

40 Commits

Author SHA1 Message Date
carm 01250a65d1 refactor(color): 独立颜色模块 2023-02-18 19:06:48 +08:00
carm 088cc62855 fix(cmd): 修复CommandHandler处理异常的问题 2023-02-11 21:11:34 +08:00
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
carm 429eb9c6ec chore(event): 为同步/异步事件唤起方法添加Javadoc 2022-07-27 14:41:20 +08:00
carm 05e2c8fad0 chore(deps): 补充新项目到bom中。 2022-07-27 14:37:23 +08:00
carm a58fe4abd6 docs(proj): 修改措辞 2022-07-27 14:34:58 +08:00
carm 79a18f2669 docs(proj): 提供更多关于子项目内容的介绍。 2022-07-27 14:30:39 +08:00
carm e5fc8acddc feat(proj): 提供更多子项目打包,便于快速导入对应依赖。 2022-07-27 14:29:13 +08:00
carm fb125ee9bd chore(gui): 为GUIItem的onClick方法提供viewer参数。
close #6
2022-07-27 13:53:30 +08:00
carm 376cde3529 chore(cmd): 令 hasPermission() 判断的参数为 CommandSender 。 2022-07-10 10:13:06 +08:00
carm 6e555a700f chore(cmd): 移除单String参数的SubCommand构造函数 2022-07-10 05:36:30 +08:00
carm b7e9295685 chore(gui): 为 GUIConfiguration 添加 serialize() 方法。 2022-07-10 04:58:59 +08:00
carm b5382a1cb3 chore(gui): 修改 GUIItemConfiguration 的读取与初始化方式 2022-07-01 20:01:50 +08:00
carm 77c035c2cb fix(main): 移除 isInitialized() 方法 (与部分服务端冲突) 2022-07-01 18:39:44 +08:00
carm fbf118436e feat(command): 指令部分新增基础方法 2022-06-26 10:34:06 +08:00
carm 572c22d2fc chore(pom): 移除无用条目 2022-06-18 05:38:13 +08:00
carm e416363751 fix(gui): 修复 GUIItemConfiguration 序列化错误的问题 2022-06-18 05:31:41 +08:00
carm 123e5463ad feat(main): 添加完整的构造方法用于测试 2022-06-18 04:40:35 +08:00
carm 65bc24d1e9 feat(storage): 为 StorageType 添加 DataStorage 泛型限制 2022-06-18 04:09:33 +08:00
carm 778235e8d1 feat(updater): 添加Github更新检查模块,方便获取基于Github发布的插件版本更新。 2022-06-18 03:04:30 +08:00
carm 120362f221 feat(updater): 添加Github更新检查模块,方便获取基于Github发布的插件版本更新。 2022-06-18 02:32:41 +08:00
carm 4c10a9798f feat(storage): 添加存储接口模块,包含存储相关的统一接口。 2022-06-18 02:32:08 +08:00
carm 558723ea82 chore(item): 添加序列化方法 2022-06-18 00:21:03 +08:00
carm b6bd4beda0 chore(item): 添加序列化方法 2022-06-18 00:16:02 +08:00
52 changed files with 2799 additions and 1244 deletions
+1 -1
View File
@@ -4,6 +4,6 @@
## 如何实现? ## 如何实现?
若您也想通过 [Github Actions](https://docs.github.com/en/actions/learn-github-actions) 若您也想通过 [Github Actions](https://docs.github.com/en/actions/learn-github-actions)
自动部署项目的Javadoc到 [Github Pages](https://pages.github.com/) 自动部署项目的Javadoc到 [Github Pages](https://pages.github.com/)
可以参考我的文章 [《自动部署Javadoc到Github Pages》](https://pages.carm.cc/doc/javadoc-in-github.html) 。 可以参考我的文章 [《自动部署Javadoc到Github Pages》](https://pages.carm.cc/doc/javadoc-in-github.html) 。
+1 -1
View File
@@ -14,6 +14,7 @@ assignees: ''
### **问题来源** ### **问题来源**
描述一下通过哪些操作才发现的问题,如: 描述一下通过哪些操作才发现的问题,如:
1. 使用了 ... 1. 使用了 ...
2. 输入了 ... 2. 输入了 ...
3. 出现了报错 ... 3. 出现了报错 ...
@@ -32,7 +33,6 @@ assignees: ''
- Java版本: `JDK11` / `OPENJDK8` / `JRE8` / `...` - Java版本: `JDK11` / `OPENJDK8` / `JRE8` / `...`
- 服务端版本: 请在后台输入 `version` 并复制相关输出。 - 服务端版本: 请在后台输入 `version` 并复制相关输出。
### **其他补充** ### **其他补充**
如有其他补充,可以在这里描述。 如有其他补充,可以在这里描述。
+4
View File
@@ -8,13 +8,17 @@ assignees: ''
--- ---
### **功能简述** ### **功能简述**
简单的描述一下你想要的功能 简单的描述一下你想要的功能
### **需求来源** ### **需求来源**
简单的描述一下为什么需要这个功能。 简单的描述一下为什么需要这个功能。
### **功能参考**(可选) ### **功能参考**(可选)
如果有相关功能的参考,如文本、截图,请提供给我们。 如果有相关功能的参考,如文本、截图,请提供给我们。
### **附加内容** ### **附加内容**
如果有什么小细节需要重点注意,请在这里告诉我们。 如果有什么小细节需要重点注意,请在这里告诉我们。
+24 -4
View File
@@ -27,7 +27,7 @@
## 内容 ## 内容
项目初创不久,加 * 的仍在开发更新中... 项目初创不久,加 * 的仍在开发更新中...欢迎各路大佬帮助提供本项目的开发文档~
### 集合部分 (`/collection`) ### 集合部分 (`/collection`)
@@ -36,12 +36,32 @@
### 主要部分 (`/base`) ### 主要部分 (`/base`)
- Utils [`easyplugin-utils`](base/utils)
- 通用工具类模块,该模块中的内容支持在Bungee、Bukkit使用。
- 本模块提供
- `ColorParser` 支持RGB颜色与RGB渐变色的颜色解析器。
- `EasyCooldown` 快速创造一个冷却时间的管理器。
- `JarResourceUtils` 快速读取Jar包内容的工具类。
- Main [`easyplugin-main`](base/main) - Main [`easyplugin-main`](base/main)
- 主要接口模块,提供了方便的插件入口类与相关工具类。
- Command [`easyplugin-command`](base/command) - Command [`easyplugin-command`](base/command)
- ~~Messages*~~ (已独立项目到 [**EasyMessages**](https://github.com/CarmJos/EasyMessages)) - 指令接口模块,便于快速进行子指令的实现,并提供单独的TabComplete方法。
- ~~Configuration~~ (已独立项目到 [**MineConfiguration**](https://github.com/CarmJos/MineConfiguration)) - 随本项目提供了 `SimpleCompleter` 类,用于快速创建补全的内容列表。
- ~~Database~~ (已独立项目到 [**EasySQL**](https://github.com/CarmJos/EasySQL))
- GUI [`easyplugin-gui`](base/main) - GUI [`easyplugin-gui`](base/main)
- 简单便捷的箱子GUI接口,可以快速实现GUI中不同图标的点击功能。
- 随本项目提供了 `AutoPagedGUI` 等翻页GUI抽象类。
- Storage [`easyplugin-storage`](base/storage)
- 抽象存储管理器,便于实现不同的存储类型。
- 随本项目提供了 `FileBasedStorage``FolderBasedStorage` 等常用存储抽象方法。
> 以下项目均已独立出单独项目,仅仅是按照包名规则打包到EasyPlugin的子项目中。
>
> 如需使用,**强烈建议自行引用对应的项目**,以支持完整的Javadoc并获取源码内容!
- _Listener_ [`easyplugin-listener`](base/listener) (打包自 [**EasyListener**](https://github.com/CarmJos/EasyListener))
- _Configuration_ [`easyplugin-conf`](base/conf) (打包自 [**MineConfiguration**](https://github.com/CarmJos/MineConfiguration))
- _Database_ [`easyplugin-database`](base/database) (打包自 [**EasySQL**](https://github.com/CarmJos/EasySQL))
- _Messages*_ [`easyplugin-message`](base/message) (打包自 [**EasyMessages**](https://github.com/CarmJos/EasyMessages))
### 附属部分 (`/extension`) ### 附属部分 (`/extension`)
+50
View File
@@ -0,0 +1,50 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cc.carm.lib</groupId>
<artifactId>easyplugin-parent</artifactId>
<version>1.4.20</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<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-color</artifactId>
<name>EasyPlugin-Color</name>
<description>轻松插件颜色模块,支持简单便捷的颜色解析器,包括基本颜色、RGB颜色与RGB渐变颜色。</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,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> <parent>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.6</version> <version>1.4.20</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -1,4 +1,3 @@
package cc.carm.lib.easyplugin.command; package cc.carm.lib.easyplugin.command;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@@ -12,13 +11,14 @@ import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@SuppressWarnings("UnusedReturnValue")
public abstract class CommandHandler implements TabExecutor, NamedExecutor { public abstract class CommandHandler implements TabExecutor, NamedExecutor {
protected final @NotNull JavaPlugin plugin; protected final @NotNull JavaPlugin plugin;
protected final @NotNull String cmd; protected final @NotNull String cmd;
protected final @NotNull List<String> aliases; 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, CommandHandler> registeredHandlers = new HashMap<>();
protected final @NotNull Map<String, String> aliasesMap = new HashMap<>(); protected final @NotNull Map<String, String> aliasesMap = new HashMap<>();
@@ -37,11 +37,18 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
this.aliases = Arrays.asList(aliases); this.aliases = Arrays.asList(aliases);
} }
public abstract void noArgs(CommandSender sender); public abstract Void noArgs(CommandSender sender);
public abstract void unknownCommand(CommandSender sender, String[] args); 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 @Override
public @NotNull List<String> getAliases() { public @NotNull List<String> getAliases() {
@@ -53,7 +60,7 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
return this.cmd; return this.cmd;
} }
public void registerSubCommand(SubCommand command) { public void registerSubCommand(SubCommand<?> command) {
String name = command.getName().toLowerCase(); String name = command.getName().toLowerCase();
this.registeredCommands.put(name, command); this.registeredCommands.put(name, command);
command.getAliases().forEach(alias -> this.aliasesMap.put(alias.toLowerCase(), name)); command.getAliases().forEach(alias -> this.aliasesMap.put(alias.toLowerCase(), name));
@@ -67,34 +74,42 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
@Override @Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (!this.hasPermission(sender)) {
noPermission(sender);
return true;
}
if (args.length == 0) { if (args.length == 0) {
this.noArgs(sender); this.noArgs(sender);
} else { return true;
String input = args[0].toLowerCase(); }
CommandHandler handler = getHandler(input); String input = args[0].toLowerCase();
if (handler != null) {
if (!handler.hasPermission(sender)) {
this.noPermission(sender);
} else {
handler.onCommand(sender, command, label, this.shortenArgs(args));
}
}
SubCommand subCommand = getSubCommand(input); CommandHandler handler = getHandler(input);
if (subCommand == null) { if (handler != null) {
this.unknownCommand(sender, args); if (!handler.hasPermission(sender)) {
} else if (!subCommand.hasPermission(sender)) {
this.noPermission(sender); this.noPermission(sender);
} else { } else {
try { handler.onCommand(sender, command, label, this.shortenArgs(args));
subCommand.execute(this.plugin, sender, this.shortenArgs(args));
} catch (ArrayIndexOutOfBoundsException var9) {
this.unknownCommand(sender, args);
}
} }
return true;
} }
SubCommand<?> sub = getSubCommand(input);
if (sub == null) {
this.unknownCommand(sender, args);
} else if (!sub.hasPermission(sender)) {
this.noPermission(sender);
} else {
try {
sub.execute(this.plugin, sender, this.shortenArgs(args));
} catch (Exception ex) {
this.onException(sender, sub, ex);
ex.printStackTrace();
}
}
return true; return true;
} }
@@ -116,9 +131,9 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
return handler.onTabComplete(sender, command, alias, this.shortenArgs(args)); return handler.onTabComplete(sender, command, alias, this.shortenArgs(args));
} }
SubCommand subCommand = getSubCommand(input); SubCommand<?> sub = getSubCommand(input);
if (subCommand != null && subCommand.hasPermission(sender)) { if (sub != null && sub.hasPermission(sender)) {
return subCommand.tabComplete(this.plugin, sender, this.shortenArgs(args)); return sub.tabComplete(this.plugin, sender, this.shortenArgs(args));
} }
return Collections.emptyList(); return Collections.emptyList();
@@ -143,8 +158,8 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
else return this.registeredHandlers.get(nameFromAlias); else return this.registeredHandlers.get(nameFromAlias);
} }
protected @Nullable SubCommand getSubCommand(@NotNull String name) { protected @Nullable SubCommand<?> getSubCommand(@NotNull String name) {
SubCommand fromName = this.registeredCommands.get(name); SubCommand<?> fromName = this.registeredCommands.get(name);
if (fromName != null) return fromName; if (fromName != null) return fromName;
String nameFromAlias = this.aliasesMap.get(name); String nameFromAlias = this.aliasesMap.get(name);
@@ -1,7 +1,6 @@
package cc.carm.lib.easyplugin.command; package cc.carm.lib.easyplugin.command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permissible;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -16,7 +15,7 @@ public interface NamedExecutor {
List<String> getAliases(); List<String> getAliases();
default boolean hasPermission(Permissible permissible) { default boolean hasPermission(CommandSender sender) {
return true; return true;
} }
@@ -1,15 +1,18 @@
package cc.carm.lib.easyplugin.command; package cc.carm.lib.easyplugin.command;
import com.google.common.collect.ImmutableList;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.StringUtil; import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -17,14 +20,22 @@ import java.util.stream.Stream;
public class SimpleCompleter { public class SimpleCompleter {
public static @NotNull List<String> objects(@NotNull String input, List<?> objects) { public static @NotNull List<String> none() {
return ImmutableList.of();
}
public static @NotNull List<String> objects(@NotNull String input, Collection<?> objects) {
return objects(input, objects.size(), objects); return objects(input, objects.size(), objects);
} }
public static @NotNull List<String> objects(@NotNull String input, int limit, List<?> objects) { public static @NotNull List<String> objects(@NotNull String input, int limit, Collection<?> objects) {
return objects(input, limit, objects.stream()); return objects(input, limit, objects.stream());
} }
public static @NotNull List<String> objects(@NotNull String input, Stream<?> stream) {
return objects(input, 20, stream);
}
public static @NotNull List<String> objects(@NotNull String input, int limit, Stream<?> stream) { public static @NotNull List<String> objects(@NotNull String input, int limit, Stream<?> stream) {
return stream.filter(Objects::nonNull).map(Object::toString) return stream.filter(Objects::nonNull).map(Object::toString)
.filter(s -> StringUtil.startsWithIgnoreCase(s, input)) .filter(s -> StringUtil.startsWithIgnoreCase(s, input))
@@ -39,11 +50,11 @@ public class SimpleCompleter {
return text(input, limit, Arrays.asList(texts)); return text(input, limit, Arrays.asList(texts));
} }
public static @NotNull List<String> text(@NotNull String input, List<String> texts) { public static @NotNull List<String> text(@NotNull String input, Collection<String> texts) {
return text(input, texts.size(), texts); return text(input, texts.size(), texts);
} }
public static @NotNull List<String> text(@NotNull String input, int limit, List<String> texts) { public static @NotNull List<String> text(@NotNull String input, int limit, Collection<String> texts) {
return objects(input, limit, texts); return objects(input, limit, texts);
} }
@@ -87,4 +98,13 @@ public class SimpleCompleter {
return objects(input, limit, Arrays.stream(PotionEffectType.values()).map(PotionEffectType::getName)); return objects(input, limit, Arrays.stream(PotionEffectType.values()).map(PotionEffectType::getName));
} }
public static @NotNull List<String> enchantments(@NotNull String input) {
return effects(input, 10);
}
@SuppressWarnings("deprecation")
public static @NotNull List<String> enchantments(@NotNull String input, int limit) {
return objects(input, limit, Arrays.stream(Enchantment.values()).map(Enchantment::getName));
}
} }
@@ -2,26 +2,30 @@ package cc.carm.lib.easyplugin.command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@SuppressWarnings("UnusedReturnValue") @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 String name;
private final List<String> aliases; private final List<String> aliases;
public SubCommand(String name) { public SubCommand(@NotNull C parent, String name, String... aliases) {
this(name, new String[0]); this.parent = parent;
}
public SubCommand(String name, String... aliases) {
this.name = name; this.name = name;
this.aliases = Arrays.asList(aliases); this.aliases = Arrays.asList(aliases);
} }
public @NotNull C getParent() {
return parent;
}
@Override @Override
public String getName() { public String getName() {
@@ -29,15 +33,15 @@ public abstract class SubCommand implements NamedExecutor {
} }
@Override @Override
@Unmodifiable
public List<String> getAliases() { public List<String> getAliases() {
return this.aliases; 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) { public List<String> tabComplete(JavaPlugin plugin, CommandSender sender, String[] args) {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
+81
View File
@@ -0,0 +1,81 @@
<?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.20</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-conf</artifactId>
<packaging>jar</packaging>
<name>EasyPlugin-Configuration</name>
<description>轻松插件配置文件接口模块,基于 MineConfiguration 项目。</description>
<url>https://github.com/CarmJos/EasyPlugin</url>
<dependencies>
<dependency>
<!-- https://github.com/CarmJos/MineConfiguration -->
<groupId>cc.carm.lib</groupId>
<artifactId>mineconfiguration-bukkit</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>cc.carm.lib.configuration.core</pattern>
<shadedPattern>cc.carm.lib.easyplugin.conf</shadedPattern>
</relocation>
<relocation>
<pattern>cc.carm.lib.mineconfiguration.common</pattern>
<shadedPattern>cc.carm.lib.easyplugin.conf</shadedPattern>
</relocation>
<relocation>
<pattern>cc.carm.lib.mineconfiguration.bukkit</pattern>
<shadedPattern>cc.carm.lib.easyplugin.conf</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
<exclude>META-INF/*.txt</exclude>
</excludes>
</filter>
</filters>
</configuration>
</plugin>
</plugins>
</build>
</project>
+73
View File
@@ -0,0 +1,73 @@
<?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.20</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-database</artifactId>
<packaging>jar</packaging>
<name>EasyPlugin-Database</name>
<description>轻松插件数据库接口模块,基于 EasySQL 项目。</description>
<url>https://github.com/CarmJos/EasyPlugin</url>
<dependencies>
<dependency>
<!-- https://github.com/CarmJos/EasySQL -->
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-beecp</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>cc.carm.lib.easysql</pattern>
<shadedPattern>cc.carm.lib.easyplugin.database</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
<exclude>META-INF/*.txt</exclude>
</excludes>
</filter>
</filters>
</configuration>
</plugin>
</plugins>
</build>
</project>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.6</version> <version>1.4.20</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -13,199 +13,196 @@ import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.IntStream; import java.util.stream.IntStream;
public class GUI { public class GUI {
private static JavaPlugin plugin; private static JavaPlugin plugin;
private static final HashMap<UUID, GUI> openedGUIs = new HashMap<>(); private static final HashMap<UUID, GUI> openedGUIs = new HashMap<>();
public static void initialize(JavaPlugin plugin) { public static void initialize(JavaPlugin plugin) {
GUI.plugin = plugin; GUI.plugin = plugin;
} }
public static JavaPlugin getPlugin() { public static JavaPlugin getPlugin() {
return plugin; return plugin;
} }
public static HashMap<UUID, GUI> getOpenedGUIs() { public static HashMap<UUID, GUI> getOpenedGUIs() {
return openedGUIs; return openedGUIs;
} }
protected GUIType type; protected GUIType type;
protected String name; protected String name;
public HashMap<Integer, GUIItem> items; public HashMap<Integer, GUIItem> items;
public Inventory inv; public Inventory inv;
/** /**
* 当玩家点击目标GUI时是否取消 * 当玩家点击目标GUI时是否取消
*/ */
boolean cancelOnTarget = true; boolean cancelOnTarget = true;
/** /**
* 当玩家点击自己背包时是否取消 * 当玩家点击自己背包时是否取消
*/ */
boolean cancelOnSelf = true; boolean cancelOnSelf = true;
/** /**
* 当玩家点击界面外时是否取消 * 当玩家点击界面外时是否取消
*/ */
boolean cancelOnOuter = true; boolean cancelOnOuter = true;
Map<String, Object> flags; protected final Map<String, Object> flags = new LinkedHashMap<>();
GUIListener listener; protected GUIListener listener;
public GUI(GUIType type, String name) { public GUI(GUIType type, String name) {
this.type = type; this.type = type;
this.name = ColorParser.parse(name); this.name = ColorParser.parse(name);
this.items = new HashMap<>(); this.items = new HashMap<>();
} }
public HashMap<@NotNull Integer, @NotNull GUIItem> getItems() { public HashMap<@NotNull Integer, @NotNull GUIItem> getItems() {
return new HashMap<>(items); return new HashMap<>(items);
} }
public final void setItem(int index, @Nullable GUIItem item) { public final void setItem(int index, @Nullable GUIItem item) {
if (item == null) { if (item == null) {
this.items.remove(index); this.items.remove(index);
} else { } else {
this.items.put(index, item); this.items.put(index, item);
} }
} }
public void setItem(GUIItem item, int... index) { public void setItem(GUIItem item, int... index) {
for (int i : index) { for (int i : index) {
setItem(i, item); setItem(i, item);
} }
} }
public GUIItem getItem(int index) { public GUIItem getItem(int index) {
return this.items.get(index); return this.items.get(index);
} }
/** /**
* 更新玩家箱子的视图 * 更新玩家箱子的视图
*/ */
public void updateView() { public void updateView() {
if (this.inv != null) { if (this.inv != null) {
List<HumanEntity> viewers = this.inv.getViewers(); List<HumanEntity> viewers = this.inv.getViewers();
IntStream.range(0, this.inv.getSize()).forEach(index -> inv.setItem(index, new ItemStack(Material.AIR))); IntStream.range(0, this.inv.getSize()).forEach(index -> inv.setItem(index, new ItemStack(Material.AIR)));
getItems().forEach((index, item) -> inv.setItem(index, item.getDisplay())); getItems().forEach((index, item) -> inv.setItem(index, item.getDisplay()));
viewers.forEach(p -> ((Player) p).updateInventory()); viewers.forEach(p -> ((Player) p).updateInventory());
} }
} }
/** /**
* 设置是否取消点击GUI内物品的事件 * 设置是否取消点击GUI内物品的事件
* 如果不取消,玩家可以从GUI中拿取物品。 * 如果不取消,玩家可以从GUI中拿取物品。
* *
* @param b 是否取消 * @param b 是否取消
*/ */
public void setCancelOnTarget(boolean b) { public void setCancelOnTarget(boolean b) {
this.cancelOnTarget = b; this.cancelOnTarget = b;
} }
/** /**
* 设置是否取消点击自己背包内物品的事件 * 设置是否取消点击自己背包内物品的事件
* 如果不取消,玩家可以从自己的背包中拿取物品。 * 如果不取消,玩家可以从自己的背包中拿取物品。
* *
* @param b 是否取消 * @param b 是否取消
*/ */
public void setCancelOnSelf(boolean b) { public void setCancelOnSelf(boolean b) {
this.cancelOnSelf = b; this.cancelOnSelf = b;
} }
/** /**
* 设置是否取消点击GUI外的事件 * 设置是否取消点击GUI外的事件
* 如果不取消,玩家可以把物品从GUI或背包中丢出去 * 如果不取消,玩家可以把物品从GUI或背包中丢出去
* *
* @param b 是否取消 * @param b 是否取消
*/ */
public void setCancelOnOuter(boolean b) { public void setCancelOnOuter(boolean b) {
this.cancelOnOuter = b; this.cancelOnOuter = b;
} }
public void addFlag(String flag, Object obj) { public Object getFlag(String flag) {
if (this.flags == null) this.flags = new HashMap<>(); return this.flags.get(flag);
this.flags.put(flag, obj); }
}
public Object getFlag(String flag) { public void setFlag(String flag, Object obj) {
if (this.flags == null) return null; this.flags.put(flag, obj);
else }
return this.flags.get(flag);
}
public void setFlag(String flag, Object obj) { public void removeFlag(String flag) {
if (this.flags == null) this.flags = new HashMap<>(); this.flags.remove(flag);
this.flags.replace(flag, obj); }
}
public void removeFlag(String flag) { public void rawClickListener(InventoryClickEvent event) {
if (this.flags == null) this.flags = new HashMap<>(); }
this.flags.remove(flag);
}
public void rawClickListener(InventoryClickEvent event) { public void openGUI(Player player) {
} if (this.type == GUIType.CANCEL) {
throw new IllegalStateException("被取消或不存在的GUI");
}
public void openGUI(Player player) { Inventory inv = Bukkit.createInventory(null, this.type.getSize(), this.name);
if (this.type == GUIType.CANCEL) { throw new IllegalStateException("被取消或不存在的GUI"); } IntStream.range(0, inv.getSize()).forEach(index -> inv.setItem(index, new ItemStack(Material.AIR)));
getItems().forEach((index, item) -> inv.setItem(index, item.getDisplay()));
Inventory inv = Bukkit.createInventory(null, this.type.getSize(), this.name); GUI previous = getOpenedGUI(player);
IntStream.range(0, inv.getSize()).forEach(index -> inv.setItem(index, new ItemStack(Material.AIR))); if (previous != null) {
getItems().forEach((index, item) -> inv.setItem(index, item.getDisplay())); previous.listener.close(player);
}
GUI previous = getOpenedGUI(player); setOpenedGUI(player, this);
if(previous != null){
previous.listener.close(player);
}
setOpenedGUI(player, this); this.inv = inv;
player.openInventory(inv);
this.inv = inv; if (listener == null) {
player.openInventory(inv); Bukkit.getPluginManager().registerEvents(listener = new GUIListener(this), getPlugin());
}
}
if (listener == null) { /**
Bukkit.getPluginManager().registerEvents(listener = new GUIListener(this), getPlugin()); * 拖动GUI内物品是执行的代码
} *
} * @param event InventoryDragEvent
*/
public void onDrag(InventoryDragEvent event) {
}
/** /**
* 拖动GUI内物品是执行的代码 * 关闭GUI执行的代码
* */
* @param event InventoryDragEvent public void onClose() {
*/ }
public void onDrag(InventoryDragEvent event) {
}
/** public GUIType getGUIType() {
* 关闭GUI时执行的代码 return type;
*/ }
public void onClose() {
}
public String getGUIName() {
return name;
}
public static void setOpenedGUI(Player player, GUI gui) { public static void setOpenedGUI(Player player, GUI gui) {
getOpenedGUIs().put(player.getUniqueId(), gui); getOpenedGUIs().put(player.getUniqueId(), gui);
} }
public static boolean hasOpenedGUI(Player player) { public static boolean hasOpenedGUI(Player player) {
return getOpenedGUIs().containsKey(player.getUniqueId()); return getOpenedGUIs().containsKey(player.getUniqueId());
} }
public static GUI getOpenedGUI(Player player) { public static GUI getOpenedGUI(Player player) {
return getOpenedGUIs().get(player.getUniqueId()); return getOpenedGUIs().get(player.getUniqueId());
} }
public static void removeOpenedGUI(Player player) { public static void removeOpenedGUI(Player player) {
getOpenedGUIs().remove(player.getUniqueId()); getOpenedGUIs().remove(player.getUniqueId());
} }
} }
@@ -10,64 +10,76 @@ import java.util.Set;
public class GUIItem { public class GUIItem {
ItemStack display; ItemStack display;
boolean actionActive = true; boolean actionActive = true;
public Set<GUIClickAction> actions = new HashSet<>(); public Set<GUIClickAction> actions = new HashSet<>();
public Set<GUIClickAction> actionsIgnoreActive = new HashSet<>(); public Set<GUIClickAction> actionsIgnoreActive = new HashSet<>();
public GUIItem(ItemStack display) { public GUIItem(ItemStack display) {
this.display = display; this.display = display;
} }
public final ItemStack getDisplay() { public final ItemStack getDisplay() {
return this.display; return this.display;
} }
public final void setDisplay(ItemStack display) { public final void setDisplay(ItemStack display) {
this.display = display; this.display = display;
} }
public final boolean isActionActive() { public final boolean isActionActive() {
return this.actionActive; return this.actionActive;
} }
public final void setActionActive(boolean b) { public final void setActionActive(boolean b) {
actionActive = b; actionActive = b;
} }
/** /**
* 玩家点击GUI后执行的代码 * 玩家点击该物品后执行的代码
* * 可以使用 {@link #onClick(Player, ClickType)} 操作点击者
* @param type 点击的类型 *
*/ * @param type 点击的类型
public void onClick(ClickType type) { */
@Deprecated
@SuppressWarnings("DeprecatedIsStillUsed")
public void onClick(ClickType type) {
}
} /**
* 玩家点击GUI后执行的代码
*
* @param clicker 点击的玩家
* @param type 点击的类型
*/
public void onClick(Player clicker, ClickType type) {
this.onClick(type); // Deprecated method support
}
public void addClickAction(GUIClickAction action) { public void addClickAction(GUIClickAction action) {
actions.add(action); actions.add(action);
} }
public void addActionIgnoreActive(GUIClickAction action) { public void addActionIgnoreActive(GUIClickAction action) {
actionsIgnoreActive.add(action); actionsIgnoreActive.add(action);
} }
public void rawClickAction(InventoryClickEvent event) { public void rawClickAction(InventoryClickEvent event) {
} }
/** /**
* 玩家点击GUI后执行的代码 * 自定义点击事件代码 (须自行触发)
* *
* @param player 点击GUI的玩家 * @param player 点击GUI的玩家
*/ */
public void customAction(Player player) { public void customAction(Player player) {
} }
public abstract static class GUIClickAction { public abstract static class GUIClickAction {
public abstract void run(ClickType type, Player player); public abstract void run(ClickType type, Player player);
} }
} }
@@ -11,82 +11,82 @@ import org.bukkit.event.player.PlayerQuitEvent;
public class GUIListener implements Listener { public class GUIListener implements Listener {
GUI currentGUI; GUI currentGUI;
public GUIListener(GUI gui) { public GUIListener(GUI gui) {
this.currentGUI = gui; this.currentGUI = gui;
} }
public GUI getCurrentGUI() { public GUI getCurrentGUI() {
return currentGUI; return currentGUI;
} }
@EventHandler @EventHandler
public void onInventoryClickEvent(InventoryClickEvent event) { public void onInventoryClickEvent(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return; if (!(event.getWhoClicked() instanceof Player)) return;
Player player = (Player) event.getWhoClicked(); Player player = (Player) event.getWhoClicked();
if (!GUI.hasOpenedGUI(player)) return; if (!GUI.hasOpenedGUI(player)) return;
if (GUI.getOpenedGUI(player) != getCurrentGUI()) return; if (GUI.getOpenedGUI(player) != getCurrentGUI()) return;
getCurrentGUI().rawClickListener(event); getCurrentGUI().rawClickListener(event);
if (event.getSlot() == -999 && getCurrentGUI().cancelOnOuter) { if (event.getSlot() == -999 && getCurrentGUI().cancelOnOuter) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (event.getClickedInventory() == null) return; if (event.getClickedInventory() == null) return;
if (event.getClickedInventory().equals(getCurrentGUI().inv)) { if (event.getClickedInventory().equals(getCurrentGUI().inv)) {
if (getCurrentGUI().cancelOnTarget) event.setCancelled(true); if (getCurrentGUI().cancelOnTarget) event.setCancelled(true);
if (event.getSlot() != -999) { if (event.getSlot() != -999) {
GUIItem clickedItem = getCurrentGUI().getItem(event.getSlot()); GUIItem clickedItem = getCurrentGUI().getItem(event.getSlot());
if (clickedItem != null) { if (clickedItem != null) {
if (clickedItem.isActionActive()) { if (clickedItem.isActionActive()) {
clickedItem.onClick(event.getClick()); clickedItem.onClick(player, event.getClick());
clickedItem.rawClickAction(event); clickedItem.rawClickAction(event);
clickedItem.actions.forEach(action -> action.run(event.getClick(), player)); clickedItem.actions.forEach(action -> action.run(event.getClick(), player));
} }
clickedItem.actionsIgnoreActive.forEach(action -> action.run(event.getClick(), player)); clickedItem.actionsIgnoreActive.forEach(action -> action.run(event.getClick(), player));
} }
} }
} else if (event.getClickedInventory().equals(player.getInventory()) && getCurrentGUI().cancelOnSelf) { } else if (event.getClickedInventory().equals(player.getInventory()) && getCurrentGUI().cancelOnSelf) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@EventHandler @EventHandler
public void onDrag(InventoryDragEvent e) { public void onDrag(InventoryDragEvent e) {
if (!(e.getWhoClicked() instanceof Player)) return; if (!(e.getWhoClicked() instanceof Player)) return;
if (e.getInventory().equals(getCurrentGUI().inv) if (e.getInventory().equals(getCurrentGUI().inv)
|| e.getInventory().equals(e.getWhoClicked().getInventory())) { || e.getInventory().equals(e.getWhoClicked().getInventory())) {
getCurrentGUI().onDrag(e); getCurrentGUI().onDrag(e);
} }
} }
@EventHandler @EventHandler
public void onInventoryCloseEvent(InventoryCloseEvent event) { public void onInventoryCloseEvent(InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof Player)) return; if (!(event.getPlayer() instanceof Player)) return;
if (!event.getInventory().equals(getCurrentGUI().inv)) return; if (!event.getInventory().equals(getCurrentGUI().inv)) return;
close((Player) event.getPlayer()); close((Player) event.getPlayer());
} }
protected void close(Player p){ protected void close(Player p) {
HandlerList.unregisterAll(this); HandlerList.unregisterAll(this);
getCurrentGUI().listener = null; getCurrentGUI().listener = null;
GUI.removeOpenedGUI(p); GUI.removeOpenedGUI(p);
getCurrentGUI().onClose(); getCurrentGUI().onClose();
} }
@EventHandler @EventHandler
public void onPlayerLeave(PlayerQuitEvent event) { public void onPlayerLeave(PlayerQuitEvent event) {
GUI.removeOpenedGUI(event.getPlayer()); GUI.removeOpenedGUI(event.getPlayer());
} }
} }
@@ -6,44 +6,44 @@ import java.util.Arrays;
public enum GUIType { public enum GUIType {
ONE_BY_NINE(1, 9), ONE_BY_NINE(1, 9),
TWO_BY_NINE(2, 18), TWO_BY_NINE(2, 18),
THREE_BY_NINE(3, 27), THREE_BY_NINE(3, 27),
FOUR_BY_NINE(4, 36), FOUR_BY_NINE(4, 36),
FIVE_BY_NINE(5, 45), FIVE_BY_NINE(5, 45),
SIX_BY_NINE(6, 54), SIX_BY_NINE(6, 54),
CANCEL(0, 0); CANCEL(0, 0);
int lines; private final int lines;
int size; private final int size;
GUIType(int lines, int size) { GUIType(int lines, int size) {
this.lines = lines; this.lines = lines;
this.size = size; this.size = size;
} }
public int getLines() { public int getLines() {
return lines; return lines;
} }
public int getSize() { public int getSize() {
return size; return size;
} }
@NotNull @NotNull
public static GUIType getBySize(int size) { public static GUIType getBySize(int size) {
return Arrays.stream(values()).filter(type -> type.getSize() == size).findFirst().orElse(CANCEL); return Arrays.stream(values()).filter(type -> type.getSize() == size).findFirst().orElse(CANCEL);
} }
@NotNull @NotNull
public static GUIType getByLines(int lines) { public static GUIType getByLines(int lines) {
return Arrays.stream(values()).filter(type -> type.getLines() == lines).findFirst().orElse(CANCEL); return Arrays.stream(values()).filter(type -> type.getLines() == lines).findFirst().orElse(CANCEL);
} }
@NotNull @NotNull
public static GUIType getByName(String name) { public static GUIType getByName(String name) {
return Arrays.stream(values()).filter(type -> type.name().equalsIgnoreCase(name)).findFirst().orElse(CANCEL); return Arrays.stream(values()).filter(type -> type.name().equalsIgnoreCase(name)).findFirst().orElse(CANCEL);
} }
} }
@@ -3,51 +3,104 @@ package cc.carm.lib.easyplugin.gui.configuration;
import cc.carm.lib.easyplugin.gui.GUIItem; import cc.carm.lib.easyplugin.gui.GUIItem;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class GUIActionConfiguration { public class GUIActionConfiguration {
public static @NotNull GUIActionConfiguration of(@NotNull GUIActionType actionType,
@Nullable ClickType clickType,
@Nullable String actionContent) {
return new GUIActionConfiguration(actionType, clickType, actionContent);
}
@Nullable ClickType clickType; public static @NotNull GUIActionConfiguration of(@NotNull GUIActionType actionType,
final @NotNull GUIActionType actionType; @Nullable String actionContent) {
final @Nullable String actionContent; return of(actionType, null, actionContent);
}
public GUIActionConfiguration(@Nullable ClickType clickType, public static @NotNull GUIActionConfiguration of(@NotNull GUIActionType actionType,
@NotNull GUIActionType actionType, @Nullable ClickType clickType) {
@Nullable String actionContent) { return of(actionType, clickType, null);
this.clickType = clickType; }
this.actionType = actionType;
this.actionContent = actionContent;
}
public @Nullable ClickType getClickType() { public static @NotNull GUIActionConfiguration of(@NotNull GUIActionType actionType) {
return clickType; return of(actionType, null, null);
} }
public @NotNull GUIActionType getActionType() { protected final @NotNull GUIActionType actionType;
return actionType;
}
public @Nullable String getActionContent() { protected final @Nullable ClickType clickType;
return actionContent; protected final @Nullable String actionContent;
}
public void checkAction(Player player, ClickType type) { public GUIActionConfiguration(@NotNull GUIActionType actionType,
if (getClickType() == null || getClickType() == type) executeAction(player); @Nullable ClickType clickType,
} @Nullable String actionContent) {
this.clickType = clickType;
this.actionType = actionType;
this.actionContent = actionContent;
}
public void executeAction(Player targetPlayer) { public @Nullable ClickType getClickType() {
getActionType().getExecutor().accept(targetPlayer, getActionContent()); return clickType;
} }
public GUIItem.GUIClickAction toClickAction() { public @NotNull GUIActionType getActionType() {
return new GUIItem.GUIClickAction() { return actionType;
@Override }
public void run(ClickType type, Player player) {
checkAction(player, type); public @Nullable String getActionContent() {
} return actionContent;
}; }
}
public void checkAction(Player player, ClickType type) {
if (getClickType() == null || getClickType() == type) executeAction(player);
}
public void executeAction(Player targetPlayer) {
getActionType().getExecutor().accept(targetPlayer, getActionContent());
}
public GUIItem.GUIClickAction toClickAction() {
return new GUIItem.GUIClickAction() {
@Override
public void run(ClickType type, Player player) {
checkAction(player, type);
}
};
}
@Nullable
@Contract("null->null")
public static GUIActionConfiguration deserialize(@Nullable String actionString) {
if (actionString == null) return null;
int prefixStart = actionString.indexOf("[");
int prefixEnd = actionString.indexOf("]");
if (prefixStart < 0 || prefixEnd < 0) return null;
String prefix = actionString.substring(prefixStart + 1, prefixEnd);
ClickType clickType = null;
GUIActionType actionType;
if (prefix.contains(":")) {
String[] args = prefix.split(":");
clickType = GUIConfiguration.readClickType(args[0]);
actionType = GUIActionType.readActionType(args[1]);
} else {
actionType = GUIActionType.readActionType(prefix);
}
if (actionType == null) return null;
String content = actionString.substring(prefixEnd + 1).trim();
return of(actionType, clickType, content);
}
public @NotNull String serialize() {
String prefix = "[" + getActionType().name() + (getClickType() == null ? "" : ":" + getClickType().name()) + "]";
String content = getActionContent() == null ? "" : " " + getActionContent();
return prefix + content;
}
} }
@@ -13,76 +13,76 @@ import java.util.function.BiConsumer;
public enum GUIActionType { public enum GUIActionType {
/** /**
* 以玩家聊天的形式执行 * 以玩家聊天的形式执行
* 若内容以 “/" 开头,则会以玩家身份执行命令。 * 若内容以 “/" 开头,则会以玩家身份执行命令。
*/ */
CHAT((player, string) -> { CHAT((player, string) -> {
if (string == null) return; if (string == null) return;
MessageUtils.setPlaceholders(player, Collections.singletonList(string)).forEach(player::chat); MessageUtils.setPlaceholders(player, Collections.singletonList(string)).forEach(player::chat);
}), }),
/** /**
* 以后台的形式执行指令 * 以后台的形式执行指令
* 指令内容不需要以“/”开头。 * 指令内容不需要以“/”开头。
*/ */
CONSOLE((player, string) -> { CONSOLE((player, string) -> {
if (string == null) return; if (string == null) return;
MessageUtils.setPlaceholders(player, Collections.singletonList(string)) MessageUtils.setPlaceholders(player, Collections.singletonList(string))
.forEach(message -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), message)); .forEach(message -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), message));
}), }),
/** /**
* 向玩家发送消息。 * 向玩家发送消息。
*/ */
MESSAGE(MessageUtils::send), MESSAGE(MessageUtils::send),
/** /**
* 向玩家发送声音。 * 向玩家发送声音。
* 允许配置音量与音调 * 允许配置音量与音调
* <ul> * <ul>
* <li>SOUND_NAME</li> * <li>SOUND_NAME</li>
* <li>SOUND_NAME:VOLUME</li> * <li>SOUND_NAME:VOLUME</li>
* <li>SOUND_NAME:VOLUME:PITCH</li> * <li>SOUND_NAME:VOLUME:PITCH</li>
* </ul> * </ul>
*/ */
SOUND((player, string) -> { SOUND((player, string) -> {
if (string == null) return; if (string == null) return;
try { try {
String[] args = string.contains(":") ? string.split(":") : new String[]{string}; String[] args = string.contains(":") ? string.split(":") : new String[]{string};
Sound sound = Arrays.stream(Sound.values()) Sound sound = Arrays.stream(Sound.values())
.filter(s -> s.name().equals(args[0])) .filter(s -> s.name().equals(args[0]))
.findFirst().orElse(null); .findFirst().orElse(null);
if (sound == null) return; if (sound == null) return;
float volume = args.length > 1 ? Float.parseFloat(args[1]) : 1F; float volume = args.length > 1 ? Float.parseFloat(args[1]) : 1F;
float pitch = args.length > 2 ? Float.parseFloat(args[2]) : 1F; float pitch = args.length > 2 ? Float.parseFloat(args[2]) : 1F;
player.playSound(player.getLocation(), sound, volume, pitch); player.playSound(player.getLocation(), sound, volume, pitch);
} catch (Exception ignored) { } catch (Exception ignored) {
} }
}), }),
/** /**
* 为玩家关闭GUI。 * 为玩家关闭GUI。
*/ */
CLOSE((player, string) -> player.closeInventory()); CLOSE((player, string) -> player.closeInventory());
BiConsumer<@NotNull Player, @Nullable String> executor; BiConsumer<@NotNull Player, @Nullable String> executor;
GUIActionType(BiConsumer<@NotNull Player, @Nullable String> executor) { GUIActionType(BiConsumer<@NotNull Player, @Nullable String> executor) {
this.executor = executor; this.executor = executor;
} }
public BiConsumer<@NotNull Player, @Nullable String> getExecutor() { public BiConsumer<@NotNull Player, @Nullable String> getExecutor() {
return executor; return executor;
} }
public static GUIActionType readActionType(String string) { public static GUIActionType readActionType(String string) {
return Arrays.stream(GUIActionType.values()) return Arrays.stream(GUIActionType.values())
.filter(action -> action.name().equalsIgnoreCase(string)) .filter(action -> action.name().equalsIgnoreCase(string))
.findFirst().orElse(null); .findFirst().orElse(null);
} }
} }
@@ -6,67 +6,93 @@ import cc.carm.lib.easyplugin.utils.ColorParser;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.Arrays;
import java.util.stream.Collectors; import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
public class GUIConfiguration { public class GUIConfiguration {
String title; protected String title;
int lines; protected int lines;
List<GUIItemConfiguration> guiItems; protected Map<String, GUIItemConfiguration> guiItems;
public GUIConfiguration(String title, int lines, List<GUIItemConfiguration> guiItems) { public GUIConfiguration(String title, int lines) {
this.title = title; this(title, lines, new LinkedHashMap<>(1));
this.lines = lines; }
this.guiItems = guiItems;
}
public String getTitle() { public GUIConfiguration(String title, int lines, Map<String, GUIItemConfiguration> guiItems) {
return ColorParser.parse(title); this.title = title;
} this.lines = lines;
this.guiItems = guiItems;
}
public int getLines() { public String getTitle() {
return lines; return ColorParser.parse(title);
} }
public GUIType getGUIType() { public int getLines() {
return Optional.of(GUIType.getByLines(lines)) return lines;
.map(type -> type == GUIType.CANCEL ? GUIType.SIX_BY_NINE : type) }
.get();
}
public List<GUIItemConfiguration> getGuiItems() { public GUIType getGUIType() {
return guiItems; return Optional.of(GUIType.getByLines(lines))
} .map(type -> type == GUIType.CANCEL ? GUIType.SIX_BY_NINE : type)
.get();
}
public void setupItems(Player player, GUI gui) { public Map<String, GUIItemConfiguration> getGUIItems() {
getGuiItems().forEach(itemConfiguration -> itemConfiguration.setupItems(player, gui)); return guiItems;
} }
public void setupItems(Player player, GUI gui) {
getGUIItems().values().forEach(itemConfiguration -> itemConfiguration.setupItems(player, gui));
}
public @NotNull Map<String, Object> serialize() {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("title", this.title);
map.put("lines", this.lines);
if (!this.guiItems.isEmpty()) {
LinkedHashMap<String, Object> items = new LinkedHashMap<>();
this.guiItems.forEach((key, value) -> items.put(key, value.serialize()));
map.put("items", items);
}
return map;
}
public static GUIConfiguration readConfiguration(@Nullable ConfigurationSection section) { public static GUIConfiguration readConfiguration(@Nullable ConfigurationSection section) {
if (section == null) return new GUIConfiguration("name", 6, new ArrayList<>()); if (section == null) return new GUIConfiguration("name", 6);
String title = section.getString("title", ""); return new GUIConfiguration(
int lines = section.getInt("lines", 6); section.getString("title", ""),
ConfigurationSection itemsSection = section.getConfigurationSection("items"); section.getInt("lines", 6),
if (itemsSection == null) return new GUIConfiguration(title, lines, new ArrayList<>()); readItems(section.getConfigurationSection("items"))
);
}
return new GUIConfiguration( public static Map<String, GUIItemConfiguration> readItems(ConfigurationSection itemsSection) {
title, lines, itemsSection.getKeys(false).stream() Map<String, GUIItemConfiguration> items = new LinkedHashMap<>();
.map(key -> GUIItemConfiguration.readFrom(itemsSection.getConfigurationSection(key))) if (itemsSection == null) return items;
.filter(Objects::nonNull)
.collect(Collectors.toList())
);
}
public static ClickType readClickType(String type) { for (String key : itemsSection.getKeys(false)) {
return Arrays.stream(ClickType.values()) GUIItemConfiguration item = GUIItemConfiguration.readFrom(itemsSection.getConfigurationSection(key));
.filter(click -> click.name().equalsIgnoreCase(type)) if (item != null) items.put(key, item);
.findFirst().orElse(null); }
}
return items;
}
public static ClickType readClickType(String type) {
return Arrays.stream(ClickType.values())
.filter(click -> click.name().equalsIgnoreCase(type))
.findFirst().orElse(null);
}
} }
@@ -2,91 +2,149 @@ package cc.carm.lib.easyplugin.gui.configuration;
import cc.carm.lib.easyplugin.gui.GUI; import cc.carm.lib.easyplugin.gui.GUI;
import cc.carm.lib.easyplugin.gui.GUIItem; 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.ItemStackFactory;
import cc.carm.lib.easyplugin.utils.MessageUtils; import cc.carm.lib.easyplugin.utils.MessageUtils;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.*;
import java.util.Collections; import java.util.stream.Collectors;
import java.util.List;
import java.util.Optional;
public class GUIItemConfiguration { public class GUIItemConfiguration {
Material material; @Nullable ItemStack original;
int data;
String name;
@NotNull List<String> lore;
@NotNull List<Integer> slots; @NotNull Material type;
@NotNull List<GUIActionConfiguration> actions; int amount;
int data;
@Nullable String name;
@NotNull List<String> lore;
public GUIItemConfiguration(Material material, int data, @NotNull List<Integer> slots;
String name, @NotNull List<String> lore, @NotNull List<GUIActionConfiguration> actions;
@NotNull List<GUIActionConfiguration> actions,
@NotNull List<Integer> slots) {
this.material = material;
this.data = data;
this.name = name;
this.lore = lore;
this.slots = slots;
this.actions = actions;
}
public void setupItems(Player player, GUI gui) { public GUIItemConfiguration(@NotNull Material type, int amount, int data,
ItemStackFactory icon = new ItemStackFactory(this.material); @Nullable String name, @NotNull List<String> lore,
icon.setDurability(this.data); @NotNull List<GUIActionConfiguration> actions,
if (this.name != null) icon.setDisplayName(this.name); @NotNull List<Integer> slots) {
icon.setLore(MessageUtils.setPlaceholders(player, this.lore)); this(null, type, amount, data, name, lore, actions, slots);
}
GUIItem item = new GUIItem(icon.toItemStack()); public GUIItemConfiguration(@Nullable ItemStack original,
this.actions.stream().map(GUIActionConfiguration::toClickAction).forEach(item::addClickAction); @NotNull Material type, int amount, int data,
this.slots.forEach(slot -> gui.setItem(slot, item)); @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;
this.name = name;
this.lore = lore;
this.slots = slots;
this.actions = actions;
}
@Nullable public void setupItems(Player player, GUI gui) {
public static GUIItemConfiguration readFrom(@Nullable ConfigurationSection itemSection) { ItemStack itemStack;
if (itemSection == null) return null; if (original != null) {
Material material = Optional.ofNullable(Material.matchMaterial(itemSection.getString("material", "STONE"))).orElse(Material.STONE); ItemStack tmp = original.clone();
int data = itemSection.getInt("data", 0); ItemMeta originalMeta = original.getItemMeta();
String name = itemSection.getString("name"); if (originalMeta != null) {
List<String> lore = itemSection.getStringList("lore"); if (originalMeta.hasDisplayName()) {
originalMeta.setDisplayName(parseText(player, originalMeta.getDisplayName()));
}
if (originalMeta.getLore() != null) {
originalMeta.setLore(parseTexts(player, originalMeta.getLore()));
}
List<Integer> slots = itemSection.getIntegerList("slots"); }
int slot = itemSection.getInt("slot", 0);
List<String> actionsString = itemSection.getStringList("actions"); tmp.setItemMeta(originalMeta);
List<GUIActionConfiguration> actions = new ArrayList<>(); itemStack = tmp;
for (String actionString : actionsString) { } else {
int prefixStart = actionString.indexOf("["); ItemStackFactory icon = new ItemStackFactory(this.type, this.amount, this.data);
int prefixEnd = actionString.indexOf("]"); if (this.name != null) {
if (prefixStart < 0 || prefixEnd < 0) continue; icon.setDisplayName(parseText(player, this.name));
}
if (!this.lore.isEmpty()) {
icon.setLore(parseTexts(player, this.lore));
}
itemStack = icon.toItemStack();
}
String prefix = actionString.substring(prefixStart + 1, prefixEnd);
ClickType clickType = null;
GUIActionType actionType;
if (prefix.contains(":")) {
String[] args = prefix.split(":");
clickType = GUIConfiguration.readClickType(args[0]);
actionType = GUIActionType.readActionType(args[1]);
} else {
actionType = GUIActionType.readActionType(prefix);
}
if (actionType == null) continue; GUIItem item = new GUIItem(itemStack);
actions.add(new GUIActionConfiguration(clickType, actionType, actionString.substring(prefixEnd + 1).trim())); this.actions.stream().map(GUIActionConfiguration::toClickAction).forEach(item::addClickAction);
} this.slots.forEach(slot -> gui.setItem(slot, item));
}
return new GUIItemConfiguration( private List<String> parseTexts(Player player, List<String> lore) {
material, data, name, lore, actions, return ColorParser.parse(MessageUtils.setPlaceholders(player, lore));
slots.size() > 0 ? slots : Collections.singletonList(slot) }
);
}
@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);
}
if (this.name != null) map.put("name", this.name);
if (this.amount != 1) map.put("amount", this.amount);
if (!this.lore.isEmpty()) map.put("lore", this.lore);
if (this.slots.size() > 1) {
map.put("slots", this.slots);
} else if (slots.size() == 1) {
map.put("slot", this.slots.get(0));
}
if (!this.actions.isEmpty()) {
map.put("actions", this.actions.stream().map(GUIActionConfiguration::serialize).collect(Collectors.toList()));
}
return map;
}
@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);
int amount = itemSection.getInt("amount", 1);
String name = itemSection.getString("name");
List<String> lore = itemSection.getStringList("lore");
List<Integer> slots = itemSection.getIntegerList("slots");
int slot = itemSection.getInt("slot", 0);
List<String> actionsString = itemSection.getStringList("actions");
List<GUIActionConfiguration> actions = new ArrayList<>();
for (String actionString : actionsString) {
GUIActionConfiguration action = GUIActionConfiguration.deserialize(actionString);
if (action == null) continue;
actions.add(action);
}
return new GUIItemConfiguration(
original, type, amount, data, name, lore, actions,
slots.size() > 0 ? slots : Collections.singletonList(slot)
);
}
} }
@@ -10,87 +10,87 @@ import java.util.function.Function;
public class AutoPagedGUI extends CommonPagedGUI { public class AutoPagedGUI extends CommonPagedGUI {
public static Function<Player, ItemStack> defaultPreviousPage = null; public static Function<Player, ItemStack> defaultPreviousPage = null;
public static Function<Player, ItemStack> defaultNextPage = null; public static Function<Player, ItemStack> defaultNextPage = null;
ItemStack previousPageUI; ItemStack previousPageUI;
ItemStack nextPageUI; ItemStack nextPageUI;
int previousPageSlot = -1; int previousPageSlot = -1;
int nextPageSlot = -1; int nextPageSlot = -1;
public AutoPagedGUI(GUIType type, String name, int[] range) { public AutoPagedGUI(GUIType type, String name, int[] range) {
super(type, name, range); super(type, name, range);
} }
public AutoPagedGUI(GUIType type, String name, int a, int b) { public AutoPagedGUI(GUIType type, String name, int a, int b) {
super(type, name, a, b); super(type, name, a, b);
} }
public void setPreviousPageUI(ItemStack lastPageUI) { public void setPreviousPageUI(ItemStack lastPageUI) {
this.previousPageUI = lastPageUI; this.previousPageUI = lastPageUI;
} }
public void setNextPageUI(ItemStack nextPageUI) { public void setNextPageUI(ItemStack nextPageUI) {
this.nextPageUI = nextPageUI; this.nextPageUI = nextPageUI;
} }
public void setPreviousPageSlot(int slot) { public void setPreviousPageSlot(int slot) {
this.previousPageSlot = slot; this.previousPageSlot = slot;
} }
public void setNextPageSlot(int slot) { public void setNextPageSlot(int slot) {
this.nextPageSlot = slot; this.nextPageSlot = slot;
} }
@Override @Override
public void openGUI(Player user) { public void openGUI(Player user) {
if (previousPageSlot >= 0) { if (previousPageSlot >= 0) {
if (hasPreviousPage()) { if (hasPreviousPage()) {
setItem(previousPageSlot, new GUIItem( setItem(previousPageSlot, new GUIItem(
previousPageUI == null ? getDefaultPreviousPage(user) : previousPageUI) { previousPageUI == null ? getDefaultPreviousPage(user) : previousPageUI) {
@Override @Override
public void onClick(ClickType type) { public void onClick(Player clicker, ClickType type) {
if (type == ClickType.RIGHT) { if (type == ClickType.RIGHT) {
goFirstPage(); goFirstPage();
} else { } else {
goPreviousPage(); goPreviousPage();
} }
openGUI(user); openGUI(user);
} }
}); });
} else { } else {
setItem(previousPageSlot, null); setItem(previousPageSlot, null);
} }
} }
if (nextPageSlot >= 0) { if (nextPageSlot >= 0) {
if (hasNextPage()) { if (hasNextPage()) {
setItem(nextPageSlot, new GUIItem( setItem(nextPageSlot, new GUIItem(
nextPageUI == null ? getDefaultNextPage(user) : nextPageUI) { nextPageUI == null ? getDefaultNextPage(user) : nextPageUI) {
@Override @Override
public void onClick(ClickType type) { public void onClick(Player clicker, ClickType type) {
if (type == ClickType.RIGHT) { if (type == ClickType.RIGHT) {
goLastPage(); goLastPage();
} else { } else {
goNextPage(); goNextPage();
} }
openGUI(user); openGUI(user);
} }
}); });
} else { } else {
setItem(nextPageSlot, null); setItem(nextPageSlot, null);
} }
} }
super.openGUI(user); super.openGUI(user);
} }
private static ItemStack getDefaultNextPage(Player player) { private static ItemStack getDefaultNextPage(Player player) {
return defaultNextPage != null ? defaultNextPage.apply(player) : null; return defaultNextPage != null ? defaultNextPage.apply(player) : null;
} }
private static ItemStack getDefaultPreviousPage(Player player) { private static ItemStack getDefaultPreviousPage(Player player) {
return defaultPreviousPage != null ? defaultPreviousPage.apply(player) : null; return defaultPreviousPage != null ? defaultPreviousPage.apply(player) : null;
} }
} }
@@ -11,22 +11,22 @@ import java.util.List;
public class CommonPagedGUI extends PagedGUI { public class CommonPagedGUI extends PagedGUI {
private int[] range; private int[] range;
private CommonPagedGUI(GUIType type, String name) { private CommonPagedGUI(GUIType type, String name) {
super(type, name); super(type, name);
} }
public CommonPagedGUI(GUIType type, String Name, int a, int b) { public CommonPagedGUI(GUIType type, String Name, int a, int b) {
this(type, Name, toRange(type, a, b)); this(type, Name, toRange(type, a, b));
} }
public CommonPagedGUI(GUIType type, String Name, int[] range) { public CommonPagedGUI(GUIType type, String Name, int[] range) {
super(type, Name); super(type, Name);
Arrays.sort(range); Arrays.sort(range);
this.range = range; this.range = range;
} }
@@ -41,122 +41,122 @@ public class CommonPagedGUI extends PagedGUI {
} }
*/ */
private static int[] toRange(GUIType type, int a, int b) { private static int[] toRange(GUIType type, int a, int b) {
if (a > b) { if (a > b) {
a = a ^ b; a = a ^ b;
b = a ^ b; b = a ^ b;
a = a ^ b; a = a ^ b;
} }
int lineA = getLine(a); int lineA = getLine(a);
int columnA = getColumn(a); int columnA = getColumn(a);
int lineB = getLine(b); int lineB = getLine(b);
int columnB = getColumn(b); int columnB = getColumn(b);
if (lineB > type.getLines()) if (lineB > type.getLines())
throw new IndexOutOfBoundsException("页面内容范围超过了GUI的大小"); throw new IndexOutOfBoundsException("页面内容范围超过了GUI的大小");
int[] range = new int[(lineB - lineA + 1) * (columnB - columnA + 1)]; int[] range = new int[(lineB - lineA + 1) * (columnB - columnA + 1)];
for (int i = 0, l = 0; i < type.getSize(); i++) { for (int i = 0, l = 0; i < type.getSize(); i++) {
int li = getLine(i); int li = getLine(i);
int ci = getColumn(i); int ci = getColumn(i);
if (li >= lineA && li <= lineB && ci >= columnA && ci <= columnB) { if (li >= lineA && li <= lineB && ci >= columnA && ci <= columnB) {
range[l] = i; range[l] = i;
l++; l++;
} }
} }
return range; return range;
} }
private static int getLine(int i) { private static int getLine(int i) {
return i / 9 + 1; return i / 9 + 1;
} }
private static int getColumn(int i) { private static int getColumn(int i) {
return i % 9 + 1; return i % 9 + 1;
} }
@Override @Override
public boolean hasPreviousPage() { public boolean hasPreviousPage() {
return page > 1; return page > 1;
} }
@Override @Override
public boolean hasNextPage() { public boolean hasNextPage() {
return page < getLastPageNumber(); return page < getLastPageNumber();
} }
/** /**
* 前往第一页 * 前往第一页
*/ */
public void goFirstPage() { public void goFirstPage() {
if (hasPreviousPage()) if (hasPreviousPage())
this.page = 1; this.page = 1;
else else
throw new IndexOutOfBoundsException(); throw new IndexOutOfBoundsException();
} }
/** /**
* 前往最后一页 * 前往最后一页
*/ */
public void goLastPage() { public void goLastPage() {
if (hasNextPage()) if (hasNextPage())
this.page = getLastPageNumber(); this.page = getLastPageNumber();
else else
throw new IndexOutOfBoundsException(); throw new IndexOutOfBoundsException();
} }
/** /**
* 得到最后一页的页码 * 得到最后一页的页码
* *
* @return 最后一页的页码 * @return 最后一页的页码
*/ */
public int getLastPageNumber() { public int getLastPageNumber() {
return (this.container.size() / range.length) + 1; return (this.container.size() / range.length) + 1;
} }
/** /**
* 得到第一页的页码 * 得到第一页的页码
* *
* @return 第一页页码(默认为1) * @return 第一页页码(默认为1)
*/ */
public int getFirstPageNumber() { public int getFirstPageNumber() {
return 1; return 1;
} }
@Override @Override
public void openGUI(Player player) { public void openGUI(Player player) {
if (container.isEmpty()) { if (container.isEmpty()) {
super.openGUI(player); super.openGUI(player);
return; return;
} }
List<GUIItem> list = new ArrayList<>(); List<GUIItem> list = new ArrayList<>();
int start = (page - 1) * range.length; int start = (page - 1) * range.length;
for (int i = start; i < start + range.length; i++) { for (int i = start; i < start + range.length; i++) {
if (i < container.size()) { if (i < container.size()) {
list.add(container.get(i)); list.add(container.get(i));
} else { } else {
break; break;
} }
} }
int i = 0; int i = 0;
Arrays.stream(range).forEach(index -> setItem(index, null)); Arrays.stream(range).forEach(index -> setItem(index, null));
for (int index : range) { for (int index : range) {
if (i < list.size()) { if (i < list.size()) {
setItem(index, list.get(i)); setItem(index, list.get(i));
i++; i++;
} else { } else {
break; break;
} }
} }
super.openGUI(player); super.openGUI(player);
} }
} }
@@ -10,70 +10,70 @@ import java.util.List;
public abstract class PagedGUI extends GUI { public abstract class PagedGUI extends GUI {
List<GUIItem> container = new ArrayList<>(); List<GUIItem> container = new ArrayList<>();
public int page = 1; public int page = 1;
public PagedGUI(GUIType type, String name) { public PagedGUI(GUIType type, String name) {
super(type, name); super(type, name);
} }
public int addItem(GUIItem i) { public int addItem(GUIItem i) {
container.add(i); container.add(i);
return container.size() - 1; return container.size() - 1;
} }
/** /**
* 从GUI中移除一个物品 * 从GUI中移除一个物品
* *
* @param item 物品 * @param item 物品
*/ */
public void removeItem(GUIItem item) { public void removeItem(GUIItem item) {
container.remove(item); container.remove(item);
} }
/** /**
* 从GUI中移除一个物品 * 从GUI中移除一个物品
* *
* @param slot 物品格子数 * @param slot 物品格子数
*/ */
public void removeItem(int slot) { public void removeItem(int slot) {
container.remove(slot); container.remove(slot);
} }
public List<GUIItem> getItemsContainer() { public List<GUIItem> getItemsContainer() {
return new ArrayList<>(container); return new ArrayList<>(container);
} }
/** /**
* 前往上一页 * 前往上一页
*/ */
public void goPreviousPage() { public void goPreviousPage() {
if (hasPreviousPage()) if (hasPreviousPage())
page--; page--;
else else
throw new IndexOutOfBoundsException(); throw new IndexOutOfBoundsException();
} }
/** /**
* 前往下一页 * 前往下一页
*/ */
public void goNextPage() { public void goNextPage() {
if (hasNextPage()) if (hasNextPage())
page++; page++;
else else
throw new IndexOutOfBoundsException(); throw new IndexOutOfBoundsException();
} }
/** /**
* @return 是否有上一页 * @return 是否有上一页
*/ */
public abstract boolean hasPreviousPage(); public abstract boolean hasPreviousPage();
/** /**
* @return 是否有下一页 * @return 是否有下一页
*/ */
public abstract boolean hasNextPage(); public abstract boolean hasNextPage();
} }
+31 -32
View File
@@ -1,4 +1,3 @@
import cc.carm.lib.easyplugin.gui.configuration.GUIActionType; import cc.carm.lib.easyplugin.gui.configuration.GUIActionType;
import cc.carm.lib.easyplugin.gui.configuration.GUIConfiguration; import cc.carm.lib.easyplugin.gui.configuration.GUIConfiguration;
import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.ClickType;
@@ -10,43 +9,43 @@ import java.util.List;
public class ActionReadTest { public class ActionReadTest {
@Test @Test
public void test() { public void test() {
List<String> actions = Arrays.asList( List<String> actions = Arrays.asList(
"[CHAT] 123123", "[CHAT] 123123",
"[SHIFT_LEFT:CHAT] /test qwq", "[SHIFT_LEFT:CHAT] /test qwq",
"[CONSOLE] say hello", "[CONSOLE] say hello",
"[CLOSE]" "[CLOSE]"
); );
for (String actionString : actions) { for (String actionString : actions) {
int prefixStart = actionString.indexOf("["); int prefixStart = actionString.indexOf("[");
int prefixEnd = actionString.indexOf("]"); int prefixEnd = actionString.indexOf("]");
if (prefixStart < 0 || prefixEnd < 0) continue; if (prefixStart < 0 || prefixEnd < 0) continue;
String prefix = actionString.substring(prefixStart + 1, prefixEnd); String prefix = actionString.substring(prefixStart + 1, prefixEnd);
ClickType clickType = null; ClickType clickType = null;
GUIActionType actionType; GUIActionType actionType;
if (prefix.contains(":")) { if (prefix.contains(":")) {
String[] args = prefix.split(":"); String[] args = prefix.split(":");
clickType = GUIConfiguration.readClickType(args[0]); clickType = GUIConfiguration.readClickType(args[0]);
actionType = GUIActionType.readActionType(args[1]); actionType = GUIActionType.readActionType(args[1]);
} else { } else {
actionType = GUIActionType.readActionType(prefix); actionType = GUIActionType.readActionType(prefix);
} }
if (actionType == null) { if (actionType == null) {
System.out.println("# " + actionString); System.out.println("# " + actionString);
System.out.println("- actionType is Null"); System.out.println("- actionType is Null");
continue; continue;
} }
System.out.println("# " + actionType.name() + " " + (clickType == null ? "" : clickType.name())); System.out.println("# " + actionType.name() + " " + (clickType == null ? "" : clickType.name()));
System.out.println("- " + actionString.substring(prefixEnd + 1).trim()); System.out.println("- " + actionString.substring(prefixEnd + 1).trim());
} }
} }
} }
+80
View File
@@ -0,0 +1,80 @@
<?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.20</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-listener</artifactId>
<name>EasyPlugin-Listener</name>
<description>轻松插件监听器接口模块,基于 EasyListener 项目。</description>
<url>https://github.com/CarmJos/EasyPlugin</url>
<licenses>
<license>
<name>GNU LESSER GENERAL PUBLIC LICENSE</name>
<url>https://www.gnu.org/licenses/lgpl-3.0.html</url>
</license>
</licenses>
<dependencies>
<dependency>
<!-- https://github.com/CarmJos/EasyListener -->
<groupId>cc.carm.lib</groupId>
<artifactId>easylistener</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>cc.carm.lib.easylistener</pattern>
<shadedPattern>cc.carm.lib.easyplugin.listener</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
<exclude>META-INF/*.txt</exclude>
</excludes>
</filter>
</filters>
</configuration>
</plugin>
</plugins>
</build>
</project>
+9 -3
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.6</version> <version>1.4.20</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -22,7 +22,7 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<name>EasyPlugin-Main</name> <name>EasyPlugin-Main</name>
<description>轻松插件主要接口模块,包含便的插件入口类与相关工具类。</description> <description>轻松插件主要接口模块,包含便的插件入口类与相关工具类。</description>
<url>https://github.com/CarmJos/EasyPlugin</url> <url>https://github.com/CarmJos/EasyPlugin</url>
<developers> <developers>
@@ -53,10 +53,16 @@
<dependencies> <dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>easyplugin-utils</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>me.clip</groupId> <groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId> <artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
@@ -9,31 +9,45 @@ import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter; import org.bukkit.command.TabCompleter;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public abstract class EasyPlugin extends JavaPlugin { public abstract class EasyPlugin extends JavaPlugin {
protected EasyPluginMessageProvider messageProvider; protected @NotNull EasyPluginMessageProvider messageProvider;
public EasyPlugin() { public EasyPlugin() {
this(EasyPluginMessageProvider.ZH_CN); this(EasyPluginMessageProvider.ZH_CN);
} }
public EasyPlugin(EasyPluginMessageProvider messageProvider) { public EasyPlugin(@NotNull EasyPluginMessageProvider messageProvider) {
this.messageProvider = messageProvider; this.messageProvider = messageProvider;
} }
private SchedulerUtils scheduler; protected EasyPlugin(JavaPluginLoader loader, PluginDescriptionFile descriptionFile, File dataFolder, File file) {
private boolean initialized = false; this(EasyPluginMessageProvider.ZH_CN, loader, descriptionFile, dataFolder, file);
}
protected EasyPlugin(@NotNull EasyPluginMessageProvider messageProvider,
JavaPluginLoader loader, PluginDescriptionFile descriptionFile, File dataFolder, File file) {
super(loader, descriptionFile, dataFolder, file);
this.messageProvider = messageProvider;
}
protected SchedulerUtils scheduler;
protected boolean initialized = false;
@Override @Override
public final void onLoad() { public final void onLoad() {
@@ -66,7 +80,7 @@ public abstract class EasyPlugin extends JavaPlugin {
@Override @Override
public final void onDisable() { public final void onDisable() {
if (!hasOverride("shutdown") || !isInitialized()) return; if (!hasOverride("shutdown") || !this.initialized) return;
outputInfo(); outputInfo();
log(messageProvider.disabling(this)); log(messageProvider.disabling(this));
@@ -90,10 +104,6 @@ public abstract class EasyPlugin extends JavaPlugin {
Optional.ofNullable(JarResourceUtils.readResource(this.getResource("PLUGIN_INFO"))).ifPresent(this::log); Optional.ofNullable(JarResourceUtils.readResource(this.getResource("PLUGIN_INFO"))).ifPresent(this::log);
} }
public boolean isInitialized() {
return initialized;
}
public boolean isDebugging() { public boolean isDebugging() {
return false; return false;
} }
@@ -136,21 +146,64 @@ public abstract class EasyPlugin extends JavaPlugin {
if (isDebugging()) print("&8[DEBUG] &r", messages); if (isDebugging()) print("&8[DEBUG] &r", messages);
} }
public void callEventSync(Event event) { /**
getScheduler().run(() -> Bukkit.getPluginManager().callEvent(event)); * 在主线程执行操作,并支持获取其结果。
*
* @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;
} }
public void callEventAsync(Event event) { /**
getScheduler().runAsync(() -> Bukkit.getPluginManager().callEvent(event)); * 在异步线程中执行一个操作,并获取操作的结果。
*
* @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;
} }
public @NotNull <T extends Event> CompletableFuture<T> callEventFuture(T event) { /**
return CompletableFuture.supplyAsync(() -> { * 在主线程唤起一个事件,并支持获取事件的结果。
*
* @param event 同步事件 (isAsync=false)
* @param <T> 事件类型
* @return CompletableFuture
*/
public @NotNull <T extends Event> CompletableFuture<T> callSync(T event) {
return supplySync(() -> {
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
return event; return event;
}); });
} }
/**
* 在异步线程中唤起一个事件,并支持获取事件的结果。
*
* @param event 异步事件 (isAsync=true)
* @param <T> 事件类型
* @return CompletableFuture
*/
public @NotNull <T extends Event> CompletableFuture<T> callAsync(T event) {
return supplyAsync(() -> {
Bukkit.getPluginManager().callEvent(event);
return event;
});
}
protected void setMessageProvider(@NotNull EasyPluginMessageProvider provider) {
this.messageProvider = provider;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted") @SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean hasOverride(String methodName) { private boolean hasOverride(String methodName) {
Map<Method, Method> methodMap = new HashMap<>(); Map<Method, Method> methodMap = new HashMap<>();
@@ -1,31 +1,90 @@
package cc.carm.lib.easyplugin.utils; package cc.carm.lib.easyplugin.utils;
import java.util.Arrays; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.List; import java.util.List;
import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; 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 class ColorParser {
public static final Pattern HEX_PATTERN = Pattern.compile("&\\(&?#([0-9a-fA-F]{6})\\)"); 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可用的格式化代码
public static String parse(String text) { /**
return parseBaseColor(parseHexColor(text)); * 清除一条消息中的全部颜色代码 (包括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;
} }
public static String[] parse(String... texts) { /**
* 对一条消息进行颜色解析,包括普通颜色代码、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]); return parse(Arrays.asList(texts)).toArray(new String[0]);
} }
public static List<String> parse(List<String> texts) { /**
* 对多条消息进行颜色解析,包括普通颜色代码、RGB颜色代码与RBG渐变代码。
*
* @param texts 源消息内容
* @return 解析后的消息
*/
public static @NotNull List<String> parse(@NotNull Collection<String> texts) {
return texts.stream().map(ColorParser::parse).collect(Collectors.toList()); 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) { public static String parseBaseColor(final String text) {
return text.replaceAll("&", "§").replace("§§", "&"); return text.replaceAll("&", "§").replace("§§", "&");
} }
/**
* 解析消息中的RGB颜色代码(版本需要≥1.14) 格式 {@code &(#XXXXXX) },如 {@literal &(#aaaaaa)}
*
* @param text 消息内容
* @return RGB处理后的消息
*/
public static String parseHexColor(String text) { public static String parseHexColor(String text) {
Matcher matcher = HEX_PATTERN.matcher(text); Matcher matcher = HEX_PATTERN.matcher(text);
while (matcher.find()) { while (matcher.find()) {
@@ -35,9 +94,114 @@ public class ColorParser {
return text; return text;
} }
private static String buildHexColor(String hexCode) { /**
return Arrays.stream(hexCode.split("")) * 对一条消息进行RGB渐变处理(版本需要≥1.14),格式 {@code &<#XXXXXX>FOOBAR&<#XXXXXX> }。
.map(s -> '§' + s) *
* @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", "")); .collect(Collectors.joining("", '§' + "x", ""));
} }
@@ -14,131 +14,131 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ItemStackFactory { public class ItemStackFactory {
ItemStack item; ItemStack item;
private ItemStackFactory() { private ItemStackFactory() {
} }
public ItemStackFactory(ItemStack is) { public ItemStackFactory(ItemStack is) {
this.item = is.clone(); this.item = is.clone();
} }
public ItemStackFactory(Material type) { public ItemStackFactory(Material type) {
this(type, 1); this(type, 1);
} }
public ItemStackFactory(Material type, int amount) { public ItemStackFactory(Material type, int amount) {
this(type, amount, (short) 0); this(type, amount, (short) 0);
} }
public ItemStackFactory(Material type, int amount, short data) { public ItemStackFactory(Material type, int amount, short data) {
this.item = new ItemStack(type, amount, data); this.item = new ItemStack(type, amount, data);
} }
public ItemStackFactory(Material type, int amount, int data) { public ItemStackFactory(Material type, int amount, int data) {
this(type, amount, (short) data); this(type, amount, (short) data);
} }
public ItemStack toItemStack() { public ItemStack toItemStack() {
return this.item; return this.item;
} }
public ItemStackFactory setType(Material type) { public ItemStackFactory setType(Material type) {
this.item.setType(type); this.item.setType(type);
return this; return this;
} }
public ItemStackFactory setDurability(int i) { public ItemStackFactory setDurability(int i) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im instanceof Damageable) { if (im instanceof Damageable) {
((Damageable) im).setDamage(i); ((Damageable) im).setDamage(i);
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
public ItemStackFactory setAmount(int a) { public ItemStackFactory setAmount(int a) {
this.item.setAmount(a); this.item.setAmount(a);
return this; return this;
} }
public ItemStackFactory setDisplayName(@NotNull String name) { public ItemStackFactory setDisplayName(@NotNull String name) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im != null) { if (im != null) {
im.setDisplayName(ColorParser.parse(name)); im.setDisplayName(ColorParser.parse(name));
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
public ItemStackFactory setLore(@NotNull List<String> loreList) { public ItemStackFactory setLore(@NotNull List<String> loreList) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im != null) { if (im != null) {
im.setLore( im.setLore(
loreList.stream() loreList.stream()
.map(ColorParser::parse) .map(ColorParser::parse)
.collect(Collectors.toList()) .collect(Collectors.toList())
); );
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
public ItemStackFactory addLore(@NotNull String s) { public ItemStackFactory addLore(@NotNull String s) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im != null) { if (im != null) {
List<String> lore = im.getLore() != null ? im.getLore() : new ArrayList<>(); List<String> lore = im.getLore() != null ? im.getLore() : new ArrayList<>();
lore.add(ColorParser.parse(s)); lore.add(ColorParser.parse(s));
im.setLore(lore); im.setLore(lore);
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
public ItemStackFactory addEnchant(@NotNull Enchantment enchant, int level, boolean ignoreLevelRestriction) { public ItemStackFactory addEnchant(@NotNull Enchantment enchant, int level, boolean ignoreLevelRestriction) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im != null) { if (im != null) {
im.addEnchant(enchant, level, ignoreLevelRestriction); im.addEnchant(enchant, level, ignoreLevelRestriction);
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
public ItemStackFactory removeEnchant(@NotNull Enchantment enchant) { public ItemStackFactory removeEnchant(@NotNull Enchantment enchant) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im != null) { if (im != null) {
im.removeEnchant(enchant); im.removeEnchant(enchant);
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
public ItemStackFactory addFlag(@NotNull ItemFlag flag) { public ItemStackFactory addFlag(@NotNull ItemFlag flag) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im != null) { if (im != null) {
im.addItemFlags(flag); im.addItemFlags(flag);
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
public ItemStackFactory removeFlag(@NotNull ItemFlag flag) { public ItemStackFactory removeFlag(@NotNull ItemFlag flag) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im != null) { if (im != null) {
im.removeItemFlags(flag); im.removeItemFlags(flag);
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
public ItemStackFactory setUnbreakable(boolean unbreakable) { public ItemStackFactory setUnbreakable(boolean unbreakable) {
ItemMeta im = this.item.getItemMeta(); ItemMeta im = this.item.getItemMeta();
if (im != null) { if (im != null) {
im.setUnbreakable(unbreakable); im.setUnbreakable(unbreakable);
this.item.setItemMeta(im); this.item.setItemMeta(im);
} }
return this; return this;
} }
} }
@@ -12,344 +12,344 @@ import java.util.concurrent.Callable;
@SuppressWarnings("DuplicatedCode") @SuppressWarnings("DuplicatedCode")
public class SchedulerUtils { public class SchedulerUtils {
private final JavaPlugin plugin; private final JavaPlugin plugin;
public SchedulerUtils(JavaPlugin plugin) { public SchedulerUtils(JavaPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
private JavaPlugin getPlugin() { private JavaPlugin getPlugin() {
return plugin; return plugin;
} }
/** /**
* 在服务端主线程中执行一个任务 * 在服务端主线程中执行一个任务
* *
* @param runnable 需要执行的任务 * @param runnable 需要执行的任务
*/ */
public void run(Runnable runnable) { public void run(Runnable runnable) {
Bukkit.getScheduler().runTask(getPlugin(), runnable); Bukkit.getScheduler().runTask(getPlugin(), runnable);
} }
/** /**
* 异步执行一个任务。 * 异步执行一个任务。
* *
* @param runnable 需要执行的任务 * @param runnable 需要执行的任务
*/ */
public void runAsync(Runnable runnable) { public void runAsync(Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), runnable); Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), runnable);
} }
/**
* 在主线程延时执行一个任务。
*
* @param delay 延迟的ticks
* @param runnable 需要执行的任务
*/
public void runLater(long delay, Runnable runnable) {
Bukkit.getScheduler().runTaskLater(getPlugin(), runnable, delay);
}
/** /**
* 异步延时执行一个任务。 * 在主线程延时执行一个任务。
* *
* @param delay 延迟的ticks * @param delay 延迟的ticks
* @param runnable 需要执行的任务 * @param runnable 需要执行的任务
*/ */
public void runLaterAsync(long delay, Runnable runnable) { public void runLater(long delay, Runnable runnable) {
Bukkit.getScheduler().runTaskLaterAsynchronously(getPlugin(), runnable, delay); Bukkit.getScheduler().runTaskLater(getPlugin(), runnable, delay);
} }
/** /**
* 间隔一段时间按顺序执行列表中的任务 * 异步延时执行一个任务
* *
* @param interval 间隔时间 * @param delay 延迟的ticks
* @param tasks 任务列表 * @param runnable 需要执行的任务
*/ */
public void runAtInterval(long interval, Runnable... tasks) { public void runLaterAsync(long delay, Runnable runnable) {
runAtInterval(0L, interval, tasks); Bukkit.getScheduler().runTaskLaterAsynchronously(getPlugin(), runnable, delay);
} }
/**
* 间隔一段时间按顺序执行列表中的任务
*
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtInterval(long interval, Runnable... tasks) {
runAtInterval(0L, interval, tasks);
}
/** /**
* 间隔一段时间按顺序执行列表中的任务 * 间隔一段时间按顺序执行列表中的任务
* *
* @param delay 延迟时间 * @param delay 延迟时间
* @param interval 间隔时间 * @param interval 间隔时间
* @param tasks 任务列表 * @param tasks 任务列表
*/ */
public void runAtInterval(long delay, long interval, Runnable... tasks) { public void runAtInterval(long delay, long interval, Runnable... tasks) {
new BukkitRunnable() { new BukkitRunnable() {
private int index; private int index;
@Override @Override
public void run() { public void run() {
if (this.index >= tasks.length) { if (this.index >= tasks.length) {
this.cancel(); this.cancel();
return; return;
} }
tasks[index].run(); tasks[index].run();
index++; index++;
} }
}.runTaskTimer(getPlugin(), delay, interval); }.runTaskTimer(getPlugin(), delay, interval);
} }
/** /**
* 间隔一段时间按顺序异步执行列表中的任务 * 间隔一段时间按顺序异步执行列表中的任务
* *
* @param interval 间隔时间 * @param interval 间隔时间
* @param tasks 任务列表 * @param tasks 任务列表
*/ */
public void runAtIntervalAsync(long interval, Runnable... tasks) { public void runAtIntervalAsync(long interval, Runnable... tasks) {
runAtIntervalAsync(0L, interval, tasks); runAtIntervalAsync(0L, interval, tasks);
} }
/** /**
* 间隔一段时间按顺序异步执行列表中的任务 * 间隔一段时间按顺序异步执行列表中的任务
* *
* @param delay 延迟时间 * @param delay 延迟时间
* @param interval 间隔时间 * @param interval 间隔时间
* @param tasks 任务列表 * @param tasks 任务列表
*/ */
public void runAtIntervalAsync(long delay, long interval, Runnable... tasks) { public void runAtIntervalAsync(long delay, long interval, Runnable... tasks) {
new BukkitRunnable() { new BukkitRunnable() {
private int index; private int index;
@Override @Override
public void run() { public void run() {
if (this.index >= tasks.length) { if (this.index >= tasks.length) {
this.cancel(); this.cancel();
return; return;
} }
tasks[index].run(); tasks[index].run();
index++; index++;
} }
}.runTaskTimerAsynchronously(getPlugin(), delay, interval); }.runTaskTimerAsynchronously(getPlugin(), delay, interval);
} }
/** /**
* 重复执行一个任务。 * 重复执行一个任务。
* *
* @param repetitions 重复次数 * @param repetitions 重复次数
* @param interval 间隔时间 * @param interval 间隔时间
* @param task 任务 * @param task 任务
* @param onComplete 结束时执行的任务 * @param onComplete 结束时执行的任务
*/ */
public void repeat(int repetitions, long interval, Runnable task, Runnable onComplete) { public void repeat(int repetitions, long interval, Runnable task, Runnable onComplete) {
new BukkitRunnable() { new BukkitRunnable() {
private int index; private int index;
@Override @Override
public void run() { public void run() {
index++; index++;
if (this.index >= repetitions) { if (this.index >= repetitions) {
this.cancel(); this.cancel();
if (onComplete == null) { if (onComplete == null) {
return; return;
} }
onComplete.run(); onComplete.run();
return; return;
} }
task.run(); task.run();
} }
}.runTaskTimer(getPlugin(), 0L, interval); }.runTaskTimer(getPlugin(), 0L, interval);
} }
/** /**
* 重复执行一个任务。 * 重复执行一个任务。
* *
* @param repetitions 重复次数 * @param repetitions 重复次数
* @param interval 间隔时间 * @param interval 间隔时间
* @param task 任务 * @param task 任务
* @param onComplete 结束时执行的任务 * @param onComplete 结束时执行的任务
*/ */
public void repeatAsync(int repetitions, long interval, Runnable task, Runnable onComplete) { public void repeatAsync(int repetitions, long interval, Runnable task, Runnable onComplete) {
new BukkitRunnable() { new BukkitRunnable() {
private int index; private int index;
@Override @Override
public void run() { public void run() {
index++; index++;
if (this.index >= repetitions) { if (this.index >= repetitions) {
this.cancel(); this.cancel();
if (onComplete == null) { if (onComplete == null) {
return; return;
} }
onComplete.run(); onComplete.run();
return; return;
} }
task.run(); task.run();
} }
}.runTaskTimerAsynchronously(getPlugin(), 0L, interval); }.runTaskTimerAsynchronously(getPlugin(), 0L, interval);
} }
/** /**
* 在满足某个条件时,重复执行一个任务。 * 在满足某个条件时,重复执行一个任务。
* *
* @param interval 重复间隔时间 * @param interval 重复间隔时间
* @param predicate 条件 * @param predicate 条件
* @param task 任务 * @param task 任务
* @param onComplete 结束时执行的任务 * @param onComplete 结束时执行的任务
*/ */
public void repeatWhile(long interval, Callable<Boolean> predicate, Runnable task, Runnable onComplete) { public void repeatWhile(long interval, Callable<Boolean> predicate, Runnable task, Runnable onComplete) {
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
try { try {
if (!predicate.call()) { if (!predicate.call()) {
this.cancel(); this.cancel();
if (onComplete == null) { if (onComplete == null) {
return; return;
} }
onComplete.run(); onComplete.run();
return; return;
} }
task.run(); task.run();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
}.runTaskTimer(getPlugin(), 0L, interval); }.runTaskTimer(getPlugin(), 0L, interval);
} }
/** /**
* 在满足某个条件时,重复执行一个任务。 * 在满足某个条件时,重复执行一个任务。
* *
* @param interval 重复间隔时间 * @param interval 重复间隔时间
* @param predicate 条件 * @param predicate 条件
* @param task 任务 * @param task 任务
* @param onComplete 结束时执行的任务 * @param onComplete 结束时执行的任务
*/ */
public void repeatWhileAsync(long interval, Callable<Boolean> predicate, Runnable task, Runnable onComplete) { public void repeatWhileAsync(long interval, Callable<Boolean> predicate, Runnable task, Runnable onComplete) {
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
try { try {
if (!predicate.call()) { if (!predicate.call()) {
this.cancel(); this.cancel();
if (onComplete == null) { if (onComplete == null) {
return; return;
} }
onComplete.run(); onComplete.run();
return; return;
} }
task.run(); task.run();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
}.runTaskTimerAsynchronously(getPlugin(), 0L, interval); }.runTaskTimerAsynchronously(getPlugin(), 0L, interval);
} }
public interface Task { public interface Task {
void start(Runnable onComplete); void start(Runnable onComplete);
} }
public class TaskBuilder { public class TaskBuilder {
private final Queue<Task> taskList; private final Queue<Task> taskList;
public TaskBuilder() { public TaskBuilder() {
this.taskList = new LinkedList<>(); this.taskList = new LinkedList<>();
} }
public TaskBuilder append(TaskBuilder builder) { public TaskBuilder append(TaskBuilder builder) {
this.taskList.addAll(builder.taskList); this.taskList.addAll(builder.taskList);
return this; return this;
} }
public TaskBuilder appendDelay(long delay) { public TaskBuilder appendDelay(long delay) {
this.taskList.add(onComplete -> SchedulerUtils.this.runLater(delay, onComplete)); this.taskList.add(onComplete -> SchedulerUtils.this.runLater(delay, onComplete));
return this; return this;
} }
public TaskBuilder appendTask(Runnable task) { public TaskBuilder appendTask(Runnable task) {
this.taskList.add(onComplete -> this.taskList.add(onComplete ->
{ {
task.run(); task.run();
onComplete.run(); onComplete.run();
}); });
return this; return this;
} }
public TaskBuilder appendTask(Task task) { public TaskBuilder appendTask(Task task) {
this.taskList.add(task); this.taskList.add(task);
return this; return this;
} }
public TaskBuilder appendDelayedTask(long delay, Runnable task) { public TaskBuilder appendDelayedTask(long delay, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.runLater(delay, () -> this.taskList.add(onComplete -> SchedulerUtils.this.runLater(delay, () ->
{ {
task.run(); task.run();
onComplete.run(); onComplete.run();
})); }));
return this; return this;
} }
public TaskBuilder appendTasks(long delay, long interval, Runnable... tasks) { public TaskBuilder appendTasks(long delay, long interval, Runnable... tasks) {
this.taskList.add(onComplete -> this.taskList.add(onComplete ->
{ {
Runnable[] runnables = Arrays.copyOf(tasks, tasks.length + 1); Runnable[] runnables = Arrays.copyOf(tasks, tasks.length + 1);
runnables[runnables.length - 1] = onComplete; runnables[runnables.length - 1] = onComplete;
SchedulerUtils.this.runAtInterval(delay, interval, runnables); SchedulerUtils.this.runAtInterval(delay, interval, runnables);
}); });
return this; return this;
} }
public TaskBuilder appendRepeatingTask(int repetitions, long interval, Runnable task) { public TaskBuilder appendRepeatingTask(int repetitions, long interval, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.repeat(repetitions, interval, task, onComplete)); this.taskList.add(onComplete -> SchedulerUtils.this.repeat(repetitions, interval, task, onComplete));
return this; return this;
} }
public TaskBuilder appendConditionalRepeatingTask(long interval, Callable<Boolean> predicate, Runnable task) { public TaskBuilder appendConditionalRepeatingTask(long interval, Callable<Boolean> predicate, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.repeatWhile(interval, predicate, task, onComplete)); this.taskList.add(onComplete -> SchedulerUtils.this.repeatWhile(interval, predicate, task, onComplete));
return this; return this;
} }
public TaskBuilder waitFor(Callable<Boolean> predicate) { public TaskBuilder waitFor(Callable<Boolean> predicate) {
this.taskList.add(onComplete -> new BukkitRunnable() { this.taskList.add(onComplete -> new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
try { try {
if (!predicate.call()) { if (!predicate.call()) {
return; return;
} }
this.cancel(); this.cancel();
onComplete.run(); onComplete.run();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
}.runTaskTimer(getPlugin(), 0L, 1L)); }.runTaskTimer(getPlugin(), 0L, 1L));
return this; return this;
} }
public void runTasks() { public void runTasks() {
this.startNext(); this.startNext();
} }
private void startNext() { private void startNext() {
Task task = this.taskList.poll(); Task task = this.taskList.poll();
if (task == null) { if (task == null) {
return; return;
} }
task.start(this::startNext); task.start(this::startNext);
} }
} }
} }
+27
View File
@@ -0,0 +1,27 @@
<?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.20</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-storage</artifactId>
<packaging>jar</packaging>
<name>EasyPlugin-Storage</name>
<description>轻松插件存储接口模块,包含存储相关的统一接口。</description>
<url>https://github.com/CarmJos/EasyPlugin</url>
</project>
@@ -0,0 +1,40 @@
package cc.carm.lib.easyplugin.storage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface DataStorage<K, T> {
/**
* 在插件加载存储源时执行。
*
* @throws Exception 当出现任何错误时抛出
*/
void initialize() throws Exception;
/**
* 在插件被卸载时执行。
*/
void shutdown();
/**
* 用于加载数据的方法。<b>该方法应当异步运行!</b>
* <br>
* <br>若不存在对应数据,请返回 null 。
* <br>若加载出现任何错误,请抛出异常。
*
* @param key 数据主键
* @throws Exception 当出现任何错误时抛出
*/
@Nullable
T loadData(@NotNull K key) throws Exception;
/**
* 用于保存数据的方法。 <b>该方法应当被异步运行!</b>
*
* @param data 数据
* @throws Exception 当出现任何错误时抛出
*/
void saveData(@NotNull T data) throws Exception;
}
@@ -0,0 +1,19 @@
package cc.carm.lib.easyplugin.storage;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public interface StorageType<K, T, S extends DataStorage<K, T>> {
int getID();
@NotNull List<String> getAlias();
@NotNull Class<? extends S> getStorageClass();
default @NotNull S createStorage() throws Exception {
return getStorageClass().newInstance();
}
}
@@ -0,0 +1,31 @@
package cc.carm.lib.easyplugin.storage.file;
import cc.carm.lib.easyplugin.storage.DataStorage;
import org.jetbrains.annotations.NotNull;
import java.io.File;
public abstract class FileBasedStorage<K, T> implements DataStorage<K, T> {
protected final String fileName;
protected File dataFile;
public FileBasedStorage(String fileName) {
this.fileName = fileName;
}
protected @NotNull File initializeFile(@NotNull File parentFolder) throws Exception {
this.dataFile = new File(parentFolder, fileName);
if (!dataFile.exists()) {
if (!dataFile.createNewFile()) throw new Exception("无法创建数据文件!");
} else if (dataFile.isDirectory()) {
throw new Exception("文件路径对应的不是一个文件!");
}
return dataFile;
}
public File getDataFile() {
return dataFile;
}
}
@@ -0,0 +1,46 @@
package cc.carm.lib.easyplugin.storage.file;
import cc.carm.lib.easyplugin.storage.DataStorage;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public abstract class FolderBasedStorage<K, T> implements DataStorage<K, T> {
protected final @NotNull String folderPath;
protected File dataFolder;
public FolderBasedStorage(@NotNull String folderPath) {
this.folderPath = folderPath;
}
protected @NotNull File initializeFolder(@NotNull File parentFolder) throws Exception {
this.dataFolder = new File(parentFolder, folderPath);
if (!dataFolder.exists()) {
if (!dataFolder.mkdir()) {
throw new Exception("无法创建数据文件夹!");
}
} else if (!dataFolder.isDirectory()) {
throw new Exception("数据文件夹路径对应的不是一个文件夹!");
}
return dataFolder;
}
protected @NotNull List<File> listFiles() {
if (this.dataFolder == null) return Collections.emptyList();
if (!this.dataFolder.isDirectory()) return Collections.emptyList();
File[] files = this.dataFolder.listFiles();
if (files == null) return Collections.emptyList();
return Arrays.asList(files);
}
public File getDataFolder() {
return dataFolder;
}
}
@@ -0,0 +1,24 @@
package cc.carm.lib.easyplugin.storage.file;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File;
public abstract class YAMLBasedStorage<K, T> extends FileBasedStorage<K, T> {
protected FileConfiguration configuration;
public YAMLBasedStorage(String fileName) {
super(fileName);
}
protected @NotNull FileConfiguration initializeConfiguration(@NotNull File parentFolder) throws Exception {
return this.configuration = YamlConfiguration.loadConfiguration(initializeFile(parentFolder));
}
public FileConfiguration getConfiguration() {
return configuration;
}
}
@@ -0,0 +1,31 @@
package cc.carm.lib.easyplugin.storage.plugin;
import cc.carm.lib.easyplugin.storage.DataStorage;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
public abstract class PluginBasedStorage<K, T> implements DataStorage<K, T> {
protected Plugin dependPlugin;
public PluginBasedStorage(String dependPluginName) {
this(Bukkit.getPluginManager().getPlugin(dependPluginName));
}
public PluginBasedStorage(Plugin dependPlugin) {
this.dependPlugin = dependPlugin;
}
@Override
public void initialize() throws NullPointerException {
if (dependPlugin == null) {
throw new NullPointerException("该存储类型依赖的插件不存在,请检查配置文件");
}
}
public Plugin getDependPlugin() {
return dependPlugin;
}
}
+60
View File
@@ -0,0 +1,60 @@
<?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.20</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>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>easyplugin-color</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<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,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));
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.6</version> <version>1.4.20</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
+30 -1
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.6</version> <version>1.4.20</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -52,6 +52,7 @@
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>${project.parent.groupId}</groupId> <groupId>${project.parent.groupId}</groupId>
<artifactId>easyplugin-main</artifactId> <artifactId>easyplugin-main</artifactId>
@@ -67,6 +68,27 @@
<artifactId>easyplugin-gui</artifactId> <artifactId>easyplugin-gui</artifactId>
<version>${project.parent.version}</version> <version>${project.parent.version}</version>
</dependency> </dependency>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>easyplugin-storage</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>easyplugin-listener</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>easyplugin-database</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>easyplugin-conf</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency> <dependency>
<groupId>${project.parent.groupId}</groupId> <groupId>${project.parent.groupId}</groupId>
<artifactId>easyplugin-papi</artifactId> <artifactId>easyplugin-papi</artifactId>
@@ -77,6 +99,13 @@
<artifactId>easyplugin-vault</artifactId> <artifactId>easyplugin-vault</artifactId>
<version>${project.parent.version}</version> <version>${project.parent.version}</version>
</dependency> </dependency>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>easyplugin-githubchecker</artifactId>
<version>${project.parent.version}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
+9 -1
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.6</version> <version>1.4.20</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -68,6 +68,14 @@
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>easyplugin-vault</artifactId> <artifactId>easyplugin-vault</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>cc.carm.lib</groupId>
<artifactId>easyplugin-database</artifactId>
</exclusion>
<exclusion>
<groupId>cc.carm.lib</groupId>
<artifactId>easyplugin-storage</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
+34
View File
@@ -0,0 +1,34 @@
<?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.20</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-githubchecker</artifactId>
<packaging>jar</packaging>
<name>EasyPlugin-GithubChecker</name>
<dependencies>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>githubreleases4j</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,84 @@
package cc.carm.lib.easyplugin.updatechecker;
import cc.carm.lib.githubreleases4j.GithubReleases4J;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GHUpdateChecker {
protected static final @NotNull Pattern GH_URL_PATTERN = Pattern.compile("^https?://github.com/([A-Za-z\\d-_]+)/([^/]*?)/?");
public static @NotNull GHUpdateChecker of(@NotNull Logger logger, @NotNull String owner, @NotNull String repo) {
return new GHUpdateChecker(logger, owner, repo);
}
public static @NotNull GHUpdateChecker of(@NotNull Plugin plugin) {
return new GHUpdateChecker(plugin.getLogger(), getGithubOwner(plugin), plugin.getName());
}
public static @NotNull Runnable runner(@NotNull Logger logger,
@NotNull String owner, @NotNull String repo,
@NotNull String currentVersion) {
return of(logger, owner, repo).runner(currentVersion);
}
public static @NotNull Runnable runner(@NotNull Plugin plugin) {
return of(plugin).runner(plugin.getDescription().getVersion());
}
protected final @NotNull Logger logger;
protected final @NotNull String owner;
protected final @NotNull String repo;
public GHUpdateChecker(@NotNull Logger logger, @NotNull String owner, @NotNull String repo) {
this.logger = logger;
this.owner = owner;
this.repo = repo;
}
public void checkUpdate(@NotNull String currentVersion) {
Integer behindVersions = GithubReleases4J.getVersionBehind(owner, repo, currentVersion);
String downloadURL = GithubReleases4J.getReleasesURL(owner, repo);
if (behindVersions == null) {
this.logger.severe("检查更新失败,请您定期查看插件是否更新,避免安全问题。");
this.logger.severe("下载地址 " + downloadURL);
} else if (behindVersions == 0) {
this.logger.info("检查完成,当前已是最新版本。");
} else if (behindVersions > 0) {
this.logger.info("发现新版本! 目前已落后 " + behindVersions + " 个版本。");
this.logger.info("最新版下载地址 " + downloadURL);
} else {
this.logger.severe("检查更新失败! 当前版本未知,请您使用原生版本以避免安全问题。");
this.logger.severe("最新版下载地址 " + downloadURL);
}
}
public Runnable runner(@NotNull String currentVersion) {
return () -> checkUpdate(currentVersion);
}
protected static String getGithubOwner(Plugin plugin) {
// 首先,尝试从插件提供的网址中获取OWNER
String websiteOwner = getGithubOwner(plugin.getDescription().getWebsite());
if (websiteOwner != null && !websiteOwner.isEmpty()) return websiteOwner;
// 如果插件提供的网址中没有,则尝试获取插件的首位作者名
List<String> authors = plugin.getDescription().getAuthors();
if (!authors.isEmpty()) return authors.get(0);
// 再没有的话只能返回插件的名称了
return plugin.getName();
}
protected static String getGithubOwner(String url) {
Matcher matcher = GH_URL_PATTERN.matcher(url);
return matcher.find() ? matcher.group(1) : null;
}
}
@@ -0,0 +1,16 @@
package cc.carm.lib.easyplugin.updatechecker;
import org.junit.Test;
public class RegexTest {
@Test
public void onTest() {
System.out.println(GHUpdateChecker.getGithubOwner("https://github.com/CarmJos/EasyPlugin"));
System.out.println(GHUpdateChecker.getGithubOwner("https://github.com/Ghost-chu/QuickShop-Hikari/pulls"));
System.out.println(GHUpdateChecker.getGithubOwner("https://github.com/QWQ123/QuickShop"));
}
}
+1 -2
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.6</version> <version>1.4.20</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -27,7 +27,6 @@
<dependency> <dependency>
<groupId>me.clip</groupId> <groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId> <artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
+2 -2
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.6</version> <version>1.4.20</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -24,10 +24,10 @@
<dependencies> <dependencies>
<!--suppress VulnerableLibrariesLocal -->
<dependency> <dependency>
<groupId>com.github.MilkBowl</groupId> <groupId>com.github.MilkBowl</groupId>
<artifactId>VaultAPI</artifactId> <artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
+45 -3
View File
@@ -15,19 +15,26 @@
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>easyplugin-parent</artifactId> <artifactId>easyplugin-parent</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<version>1.4.6</version> <version>1.4.20</version>
<modules> <modules>
<module>base/utils</module>
<module>base/main</module> <module>base/main</module>
<module>base/command</module> <module>base/conf</module>
<module>base/gui</module> <module>base/gui</module>
<module>base/command</module>
<module>base/storage</module>
<module>base/listener</module>
<module>base/database</module>
<module>extension/papi</module> <module>extension/papi</module>
<module>extension/vault</module> <module>extension/vault</module>
<module>extension/gh-checker</module>
<module>collection/all</module> <module>collection/all</module>
<module>collection/bom</module> <module>collection/bom</module>
<module>collection/common</module> <module>collection/common</module>
<module>base/color</module>
</modules> </modules>
@@ -101,7 +108,7 @@
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId> <artifactId>spigot-api</artifactId>
<version>1.13.2-R0.1-SNAPSHOT</version> <version>1.13.2-R0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
@@ -122,6 +129,41 @@
</dependencies> </dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
</dependency>
<dependency>
<groupId>com.github.MilkBowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>githubreleases4j</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>easylistener</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>mineconfiguration-bukkit</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-beecp</artifactId>
<version>0.4.3</version>
</dependency>
</dependencies>
</dependencyManagement>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>