Skip to content

Commit

Permalink
Some lib config changes
Browse files Browse the repository at this point in the history
  • Loading branch information
simon816 committed Feb 18, 2019
1 parent e45d43d commit 595738d
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 44 deletions.
22 changes: 14 additions & 8 deletions ChatUILib/src/main/java/com/simon816/chatui/lib/ChatUILib.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
Expand Down Expand Up @@ -48,6 +49,8 @@
@Plugin(id = "chatuilib", name = "Chat UI Library")
public class ChatUILib {

private static final String COMMAND_NAME = "chatui";

private static ChatUILib instance;

private final Map<UUID, PlayerChatView> playerViewMap = Maps.newHashMap();
Expand All @@ -57,6 +60,10 @@ public class ChatUILib {
@Inject
private Logger logger;

@Inject
@ConfigDir(sharedRoot = false)
private Path confDir;

/* Public API utility functions */

public static PlayerChatView getView(UUID uuid) {
Expand All @@ -73,7 +80,7 @@ public static PlayerChatView getView(CommandSource source) {
}

public static ClickAction<?> command(String subcommand) {
return TextActions.runCommand("/chatui " + subcommand);
return TextActions.runCommand("/" + COMMAND_NAME + " " + subcommand);
}

public static ChatUILib getInstance() {
Expand All @@ -93,17 +100,16 @@ public void onPreInit(GamePreInitializationEvent event) {

@Listener
public void onInit(GameInitializationEvent event) {
Path confDir = Sponge.getGame().getConfigManager().getSharedConfig(this).getDirectory().resolve("chatui");
try {
Files.createDirectories(confDir);
Files.createDirectories(this.confDir);
} catch (IOException e) {
this.logger.error("Failed to create configuration directory at {}", confDir, e);
this.logger.error("Failed to create config directory {}", this.confDir, e);
}
Path confFile = confDir.resolve("preferences.conf");

Path confFile = this.confDir.resolve("preferences.conf");
HoconConfigurationLoader confLoader = HoconConfigurationLoader.builder().setPath(confFile).build();
LibConfig.init(confLoader, this.logger);
this.languageManager = new LanguagePackManager(confDir);

this.languageManager = new LanguagePackManager(this.confDir, this.logger);
if (LibConfig.useLanguagePack()) {
this.languageManager.fetch(this.logger);
}
Expand Down Expand Up @@ -134,7 +140,7 @@ public void onInit(GameInitializationEvent event) {
})
.description(Text.of("Internal Chat UI commands"))
.build();
Sponge.getGame().getCommandManager().register(this, cmd, "chatui");
Sponge.getGame().getCommandManager().register(this, cmd, COMMAND_NAME);
}

@Listener
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.simon816.chatui.lib.config;

import com.simon816.chatui.lib.event.PlayerChangeConfigEvent;
import com.simon816.chatui.util.FontData;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import ninja.leaping.configurate.objectmapping.ObjectMapper;
Expand All @@ -26,10 +27,12 @@ public class LibConfig {

private static Logger logger;
private static CommentedConfigurationNode config;
private static boolean dirty;

private static ObjectMapper<PlayerSettings> settingsMapper;

private static boolean useLanguagePack;
private static FontData defaultFontData;

public static CommandCallable createCommand() {
return CommandSpec.builder()
Expand Down Expand Up @@ -94,35 +97,65 @@ public static void init(ConfigurationLoader<CommentedConfigurationNode> confLoad
}

public static void loadConfig() {
try {
settingsMapper = ObjectMapper.forClass(PlayerSettings.class);
} catch (ObjectMappingException e) {
throw new RuntimeException(e);
}
try {
config = confLoader.load();
} catch (IOException e) {
logger.error("Error while loading config", e);
logger.error("Error while loading config. Resetting to default config.", e);
config = confLoader.createEmptyNode();
}
dirty = false;

CommentedConfigurationNode playerSettings = config.getNode("player-settings");
if (playerSettings.isVirtual()) {
playerSettings.setValue(Collections.emptyMap());
dirty = true;
}
try {
settingsMapper = ObjectMapper.forClass(PlayerSettings.class);
} catch (ObjectMappingException e) {
throw new RuntimeException(e);
}

CommentedConfigurationNode useLanguagePack = config.getNode("use-language-pack");
if (useLanguagePack.isVirtual()) {
useLanguagePack.setValue(false);
dirty = true;
}
LibConfig.useLanguagePack = useLanguagePack.getBoolean();

CommentedConfigurationNode defaultFontNode = config.getNode("default-font");
if (defaultFontNode.isVirtual()) {
defaultFontNode.setValue("");
dirty = true;
}

String defaultFontString = defaultFontNode.getString();
try {
FontData.checkValid(defaultFontString);
} catch (IllegalArgumentException e) {
logger.warn("Default font is invalid, falling back to vanilla font", e);
defaultFontString = null;
}
defaultFontData = FontData.fromString(defaultFontString, FontData.VANILLA);

saveConfig();
}

public static boolean useLanguagePack() {
return useLanguagePack;
}

public static FontData defaultFontData() {
return defaultFontData;
}

public static void saveConfig() {
if (!dirty) {
return;
}
try {
confLoader.save(config);
dirty = false;
} catch (IOException e) {
logger.error("Failed to save config", e);
}
Expand All @@ -131,6 +164,8 @@ public static void saveConfig() {
public static PlayerSettings playerConfig(UUID uuid) {
CommentedConfigurationNode settings = config.getNode("player-settings", uuid.toString());
try {
// Save defaults to config file
dirty |= settings.isVirtual();
return settingsMapper.bindToNew().populate(settings);
} catch (ObjectMappingException e) {
throw new RuntimeException(e);
Expand All @@ -149,6 +184,7 @@ public static void updatePlayer(PlayerSettings settings, Player player) {
return;
}
settingsMapper.bind(settings).serialize(config.getNode("player-settings", uuid.toString()));
dirty = true;
Sponge.getEventManager()
.post(new PlayerChangeConfigEvent(player, oldSettings, settings, Sponge.getCauseStackManager().getCurrentCause()));
} catch (ObjectMappingException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ public PlayerSettings withFontData(String fontData) {
}

public PlayerContext createContext(Player player) {
return new PlayerContext(player, getWidth(), getHeightLines(), getForceUnicode(), FontData.fromString(getFontData()));
return new PlayerContext(player, getWidth(), getHeightLines(), getForceUnicode(),
FontData.fromString(getFontData(), LibConfig.defaultFontData()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public void run() {
}
}
if (versionUrlString == null) {
this.logger.error("Could not find version %s from manifest", this.mcVersion);
this.logger.error("Could not find version {} from manifest", this.mcVersion);
return;
}
URL versionJsonUrl;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.IllegalFormatException;
import java.util.Locale;
import java.util.Map;
Expand All @@ -38,12 +39,12 @@ public Map<String, String> load(Locale key) throws Exception {
}
});

public LanguagePackManager(Path confDir) {
public LanguagePackManager(Path confDir, Logger logger) {
this.langZipFile = confDir.resolve("lang").resolve(getMcVersion() + "-languagepack.zip");
try {
Files.createDirectories(this.langZipFile.getParent());
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to create language pack directory {}", this.langZipFile.getParent(), e);
}
}

Expand All @@ -68,7 +69,6 @@ public Translation forTranslation(Translation translation) {

public String translate(Locale locale, String id) {
return this.translationCache.getUnchecked(locale).getOrDefault(id, id);

}

public void incrementLocale(Locale locale) {
Expand Down Expand Up @@ -96,32 +96,29 @@ public boolean isDefault(Locale locale) {
}

Map<String, String> loadTranslations(Locale locale) {
Map<String, String> translations = Maps.newHashMap();
if (!Files.exists(langZipFile)) {
return translations;
if (!Files.exists(this.langZipFile)) {
return Collections.emptyMap();
}
try {
ZipFile zipFile = new ZipFile(this.langZipFile.toFile());
Map<String, String> translations = Maps.newHashMap();
try (ZipFile zipFile = new ZipFile(this.langZipFile.toFile())) {
ZipEntry entry = zipFile.getEntry(locale.toString().toLowerCase() + ".lang");
if (entry == null) {
zipFile.close();
return translations;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
String line;
while ((line = reader.readLine()) != null) {
if (!line.isEmpty() && line.charAt(0) != '#') {
int eqPos = line.indexOf('=');
if (eqPos != -1) {
String key = line.substring(0, eqPos);
String value = eqPos == line.length() - 1 ? "" : line.substring(eqPos + 1);
value = NUMERIC_VARIABLE_PATTERN.matcher(value).replaceAll("%$1s");
translations.put(key, value);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.isEmpty() && line.charAt(0) != '#') {
int eqPos = line.indexOf('=');
if (eqPos != -1) {
String key = line.substring(0, eqPos);
String value = eqPos == line.length() - 1 ? "" : line.substring(eqPos + 1);
value = NUMERIC_VARIABLE_PATTERN.matcher(value).replaceAll("%$1s");
translations.put(key, value);
}
}
}
}
reader.close();
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
Expand Down
27 changes: 20 additions & 7 deletions ChatUILib/src/main/java/com/simon816/chatui/util/FontData.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,17 @@ public FontData(InputStream asciiPng) throws IOException {
readCompressedAscii(compressedData);
}

private void readCompressedAscii(byte[] compressedData) {
private static Inflater inflate(byte[] src, byte[] dest) throws DataFormatException {
Inflater inflater = new Inflater();
inflater.setInput(compressedData);
inflater.setInput(src);
inflater.inflate(dest);
return inflater;
}

private void readCompressedAscii(byte[] compressedData) {
byte[] data = new byte[this.asciiCharWidths.length >>> 1];
try {
inflater.inflate(data);
inflate(compressedData, data);
} catch (DataFormatException e) {
throw new RuntimeException(e);
}
Expand Down Expand Up @@ -180,15 +185,15 @@ public int getWidthInt(int codePoint, boolean isBold, boolean forceUnicode) {
return (int) Math.ceil(getWidth(codePoint, isBold, forceUnicode));
}

public static FontData fromString(String fontData) {
public static FontData fromString(String fontData, FontData fallback) {
if (fontData == null || fontData.isEmpty()) {
return VANILLA;
return fallback;
}
try {
return dataCache.getUnchecked(fontData);
} catch (Exception e) {
e.printStackTrace();
return VANILLA;
return fallback;
}
}

Expand All @@ -198,7 +203,15 @@ public static void checkValid(String fontData) throws IllegalArgumentException {
}
// Throws IllegalArgumentException if invalid
byte[] data = Base64.getDecoder().decode(fontData);
checkArgument(data.length == ASCII_PNG_CHARS.length() >>> 1, "Length of font data not valid");
try {
int expectLen = ASCII_PNG_CHARS.length() >>> 1;
Inflater inflater = inflate(data, new byte[expectLen]);
long written = inflater.getBytesWritten();
checkArgument(inflater.finished(), "Font data larger than expected, expected %s", expectLen);
checkArgument(written == expectLen, "Font data not of expected size, expected %s got %s", expectLen, written);
} catch (DataFormatException e) {
throw new IllegalArgumentException("Corrupt font data", e);
}
}

}

0 comments on commit 595738d

Please sign in to comment.