Entry.java 10 KB

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