mirror of
https://github.com/darksaid98/Carbon.git
synced 2026-12-01 22:15:08 +00:00
More TODOs: color argument, console in parseMessage return
This commit is contained in:
1 parent
bea9816c45
commit
8e91232345
16 files changed
+350
-42
No files matched your search
@@ -25,10 +25,10 @@ public interface ChatChannel extends Audience {
|
||||
@Nullable TextColor channelColor(@NonNull CarbonUser user);
|
||||
|
||||
@NonNull
|
||||
Map<PlayerUser, Component> parseMessage(@NonNull PlayerUser user, @NonNull String message, boolean fromRemote);
|
||||
Map<CarbonUser, Component> parseMessage(@NonNull PlayerUser user, @NonNull String message, boolean fromRemote);
|
||||
|
||||
@NonNull
|
||||
Map<PlayerUser, Component> parseMessage(@NonNull PlayerUser user, @NonNull Collection<@NonNull PlayerUser> recipients,
|
||||
Map<CarbonUser, Component> parseMessage(@NonNull PlayerUser user, @NonNull Collection<@NonNull PlayerUser> recipients,
|
||||
@NonNull String message, boolean fromRemote);
|
||||
|
||||
boolean canPlayerUse(@NonNull PlayerUser user);
|
||||
|
||||
@@ -35,8 +35,8 @@ public final class ChannelOptions {
|
||||
@Setting
|
||||
@Comment("The formats for this channel. The key is the name of the group as your permissions plugin reports it.")
|
||||
private Map<String, String> formats = new HashMap<String, String>() {{
|
||||
put("default", "<color><<displayname><reset><color>> <message>");
|
||||
}};
|
||||
put("default", "<color><<displayname><reset><color>> <message>");
|
||||
}};
|
||||
|
||||
@Setting
|
||||
@Comment("The name of the format that the plugin will fall back to when it cannot find a matching format for the player's groups.")
|
||||
|
||||
+3
-3
@@ -17,9 +17,9 @@ public final class SharedChannelOptions {
|
||||
@Setting private String color = "#FFFFFF";
|
||||
@Setting private Map<String, Context> contexts = new HashMap<>();
|
||||
@Setting private Map<String, String> formats = new HashMap<String, String>() {{
|
||||
put("default", "<color><<displayname><reset><color>> <message>");
|
||||
put("staff", "<#00CED1>[Staff] <color><<displayname><reset><color>> <message>");
|
||||
}};
|
||||
put("default", "<color><<displayname><reset><color>> <message>");
|
||||
put("staff", "<#00CED1>[Staff] <color><<displayname><reset><color>> <message>");
|
||||
}};
|
||||
@Setting private String defaultFormatName = "default";
|
||||
@Setting private boolean ignorable = true;
|
||||
@Setting private boolean crossServer = true;
|
||||
|
||||
@@ -13,6 +13,9 @@ public interface UserService<T extends PlayerUser> {
|
||||
@Nullable
|
||||
T wrap(UUID uuid);
|
||||
|
||||
@Nullable // Maybe NonNull?
|
||||
<C extends ConsoleUser> C consoleUser();
|
||||
|
||||
@Nullable
|
||||
T wrapIfLoaded(@NonNull UUID uuid);
|
||||
|
||||
|
||||
@@ -164,13 +164,16 @@ public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
|
||||
if (storageType == StorageType.MYSQL) {
|
||||
this.logger().info("Enabling MySQL storage!");
|
||||
final SQLCredentials credentials = this.carbonSettings().sqlCredentials();
|
||||
this.userService = new MySQLUserService<>(this, credentials, supplier, BukkitPlayerUser::new, nameResolver);
|
||||
this.userService = new MySQLUserService<>(this, credentials, supplier, BukkitPlayerUser::new,
|
||||
nameResolver, BukkitConsoleUser::new);
|
||||
} else if (storageType == StorageType.JSON) {
|
||||
this.logger().info("Enabling JSON storage!");
|
||||
this.userService = new JSONUserService<>(BukkitPlayerUser.class, this, supplier, BukkitPlayerUser::new, nameResolver);
|
||||
this.userService = new JSONUserService<>(BukkitPlayerUser.class, this, supplier, BukkitPlayerUser::new,
|
||||
nameResolver, BukkitConsoleUser::new);
|
||||
} else {
|
||||
this.logger().error("Invalid storage type selected! Falling back to JSON.");
|
||||
this.userService = new JSONUserService<>(BukkitPlayerUser.class, this, supplier, BukkitPlayerUser::new, nameResolver);
|
||||
this.userService = new JSONUserService<>(BukkitPlayerUser.class, this, supplier, BukkitPlayerUser::new,
|
||||
nameResolver, BukkitConsoleUser::new);
|
||||
}
|
||||
|
||||
// Setup listeners
|
||||
|
||||
-1
@@ -11,7 +11,6 @@ import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChannelSwitchEvent;
|
||||
import net.draycia.carbon.api.events.MessageContextEvent;
|
||||
import net.draycia.carbon.api.events.ReceiverContextEvent;
|
||||
import net.draycia.carbon.api.users.CarbonUser;
|
||||
import net.draycia.carbon.api.Context;
|
||||
import net.draycia.carbon.api.users.PlayerUser;
|
||||
import net.kyori.event.PostOrders;
|
||||
|
||||
+7
-5
@@ -4,6 +4,8 @@ import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.channels.TextChannel;
|
||||
import net.draycia.carbon.api.events.UserEvent;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.users.CarbonUser;
|
||||
import net.draycia.carbon.api.users.ConsoleUser;
|
||||
import net.draycia.carbon.bukkit.CarbonChatBukkit;
|
||||
import net.draycia.carbon.api.users.PlayerUser;
|
||||
import net.kyori.adventure.text.Component;
|
||||
@@ -74,19 +76,19 @@ public class BukkitChatListener implements Listener {
|
||||
event.getRecipients().clear();
|
||||
|
||||
if (event.isAsynchronous()) {
|
||||
final Map<PlayerUser, Component> messages =
|
||||
final Map<CarbonUser, Component> messages =
|
||||
selectedChannel.parseMessage(user, event.getMessage(), false);
|
||||
|
||||
for (final Map.Entry<PlayerUser, Component> entry : messages.entrySet()) {
|
||||
for (final Map.Entry<CarbonUser, Component> entry : messages.entrySet()) {
|
||||
if (entry.getValue().equals(Component.empty())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
entry.getKey().sendMessage(user.identity(), entry.getValue());
|
||||
|
||||
if (user.equals(entry.getKey())) {
|
||||
if (user instanceof ConsoleUser) {
|
||||
event.setFormat(PlainComponentSerializer.plain().serialize(entry.getValue())
|
||||
.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%"));
|
||||
} else {
|
||||
entry.getKey().sendMessage(user.identity(), entry.getValue());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -20,6 +20,10 @@ public class BukkitConsoleUser implements ConsoleUser, ForwardingAudience.Single
|
||||
this.audience = BukkitAudiences.create(plugin).sender(sender);
|
||||
}
|
||||
|
||||
public BukkitConsoleUser() {
|
||||
this(Bukkit.getConsoleSender());
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Identity identity() {
|
||||
return Identity.nil();
|
||||
|
||||
+7
-4
@@ -99,7 +99,7 @@ public class CarbonChatChannel implements TextChannel {
|
||||
// }
|
||||
|
||||
@Override
|
||||
public @NonNull Map<PlayerUser, Component> parseMessage(@NonNull final PlayerUser user, @NonNull final Collection<@NonNull PlayerUser> recipients, @NonNull final String message, final boolean fromRemote) {
|
||||
public @NonNull Map<CarbonUser, Component> parseMessage(@NonNull final PlayerUser user, @NonNull final Collection<@NonNull PlayerUser> recipients, @NonNull final String message, final boolean fromRemote) {
|
||||
//this.updateUserNickname(user);
|
||||
|
||||
final MessageContextEvent event = new MessageContextEvent(this, user);
|
||||
@@ -132,7 +132,7 @@ public class CarbonChatChannel implements TextChannel {
|
||||
displayName = user.displayName();
|
||||
}
|
||||
|
||||
final Map<PlayerUser, Component> users = new HashMap<>();
|
||||
final Map<CarbonUser, Component> users = new HashMap<>();
|
||||
|
||||
// Iterate through players who should receive messages in this channel
|
||||
for (final PlayerUser target : recipients) {
|
||||
@@ -182,12 +182,15 @@ public class CarbonChatChannel implements TextChannel {
|
||||
"phase", Long.toString(System.currentTimeMillis() % 25),
|
||||
"message", consoleFormatEvent.message());
|
||||
|
||||
// TODO: add ConsoleUser to users map. Requires "users" to be CarbonUser and not PlayerUser.
|
||||
final ChatComponentEvent consoleEvent = new ChatComponentEvent(user, null, this, consoleFormat,
|
||||
consoleFormatEvent.message());
|
||||
|
||||
CarbonEvents.post(consoleEvent);
|
||||
|
||||
if (!consoleEvent.cancelled()) {
|
||||
users.put(this.carbonChat.userService().consoleUser(), consoleEvent.component());
|
||||
}
|
||||
|
||||
if (user.online() && !fromRemote && this.crossServer()) {
|
||||
this.sendMessageToBungee(user.uuid(), consoleEvent.component());
|
||||
}
|
||||
@@ -225,7 +228,7 @@ public class CarbonChatChannel implements TextChannel {
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<PlayerUser, Component> parseMessage(@NonNull final PlayerUser user, @NonNull final String message, final boolean fromRemote) {
|
||||
public @NonNull Map<CarbonUser, Component> parseMessage(@NonNull final PlayerUser user, @NonNull final String message, final boolean fromRemote) {
|
||||
return this.parseMessage(user, this.audiences(), message, fromRemote);
|
||||
}
|
||||
|
||||
|
||||
+7
-4
@@ -53,16 +53,16 @@ public class CarbonWhisperChannel implements WhisperChannel {
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<PlayerUser, Component> parseMessage(@NonNull final PlayerUser user, @NonNull final String message,
|
||||
public @NonNull Map<CarbonUser, Component> parseMessage(@NonNull final PlayerUser user, @NonNull final String message,
|
||||
final boolean fromRemote) {
|
||||
return this.parseMessage(user, Collections.singleton(this.audience()), message, fromRemote);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<PlayerUser, Component> parseMessage(@NonNull final PlayerUser user,
|
||||
public @NonNull Map<CarbonUser, Component> parseMessage(@NonNull final PlayerUser user,
|
||||
@NonNull final Collection<@NonNull PlayerUser> recipients,
|
||||
@NonNull final String message, final boolean fromRemote) {
|
||||
final Map<PlayerUser, Component> result = new HashMap<>();
|
||||
final Map<CarbonUser, Component> result = new HashMap<>();
|
||||
|
||||
// Formats
|
||||
final String senderFormat = this.senderFormat();
|
||||
@@ -148,12 +148,15 @@ public class CarbonWhisperChannel implements WhisperChannel {
|
||||
"phase", Long.toString(System.currentTimeMillis() % 25),
|
||||
"message", senderFormatEvent.message());
|
||||
|
||||
// TODO: add ConsoleUser to users map
|
||||
final ChatComponentEvent consoleEvent = new ChatComponentEvent(this.sender, null, this, consoleFormat,
|
||||
consoleFormatEvent.message());
|
||||
|
||||
CarbonEvents.post(consoleEvent);
|
||||
|
||||
if (!consoleEvent.cancelled()) {
|
||||
result.put(this.carbonChat.userService().consoleUser(), consoleEvent.component());
|
||||
}
|
||||
|
||||
this.sender.replyTarget(this.audience);
|
||||
this.audience.replyTarget(this.sender);
|
||||
|
||||
|
||||
+3
-13
@@ -9,6 +9,7 @@ import net.draycia.carbon.api.users.CarbonUser;
|
||||
import net.draycia.carbon.api.commands.settings.CommandSettings;
|
||||
import net.draycia.carbon.api.users.PlayerUser;
|
||||
import net.draycia.carbon.api.users.UserChannelSettings;
|
||||
import net.draycia.carbon.common.utils.TextColorArgument;
|
||||
import net.kyori.adventure.identity.Identity;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
@@ -31,23 +32,12 @@ public class SetColorCommand {
|
||||
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
|
||||
commandManager.createDefaultCommandMeta())
|
||||
.senderType(PlayerUser.class) // player
|
||||
.permission("carbonchat.setcolor")
|
||||
.permission("carbonchat.setcolor." + channel.key())
|
||||
.argument(StaticArgument.of(channel.key()))
|
||||
// TODO: register command for each channel with the channel key as a literal, with permission
|
||||
// TODO: colorArgument (cloud 1.1.0-SNAPSHOT)
|
||||
//.argument(CommandUtils.colorArgument())
|
||||
.argument(TextColorArgument.of("color")) // remember to replace this when cloud 1.1.0 releases
|
||||
.handler(context -> {
|
||||
final PlayerUser user = (PlayerUser) context.getSender();
|
||||
final TextColor color = context.get("color");
|
||||
|
||||
if (!user.hasPermission("carbonchat.setcolor." + channel.key())) {
|
||||
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(
|
||||
this.carbonChat.translations().cannotSetColor(), "input", color.asHexString(),
|
||||
"channel", channel.name()));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
final UserChannelSettings settings = user.channelSettings(channel);
|
||||
|
||||
settings.color(color);
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ public class SudoChannelCommand {
|
||||
|
||||
private void otherChannel(@NonNull final CommandContext<CarbonUser> context) {
|
||||
final CarbonUser sender = context.getSender();
|
||||
final CarbonUser user = context.get("user");
|
||||
final PlayerUser user = context.get("user");
|
||||
final ChatChannel channel = context.get("channel");
|
||||
|
||||
user.selectedChannel(channel);
|
||||
|
||||
+11
-2
@@ -10,6 +10,7 @@ import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import net.draycia.carbon.api.CarbonChat;
|
||||
import net.draycia.carbon.api.users.CarbonUser;
|
||||
import net.draycia.carbon.api.users.ConsoleUser;
|
||||
import net.draycia.carbon.api.users.PlayerUser;
|
||||
import net.draycia.carbon.api.users.UserService;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
@@ -27,7 +28,7 @@ import java.util.concurrent.ExecutionException;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class JSONUserService<T extends PlayerUser> implements UserService<T> {
|
||||
public class JSONUserService<T extends PlayerUser, C extends ConsoleUser> implements UserService<T> {
|
||||
|
||||
private @NonNull final CarbonChat carbonChat;
|
||||
private @NonNull final Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
@@ -35,6 +36,7 @@ public class JSONUserService<T extends PlayerUser> implements UserService<T> {
|
||||
private @NonNull final Supplier<@NonNull Iterable<@NonNull T>> supplier;
|
||||
private @NonNull final Function<UUID, T> userFactory;
|
||||
private @NonNull final Function<String, UUID> nameResolver;
|
||||
private @NonNull final Supplier<C> consoleFactory;
|
||||
|
||||
private @NonNull final LoadingCache<@NonNull UUID, @NonNull T> userCache = CacheBuilder.newBuilder()
|
||||
.removalListener(this::saveUser)
|
||||
@@ -44,12 +46,14 @@ public class JSONUserService<T extends PlayerUser> implements UserService<T> {
|
||||
@NonNull final CarbonChat carbonChat,
|
||||
@NonNull final Supplier<@NonNull Iterable<@NonNull T>> supplier,
|
||||
@NonNull final Function<UUID, T> userFactory,
|
||||
@NonNull final Function<String, UUID> nameResolver) {
|
||||
@NonNull final Function<String, UUID> nameResolver,
|
||||
@NonNull final Supplier<C> consoleFactory) {
|
||||
this.userType = userType;
|
||||
this.carbonChat = carbonChat;
|
||||
this.supplier = supplier;
|
||||
this.userFactory = userFactory;
|
||||
this.nameResolver = nameResolver;
|
||||
this.consoleFactory = consoleFactory;
|
||||
|
||||
final TimerTask timerTask = new TimerTask() {
|
||||
@Override
|
||||
@@ -82,6 +86,11 @@ public class JSONUserService<T extends PlayerUser> implements UserService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable C consoleUser() {
|
||||
return this.consoleFactory.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable T wrapIfLoaded(@NonNull final UUID uuid) {
|
||||
return this.userCache.getIfPresent(uuid);
|
||||
|
||||
+11
-2
@@ -4,6 +4,7 @@ import co.aikar.idb.DatabaseOptions;
|
||||
import co.aikar.idb.PooledDatabaseOptions;
|
||||
import net.draycia.carbon.api.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ConsoleUser;
|
||||
import net.draycia.carbon.api.users.PlayerUser;
|
||||
import net.draycia.carbon.api.users.UserChannelSettings;
|
||||
import co.aikar.idb.DB;
|
||||
@@ -31,13 +32,14 @@ import java.util.concurrent.ExecutionException;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class MySQLUserService<T extends PlayerUser> implements UserService<T> {
|
||||
public class MySQLUserService<T extends PlayerUser, C extends ConsoleUser> implements UserService<T> {
|
||||
|
||||
private @NonNull final CarbonChat carbonChat;
|
||||
private @NonNull final Database database;
|
||||
private @NonNull final Supplier<@NonNull Iterable<@NonNull T>> supplier;
|
||||
private @NonNull final Function<UUID, T> userFactory;
|
||||
private @NonNull final Function<String, UUID> nameResolver;
|
||||
private @NonNull final Supplier<C> consoleFactory;
|
||||
|
||||
private @NonNull final LoadingCache<@NonNull UUID, @NonNull T> userCache = CacheBuilder.newBuilder()
|
||||
.removalListener(this::saveUser)
|
||||
@@ -46,11 +48,13 @@ public class MySQLUserService<T extends PlayerUser> implements UserService<T> {
|
||||
public MySQLUserService(@NonNull final CarbonChat carbonChat, @NonNull final SQLCredentials credentials,
|
||||
@NonNull final Supplier<@NonNull Iterable<@NonNull T>> supplier,
|
||||
@NonNull final Function<UUID, T> userFactory,
|
||||
@NonNull final Function<String, UUID> nameResolver) {
|
||||
@NonNull final Function<String, UUID> nameResolver,
|
||||
@NonNull final Supplier<C> consoleFactory) {
|
||||
this.carbonChat = carbonChat;
|
||||
this.supplier = supplier;
|
||||
this.userFactory = userFactory;
|
||||
this.nameResolver = nameResolver;
|
||||
this.consoleFactory = consoleFactory;
|
||||
|
||||
final String username = credentials.username();
|
||||
final String password = credentials.password();
|
||||
@@ -116,6 +120,11 @@ public class MySQLUserService<T extends PlayerUser> implements UserService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable C consoleUser() {
|
||||
return this.consoleFactory.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable T wrapIfLoaded(@NonNull final UUID uuid) {
|
||||
return this.userCache.getIfPresent(uuid);
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2020 Alexander Söderberg & Contributors
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
package net.draycia.carbon.common.utils;
|
||||
|
||||
import cloud.commandframework.captions.Caption;
|
||||
import cloud.commandframework.context.CommandContext;
|
||||
import cloud.commandframework.exceptions.parsing.ParserException;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
/**
|
||||
* An exception which is thrown when an argument's input is unexpectedly null or empty
|
||||
*/
|
||||
public class NoInputProvidedException extends ParserException {
|
||||
|
||||
/**
|
||||
* Construct a new NoInputProvidedException
|
||||
*
|
||||
* @param argumentParser Argument parser class
|
||||
* @param context Command context
|
||||
*/
|
||||
public NoInputProvidedException(
|
||||
final Class<?> argumentParser,
|
||||
final @NonNull CommandContext<?> context
|
||||
) {
|
||||
super(
|
||||
argumentParser,
|
||||
context,
|
||||
Caption.of("argument.parse.failure.no_input_was_provided")
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
//
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2020 Alexander Söderberg & Contributors
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
package net.draycia.carbon.common.utils;
|
||||
|
||||
import cloud.commandframework.arguments.CommandArgument;
|
||||
import cloud.commandframework.arguments.parser.ArgumentParseResult;
|
||||
import cloud.commandframework.arguments.parser.ArgumentParser;
|
||||
import cloud.commandframework.captions.Caption;
|
||||
import cloud.commandframework.captions.CaptionVariable;
|
||||
import cloud.commandframework.context.CommandContext;
|
||||
import cloud.commandframework.exceptions.parsing.ParserException;
|
||||
import cloud.commandframework.types.tuples.Pair;
|
||||
import io.leangen.geantyref.TypeToken;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Parser for color codes.
|
||||
* <p>
|
||||
* Accepts {@link NamedTextColor NamedTextColors}, Legacy Minecraft {@literal &} color codes, Hex Codes (#RRGGBB)
|
||||
*
|
||||
* @param <C> Command sender type
|
||||
*/
|
||||
public final class TextColorArgument<C> extends CommandArgument<C, TextColor> {
|
||||
|
||||
private static final Pattern LEGACY_PREDICATE = Pattern.compile(
|
||||
"&[0-9a-fA-F]"
|
||||
);
|
||||
|
||||
private static final Pattern HEX_PREDICATE = Pattern.compile(
|
||||
"#?([a-fA-F0-9]{1,6})"
|
||||
);
|
||||
|
||||
private static final Collection<Pair<Character, NamedTextColor>> COLORS = Arrays.asList(
|
||||
Pair.of('0', NamedTextColor.BLACK),
|
||||
Pair.of('1', NamedTextColor.DARK_BLUE),
|
||||
Pair.of('2', NamedTextColor.DARK_GREEN),
|
||||
Pair.of('3', NamedTextColor.DARK_GREEN),
|
||||
Pair.of('4', NamedTextColor.DARK_AQUA),
|
||||
Pair.of('5', NamedTextColor.DARK_PURPLE),
|
||||
Pair.of('6', NamedTextColor.GOLD),
|
||||
Pair.of('7', NamedTextColor.GRAY),
|
||||
Pair.of('8', NamedTextColor.DARK_GRAY),
|
||||
Pair.of('9', NamedTextColor.BLUE),
|
||||
Pair.of('a', NamedTextColor.GREEN),
|
||||
Pair.of('b', NamedTextColor.AQUA),
|
||||
Pair.of('c', NamedTextColor.RED),
|
||||
Pair.of('d', NamedTextColor.LIGHT_PURPLE),
|
||||
Pair.of('e', NamedTextColor.YELLOW),
|
||||
Pair.of('f', NamedTextColor.WHITE)
|
||||
);
|
||||
|
||||
private TextColorArgument(
|
||||
final boolean required,
|
||||
final @NonNull String name,
|
||||
final @NonNull String defaultValue
|
||||
) {
|
||||
super(
|
||||
required,
|
||||
name,
|
||||
new TextColorParser<>(),
|
||||
defaultValue,
|
||||
TypeToken.get(TextColor.class),
|
||||
null,
|
||||
new LinkedList<>()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new required TextColor argument
|
||||
*
|
||||
* @param name Argument name
|
||||
* @param <C> Command sender type
|
||||
* @return Created argument
|
||||
*/
|
||||
public static <C> @NonNull TextColorArgument<C> of(final @NonNull String name) {
|
||||
return new TextColorArgument<>(
|
||||
true,
|
||||
name,
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new optional TextColor argument
|
||||
*
|
||||
* @param name Argument name
|
||||
* @param <C> Command sender type
|
||||
* @return Created argument
|
||||
*/
|
||||
public static <C> @NonNull TextColorArgument<C> optional(final @NonNull String name) {
|
||||
return new TextColorArgument<>(
|
||||
false,
|
||||
name,
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new optional TextColor argument
|
||||
*
|
||||
* @param name Argument name
|
||||
* @param defaultValue Default value
|
||||
* @param <C> Command sender type
|
||||
* @return Created argument
|
||||
*/
|
||||
public static <C> @NonNull TextColorArgument<C> optionalWithDefault(
|
||||
final @NonNull String name,
|
||||
final @NonNull String defaultValue
|
||||
) {
|
||||
return new TextColorArgument<>(
|
||||
false,
|
||||
name,
|
||||
defaultValue
|
||||
);
|
||||
}
|
||||
|
||||
public static final class TextColorParser<C> implements ArgumentParser<C, TextColor> {
|
||||
|
||||
@Override
|
||||
public @NonNull ArgumentParseResult<@NonNull TextColor> parse(
|
||||
final @NonNull CommandContext<@NonNull C> commandContext,
|
||||
final @NonNull Queue<@NonNull String> inputQueue
|
||||
) {
|
||||
final String input = inputQueue.peek();
|
||||
if (input == null) {
|
||||
return ArgumentParseResult.failure(new NoInputProvidedException(
|
||||
TextColorParser.class,
|
||||
commandContext
|
||||
));
|
||||
}
|
||||
if (LEGACY_PREDICATE.matcher(input).matches()) {
|
||||
final char code = input.substring(1).toLowerCase().charAt(0);
|
||||
for (final Pair<Character, NamedTextColor> pair : COLORS) {
|
||||
if (pair.getFirst() == code) {
|
||||
inputQueue.remove();
|
||||
return ArgumentParseResult.success(
|
||||
pair.getSecond()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (final Pair<Character, NamedTextColor> pair : COLORS) {
|
||||
if (pair.getSecond().toString().equalsIgnoreCase(input)) {
|
||||
inputQueue.remove();
|
||||
return ArgumentParseResult.success(
|
||||
pair.getSecond()
|
||||
);
|
||||
}
|
||||
}
|
||||
if (HEX_PREDICATE.matcher(input).matches()) {
|
||||
return ArgumentParseResult.success(
|
||||
TextColor.color(Integer.parseInt(input.startsWith("#") ? input.substring(1) : input, 16))
|
||||
);
|
||||
}
|
||||
return ArgumentParseResult.failure(
|
||||
new TextColorParseException(
|
||||
commandContext,
|
||||
input
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull List<@NonNull String> suggestions(
|
||||
final @NonNull CommandContext<C> commandContext, final @NonNull String input
|
||||
) {
|
||||
final List<String> suggestions = new LinkedList<>();
|
||||
if (input.isEmpty() || input.equals("#") || (HEX_PREDICATE.matcher(input).matches()
|
||||
&& input.length() < (input.startsWith("#") ? 7 : 6))) {
|
||||
for (char c = 'a'; c <= 'f'; c++) {
|
||||
suggestions.add(String.format("%s%c", input, c));
|
||||
suggestions.add(String.format("&%c", c));
|
||||
}
|
||||
for (char c = '0'; c <= '9'; c++) {
|
||||
suggestions.add(String.format("%s%c", input, c));
|
||||
suggestions.add(String.format("&%c", c));
|
||||
}
|
||||
}
|
||||
suggestions.addAll(NamedTextColor.NAMES.keys());
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final class TextColorParseException extends ParserException {
|
||||
|
||||
private TextColorParseException(
|
||||
final @NonNull CommandContext<?> commandContext,
|
||||
final @NonNull String input
|
||||
) {
|
||||
super(
|
||||
TextColorParser.class,
|
||||
commandContext,
|
||||
Caption.of("'{input}' is not a valid color"),
|
||||
CaptionVariable.of("input", input)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user