feat: item translation

This commit is contained in:
ineanto 2023-07-27 23:29:57 +02:00
parent c929e73b0d
commit b64f56a0bb
9 changed files with 97 additions and 47 deletions

View file

@ -33,5 +33,6 @@ public class PlayerJoinListener implements Listener {
} }
} }
}, 20L); }, 20L);
System.out.println("i18n.getPlayerLocale().getCode() = " + i18n.getPlayerLocale().getCode());
} }
} }

View file

@ -11,20 +11,17 @@ import xyz.xenondevs.invui.item.impl.SuppliedItem;
import xyz.xenondevs.invui.window.Window; import xyz.xenondevs.invui.window.Window;
public class GoBackItem { public class GoBackItem {
private final Player player;
private final I18N i18n; private final I18N i18n;
public GoBackItem(Player player) { public GoBackItem(Player player) {
this.player = player;
this.i18n = new I18N(player); this.i18n = new I18N(player);
} }
public SuppliedItem get(Gui gui, String parentTitle) { public SuppliedItem get(Gui gui, String parentTitle) {
final ItemTranslation translation = i18n.translateItem(I18NDict.GUI.GO_BACK);
return new SuppliedItem(() -> { return new SuppliedItem(() -> {
final ItemBuilder builder = new ItemBuilder(Material.ARROW); final ItemBuilder builder = new ItemBuilder(Material.ARROW);
final ItemTranslation translation = i18n.translateItem(I18NDict.GUI.GO_BACK);
builder.setDisplayName(translation.getName()); builder.setDisplayName(translation.getName());
translation.getLore().forEach(builder::addLoreLines);
return builder; return builder;
}, click -> { }, click -> {
click.getEvent().getView().close(); click.getEvent().getView().close();

View file

@ -1,13 +1,13 @@
package xyz.atnrch.nicko.gui.items.settings; package xyz.atnrch.nicko.gui.items.settings;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import xyz.atnrch.nicko.NickoBukkit; import xyz.atnrch.nicko.NickoBukkit;
import xyz.atnrch.nicko.i18n.I18N; import xyz.atnrch.nicko.i18n.I18N;
import xyz.atnrch.nicko.i18n.I18NDict; import xyz.atnrch.nicko.i18n.I18NDict;
import xyz.atnrch.nicko.i18n.ItemTranslation; import xyz.atnrch.nicko.i18n.ItemTranslation;
import xyz.atnrch.nicko.profile.NickoProfile; import xyz.atnrch.nicko.profile.NickoProfile;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import xyz.xenondevs.invui.item.ItemProvider; import xyz.xenondevs.invui.item.ItemProvider;
import xyz.xenondevs.invui.item.builder.ItemBuilder; import xyz.xenondevs.invui.item.builder.ItemBuilder;
import xyz.xenondevs.invui.item.impl.AbstractItem; import xyz.xenondevs.invui.item.impl.AbstractItem;
@ -49,6 +49,8 @@ public class BungeeCordCyclingItem {
final ItemTranslation translation = i18n.translateItem(I18NDict.GUI.Settings.BUNGEECORD); final ItemTranslation translation = i18n.translateItem(I18NDict.GUI.Settings.BUNGEECORD);
builder.setDisplayName(translation.getName()); builder.setDisplayName(translation.getName());
translation.getLore().forEach(builder::addLoreLines);
/*
if (enabled) { if (enabled) {
builder.addLoreLines("§7> §cDisabled"); builder.addLoreLines("§7> §cDisabled");
builder.addLoreLines("§6§l> §a§lEnabled"); builder.addLoreLines("§6§l> §a§lEnabled");
@ -57,6 +59,7 @@ public class BungeeCordCyclingItem {
builder.addLoreLines("§7> §aEnabled"); builder.addLoreLines("§7> §aEnabled");
} }
builder.addLoreLines("§7§oCycle through the values by", "§7§oleft and right clicking."); builder.addLoreLines("§7§oCycle through the values by", "§7§oleft and right clicking.");
*/
return builder; return builder;
} }
} }

View file

@ -43,9 +43,10 @@ public class LanguageCyclingItem {
observer.playSound(player, Sound.UI_BUTTON_CLICK, 1f, 0.707107f); // 0.707107 ~= C observer.playSound(player, Sound.UI_BUTTON_CLICK, 1f, 0.707107f); // 0.707107 ~= C
// TODO (Ineanto, 7/14/23): This checks a 2nd time for the profile. // TODO (Ineanto, 7/14/23): This checks a 2nd time for the profile.
if (dataStore.updateCache(player.getUniqueId(), nickoProfile).isError()) { if (dataStore.updateCache(player.getUniqueId(), nickoProfile).isError()) {
final I18N i18n = new I18N(player);
player.sendMessage(i18n.translate(I18NDict.Event.Settings.ERROR)); player.sendMessage(i18n.translate(I18NDict.Event.Settings.ERROR));
player.getOpenInventory().close(); player.getOpenInventory().close();
} else {
player.sendMessage("Updated language to " + nickoProfile.getLocale().getCode());
} }
}, localeOrdinal, providers); }, localeOrdinal, providers);
} }

View file

@ -9,11 +9,16 @@ import java.io.InputStream;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class I18N { public class I18N {
private final MessageFormat formatter = new MessageFormat(""); private final MessageFormat formatter = new MessageFormat("");
private final YamlConfig yamlConfig; private final Logger logger = Logger.getLogger("I18N");
private final NickoBukkit instance = NickoBukkit.getInstance(); private final NickoBukkit instance = NickoBukkit.getInstance();
private final Pattern replacementPattern = Pattern.compile("\\{\\d+}");
private final YamlConfig yamlConfig;
private final Player player; private final Player player;
private final Locale playerLocale; private final Locale playerLocale;
@ -30,37 +35,63 @@ public class I18N {
} }
public ItemTranslation translateItem(String key, String... args) { public ItemTranslation translateItem(String key, String... args) {
final String name = readString(key + ".name"); final String nameKey = key + ".name";
final ArrayList<String> lore = readList(key + ".lore"); final String loreKey = key + ".lore";
final String name = readString(nameKey);
final ArrayList<String> lore = readList(loreKey);
if (name == null) {
logger.warning(nameKey + " doesn't exists! Please translate this entry.");
return new ItemTranslation(nameKey, new ArrayList<String>() {{
add(loreKey);
}});
}
// Add all elements to a list // Add all elements to a list
final ArrayList<String> toTranslate = new ArrayList<>(); final ArrayList<String> toTranslate = new ArrayList<>();
toTranslate.add(name); toTranslate.add(name);
if (lore != null && !lore.isEmpty()) {
toTranslate.addAll(lore); toTranslate.addAll(lore);
}
// Set starting index to 0 // Set starting index to 0
int index = 0; int lineIndex = 0;
int replacementIndex = 0;
// While iterator next value exists/isn't null // While iterator next value exists/isn't null
final Iterator<String> iterator = toTranslate.iterator(); final Iterator<String> iterator = toTranslate.iterator();
while (!iterator.hasNext() || iterator.next() == null) { while (iterator.hasNext() && iterator.next() != null) {
// Get the current line // Get the current line
final String currentLine = toTranslate.get(index); final String currentLine = toTranslate.get(lineIndex);
// If the line doesn't contain {i}, skip it
final Matcher matcher = replacementPattern.matcher(currentLine);
if (!matcher.matches()) {
lineIndex++;
continue;
}
// If it does, replace the content with the args at position replacementIndex
if (replacementIndex < args.length && args[replacementIndex] != null) {
// Replace with the corresponding varargs index // Replace with the corresponding varargs index
toTranslate.set(index, currentLine.replace("{" + index + "}", args[index])); toTranslate.set(lineIndex, currentLine.replace("{" + replacementIndex + "}", args[replacementIndex]));
replacementIndex++;
}
// Increment the index // Increment the index
index++; lineIndex++;
} }
return new ItemTranslation(toTranslate.get(0), toTranslate.subList(1, toTranslate.size()));
if (lore == null || lore.isEmpty()) {
return new ItemTranslation(toTranslate.get(0), new ArrayList<>());
}
return new ItemTranslation(toTranslate.get(0), new ArrayList<>(toTranslate.subList(1, toTranslate.size())));
} }
public String translate(String key, Object... arguments) { public String translate(String key, Object... arguments) {
final String string = readString(key); final String translation = readString(key);
try { try {
formatter.applyPattern(string); formatter.applyPattern(translation);
return instance.getNickoConfig().getPrefix() + formatter.format(arguments); return instance.getNickoConfig().getPrefix() + formatter.format(arguments);
} catch (Exception e) { } catch (Exception e) {
return instance.getNickoConfig().getPrefix() + key; return instance.getNickoConfig().getPrefix() + key;
@ -94,7 +125,7 @@ public class I18N {
} }
} }
private Locale getPlayerLocale() { public Locale getPlayerLocale() {
try { try {
final AppearanceManager appearanceManager = AppearanceManager.get(player); final AppearanceManager appearanceManager = AppearanceManager.get(player);
return !appearanceManager.hasData() ? Locale.FALLBACK_LOCALE : appearanceManager.getLocale(); return !appearanceManager.hasData() ? Locale.FALLBACK_LOCALE : appearanceManager.getLocale();

View file

@ -1,12 +1,12 @@
package xyz.atnrch.nicko.i18n; package xyz.atnrch.nicko.i18n;
import java.util.List; import java.util.ArrayList;
public class ItemTranslation { public class ItemTranslation {
private final String name; private final String name;
private final List<String> lore; private final ArrayList<String> lore;
public ItemTranslation(String name, List<String> lore) { public ItemTranslation(String name, ArrayList<String> lore) {
this.name = name; this.name = name;
this.lore = lore; this.lore = lore;
} }
@ -15,7 +15,7 @@ public class ItemTranslation {
return name; return name;
} }
public List<String> getLore() { public ArrayList<String> getLore() {
return lore; return lore;
} }
} }

View file

@ -29,6 +29,8 @@ event:
gui: gui:
exit: "Exit" exit: "Exit"
go_back:
name: "Back"
home: home:
admin: admin:
name: "Administration panel" name: "Administration panel"
@ -58,5 +60,6 @@ gui:
bungeecord: bungeecord:
name: "Bungeecord Transfer" name: "Bungeecord Transfer"
lore: lore:
- "{0}"
- "§7§oGet through the values" - "§7§oGet through the values"
- "§7§oby left or right clicking." - "§7§oby left or right clicking."

View file

@ -9,6 +9,8 @@ error:
json: "Erreur JSON" json: "Erreur JSON"
event: event:
settings:
error: "§cImpossible de mettre à jour vos paramètres. §7§o({0})"
appearance: appearance:
set: set:
error: "§cImpossible d''appliquer votre déguisement. §7§o({0})" error: "§cImpossible d''appliquer votre déguisement. §7§o({0})"
@ -27,6 +29,8 @@ event:
gui: gui:
exit: "Quitter" exit: "Quitter"
go_back:
name: "Retour"
home: home:
admin: admin:
name: "Panel d''administration" name: "Panel d''administration"
@ -54,7 +58,8 @@ gui:
- "§7§oParcourez les valeurs" - "§7§oParcourez les valeurs"
- "§7§oavec un clique gauche/droit." - "§7§oavec un clique gauche/droit."
bungeecord: bungeecord:
name: "Bungeecord Transfer" name: "Transfert Bungeecord"
lore: lore:
- "§7§oGet through the values" - "{0}"
- "§7§oby left or right clicking." - "§7§oParcourez les valeurs"
- "§7§oavec un clique gauche/droit."

View file

@ -1,7 +1,6 @@
package xyz.atnrch.nicko.test.i18n; package xyz.atnrch.nicko.test.i18n;
import be.seeseemelk.mockbukkit.MockBukkit; import be.seeseemelk.mockbukkit.MockBukkit;
import be.seeseemelk.mockbukkit.ServerMock;
import be.seeseemelk.mockbukkit.entity.PlayerMock; import be.seeseemelk.mockbukkit.entity.PlayerMock;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
@ -15,8 +14,10 @@ import xyz.atnrch.nicko.i18n.I18NDict;
import xyz.atnrch.nicko.i18n.ItemTranslation; import xyz.atnrch.nicko.i18n.ItemTranslation;
import xyz.atnrch.nicko.i18n.Locale; import xyz.atnrch.nicko.i18n.Locale;
public class I18NLoreTest { import static org.junit.jupiter.api.Assertions.assertEquals;
private static NickoBukkit plugin; import static org.junit.jupiter.api.Assertions.assertTrue;
public class I18NItemTranslationTest {
private static PlayerMock player; private static PlayerMock player;
@BeforeAll @BeforeAll
@ -26,17 +27,25 @@ public class I18NLoreTest {
DataSourceConfiguration.REDIS_EMPTY, DataSourceConfiguration.REDIS_EMPTY,
"", "",
false); false);
final ServerMock server = MockBukkit.mock(); MockBukkit.mock();
plugin = MockBukkit.load(NickoBukkit.class, config); MockBukkit.load(NickoBukkit.class, config);
} }
@Test @Test
@DisplayName("Translate Item Lore") @DisplayName("Translate Item Without Lore")
public void translateItemTranslationWithoutLore() {
final I18N i18n = new I18N(Locale.FRENCH);
final ItemTranslation translation = i18n.translateItem(I18NDict.GUI.GO_BACK);
assertTrue(translation.getLore().isEmpty());
assertEquals(translation.getName(), "Retour");
}
@Test
@DisplayName("Translate Item")
public void translateItemLore() { public void translateItemLore() {
final I18N i18n = new I18N(Locale.FRENCH); final I18N i18n = new I18N(Locale.FRENCH);
final ItemTranslation translation = i18n.translateItem(I18NDict.GUI.Home.ADMIN); final ItemTranslation translation = i18n.translateItem(I18NDict.GUI.Settings.BUNGEECORD, "Test");
System.out.println("name = " + translation.getName()); assertEquals("Test", translation.getLore().get(0));
System.out.println("lore = " + translation.getLore());
} }
@AfterAll @AfterAll