aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/anthonyhilyard/iceberg/config/IcebergConfigSpec.java
blob: 89b81b25fed2449f911e3adc0e6cab7b7584f520 (plain)
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
package com.anthonyhilyard.iceberg.config;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import javax.annotation.Nullable;

import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec.ConfigValue;
import net.minecraftforge.common.ForgeConfigSpec.ValueSpec;
import net.minecraftforge.fml.Logging;
import net.minecraftforge.fml.config.IConfigSpec;
import net.minecraftforge.fml.unsafe.UnsafeHacks;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;

import com.anthonyhilyard.iceberg.Loader;
import com.electronwill.nightconfig.core.AbstractCommentedConfig;
import com.electronwill.nightconfig.core.CommentedConfig;
import com.electronwill.nightconfig.core.Config;
import com.electronwill.nightconfig.core.ConfigFormat;
import com.electronwill.nightconfig.core.ConfigSpec.CorrectionAction;
import com.electronwill.nightconfig.core.ConfigSpec.CorrectionListener;
import com.electronwill.nightconfig.core.InMemoryFormat;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.electronwill.nightconfig.core.file.FileWatcher;
import com.electronwill.nightconfig.core.utils.UnmodifiableConfigWrapper;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

/*
 * Basically an improved ForgeConfigSpec that supports subconfigs.
 */
public class IcebergConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfig> implements IConfigSpec<IcebergConfigSpec>
{
	private Map<List<String>, String> levelComments;
	private Map<List<String>, String> levelTranslationKeys;

	private UnmodifiableConfig values;
	private Config childConfig;

	private boolean isCorrecting = false;

	private IcebergConfigSpec(UnmodifiableConfig storage, UnmodifiableConfig values, Map<List<String>, String> levelComments, Map<List<String>, String> levelTranslationKeys)
	{
		super(storage);
		this.values = values;
		this.levelComments = levelComments;
		this.levelTranslationKeys = levelTranslationKeys;

		// Update the filewatcher's default instance to have a more sensible exception handler.
		try
		{
			Field exceptionHandlerField = FileWatcher.class.getDeclaredField("exceptionHandler");
			UnsafeHacks.setField(exceptionHandlerField, FileWatcher.defaultInstance(), (Consumer<Exception>)e -> {
				LogManager.getLogger().warn(Logging.CORE, "An error occurred while reloading config:", e);
			});
		}
		catch (Exception e) {}
	}

	public String getLevelComment(List<String> path)
	{
		return levelComments.get(path);
	}

	public String getLevelTranslationKey(List<String> path)
	{
		return levelTranslationKeys.get(path);
	}

	public void setConfig(CommentedConfig config)
	{
		this.childConfig = config;
		if (config != null && !isCorrect(config))
		{
			String configName = config instanceof FileConfig fileConfig ? fileConfig.getNioPath().toString() : config.toString();
			Loader.LOGGER.warn("Configuration file {} is not correct. Correcting", configName);
			correct(config,
					(action, path, incorrectValue, correctedValue) ->
							Loader.LOGGER.warn("Incorrect key {} was corrected from {} to its default, {}. {}", DOT_JOINER.join( path ), incorrectValue, correctedValue, incorrectValue == correctedValue ? "This seems to be an error." : ""),
					(action, path, incorrectValue, correctedValue) ->
							Loader.LOGGER.debug("The comment on key {} does not match the spec. This may create a backup.", DOT_JOINER.join( path )));

			if (config instanceof FileConfig fileConfig)
			{
				fileConfig.save();
			}
		}
		this.afterReload();
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T getRaw(List<String> path)
	{
		T value = super.getRaw(path);
		if (value != null)
		{
			return value;
		}
		// Try to "recursively" get the value if needed.
		List<String> subPath = path.subList(0, path.size() - 1);
		Object test = super.getRaw(subPath);
		if (test instanceof ValueSpec valueSpec && valueSpec.getDefault() instanceof MutableSubconfig subconfig)
		{
			// Okay, this is a dynamic subconfig.  That means that only values defined in the default have
			// an actual value spec.
			value = subconfig.getRaw(path.get(path.size() - 1));

			// Value will be null here for non-default entries.  In that case, just return a default value spec.
			if (value == null)
			{
				value = (T) subconfig.defaultValueSpec();
			}
			return value;
		}
		return null;
	}

	@Override
	public void acceptConfig(final CommentedConfig data)
	{
		setConfig(data);
	}

	public boolean isCorrecting()
	{
		return isCorrecting;
	}

	public boolean isLoaded()
	{
		return childConfig != null;
	}

	public UnmodifiableConfig getSpec()
	{
		return this.config;
	}

	public UnmodifiableConfig getValues()
	{
		return this.values;
	}

	public void afterReload()
	{
		this.resetCaches(getValues().valueMap().values());
	}

	private void resetCaches(final Iterable<Object> configValues)
	{
		configValues.forEach(value ->
		{
			if (value instanceof ConfigValue<?> configValue)
			{
				configValue.clearCache();
			}
			else if (value instanceof Config innerConfig)
			{
				this.resetCaches(innerConfig.valueMap().values());
			}
		});
	}

	public void save()
	{
		Preconditions.checkNotNull(childConfig, "Cannot save config value without assigned Config object present!");
		if (childConfig instanceof FileConfig fileConfig)
		{
			fileConfig.save();
		}
	}

	public synchronized boolean isCorrect(CommentedConfig config)
	{
		LinkedList<String> parentPath = new LinkedList<>();

		// Forge's config watcher isn't properly atomic, so sometimes this method can give false negatives leading
		// to the entire config file reverting to defaults.  To prevent this, we'll check for an invalid state and
		// skip the correction process when that happens.
		if (config.valueMap().isEmpty() && config instanceof FileConfig fileConfig)
		{
			File configFile = fileConfig.getFile();

			// Sleep for 10 ms to give it a chance to catch up.  This shouldn't cause any issues since
			// this method only runs when the file changes and at startup.
			try { Thread.sleep(10); } catch (Exception e) { }

			// The file isn't actually empty, so this is an invalid state.  Skip this correction phase.
			if (configFile.length() > 0)
			{
				return true;
			}
		}

		return correct(this.config, config, parentPath, Collections.unmodifiableList( parentPath ), (a, b, c, d) -> {}, null, true) == 0;
	}

	public synchronized int correct(CommentedConfig config)
	{
		return correct(config, (action, path, incorrectValue, correctedValue) -> {}, null);
	}

	public synchronized int correct(CommentedConfig config, CorrectionListener listener)
	{
		return correct(config, listener, null);
	}

	public synchronized int correct(CommentedConfig config, CorrectionListener listener, CorrectionListener commentListener)
	{
		LinkedList<String> parentPath = new LinkedList<>();
		int ret = -1;
		try
		{
			isCorrecting = true;
			ret = correct(this.config, config, parentPath, Collections.unmodifiableList(parentPath), listener, commentListener, false);
		}
		finally
		{
			isCorrecting = false;
		}
		return ret;
	}

	private synchronized int correct(UnmodifiableConfig spec, CommentedConfig config, LinkedList<String> parentPath, List<String> parentPathUnmodifiable, CorrectionListener listener, CorrectionListener commentListener, boolean dryRun)
	{
		int count = 0;

		Map<String, Object> specMap = spec.valueMap();
		Map<String, Object> configMap = config.valueMap();

		for (Map.Entry<String, Object> specEntry : specMap.entrySet())
		{
			final String key = specEntry.getKey();
			Object specValue = specEntry.getValue();
			final Object configValue = configMap.get(key);
			final CorrectionAction action = configValue == null ? CorrectionAction.ADD : CorrectionAction.REPLACE;

			parentPath.addLast(key);

			String subConfigComment = null;

			// If this value is a config, use that as the spec value to support subconfigs.
			if (specValue instanceof ValueSpec valueSpec && valueSpec.getDefault() instanceof UnmodifiableConfig)
			{
				subConfigComment = valueSpec.getComment();
				specValue = valueSpec.getDefault();
			}

			if (specValue instanceof UnmodifiableConfig)
			{
				if (configValue instanceof Config)
				{
					count += correct((UnmodifiableConfig)specValue, configValue instanceof CommentedConfig commentedConfig ? commentedConfig : CommentedConfig.copy((Config)configValue), parentPath, parentPathUnmodifiable, listener, commentListener, dryRun);
					if (count > 0 && dryRun)
					{
						return count;
					}
				}
				else if (dryRun)
				{
					return 1;
				}
				else
				{
					CommentedConfig newValue = config.createSubConfig();
					configMap.put(key, newValue);
					listener.onCorrect(action, parentPathUnmodifiable, configValue, newValue);
					count++;
					count += correct((UnmodifiableConfig)specValue, newValue, parentPath, parentPathUnmodifiable, listener, commentListener, dryRun);
				}

				String newComment = subConfigComment == null ? levelComments.get(parentPath) : subConfigComment;
				String oldComment = config.getComment(key);
				if (!stringsMatchIgnoringNewlines(oldComment, newComment))
				{
					if (commentListener != null)
					{
						commentListener.onCorrect(action, parentPathUnmodifiable, oldComment, newComment);
					}

					if (dryRun)
					{
						return 1;
					}

					config.setComment(key, newComment);
				}
			}
			else
			{
				ValueSpec valueSpec = (ValueSpec)specValue;
				if (!valueSpec.test(configValue))
				{
					if (dryRun)
					{
						return 1;
					}

					Object newValue = valueSpec.correct(configValue);
					configMap.put(key, newValue);
					listener.onCorrect(action, parentPathUnmodifiable, configValue, newValue);
					count++;
				}
				String oldComment = config.getComment(key);
				if (!stringsMatchIgnoringNewlines(oldComment, valueSpec.getComment()))
				{
					if (commentListener != null)
					{
						commentListener.onCorrect(action, parentPathUnmodifiable, oldComment, valueSpec.getComment());
					}

					if (dryRun)
					{
						return 1;
					}

					config.setComment(key, valueSpec.getComment());
				}
			}

			parentPath.removeLast();
		}

		// Now remove any config values that are not explicitly set in the spec.
		for (Iterator<Map.Entry<String, Object>> iterator = configMap.entrySet().iterator(); iterator.hasNext();)
		{
			Map.Entry<String, Object> entry = iterator.next();

			// If the spec is a dynamic subconfig, don't bother checking the spec since that's the point.
			if (!(spec instanceof MutableSubconfig) && !specMap.containsKey(entry.getKey()))
			{
				if (dryRun)
				{
					return 1;
				}

				iterator.remove();
				parentPath.addLast(entry.getKey());
				listener.onCorrect(CorrectionAction.REMOVE, parentPathUnmodifiable, entry.getValue(), null);
				parentPath.removeLast();
				count++;
			}
		}
		return count;
	}

	private boolean stringsMatchIgnoringNewlines(@Nullable Object obj1, @Nullable Object obj2)
	{
		if (obj1 instanceof String && obj2 instanceof String)
		{
			String string1 = (String) obj1;
			String string2 = (String) obj2;

			if (string1.length() > 0 && string2.length() > 0)
			{
				return string1.replaceAll("\r\n", "\n").equals(string2.replaceAll("\r\n", "\n"));
			}
		}

		// Fallback for when we're not given Strings, or one of them is empty
		return Objects.equals(obj1, obj2);
	}

	public static ValueSpec createValueSpec(String comment, String langKey, boolean worldRestart, Class<?> clazz, Supplier<?> defaultSupplier, Predicate<Object> validator)
	{
		Objects.requireNonNull(defaultSupplier, "Default supplier can not be null!");
		Objects.requireNonNull(validator, "Validator can not be null!");

		// Instantiate the new ValueSpec instance, then use reflection to set the required fields.
		ValueSpec result = UnsafeHacks.newInstance(ValueSpec.class);
		try
		{
			Field commentField = ValueSpec.class.getDeclaredField("comment");
			Field langKeyField = ValueSpec.class.getDeclaredField("langKey");
			Field rangeField = ValueSpec.class.getDeclaredField("range");
			Field worldRestartField = ValueSpec.class.getDeclaredField("worldRestart");
			Field clazzField = ValueSpec.class.getDeclaredField("clazz");
			Field supplierField = ValueSpec.class.getDeclaredField("supplier");
			Field validatorField = ValueSpec.class.getDeclaredField("validator");
			UnsafeHacks.setField(commentField, result, comment);
			UnsafeHacks.setField(langKeyField, result, langKey);
			UnsafeHacks.setField(rangeField, result, null);
			UnsafeHacks.setField(worldRestartField, result, worldRestart);
			UnsafeHacks.setField(clazzField, result, clazz);
			UnsafeHacks.setField(supplierField, result, defaultSupplier);
			UnsafeHacks.setField(validatorField, result, validator);
		}
		catch (Exception e) {
			Loader.LOGGER.warn("Failed to instantiate ValueSpec!");
			Loader.LOGGER.warn(ExceptionUtils.getStackTrace(e));
		 }

		return result;
	}

	public static class Builder extends ForgeConfigSpec.Builder
	{
		@Override
		public Builder comment(String comment)
		{
			return (Builder) super.comment(comment);
		}

		@Override
		public Builder comment(String... comment)
		{
			return (Builder) super.comment(comment);
		}

		@Override
		public Builder translation(String translationKey)
		{
			return (Builder) super.translation(translationKey);
		}

		@Override
		public Builder worldRestart()
		{
			return (Builder) super.worldRestart();
		}

		@Override
		public Builder push(String path)
		{
			return (Builder) super.push(path);
		}

		@Override
		public Builder push(List<String> path)
		{
			return (Builder) super.push(path);
		}

		@Override
		public Builder pop()
		{
			return (Builder) super.pop();
		}

		@Override
		public Builder pop(int count)
		{
			return (Builder) super.pop(count);
		}

		public ConfigValue<UnmodifiableConfig> defineSubconfig(String path, UnmodifiableConfig defaultValue, Predicate<Object> keyValidator, Predicate<Object> valueValidator)
		{
			return defineSubconfig(split(path), defaultValue, keyValidator, valueValidator);
		}

		public ConfigValue<UnmodifiableConfig> defineSubconfig(List<String> path, UnmodifiableConfig defaultValue, Predicate<Object> keyValidator, Predicate<Object> valueValidator)
		{
			return defineSubconfig(path, () -> defaultValue, keyValidator, valueValidator);
		}

		public ConfigValue<UnmodifiableConfig> defineSubconfig(String path, Supplier<UnmodifiableConfig> defaultSupplier, Predicate<Object> keyValidator, Predicate<Object> valueValidator)
		{
			return defineSubconfig(split(path), defaultSupplier, keyValidator, valueValidator);
		}

		public ConfigValue<UnmodifiableConfig> defineSubconfig(List<String> path, Supplier<UnmodifiableConfig> defaultSupplier, Predicate<Object> keyValidator, Predicate<Object> valueValidator)
		{
			final UnmodifiableConfig defaultConfig = defaultSupplier.get();
			return define(path, () -> MutableSubconfig.copy(defaultConfig, keyValidator, valueValidator), o -> o != null);
		}

		private IcebergConfigSpec finishBuild()
		{
			IcebergConfigSpec result = null;

			try
			{
				Field valuesField = ForgeConfigSpec.Builder.class.getDeclaredField("values");
				Field storageField = ForgeConfigSpec.Builder.class.getDeclaredField("storage");
				Field levelCommentsField = ForgeConfigSpec.Builder.class.getDeclaredField("levelComments");
				Field levelTranslationKeysField = ForgeConfigSpec.Builder.class.getDeclaredField("levelTranslationKeys");

				List<ConfigValue<?>> values = UnsafeHacks.<List<ConfigValue<?>>>getField(valuesField, this);
				Config storage = UnsafeHacks.<Config>getField(storageField, this);
				Map<List<String>, String> levelComments = UnsafeHacks.<Map<List<String>, String>>getField(levelCommentsField, this);
				Map<List<String>, String> levelTranslationKeys = UnsafeHacks.<Map<List<String>, String>>getField(levelTranslationKeysField, this);

				Config valueCfg = Config.of(Config.getDefaultMapCreator(true, true), InMemoryFormat.withSupport(ConfigValue.class::isAssignableFrom));
				values.forEach(v -> valueCfg.set(v.getPath(), v));

				final IcebergConfigSpec ret = new IcebergConfigSpec(storage, valueCfg, levelComments, levelTranslationKeys);
				values.forEach(v -> {
					try
					{
						Field specField = ConfigValue.class.getDeclaredField("spec");
						UnsafeHacks.setField(specField, v, ret);
					}
					catch (Exception e) {
						Loader.LOGGER.warn("Failed to create spec field {}!", v.toString());
						Loader.LOGGER.warn(ExceptionUtils.getStackTrace(e));
					 }
				});
				result = ret;
			}
			catch (Exception e) {
				Loader.LOGGER.warn("Failed to build IcebergConfigSpec!");
				Loader.LOGGER.warn(ExceptionUtils.getStackTrace(e));
			 }
			return result;
		}

		<T> Pair<T, IcebergConfigSpec> finish(Function<IcebergConfigSpec.Builder, T> consumer)
		{
			T o = consumer.apply(this);
			return Pair.of(o, this.finishBuild());
		}

		@Deprecated
		@Override
		public <T> Pair<T, ForgeConfigSpec> configure(Function<ForgeConfigSpec.Builder, T> consumer)
		{
			throw new UnsupportedOperationException("Configure method not supported.  Use IcebergConfig instead.");
		}

		@Deprecated
		@Override
		public ForgeConfigSpec build()
		{
			throw new UnsupportedOperationException("Build method not supported.  Use IcebergConfig instead.");
		}
	}

	/**
	 * This class is specifically meant for dynamic subconfigs--subconfigs where both keys and values are mutable.
	 */
	final public static class MutableSubconfig extends AbstractCommentedConfig
	{
		private final ConfigFormat<?> configFormat;
		private final Predicate<Object> keyValidator;
		private final Predicate<Object> valueValidator;
		private static ValueSpec defaultValueSpec = null;

		/**
		 * Creates a Subconfig by copying a config and with the specified format.
		 *
		 * @param toCopy       the config to copy
		 * @param configFormat the config's format
		 */
		MutableSubconfig(UnmodifiableConfig toCopy, ConfigFormat<?> configFormat, boolean concurrent, Predicate<Object> keyValidator, Predicate<Object> valueValidator)
		{
			super(toCopy, concurrent);
			this.configFormat = configFormat;
			this.keyValidator = keyValidator;
			this.valueValidator = valueValidator;
		}

		// Returns a value spec to use for each entry in this subconfig.
		public ValueSpec defaultValueSpec()
		{
			if (defaultValueSpec == null)
			{
				defaultValueSpec = createValueSpec(null, null, false, Object.class, () -> null, valueValidator);
			}
			return defaultValueSpec;
		}

		@Override
		public ConfigFormat<?> configFormat()
		{
			return configFormat;
		}

		public Predicate<Object> keyValidator()
		{
			return keyValidator;
		}

		public Predicate<Object> valueValidator()
		{
			return valueValidator;
		}

		/**
		 * Creates a new Subconfig with the content of the given config. The returned config will have
		 * the same format as the copied config.
		 *
		 * @param config the config to copy
		 * @return a copy of the config
		 */
		public static MutableSubconfig copy(UnmodifiableConfig config, Predicate<Object> keyValidator, Predicate<Object> valueValidator)
		{
			return new MutableSubconfig(config, config.configFormat(), false, keyValidator, valueValidator);
		}

		@Override
		public CommentedConfig createSubConfig() { throw new UnsupportedOperationException("Can't make a subconfig of a dynamic subconfig!"); }

		@Override
		public AbstractCommentedConfig clone() { throw new UnsupportedOperationException("Can't clone a dynamic subconfig!"); }
	}

	private static final Joiner DOT_JOINER = Joiner.on(".");
	private static final Splitter DOT_SPLITTER = Splitter.on(".");
	private static List<String> split(String path)
	{
		return Lists.newArrayList(DOT_SPLITTER.split(path));
	}
}