Skip to content

Commit

Permalink
Translatable text component support
Browse files Browse the repository at this point in the history
  • Loading branch information
rfresh2 committed Aug 18, 2023
1 parent 784431b commit d838c9e
Show file tree
Hide file tree
Showing 12 changed files with 80 additions and 16 deletions.
7 changes: 7 additions & 0 deletions src/main/java/com/zenith/Shared.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.zenith.database.DatabaseManager;
import com.zenith.discord.DiscordBot;
import com.zenith.event.SimpleEventBus;
import com.zenith.feature.language.LanguageManager;
import com.zenith.feature.pathing.Pathing;
import com.zenith.feature.pathing.World;
import com.zenith.feature.pathing.blockdata.BlockDataManager;
Expand Down Expand Up @@ -44,6 +45,8 @@
import com.zenith.terminal.TerminalManager;
import com.zenith.util.Config;
import com.zenith.util.LaunchConfig;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;
import net.daporkchop.lib.minecraft.text.util.TranslationSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -95,6 +98,8 @@ public static boolean isReconnectableDisconnect(final String reason) {
public static final Pathing PATHING;
public static final TerminalManager TERMINAL_MANAGER;
public static final CommandManager COMMAND_MANAGER;
public static final LanguageManager LANGUAGE_MANAGER;
public static final AutoMCFormatParser FORMAT_PARSER;
public static final HandlerRegistry<ClientSession> CLIENT_HANDLERS = new HandlerRegistry.Builder<ClientSession>()
.setLogger(CLIENT_LOG)
.allowUnhandled(true)
Expand Down Expand Up @@ -318,6 +323,8 @@ public static synchronized void saveLaunchConfig() {
PATHING = new Pathing(WORLD);
TERMINAL_MANAGER = new TerminalManager();
COMMAND_MANAGER = new CommandManager();
LANGUAGE_MANAGER = new LanguageManager();
FORMAT_PARSER = new AutoMCFormatParser(TranslationSource.ofMap(LANGUAGE_MANAGER.getLanguageDataMap()));
} catch (final Throwable e) {
DEFAULT_LOG.error("Unable to initialize!", e);
throw e;
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/com/zenith/feature/language/LanguageManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.zenith.feature.language;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Collections;
import java.util.Map;

public class LanguageManager {
private final ObjectMapper objectMapper;
private Map<String, String> languageDataMap = Collections.emptyMap();

public LanguageManager() {
this.objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
init();
}

private void init() {
try {
this.languageDataMap = objectMapper.readValue(
getClass().getResourceAsStream("/pc/1.12/language.json"),
new TypeReference<Map<String, String>>() {});
} catch (final Exception e) {
throw new RuntimeException(e);
}
}

public Map<String, String> getLanguageDataMap() {
return this.languageDataMap;
}
}
3 changes: 1 addition & 2 deletions src/main/java/com/zenith/network/client/ClientListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;

import static com.zenith.Shared.*;
import static java.util.Objects.isNull;
Expand Down Expand Up @@ -93,7 +92,7 @@ public void disconnected(DisconnectedEvent event) {
session.setDisconnected(true);
String reason;
try {
reason = AutoMCFormatParser.DEFAULT.parse(event.getReason()).toRawString();
reason = FORMAT_PARSER.parse(event.getReason()).toRawString();
} catch (final Exception e) {
CLIENT_LOG.warn("Unable to parse disconnect reason: {}", event.getReason(), e);
reason = isNull(event.getReason()) ? "Disconnected" : event.getReason();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import com.zenith.util.Color;
import lombok.NonNull;
import net.daporkchop.lib.minecraft.text.component.MCTextRoot;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;

import java.time.Duration;
import java.time.Instant;
Expand All @@ -29,7 +28,7 @@ public class ChatHandler implements AsyncIncomingHandler<ServerChatPacket, Clien
public boolean applyAsync(@NonNull ServerChatPacket packet, @NonNull ClientSession session) {
try {
CHAT_LOG.info(packet.getMessage().replace("\\n\\n", "")); // removes the chat clearing linebreaks from queue messages
final MCTextRoot mcTextRoot = AutoMCFormatParser.DEFAULT.parse(packet.getMessage());
final MCTextRoot mcTextRoot = FORMAT_PARSER.parse(packet.getMessage());
final String messageString = mcTextRoot.toRawString();
/*
* example death message:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import lombok.NonNull;
import net.daporkchop.lib.logging.format.component.TextComponent;
import net.daporkchop.lib.minecraft.text.component.MCTextRoot;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;

import java.util.Arrays;
import java.util.List;
Expand Down Expand Up @@ -112,7 +111,7 @@ private synchronized void parse2bPing(final ServerPlayerListDataPacket packet, C

private Optional<MCTextRoot> parse2b2tTablistFooter(final String footer) {
try {
return Optional.of(AutoMCFormatParser.DEFAULT.parse(footer));
return Optional.of(FORMAT_PARSER.parse(footer));
} catch (final Exception e) {
CLIENT_LOG.debug("Error parsing 2b2t tablist footer", e);
return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@
import com.zenith.event.proxy.QueuePositionUpdateEvent;
import com.zenith.network.client.ClientSession;
import com.zenith.network.registry.AsyncIncomingHandler;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;

import java.util.Optional;

import static com.zenith.Shared.CLIENT_LOG;
import static com.zenith.Shared.EVENT_BUS;
import static com.zenith.Shared.*;

public class TitlePacketHandler implements AsyncIncomingHandler<ServerTitlePacket, ClientSession> {
@Override
Expand All @@ -29,7 +27,7 @@ private void parse2bQueuePos(ServerTitlePacket serverTitlePacket, final ClientSe
Optional<Integer> position = Optional.of(serverTitlePacket)
.filter(packet -> packet.getAction().equals(TitleAction.SUBTITLE))
.map(ServerTitlePacket::getSubtitle)
.map(title -> AutoMCFormatParser.DEFAULT.parse(title).toRawString())
.map(title -> FORMAT_PARSER.parse(title).toRawString())
.map(text -> {
String[] split = text.split(":");
if (split.length > 1) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;

import javax.crypto.SecretKey;
import java.io.IOException;
Expand Down Expand Up @@ -148,7 +147,7 @@ public void disconnected(DisconnectedEvent event) {
return;
}
if (this.isPlayer) {
final String reason = AutoMCFormatParser.DEFAULT.parse(event.getReason()).toRawString();
final String reason = FORMAT_PARSER.parse(event.getReason()).toRawString();
if (!isSpectator()) {
SERVER_LOG.info("Player disconnected: UUID: {}, Username: {}, Address: {}, Reason {}",
Optional.ofNullable(this.profileCache.getProfile()).map(GameProfile::getId).orElse(null),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.zenith.network.server.ServerConnection;
import com.zenith.util.Color;
import net.daporkchop.lib.minecraft.text.component.MCTextRoot;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;

import static com.zenith.Shared.*;
import static java.util.Objects.nonNull;
Expand All @@ -14,7 +13,7 @@ public class ServerChatOutgoingHandler implements OutgoingHandler<ServerChatPack
@Override
public ServerChatPacket apply(ServerChatPacket packet, ServerConnection session) {
try {
final MCTextRoot mcTextRoot = AutoMCFormatParser.DEFAULT.parse(packet.getMessage());
final MCTextRoot mcTextRoot = FORMAT_PARSER.parse(packet.getMessage());
final String message = mcTextRoot.toRawString();
if (message.startsWith("<")) {
if (CONFIG.client.extra.chat.hideChat) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,26 @@

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.zenith.Shared;
import lombok.NonNull;
import net.daporkchop.lib.logging.console.ansi.VGAColor;
import net.daporkchop.lib.logging.format.FormatParser;
import net.daporkchop.lib.logging.format.TextStyle;
import net.daporkchop.lib.logging.format.component.TextComponent;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;

import java.util.function.Supplier;

import static net.daporkchop.lib.logging.console.ansi.ANSI.ESC;

/**
* All the ANSI formatting stuff is taken from PorkLib:
* https://github.com/PorkStudios/PorkLib/blob/development/logging/src/main/java/net/daporkchop/lib/logging/console/ansi/
*/
public class MCTextFormatANSIConverter extends MessageConverter {
private final FormatParser formatParser = AutoMCFormatParser.DEFAULT;
private final FormatParser defaultFormatParser = AutoMCFormatParser.DEFAULT;
// need to lazily init this to get around static init order
private final Supplier<FormatParser> translatableFormatParser = () -> Shared.FORMAT_PARSER;

protected static String getUpdateTextFormatCommand(VGAColor textColor, VGAColor backgroundColor, int style) {
return String.format(
Expand Down Expand Up @@ -57,6 +62,8 @@ protected static CharSequence getStyleStuff(int style) {

@Override
public String convert(ILoggingEvent event) {
FormatParser formatParser = translatableFormatParser.get();
if (formatParser == null) formatParser = defaultFormatParser;
TextComponent textComponent = formatParser.parse(event.getFormattedMessage());
StringBuilder builder = new StringBuilder();
this.doBuild(builder, textComponent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.zenith.Shared;
import com.zenith.util.ImageInfo;
import net.daporkchop.lib.logging.format.FormatParser;
import net.daporkchop.lib.logging.format.component.TextComponent;
import net.daporkchop.lib.minecraft.text.parser.AutoMCFormatParser;

import java.util.function.Supplier;

public class MCTextFormatConverter extends MessageConverter {
private final FormatParser formatParser = AutoMCFormatParser.DEFAULT;
private final FormatParser defaultFormatParser = AutoMCFormatParser.DEFAULT;
// need to lazily init this to get around static init order
private final Supplier<FormatParser> translatableFormatParser = () -> Shared.FORMAT_PARSER;

@Override
public String convert(ILoggingEvent event) {
Expand All @@ -17,6 +22,8 @@ public String convert(ILoggingEvent event) {
try {
// if the message doesn't start with a curly brace it ain't json
if (formattedMessage.startsWith("{") || formattedMessage.contains("§")) {
FormatParser formatParser = translatableFormatParser.get();
if (formatParser == null) formatParser = defaultFormatParser;
TextComponent textComponent = formatParser.parse(formattedMessage);
return textComponent.toRawString();
}
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/META-INF/native-image/resource-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@
"pattern":"\\Qpc/1.12/blocks.json\\E"
}, {
"pattern":"\\Qpc/1.12/foods.json\\E"
}, {
"pattern":"\\Qpc/1.12/language.json\\E"
}, {
"pattern":"\\Qproxy_commit.txt\\E"
}, {
Expand Down
15 changes: 15 additions & 0 deletions src/test/java/com/zenith/TranslatableTextParserTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.zenith;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class TranslatableTextParserTest {

@Test
public void translatableTextComponentParseTest() {
final String chatText = "{\"translate\":\"chat.type.text\",\"with\":[{\"text\":\"bonk2b2t\"},{\"text\":\"you should never talk about that with them\"}]}";
final String rawString = Shared.FORMAT_PARSER.parse(chatText).toRawString();
assertEquals(rawString, "<bonk2b2t> you should never talk about that with them");
}
}

0 comments on commit d838c9e

Please sign in to comment.