Change indentation and improve event

This commit is contained in:
Draycia committed 2021-05-16 18:51:32 -07:00
1 parent 73c7f3f78f
commit 591a6606cc
31 files changed
+1072 -974

No files matched your search

+4 -4
View File
@@ -109,12 +109,12 @@
<!-- https://checkstyle.org/config_misc.html#Indentation -->
<module name="Indentation">
<property name="arrayInitIndent" value="2"/>
<property name="basicOffset" value="2"/>
<property name="arrayInitIndent" value="4"/>
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="2"/>
<property name="caseIndent" value="4"/>
<property name="lineWrappingIndentation" value="0"/>
<property name="throwsIndent" value="2"/>
<property name="throwsIndent" value="4"/>
</module>
<!-- https://checkstyle.org/config_javadoc.html#InvalidJavadocPosition -->
+1 -1
View File
@@ -24,7 +24,7 @@ root = true
[*]
charset = utf-8
indent_size = 2
indent_size = 4
indent_style = space
insert_final_newline = true
max_line_length = off
@@ -5,6 +5,7 @@ import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
/**
* The main plugin interface.<br>
@@ -12,34 +13,32 @@ import org.checkerframework.checker.nullness.qual.NonNull;
*
* @since 1.0.0
*/
@DefaultQualifier(NonNull.class)
public interface CarbonChat {
/**
* The plugin's logger.<br>
* All messages will be logged through this.
*
* @return the plugin's logger
*
* @since 2.0.0
*/
@NonNull Logger logger();
/**
* The plugin's logger.<br>
* All messages will be logged through this.
*
* @return the plugin's logger
* @since 2.0.0
*/
Logger logger();
/**
* The event handler, used for listening to and emitting events.
*
* @return the event handler
*
* @since 2.0.0
*/
@NonNull CarbonEventHandler eventHandler();
/**
* The event handler, used for listening to and emitting events.
*
* @return the event handler
* @since 2.0.0
*/
CarbonEventHandler eventHandler();
/**
* The user manager, used for loading and obtaining {@link CarbonPlayer CarbonPlayers}.
*
* @return the user manager
*
* @since 2.0.0
*/
@NonNull UserManager userManager();
/**
* The user manager, used for loading and obtaining {@link CarbonPlayer CarbonPlayers}.
*
* @return the user manager
* @since 2.0.0
*/
UserManager userManager();
}
@@ -2,44 +2,44 @@ package net.draycia.carbon.api;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
/**
* Static accessor for the {@link CarbonChat} class.
*
* @since 1.0.0
*/
@DefaultQualifier(NonNull.class)
public final class CarbonChatProvider {
private CarbonChatProvider() {
private CarbonChatProvider() {
}
private static @Nullable CarbonChat instance;
/**
* Registers the {@link CarbonChat} implementation.
*
* @param carbonChat the carbon implementation
*
* @since 1.0.0
*/
public static void register(final @NonNull CarbonChat carbonChat) {
CarbonChatProvider.instance = carbonChat;
}
/**
* Gets the currently registered {@link CarbonChat} implementation.
*
* @return the registered carbon implementation
*
* @since 1.0.0
*/
public static @NonNull CarbonChat carbonChat() {
if (CarbonChatProvider.instance == null) {
throw new IllegalStateException("CarbonChat not initialized!"); // LuckPerms design go brrrr
}
return CarbonChatProvider.instance;
}
private static @Nullable CarbonChat instance;
/**
* Registers the {@link CarbonChat} implementation.
*
* @param carbonChat the carbon implementation
* @since 1.0.0
*/
public static void register(final CarbonChat carbonChat) {
CarbonChatProvider.instance = carbonChat;
}
/**
* Gets the currently registered {@link CarbonChat} implementation.
*
* @return the registered carbon implementation
* @since 1.0.0
*/
public static CarbonChat carbonChat() {
if (CarbonChatProvider.instance == null) {
throw new IllegalStateException("CarbonChat not initialized!"); // LuckPerms design go brrrr
}
return CarbonChatProvider.instance;
}
}
@@ -0,0 +1,42 @@
package net.draycia.carbon.api.channels;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.ChatComponentRenderer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
/**
* ChatChannel interface, supplies a formatter and filters recipients.
*
* @since 2.0.0
*/
@DefaultQualifier(NonNull.class)
public interface ChatChannel {
/**
* Checks if the player may receive messages from this channel.
*
* @param player the player
* @return if the player may receive this channel's messages
* @since 2.0.0
*/
boolean mayReceiveMessages(final CarbonPlayer player);
/**
* Checks if the player may send messages in this channel.
*
* @param player the player
* @return if the player may send messages in this channel
* @since 2.0.0
*/
boolean maySendMessages(final CarbonPlayer player);
/**
* This channel's renderer.
*
* @return the renderer
* @since 2.0.0
*/
ChatComponentRenderer renderer();
}
@@ -6,6 +6,7 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.List;
import java.util.Map;
@@ -15,107 +16,101 @@ import java.util.Map;
*
* @since 2.0.0
*/
@DefaultQualifier(NonNull.class)
public class CarbonChatEvent extends CancellableCarbonEvent {
private final @NonNull Map<Key, ChatComponentRenderer> renderers;
private final Map<Key, ChatComponentRenderer> renderers;
private final @NonNull CarbonPlayer sender;
private final CarbonPlayer sender;
private final @NonNull Component originalMessage;
private final Component originalMessage;
private @NonNull Component message;
private Component message;
private final @NonNull List<@NonNull ? extends Audience> recipients;
private final List<? extends Audience> recipients;
/**
* {@link CancellableCarbonEvent} that's called when players send messages in chat.
*
* @param sender the sender of the message
* @param originalMessage the original message that was sent
* @param recipients the recipients of the message
* @param renderers the renderers of the message
*
* @since 2.0.0
*/
public CarbonChatEvent(
final @NonNull CarbonPlayer sender,
final @NonNull Component originalMessage,
final @NonNull List<@NonNull ? extends Audience> recipients,
final @NonNull Map<Key, ChatComponentRenderer> renderers
) {
this.sender = sender;
this.originalMessage = originalMessage;
this.message = originalMessage;
this.recipients = recipients;
this.renderers = renderers;
}
/**
* {@link CancellableCarbonEvent} that's called when players send messages in chat.
*
* @param sender the sender of the message
* @param originalMessage the original message that was sent
* @param recipients the recipients of the message
* @param renderers the renderers of the message
* @since 2.0.0
*/
public CarbonChatEvent(
final CarbonPlayer sender,
final Component originalMessage,
final List<? extends Audience> recipients,
final Map<Key, ChatComponentRenderer> renderers
) {
this.sender = sender;
this.originalMessage = originalMessage;
this.message = originalMessage;
this.recipients = recipients;
this.renderers = renderers;
}
/**
* Get the renderers used to construct components for each of the recipients.
*
* @return The per-recipient component renderers.
*
* @since 2.0.0
*/
public @NonNull Map<Key, ChatComponentRenderer> renderers() {
return this.renderers;
}
/**
* Get the renderers used to construct components for each of the recipients.
*
* @return The per-recipient component renderers.
* @since 2.0.0
*/
public Map<Key, ChatComponentRenderer> renderers() {
return this.renderers;
}
/**
* Get the sender of the message.
*
* @return The message sender.
*
* @since 2.0.0
*/
public CarbonPlayer sender() {
return this.sender;
}
/**
* Get the sender of the message.
*
* @return The message sender.
* @since 2.0.0
*/
public CarbonPlayer sender() {
return this.sender;
}
/**
* Get the original message that was sent.
*
* @return The original message.
*
* @since 2.0.0
*/
public Component originalMessage() {
return this.originalMessage;
}
/**
* Get the original message that was sent.
*
* @return The original message.
* @since 2.0.0
*/
public Component originalMessage() {
return this.originalMessage;
}
/**
* Get the chat message that will be sent.
*
* @return The chat message.
*
* @since 2.0.0
*/
public Component message() {
return this.message;
}
/**
* Get the chat message that will be sent.
*
* @return The chat message.
* @since 2.0.0
*/
public Component message() {
return this.message;
}
/**
* Set the chat message that will be sent.
*
* @param message new message
*
* @since 2.0.0
*/
public void message(final @NonNull Component message) {
this.message = message;
}
/**
* Set the chat message that will be sent.
*
* @param message new message
* @since 2.0.0
*/
public void message(final Component message) {
this.message = message;
}
/**
* The recipients of the message.
* List is mutable and elements may be added/removed.
*
* @return the recipients of the message.
* entries may be players, console, or other audience implementations
*
* @since 2.0.0
*/
public @NonNull List<@NonNull ? extends Audience> recipients() {
return this.recipients;
}
/**
* The recipients of the message.
* List is mutable and elements may be added/removed.
*
* @return the recipients of the message.
* entries may be players, console, or other audience implementations
* @since 2.0.0
*/
public List<? extends Audience> recipients() {
return this.recipients;
}
}
@@ -4,6 +4,7 @@ import net.kyori.event.EventSubscriber;
import net.kyori.event.PostResult;
import net.kyori.event.SimpleEventBus;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.function.Consumer;
@@ -12,84 +13,83 @@ import java.util.function.Consumer;
*
* @since 1.0.0
*/
@DefaultQualifier(NonNull.class)
public final class CarbonEventHandler {
private final SimpleEventBus<CarbonEvent> eventBus = new SimpleEventBus<>(CarbonEvent.class);
private final SimpleEventBus<CarbonEvent> eventBus = new SimpleEventBus<>(CarbonEvent.class);
/**
* Registers a subscriber for the given event class.
*
* @param eventClass the class to listen for
* @param subscriber the subscriber that's executed when the event is emitted
* @param <T> the class to listen for
*
* @since 1.0.0
*/
public <T extends CarbonEvent> void register(final @NonNull Class<T> eventClass, final @NonNull EventSubscriber<T> subscriber) {
this.eventBus.register(eventClass, subscriber);
}
/**
* Registers a subscriber for the given event class.
*
* @param eventClass the class to listen for
* @param subscriber the subscriber that's executed when the event is emitted
* @param <T> the class to listen for
* @since 1.0.0
*/
public <T extends CarbonEvent> void register(final Class<T> eventClass, final EventSubscriber<T> subscriber) {
this.eventBus.register(eventClass, subscriber);
}
/**
* Registers a subscriber for the given event class.<br>
* Includes extra values to control when the consumer is executed.
*
* @param eventClass the class to listen for
* @param priority the priority of the consumer
* @param consumeCancelled if the consumer should be executed if the event is cancelled early
* @param consumer the consumer that's executed when the event is emitted
* @param <T> the class to listen for
*
* @return the subscriber, so that it may be unregistered
*
* @since 2.0.0
*/
public <T extends CarbonEvent> EventSubscriber<T> register(final @NonNull Class<T> eventClass, final int priority, final boolean consumeCancelled, final @NonNull Consumer<T> consumer) {
final var subscriber = new EventSubscriber<T>() {
@Override
public int postOrder() {
return priority;
}
/**
* Registers a subscriber for the given event class.<br>
* Includes extra values to control when the consumer is executed.
*
* @param eventClass the class to listen for
* @param priority the priority of the consumer
* @param consumeCancelled if the consumer should be executed if the event is cancelled early
* @param consumer the consumer that's executed when the event is emitted
* @param <T> the class to listen for
* @return the subscriber, so that it may be unregistered
* @since 2.0.0
*/
public <T extends CarbonEvent> EventSubscriber<T> register(
final Class<T> eventClass, final int priority,
final boolean consumeCancelled,
final Consumer<T> consumer) {
@Override
public boolean consumeCancelledEvents() {
return consumeCancelled;
}
final var subscriber = new EventSubscriber<T>() {
@Override
public int postOrder() {
return priority;
}
@Override
public void invoke(final @NonNull T event) {
consumer.accept(event);
}
};
@Override
public boolean consumeCancelledEvents() {
return consumeCancelled;
}
this.eventBus.register(eventClass, subscriber);
@Override
public void invoke(final T event) {
consumer.accept(event);
}
};
return subscriber;
}
this.eventBus.register(eventClass, subscriber);
/**
* Unregisters the subscriber and prevents it from being executed.
*
* @param subscriber the subscriber
*
* @since 1.0.0
*/
public void unregister(final @NonNull EventSubscriber<? super CarbonEvent> subscriber) {
this.eventBus.unregister(subscriber);
}
return subscriber;
}
/**
* Emits the supplied event and returns its result.<br>
* Events are modified in place, so care should be taken to keep a reference to
* the event while it's being emitted.
*
* @param event the event to be emitted
*
* @return the result
*
* @since 2.0.0
*/
public PostResult emit(final @NonNull CarbonEvent event) {
return this.eventBus.post(event);
}
/**
* Unregisters the subscriber and prevents it from being executed.
*
* @param subscriber the subscriber
* @since 1.0.0
*/
public void unregister(final EventSubscriber<? super CarbonEvent> subscriber) {
this.eventBus.unregister(subscriber);
}
/**
* Emits the supplied event and returns its result.<br>
* Events are modified in place, so care should be taken to keep a reference to
* the event while it's being emitted.
*
* @param event the event to be emitted
* @return the result
* @since 2.0.0
*/
public PostResult emit(final CarbonEvent event) {
return this.eventBus.post(event);
}
}
@@ -1,10 +1,12 @@
package net.draycia.carbon.api.users;
import net.draycia.carbon.api.channels.ChatChannel;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identified;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.UUID;
@@ -13,52 +15,64 @@ import java.util.UUID;
*
* @since 2.0.0
*/
@DefaultQualifier(NonNull.class)
public interface CarbonPlayer extends Audience, Identified {
/**
* Gets the player's username.
*
* @return the player's username
*
* @since 2.0.0
*/
@NonNull String username();
/**
* Gets the player's username.
*
* @return the player's username
* @since 2.0.0
*/
String username();
/**
* Gets the player's display name, shown in places like chat and tab menu.
*
* @return the player's display name
*
* @since 2.0.0
*/
@NonNull Component displayName();
/**
* Gets the player's display name, shown in places like chat and tab menu.
*
* @return the player's display name
* @since 2.0.0
*/
Component displayName();
/**
* Sets the player's display name.<br>
* Setting null is equivalent to setting the display name to the username.
*
* @param displayName the new display name
*
* @since 2.0.0
*/
void displayName(final @Nullable Component displayName);
/**
* Sets the player's display name.<br>
* Setting null is equivalent to setting the display name to the username.
*
* @param displayName the new display name
* @since 2.0.0
*/
void displayName(final @Nullable Component displayName);
/**
* The player's UUID, often used for identification purposes.
*
* @return the player's UUID
*
* @since 2.0.0
*/
@NonNull UUID uuid();
/**
* The player's UUID, often used for identification purposes.
*
* @return the player's UUID
* @since 2.0.0
*/
UUID uuid();
/**
* Creates a {@link Component} with a content and item hover given the player's actively held item.
*
* @return the player's held item as an item hover component
*
* @since 2.0.0
*/
@NonNull Component createItemHoverComponent();
/**
* Creates a {@link Component} with a content and item hover given the player's actively held item.
*
* @return the player's held item as an item hover component
* @since 2.0.0
*/
Component createItemHoverComponent();
/**
* The player's selected channel. If none has been set, returns the server default.
*
* @return the player's selected channel
* @since 2.0.0
*/
ChatChannel selectedChannel();
/**
* Sets the player's selected channel.
*
* @param chatChannel the channel
* @since 2.0.0
*/
void selectedChannel(final ChatChannel chatChannel);
}
@@ -2,6 +2,7 @@ package net.draycia.carbon.api.users;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.UUID;
@@ -10,28 +11,25 @@ import java.util.UUID;
*
* @since 2.0.0
*/
@DefaultQualifier(NonNull.class)
public interface UserManager {
/**
* Loads and returns a {@link CarbonPlayer} with the given {@link UUID}.
*
* @param uuid The player's UUID.
*
* @return The {@link CarbonPlayer}, or null if the player doesn't exist.
*
* @since 2.0.0
*/
@Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid);
/**
* Loads and returns a {@link CarbonPlayer} with the given {@link UUID}.
*
* @param uuid The player's UUID.
* @return The {@link CarbonPlayer}, or null if the player doesn't exist.
* @since 2.0.0
*/
@Nullable CarbonPlayer carbonPlayer(final UUID uuid);
/**
* Loads and returns a {@link CarbonPlayer} with the given username.
*
* @param username The player's username.
*
* @return The {@link CarbonPlayer}, or null if the player doesn't exist.
*
* @since 2.0.0
*/
@Nullable CarbonPlayer carbonPlayer(final @NonNull String username);
/**
* Loads and returns a {@link CarbonPlayer} with the given username.
*
* @param username The player's username.
* @return The {@link CarbonPlayer}, or null if the player doesn't exist.
* @since 2.0.0
*/
@Nullable CarbonPlayer carbonPlayer(final String username);
}
@@ -5,6 +5,7 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
/**
* Renderer used to construct chat components on a per-player basis.
@@ -12,26 +13,25 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 2.0.0
*/
@FunctionalInterface
@DefaultQualifier(NonNull.class)
public interface ChatComponentRenderer {
/**
* Renders a Component for the specified recipient.
*
* @param sender the player that sent the message
* @param recipient a recipient of the message.
* may be a player, console, or other Audience implementations
* @param message the message being sent
* @param originalMessage the original message that was sent
*
* @return the component to be shown to the recipient,
* or null if the recipient should not receive the message
*
* @since 2.0.0
*/
@Nullable
Component render(final @NonNull CarbonPlayer sender,
final @NonNull Audience recipient,
final @NonNull Component message,
final @NonNull Component originalMessage);
/**
* Renders a Component for the specified recipient.
*
* @param sender the player that sent the message
* @param recipient a recipient of the message.
* may be a player, console, or other Audience implementations
* @param message the message being sent
* @param originalMessage the original message that was sent
* @return the component to be shown to the recipient,
* or null if the recipient should not receive the message
* @since 2.0.0
*/
@Nullable
Component render(final CarbonPlayer sender,
final Audience recipient,
final Component message,
final Component originalMessage);
}
@@ -7,6 +7,7 @@ import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyFormat;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.regex.Pattern;
@@ -15,95 +16,92 @@ import java.util.regex.Pattern;
*
* @since 1.0.0
*/
@DefaultQualifier(NonNull.class)
public final class ColorUtils {
private ColorUtils() {
private ColorUtils() {
}
/**
* Parses the input into a color.<br>
* Supports named colors, legacy, and hex inputs.
*
* @param input the color input
*
* @return the color
*
* @since 1.0.0
*/
public static @Nullable TextColor parseColor(@NonNull String input) {
if (input.isEmpty()) {
return NamedTextColor.WHITE;
}
for (final NamedTextColor namedColor : NamedTextColor.NAMES.values()) {
if (namedColor.toString().equalsIgnoreCase(input)) {
return namedColor;
}
}
if (input.contains("&") || input.contains("§")) {
input = input.replace("&", "§");
return LegacyComponentSerializer.legacySection().deserialize(input).color();
}
return TextColor.fromCSSHexString(input);
}
private static final @NonNull Pattern spigotLegacyRGB =
Pattern.compile("[§&]x[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])");
private static final @NonNull Pattern pluginRGB =
Pattern.compile("[§&]#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
private static final @NonNull String hexReplacement = "<#$1$2$3$4$5$6>";
/**
* Converts the input legacy, legacy rgb, and alternate color formats to MiniMessage color tags.
*
* @param input the message to convert
*
* @return the converted message
*
* @since 1.0.0
*/
public static @NonNull String legacyToMiniMessage(final @NonNull String input) {
String output = input;
// Legacy RGB
output = spigotLegacyRGB.matcher(output).replaceAll(hexReplacement);
// Alternate RGB, TAB (neznamy) && KiteBoard
output = pluginRGB.matcher(output).replaceAll(hexReplacement);
// Legacy Colors
for (final char c : "0123456789abcdefABCDEF".toCharArray()) {
final LegacyFormat format = LegacyComponentSerializer.parseChar(Character.toLowerCase(c));
if (format != null) {
final TextColor color = format.color();
if (color != null) {
output = output.replaceAll("[§&]" + c, "<" + color.asHexString() + ">");
/**
* Parses the input into a color.<br>
* Supports named colors, legacy, and hex inputs.
*
* @param input the color input
* @return the color
* @since 1.0.0
*/
public static @Nullable TextColor parseColor(String input) {
if (input.isEmpty()) {
return NamedTextColor.WHITE;
}
}
}
// Legacy Formatting
for (final char c : "klmnoKLMNO".toCharArray()) {
final LegacyFormat format = LegacyComponentSerializer.parseChar(Character.toLowerCase(c));
if (format != null) {
final TextDecoration decoration = format.decoration();
if (decoration != null) {
output = output.replaceAll("[§&]" + c, "<" + decoration.name() + ">");
for (final NamedTextColor namedColor : NamedTextColor.NAMES.values()) {
if (namedColor.toString().equalsIgnoreCase(input)) {
return namedColor;
}
}
}
if (input.contains("&") || input.contains("§")) {
input = input.replace("&", "§");
return LegacyComponentSerializer.legacySection().deserialize(input).color();
}
return TextColor.fromCSSHexString(input);
}
return output;
}
private static final Pattern spigotLegacyRGB =
Pattern.compile("[§&]x[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])");
private static final Pattern pluginRGB =
Pattern.compile("[§&]#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
private static final String hexReplacement = "<#$1$2$3$4$5$6>";
/**
* Converts the input legacy, legacy rgb, and alternate color formats to MiniMessage color tags.
*
* @param input the message to convert
* @return the converted message
* @since 1.0.0
*/
public static String legacyToMiniMessage(final String input) {
String output = input;
// Legacy RGB
output = spigotLegacyRGB.matcher(output).replaceAll(hexReplacement);
// Alternate RGB, TAB (neznamy) && KiteBoard
output = pluginRGB.matcher(output).replaceAll(hexReplacement);
// Legacy Colors
for (final char c : "0123456789abcdefABCDEF".toCharArray()) {
final @Nullable LegacyFormat format = LegacyComponentSerializer.parseChar(Character.toLowerCase(c));
if (format != null) {
final @Nullable TextColor color = format.color();
if (color != null) {
output = output.replaceAll("[§&]" + c, "<" + color.asHexString() + ">");
}
}
}
// Legacy Formatting
for (final char c : "klmnoKLMNO".toCharArray()) {
final @Nullable LegacyFormat format = LegacyComponentSerializer.parseChar(Character.toLowerCase(c));
if (format != null) {
final @Nullable TextDecoration decoration = format.decoration();
if (decoration != null) {
output = output.replaceAll("[§&]" + c, "<" + decoration.name() + ">");
}
}
}
return output;
}
}
@@ -8,18 +8,16 @@ import org.checkerframework.checker.nullness.qual.NonNull;
*
* @param <K> the key type
* @param <V> the value type
*
* @since 1.0.0
*/
public interface DefaultedKeyValueRegistry<K, V> extends DefaultedRegistryGetter<K, V> {
/**
* Gets the default value.
*
* @return the default value
*
* @since 1.0.0
*/
@NonNull V defaultValue();
/**
* Gets the default value.
*
* @return the default value
* @since 1.0.0
*/
@NonNull V defaultValue();
}
@@ -18,51 +18,51 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public final class CarbonChatBukkit extends CarbonChatCommon {
private final @NonNull UserManager userManager = new MemoryUserManagerBukkit();
private final Logger logger = LogManager.getLogger("CarbonChat");
private final CarbonChatBukkitEntry plugin;
private final @NonNull UserManager userManager = new MemoryUserManagerBukkit();
private final Logger logger = LogManager.getLogger("CarbonChat");
private final CarbonChatBukkitEntry plugin;
CarbonChatBukkit(final @NonNull CarbonChatBukkitEntry plugin) {
this.plugin = plugin;
CarbonChatBukkit(final @NonNull CarbonChatBukkitEntry plugin) {
this.plugin = plugin;
Injector.provide(CarbonChat.class, this);
}
@Override
public @NonNull Logger logger() {
return this.logger;
}
@Override
public @NonNull UserManager userManager() {
return this.userManager;
}
@Override
protected @NonNull CommandManager<Commander> createCommandManager() {
final PaperCommandManager<Commander> commandManager;
try {
commandManager = new PaperCommandManager<>(
this.plugin,
AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(),
commandSender -> {
if (commandSender instanceof Player player) {
return new BukkitPlayerCommander(this, player);
}
return BukkitCommander.from(commandSender);
},
commander -> ((BukkitCommander) commander).commandSender()
);
} catch (final Exception ex) {
throw new RuntimeException("Failed to initialize command manager.", ex);
Injector.provide(CarbonChat.class, this);
}
commandManager.registerAsynchronousCompletions();
commandManager.registerBrigadier();
final var brigadierManager = commandManager.brigadierManager();
if (brigadierManager != null) {
brigadierManager.setNativeNumberSuggestions(false);
@Override
public @NonNull Logger logger() {
return this.logger;
}
@Override
public @NonNull UserManager userManager() {
return this.userManager;
}
@Override
protected @NonNull CommandManager<Commander> createCommandManager() {
final PaperCommandManager<Commander> commandManager;
try {
commandManager = new PaperCommandManager<>(
this.plugin,
AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(),
commandSender -> {
if (commandSender instanceof Player player) {
return new BukkitPlayerCommander(this, player);
}
return BukkitCommander.from(commandSender);
},
commander -> ((BukkitCommander) commander).commandSender()
);
} catch (final Exception ex) {
throw new RuntimeException("Failed to initialize command manager.", ex);
}
commandManager.registerAsynchronousCompletions();
commandManager.registerBrigadier();
final var brigadierManager = commandManager.brigadierManager();
if (brigadierManager != null) {
brigadierManager.setNativeNumberSuggestions(false);
}
return commandManager;
}
return commandManager;
}
}
@@ -11,34 +11,34 @@ import java.util.logging.Level;
public final class CarbonChatBukkitEntry extends JavaPlugin {
private static final int BSTATS_PLUGIN_ID = 8720;
private static final int BSTATS_PLUGIN_ID = 8720;
private @MonotonicNonNull CarbonChatBukkit carbon;
private @MonotonicNonNull CarbonChatBukkit carbon;
@Override
public void onEnable() {
if (!PaperLib.isPaper()) {
this.getLogger().log(Level.SEVERE, "*");
this.getLogger().log(Level.SEVERE, "* CarbonChat makes extensive use of APIs added by Paper.");
this.getLogger().log(Level.SEVERE, "* For this reason, CarbonChat is not compatible with Spigot or CraftBukkit servers.");
this.getLogger().log(Level.SEVERE, "* Upgrade your server to Paper in order to use CarbonChat.");
this.getLogger().log(Level.SEVERE, "*");
PaperLib.suggestPaper(this, Level.SEVERE);
Bukkit.getPluginManager().disablePlugin(this);
return;
@Override
public void onEnable() {
if (!PaperLib.isPaper()) {
this.getLogger().log(Level.SEVERE, "*");
this.getLogger().log(Level.SEVERE, "* CarbonChat makes extensive use of APIs added by Paper.");
this.getLogger().log(Level.SEVERE, "* For this reason, CarbonChat is not compatible with Spigot or CraftBukkit servers.");
this.getLogger().log(Level.SEVERE, "* Upgrade your server to Paper in order to use CarbonChat.");
this.getLogger().log(Level.SEVERE, "*");
PaperLib.suggestPaper(this, Level.SEVERE);
Bukkit.getPluginManager().disablePlugin(this);
return;
}
this.carbon = new CarbonChatBukkit(this);
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
Bukkit.getPluginManager().registerEvents(new BukkitChatListener(), this);
this.carbon.initialize();
}
this.carbon = new CarbonChatBukkit(this);
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
Bukkit.getPluginManager().registerEvents(new BukkitChatListener(), this);
this.carbon.initialize();
}
@Override
public void onDisable() {
}
@Override
public void onDisable() {
}
}
@@ -8,29 +8,29 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public interface BukkitCommander extends Commander, ForwardingAudience.Single {
@NonNull CommandSender commandSender();
@NonNull CommandSender commandSender();
static @NonNull BukkitCommander from(final @NonNull CommandSender sender) {
return new BukkitCommanderImpl(sender);
}
final class BukkitCommanderImpl implements BukkitCommander {
private final CommandSender commandSender;
private BukkitCommanderImpl(final @NonNull CommandSender commandSender) {
this.commandSender = commandSender;
static @NonNull BukkitCommander from(final @NonNull CommandSender sender) {
return new BukkitCommanderImpl(sender);
}
public @NonNull CommandSender commandSender() {
return this.commandSender;
}
final class BukkitCommanderImpl implements BukkitCommander {
@Override
public @NonNull Audience audience() {
return this.commandSender;
}
private final CommandSender commandSender;
}
private BukkitCommanderImpl(final @NonNull CommandSender commandSender) {
this.commandSender = commandSender;
}
public @NonNull CommandSender commandSender() {
return this.commandSender;
}
@Override
public @NonNull Audience audience() {
return this.commandSender;
}
}
}
@@ -11,23 +11,23 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import static java.util.Objects.requireNonNull;
public record BukkitPlayerCommander(
@NonNull CarbonChat carbon,
@NonNull Player player
@NonNull CarbonChat carbon,
@NonNull Player player
) implements PlayerCommander, BukkitCommander {
@Override
public @NonNull CommandSender commandSender() {
return this.player;
}
@Override
public @NonNull CommandSender commandSender() {
return this.player;
}
@Override
public @NonNull Audience audience() {
return this.player;
}
@Override
public @NonNull Audience audience() {
return this.player;
}
@Override
public @NonNull CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.userManager().carbonPlayer(this.player.getUniqueId()), "No CarbonPlayer for logged in Player!");
}
@Override
public @NonNull CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.userManager().carbonPlayer(this.player.getUniqueId()), "No CarbonPlayer for logged in Player!");
}
}
@@ -3,9 +3,10 @@ package net.draycia.carbon.bukkit.listeners;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.kyori.adventure.audience.Audience;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@@ -19,51 +20,57 @@ import static net.kyori.adventure.key.Key.key;
public final class BukkitChatListener implements Listener {
private final CarbonChatBukkit carbonChat = byInject(CarbonChat.class); // lol this is dumb
private final UserManager userManager = this.carbonChat.userManager();
private final CarbonChatBukkit carbonChat = byInject(CarbonChat.class); // lol this is dumb
private final UserManager userManager = this.carbonChat.userManager();
@EventHandler
public void onPlayerChat(final @NonNull AsyncChatEvent event) {
final var player = this.userManager.carbonPlayer(event.getPlayer().getUniqueId());
@EventHandler
public void onPlayerChat(final @NonNull AsyncChatEvent event) {
final var sender = this.userManager.carbonPlayer(event.getPlayer().getUniqueId());
if (player == null) {
return;
}
final var recipients = new ArrayList<CarbonPlayer>();
for (final Player recipient : event.recipients()) {
final var bukkitRecipient = this.userManager.carbonPlayer(recipient.getUniqueId());
if (bukkitRecipient != null) {
recipients.add(bukkitRecipient);
}
}
final var chatEvent = new CarbonChatEvent(player, event.message(), recipients,
Map.of(key("carbon", "default"), this.carbonChat.vanillaChatRenderer));
final var result = this.carbonChat.eventHandler().emit(chatEvent);
if (result.wasSuccessful()) {
// TODO: send to channels
for (final var recipient : chatEvent.recipients()) {
var component = chatEvent.message();
for (final var entry : chatEvent.renderers().entrySet()) {
component = entry.getValue().render(player,
recipient, chatEvent.message(), chatEvent.originalMessage());
if (sender == null) {
return;
}
if (component != null) {
recipient.sendMessage(component);
}
}
}
final var recipients = new ArrayList<Audience>();
final var channel = sender.selectedChannel();
// There's no guarantee that recipients is mutable.
// If it's ever immutable, we yell at who ever is responsible.
event.recipients().clear();
}
for (final Player bukkitRecipient : event.recipients()) {
final var recipient = this.userManager.carbonPlayer(bukkitRecipient.getUniqueId());
// The naming is a little backwards, ChatChannel#mayReceiveMessages
// TODO: Change it at some point
if (recipient != null && channel.mayReceiveMessages(recipient)) {
recipients.add(recipient);
}
}
// console too!
recipients.add(Bukkit.getConsoleSender());
final var chatEvent = new CarbonChatEvent(sender, event.message(), recipients,
Map.of(key("carbon", "default"), channel.renderer()));
final var result = this.carbonChat.eventHandler().emit(chatEvent);
if (result.wasSuccessful()) {
// TODO: send to channels
for (final var recipient : chatEvent.recipients()) {
var component = chatEvent.message();
for (final var entry : chatEvent.renderers().entrySet()) {
component = entry.getValue().render(sender,
recipient, chatEvent.message(), chatEvent.originalMessage());
}
if (component != null) {
recipient.sendMessage(component);
}
}
}
// There's no guarantee that recipients is mutable.
// If it's ever immutable, we yell at who ever is responsible.
event.recipients().clear();
}
}
@@ -14,73 +14,74 @@ import java.util.UUID;
public final class CarbonPlayerBukkit extends CarbonPlayerCommon {
public CarbonPlayerBukkit(
final @NonNull String username,
final @NonNull Component displayName,
final @NonNull UUID uuid
) {
super(username, displayName, uuid, Identity.identity(uuid));
}
@Override
public void displayName(final @Nullable Component displayName) {
super.displayName(displayName);
final Player player = this.player();
if (player != null) {
player.displayName(displayName);
}
}
@Override
public @NonNull Audience audience() {
final Player player = this.player();
if (player == null) {
return Audience.empty();
public CarbonPlayerBukkit(
final @NonNull String username,
final @NonNull Component displayName,
final @NonNull UUID uuid
) {
super(username, displayName, uuid, Identity.identity(uuid));
}
return player;
}
@Override
public void displayName(final @Nullable Component displayName) {
super.displayName(displayName);
private @Nullable Player player() {
return Bukkit.getPlayer(this.uuid);
}
final Player player = this.player();
@Override
public @NonNull Component createItemHoverComponent() {
final Player player = this.player(); // This is temporary (it's not)
if (player == null) {
return Component.empty();
if (player != null) {
player.displayName(displayName);
player.playerListName(displayName);
}
}
final ItemStack itemStack;
@Override
public @NonNull Audience audience() {
final Player player = this.player();
final ItemStack mainHand = player.getInventory().getItemInMainHand();
if (player == null) {
return Audience.empty();
}
if (!mainHand.getType().isAir()) {
itemStack = mainHand;
} else {
final ItemStack offHand = player.getInventory().getItemInMainHand();
if (!offHand.getType().isAir()) {
itemStack = offHand;
} else {
itemStack = null;
}
return player;
}
if (itemStack == null) {
return Component.empty();
private @Nullable Player player() {
return Bukkit.getPlayer(this.uuid);
}
if (itemStack.getType().isAir()) {
return Component.empty();
}
@Override
public @NonNull Component createItemHoverComponent() {
final Player player = this.player(); // This is temporary (it's not)
return itemStack.displayName();
}
if (player == null) {
return Component.empty();
}
final ItemStack itemStack;
final ItemStack mainHand = player.getInventory().getItemInMainHand();
if (!mainHand.getType().isAir()) {
itemStack = mainHand;
} else {
final ItemStack offHand = player.getInventory().getItemInMainHand();
if (!offHand.getType().isAir()) {
itemStack = offHand;
} else {
itemStack = null;
}
}
if (itemStack == null) {
return Component.empty();
}
if (itemStack.getType().isAir()) {
return Component.empty();
}
return itemStack.displayName();
}
}
@@ -18,40 +18,40 @@ import java.util.UUID;
*/
public final class MemoryUserManagerBukkit implements UserManager {
private final @NonNull Map<UUID, @NonNull CarbonPlayer> users = new HashMap<>();
private final @NonNull Map<UUID, @NonNull CarbonPlayer> users = new HashMap<>();
@Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) {
if (this.users.containsKey(uuid)) {
return this.users.get(uuid);
@Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) {
if (this.users.containsKey(uuid)) {
return this.users.get(uuid);
}
final Player player = Bukkit.getPlayer(uuid);
if (player == null) {
return null;
}
final CarbonPlayer carbonPlayer = new CarbonPlayerBukkit(player.getName(), player.displayName(), player.getUniqueId());
this.users.put(uuid, carbonPlayer);
return carbonPlayer;
}
final Player player = Bukkit.getPlayer(uuid);
@Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull String username) {
final Player player = Bukkit.getPlayer(username);
if (player == null) {
return null;
if (player == null) {
return null;
}
if (this.users.containsKey(player.getUniqueId())) {
return this.users.get(player.getUniqueId());
}
return new CarbonPlayerBukkit(player.getName(), player.displayName(), player.getUniqueId());
}
final CarbonPlayer carbonPlayer = new CarbonPlayerBukkit(player.getName(), player.displayName(), player.getUniqueId());
this.users.put(uuid, carbonPlayer);
return carbonPlayer;
}
@Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull String username) {
final Player player = Bukkit.getPlayer(username);
if (player == null) {
return null;
}
if (this.users.containsKey(player.getUniqueId())) {
return this.users.get(player.getUniqueId());
}
return new CarbonPlayerBukkit(player.getName(), player.displayName(), player.getUniqueId());
}
}
@@ -20,76 +20,76 @@ import static java.util.Collections.emptyList;
public final class PlaceholderAPIMiniMessageParser {
private final MiniMessage miniMessage;
private final MiniMessage miniMessage;
private PlaceholderAPIMiniMessageParser(final @NonNull MiniMessage miniMessage) {
this.miniMessage = miniMessage;
}
public @NonNull Component parse(final @NonNull OfflinePlayer player, final @NonNull String input, final @NonNull Collection<Template> templates) {
return this.parse(
PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(player, match),
input,
templates
);
}
public @NonNull Component parse(final @NonNull OfflinePlayer player, final @NonNull String input) {
return this.parse(player, input, emptyList());
}
public @NonNull Component parseRelational(final @NonNull Player one, final @NonNull Player two, final @NonNull String input, final @NonNull Collection<Template> templates) {
return this.parse(
PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(one, PlaceholderAPI.setRelationalPlaceholders(one, two, match)),
input,
templates
);
}
public @NonNull Component parseRelational(final @NonNull Player one, final @NonNull Player two, final @NonNull String input) {
return this.parseRelational(one, two, input, emptyList());
}
private @NonNull Component parse(
final @NonNull Pattern pattern,
final @NonNull UnaryOperator<String> placeholderResolver,
final @NonNull String input,
final @NonNull Collection<Template> originalTemplates
) {
final Matcher matcher = pattern.matcher(input);
final List<Template> templates = new ArrayList<>(originalTemplates);
final StringBuilder builder = new StringBuilder();
int id = 0;
while (matcher.find()) {
final String match = matcher.group();
final String replaced = placeholderResolver.apply(match);
if (match.equals(replaced) || !containsLegacyColorCodes(replaced)) {
matcher.appendReplacement(builder, replaced);
} else {
final String key = "papi_generated_template_" + id;
id++;
templates.add(Template.of(key, LegacyComponentSerializer.legacySection().deserialize(replaced)));
matcher.appendReplacement(builder, "<" + key + ">");
}
private PlaceholderAPIMiniMessageParser(final @NonNull MiniMessage miniMessage) {
this.miniMessage = miniMessage;
}
matcher.appendTail(builder);
return this.miniMessage.parse(builder.toString(), templates);
}
public static @NonNull PlaceholderAPIMiniMessageParser create(final @NonNull MiniMessage backingInstance) {
return new PlaceholderAPIMiniMessageParser(backingInstance);
}
private static boolean containsLegacyColorCodes(final @NonNull String string) {
final char[] charArray = string.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == LegacyComponentSerializer.SECTION_CHAR) {
return true;
}
public @NonNull Component parse(final @NonNull OfflinePlayer player, final @NonNull String input, final @NonNull Collection<Template> templates) {
return this.parse(
PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(player, match),
input,
templates
);
}
public @NonNull Component parse(final @NonNull OfflinePlayer player, final @NonNull String input) {
return this.parse(player, input, emptyList());
}
public @NonNull Component parseRelational(final @NonNull Player one, final @NonNull Player two, final @NonNull String input, final @NonNull Collection<Template> templates) {
return this.parse(
PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(one, PlaceholderAPI.setRelationalPlaceholders(one, two, match)),
input,
templates
);
}
public @NonNull Component parseRelational(final @NonNull Player one, final @NonNull Player two, final @NonNull String input) {
return this.parseRelational(one, two, input, emptyList());
}
private @NonNull Component parse(
final @NonNull Pattern pattern,
final @NonNull UnaryOperator<String> placeholderResolver,
final @NonNull String input,
final @NonNull Collection<Template> originalTemplates
) {
final Matcher matcher = pattern.matcher(input);
final List<Template> templates = new ArrayList<>(originalTemplates);
final StringBuilder builder = new StringBuilder();
int id = 0;
while (matcher.find()) {
final String match = matcher.group();
final String replaced = placeholderResolver.apply(match);
if (match.equals(replaced) || !containsLegacyColorCodes(replaced)) {
matcher.appendReplacement(builder, replaced);
} else {
final String key = "papi_generated_template_" + id;
id++;
templates.add(Template.of(key, LegacyComponentSerializer.legacySection().deserialize(replaced)));
matcher.appendReplacement(builder, "<" + key + ">");
}
}
matcher.appendTail(builder);
return this.miniMessage.parse(builder.toString(), templates);
}
public static @NonNull PlaceholderAPIMiniMessageParser create(final @NonNull MiniMessage backingInstance) {
return new PlaceholderAPIMiniMessageParser(backingInstance);
}
private static boolean containsLegacyColorCodes(final @NonNull String string) {
final char[] charArray = string.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == LegacyComponentSerializer.SECTION_CHAR) {
return true;
}
}
return false;
}
return false;
}
}
@@ -3,68 +3,46 @@ package net.draycia.carbon.common;
import cloud.commandframework.CommandManager;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.util.ChatComponentRenderer;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text;
import static net.kyori.adventure.text.Component.translatable;
import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY;
import static net.kyori.adventure.text.format.TextDecoration.BOLD;
public abstract class CarbonChatCommon implements CarbonChat {
// Mimics vanilla chat, should be *visually* identical but without the hover stuff.
// Temporary: This will be removed in the future.
@Deprecated(forRemoval = true)
public final @NonNull ChatComponentRenderer vanillaChatRenderer =
(sender, recipient, message, originalMessage) -> {
final var clickEvent = ClickEvent.suggestCommand("/msg " + sender.username());
final var hoverEvent = HoverEvent.showEntity(Key.key("player"),
sender.uuid(), text(sender.username()));
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
final var name = sender.displayName()
.clickEvent(clickEvent)
.hoverEvent(hoverEvent)
.insertion(sender.username());
public final void initialize() {
final CommandManager<Commander> commandManager = this.createCommandManager();
commandManager.command(commandManager.commandBuilder("carbon")
.handler(ctx -> {
final Commander sender = ctx.getSender();
sender.sendMessage(text()
.content("Hello from ")
.append(text("Carbon", DARK_GRAY, BOLD))
.append(text('!')));
if (sender instanceof PlayerCommander) {
final Component itemComponent = ((PlayerCommander) sender).carbonPlayer().createItemHoverComponent();
if (itemComponent != empty()) {
sender.sendMessage(TextComponent.ofChildren(text("Item: "), itemComponent));
} else {
sender.sendMessage(text("You are not holding an item!"));
}
}
}));
}
return translatable("chat.type.text", name, message);
};
protected abstract @NonNull CommandManager<Commander> createCommandManager();
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
public final void initialize() {
final CommandManager<Commander> commandManager = this.createCommandManager();
commandManager.command(commandManager.commandBuilder("carbon")
.handler(ctx -> {
final Commander sender = ctx.getSender();
sender.sendMessage(text()
.content("Hello from ")
.append(text("Carbon", DARK_GRAY, BOLD))
.append(text('!')));
if (sender instanceof PlayerCommander) {
final Component itemComponent = ((PlayerCommander) sender).carbonPlayer().createItemHoverComponent();
if (itemComponent != empty()) {
sender.sendMessage(TextComponent.ofChildren(text("Item: "), itemComponent));
} else {
sender.sendMessage(text("You are not holding an item!"));
}
}
}));
}
protected abstract @NonNull CommandManager<Commander> createCommandManager();
@Override
public final @NonNull CarbonEventHandler eventHandler() {
return this.eventHandler;
}
@Override
public final @NonNull CarbonEventHandler eventHandler() {
return this.eventHandler;
}
}
@@ -8,20 +8,20 @@ import java.util.Map;
// TODO: remove
public final class Injector {
private Injector() {
private Injector() {
}
}
private static final Map<Class<?>, Object> providers = new HashMap<>();
private static final Map<Class<?>, Object> providers = new HashMap<>();
@Deprecated(forRemoval = true)
public static <T, S extends T> S byInject(final @NonNull Class<T> clazz) {
return (S) providers.get(clazz);
}
@Deprecated(forRemoval = true)
public static <T, S extends T> S byInject(final @NonNull Class<T> clazz) {
return (S) providers.get(clazz);
}
@Deprecated(forRemoval = true)
public static <T> void provide(final @NonNull Class<T> clazz, final @NonNull T provider) {
providers.put(clazz, provider);
}
@Deprecated(forRemoval = true)
public static <T> void provide(final @NonNull Class<T> clazz, final @NonNull T provider) {
providers.put(clazz, provider);
}
}
@@ -0,0 +1,47 @@
package net.draycia.carbon.common.channels;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.ChatComponentRenderer;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import static net.kyori.adventure.text.Component.text;
import static net.kyori.adventure.text.Component.translatable;
@DefaultQualifier(NonNull.class)
public class VanillaChatChannel implements ChatChannel {
private final @NonNull ChatComponentRenderer renderer =
(sender, recipient, message, originalMessage) -> {
final var clickEvent = ClickEvent.suggestCommand("/msg " + sender.username());
final var hoverEvent = HoverEvent.showEntity(Key.key("player"),
sender.uuid(), text(sender.username()));
final var name = sender.displayName()
.clickEvent(clickEvent)
.hoverEvent(hoverEvent)
.insertion(sender.username());
return translatable("chat.type.text", name.color(TextColor.color(0xff0000)), message);
};
@Override
public boolean mayReceiveMessages(final CarbonPlayer player) {
return true;
}
@Override
public boolean maySendMessages(final CarbonPlayer player) {
return true;
}
@Override
public ChatComponentRenderer renderer() {
return this.renderer;
}
}
@@ -5,6 +5,6 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public interface PlayerCommander extends Commander {
@NonNull CarbonPlayer carbonPlayer();
@NonNull CarbonPlayer carbonPlayer();
}
@@ -1,59 +1,75 @@
package net.draycia.carbon.common.users;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.channels.VanillaChatChannel;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.UUID;
import static java.util.Objects.requireNonNullElseGet;
import static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class)
public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single {
protected final @NonNull String username;
protected @NonNull Component displayName;
protected final @NonNull UUID uuid;
protected final @NonNull Identity identity;
protected final String username;
protected Component displayName;
protected final UUID uuid;
protected final Identity identity;
protected ChatChannel selectedChannel;
protected CarbonPlayerCommon(
final @NonNull String username,
final @NonNull Component displayName,
final @NonNull UUID uuid,
final @NonNull Identity identity
) {
this.username = username;
this.displayName = displayName;
this.uuid = uuid;
this.identity = identity;
}
protected CarbonPlayerCommon(
final String username,
final Component displayName,
final UUID uuid,
final Identity identity
) {
this.username = username;
this.displayName = displayName;
this.uuid = uuid;
this.identity = identity;
this.selectedChannel = new VanillaChatChannel(); // TODO: replace, persist and use global instance
}
@Override
public @NonNull String username() {
return this.username;
}
@Override
public String username() {
return this.username;
}
@Override
public @NonNull Component displayName() {
return this.displayName;
}
@Override
public Component displayName() {
return this.displayName;
}
@Override
public void displayName(final @Nullable Component displayName) {
this.displayName = requireNonNullElseGet(displayName, () -> text(this.username));
}
@Override
public void displayName(final @Nullable Component displayName) {
this.displayName = requireNonNullElseGet(displayName, () -> text(this.username));
}
@Override
public @NonNull Identity identity() {
return this.identity;
}
@Override
public Identity identity() {
return this.identity;
}
@Override
public @NonNull UUID uuid() {
return this.uuid;
}
@Override
public UUID uuid() {
return this.uuid;
}
@Override
public ChatChannel selectedChannel() {
return this.selectedChannel;
}
@Override
public void selectedChannel(final ChatChannel chatChannel) {
this.selectedChannel = chatChannel;
}
}
@@ -23,56 +23,56 @@ import org.spongepowered.plugin.jvm.Plugin;
@Plugin("carbonchat")
public final class CarbonChatSponge extends CarbonChatCommon {
private static final int BSTATS_PLUGIN_ID = 11279;
private static final int BSTATS_PLUGIN_ID = 11279;
private final PluginContainer pluginContainer;
private final Logger logger;
private final PluginContainer pluginContainer;
private final Logger logger;
private final @NonNull UserManager userManager = new MemoryUserManagerSponge();
private final @NonNull UserManager userManager = new MemoryUserManagerSponge();
@Inject
public CarbonChatSponge(
//final Metrics.@NonNull Factory metricsFactory,
final @NonNull PluginContainer pluginContainer,
final @NonNull Logger logger
) {
this.pluginContainer = pluginContainer;
this.logger = logger;
@Inject
public CarbonChatSponge(
//final Metrics.@NonNull Factory metricsFactory,
final @NonNull PluginContainer pluginContainer,
final @NonNull Logger logger
) {
this.pluginContainer = pluginContainer;
this.logger = logger;
Injector.provide(CarbonChat.class, this);
Injector.provide(CarbonChat.class, this);
Sponge.eventManager().registerListeners(pluginContainer, new SpongeChatListener());
Sponge.eventManager().registerListeners(pluginContainer, new SpongeChatListener());
this.initialize();
this.initialize();
//metricsFactory.make(BSTATS_PLUGIN_ID);
}
//metricsFactory.make(BSTATS_PLUGIN_ID);
}
@Override
public @NonNull Logger logger() {
return this.logger;
}
@Override
public @NonNull Logger logger() {
return this.logger;
}
@Override
public @NonNull UserManager userManager() {
return this.userManager;
}
@Override
public @NonNull UserManager userManager() {
return this.userManager;
}
@Override
protected @NonNull CommandManager<Commander> createCommandManager() {
final SpongeCommandManager<Commander> commandManager = new SpongeCommandManager<>(
this.pluginContainer,
AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(),
commander -> ((SpongeCommander) commander).commandCause(),
commandCause -> {
if (commandCause.subject() instanceof ServerPlayer player) {
return new SpongePlayerCommander(this, player, commandCause);
}
return SpongeCommander.from(commandCause);
}
);
commandManager.parserMapper().cloudNumberSuggestions(true);
return commandManager;
}
@Override
protected @NonNull CommandManager<Commander> createCommandManager() {
final SpongeCommandManager<Commander> commandManager = new SpongeCommandManager<>(
this.pluginContainer,
AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(),
commander -> ((SpongeCommander) commander).commandCause(),
commandCause -> {
if (commandCause.subject() instanceof ServerPlayer player) {
return new SpongePlayerCommander(this, player, commandCause);
}
return SpongeCommander.from(commandCause);
}
);
commandManager.parserMapper().cloudNumberSuggestions(true);
return commandManager;
}
}
@@ -8,30 +8,30 @@ import org.spongepowered.api.command.CommandCause;
public interface SpongeCommander extends Commander, ForwardingAudience.Single {
@NonNull CommandCause commandCause();
@NonNull CommandCause commandCause();
static @NonNull SpongeCommander from(final @NonNull CommandCause commandCause) {
return new SpongeCommanderImpl(commandCause);
}
final class SpongeCommanderImpl implements SpongeCommander {
private final CommandCause commandCause;
private SpongeCommanderImpl(final @NonNull CommandCause commandCause) {
this.commandCause = commandCause;
static @NonNull SpongeCommander from(final @NonNull CommandCause commandCause) {
return new SpongeCommanderImpl(commandCause);
}
@Override
public @NonNull CommandCause commandCause() {
return this.commandCause;
}
final class SpongeCommanderImpl implements SpongeCommander {
@Override
public @NonNull Audience audience() {
return this.commandCause.audience();
}
private final CommandCause commandCause;
}
private SpongeCommanderImpl(final @NonNull CommandCause commandCause) {
this.commandCause = commandCause;
}
@Override
public @NonNull CommandCause commandCause() {
return this.commandCause;
}
@Override
public @NonNull Audience audience() {
return this.commandCause.audience();
}
}
}
@@ -11,19 +11,19 @@ import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import static java.util.Objects.requireNonNull;
public record SpongePlayerCommander(
@NonNull CarbonChat carbon,
@NonNull ServerPlayer player,
@NonNull CommandCause commandCause
@NonNull CarbonChat carbon,
@NonNull ServerPlayer player,
@NonNull CommandCause commandCause
) implements PlayerCommander, SpongeCommander {
@Override
public @NonNull CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.userManager().carbonPlayer(this.player.uniqueId()), "No CarbonPlayer for logged in Player!");
}
@Override
public @NonNull CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.userManager().carbonPlayer(this.player.uniqueId()), "No CarbonPlayer for logged in Player!");
}
@Override
public @NonNull Audience audience() {
return this.commandCause.audience();
}
@Override
public @NonNull Audience audience() {
return this.commandCause.audience();
}
}
@@ -2,9 +2,9 @@ package net.draycia.carbon.sponge.listeners;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.sponge.CarbonChatSponge;
import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.Player;
@@ -21,53 +21,58 @@ import static net.kyori.adventure.key.Key.key;
public final class SpongeChatListener {
private final CarbonChatSponge carbonChat = byInject(CarbonChat.class); // lol this is dumb
private final UserManager userManager = this.carbonChat.userManager();
private final CarbonChatSponge carbonChat = byInject(CarbonChat.class); // lol this is dumb
private final UserManager userManager = this.carbonChat.userManager();
@Listener
public void onPlayerChat(final @NonNull PlayerChatEvent event, final @First Player sender) {
// https://github.com/SpongePowered/SpongeAPI/pull/2340
// this event currently doesn't have a concept of recipients, it seems?
// or they're in the stack?
// idk, let's just do our own thing in the meantime
event.setCancelled(true);
@Listener
public void onPlayerChat(final @NonNull PlayerChatEvent event, final @First Player messageSender) {
// https://github.com/SpongePowered/SpongeAPI/pull/2340
// this event currently doesn't have a concept of recipients, it seems?
// or they're in the stack?
// idk, let's just do our own thing in the meantime
event.setCancelled(true);
final var player = this.userManager.carbonPlayer(sender.uniqueId());
final var sender = this.userManager.carbonPlayer(messageSender.uniqueId());
if (player == null) {
return;
}
final var recipients = new ArrayList<CarbonPlayer>();
for (final ServerPlayer recipient : Sponge.server().onlinePlayers()) {
final var bukkitRecipient = this.userManager.carbonPlayer(recipient.uniqueId());
if (bukkitRecipient != null) {
recipients.add(bukkitRecipient);
}
}
final var chatEvent = new CarbonChatEvent(player, event.message(), recipients,
Map.of(key("carbon", "default"), this.carbonChat.vanillaChatRenderer));
final var result = this.carbonChat.eventHandler().emit(chatEvent);
if (result.wasSuccessful()) {
// TODO: send to channels
for (final var recipient : chatEvent.recipients()) {
var component = chatEvent.message();
for (final var entry : chatEvent.renderers().entrySet()) {
component = entry.getValue().render(player,
recipient, chatEvent.message(), chatEvent.originalMessage());
if (sender == null) {
return;
}
if (component != null) {
recipient.sendMessage(component);
final var recipients = new ArrayList<Audience>();
final var channel = sender.selectedChannel();
for (final ServerPlayer spongeRecipient : Sponge.server().onlinePlayers()) {
final var recipient = this.userManager.carbonPlayer(spongeRecipient.uniqueId());
if (recipient != null && channel.mayReceiveMessages(recipient)) {
recipients.add(recipient);
}
}
// console too!
// i'm not 100% sure this is "console" but I literally cannot find anything that explicitly says console
recipients.add(Sponge.systemSubject());
final var chatEvent = new CarbonChatEvent(sender, event.message(), recipients,
Map.of(key("carbon", "default"), channel.renderer()));
final var result = this.carbonChat.eventHandler().emit(chatEvent);
if (result.wasSuccessful()) {
// TODO: send to channels
for (final var recipient : chatEvent.recipients()) {
var component = chatEvent.message();
for (final var entry : chatEvent.renderers().entrySet()) {
component = entry.getValue().render(sender,
recipient, chatEvent.message(), chatEvent.originalMessage());
}
if (component != null) {
recipient.sendMessage(component);
}
}
}
}
}
}
}
@@ -17,67 +17,67 @@ import java.util.UUID;
public final class CarbonPlayerSponge extends CarbonPlayerCommon {
public CarbonPlayerSponge(
final @NonNull String username,
final @NonNull Component displayName,
final @NonNull UUID uuid
) {
super(username, displayName, uuid, Identity.identity(uuid));
}
@Override
public void displayName(final @Nullable Component displayName) {
super.displayName(displayName);
this.player().ifPresent(player -> {
if (displayName != null) {
player.offer(Keys.CUSTOM_NAME, displayName);
} else {
player.remove(Keys.CUSTOM_NAME);
}
});
}
@Override
public @NonNull Audience audience() {
return this.player()
.map(player -> (Audience) player)
.orElseGet(Audience::empty);
}
private @NonNull Optional<ServerPlayer> player() {
return Sponge.server().player(this.uuid);
}
@Override
public @NonNull Component createItemHoverComponent() {
final ServerPlayer player = this.player().orElse(null);
if (player == null) {
return Component.empty();
public CarbonPlayerSponge(
final @NonNull String username,
final @NonNull Component displayName,
final @NonNull UUID uuid
) {
super(username, displayName, uuid, Identity.identity(uuid));
}
final ItemStack itemStack;
@Override
public void displayName(final @Nullable Component displayName) {
super.displayName(displayName);
final ItemStack mainHand = player.itemInHand(HandTypes.MAIN_HAND);
if (!mainHand.isEmpty()) {
itemStack = mainHand;
} else {
final ItemStack offHand = player.itemInHand(HandTypes.OFF_HAND);
if (!offHand.isEmpty()) {
itemStack = offHand;
} else {
itemStack = null;
}
this.player().ifPresent(player -> {
if (displayName != null) {
player.offer(Keys.CUSTOM_NAME, displayName);
} else {
player.remove(Keys.CUSTOM_NAME);
}
});
}
if (itemStack == null || itemStack.isEmpty()) {
return Component.empty();
@Override
public @NonNull Audience audience() {
return this.player()
.map(player -> (Audience) player)
.orElseGet(Audience::empty);
}
return itemStack.get(Keys.DISPLAY_NAME)
.orElse(itemStack.type().asComponent());
}
private @NonNull Optional<ServerPlayer> player() {
return Sponge.server().player(this.uuid);
}
@Override
public @NonNull Component createItemHoverComponent() {
final ServerPlayer player = this.player().orElse(null);
if (player == null) {
return Component.empty();
}
final ItemStack itemStack;
final ItemStack mainHand = player.itemInHand(HandTypes.MAIN_HAND);
if (!mainHand.isEmpty()) {
itemStack = mainHand;
} else {
final ItemStack offHand = player.itemInHand(HandTypes.OFF_HAND);
if (!offHand.isEmpty()) {
itemStack = offHand;
} else {
itemStack = null;
}
}
if (itemStack == null || itemStack.isEmpty()) {
return Component.empty();
}
return itemStack.get(Keys.DISPLAY_NAME)
.orElse(itemStack.type().asComponent());
}
}
@@ -21,42 +21,42 @@ import static net.kyori.adventure.text.Component.text;
*/
public final class MemoryUserManagerSponge implements UserManager {
private final @NonNull Map<UUID, @NonNull CarbonPlayer> users = new HashMap<>();
private final @NonNull Map<UUID, @NonNull CarbonPlayer> users = new HashMap<>();
@Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) {
if (this.users.containsKey(uuid)) {
return this.users.get(uuid);
@Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) {
if (this.users.containsKey(uuid)) {
return this.users.get(uuid);
}
final Optional<ServerPlayer> player = Sponge.server().player(uuid);
if (player.isEmpty()) {
return null;
}
final CarbonPlayer carbonPlayer = new CarbonPlayerSponge(player.get().name(),
text(player.get().name()), player.get().uniqueId());
this.users.put(uuid, carbonPlayer);
return carbonPlayer;
}
final Optional<ServerPlayer> player = Sponge.server().player(uuid);
@Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull String username) {
final Optional<ServerPlayer> player = Sponge.server().player(username);
if (player.isEmpty()) {
return null;
if (player.isEmpty()) {
return null;
}
if (this.users.containsKey(player.get().uniqueId())) {
return this.users.get(player.get().uniqueId());
}
return new CarbonPlayerSponge(player.get().name(), text(player.get().name()),
player.get().uniqueId());
}
final CarbonPlayer carbonPlayer = new CarbonPlayerSponge(player.get().name(),
text(player.get().name()), player.get().uniqueId());
this.users.put(uuid, carbonPlayer);
return carbonPlayer;
}
@Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull String username) {
final Optional<ServerPlayer> player = Sponge.server().player(username);
if (player.isEmpty()) {
return null;
}
if (this.users.containsKey(player.get().uniqueId())) {
return this.users.get(player.get().uniqueId());
}
return new CarbonPlayerSponge(player.get().name(), text(player.get().name()),
player.get().uniqueId());
}
}