Entry.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package me.lortseam.completeconfig.data;
  2. import com.google.common.collect.Lists;
  3. import lombok.Getter;
  4. import lombok.NonNull;
  5. import lombok.extern.log4j.Log4j2;
  6. import me.lortseam.completeconfig.CompleteConfig;
  7. import me.lortseam.completeconfig.api.ConfigEntry;
  8. import me.lortseam.completeconfig.api.ConfigEntryContainer;
  9. import me.lortseam.completeconfig.data.entry.EntryOrigin;
  10. import me.lortseam.completeconfig.data.entry.Transformation;
  11. import me.lortseam.completeconfig.data.structure.DataPart;
  12. import me.lortseam.completeconfig.data.text.TranslationIdentifier;
  13. import me.lortseam.completeconfig.exception.IllegalAnnotationParameterException;
  14. import me.lortseam.completeconfig.extensions.CompleteConfigExtension;
  15. import net.minecraft.text.Text;
  16. import net.minecraft.text.TextColor;
  17. import org.apache.commons.lang3.StringUtils;
  18. import org.spongepowered.configurate.CommentedConfigurationNode;
  19. import org.spongepowered.configurate.serialize.SerializationException;
  20. import java.lang.reflect.Field;
  21. import java.lang.reflect.Method;
  22. import java.util.*;
  23. import java.util.function.Consumer;
  24. import java.util.function.UnaryOperator;
  25. @Log4j2
  26. public class Entry<T> extends EntryBase<T> implements DataPart {
  27. private static final List<Transformation> transformations = Lists.newArrayList(
  28. Transformation.ofAnnotation(ConfigEntry.BoundedInteger.class, origin -> {
  29. ConfigEntry.BoundedInteger bounds = origin.getAnnotation();
  30. return new BoundedEntry<>(origin, bounds.min(), bounds.max(), bounds.slider());
  31. }, int.class, Integer.class),
  32. Transformation.ofAnnotation(ConfigEntry.BoundedLong.class, origin -> {
  33. ConfigEntry.BoundedLong bounds = origin.getAnnotation();
  34. return new BoundedEntry<>(origin, bounds.min(), bounds.max(), bounds.slider());
  35. }, long.class, Long.class),
  36. Transformation.ofAnnotation(ConfigEntry.BoundedFloat.class, origin -> {
  37. ConfigEntry.BoundedFloat bounds = origin.getAnnotation();
  38. return new BoundedEntry<>(origin, bounds.min(), bounds.max());
  39. }, float.class, Float.class),
  40. Transformation.ofAnnotation(ConfigEntry.BoundedDouble.class, origin -> {
  41. ConfigEntry.BoundedDouble bounds = origin.getAnnotation();
  42. return new BoundedEntry<>(origin, bounds.min(), bounds.max());
  43. }, double.class, Double.class),
  44. Transformation.of(base -> Enum.class.isAssignableFrom(base.typeClass), EnumEntry::new),
  45. Transformation.ofAnnotation(ConfigEntry.Enum.class, origin -> new EnumEntry<>(origin, origin.getAnnotation().displayType()), base -> Enum.class.isAssignableFrom(base.typeClass)),
  46. Transformation.ofAnnotation(ConfigEntry.Color.class, origin -> new ColorEntry<>(origin, origin.getAnnotation().alphaMode())),
  47. Transformation.ofType(TextColor.class, origin -> new ColorEntry<>(origin, false))
  48. );
  49. private static final Map<Field, EntryBase> entries = new HashMap<>();
  50. static {
  51. CompleteConfig.getExtensions().stream().map(CompleteConfigExtension::getTransformations).filter(Objects::nonNull).forEach(extensionTransformations -> {
  52. transformations.addAll(0, extensionTransformations);
  53. });
  54. }
  55. static EntryBase<?> of(String fieldName, Class<? extends ConfigEntryContainer> parentClass) {
  56. try {
  57. return of(parentClass.getDeclaredField(fieldName));
  58. } catch (NoSuchFieldException e) {
  59. throw new RuntimeException(e);
  60. }
  61. }
  62. static EntryBase<?> of(Field field) {
  63. return entries.computeIfAbsent(field, absentField -> new Draft<>(field));
  64. }
  65. private final ConfigEntryContainer parentObject;
  66. private String customID;
  67. @Getter
  68. private final T defaultValue;
  69. private final TranslationIdentifier parentTranslation;
  70. private TranslationIdentifier customTranslation;
  71. private TranslationIdentifier[] customTooltipTranslation;
  72. private boolean forceUpdate;
  73. private boolean requiresRestart;
  74. private String comment;
  75. private final UnaryOperator<T> modifier;
  76. private final List<Listener<T>> listeners = new ArrayList<>();
  77. protected Entry(EntryOrigin origin, UnaryOperator<T> modifier) {
  78. super(origin.getField());
  79. parentObject = origin.getParentObject();
  80. parentTranslation = origin.getParentTranslation();
  81. this.modifier = modifier;
  82. defaultValue = getValue();
  83. }
  84. protected Entry(EntryOrigin origin) {
  85. this(origin, null);
  86. }
  87. public T getValue() {
  88. if (update()) {
  89. return getValue();
  90. }
  91. return getFieldValue();
  92. }
  93. private T getFieldValue() {
  94. try {
  95. return (T) Objects.requireNonNull(field.get(parentObject), field.toString());
  96. } catch (IllegalAccessException e) {
  97. throw new RuntimeException(e);
  98. }
  99. }
  100. public void setValue(@NonNull T value) {
  101. update(value);
  102. }
  103. private boolean update() {
  104. return update(getFieldValue());
  105. }
  106. private boolean update(T value) {
  107. if (modifier != null) {
  108. value = modifier.apply(value);
  109. }
  110. if (value.equals(getFieldValue())) {
  111. return false;
  112. }
  113. set(value);
  114. return true;
  115. }
  116. private void set(T value) {
  117. if (listeners.stream().noneMatch(listener -> listener.getParentObject() == parentObject) || forceUpdate) {
  118. try {
  119. field.set(parentObject, value);
  120. } catch (IllegalAccessException e) {
  121. throw new RuntimeException(e);
  122. }
  123. }
  124. for (Listener<T> listener : listeners) {
  125. listener.invoke(value);
  126. }
  127. }
  128. void addListener(Method method, ConfigEntryContainer parentObject) {
  129. listeners.add(new Listener<>(method, parentObject));
  130. }
  131. String getID() {
  132. return customID != null ? customID : field.getName();
  133. }
  134. TranslationIdentifier getTranslation() {
  135. return customTranslation != null ? customTranslation : parentTranslation.append(getID());
  136. }
  137. public Text getText() {
  138. return getTranslation().toText();
  139. }
  140. public Optional<Text[]> getTooltip() {
  141. TranslationIdentifier[] translation;
  142. if (customTooltipTranslation != null) {
  143. translation = customTooltipTranslation;
  144. } else {
  145. Optional<TranslationIdentifier[]> defaultTooltip = getTranslation().appendTooltip();
  146. if (defaultTooltip.isPresent()) {
  147. translation = defaultTooltip.get();
  148. } else {
  149. return Optional.empty();
  150. }
  151. }
  152. return Optional.of(Arrays.stream(translation).map(TranslationIdentifier::toText).toArray(Text[]::new));
  153. }
  154. public boolean requiresRestart() {
  155. return requiresRestart;
  156. }
  157. void resolve(Field field) {
  158. if (field.isAnnotationPresent(ConfigEntry.class)) {
  159. ConfigEntry annotation = field.getDeclaredAnnotation(ConfigEntry.class);
  160. String id = annotation.value();
  161. if (!StringUtils.isBlank(id)) {
  162. customID = id;
  163. }
  164. String customTranslationKey = annotation.translationKey();
  165. if (!StringUtils.isBlank(customTranslationKey)) {
  166. customTranslation = parentTranslation.root().appendKey(customTranslationKey);
  167. }
  168. String[] customTooltipTranslationKeys = annotation.tooltipTranslationKeys();
  169. if (customTooltipTranslationKeys.length > 0) {
  170. if (Arrays.stream(customTooltipTranslationKeys).anyMatch(StringUtils::isBlank)) {
  171. throw new IllegalAnnotationParameterException("Entry tooltip translation key(s) must not be blank");
  172. }
  173. customTooltipTranslation = Arrays.stream(customTooltipTranslationKeys).map(key -> parentTranslation.root().appendKey(key)).toArray(TranslationIdentifier[]::new);
  174. }
  175. forceUpdate = annotation.forceUpdate();
  176. requiresRestart = annotation.requiresRestart();
  177. String comment = annotation.comment();
  178. if (!StringUtils.isBlank(comment)) {
  179. this.comment = comment;
  180. }
  181. }
  182. }
  183. @Override
  184. public void apply(CommentedConfigurationNode node) {
  185. try {
  186. T value = (T) node.get(type);
  187. // value could be null despite the virtual() check (see https://github.com/SpongePowered/Configurate/issues/187)
  188. if(value == null) return;
  189. setValue(value);
  190. } catch (SerializationException e) {
  191. logger.error("[CompleteConfig] Failed to apply value to entry!", e);
  192. }
  193. }
  194. @Override
  195. public void fetch(CommentedConfigurationNode node) {
  196. try {
  197. node.set(type, getValue());
  198. if (comment != null) {
  199. node.comment(comment);
  200. }
  201. } catch (SerializationException e) {
  202. logger.error("[CompleteConfig] Failed to fetch value from entry!", e);
  203. }
  204. }
  205. @Override
  206. void interact(Consumer<Entry<T>> interaction) {
  207. interaction.accept(this);
  208. }
  209. static class Draft<T> extends EntryBase<T> {
  210. static <T> Draft<T> of(Field field) {
  211. EntryBase<T> accessor = (EntryBase<T>) Entry.of(field);
  212. if (!(accessor instanceof Draft)) {
  213. throw new UnsupportedOperationException("Entry draft of field " + field + " was already built");
  214. }
  215. return (Draft<T>) accessor;
  216. }
  217. private final List<Consumer<Entry<T>>> interactions = new ArrayList<>();
  218. private Draft(Field field) {
  219. super(field);
  220. }
  221. @Override
  222. void interact(Consumer<Entry<T>> interaction) {
  223. interactions.add(interaction);
  224. }
  225. Entry<T> build(ConfigEntryContainer parentObject, TranslationIdentifier parentTranslation) {
  226. Entry<T> entry = transformations.stream().filter(transformation -> transformation.test(this)).findFirst().orElse(Transformation.of(base -> true, Entry::new)).transform(this, parentObject, parentTranslation);
  227. for (Consumer<Entry<T>> interaction : interactions) {
  228. interaction.accept(entry);
  229. }
  230. entries.put(field, entry);
  231. return entry;
  232. }
  233. }
  234. }