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 --> <!-- https://checkstyle.org/config_misc.html#Indentation -->
<module name="Indentation"> <module name="Indentation">
<property name="arrayInitIndent" value="2"/> <property name="arrayInitIndent" value="4"/>
<property name="basicOffset" value="2"/> <property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/> <property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="2"/> <property name="caseIndent" value="4"/>
<property name="lineWrappingIndentation" value="0"/> <property name="lineWrappingIndentation" value="0"/>
<property name="throwsIndent" value="2"/> <property name="throwsIndent" value="4"/>
</module> </module>
<!-- https://checkstyle.org/config_javadoc.html#InvalidJavadocPosition --> <!-- https://checkstyle.org/config_javadoc.html#InvalidJavadocPosition -->
+1 -1
View File
@@ -24,7 +24,7 @@ root = true
[*] [*]
charset = utf-8 charset = utf-8
indent_size = 2 indent_size = 4
indent_style = space indent_style = space
insert_final_newline = true insert_final_newline = true
max_line_length = off max_line_length = off
@@ -5,6 +5,7 @@ import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.api.users.UserManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
/** /**
* The main plugin interface.<br> * The main plugin interface.<br>
@@ -12,34 +13,32 @@ import org.checkerframework.checker.nullness.qual.NonNull;
* *
* @since 1.0.0 * @since 1.0.0
*/ */
@DefaultQualifier(NonNull.class)
public interface CarbonChat { public interface CarbonChat {
/** /**
* The plugin's logger.<br> * The plugin's logger.<br>
* All messages will be logged through this. * All messages will be logged through this.
* *
* @return the plugin's logger * @return the plugin's logger
* * @since 2.0.0
* @since 2.0.0 */
*/ Logger logger();
@NonNull Logger logger();
/** /**
* The event handler, used for listening to and emitting events. * The event handler, used for listening to and emitting events.
* *
* @return the event handler * @return the event handler
* * @since 2.0.0
* @since 2.0.0 */
*/ CarbonEventHandler eventHandler();
@NonNull CarbonEventHandler eventHandler();
/** /**
* The user manager, used for loading and obtaining {@link CarbonPlayer CarbonPlayers}. * The user manager, used for loading and obtaining {@link CarbonPlayer CarbonPlayers}.
* *
* @return the user manager * @return the user manager
* * @since 2.0.0
* @since 2.0.0 */
*/ UserManager userManager();
@NonNull UserManager userManager();
} }
@@ -2,44 +2,44 @@ package net.draycia.carbon.api;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
/** /**
* Static accessor for the {@link CarbonChat} class. * Static accessor for the {@link CarbonChat} class.
* *
* @since 1.0.0 * @since 1.0.0
*/ */
@DefaultQualifier(NonNull.class)
public final class CarbonChatProvider { 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.key.Key;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -15,107 +16,101 @@ import java.util.Map;
* *
* @since 2.0.0 * @since 2.0.0
*/ */
@DefaultQualifier(NonNull.class)
public class CarbonChatEvent extends CancellableCarbonEvent { 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. * {@link CancellableCarbonEvent} that's called when players send messages in chat.
* *
* @param sender the sender of the message * @param sender the sender of the message
* @param originalMessage the original message that was sent * @param originalMessage the original message that was sent
* @param recipients the recipients of the message * @param recipients the recipients of the message
* @param renderers the renderers of the message * @param renderers the renderers of the message
* * @since 2.0.0
* @since 2.0.0 */
*/ public CarbonChatEvent(
public CarbonChatEvent( final CarbonPlayer sender,
final @NonNull CarbonPlayer sender, final Component originalMessage,
final @NonNull Component originalMessage, final List<? extends Audience> recipients,
final @NonNull List<@NonNull ? extends Audience> recipients, final Map<Key, ChatComponentRenderer> renderers
final @NonNull Map<Key, ChatComponentRenderer> renderers ) {
) { this.sender = sender;
this.sender = sender; this.originalMessage = originalMessage;
this.originalMessage = originalMessage; this.message = originalMessage;
this.message = originalMessage; this.recipients = recipients;
this.recipients = recipients; this.renderers = renderers;
this.renderers = renderers; }
}
/** /**
* Get the renderers used to construct components for each of the recipients. * Get the renderers used to construct components for each of the recipients.
* *
* @return The per-recipient component renderers. * @return The per-recipient component renderers.
* * @since 2.0.0
* @since 2.0.0 */
*/ public Map<Key, ChatComponentRenderer> renderers() {
public @NonNull Map<Key, ChatComponentRenderer> renderers() { return this.renderers;
return this.renderers; }
}
/** /**
* Get the sender of the message. * Get the sender of the message.
* *
* @return The message sender. * @return The message sender.
* * @since 2.0.0
* @since 2.0.0 */
*/ public CarbonPlayer sender() {
public CarbonPlayer sender() { return this.sender;
return this.sender; }
}
/** /**
* Get the original message that was sent. * Get the original message that was sent.
* *
* @return The original message. * @return The original message.
* * @since 2.0.0
* @since 2.0.0 */
*/ public Component originalMessage() {
public Component originalMessage() { return this.originalMessage;
return this.originalMessage; }
}
/** /**
* Get the chat message that will be sent. * Get the chat message that will be sent.
* *
* @return The chat message. * @return The chat message.
* * @since 2.0.0
* @since 2.0.0 */
*/ public Component message() {
public Component message() { return this.message;
return this.message; }
}
/** /**
* Set the chat message that will be sent. * Set the chat message that will be sent.
* *
* @param message new message * @param message new message
* * @since 2.0.0
* @since 2.0.0 */
*/ public void message(final Component message) {
public void message(final @NonNull Component message) { this.message = message;
this.message = message; }
}
/** /**
* The recipients of the message. * The recipients of the message.
* List is mutable and elements may be added/removed. * List is mutable and elements may be added/removed.
* *
* @return the recipients of the message. * @return the recipients of the message.
* entries may be players, console, or other audience implementations * entries may be players, console, or other audience implementations
* * @since 2.0.0
* @since 2.0.0 */
*/ public List<? extends Audience> recipients() {
public @NonNull List<@NonNull ? extends Audience> recipients() { return this.recipients;
return this.recipients; }
}
} }
@@ -4,6 +4,7 @@ import net.kyori.event.EventSubscriber;
import net.kyori.event.PostResult; import net.kyori.event.PostResult;
import net.kyori.event.SimpleEventBus; import net.kyori.event.SimpleEventBus;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -12,84 +13,83 @@ import java.util.function.Consumer;
* *
* @since 1.0.0 * @since 1.0.0
*/ */
@DefaultQualifier(NonNull.class)
public final class CarbonEventHandler { 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. * Registers a subscriber for the given event class.
* *
* @param eventClass the class to listen for * @param eventClass the class to listen for
* @param subscriber the subscriber that's executed when the event is emitted * @param subscriber the subscriber that's executed when the event is emitted
* @param <T> the class to listen for * @param <T> the class to listen for
* * @since 1.0.0
* @since 1.0.0 */
*/ public <T extends CarbonEvent> void register(final Class<T> eventClass, final EventSubscriber<T> subscriber) {
public <T extends CarbonEvent> void register(final @NonNull Class<T> eventClass, final @NonNull EventSubscriber<T> subscriber) { this.eventBus.register(eventClass, subscriber);
this.eventBus.register(eventClass, subscriber); }
}
/** /**
* Registers a subscriber for the given event class.<br> * Registers a subscriber for the given event class.<br>
* Includes extra values to control when the consumer is executed. * Includes extra values to control when the consumer is executed.
* *
* @param eventClass the class to listen for * @param eventClass the class to listen for
* @param priority the priority of the consumer * @param priority the priority of the consumer
* @param consumeCancelled if the consumer should be executed if the event is cancelled early * @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 consumer the consumer that's executed when the event is emitted
* @param <T> the class to listen for * @param <T> the class to listen for
* * @return the subscriber, so that it may be unregistered
* @return the subscriber, so that it may be unregistered * @since 2.0.0
* */
* @since 2.0.0 public <T extends CarbonEvent> EventSubscriber<T> register(
*/ final Class<T> eventClass, final int priority,
public <T extends CarbonEvent> EventSubscriber<T> register(final @NonNull Class<T> eventClass, final int priority, final boolean consumeCancelled, final @NonNull Consumer<T> consumer) { final boolean consumeCancelled,
final var subscriber = new EventSubscriber<T>() { final Consumer<T> consumer) {
@Override
public int postOrder() {
return priority;
}
@Override final var subscriber = new EventSubscriber<T>() {
public boolean consumeCancelledEvents() { @Override
return consumeCancelled; public int postOrder() {
} return priority;
}
@Override @Override
public void invoke(final @NonNull T event) { public boolean consumeCancelledEvents() {
consumer.accept(event); return consumeCancelled;
} }
};
this.eventBus.register(eventClass, subscriber); @Override
public void invoke(final T event) {
consumer.accept(event);
}
};
return subscriber; this.eventBus.register(eventClass, subscriber);
}
/** return 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);
}
/** /**
* Emits the supplied event and returns its result.<br> * Unregisters the subscriber and prevents it from being executed.
* Events are modified in place, so care should be taken to keep a reference to *
* the event while it's being emitted. * @param subscriber the subscriber
* * @since 1.0.0
* @param event the event to be emitted */
* public void unregister(final EventSubscriber<? super CarbonEvent> subscriber) {
* @return the result this.eventBus.unregister(subscriber);
* }
* @since 2.0.0
*/ /**
public PostResult emit(final @NonNull CarbonEvent event) { * Emits the supplied event and returns its result.<br>
return this.eventBus.post(event); * 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; package net.draycia.carbon.api.users;
import net.draycia.carbon.api.channels.ChatChannel;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identified; import net.kyori.adventure.identity.Identified;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.UUID; import java.util.UUID;
@@ -13,52 +15,64 @@ import java.util.UUID;
* *
* @since 2.0.0 * @since 2.0.0
*/ */
@DefaultQualifier(NonNull.class)
public interface CarbonPlayer extends Audience, Identified { public interface CarbonPlayer extends Audience, Identified {
/** /**
* Gets the player's username. * Gets the player's username.
* *
* @return the player's username * @return the player's username
* * @since 2.0.0
* @since 2.0.0 */
*/ String username();
@NonNull String username();
/** /**
* Gets the player's display name, shown in places like chat and tab menu. * Gets the player's display name, shown in places like chat and tab menu.
* *
* @return the player's display name * @return the player's display name
* * @since 2.0.0
* @since 2.0.0 */
*/ Component displayName();
@NonNull Component displayName();
/** /**
* Sets the player's display name.<br> * Sets the player's display name.<br>
* Setting null is equivalent to setting the display name to the username. * Setting null is equivalent to setting the display name to the username.
* *
* @param displayName the new display name * @param displayName the new display name
* * @since 2.0.0
* @since 2.0.0 */
*/ void displayName(final @Nullable Component displayName);
void displayName(final @Nullable Component displayName);
/** /**
* The player's UUID, often used for identification purposes. * The player's UUID, often used for identification purposes.
* *
* @return the player's UUID * @return the player's UUID
* * @since 2.0.0
* @since 2.0.0 */
*/ UUID uuid();
@NonNull UUID uuid();
/** /**
* Creates a {@link Component} with a content and item hover given the player's actively held item. * 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 * @return the player's held item as an item hover component
* * @since 2.0.0
* @since 2.0.0 */
*/ Component createItemHoverComponent();
@NonNull 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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.UUID; import java.util.UUID;
@@ -10,28 +11,25 @@ import java.util.UUID;
* *
* @since 2.0.0 * @since 2.0.0
*/ */
@DefaultQualifier(NonNull.class)
public interface UserManager { public interface UserManager {
/** /**
* Loads and returns a {@link CarbonPlayer} with the given {@link UUID}. * Loads and returns a {@link CarbonPlayer} with the given {@link UUID}.
* *
* @param uuid The player's UUID. * @param uuid The player's UUID.
* * @return The {@link CarbonPlayer}, or null if the player doesn't exist.
* @return The {@link CarbonPlayer}, or null if the player doesn't exist. * @since 2.0.0
* */
* @since 2.0.0 @Nullable CarbonPlayer carbonPlayer(final UUID uuid);
*/
@Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid);
/** /**
* Loads and returns a {@link CarbonPlayer} with the given username. * Loads and returns a {@link CarbonPlayer} with the given username.
* *
* @param username The player's username. * @param username The player's username.
* * @return The {@link CarbonPlayer}, or null if the player doesn't exist.
* @return The {@link CarbonPlayer}, or null if the player doesn't exist. * @since 2.0.0
* */
* @since 2.0.0 @Nullable CarbonPlayer carbonPlayer(final String username);
*/
@Nullable CarbonPlayer carbonPlayer(final @NonNull String username);
} }
@@ -5,6 +5,7 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
/** /**
* Renderer used to construct chat components on a per-player basis. * 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 * @since 2.0.0
*/ */
@FunctionalInterface @FunctionalInterface
@DefaultQualifier(NonNull.class)
public interface ChatComponentRenderer { public interface ChatComponentRenderer {
/** /**
* Renders a Component for the specified recipient. * Renders a Component for the specified recipient.
* *
* @param sender the player that sent the message * @param sender the player that sent the message
* @param recipient a recipient of the message. * @param recipient a recipient of the message.
* may be a player, console, or other Audience implementations * may be a player, console, or other Audience implementations
* @param message the message being sent * @param message the message being sent
* @param originalMessage the original message that was sent * @param originalMessage the original message that was sent
* * @return the component to be shown to the recipient,
* @return the component to be shown to the recipient, * or null if the recipient should not receive the message
* or null if the recipient should not receive the message * @since 2.0.0
* */
* @since 2.0.0 @Nullable
*/ Component render(final CarbonPlayer sender,
@Nullable final Audience recipient,
Component render(final @NonNull CarbonPlayer sender, final Component message,
final @NonNull Audience recipient, final Component originalMessage);
final @NonNull Component message,
final @NonNull Component originalMessage);
} }
@@ -7,6 +7,7 @@ import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyFormat; import net.kyori.adventure.text.serializer.legacy.LegacyFormat;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -15,95 +16,92 @@ import java.util.regex.Pattern;
* *
* @since 1.0.0 * @since 1.0.0
*/ */
@DefaultQualifier(NonNull.class)
public final class ColorUtils { 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)) { * Parses the input into a color.<br>
return namedColor; * Supports named colors, legacy, and hex inputs.
} *
} * @param input the color input
* @return the color
if (input.contains("&") || input.contains("§")) { * @since 1.0.0
input = input.replace("&", "§"); */
public static @Nullable TextColor parseColor(String input) {
return LegacyComponentSerializer.legacySection().deserialize(input).color(); if (input.isEmpty()) {
} return NamedTextColor.WHITE;
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() + ">");
} }
}
}
// Legacy Formatting for (final NamedTextColor namedColor : NamedTextColor.NAMES.values()) {
for (final char c : "klmnoKLMNO".toCharArray()) { if (namedColor.toString().equalsIgnoreCase(input)) {
final LegacyFormat format = LegacyComponentSerializer.parseChar(Character.toLowerCase(c)); return namedColor;
}
if (format != null) {
final TextDecoration decoration = format.decoration();
if (decoration != null) {
output = output.replaceAll("[§&]" + c, "<" + decoration.name() + ">");
} }
}
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 <K> the key type
* @param <V> the value type * @param <V> the value type
*
* @since 1.0.0 * @since 1.0.0
*/ */
public interface DefaultedKeyValueRegistry<K, V> extends DefaultedRegistryGetter<K, V> { public interface DefaultedKeyValueRegistry<K, V> extends DefaultedRegistryGetter<K, V> {
/** /**
* Gets the default value. * Gets the default value.
* *
* @return the default value * @return the default value
* * @since 1.0.0
* @since 1.0.0 */
*/ @NonNull V defaultValue();
@NonNull V defaultValue();
} }
@@ -18,51 +18,51 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public final class CarbonChatBukkit extends CarbonChatCommon { public final class CarbonChatBukkit extends CarbonChatCommon {
private final @NonNull UserManager userManager = new MemoryUserManagerBukkit(); private final @NonNull UserManager userManager = new MemoryUserManagerBukkit();
private final Logger logger = LogManager.getLogger("CarbonChat"); private final Logger logger = LogManager.getLogger("CarbonChat");
private final CarbonChatBukkitEntry plugin; private final CarbonChatBukkitEntry plugin;
CarbonChatBukkit(final @NonNull CarbonChatBukkitEntry plugin) { CarbonChatBukkit(final @NonNull CarbonChatBukkitEntry plugin) {
this.plugin = plugin; this.plugin = plugin;
Injector.provide(CarbonChat.class, this); 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);
} }
commandManager.registerAsynchronousCompletions();
commandManager.registerBrigadier(); @Override
final var brigadierManager = commandManager.brigadierManager(); public @NonNull Logger logger() {
if (brigadierManager != null) { return this.logger;
brigadierManager.setNativeNumberSuggestions(false); }
@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 { 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 @Override
public void onEnable() { public void onEnable() {
if (!PaperLib.isPaper()) { if (!PaperLib.isPaper()) {
this.getLogger().log(Level.SEVERE, "*"); this.getLogger().log(Level.SEVERE, "*");
this.getLogger().log(Level.SEVERE, "* CarbonChat makes extensive use of APIs added by Paper."); 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, "* 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, "* Upgrade your server to Paper in order to use CarbonChat.");
this.getLogger().log(Level.SEVERE, "*"); this.getLogger().log(Level.SEVERE, "*");
PaperLib.suggestPaper(this, Level.SEVERE); PaperLib.suggestPaper(this, Level.SEVERE);
Bukkit.getPluginManager().disablePlugin(this); Bukkit.getPluginManager().disablePlugin(this);
return; 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); @Override
public void onDisable() {
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID); }
Bukkit.getPluginManager().registerEvents(new BukkitChatListener(), this);
this.carbon.initialize();
}
@Override
public void onDisable() {
}
} }
@@ -8,29 +8,29 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public interface BukkitCommander extends Commander, ForwardingAudience.Single { public interface BukkitCommander extends Commander, ForwardingAudience.Single {
@NonNull CommandSender commandSender(); @NonNull CommandSender commandSender();
static @NonNull BukkitCommander from(final @NonNull CommandSender sender) { static @NonNull BukkitCommander from(final @NonNull CommandSender sender) {
return new BukkitCommanderImpl(sender); return new BukkitCommanderImpl(sender);
}
final class BukkitCommanderImpl implements BukkitCommander {
private final CommandSender commandSender;
private BukkitCommanderImpl(final @NonNull CommandSender commandSender) {
this.commandSender = commandSender;
} }
public @NonNull CommandSender commandSender() { final class BukkitCommanderImpl implements BukkitCommander {
return this.commandSender;
}
@Override private final CommandSender commandSender;
public @NonNull Audience audience() {
return this.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; import static java.util.Objects.requireNonNull;
public record BukkitPlayerCommander( public record BukkitPlayerCommander(
@NonNull CarbonChat carbon, @NonNull CarbonChat carbon,
@NonNull Player player @NonNull Player player
) implements PlayerCommander, BukkitCommander { ) implements PlayerCommander, BukkitCommander {
@Override @Override
public @NonNull CommandSender commandSender() { public @NonNull CommandSender commandSender() {
return this.player; return this.player;
} }
@Override @Override
public @NonNull Audience audience() { public @NonNull Audience audience() {
return this.player; return this.player;
} }
@Override @Override
public @NonNull CarbonPlayer carbonPlayer() { public @NonNull CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.userManager().carbonPlayer(this.player.getUniqueId()), "No CarbonPlayer for logged in Player!"); 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 io.papermc.paper.event.player.AsyncChatEvent;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; 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.api.users.UserManager;
import net.draycia.carbon.bukkit.CarbonChatBukkit; import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.kyori.adventure.audience.Audience;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
@@ -19,51 +20,57 @@ import static net.kyori.adventure.key.Key.key;
public final class BukkitChatListener implements Listener { public final class BukkitChatListener implements Listener {
private final CarbonChatBukkit carbonChat = byInject(CarbonChat.class); // lol this is dumb private final CarbonChatBukkit carbonChat = byInject(CarbonChat.class); // lol this is dumb
private final UserManager userManager = this.carbonChat.userManager(); private final UserManager userManager = this.carbonChat.userManager();
@EventHandler @EventHandler
public void onPlayerChat(final @NonNull AsyncChatEvent event) { public void onPlayerChat(final @NonNull AsyncChatEvent event) {
final var player = this.userManager.carbonPlayer(event.getPlayer().getUniqueId()); final var sender = this.userManager.carbonPlayer(event.getPlayer().getUniqueId());
if (player == null) { if (sender == null) {
return; 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 (component != null) { final var recipients = new ArrayList<Audience>();
recipient.sendMessage(component); final var channel = sender.selectedChannel();
}
}
}
// There's no guarantee that recipients is mutable. for (final Player bukkitRecipient : event.recipients()) {
// If it's ever immutable, we yell at who ever is responsible. final var recipient = this.userManager.carbonPlayer(bukkitRecipient.getUniqueId());
event.recipients().clear();
} // 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 final class CarbonPlayerBukkit extends CarbonPlayerCommon {
public CarbonPlayerBukkit( public CarbonPlayerBukkit(
final @NonNull String username, final @NonNull String username,
final @NonNull Component displayName, final @NonNull Component displayName,
final @NonNull UUID uuid final @NonNull UUID uuid
) { ) {
super(username, displayName, uuid, Identity.identity(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();
} }
return player; @Override
} public void displayName(final @Nullable Component displayName) {
super.displayName(displayName);
private @Nullable Player player() { final Player player = this.player();
return Bukkit.getPlayer(this.uuid);
}
@Override if (player != null) {
public @NonNull Component createItemHoverComponent() { player.displayName(displayName);
final Player player = this.player(); // This is temporary (it's not) player.playerListName(displayName);
}
if (player == null) {
return Component.empty();
} }
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()) { return player;
itemStack = mainHand;
} else {
final ItemStack offHand = player.getInventory().getItemInMainHand();
if (!offHand.getType().isAir()) {
itemStack = offHand;
} else {
itemStack = null;
}
} }
if (itemStack == null) { private @Nullable Player player() {
return Component.empty(); return Bukkit.getPlayer(this.uuid);
} }
if (itemStack.getType().isAir()) { @Override
return Component.empty(); 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 { 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 @Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) { public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) {
if (this.users.containsKey(uuid)) { if (this.users.containsKey(uuid)) {
return this.users.get(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) { if (player == null) {
return 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 { public final class PlaceholderAPIMiniMessageParser {
private final MiniMessage miniMessage; private final MiniMessage miniMessage;
private PlaceholderAPIMiniMessageParser(final @NonNull MiniMessage miniMessage) { private PlaceholderAPIMiniMessageParser(final @NonNull MiniMessage miniMessage) {
this.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 + ">");
}
} }
matcher.appendTail(builder);
return this.miniMessage.parse(builder.toString(), templates);
}
public static @NonNull PlaceholderAPIMiniMessageParser create(final @NonNull MiniMessage backingInstance) { public @NonNull Component parse(final @NonNull OfflinePlayer player, final @NonNull String input, final @NonNull Collection<Template> templates) {
return new PlaceholderAPIMiniMessageParser(backingInstance); return this.parse(
} PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(player, match),
private static boolean containsLegacyColorCodes(final @NonNull String string) { input,
final char[] charArray = string.toCharArray(); templates
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) {
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 cloud.commandframework.CommandManager;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonEventHandler; 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.Commander;
import net.draycia.carbon.common.command.PlayerCommander; import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent; 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 org.checkerframework.checker.nullness.qual.NonNull;
import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text; 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.NamedTextColor.DARK_GRAY;
import static net.kyori.adventure.text.format.TextDecoration.BOLD; import static net.kyori.adventure.text.format.TextDecoration.BOLD;
public abstract class CarbonChatCommon implements CarbonChat { public abstract class CarbonChatCommon implements CarbonChat {
// Mimics vanilla chat, should be *visually* identical but without the hover stuff. private final CarbonEventHandler eventHandler = new CarbonEventHandler();
// 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()));
final var name = sender.displayName() public final void initialize() {
.clickEvent(clickEvent) final CommandManager<Commander> commandManager = this.createCommandManager();
.hoverEvent(hoverEvent) commandManager.command(commandManager.commandBuilder("carbon")
.insertion(sender.username()); .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(); @Override
public final @NonNull CarbonEventHandler eventHandler() {
public final void initialize() { return this.eventHandler;
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;
}
} }
@@ -8,20 +8,20 @@ import java.util.Map;
// TODO: remove // TODO: remove
public final class Injector { 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) @Deprecated(forRemoval = true)
public static <T, S extends T> S byInject(final @NonNull Class<T> clazz) { public static <T, S extends T> S byInject(final @NonNull Class<T> clazz) {
return (S) providers.get(clazz); return (S) providers.get(clazz);
} }
@Deprecated(forRemoval = true) @Deprecated(forRemoval = true)
public static <T> void provide(final @NonNull Class<T> clazz, final @NonNull T provider) { public static <T> void provide(final @NonNull Class<T> clazz, final @NonNull T provider) {
providers.put(clazz, 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 { public interface PlayerCommander extends Commander {
@NonNull CarbonPlayer carbonPlayer(); @NonNull CarbonPlayer carbonPlayer();
} }
@@ -1,59 +1,75 @@
package net.draycia.carbon.common.users; package net.draycia.carbon.common.users;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.channels.VanillaChatChannel;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity; import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import java.util.UUID; import java.util.UUID;
import static java.util.Objects.requireNonNullElseGet; import static java.util.Objects.requireNonNullElseGet;
import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class)
public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single { public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single {
protected final @NonNull String username; protected final String username;
protected @NonNull Component displayName; protected Component displayName;
protected final @NonNull UUID uuid; protected final UUID uuid;
protected final @NonNull Identity identity; protected final Identity identity;
protected ChatChannel selectedChannel;
protected CarbonPlayerCommon( protected CarbonPlayerCommon(
final @NonNull String username, final String username,
final @NonNull Component displayName, final Component displayName,
final @NonNull UUID uuid, final UUID uuid,
final @NonNull Identity identity final Identity identity
) { ) {
this.username = username; this.username = username;
this.displayName = displayName; this.displayName = displayName;
this.uuid = uuid; this.uuid = uuid;
this.identity = identity; this.identity = identity;
} this.selectedChannel = new VanillaChatChannel(); // TODO: replace, persist and use global instance
}
@Override @Override
public @NonNull String username() { public String username() {
return this.username; return this.username;
} }
@Override @Override
public @NonNull Component displayName() { public Component displayName() {
return this.displayName; return this.displayName;
} }
@Override @Override
public void displayName(final @Nullable Component displayName) { public void displayName(final @Nullable Component displayName) {
this.displayName = requireNonNullElseGet(displayName, () -> text(this.username)); this.displayName = requireNonNullElseGet(displayName, () -> text(this.username));
} }
@Override @Override
public @NonNull Identity identity() { public Identity identity() {
return this.identity; return this.identity;
} }
@Override @Override
public @NonNull UUID uuid() { public UUID uuid() {
return this.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") @Plugin("carbonchat")
public final class CarbonChatSponge extends CarbonChatCommon { 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 PluginContainer pluginContainer;
private final Logger logger; private final Logger logger;
private final @NonNull UserManager userManager = new MemoryUserManagerSponge(); private final @NonNull UserManager userManager = new MemoryUserManagerSponge();
@Inject @Inject
public CarbonChatSponge( public CarbonChatSponge(
//final Metrics.@NonNull Factory metricsFactory, //final Metrics.@NonNull Factory metricsFactory,
final @NonNull PluginContainer pluginContainer, final @NonNull PluginContainer pluginContainer,
final @NonNull Logger logger final @NonNull Logger logger
) { ) {
this.pluginContainer = pluginContainer; this.pluginContainer = pluginContainer;
this.logger = logger; 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 @Override
public @NonNull Logger logger() { public @NonNull Logger logger() {
return this.logger; return this.logger;
} }
@Override @Override
public @NonNull UserManager userManager() { public @NonNull UserManager userManager() {
return this.userManager; return this.userManager;
} }
@Override @Override
protected @NonNull CommandManager<Commander> createCommandManager() { protected @NonNull CommandManager<Commander> createCommandManager() {
final SpongeCommandManager<Commander> commandManager = new SpongeCommandManager<>( final SpongeCommandManager<Commander> commandManager = new SpongeCommandManager<>(
this.pluginContainer, this.pluginContainer,
AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(), AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(),
commander -> ((SpongeCommander) commander).commandCause(), commander -> ((SpongeCommander) commander).commandCause(),
commandCause -> { commandCause -> {
if (commandCause.subject() instanceof ServerPlayer player) { if (commandCause.subject() instanceof ServerPlayer player) {
return new SpongePlayerCommander(this, player, commandCause); return new SpongePlayerCommander(this, player, commandCause);
} }
return SpongeCommander.from(commandCause); return SpongeCommander.from(commandCause);
} }
); );
commandManager.parserMapper().cloudNumberSuggestions(true); commandManager.parserMapper().cloudNumberSuggestions(true);
return commandManager; return commandManager;
} }
} }
@@ -8,30 +8,30 @@ import org.spongepowered.api.command.CommandCause;
public interface SpongeCommander extends Commander, ForwardingAudience.Single { public interface SpongeCommander extends Commander, ForwardingAudience.Single {
@NonNull CommandCause commandCause(); @NonNull CommandCause commandCause();
static @NonNull SpongeCommander from(final @NonNull CommandCause commandCause) { static @NonNull SpongeCommander from(final @NonNull CommandCause commandCause) {
return new SpongeCommanderImpl(commandCause); return new SpongeCommanderImpl(commandCause);
}
final class SpongeCommanderImpl implements SpongeCommander {
private final CommandCause commandCause;
private SpongeCommanderImpl(final @NonNull CommandCause commandCause) {
this.commandCause = commandCause;
} }
@Override final class SpongeCommanderImpl implements SpongeCommander {
public @NonNull CommandCause commandCause() {
return this.commandCause;
}
@Override private final CommandCause commandCause;
public @NonNull Audience audience() {
return this.commandCause.audience();
}
} 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; import static java.util.Objects.requireNonNull;
public record SpongePlayerCommander( public record SpongePlayerCommander(
@NonNull CarbonChat carbon, @NonNull CarbonChat carbon,
@NonNull ServerPlayer player, @NonNull ServerPlayer player,
@NonNull CommandCause commandCause @NonNull CommandCause commandCause
) implements PlayerCommander, SpongeCommander { ) implements PlayerCommander, SpongeCommander {
@Override @Override
public @NonNull CarbonPlayer carbonPlayer() { public @NonNull CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.userManager().carbonPlayer(this.player.uniqueId()), "No CarbonPlayer for logged in Player!"); return requireNonNull(this.carbon.userManager().carbonPlayer(this.player.uniqueId()), "No CarbonPlayer for logged in Player!");
} }
@Override @Override
public @NonNull Audience audience() { public @NonNull Audience audience() {
return this.commandCause.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.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; 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.api.users.UserManager;
import net.draycia.carbon.sponge.CarbonChatSponge; import net.draycia.carbon.sponge.CarbonChatSponge;
import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.api.Sponge; import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.Player;
@@ -21,53 +21,58 @@ import static net.kyori.adventure.key.Key.key;
public final class SpongeChatListener { public final class SpongeChatListener {
private final CarbonChatSponge carbonChat = byInject(CarbonChat.class); // lol this is dumb private final CarbonChatSponge carbonChat = byInject(CarbonChat.class); // lol this is dumb
private final UserManager userManager = this.carbonChat.userManager(); private final UserManager userManager = this.carbonChat.userManager();
@Listener @Listener
public void onPlayerChat(final @NonNull PlayerChatEvent event, final @First Player sender) { public void onPlayerChat(final @NonNull PlayerChatEvent event, final @First Player messageSender) {
// https://github.com/SpongePowered/SpongeAPI/pull/2340 // https://github.com/SpongePowered/SpongeAPI/pull/2340
// this event currently doesn't have a concept of recipients, it seems? // this event currently doesn't have a concept of recipients, it seems?
// or they're in the stack? // or they're in the stack?
// idk, let's just do our own thing in the meantime // idk, let's just do our own thing in the meantime
event.setCancelled(true); event.setCancelled(true);
final var player = this.userManager.carbonPlayer(sender.uniqueId()); final var sender = this.userManager.carbonPlayer(messageSender.uniqueId());
if (player == null) { if (sender == null) {
return; 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 (component != null) { final var recipients = new ArrayList<Audience>();
recipient.sendMessage(component); 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 final class CarbonPlayerSponge extends CarbonPlayerCommon {
public CarbonPlayerSponge( public CarbonPlayerSponge(
final @NonNull String username, final @NonNull String username,
final @NonNull Component displayName, final @NonNull Component displayName,
final @NonNull UUID uuid final @NonNull UUID uuid
) { ) {
super(username, displayName, uuid, Identity.identity(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();
} }
final ItemStack itemStack; @Override
public void displayName(final @Nullable Component displayName) {
super.displayName(displayName);
final ItemStack mainHand = player.itemInHand(HandTypes.MAIN_HAND); this.player().ifPresent(player -> {
if (displayName != null) {
if (!mainHand.isEmpty()) { player.offer(Keys.CUSTOM_NAME, displayName);
itemStack = mainHand; } else {
} else { player.remove(Keys.CUSTOM_NAME);
final ItemStack offHand = player.itemInHand(HandTypes.OFF_HAND); }
});
if (!offHand.isEmpty()) {
itemStack = offHand;
} else {
itemStack = null;
}
} }
if (itemStack == null || itemStack.isEmpty()) { @Override
return Component.empty(); public @NonNull Audience audience() {
return this.player()
.map(player -> (Audience) player)
.orElseGet(Audience::empty);
} }
return itemStack.get(Keys.DISPLAY_NAME) private @NonNull Optional<ServerPlayer> player() {
.orElse(itemStack.type().asComponent()); 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 { 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 @Override
public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) { public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) {
if (this.users.containsKey(uuid)) { if (this.users.containsKey(uuid)) {
return this.users.get(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()) { if (player.isEmpty()) {
return null; 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());
}
} }