| 1 | package net.minecraft.commands.arguments;
|
| 2 |
|
| 3 | import com.mojang.brigadier.StringReader;
|
| 4 | import com.mojang.brigadier.arguments.ArgumentType;
|
| 5 | import com.mojang.brigadier.context.CommandContext;
|
| 6 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 7 | import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
| 8 | import com.mojang.brigadier.suggestion.Suggestions;
|
| 9 | import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
| 10 | import java.util.Arrays;
|
| 11 | import java.util.Collection;
|
| 12 | import java.util.concurrent.CompletableFuture;
|
| 13 | import net.minecraft.commands.CommandSourceStack;
|
| 14 | import net.minecraft.commands.SharedSuggestionProvider;
|
| 15 | import net.minecraft.network.chat.Component;
|
| 16 | import net.minecraft.util.ARGB;
|
| 17 |
|
| 18 | public class HexColorArgument implements ArgumentType<Integer> {
|
| 19 | private static final Collection<String> EXAMPLES = Arrays.asList("F00", "FF0000");
|
| 20 | public static final DynamicCommandExceptionType ERROR_INVALID_HEX = new DynamicCommandExceptionType(
|
| 21 | value -> Component.translatableEscape("argument.hexcolor.invalid", value)
|
| 22 | );
|
| 23 |
|
| 24 | private HexColorArgument() {
|
| 25 | }
|
| 26 |
|
| 27 | public static HexColorArgument hexColor() {
|
| 28 | return new HexColorArgument();
|
| 29 | }
|
| 30 |
|
| 31 | public static Integer getHexColor(final CommandContext<CommandSourceStack> context, final String name) {
|
| 32 | return context.getArgument(name, Integer.class);
|
| 33 | }
|
| 34 |
|
| 35 | public Integer parse(final StringReader reader) throws CommandSyntaxException {
|
| 36 | String colorString = reader.readUnquotedString();
|
| 37 |
|
| 38 | return switch (colorString.length()) {
|
| 39 | case 3 -> ARGB.color(
|
| 40 | duplicateDigit(Integer.parseInt(colorString, 0, 1, 16)),
|
| 41 | duplicateDigit(Integer.parseInt(colorString, 1, 2, 16)),
|
| 42 | duplicateDigit(Integer.parseInt(colorString, 2, 3, 16))
|
| 43 | );
|
| 44 | case 6 -> ARGB.color(Integer.parseInt(colorString, 0, 2, 16), Integer.parseInt(colorString, 2, 4, 16), Integer.parseInt(colorString, 4, 6, 16));
|
| 45 | default -> throw ERROR_INVALID_HEX.createWithContext(reader, colorString);
|
| 46 | };
|
| 47 | }
|
| 48 |
|
| 49 | private static int duplicateDigit(final int digit) {
|
| 50 | return digit * 17;
|
| 51 | }
|
| 52 |
|
| 53 | @Override
|
| 54 | public <S> CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> contextBuilder, final SuggestionsBuilder builder) {
|
| 55 | return SharedSuggestionProvider.suggest(EXAMPLES, builder);
|
| 56 | }
|
| 57 |
|
| 58 | @Override
|
| 59 | public Collection<String> getExamples() {
|
| 60 | return EXAMPLES;
|
| 61 | }
|
| 62 | }
|
| 63 |
|