| 1 | package net.minecraft.network.chat.contents;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableList;
|
| 4 | import com.google.common.collect.ImmutableList.Builder;
|
| 5 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 6 | import com.mojang.datafixers.util.Either;
|
| 7 | import com.mojang.serialization.Codec;
|
| 8 | import com.mojang.serialization.DataResult;
|
| 9 | import com.mojang.serialization.MapCodec;
|
| 10 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 11 | import java.util.Arrays;
|
| 12 | import java.util.List;
|
| 13 | import java.util.Objects;
|
| 14 | import java.util.Optional;
|
| 15 | import java.util.function.Consumer;
|
| 16 | import java.util.regex.Matcher;
|
| 17 | import java.util.regex.Pattern;
|
| 18 | import net.minecraft.locale.Language;
|
| 19 | import net.minecraft.network.chat.Component;
|
| 20 | import net.minecraft.network.chat.ComponentContents;
|
| 21 | import net.minecraft.network.chat.ComponentSerialization;
|
| 22 | import net.minecraft.network.chat.ComponentUtils;
|
| 23 | import net.minecraft.network.chat.FormattedText;
|
| 24 | import net.minecraft.network.chat.MutableComponent;
|
| 25 | import net.minecraft.network.chat.ResolutionContext;
|
| 26 | import net.minecraft.network.chat.Style;
|
| 27 | import net.minecraft.util.ExtraCodecs;
|
| 28 | import org.jspecify.annotations.Nullable;
|
| 29 |
|
| 30 | /**
|
| 31 | * Access widened by fabric-transitive-access-wideners-v1 to accessible
|
| 32 | */
|
| 33 | public class TranslatableContents implements ComponentContents {
|
| 34 | public static final Object[] NO_ARGS = new Object[0];
|
| 35 | private static final Codec<Object> PRIMITIVE_ARG_CODEC = ExtraCodecs.JAVA.validate(TranslatableContents::filterAllowedArguments);
|
| 36 | private static final Codec<Object> ARG_CODEC = Codec.either(PRIMITIVE_ARG_CODEC, ComponentSerialization.CODEC)
|
| 37 | .xmap(
|
| 38 | e -> e.map(o -> o, component -> Objects.requireNonNullElse(component.tryCollapseToString(), component)),
|
| 39 | o -> o instanceof Component c ? Either.right(c) : Either.left(o)
|
| 40 | );
|
| 41 | public static final MapCodec<TranslatableContents> MAP_CODEC = RecordCodecBuilder.mapCodec(
|
| 42 | i -> i.group(
|
| 43 | Codec.STRING.fieldOf("translate").forGetter(o -> o.key),
|
| 44 | Codec.STRING.lenientOptionalFieldOf("fallback").forGetter(o -> Optional.ofNullable(o.fallback)),
|
| 45 | ARG_CODEC.listOf().optionalFieldOf("with").forGetter(o -> adjustArgs(o.args))
|
| 46 | )
|
| 47 | .apply(i, TranslatableContents::create)
|
| 48 | );
|
| 49 | private static final FormattedText TEXT_PERCENT = FormattedText.of("%");
|
| 50 | private static final FormattedText TEXT_NULL = FormattedText.of("null");
|
| 51 | private final String key;
|
| 52 | private final @Nullable String fallback;
|
| 53 | private final Object[] args;
|
| 54 | private @Nullable Language decomposedWith;
|
| 55 | private List<FormattedText> decomposedParts = ImmutableList.of();
|
| 56 | private static final Pattern FORMAT_PATTERN = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)");
|
| 57 |
|
| 58 | private static DataResult<Object> filterAllowedArguments(final @Nullable Object result) {
|
| 59 | return !isAllowedPrimitiveArgument(result) ? DataResult.error(() -> "This value needs to be parsed as component") : DataResult.success(result);
|
| 60 | }
|
| 61 |
|
| 62 | public static boolean isAllowedPrimitiveArgument(final @Nullable Object object) {
|
| 63 | return object instanceof Number || object instanceof Boolean || object instanceof String;
|
| 64 | }
|
| 65 |
|
| 66 | private static Optional<List<Object>> adjustArgs(final Object[] args) {
|
| 67 | return args.length == 0 ? Optional.empty() : Optional.of(Arrays.asList(args));
|
| 68 | }
|
| 69 |
|
| 70 | private static Object[] adjustArgs(final Optional<List<Object>> args) {
|
| 71 | return args.<Object[]>map(a -> a.isEmpty() ? NO_ARGS : a.toArray()).orElse(NO_ARGS);
|
| 72 | }
|
| 73 |
|
| 74 | private static TranslatableContents create(final String key, final Optional<String> fallback, final Optional<List<Object>> args) {
|
| 75 | return new TranslatableContents(key, fallback.orElse(null), adjustArgs(args));
|
| 76 | }
|
| 77 |
|
| 78 | public TranslatableContents(final String key, final @Nullable String fallback, final Object[] args) {
|
| 79 | this.key = key;
|
| 80 | this.fallback = fallback;
|
| 81 | this.args = args;
|
| 82 | }
|
| 83 |
|
| 84 | @Override
|
| 85 | public MapCodec<TranslatableContents> codec() {
|
| 86 | return MAP_CODEC;
|
| 87 | }
|
| 88 |
|
| 89 | private void decompose() {
|
| 90 | Language currentLanguage = Language.getInstance();
|
| 91 | if (currentLanguage != this.decomposedWith) {
|
| 92 | this.decomposedWith = currentLanguage;
|
| 93 | String format = this.fallback != null ? currentLanguage.getOrDefault(this.key, this.fallback) : currentLanguage.getOrDefault(this.key);
|
| 94 |
|
| 95 | try {
|
| 96 | Builder<FormattedText> parts = ImmutableList.builder();
|
| 97 | this.decomposeTemplate(format, parts::add);
|
| 98 | this.decomposedParts = parts.build();
|
| 99 | } catch (TranslatableFormatException e) {
|
| 100 | this.decomposedParts = ImmutableList.of(FormattedText.of(format));
|
| 101 | }
|
| 102 | }
|
| 103 | }
|
| 104 |
|
| 105 | private void decomposeTemplate(final String template, final Consumer<FormattedText> decomposedParts) {
|
| 106 | Matcher matcher = FORMAT_PATTERN.matcher(template);
|
| 107 |
|
| 108 | try {
|
| 109 | int replacementIndex = 0;
|
| 110 | int current = 0;
|
| 111 |
|
| 112 | while (matcher.find(current)) {
|
| 113 | int start = matcher.start();
|
| 114 | int end = matcher.end();
|
| 115 | if (start > current) {
|
| 116 | String prefix = template.substring(current, start);
|
| 117 | if (prefix.indexOf(37) != -1) {
|
| 118 | throw new IllegalArgumentException();
|
| 119 | }
|
| 120 |
|
| 121 | decomposedParts.accept(FormattedText.of(prefix));
|
| 122 | }
|
| 123 |
|
| 124 | String formatType = matcher.group(2);
|
| 125 | String formatString = template.substring(start, end);
|
| 126 | if ("%".equals(formatType) && "%%".equals(formatString)) {
|
| 127 | decomposedParts.accept(TEXT_PERCENT);
|
| 128 | } else {
|
| 129 | if (!"s".equals(formatType)) {
|
| 130 | throw new TranslatableFormatException(this, "Unsupported format: '" + formatString + "'");
|
| 131 | }
|
| 132 |
|
| 133 | String possiblePositionIndex = matcher.group(1);
|
| 134 | int index = possiblePositionIndex != null ? Integer.parseInt(possiblePositionIndex) - 1 : replacementIndex++;
|
| 135 | decomposedParts.accept(this.getArgument(index));
|
| 136 | }
|
| 137 |
|
| 138 | current = end;
|
| 139 | }
|
| 140 |
|
| 141 | if (current < template.length()) {
|
| 142 | String tail = template.substring(current);
|
| 143 | if (tail.indexOf(37) != -1) {
|
| 144 | throw new IllegalArgumentException();
|
| 145 | }
|
| 146 |
|
| 147 | decomposedParts.accept(FormattedText.of(tail));
|
| 148 | }
|
| 149 | } catch (IllegalArgumentException e) {
|
| 150 | throw new TranslatableFormatException(this, e);
|
| 151 | }
|
| 152 | }
|
| 153 |
|
| 154 | /**
|
| 155 | * Access widened by fabric-transitive-access-wideners-v1 to accessible
|
| 156 | */
|
| 157 | public final FormattedText getArgument(final int index) {
|
| 158 | if (index >= 0 && index < this.args.length) {
|
| 159 | Object arg = this.args[index];
|
| 160 | if (arg instanceof Component componentArg) {
|
| 161 | return componentArg;
|
| 162 | } else {
|
| 163 | return arg == null ? TEXT_NULL : FormattedText.of(arg.toString());
|
| 164 | }
|
| 165 | } else {
|
| 166 | throw new TranslatableFormatException(this, index);
|
| 167 | }
|
| 168 | }
|
| 169 |
|
| 170 | @Override
|
| 171 | public <T> Optional<T> visit(final FormattedText.StyledContentConsumer<T> output, final Style currentStyle) {
|
| 172 | this.decompose();
|
| 173 |
|
| 174 | for (FormattedText part : this.decomposedParts) {
|
| 175 | Optional<T> result = part.visit(output, currentStyle);
|
| 176 | if (result.isPresent()) {
|
| 177 | return result;
|
| 178 | }
|
| 179 | }
|
| 180 |
|
| 181 | return Optional.empty();
|
| 182 | }
|
| 183 |
|
| 184 | @Override
|
| 185 | public <T> Optional<T> visit(final FormattedText.ContentConsumer<T> output) {
|
| 186 | this.decompose();
|
| 187 |
|
| 188 | for (FormattedText part : this.decomposedParts) {
|
| 189 | Optional<T> result = part.visit(output);
|
| 190 | if (result.isPresent()) {
|
| 191 | return result;
|
| 192 | }
|
| 193 | }
|
| 194 |
|
| 195 | return Optional.empty();
|
| 196 | }
|
| 197 |
|
| 198 | @Override
|
| 199 | public MutableComponent resolve(final ResolutionContext context, final int recursionDepth) throws CommandSyntaxException {
|
| 200 | Object[] argsCopy = new Object[this.args.length];
|
| 201 |
|
| 202 | for (int i = 0; i < argsCopy.length; i++) {
|
| 203 | Object param = this.args[i];
|
| 204 | if (param instanceof Component component) {
|
| 205 | argsCopy[i] = ComponentUtils.resolve(context, component, recursionDepth);
|
| 206 | } else {
|
| 207 | argsCopy[i] = param;
|
| 208 | }
|
| 209 | }
|
| 210 |
|
| 211 | return MutableComponent.create(new TranslatableContents(this.key, this.fallback, argsCopy));
|
| 212 | }
|
| 213 |
|
| 214 | @Override
|
| 215 | public boolean equals(final Object o) {
|
| 216 | return this == o
|
| 217 | ? true
|
| 218 | : o instanceof TranslatableContents that
|
| 219 | && Objects.equals(this.key, that.key)
|
| 220 | && Objects.equals(this.fallback, that.fallback)
|
| 221 | && Arrays.equals(this.args, that.args);
|
| 222 | }
|
| 223 |
|
| 224 | @Override
|
| 225 | public int hashCode() {
|
| 226 | int result = Objects.hashCode(this.key);
|
| 227 | result = 31 * result + Objects.hashCode(this.fallback);
|
| 228 | return 31 * result + Arrays.hashCode(this.args);
|
| 229 | }
|
| 230 |
|
| 231 | @Override
|
| 232 | public String toString() {
|
| 233 | return "translation{key='"
|
| 234 | + this.key
|
| 235 | + "'"
|
| 236 | + (this.fallback != null ? ", fallback='" + this.fallback + "'" : "")
|
| 237 | + ", args="
|
| 238 | + Arrays.toString(this.args)
|
| 239 | + "}";
|
| 240 | }
|
| 241 |
|
| 242 | public String getKey() {
|
| 243 | return this.key;
|
| 244 | }
|
| 245 |
|
| 246 | public @Nullable String getFallback() {
|
| 247 | return this.fallback;
|
| 248 | }
|
| 249 |
|
| 250 | public Object[] getArgs() {
|
| 251 | return this.args;
|
| 252 | }
|
| 253 | }
|
| 254 |
|