Search in sources :

Example 1 with ChatFormatting

use of net.minecraft.ChatFormatting in project SpongeCommon by SpongePowered.

the class SpongeColorValueParameter method parseValue.

@Override
@NonNull
public Optional<? extends Color> parseValue(@NonNull final CommandCause cause, final ArgumentReader.@NonNull Mutable reader) throws ArgumentParseException {
    final ArgumentReader.Immutable state = reader.immutable();
    // First, is the argument type giving the correct return type?
    try {
        final ChatFormatting formatting = this.colorArgumentType.parse((StringReader) reader);
        final Integer colorCode = ((ChatFormattingAccessor) (Object) formatting).accessor$color();
        if (colorCode != null) {
            return Optional.of(Color.ofRgb(colorCode));
        }
        // "reset" slips through the net here.
        throw reader.createException(Component.text().content(String.format("%s is not a valid color", formatting.getName())).build());
    } catch (final CommandSyntaxException e) {
    // ignored
    }
    reader.setState(state);
    // Hex codes and comma separated RGB values require commas, so we need to parse the string,
    // rather than use the unquoted string the ColorArgument does.
    final String string = reader.parseString();
    // Hex code (with optional #)
    final Matcher matcher = SpongeColorValueParameter.HEX_CODE.matcher(string);
    if (matcher.matches()) {
        try {
            return Optional.of(Color.ofRgb(Integer.parseInt(matcher.group("colorcode"), 16)));
        } catch (final NumberFormatException ex) {
        // handled below
        }
    }
    final String[] rgb = string.split(",", 3);
    if (rgb.length == 3) {
        final Optional<Color> result = this.checkIntConversion(rgb);
        if (result.isPresent()) {
            return result;
        }
    }
    throw reader.createException(SpongeColorValueParameter.EXCEPTION_MESSAGE);
}
Also used : Matcher(java.util.regex.Matcher) Color(org.spongepowered.api.util.Color) ChatFormattingAccessor(org.spongepowered.common.accessor.ChatFormattingAccessor) ChatFormatting(net.minecraft.ChatFormatting) ArgumentReader(org.spongepowered.api.command.parameter.ArgumentReader) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Aggregations

CommandSyntaxException (com.mojang.brigadier.exceptions.CommandSyntaxException)1 Matcher (java.util.regex.Matcher)1 ChatFormatting (net.minecraft.ChatFormatting)1 NonNull (org.checkerframework.checker.nullness.qual.NonNull)1 ArgumentReader (org.spongepowered.api.command.parameter.ArgumentReader)1 Color (org.spongepowered.api.util.Color)1 ChatFormattingAccessor (org.spongepowered.common.accessor.ChatFormattingAccessor)1