switch to CTxT

This commit is contained in:
Oth3r 2025-05-03 15:41:16 -05:00
commit c3b7bb02fd
6 changed files with 79 additions and 50 deletions

View file

@ -14,6 +14,7 @@ import one.oth3r.sit.utl.Data;
import one.oth3r.sit.utl.Logic;
import one.oth3r.sit.utl.Utl;
import java.awt.*;
import java.util.concurrent.CompletableFuture;
public class SitCommand {
@ -49,7 +50,7 @@ public class SitCommand {
if (player == null) {
if (args[0].equalsIgnoreCase("reload")) {
Logic.reload();
Data.LOGGER.info(Utl.lang("sit!.chat.reloaded").getString());
Data.LOGGER.info(Utl.lang("sit!.chat.reloaded").toString());
}
return 1;
}
@ -75,7 +76,7 @@ public class SitCommand {
if (args[0].equalsIgnoreCase("reload")) {
Logic.reload();
player.sendMessage(Utl.messageTag().append(Utl.lang("sit!.chat.reloaded").formatted(Formatting.GREEN)));
player.sendMessage(Utl.messageTag().append(Utl.lang("sit!.chat.reloaded").color(Color.GREEN)).b());
}
if (args[0].equalsIgnoreCase("purgeChairEntities")) Utl.Entity.purge(player,true);

View file

@ -4,6 +4,7 @@ import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import one.oth3r.otterlib.chat.CTxT;
import one.oth3r.sit.Sit;
import one.oth3r.sit.utl.Data;
@ -20,14 +21,19 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LangReader {
private static final Map<String, String> defaultLangMap = new HashMap<>();
private static final Map<String, String> languageMap = new HashMap<>();
private final String translationKey;
private final Object[] placeholders;
public LangReader(String translationKey, Object... placeholders) {
this.translationKey = translationKey;
this.placeholders = placeholders;
}
public MutableText getTxT() {
public CTxT getTxT() {
String translated = getLanguageValue(translationKey);
if (placeholders != null && placeholders.length > 0) {
//removed all double \\ and replaces with \
@ -35,7 +41,8 @@ public class LangReader {
String regex = "%\\d*\\$?[dfs]";
Matcher anyMatch = Pattern.compile(regex).matcher(translated);
Matcher endMatch = Pattern.compile(regex+"$").matcher(translated);
//Arraylist with all the %(#$)[dfs]
// Arraylist with all the %(#$)[dfs]
ArrayList<String> matches = new ArrayList<>();
while (anyMatch.find()) {
String match = anyMatch.group();
@ -51,7 +58,7 @@ public class LangReader {
}
//if there are placeholders specified, and the split is more than 1, it will replace %(dfs) with the placeholder objects
if (parts.length > 1) {
MutableText txt = Text.empty();
CTxT txt = new CTxT("");
int i = 0;
for (String match : matches) {
int get = i;
@ -62,47 +69,56 @@ public class LangReader {
}
if (parts.length != i) txt.append(parts[i]);
//convert the obj into txt
Object obj = placeholders[get];
if (obj instanceof Text) txt.append((Text) obj);
else txt.append(String.valueOf(obj));
txt.append(getTxTFromObj(placeholders[get]));
i++;
}
if (parts.length != i) txt.append(parts[i]);
return txt;
return new CTxT(txt);
}
}
return Text.empty().append(translated);
return new CTxT(translated);
}
private CTxT getTxTFromObj(Object obj) {
if (obj instanceof CTxT) return (((CTxT) obj));
else if (obj instanceof Text) return new CTxT((MutableText) obj);
else return new CTxT(String.valueOf(obj));
}
public static LangReader of(String translationKey, Object... placeholders) {
return new LangReader(translationKey, placeholders);
}
public static void loadLanguageFile() {
ClassLoader classLoader = Sit.class.getClassLoader();
Type tToken = new TypeToken<Map<String, String>>(){}.getType();
try {
InputStream inputStream = classLoader.getResourceAsStream("assets/sit-oth3r/lang/" + FileData.getServerConfig().getLang() +".json");
// if the input stream is null, the language file wasn't found
if (inputStream == null) {
// try loading the default language file
inputStream = classLoader.getResourceAsStream("assets/sit-oth3r/lang/" + new ServerConfig().getLang() +".json");
Data.LOGGER.error("COULDN'T LOAD THE LANGUAGE FILE. RESETTING TO en_us.");
}
// if the input stream is still null, throw an exception
if (inputStream == null) throw new IllegalArgumentException("UNABLE TO LOAD THE ENGLISH LANGUAGE FILE.");
Type type = new TypeToken<Map<String, String>>(){}.getType();
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
languageMap.putAll(new Gson().fromJson(reader, type));
// close the input stream
inputStream.close();
// load the config language
Reader selectionReader = new InputStreamReader(getInputStream(false), StandardCharsets.UTF_8);
languageMap.putAll(new Gson().fromJson(selectionReader, tToken));
// load the default language as well (fallback)
Reader defaultReader = new InputStreamReader(getInputStream(true), StandardCharsets.UTF_8);
defaultLangMap.putAll(new Gson().fromJson(defaultReader, tToken));
} catch (Exception e) {
Data.LOGGER.error(e.getMessage());
Data.LOGGER.info("ERROR WITH LANGUAGE FILE - PLEASE REPORT WITH THE ERROR LOG");
Data.LOGGER.info(e.getMessage());
}
}
private static InputStream getInputStream(boolean english) {
ClassLoader classLoader = Sit.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("assets/sit-oth3r/lang/"+FileData.getServerConfig().getLang()+".json");
// make null if english
if (english) inputStream = null;
// if it cant read (null), try again, but with the english file
if (inputStream == null) inputStream = classLoader.getResourceAsStream("assets/sit-oth3r/lang/"+new ServerConfig().getLang()+".json");
// if null after that, throw an exception
if (inputStream == null) throw new IllegalArgumentException("CANT LOAD THE LANGUAGE FILE. SIT! WILL BREAK.");
return inputStream;
}
public static String getLanguageValue(String key) {
return languageMap.getOrDefault(key, key);
return languageMap.getOrDefault(key, defaultLangMap.getOrDefault(key, key));
}
}

View file

@ -14,6 +14,8 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.awt.*;
@Mixin(ReloadCommand.class)
public class ReloadCommandMixin {
@Inject(at = @At("TAIL"), method = "register")
@ -27,7 +29,7 @@ public class ReloadCommandMixin {
// send a reloaded message to all players with permissions
for (ServerPlayerEntity player : server.getPlayerManager().getPlayerList()) {
if (player.isCreativeLevelTwoOp()) {
player.sendMessage(Utl.messageTag().append(Utl.lang("sit!.chat.reloaded").formatted(Formatting.GREEN)));
player.sendMessage(Utl.messageTag().append(Utl.lang("sit!.chat.reloaded").color(Color.GREEN)).b());
}
}
}

View file

@ -29,6 +29,8 @@ import one.oth3r.sit.packet.SitPayloads;
import one.oth3r.sit.screen.ConfigScreen;
import org.lwjgl.glfw.GLFW;
import java.awt.*;
public class Events {
private static class Keybindings {
@ -78,7 +80,7 @@ public class Events {
} else {
// unsupported server message if not in a Sit! server
player.sendMessage(Utl.lang("sit!.chat.unsupported")
.formatted(Formatting.RED), true);
.color(Color.RED).b(), true);
}
}
}
@ -103,7 +105,7 @@ public class Events {
ServerPlayNetworking.send(context.player(),new SitPayloads.ResponsePayload(SitPayloads.ResponsePayload.VERSION));
// log the receiving of the packet from the player
Data.LOGGER.info(Utl.lang("sit!.console.player_settings",context.player().getName().getString()).getString());
Data.LOGGER.info(Utl.lang("sit!.console.player_settings",context.player().getName().getString()).toString());
})));
}
@ -113,7 +115,7 @@ public class Events {
// only update when needed
if (!Data.isSupportedServer()) {
Data.setSupportedServer(true);
Data.LOGGER.info(Utl.lang("sit!.console.connected",payload.value()).getString());
Data.LOGGER.info(Utl.lang("sit!.console.connected",payload.value()).toString());
}
}));
}

View file

@ -11,6 +11,8 @@ import net.minecraft.util.math.BlockPos;
import one.oth3r.sit.file.*;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
public class Logic {
/**
@ -226,11 +228,11 @@ public class Logic {
// send the player the actionbar message
return Utl.lang("sit!.chat.toggle_sit",
Utl.lang(messageKey).formatted(messageColor));
Utl.lang(messageKey).color(config.getEnabled()? Color.GREEN : Color.RED)).b();
} else {
// unsupported server message if not in a Sit! server
return Utl.lang("sit!.chat.unsupported")
.formatted(Formatting.RED);
.color(Color.RED).b();
}
}

View file

@ -18,9 +18,7 @@ import net.minecraft.item.consume.UseAction;
import net.minecraft.registry.Registries;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.text.TextColor;
import net.minecraft.util.*;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.HitResult;
@ -28,11 +26,13 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.RaycastContext;
import net.minecraft.world.World;
import one.oth3r.otterlib.chat.CTxT;
import one.oth3r.sit.file.*;
import one.oth3r.sit.packet.SitPayloads;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@ -320,26 +320,32 @@ public class Utl {
// send a message if needed
if (message) {
player.sendMessage(messageTag().append(Utl.lang("sit!.chat.purged",Utl.lang("sit!.chat.purged.total",count).styled(
style -> style.withColor(Colors.LIGHT_GRAY).withItalic(true)
)).styled(
style -> style.withColor(Colors.GREEN)
)));
player.sendMessage(messageTag()
.append(lang("sit!.chat.purged",lang("sit!.chat.purged.total",count).color(Color.gray).b()).color(Color.GREEN)).b());
}
}
}
public static MutableText messageTag() {
return Text.literal("[").append(Text.literal("Sit!").styled(
style -> style.withColor(TextColor.parse("#c400ff").result().orElse(TextColor.fromFormatting(Formatting.DARK_PURPLE))))
).append("] ");
public static CTxT messageTag() {
return new CTxT("Sit!").btn(true).color(Color.decode("#c400ff")).append(" ");
}
/**
* gets a MutableText using the language key, if on server, using the custom lang reader
*/
public static MutableText lang(String key, Object... args) {
if (Data.isClient()) return Text.translatable(key, args);
public static CTxT lang(String key, Object... args) {
if (Data.isClient()) {
// we have to first convert all the CTxT's to the built version because minecraft lang reader doesn't know how to process it
// make a array with the same size of the args
Object[] fixedArgs = new Object[args.length];
// for every arg, build & add if CTxT or just add if not
for (var i = 0; i < args.length; i++) {
if (args[i] instanceof CTxT) fixedArgs[i] = ((CTxT) args[i]).b();
else fixedArgs[i] = args[i];
}
// return the translated text
return new CTxT(Text.translatable(key,fixedArgs));
}
else return LangReader.of(key, args).getTxT();
}