forked from BVengo/sound-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigParser.java
More file actions
285 lines (255 loc) · 8.66 KB
/
Copy pathConfigParser.java
File metadata and controls
285 lines (255 loc) · 8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package com.bvengo.soundcontroller.config;
import com.bvengo.soundcontroller.SoundController;
import com.bvengo.soundcontroller.VolumeData;
import com.google.gson.*;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.resources.Identifier;
import java.io.*;
import java.util.Comparator;
import java.util.HashMap;
public class ConfigParser {
private static final File file = new File(FabricLoader.getInstance().getConfigDir().toFile(),
SoundController.MOD_ID + ".json");
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
/**
* Loads data into a VolumeConfig object from a JSON file.
*
* @param config The VolumeConfig to load the data into.
*/
public static void loadConfig(VolumeConfig config) {
if (!file.exists()) {
SoundController.LOGGER.info("Config file not found. Creating a new one.");
buildEmptyConfig();
return;
}
try (Reader reader = new FileReader(file)) {
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
if (jsonObject == null) {
SoundController.LOGGER.error("Config file is empty, creating a new one.");
buildEmptyConfig();
return;
}
parseConfig(config, jsonObject);
} catch (Exception e) {
SoundController.LOGGER.error("Error reading config file, creating a new one. Original error: ", e);
moveOldConfig();
buildEmptyConfig();
}
}
/**
* Saves the provided VolumeConfig to a JSON file.
*
* @param config The VolumeConfig to save.
*/
public static void saveConfig(VolumeConfig config) {
JsonObject jsonObject = createJsonConfig(config);
saveToJsonFile(jsonObject);
}
/**
* Creates a JsonObject from a VolumeConfig.
*
* @param config The VolumeConfig to convert to JSON.
* @return JsonObject representing the provided VolumeConfig.
*/
private static JsonObject createJsonConfig(VolumeConfig config) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("version", VolumeConfig.CONFIG_VERSION);
jsonObject.addProperty("subtitlesEnabled", config.subtitlesEnabled);
JsonArray sounds = new JsonArray();
config.getVolumes().values().stream()
.filter(volumeData -> volumeData.getVolume() != 1.0F)
.sorted(Comparator.comparing(v -> v.getId().toString()))
.forEach(volumeData -> {
JsonObject soundObject = new JsonObject();
soundObject.addProperty("soundId", volumeData.getId().toString());
soundObject.addProperty("volume", volumeData.getVolume());
sounds.add(soundObject);
});
jsonObject.add("sounds", sounds);
return jsonObject;
}
/**
* Writes a JsonObject to a JSON file.
*
* @param jsonObject The JsonObject to write to file.
*/
private static void saveToJsonFile(JsonObject jsonObject) {
try (Writer writer = new FileWriter(file)) {
gson.toJson(jsonObject, writer);
} catch (IOException e) {
SoundController.LOGGER.error("Unable to save sound config to file.", e);
}
}
/**
* Parses volume data from a JSON object into a map. Handles versioning.
*
* @param config The config being updated.
* @param jsonObject The JSON object to parse.
*/
private static void parseConfig(VolumeConfig config, JsonObject jsonObject) {
int version = jsonObject.has("version") ? jsonObject.get("version").getAsInt() : -1;
// Check if the version key exists to determine the handling strategy
if (version == -1) {
String msg = "Config file does not have a version number. Trying to parse old un-versioned format.";
SoundController.LOGGER.warn(msg);
parseConfigUnversioned(config, jsonObject);
return;
}
if (version < 4 || version > VolumeConfig.CONFIG_VERSION) {
String msg = "Version number invalid - must be between 4 and " + VolumeConfig.CONFIG_VERSION +
" (inclusive). Got " + version + " instead. Storing old config file with `old.` prefix, " +
"and initializing a new empty config file.";
SoundController.LOGGER.error(msg);
moveOldConfig();
buildEmptyConfig();
return;
}
// if (version == 4) {
// Currently always true
parseConfig4(config, jsonObject);
// }
}
/**
* Moves the old config file to a new file with a prefix of `old.`.
*/
private static void moveOldConfig() {
File oldFile = new File(file.getParentFile(), "old." + file.getName());
if (file.renameTo(oldFile)) {
SoundController.LOGGER.info("Renamed old config file to " + oldFile.getName());
} else {
SoundController.LOGGER.error("Failed to rename old config file.");
}
}
/**
* Builds an empty config file with the current version number.
*/
private static void buildEmptyConfig() {
JsonObject newConfig = new JsonObject();
newConfig.addProperty("version", VolumeConfig.CONFIG_VERSION);
newConfig.add("sounds", new JsonArray());
try (Writer writer = new FileWriter(file)) {
gson.toJson(newConfig, writer);
} catch (IOException e) {
SoundController.LOGGER.error("Failed to create a new empty config file.", e);
}
}
/**
* Adds a sound ID and volume to the soundVolumes map, provided the sound is valid.
*
* @param soundVolumes The map to store the sound volumes.
* @param soundId The sound ID to add.
* @param volume The volume to add.
*/
private static void addVolumeData(HashMap<Identifier, VolumeData> soundVolumes, String soundId, float volume) {
Identifier id = Identifier.tryParse(soundId);
if (soundVolumes.containsKey(id)) {
SoundController.LOGGER.warn("Duplicate sound ID found in config: {}. Taking first only.", soundId);
return;
}
VolumeData volumeData = new VolumeData(id, volume);
if(id != null) {
soundVolumes.put(id, volumeData);
} else {
SoundController.LOGGER.warn("Invalid sound ID found in config: {}. Skipping.", soundId);
}
}
/**
* Parse V4 configs. The structure is as follows:
* <pre>
* {
* "version": 4,
* "sounds": [
* {
* "soundId": "minecraft:entity.player.hurt",
* "volume": 0.5
* },
* ...
* }
* </pre>
*
* @param config The config being updated.
* @param jsonObject The JSON object to parse.
*/
private static void parseConfig4(VolumeConfig config, JsonObject jsonObject) {
JsonElement subtitlesElement = jsonObject.get("subtitlesEnabled");
if (subtitlesElement != null) {
config.subtitlesEnabled = subtitlesElement.getAsBoolean();
}
HashMap<Identifier, VolumeData> soundVolumes = config.getVolumes();
JsonArray sounds = jsonObject.getAsJsonArray("sounds");
for (JsonElement soundElement : sounds) {
JsonObject soundObject = soundElement.getAsJsonObject();
String soundId = soundObject.get("soundId").getAsString();
float volume = soundObject.get("volume").getAsFloat();
addVolumeData(soundVolumes, soundId, volume);
}
SoundController.LOGGER.info("Successfully loaded in configs.");
}
/**
* Parse un-versioned configs. The structure is as follows:
* <pre>
* {
* // version 1:
* "minecraft.entity.player.hurt": 0.5,
* ...
*
* // version 2:
* "minecraft:entity.player.hurt": {
* "id": "minecraft:entity.player.hurt",
* "volume": 0.5,
* "shouldOverride": false
* },
* ...
*
* // version 3:
* "minecraft:entity.player.hurt": {
* "soundId": "minecraft:entity.player.hurt",
* "volume": 0.5
* },
* ...
* }
* </pre>
*
* @param config The config being updated.
* @param jsonObject The JSON object to parse.
*/
private static void parseConfigUnversioned(VolumeConfig config, JsonObject jsonObject) {
HashMap<Identifier, VolumeData> soundVolumes = config.getVolumes();
// Iterate over each entry in the JSON object assuming each key is a sound ID
jsonObject.entrySet().forEach(entry -> {
String key = entry.getKey(); // Should be the soundId as well
JsonElement element = entry.getValue();
String soundId;
float volume;
if(element.isJsonPrimitive()) {
if(element.getAsJsonPrimitive().isNumber()) {
// Handle V1 format
soundId = key;
volume = element.getAsFloat();
} else {
String msg = "Unsupported config format for sound ID: " + key;
SoundController.LOGGER.error(msg);
throw new IllegalStateException(msg);
}
}
else {
JsonObject soundObject = element.getAsJsonObject();
if (soundObject.has("id")) {
// Handle V2 format
soundId = soundObject.get("id").getAsString();
volume = soundObject.get("volume").getAsFloat();
// ignore "shouldOverride"
} else if (soundObject.has("soundId")) {
// Handle V3 format
soundId = soundObject.get("soundId").getAsString();
volume = soundObject.get("volume").getAsFloat();
} else {
String msg = "Unsupported config format for sound ID: " + key;
SoundController.LOGGER.error(msg);
throw new IllegalStateException(msg);
}
}
addVolumeData(soundVolumes, soundId, volume);
});
}
}