This commit is contained in:
michiel
2025-10-04 22:33:46 +02:00
parent 39fa2edb3a
commit d7d6a49b98
9 changed files with 211 additions and 17 deletions

View File

@@ -0,0 +1,75 @@
package org.toop.framework.asset.resources;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.toop.framework.asset.types.FileExtension;
import org.toop.framework.asset.types.LoadableResource;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
@FileExtension({"json"})
public class JsonAsset<T> extends BaseResource implements LoadableResource {
private T content;
private Class<T> type;
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
public JsonAsset(File file, Class<T> type) {
super(file);
this.type = type;
}
@Override
public void load() {
File file = getFile();
if (!file.exists()) {
try {
// make a new file with the declared constructor (example: settings) if it doesn't exist
content = type.getDeclaredConstructor().newInstance();
save();
} catch (Exception e) {
throw new RuntimeException("Could not make default JSON settings for" + file, e);
}
} else {
// else open the file, try reading it using gson, and set it to loaded
try (FileReader reader = new FileReader(file)) {
content = gson.fromJson(reader, type);
this.isLoaded = true;
} catch(Exception e) {
throw new RuntimeException("Failed to load JSON asset" + getFile(), e);
}
}
}
@Override
public void unload() {
this.content = null;
this.isLoaded = false;
}
public T getContent() {
if (!isLoaded()) {
load();
}
return content;
}
public void save() {
File file = getFile();
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
try (FileWriter writer = new FileWriter(file)) {
gson.toJson(content, writer);
} catch (IOException e) {
throw new RuntimeException("Failed to save JSON asset" + getFile(), e);
}
}
@Override
public boolean isLoaded() {
return this.isLoaded;
}
}

View File

@@ -0,0 +1,41 @@
package org.toop.framework.asset.resources;
import org.toop.framework.settings.Settings;
import java.io.File;
import java.util.Locale;
public class SettingsAsset extends JsonAsset<Settings> {
public SettingsAsset(File file) {
super(file, Settings.class);
}
public int getVolume() {
return getContent().volume;
}
public Locale getLocale() {
return Locale.forLanguageTag(getContent().locale);
}
public boolean getFullscreen() {
return getContent().fullScreen;
}
public void setVolume(int volume) {
getContent().volume = volume;
save();
}
public void setLocale(String locale) {
getContent().locale = locale;
save();
}
public void setFullscreen(boolean fullscreen) {
getContent().fullScreen = fullscreen;
save();
}
}

View File

@@ -0,0 +1,9 @@
package org.toop.framework.settings;
import java.util.Locale;
public class Settings {
public boolean fullScreen = false;
public String locale = Locale.getDefault().toLanguageTag();
public int volume = 100;
}