Compare commits

...

52 Commits

Author SHA1 Message Date
Martin Prokoph
3db1c1eb23 fix: crash on servers
- This makes overriding the screen less flexible, but out of all options, this was the best way to do it. Previously, the `@EnvType` annotation took care of keeping this out of the server code, but NeoForge decided to break perfectly functional behaviour once again, requiring me to remove the annotations 🫠
2025-10-03 14:55:40 +02:00
Martin Prokoph
c07c466398 fix: make tooltip translation key respect custom entry names 2025-10-02 16:52:30 +02:00
Martin Prokoph
16710282ba feat: better UX and accessibility
Closes #118
Action buttons now show tooltips explaining their functionality. These will also be read by the narrator.
2025-10-01 18:18:05 +02:00
Martin Prokoph
98859fbc28 feat: support NeoForge on 1.21.9
`@Environment` annotations had to be removed because NeoForge doesn't like them. Also, this brings down file size :)
2025-10-01 17:50:18 +02:00
Martin Prokoph
72a403080c chore: update to 1.21.9-rc1 2025-09-27 16:26:08 +02:00
Martin Prokoph
44b92726ed clean: even more refactoring 2025-09-27 16:07:50 +02:00
Martin Prokoph
b8e5ab7907 fix: centered multiline comments
Closes #117
2025-09-27 16:05:32 +02:00
Martin Prokoph
bb18e1a00a clean: additional refactoring 2025-09-27 15:47:38 +02:00
Martin Prokoph
0020eb86b6 clean: extract inner classes 2025-09-26 20:57:23 +02:00
Martin Prokoph
284037cc6c clean: refactoring (less static methods/fields) 2025-09-26 20:03:59 +02:00
Martin Prokoph
58970157b4 feat: support for 1.21.9 (pre3) 2025-09-23 17:06:35 +02:00
Martin Prokoph
a3c92223d3 Merge pull request #116 from Jaffe2718/architectury-1.21.6
Fix bugs & Better test
2025-09-23 15:38:26 +02:00
Martin Prokoph
78d1ca8de4 Merge branch 'dev/1.21.9' into architectury-1.21.6 2025-09-23 15:37:51 +02:00
Martin Prokoph
bee3553498 chore: update gradle config for 1.21.9 2025-09-23 15:36:06 +02:00
Jaffe2718
c775a9d221 - fix: NullPointerException when the config class of mod updated
- alter: better test code in `common/src/test`, `neoforge/src/test` and `fabric/src/test`, run `Test Minecraft Client(:fabric)` or `Test Minecraft Client(:neoforge)` for testing
2025-09-11 11:48:26 +08:00
Martin Prokoph
78c462dc1c Merge pull request #108 from Texaliuz/patch-3
Update es_ar.json
2025-08-23 19:45:24 +02:00
Martin Prokoph
b0e4a44a16 Merge pull request #109 from Texaliuz/patch-4
Update es_ar.json
2025-08-23 19:44:41 +02:00
Texaliuz
66b3ffbceb Update es_ar.json 2025-07-16 00:47:30 -03:00
Texaliuz
0c83a0902c Update es_ar.json 2025-07-16 00:43:57 -03:00
Martin Prokoph
9602736335 fix: screen titles not showing 2025-06-17 23:44:21 +02:00
Martin Prokoph
30d213b92c feat: NeoForge 1.21.6 2025-06-17 18:00:22 +02:00
Martin Prokoph
b61b2cdf12 port: update to full 1.21.6 2025-06-17 17:55:20 +02:00
Martin Prokoph
bcde119f23 fix: correctly wrap option text labels 2025-06-17 17:54:53 +02:00
Martin Prokoph
b08e38ae11 port: 1.21.6 (pre1) 2025-05-28 23:28:03 +02:00
Martin Prokoph
a1ad6dd1f0 chore: bump version 2025-05-13 12:05:21 +02:00
Martin Prokoph
7ddfadd4ec clean: some code cleanup 2025-05-13 12:05:07 +02:00
Martin Prokoph
6bbaf1ab5d optimize: remove unchanged translations in es_ar 2025-05-12 22:58:22 +02:00
Martin Prokoph
f1fe868192 feat: remove checkbox widgets
- As voted on in a recent MidnightDust Discord Poll
2025-05-12 22:57:15 +02:00
Martin Prokoph
74d8800fa5 Merge pull request #102 from Texaliuz/patch-1
🌐 add Argentine Spanish localization (for example)
2025-05-12 22:48:52 +02:00
Martin Prokoph
3e2ceb09c6 Merge pull request #103 from Texaliuz/patch-2
🌐 add Argentine Spanish localization
2025-05-12 22:48:05 +02:00
Martin Prokoph
f1a3b2c634 Merge pull request #101 from joriskleiber/architectury-1.21.4
Respect TranslatableOption on enums
2025-05-12 22:47:11 +02:00
Martin Prokoph
f9fc657695 Merge branch 'architectury-1.21.4' into architectury-1.21.4 2025-05-12 22:46:51 +02:00
Martin Prokoph
7a15f1fb8d fix: conditions are not applied in default tab
- Closes #104
2025-05-12 18:53:54 +02:00
Martin Prokoph
b2c24010da fix: adjust option title position 2025-05-12 12:45:27 +02:00
Martin Prokoph
302728192f feat: new method to manually add widgets
- Also added a keybind widget as an example for this.
It will not be included in the base jar, but can be manually copied into mods that rely on it.
2025-05-12 12:35:20 +02:00
Texaliuz
3eb345ce3c Update es_ar.json
Minor corrections
2025-05-04 13:10:32 -03:00
Texaliuz
f986d10e1f Translation into Argentine Spanish (es_ar) for MidnightLib
Hello, I would appreciate if you could add the translation to my language (es_ar) for version 1.21.1 please and thank you.
2025-04-29 19:45:28 -03:00
Texaliuz
03223b8d9b Translation into Argentine Spanish (es_ar) for MidnightLib
Hello, I would appreciate if you could add the translation to my language (es_ar) for version 1.21.1 please and thank you.
2025-04-29 19:41:32 -03:00
Joris Kleiber
daec2a3187 feat: respect TranslatableOption on enums 2025-04-26 01:10:57 +02:00
Martin Prokoph
6693580cfa Merge pull request #99 from TeamMidnightDust/dev
MidnightLib 1.7.2 – Clickable URLs in Comments and added Checkbox buttons
2025-04-21 11:04:15 +02:00
Martin Prokoph
356064b052 chore: bump version 2025-04-21 10:46:02 +02:00
Martin Prokoph
06ef4fdcf7 clean: remove unused import 2025-04-21 10:45:02 +02:00
Martin Prokoph
82889b8c06 docs: improve JavaDocs 2025-04-21 10:43:40 +02:00
Martin Prokoph
e58c7fc0fd feat: improve URL handling
- Uses the `open` method of `ConfirmLinkScreen` instead of manually instantiating it
- Also re-add the `requiredMod` field for `@Comment` to prevent mods that haven't adjusted yet from outright crashing
2025-04-18 12:37:46 +02:00
Martin Prokoph
4def02af12 Merge pull request #98 from Jaffe2718/dev
1.7.2-rc.2
2025-04-18 12:20:15 +02:00
Jaffe2718
5905eed58f - feat: add clickable url for @Comment
- chore: bump version `1.7.2-rc.2`
2025-04-18 17:01:35 +08:00
Martin Prokoph
0297d91e70 feat: 'visibleButLocked' now applies for all buttons 2025-04-14 18:02:56 +02:00
Martin Prokoph
3e6a72cda4 feat: checkbox buttons next to boolean yes/no text buttons 2025-04-14 17:49:02 +02:00
Martin Prokoph
dcf0dbcaab fix: improve identifier crash fix
Now uses Minecraft's built-in Identifier.validate function to check validity before applying changes
2025-04-14 17:47:11 +02:00
Martin Prokoph
dd128bd2d0 Merge pull request #97 from Jaffe2718/architectury-1.21.4
1.7.2-rc.1
2025-04-14 16:39:58 +02:00
Jaffe2718
517d3c8a0e - adjust: optimize code & add comment 2025-04-14 20:05:21 +08:00
Jaffe2718
e046463f66 - rollback: boolean field (CheckboxWidget -> ButtonWidget) 2025-04-14 20:00:51 +08:00
35 changed files with 1122 additions and 548 deletions

View File

@@ -3,7 +3,7 @@ import groovy.json.JsonOutput
plugins { plugins {
id "architectury-plugin" version "3.4-SNAPSHOT" id "architectury-plugin" version "3.4-SNAPSHOT"
id "dev.architectury.loom" version "1.7-SNAPSHOT" apply false id "dev.architectury.loom" version "1.11-SNAPSHOT" apply false
id "me.shedaniel.unified-publishing" version "0.1.+" apply false id "me.shedaniel.unified-publishing" version "0.1.+" apply false
id 'com.github.johnrengelman.shadow' version '8.1.1' apply false id 'com.github.johnrengelman.shadow' version '8.1.1' apply false
} }

View File

@@ -1,3 +1,7 @@
plugins {
id 'java'
}
architectury { architectury {
common(rootProject.enabled_platforms.split(",")) common(rootProject.enabled_platforms.split(","))
} }
@@ -21,3 +25,16 @@ publishing {
// Add repositories to publish to here. // Add repositories to publish to here.
} }
} }
configurations {
testOutput.extendsFrom(testImplementation)
}
tasks.register('testJar', Jar) {
from sourceSets.test.output
archiveClassifier = 'tests'
}
artifacts {
testOutput testJar
}

View File

@@ -3,8 +3,7 @@ package eu.midnightdust.core;
import eu.midnightdust.core.config.MidnightLibConfig; import eu.midnightdust.core.config.MidnightLibConfig;
import eu.midnightdust.lib.config.AutoCommand; import eu.midnightdust.lib.config.AutoCommand;
import eu.midnightdust.lib.config.MidnightConfig; import eu.midnightdust.lib.config.MidnightConfig;
import net.fabricmc.api.EnvType; import net.minecraft.util.Util;
import net.fabricmc.api.Environment;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -13,24 +12,23 @@ import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static net.minecraft.client.MinecraftClient.IS_SYSTEM_MAC;
public class MidnightLib { public class MidnightLib {
public static List<String> hiddenMods = new ArrayList<>(); public static List<String> hiddenMods = new ArrayList<>();
public static final String MOD_ID = "midnightlib"; public static final String MOD_ID = "midnightlib";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Environment(EnvType.CLIENT)
public static void onInitializeClient() { public static void onInitializeClient() {
try { if (!IS_SYSTEM_MAC) { try {
System.setProperty("java.awt.headless", "false"); if (Util.getOperatingSystem() != Util.OperatingSystem.OSX) {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); System.setProperty("java.awt.headless", "false");
}} catch (Exception | Error e) { LOGGER.error("Error setting system look and feel", e); } UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
} catch (Exception | Error e) { LOGGER.error("Error setting system look and feel", e); }
MidnightLibConfig.init(MOD_ID, MidnightLibConfig.class); MidnightLibConfig.init(MOD_ID, MidnightLibConfig.class);
} }
public static void registerAutoCommand() { public static void registerAutoCommand() {
MidnightConfig.configClass.forEach((modid, config) -> { MidnightConfig.configInstances.forEach((modid, config) -> {
for (Field field : config.getFields()) { for (Field field : config.configClass.getFields()) {
if (field.isAnnotationPresent(MidnightConfig.Entry.class) && !field.isAnnotationPresent(MidnightConfig.Client.class) && !field.isAnnotationPresent(MidnightConfig.Hidden.class)) if (field.isAnnotationPresent(MidnightConfig.Entry.class) && !field.isAnnotationPresent(MidnightConfig.Client.class) && !field.isAnnotationPresent(MidnightConfig.Hidden.class))
new AutoCommand(field, modid); new AutoCommand(field, modid);
} }

View File

@@ -2,8 +2,6 @@ package eu.midnightdust.core.screen;
import eu.midnightdust.core.MidnightLib; import eu.midnightdust.core.MidnightLib;
import eu.midnightdust.lib.config.MidnightConfig; import eu.midnightdust.lib.config.MidnightConfig;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.ButtonWidget;
@@ -15,9 +13,8 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import static eu.midnightdust.lib.config.MidnightConfig.MidnightConfigListWidget; import eu.midnightdust.lib.config.MidnightConfigListWidget;
@Environment(EnvType.CLIENT)
public class MidnightConfigOverviewScreen extends Screen { public class MidnightConfigOverviewScreen extends Screen {
public MidnightConfigOverviewScreen(Screen parent) { public MidnightConfigOverviewScreen(Screen parent) {
@@ -32,7 +29,7 @@ public class MidnightConfigOverviewScreen extends Screen {
this.addDrawableChild(ButtonWidget.builder(ScreenTexts.DONE, (button) -> Objects.requireNonNull(client).setScreen(parent)).dimensions(this.width / 2 - 100, this.height - 26, 200, 20).build()); this.addDrawableChild(ButtonWidget.builder(ScreenTexts.DONE, (button) -> Objects.requireNonNull(client).setScreen(parent)).dimensions(this.width / 2 - 100, this.height - 26, 200, 20).build());
this.addSelectableChild(this.list = new MidnightConfigListWidget(this.client, this.width, this.height - 57, 24, 25)); this.addSelectableChild(this.list = new MidnightConfigListWidget(this.client, this.width, this.height - 57, 24, 25));
List<String> sortedMods = new ArrayList<>(MidnightConfig.configClass.keySet()); List<String> sortedMods = new ArrayList<>(MidnightConfig.configInstances.keySet());
Collections.sort(sortedMods); Collections.sort(sortedMods);
sortedMods.forEach((modid) -> { sortedMods.forEach((modid) -> {
if (!MidnightLib.hiddenMods.contains(modid)) { if (!MidnightLib.hiddenMods.contains(modid)) {
@@ -45,6 +42,6 @@ public class MidnightConfigOverviewScreen extends Screen {
public void render(DrawContext context, int mouseX, int mouseY, float delta) { public void render(DrawContext context, int mouseX, int mouseY, float delta) {
super.render(context, mouseX, mouseY, delta); super.render(context, mouseX, mouseY, delta);
this.list.render(context, mouseX, mouseY, delta); this.list.render(context, mouseX, mouseY, delta);
context.drawCenteredTextWithShadow(textRenderer, title, width / 2, 10, 0xFFFFFF); context.drawCenteredTextWithShadow(textRenderer, title, width / 2, 10, 0xFFFFFFFF);
} }
} }

View File

@@ -0,0 +1,78 @@
package eu.midnightdust.lib.config;
import com.google.common.collect.Lists;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.Click;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.Element;
import net.minecraft.client.gui.Selectable;
import net.minecraft.client.gui.screen.ConfirmLinkScreen;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.gui.widget.ElementListWidget;
import net.minecraft.client.gui.widget.MultilineTextWidget;
import net.minecraft.registry.Registries;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import java.util.List;
public class ButtonEntry extends ElementListWidget.Entry<ButtonEntry> {
private static final TextRenderer textRenderer = MinecraftClient.getInstance().textRenderer;
public final Text text;
public final List<ClickableWidget> buttons;
public final EntryInfo info;
public boolean centered = false;
public MultilineTextWidget title;
public ButtonEntry(List<ClickableWidget> buttons, Text text, EntryInfo info) {
this.buttons = buttons;
this.text = text;
this.info = info;
if (info != null && info.comment != null)
this.centered = info.comment.centered();
int scaledWidth = MinecraftClient.getInstance().getWindow().getScaledWidth();
if (text != null && (!text.getString().contains("spacer") || !buttons.isEmpty())) {
title = new MultilineTextWidget(12, 0, Text.of(text), textRenderer).setCentered(centered);
if (info != null)
title.setTooltip(info.getTooltip(false));
title.setMaxWidth(!buttons.isEmpty() ? buttons.get(buttons.size() > 2 ? buttons.size() - 1 : 0).getX() - 16 : scaledWidth - 24);
if (centered) title.setX(scaledWidth / 2 - (title.getWidth() / 2));
}
}
public void render(DrawContext context, int mouseX, int mouseY, boolean hovered, float tickDelta) {
buttons.forEach(b -> {
b.setY(this.getY());
b.render(context, mouseX, mouseY, tickDelta);
});
if (title != null) {
title.setY(this.getY() + 5);
title.render(context, mouseX, mouseY, tickDelta);
if (info.entry != null && !this.buttons.isEmpty() && this.buttons.getFirst() instanceof ClickableWidget widget) {
int idMode = this.info.entry.idMode();
if (idMode != -1) context.drawItem(idMode == 0 ?
Registries.ITEM.get(Identifier.tryParse(this.info.tempValue)).getDefaultStack()
: Registries.BLOCK.get(Identifier.tryParse(this.info.tempValue)).asItem().getDefaultStack(),
widget.getX() + widget.getWidth() - 18, this.getY() + 2);
}
}
}
@Override
public boolean mouseClicked(Click click, boolean doubled) {
if (this.info != null && this.info.comment != null && !this.info.comment.url().isBlank())
ConfirmLinkScreen.open(MinecraftClient.getInstance().currentScreen, this.info.comment.url(), true);
return super.mouseClicked(click, doubled);
}
public List<? extends Element> children() {
return Lists.newArrayList(buttons);
}
public List<? extends Selectable> selectableChildren() {
return Lists.newArrayList(buttons);
}
}

View File

@@ -0,0 +1,104 @@
package eu.midnightdust.lib.config;
import eu.midnightdust.lib.util.PlatformFunctions;
import net.minecraft.client.gui.tab.Tab;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.text.Text;
import java.lang.reflect.Field;
import java.util.List;
public class EntryInfo {
public MidnightConfig.Entry entry;
public MidnightConfig.Comment comment;
public MidnightConfig.Condition[] conditions;
public final Field field;
public final Class<?> dataType;
public final String modid, fieldName, translationKey;
int listIndex;
Object defaultValue, value, function;
String tempValue; // The value visible in the config screen
boolean inLimits = true;
Text error;
ClickableWidget actionButton; // color picker button / explorer button
Tab tab;
boolean conditionsMet = true;
public EntryInfo(Field field, String modid) {
this.field = field;
this.modid = modid;
if (field != null) {
this.fieldName = field.getName();
this.dataType = MidnightConfig.getUnderlyingType(field);
this.entry = field.getAnnotation(MidnightConfig.Entry.class);
this.comment = field.getAnnotation(MidnightConfig.Comment.class);
this.conditions = field.getAnnotationsByType(MidnightConfig.Condition.class);
} else {
this.fieldName = "";
this.dataType = null;
}
if (entry != null && !entry.name().isEmpty())
this.translationKey = entry.name();
else if (comment != null && !comment.name().isEmpty())
this.translationKey = comment.name();
else this.translationKey = modid + ".midnightconfig." + fieldName;
}
public void setValue(Object value) {
if (this.field.getType() != List.class) {
this.value = value;
this.tempValue = value.toString();
} else {
writeList(this.listIndex, value);
this.tempValue = toTemporaryValue();
}
}
public String toTemporaryValue() {
if (this.field.getType() != List.class) return this.value.toString();
else try {
return ((List<?>) this.value).get(this.listIndex).toString();
} catch (Exception ignored) {
return "";
}
}
public void updateFieldValue() {
try {
if (this.field.get(null) != value) MidnightConfig.entries.values().forEach(EntryInfo::updateConditions);
this.field.set(null, this.value);
} catch (IllegalAccessException ignored) {
}
}
public void updateConditions() {
boolean prevConditionState = this.conditionsMet;
if (this.conditions.length > 0) this.conditionsMet = true; // reset conditions
for (MidnightConfig.Condition condition : this.conditions) {
//noinspection ConstantValue
if (!condition.requiredModId().isEmpty() && !PlatformFunctions.isModLoaded(condition.requiredModId()))
this.conditionsMet = false;
String requiredOption = condition.requiredOption().contains(":") ? condition.requiredOption() : (this.modid + ":" + condition.requiredOption());
if (MidnightConfig.entries.get(requiredOption) instanceof EntryInfo info)
this.conditionsMet &= List.of(condition.requiredValue()).contains(info.tempValue);
if (!this.conditionsMet) break;
}
if (prevConditionState != this.conditionsMet) MidnightConfig.configInstances.get(modid).reloadScreen = true;
}
public <T> void writeList(int index, T value) {
//noinspection unchecked
var list = (List<T>) this.value;
if (index >= list.size())
list.add(value);
else list.set(index, value);
}
public Tooltip getTooltip(boolean isButton) {
String key = translationKey + (!isButton ? ".label" : "") + ".tooltip";
return Tooltip.of(isButton && this.error != null ? this.error : I18n.hasTranslation(key) ? Text.translatable(key) : Text.empty());
}
}

View File

@@ -1,36 +1,34 @@
package eu.midnightdust.lib.config; package eu.midnightdust.lib.config;
import com.google.common.collect.Lists; import com.google.gson.*;
import com.google.gson.*; import com.google.gson.stream.*; import com.google.gson.stream.*;
import eu.midnightdust.lib.util.PlatformFunctions; import eu.midnightdust.lib.util.PlatformFunctions;
import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.MinecraftClient; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.widget.*;
import net.minecraft.client.gui.Element; import net.minecraft.client.gui.Selectable; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.tab.GridScreenTab; import net.minecraft.client.gui.tab.Tab; import net.minecraft.client.gui.tab.TabManager;
import net.minecraft.client.gui.tooltip.Tooltip; import net.minecraft.client.gui.widget.*;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.resource.language.I18n; import net.minecraft.client.resource.language.I18n;
import net.minecraft.registry.Registries; import net.minecraft.text.Style;
import net.minecraft.screen.ScreenTexts; import net.minecraft.text.Text;
import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.util.*;
import net.minecraft.util.Formatting; import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.*;
import java.awt.Color; import java.awt.Color;
import java.io.IOException; import java.io.IOException;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Field;
import java.nio.file.Files; import java.nio.file.Path; import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static net.minecraft.client.MinecraftClient.IS_SYSTEM_MAC;
/** MidnightConfig by Martin "Motschen" Prokoph /** MidnightConfig by Martin "Motschen" Prokoph
* Single class config library - feel free to copy! * Minimalist config library - feel free to copy!
* Based on <a href="https://github.com/Minenash/TinyConfig">...</a> * Originally based on <a href="https://github.com/Minenash/TinyConfig">...</a>
* Credits to Minenash */ * Credits to Minenash */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -38,146 +36,78 @@ public abstract class MidnightConfig {
private static final Pattern INTEGER_ONLY = Pattern.compile("(-?[0-9]*)"); private static final Pattern INTEGER_ONLY = Pattern.compile("(-?[0-9]*)");
private static final Pattern DECIMAL_ONLY = Pattern.compile("-?(\\d+\\.?\\d*|\\d*\\.?\\d+|\\.)"); private static final Pattern DECIMAL_ONLY = Pattern.compile("-?(\\d+\\.?\\d*|\\d*\\.?\\d+|\\.)");
private static final Pattern HEXADECIMAL_ONLY = Pattern.compile("(-?[#0-9a-fA-F]*)"); private static final Pattern HEXADECIMAL_ONLY = Pattern.compile("(-?[#0-9a-fA-F]*)");
private static final LinkedHashMap<String, EntryInfo> entries = new LinkedHashMap<>(); // modid:fieldName -> EntryInfo
private static boolean reloadScreen = false;
public static class EntryInfo {
public Entry entry;
public Comment comment;
public Condition[] conditions;
public final Field field;
public final Class<?> dataType;
public final String modid, fieldName;
int listIndex;
Object defaultValue, value, function;
String tempValue; // The value visible in the config screen
boolean inLimits = true;
Text name, error;
ClickableWidget actionButton; // color picker button / explorer button
Tab tab;
boolean conditionsMet = true;
public EntryInfo(Field field, String modid) {
this.field = field; this.modid = modid;
if (field != null) {
this.fieldName = field.getName();
this.dataType = getUnderlyingType(field);
this.entry = field.getAnnotation(Entry.class);
this.comment = field.getAnnotation(Comment.class);
this.conditions = field.getAnnotationsByType(Condition.class);
} else {
this.fieldName = ""; this.dataType = null;
}
if (entry != null && !entry.name().isEmpty()) this.name = Text.translatable(entry.name());
else if (comment != null && !comment.name().isEmpty()) this.name = Text.translatable(comment.name());
}
public void setValue(Object value) {
if (this.field.getType() != List.class) { this.value = value;
this.tempValue = value == null ? "" : value.toString(); // fix bug+: illegal Identifier cannot input character
} else { writeList(this.listIndex, value);
this.tempValue = toTemporaryValue(); }
}
public String toTemporaryValue() {
if (this.field.getType() != List.class) return this.value == null ? "" : this.value.toString(); // fix bug+: illegal Identifier cannot input character
else try { return ((List<?>) this.value).get(this.listIndex).toString(); } catch (Exception ignored) {return "";}
}
public void updateFieldValue() {
try {
if (this.field.get(null) != value) entries.values().forEach(EntryInfo::updateConditions);
this.field.set(null, this.value);
} catch (IllegalAccessException ignored) {}
}
@SuppressWarnings("ConstantValue") //pertains to requiredModLoaded
public void updateConditions() {
boolean prevConditionState = this.conditionsMet;
if (this.conditions.length > 0) this.conditionsMet = true; // reset conditions
for (Condition condition : this.conditions) {
if (!condition.requiredModId().isEmpty() && !PlatformFunctions.isModLoaded(condition.requiredModId()))
this.conditionsMet = false;
String requiredOption = condition.requiredOption().contains(":") ? condition.requiredOption() : (this.modid + ":" + condition.requiredOption());
if (entries.get(requiredOption) instanceof EntryInfo info)
this.conditionsMet &= List.of(condition.requiredValue()).contains(info.tempValue);
if (!this.conditionsMet) break;
}
if (prevConditionState != this.conditionsMet) reloadScreen = true;
}
public <T> void writeList(int index, T value) {
var list = (List<T>) this.value;
if (index >= list.size()) list.add(value);
else list.set(index, value);
}
}
public static final Map<String, Class<? extends MidnightConfig>> configClass = new HashMap<>();
private static Path path;
private static final Gson gson = new GsonBuilder() private static final Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.TRANSIENT).excludeFieldsWithModifiers(Modifier.PRIVATE) .excludeFieldsWithModifiers(Modifier.TRANSIENT).excludeFieldsWithModifiers(Modifier.PRIVATE).excludeFieldsWithModifiers(Modifier.FINAL)
.addSerializationExclusionStrategy(new NonEntryExclusionStrategy()) .addSerializationExclusionStrategy(new ExclusionStrategy() {
public boolean shouldSkipClass(Class<?> clazz) { return false; }
public boolean shouldSkipField(FieldAttributes fieldAttributes) { return fieldAttributes.getAnnotation(Entry.class) == null; }
})
.registerTypeAdapter(Identifier.class, new TypeAdapter<Identifier>() { .registerTypeAdapter(Identifier.class, new TypeAdapter<Identifier>() {
public void write(JsonWriter out, Identifier id) throws IOException { out.value(id.toString()); } public void write(JsonWriter out, Identifier id) throws IOException { out.value(id.toString()); }
public Identifier read(JsonReader in) throws IOException { return Identifier.of(in.nextString()); } public Identifier read(JsonReader in) throws IOException { return Identifier.of(in.nextString()); }
}).setPrettyPrinting().create(); }).setPrettyPrinting().create();
@SuppressWarnings("unused") // Utility for mod authors protected static final LinkedHashMap<String, EntryInfo> entries = new LinkedHashMap<>(); // modid:fieldName -> EntryInfo
public static @Nullable Object getDefaultValue(String modid, String entry) {
String key = modid + ":" + entry; public static final Map<String, MidnightConfig> configInstances = new HashMap<>();
return entries.containsKey(key) ? entries.get(key).defaultValue : null;
} protected String modid;
public static void loadValuesFromJson(String modid) { protected boolean reloadScreen = false;
try { gson.fromJson(Files.newBufferedReader(path), configClass.get(modid)); } public Class<? extends MidnightConfig> configClass;
catch (Exception e) { write(modid); }
entries.values().forEach(info -> { public static <T extends MidnightConfig> T createInstance(String modid, Class<? extends MidnightConfig> configClass) { // This is basically an argumented constructor without the requirement of having one in each config class
if (info.field != null && info.entry != null) { try {
try { T instance = (T) configClass.getDeclaredConstructor().newInstance();
info.value = info.field.get(null); instance.modid = modid;
info.tempValue = info.toTemporaryValue(); instance.configClass = configClass;
info.updateConditions(); configInstances.put(modid, instance);
} catch (IllegalAccessException ignored) {} return instance;
} }
}); catch (Exception e) { throw new RuntimeException(e); }
} }
public static void init(String modid, Class<? extends MidnightConfig> config) { public static void init(String modid, Class<? extends MidnightConfig> config) {
path = PlatformFunctions.getConfigDirectory().resolve(modid + ".json"); MidnightConfig instance = createInstance(modid, config);
configClass.put(modid, config);
for (Field field : config.getFields()) { for (Field field : config.getFields()) {
EntryInfo info = new EntryInfo(field, modid); //noinspection ConstantValue
if ((field.isAnnotationPresent(Entry.class) || field.isAnnotationPresent(Comment.class)) && !field.isAnnotationPresent(Server.class) && !field.isAnnotationPresent(Hidden.class) && PlatformFunctions.isClientEnv()) if ((field.isAnnotationPresent(Entry.class) || field.isAnnotationPresent(Comment.class))
initClient(modid, field, info); && !field.isAnnotationPresent(Server.class)
if (field.isAnnotationPresent(Entry.class)) && !field.isAnnotationPresent(Hidden.class)
try { info.defaultValue = field.get(null); && PlatformFunctions.isClientEnv())
} catch (IllegalAccessException ignored) {} instance.addClientEntry(field, new EntryInfo(field, modid));
} }
loadValuesFromJson(modid); instance.loadValuesFromJson();
} }
@Environment(EnvType.CLIENT)
private static void initClient(String modid, Field field, EntryInfo info) { public void addClientEntry(Field field, EntryInfo info) {
Entry e = info.entry; Entry e = info.entry;
String key = modid + ":" + field.getName(); if (e != null && info.dataType != null) {
if (e != null) {
if (info.dataType == int.class) textField(info, Integer::parseInt, INTEGER_ONLY, (int) e.min(), (int) e.max(), true); if (info.dataType == int.class) textField(info, Integer::parseInt, INTEGER_ONLY, (int) e.min(), (int) e.max(), true);
else if (info.dataType == float.class) textField(info, Float::parseFloat, DECIMAL_ONLY, (float) e.min(), (float) e.max(), false); else if (info.dataType == float.class) textField(info, Float::parseFloat, DECIMAL_ONLY, (float) e.min(), (float) e.max(), false);
else if (info.dataType == double.class) textField(info, Double::parseDouble, DECIMAL_ONLY, e.min(), e.max(), false); else if (info.dataType == double.class) textField(info, Double::parseDouble, DECIMAL_ONLY, e.min(), e.max(), false);
else if (info.dataType == String.class || info.dataType == Identifier.class) textField(info, String::length, null, Math.min(e.min(), 0), Math.max(e.max(), 1), true); else if (info.dataType == String.class || info.dataType == Identifier.class) textField(info, String::length, null, Math.min(e.min(), 0), Math.max(e.max(), 1), true);
else if (info.dataType == boolean.class) { else if (info.dataType == boolean.class) {
info.function = (CheckboxWidget.Callback) (ch, b) -> info.setValue(b); Function<Object, Text> func = value -> Text.translatable((Boolean) value ? "gui.yes" : "gui.no").formatted((Boolean) value ? Formatting.GREEN : Formatting.RED);
info.function = new AbstractMap.SimpleEntry<ButtonWidget.PressAction, Function<Object, Text>>(button -> {
info.setValue(!(Boolean) info.value); button.setMessage(func.apply(info.value));
}, func);
} else if (info.dataType.isEnum()) { } else if (info.dataType.isEnum()) {
List<?> values = Arrays.asList(field.getType().getEnumConstants()); List<?> values = Arrays.asList(field.getType().getEnumConstants());
Function<Object, Text> func = value -> { Function<Object, Text> func = value -> getEnumTranslatableText(value, info);
String translationKey = modid + ".midnightconfig.enum." + info.dataType.getSimpleName() + "." + info.toTemporaryValue();
return I18n.hasTranslation(translationKey) ? Text.translatable(translationKey) : Text.literal(info.toTemporaryValue());
};
info.function = new AbstractMap.SimpleEntry<ButtonWidget.PressAction, Function<Object, Text>>(button -> { info.function = new AbstractMap.SimpleEntry<ButtonWidget.PressAction, Function<Object, Text>>(button -> {
int index = values.indexOf(info.value) + 1; int index = values.indexOf(info.value) + 1;
info.setValue(values.get(index >= values.size() ? 0 : index)); info.setValue(values.get(index >= values.size() ? 0 : index));
button.setMessage(func.apply(info.value)); button.setMessage(func.apply(info.value));
}, func); }, func);
} }
try { info.defaultValue = field.get(null);
} catch (IllegalAccessException ignored) {}
} }
entries.put(key, info); entries.put(modid + ":" + field.getName(), info);
} }
public static Class<?> getUnderlyingType(Field field) { public static Class<?> getUnderlyingType(Field field) {
Class<?> rawType = field.getType(); Class<?> rawType = field.getType();
if (field.getType() == List.class) if (field.getType() == List.class)
@@ -185,16 +115,13 @@ public abstract class MidnightConfig {
try { return (Class<?>) rawType.getField("TYPE").get(null); // Tries to get primitive types from non-primitives (e.g. Boolean -> boolean) try { return (Class<?>) rawType.getField("TYPE").get(null); // Tries to get primitive types from non-primitives (e.g. Boolean -> boolean)
} catch (NoSuchFieldException | IllegalAccessException ignored) { return rawType; } } catch (NoSuchFieldException | IllegalAccessException ignored) { return rawType; }
} }
public static Tooltip getTooltip(EntryInfo info, boolean isButton) {
String key = info.modid + ".midnightconfig."+info.fieldName+(!isButton ? ".label" : "" )+".tooltip";
return Tooltip.of(isButton && info.error != null ? info.error : I18n.hasTranslation(key) ? Text.translatable(key) : Text.empty());
}
private static void textField(EntryInfo info, Function<String,Number> f, Pattern pattern, double min, double max, boolean cast) { private static void textField(EntryInfo info, Function<String,Number> f, Pattern pattern, double min, double max, boolean cast) {
boolean isNumber = pattern != null; boolean isNumber = pattern != null;
info.function = (BiFunction<TextFieldWidget, ButtonWidget, Predicate<String>>) (t, b) -> s -> { info.function = (BiFunction<TextFieldWidget, ButtonWidget, Predicate<String>>) (t, b) -> s -> {
s = s.trim(); s = s.trim();
if (!(s.isEmpty() || !isNumber || pattern.matcher(s).matches())) return false; if (!(s.isEmpty() || !isNumber || pattern.matcher(s).matches()) ||
(info.dataType == Identifier.class && Identifier.validate(s).isError())) return false;
Number value = 0; boolean inLimits = false; info.error = null; Number value = 0; boolean inLimits = false; info.error = null;
if (!(isNumber && s.isEmpty()) && !s.equals("-") && !s.equals(".")) { if (!(isNumber && s.isEmpty()) && !s.equals("-") && !s.equals(".")) {
@@ -203,7 +130,7 @@ public abstract class MidnightConfig {
info.error = inLimits? null : Text.literal(value.doubleValue() < min ? info.error = inLimits? null : Text.literal(value.doubleValue() < min ?
"§cMinimum " + (isNumber? "value" : "length") + (cast? " is " + (int)min : " is " + min) : "§cMinimum " + (isNumber? "value" : "length") + (cast? " is " + (int)min : " is " + min) :
"§cMaximum " + (isNumber? "value" : "length") + (cast? " is " + (int)max : " is " + max)).formatted(Formatting.RED); "§cMaximum " + (isNumber? "value" : "length") + (cast? " is " + (int)max : " is " + max)).formatted(Formatting.RED);
t.setTooltip(getTooltip(info, true)); t.setTooltip(info.getTooltip(true));
} }
info.tempValue = s; info.tempValue = s;
@@ -212,11 +139,8 @@ public abstract class MidnightConfig {
b.active = entries.values().stream().allMatch(e -> e.inLimits); b.active = entries.values().stream().allMatch(e -> e.inLimits);
if (inLimits) { if (inLimits) {
if (info.dataType == Identifier.class) { // avoid the crash due to Identifier syntax not legitimate if (info.dataType == Identifier.class)
Identifier id = Identifier.tryParse(s);
if (id == null) return false;
info.setValue(Identifier.tryParse(s)); info.setValue(Identifier.tryParse(s));
}
else info.setValue(isNumber ? value : s); else info.setValue(isNumber ? value : s);
} }
@@ -229,297 +153,77 @@ public abstract class MidnightConfig {
return true; return true;
}; };
} }
public static MidnightConfig getClass(String modid) {
try { return configClass.get(modid).getDeclaredConstructor().newInstance(); } catch (Exception e) {throw new RuntimeException(e);}
}
public static void write(String modid) { getClass(modid).writeChanges(modid); }
protected Text getEnumTranslatableText(Object value, EntryInfo info) {
if (value instanceof TranslatableOption translatableOption) return translatableOption.getText();
String translationKey = "%s.midnightconfig.enum.%s.%s".formatted(modid, info.dataType.getSimpleName(), info.toTemporaryValue());
return I18n.hasTranslation(translationKey) ? Text.translatable(translationKey) : Text.literal(info.toTemporaryValue());
}
public void loadValuesFromJson() {
try {
gson.fromJson(Files.newBufferedReader(getJsonFilePath()), configClass);
} catch (Exception e) {
write(modid);
}
entries.values().forEach(info -> {
if (info.field != null && info.entry != null) {
try {
info.value = info.field.get(null) == null ? info.defaultValue : info.field.get(null);
info.tempValue = info.toTemporaryValue();
info.updateConditions();
} catch (IllegalAccessException ignored) {}
}
});
}
public static void write(String modid) {
configInstances.get(modid).writeChanges(modid);
}
@Deprecated
public void writeChanges(String modid) { public void writeChanges(String modid) {
try { if (!Files.exists(path = PlatformFunctions.getConfigDirectory().resolve(modid + ".json"))) Files.createFile(path); this.writeChanges();
Files.write(path, gson.toJson(getClass(modid)).getBytes()); }
public void writeChanges() {
try {
Path path;
if (!Files.exists(path = getJsonFilePath()))
Files.createFile(path);
Files.write(path, gson.toJson(this).getBytes());
} catch (Exception e) { e.fillInStackTrace(); } } catch (Exception e) { e.fillInStackTrace(); }
} }
@Environment(EnvType.CLIENT)
public static Screen getScreen(Screen parent, String modid) { public Path getJsonFilePath() {
return PlatformFunctions.getConfigDirectory().resolve(modid + ".json");
}
@SuppressWarnings("unused") // Utility for mod authors
public static @Nullable Object getDefaultValue(String modid, String entry) {
String key = modid + ":" + entry;
return entries.containsKey(key) ? entries.get(key).defaultValue : null;
}
// Overridable method
public void onTabInit(String tabName, MidnightConfigListWidget list, MidnightConfigScreen screen) {
}
public static MidnightConfigScreen getScreen(Screen parent, String modid) {
return configInstances.get(modid).getScreen(parent);
}
public MidnightConfigScreen getScreen(Screen parent) {
return new MidnightConfigScreen(parent, modid); return new MidnightConfigScreen(parent, modid);
} }
@Environment(EnvType.CLIENT)
public static class MidnightConfigScreen extends Screen {
protected MidnightConfigScreen(Screen parent, String modid) {
super(Text.translatable(modid + ".midnightconfig." + "title"));
this.parent = parent; this.modid = modid;
this.translationPrefix = modid + ".midnightconfig.";
loadValuesFromJson(modid);
entries.values().forEach(info -> {
if (info.modid.equals(modid)) {
String tabId = info.entry != null ? info.entry.category() : info.comment.category();
String name = translationPrefix + "category." + tabId;
if (!I18n.hasTranslation(name) && tabId.equals("default"))
name = translationPrefix + "title";
if (!tabs.containsKey(name)) {
Tab tab = new GridScreenTab(Text.translatable(name));
info.tab = tab; tabs.put(name, tab);
} else info.tab = tabs.get(name);
}
});
tabNavigation = TabNavigationWidget.builder(tabManager, this.width).tabs(tabs.values().toArray(new Tab[0])).build();
tabNavigation.selectTab(0, false);
tabNavigation.init();
prevTab = tabManager.getCurrentTab();
}
public final String translationPrefix, modid;
public final Screen parent;
public MidnightConfigListWidget list;
public TabManager tabManager = new TabManager(a -> {}, a -> {});
public Map<String, Tab> tabs = new LinkedHashMap<>();
public Tab prevTab;
public TabNavigationWidget tabNavigation;
public ButtonWidget done;
public double scrollProgress = 0d;
// Real Time config update //
@Override
public void tick() {
super.tick();
if (prevTab != null && prevTab != tabManager.getCurrentTab()) {
prevTab = tabManager.getCurrentTab();
updateList(); list.setScrollY(0);
}
scrollProgress = list.getScrollY();
for (EntryInfo info : entries.values()) info.updateFieldValue();
updateButtons();
if (reloadScreen) { updateList(); reloadScreen = false; }
}
public void updateButtons() {
if (this.list != null) {
for (ButtonEntry entry : this.list.children()) {
if (entry.buttons != null && entry.buttons.size() > 1) {
if (entry.buttons.get(0) instanceof ClickableWidget widget)
if (widget.isFocused() || widget.isHovered()) widget.setTooltip(getTooltip(entry.info, true));
if (entry.buttons.get(1) instanceof ButtonWidget button)
button.active = !Objects.equals(String.valueOf(entry.info.value), String.valueOf(entry.info.defaultValue));
}}}}
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (this.tabNavigation.trySwitchTabsWithKey(keyCode)) return true;
return super.keyPressed(keyCode, scanCode, modifiers);
}
@Override
public void close() {
loadValuesFromJson(modid); cleanup();
Objects.requireNonNull(client).setScreen(parent);
}
private void cleanup() {
entries.values().forEach(info -> {
info.error = null; info.value = null; info.tempValue = null; info.actionButton = null; info.listIndex = 0; info.tab = null; info.inLimits = true;
});
}
@Override
public void init() {
super.init();
tabNavigation.setWidth(this.width); tabNavigation.init();
if (tabs.size() > 1) this.addDrawableChild(tabNavigation);
this.addDrawableChild(ButtonWidget.builder(ScreenTexts.CANCEL, button -> this.close()).dimensions(this.width / 2 - 154, this.height - 26, 150, 20).build());
done = this.addDrawableChild(ButtonWidget.builder(ScreenTexts.DONE, (button) -> {
for (EntryInfo info : entries.values()) if (info.modid.equals(modid)) info.updateFieldValue();
write(modid); cleanup();
Objects.requireNonNull(client).setScreen(parent);
}).dimensions(this.width / 2 + 4, this.height - 26, 150, 20).build());
this.list = new MidnightConfigListWidget(this.client, this.width, this.height - 57, 24, 25);
this.addSelectableChild(this.list); fillList();
if (tabs.size() > 1) list.renderHeaderSeparator = false;
}
public void updateList() {
this.list.clear(); fillList();
}
public void fillList() {
for (EntryInfo info : entries.values()) {
if (!info.conditionsMet) {
boolean visibleButLocked = false;
for (Condition condition : info.conditions) {
visibleButLocked |= condition.visibleButLocked();
}
if (!visibleButLocked) continue;
}
if (info.modid.equals(modid) && (info.tab == null || info.tab == tabManager.getCurrentTab())) {
Text name = Objects.requireNonNullElseGet(info.name, () -> Text.translatable(translationPrefix + info.fieldName));
TextIconButtonWidget resetButton = TextIconButtonWidget.builder(Text.translatable("controls.reset"), (button -> {
info.value = info.defaultValue; info.listIndex = 0;
info.tempValue = info.toTemporaryValue();
updateList();
}), true).texture(Identifier.of("midnightlib","icon/reset"), 12, 12).dimension(20, 20).build();
resetButton.setPosition(width - 205 + 150 + 25, 0);
if (info.function != null) {
ClickableWidget widget;
Entry e = info.entry;
if (info.dataType == boolean.class) {
widget = CheckboxWidget.builder(Text.empty(), textRenderer).pos(width - 185, 0).callback((CheckboxWidget.Callback) info.function).checked((boolean) info.value).build();
} else if (info.dataType.isEnum()) {
var values = (Map.Entry<ButtonWidget.PressAction, Function<Object, Text>>) info.function;
values.setValue(value -> Text.translatable(translationPrefix + "enum." + info.dataType.getSimpleName() + "." + info.value.toString()));
widget = ButtonWidget.builder(values.getValue().apply(info.value), values.getKey()).dimensions(width - 185, 0, 150, 20).tooltip(getTooltip(info, true)).build();
} else if (e.isSlider())
widget = new MidnightSliderWidget(width - 185, 0, 150, 20, Text.of(info.tempValue), (Double.parseDouble(info.tempValue) - e.min()) / (e.max() - e.min()), info);
else
widget = new TextFieldWidget(textRenderer, width - 185, 0, 150, 20, Text.empty());
if (widget instanceof TextFieldWidget textField) {
textField.setMaxLength(e.width()); textField.setText(info.tempValue);
Predicate<String> processor = ((BiFunction<TextFieldWidget, ButtonWidget, Predicate<String>>) info.function).apply(textField, done);
textField.setTextPredicate(processor);
}
widget.setTooltip(getTooltip(info, true));
ButtonWidget cycleButton = null;
if (info.field.getType() == List.class) {
cycleButton = ButtonWidget.builder(Text.literal(String.valueOf(info.listIndex)).formatted(Formatting.GOLD), (button -> {
var values = (List<?>) info.value;
values.remove("");
info.listIndex = info.listIndex + 1;
if (info.listIndex > values.size()) info.listIndex = 0;
info.tempValue = info.toTemporaryValue();
if (info.listIndex == values.size()) info.tempValue = "";
updateList();
})).dimensions(width - 185, 0, 20, 20).build();
}
if (e.isColor()) {
ButtonWidget colorButton = ButtonWidget.builder(Text.literal(""),
button -> new Thread(() -> {
Color newColor = JColorChooser.showDialog(null, Text.translatable("midnightconfig.colorChooser.title").getString(), Color.decode(!Objects.equals(info.tempValue, "") ? info.tempValue : "#FFFFFF"));
if (newColor != null) {
info.setValue("#" + Integer.toHexString(newColor.getRGB()).substring(2));
updateList();
}
}).start()
).dimensions(width - 185, 0, 20, 20).build();
try { colorButton.setMessage(Text.literal("").setStyle(Style.EMPTY.withColor(Color.decode(info.tempValue).getRGB())));
} catch (Exception ignored) {}
info.actionButton = colorButton;
} else if (e.selectionMode() > -1) {
ButtonWidget explorerButton = TextIconButtonWidget.builder(Text.empty(),
button -> new Thread(() -> {
JFileChooser fileChooser = new JFileChooser(info.tempValue);
fileChooser.setFileSelectionMode(e.selectionMode()); fileChooser.setDialogType(e.fileChooserType());
fileChooser.setDialogTitle(Text.translatable(translationPrefix + info.fieldName + ".fileChooser").getString());
if ((e.selectionMode() == JFileChooser.FILES_ONLY || e.selectionMode() == JFileChooser.FILES_AND_DIRECTORIES) && Arrays.stream(e.fileExtensions()).noneMatch("*"::equals))
fileChooser.setFileFilter(new FileNameExtensionFilter(
Text.translatable(translationPrefix + info.fieldName + ".fileFilter").getString(), e.fileExtensions()));
if (fileChooser.showDialog(null, null) == JFileChooser.APPROVE_OPTION) {
info.setValue(fileChooser.getSelectedFile().getAbsolutePath());
updateList();
}
}).start(), true
).texture(Identifier.of("midnightlib", "icon/explorer"), 12, 12).dimension(20, 20).build();
explorerButton.setPosition(width - 185, 0);
info.actionButton = explorerButton;
}
if (!info.conditionsMet) widget.active = false;
List<ClickableWidget> widgets = Lists.newArrayList(widget, resetButton);
if (info.actionButton != null) {
if (IS_SYSTEM_MAC) info.actionButton.active = false;
widget.setWidth(widget.getWidth() - 22); widget.setX(widget.getX() + 22);
widgets.add(info.actionButton);
} if (cycleButton != null) {
if (info.actionButton != null) info.actionButton.setX(info.actionButton.getX() + 22);
widget.setWidth(widget.getWidth() - 22); widget.setX(widget.getX() + 22);
widgets.add(cycleButton);
}
this.list.addButton(widgets, name, info);
} else this.list.addButton(List.of(), name, info);
} list.setScrollY(scrollProgress);
updateButtons();
}
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
super.render(context, mouseX, mouseY, delta);
this.list.render(context, mouseX, mouseY, delta);
if (tabs.size() < 2) context.drawCenteredTextWithShadow(textRenderer, title, width / 2, 10, 0xFFFFFF);
}
}
@Environment(EnvType.CLIENT)
public static class MidnightConfigListWidget extends ElementListWidget<ButtonEntry> {
public boolean renderHeaderSeparator = true;
public MidnightConfigListWidget(MinecraftClient client, int width, int height, int y, int itemHeight) { super(client, width, height, y, itemHeight); }
@Override public int getScrollbarX() { return this.width -7; }
@Override
protected void drawHeaderAndFooterSeparators(DrawContext context) {
if (renderHeaderSeparator) super.drawHeaderAndFooterSeparators(context);
else context.drawTexture(RenderLayer::getGuiTextured, this.client.world == null ? Screen.FOOTER_SEPARATOR_TEXTURE : Screen.INWORLD_FOOTER_SEPARATOR_TEXTURE, this.getX(), this.getBottom(), 0, 0, this.getWidth(), 2, 32, 2);
}
public void addButton(List<ClickableWidget> buttons, Text text, EntryInfo info) { this.addEntry(new ButtonEntry(buttons, text, info)); }
public void clear() { this.clearEntries(); }
@Override public int getRowWidth() { return 10000; }
}
public static class ButtonEntry extends ElementListWidget.Entry<ButtonEntry> {
private static final TextRenderer textRenderer = MinecraftClient.getInstance().textRenderer;
public final Text text;
public final List<ClickableWidget> buttons;
public final EntryInfo info;
public boolean centered = false;
public MultilineTextWidget title;
public ButtonEntry(List<ClickableWidget> buttons, Text text, EntryInfo info) {
this.buttons = buttons; this.text = text; this.info = info;
if (info != null && info.comment != null) this.centered = info.comment.centered();
int scaledWidth = MinecraftClient.getInstance().getWindow().getScaledWidth();
if (text != null && (!text.getString().contains("spacer") || !buttons.isEmpty())) {
title = new MultilineTextWidget((centered) ? (scaledWidth / 2 - (textRenderer.getWidth(text) / 2)) : 12, 0, Text.of(text), textRenderer);
if (info != null) title.setTooltip(getTooltip(info, false));
title.setMaxWidth(buttons.size() > 1 ? buttons.get(1).getX() - 24 : scaledWidth - 24);
}
}
public void render(DrawContext context, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) {
buttons.forEach(b -> { b.setY(y); b.render(context, mouseX, mouseY, tickDelta);});
if (title != null) {
title.setY(y + 9);
title.renderWidget(context, mouseX, mouseY, tickDelta);
boolean tooltipVisible = mouseX >= title.getX() && mouseX < title.getWidth() + title.getX() && mouseY >= title.getY() && mouseY < title.getHeight() + title.getY();
if (tooltipVisible && title.getTooltip() != null) context.drawOrderedTooltip(textRenderer, title.getTooltip().getLines(MinecraftClient.getInstance()), mouseX, mouseY);
if (info.entry != null && !this.buttons.isEmpty() && this.buttons.getFirst() instanceof ClickableWidget widget) {
int idMode = this.info.entry.idMode();
if (idMode != -1) context.drawItem(idMode == 0 ? Registries.ITEM.get(Identifier.tryParse(this.info.tempValue)).getDefaultStack() : Registries.BLOCK.get(Identifier.tryParse(this.info.tempValue)).asItem().getDefaultStack(), widget.getX() + widget.getWidth() - 18, y + 2);
}
}
}
public List<? extends Element> children() {return Lists.newArrayList(buttons);}
public List<? extends Selectable> selectableChildren() {return Lists.newArrayList(buttons);}
}
public static class MidnightSliderWidget extends SliderWidget {
private final EntryInfo info; private final Entry e;
public MidnightSliderWidget(int x, int y, int width, int height, Text text, double value, EntryInfo info) {
super(x, y, width, height, text, value);
this.e = info.entry;
this.info = info;
}
@Override
public void updateMessage() { this.setMessage(Text.of(info.tempValue)); }
@Override
public void applyValue() {
if (info.dataType == int.class) info.setValue(((Number) (e.min() + value * (e.max() - e.min()))).intValue());
else if (info.dataType == double.class) info.setValue(Math.round((e.min() + value * (e.max() - e.min())) * (double) e.precision()) / (double) e.precision());
else if (info.dataType == float.class) info.setValue(Math.round((e.min() + value * (e.max() - e.min())) * (float) e.precision()) / (float) e.precision());
}
}
public static class NonEntryExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> clazz) { return false; }
public boolean shouldSkipField(FieldAttributes fieldAttributes) { return fieldAttributes.getAnnotation(Entry.class) == null; }
}
/** /**
* Entry Annotation<br> * Entry Annotation<br>
* - <b>width</b>: The maximum character length of the {@link String}, {@link Identifier} or String/Identifier {@link List<>} field<br> * - <b>width</b>: The maximum character length of the {@link String}, {@link Identifier} or String/Identifier {@link List<>} field<br>
* - <b>min</b>: The minimum value of the <code>int</code>, <code>float</code> or <code>double</code> field<br> * - <b>min</b>: The minimum value of the <code>int</code>, <code>float</code> or <code>double</code> field<br>
* - <b>max</b>: The maximum value of the <code>int</code>, <code>float</code> or <code>double</code> field<br> * - <b>max</b>: The maximum value of the <code>int</code>, <code>float</code> or <code>double</code> field<br>
* - <b>name</b>: The name of the field in the config screen<br> * - <b>name</b>: Will be used instead of the default translation key, if not empty<br>
* - <b>selectionMode</b>: The selection mode of the file picker button for {@link String} fields, * - <b>selectionMode</b>: The selection mode of the file picker button for {@link String} fields,
* -1 for none, {@link JFileChooser#FILES_ONLY} for files, {@link JFileChooser#DIRECTORIES_ONLY} for directories, * -1 for none, {@link JFileChooser#FILES_ONLY} for files, {@link JFileChooser#DIRECTORIES_ONLY} for directories,
* {@link JFileChooser#FILES_AND_DIRECTORIES} for both (default: -1). Remember to set the translation key * {@link JFileChooser#FILES_AND_DIRECTORIES} for both (default: -1). Remember to set the translation key
@@ -553,24 +257,40 @@ public abstract class MidnightConfig {
@Deprecated String requiredMod() default ""; @Deprecated String requiredMod() default "";
} }
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Client {} @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Client {}
/** /**
* Hides the entry in config screens, but still makes it accessible through the command {@code /midnightconfig MOD_ID ENTRY} and directly editing the config file. * Hides the entry in config screens, but still makes it accessible through the command {@code /midnightconfig MOD_ID ENTRY} and directly editing the config file.
*/ */
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Server {} @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Server {}
/** /**
* Hides the entry entirely. * Hides the entry entirely.
* Accessible only through directly editing the config file. * Accessible only through directly editing the config file.
* Perfect for saving persistent internal data. * Perfect for saving persistent internal data.
*/ */
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Hidden {} @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Hidden {}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Comment { /**
* Comment Annotation<br>
* - <b>{@link Comment#centered()}</b>: If the comment should be centered<br>
* - <b>{@link Comment#category()}</b>: The category of the comment in the config screen<br>
* - <b>{@link Comment#name()}</b>: Will be used instead of the default translation key, if not empty<br>
* - <b>{@link Comment#url()}</b>: The url of the comment should link to in the config screen (none if left empty)<br>
* */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Comment {
boolean centered() default false; boolean centered() default false;
String category() default "default"; String category() default "default";
String name() default ""; String name() default "";
String url() default "";
@Deprecated String requiredMod() default ""; @Deprecated String requiredMod() default "";
} }
/** /**

View File

@@ -0,0 +1,45 @@
package eu.midnightdust.lib.config;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gl.RenderPipelines;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.gui.widget.ElementListWidget;
import net.minecraft.text.Text;
import java.util.List;
public class MidnightConfigListWidget extends ElementListWidget<ButtonEntry> {
public boolean renderHeaderSeparator = true;
public MidnightConfigListWidget(MinecraftClient client, int width, int height, int y, int itemHeight) {
super(client, width, height, y, itemHeight);
}
@Override
public int getScrollbarX() {
return this.width - 7;
}
@Override
public void drawHeaderAndFooterSeparators(DrawContext context) {
if (renderHeaderSeparator)
super.drawHeaderAndFooterSeparators(context);
else
context.drawTexture(RenderPipelines.GUI_TEXTURED, this.client.world == null ? Screen.FOOTER_SEPARATOR_TEXTURE : Screen.INWORLD_FOOTER_SEPARATOR_TEXTURE, this.getX(), this.getBottom(), 0, 0, this.getWidth(), 2, 32, 2);
}
public void addButton(List<ClickableWidget> buttons, Text text, EntryInfo info) {
this.addEntry(new ButtonEntry(buttons, text, info));
}
public void clear() {
this.clearEntries();
}
@Override
public int getRowWidth() {
return 10000;
}
}

View File

@@ -0,0 +1,261 @@
package eu.midnightdust.lib.config;
import com.google.common.collect.Lists;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.tab.GridScreenTab;
import net.minecraft.client.gui.tab.Tab;
import net.minecraft.client.gui.tab.TabManager;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.*;
import net.minecraft.client.input.KeyInput;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.screen.ScreenTexts;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableTextContent;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.Util;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
public class MidnightConfigScreen extends Screen {
public MidnightConfig instance;
public final String translationPrefix, modid;
public final Screen parent;
public MidnightConfigListWidget list;
public TabManager tabManager = new TabManager(a -> {}, a -> {});
public Map<String, Tab> tabs = new LinkedHashMap<>();
public Tab prevTab;
public TabNavigationWidget tabNavigation;
public ButtonWidget done;
public double scrollProgress = 0d;
public MidnightConfigScreen(Screen parent, String modid) {
super(Text.translatable(modid + ".midnightconfig.title"));
this.parent = parent;
this.modid = modid;
this.translationPrefix = modid + ".midnightconfig.";
this.instance = MidnightConfig.configInstances.get(modid);
instance.loadValuesFromJson();
MidnightConfig.entries.values().forEach(info -> {
if (Objects.equals(info.modid, modid)) {
String tabId = info.entry != null ? info.entry.category() : info.comment.category();
String name = translationPrefix + "category." + tabId;
if (!I18n.hasTranslation(name) && tabId.equals("default"))
name = translationPrefix + "title";
if (!tabs.containsKey(name)) {
info.tab = new GridScreenTab(Text.translatable(name));
tabs.put(name, info.tab);
} else info.tab = tabs.get(name);
}
});
tabNavigation = TabNavigationWidget.builder(tabManager, this.width).tabs(tabs.values().toArray(new Tab[0])).build();
tabNavigation.selectTab(0, false);
tabNavigation.init();
prevTab = tabManager.getCurrentTab();
}
// Real Time config update //
@Override
public void tick() {
super.tick();
if (prevTab != null && prevTab != tabManager.getCurrentTab()) {
prevTab = tabManager.getCurrentTab();
updateList();
list.setScrollY(0);
}
scrollProgress = list.getScrollY();
for (EntryInfo info : MidnightConfig.entries.values())
if (Objects.equals(modid, info.modid)) info.updateFieldValue();
updateButtons();
if (instance.reloadScreen) {
updateList();
instance.reloadScreen = false;
}
}
public void updateButtons() {
if (this.list == null) return;
for (ButtonEntry entry : this.list.children()) {
if (entry.buttons != null && entry.buttons.size() > 1 && entry.info.field != null) {
if (entry.buttons.get(0) instanceof ClickableWidget widget)
if (widget.isFocused() || widget.isHovered())
widget.setTooltip(entry.info.getTooltip(true));
if (entry.buttons.get(1) instanceof ButtonWidget button)
button.active = !Objects.equals(String.valueOf(entry.info.value), String.valueOf(entry.info.defaultValue)) && entry.info.conditionsMet;
}
}
}
@Override
public boolean keyPressed(KeyInput input) {
return this.tabNavigation.keyPressed(input) || super.keyPressed(input);
}
@Override
public void close() {
instance.loadValuesFromJson();
MidnightConfig.entries.values().forEach(info -> {
info.error = null;
info.value = null;
info.tempValue = null;
info.actionButton = null;
info.listIndex = 0;
info.tab = null;
info.inLimits = true;
});
Objects.requireNonNull(client).setScreen(parent);
}
@Override
public void init() {
super.init();
tabNavigation.setWidth(this.width);
tabNavigation.init();
if (tabs.size() > 1)
this.addDrawableChild(tabNavigation);
this.addDrawableChild(ButtonWidget.builder(ScreenTexts.CANCEL, button -> this.close()).dimensions(this.width / 2 - 154, this.height - 26, 150, 20).build());
done = this.addDrawableChild(ButtonWidget.builder(ScreenTexts.DONE, (button) -> {
for (EntryInfo info : MidnightConfig.entries.values())
if (info.modid.equals(modid))
info.updateFieldValue();
MidnightConfig.write(modid);
close();
}).dimensions(this.width / 2 + 4, this.height - 26, 150, 20).build());
this.list = new MidnightConfigListWidget(this.client, this.width, this.height - 57, 24, 25);
this.addSelectableChild(this.list);
updateList();
if (tabs.size() > 1)
list.renderHeaderSeparator = false;
}
public void updateList() {
this.list.clear();
instance.onTabInit(prevTab.getTitle().getContent() instanceof TranslatableTextContent translatable ?
translatable.getKey().substring(translatable.getKey().lastIndexOf('.') + 1) : prevTab.getTitle().toString(), list, this);
for (EntryInfo info : MidnightConfig.entries.values()) {
info.updateConditions();
if (!info.conditionsMet) {
boolean visibleButLocked = false;
for (MidnightConfig.Condition condition : info.conditions)
visibleButLocked |= condition.visibleButLocked();
if (!visibleButLocked) continue;
}
if (info.modid.equals(modid) && (info.tab == null || info.tab == tabManager.getCurrentTab())) {
TextIconButtonWidget resetButton = TextIconButtonWidget.builder(Text.translatable("controls.reset"), (button -> {
info.value = info.defaultValue;
info.listIndex = 0;
info.tempValue = info.toTemporaryValue();
updateList();
}), true).texture(Identifier.of("midnightlib", "icon/reset"), 12, 12).dimension(20, 20).build();
resetButton.setPosition(width - 205 + 150 + 25, 0);
if (info.function != null) {
ClickableWidget widget;
MidnightConfig.Entry e = info.entry;
if (info.function instanceof Map.Entry) { // Enums & booleans
var values = (Map.Entry<ButtonWidget.PressAction, Function<Object, Text>>) info.function;
if (info.dataType.isEnum()) {
values.setValue(value -> instance.getEnumTranslatableText(value, info));
}
widget = ButtonWidget.builder(values.getValue().apply(info.value), values.getKey()).dimensions(width - 185, 0, 150, 20).tooltip(info.getTooltip(true)).build();
} else if (e.isSlider())
widget = new MidnightSliderWidget(width - 185, 0, 150, 20, Text.of(info.tempValue), (Double.parseDouble(info.tempValue) - e.min()) / (e.max() - e.min()), info);
else
widget = new TextFieldWidget(textRenderer, width - 185, 0, 150, 20, Text.empty());
if (widget instanceof TextFieldWidget textField) {
textField.setMaxLength(e.width());
textField.setText(info.tempValue);
Predicate<String> processor = ((BiFunction<TextFieldWidget, ButtonWidget, Predicate<String>>) info.function).apply(textField, done);
textField.setTextPredicate(processor);
}
widget.setTooltip(info.getTooltip(true));
ButtonWidget cycleButton = null;
if (info.field.getType() == List.class) {
cycleButton = ButtonWidget.builder(Text.literal(String.valueOf(info.listIndex)).formatted(Formatting.GOLD), (button -> {
var values = (List<?>) info.value;
values.remove("");
info.listIndex = info.listIndex != values.size() ? info.listIndex + 1 : 0;
info.tempValue = info.listIndex != values.size() ? info.toTemporaryValue() : "";
updateList();
})).dimensions(width - 185, 0, 20, 20).tooltip(Tooltip.of(Text.translatable("midnightconfig.action.list_index", info.listIndex))).build();
}
if (e.isColor()) {
ButtonWidget colorButton = ButtonWidget.builder(Text.literal(""),
button -> new Thread(() -> {
Color newColor = JColorChooser.showDialog(null, Text.translatable("midnightconfig.colorChooser.title").getString(), Color.decode(!Objects.equals(info.tempValue, "") ? info.tempValue : "#FFFFFF"));
if (newColor != null) {
info.setValue("#" + Integer.toHexString(newColor.getRGB()).substring(2));
updateList();
}
}).start()
).dimensions(width - 185, 0, 20, 20).tooltip(Tooltip.of(Text.translatable("midnightconfig.action.color_chooser"))).build();
try {
colorButton.setMessage(Text.literal("").setStyle(Style.EMPTY.withColor(Color.decode(info.tempValue).getRGB())));
} catch (Exception ignored) {
}
info.actionButton = colorButton;
} else if (e.selectionMode() > -1) {
ButtonWidget explorerButton = TextIconButtonWidget.builder(Text.empty(),
button -> new Thread(() -> {
JFileChooser fileChooser = new JFileChooser(info.tempValue);
fileChooser.setFileSelectionMode(e.selectionMode());
fileChooser.setDialogType(e.fileChooserType());
fileChooser.setDialogTitle(Text.translatable(translationPrefix + info.fieldName + ".fileChooser").getString());
if ((e.selectionMode() == JFileChooser.FILES_ONLY || e.selectionMode() == JFileChooser.FILES_AND_DIRECTORIES) && Arrays.stream(e.fileExtensions()).noneMatch("*"::equals))
fileChooser.setFileFilter(new FileNameExtensionFilter(
Text.translatable(translationPrefix + info.fieldName + ".fileFilter").getString(), e.fileExtensions()));
if (fileChooser.showDialog(null, null) == JFileChooser.APPROVE_OPTION) {
info.setValue(fileChooser.getSelectedFile().getAbsolutePath());
updateList();
}
}).start(), true
).texture(Identifier.of("midnightlib", "icon/explorer"), 12, 12).dimension(20, 20).build();
explorerButton.setTooltip(Tooltip.of(Text.translatable("midnightconfig.action.file_chooser")));
explorerButton.setPosition(width - 185, 0);
info.actionButton = explorerButton;
}
List<ClickableWidget> widgets = Lists.newArrayList(widget, resetButton);
if (info.actionButton != null) {
if (Util.getOperatingSystem() == Util.OperatingSystem.OSX) info.actionButton.active = false;
widget.setWidth(widget.getWidth() - 22);
widget.setX(widget.getX() + 22);
widgets.add(info.actionButton);
}
if (cycleButton != null) {
if (info.actionButton != null) info.actionButton.setX(info.actionButton.getX() + 22);
widget.setWidth(widget.getWidth() - 22);
widget.setX(widget.getX() + 22);
widgets.add(cycleButton);
}
if (!info.conditionsMet) widgets.forEach(w -> w.active = false);
this.list.addButton(widgets, Text.translatable(info.translationKey), info);
} else this.list.addButton(List.of(), Text.translatable(info.translationKey), info);
}
list.setScrollY(scrollProgress);
updateButtons();
}
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
super.render(context, mouseX, mouseY, delta);
this.list.render(context, mouseX, mouseY, delta);
if (tabs.size() < 2) context.drawCenteredTextWithShadow(textRenderer, title, width / 2, 10, 0xFFFFFFFF);
}
}

View File

@@ -0,0 +1,29 @@
package eu.midnightdust.lib.config;
import net.minecraft.client.gui.widget.SliderWidget;
import net.minecraft.text.Text;
public class MidnightSliderWidget extends SliderWidget {
private final EntryInfo info;
private final MidnightConfig.Entry e;
public MidnightSliderWidget(int x, int y, int width, int height, Text text, double value, EntryInfo info) {
super(x, y, width, height, text, value);
this.e = info.entry;
this.info = info;
}
@Override
public void updateMessage() {
this.setMessage(Text.of(info.tempValue));
}
@Override
public void applyValue() {
if (info.dataType == int.class) info.setValue(((Number) (e.min() + value * (e.max() - e.min()))).intValue());
else if (info.dataType == double.class)
info.setValue(Math.round((e.min() + value * (e.max() - e.min())) * (double) e.precision()) / (double) e.precision());
else if (info.dataType == float.class)
info.setValue(Math.round((e.min() + value * (e.max() - e.min())) * (float) e.precision()) / (float) e.precision());
}
}

View File

@@ -3,5 +3,8 @@
"midnightlib.midnightconfig.title":"MidnightLib Konfiguration", "midnightlib.midnightconfig.title":"MidnightLib Konfiguration",
"midnightlib.midnightconfig.config_screen_list":"Konfigurationsübersicht", "midnightlib.midnightconfig.config_screen_list":"Konfigurationsübersicht",
"modmenu.summaryTranslation.midnightlib": "Code-Bibliothek für einfache Konfiguration.", "modmenu.summaryTranslation.midnightlib": "Code-Bibliothek für einfache Konfiguration.",
"midnightconfig.colorChooser.title": "Wähle eine Farbe" "midnightconfig.colorChooser.title": "Wähle eine Farbe",
"midnightconfig.action.list_index": "Bearbeite Liste an Index %s",
"midnightconfig.action.color_chooser": "Öffne Farbauswahl",
"midnightconfig.action.file_chooser": "Öffne Dateiauswahl"
} }

View File

@@ -9,5 +9,8 @@
"midnightlib.curseforge":"CurseForge", "midnightlib.curseforge":"CurseForge",
"midnightlib.wiki":"Wiki", "midnightlib.wiki":"Wiki",
"modmenu.summaryTranslation.midnightlib": "Common Library for easy configuration.", "modmenu.summaryTranslation.midnightlib": "Common Library for easy configuration.",
"midnightconfig.colorChooser.title": "Choose a color" "midnightconfig.colorChooser.title": "Choose a color",
"midnightconfig.action.list_index": "Editing list at index %s",
"midnightconfig.action.color_chooser": "Open color chooser",
"midnightconfig.action.file_chooser": "Open file chooser"
} }

View File

@@ -0,0 +1,13 @@
{
"midnightlib.overview.title": "Visión general de MidnightConfig",
"midnightlib.midnightconfig.title": "Configuración de MidnightLib",
"midnightlib.midnightconfig.config_screen_list": "Habilitar lista de pantallas de configuración",
"midnightlib.midnightconfig.enum.ConfigButton.TRUE":"§aSí",
"midnightlib.midnightconfig.enum.ConfigButton.FALSE":"§cNo",
"midnightlib.midnightconfig.enum.ConfigButton.MODMENU":"§bMenú del Mod",
"midnightlib.modrinth":"Modrinth",
"midnightlib.curseforge":"CurseForge",
"midnightlib.wiki":"Wiki",
"modmenu.summaryTranslation.midnightlib": "Librería común para facilitar la configuración.",
"midnightconfig.colorChooser.title": "Elegí un color"
}

View File

@@ -0,0 +1,99 @@
package eu.midnightdust.test;
import com.google.common.collect.Lists;
import eu.midnightdust.lib.config.EntryInfo;
import eu.midnightdust.lib.config.MidnightConfigListWidget;
import eu.midnightdust.lib.config.MidnightConfigScreen;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.gui.widget.TextIconButtonWidget;
import net.minecraft.client.input.KeyInput;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.glfw.GLFW;
/*
Pre-made additional (niche) functionality that is not included in MidnightLib to keep the file size small.
Feel free to copy the parts you need :)
*/
public class MidnightLibExtras {
public static class KeybindButton extends ButtonWidget {
public static ButtonWidget focusedButton;
public static void add(KeyBinding binding, MidnightConfigListWidget list, MidnightConfigScreen screen) {
KeybindButton editButton = new KeybindButton(screen.width - 185, 0, 150, 20, binding);
TextIconButtonWidget resetButton = TextIconButtonWidget.builder(Text.translatable("controls.reset"), (button -> {
binding.setBoundKey(binding.getDefaultKey());
screen.updateList();
}), true).texture(Identifier.of("midnightlib","icon/reset"), 12, 12).dimension(20, 20).build();
resetButton.setPosition(screen.width - 205 + 150 + 25, 0);
editButton.resetButton = resetButton;
editButton.updateMessage(false);
EntryInfo info = new EntryInfo(null, screen.modid);
list.addButton(Lists.newArrayList(editButton, resetButton), Text.translatable(binding.getId()), info);
}
private final KeyBinding binding;
private @Nullable ClickableWidget resetButton;
public KeybindButton(int x, int y, int width, int height, KeyBinding binding) {
super(x, y, width, height, binding.getBoundKeyLocalizedText(), (button) -> {
((KeybindButton) button).updateMessage(true);
focusedButton = button;
}, (textSupplier) -> binding.isUnbound() ? Text.translatable("narrator.controls.unbound", binding.getId()) : Text.translatable("narrator.controls.bound", binding.getId(), textSupplier.get()));
this.binding = binding;
updateMessage(false);
}
@Override
public boolean keyPressed(KeyInput input) {
if (focusedButton == this) {
if (input.key() == GLFW.GLFW_KEY_ESCAPE) {
this.binding.setBoundKey(InputUtil.UNKNOWN_KEY);
} else {
this.binding.setBoundKey(InputUtil.fromKeyCode(input));
}
updateMessage(false);
focusedButton = null;
return true;
}
return super.keyPressed(input);
}
public void updateMessage(boolean focused) {
boolean hasConflicts = false;
MutableText conflictingBindings = Text.empty();
if (focused) this.setMessage(Text.literal("> ").append(this.binding.getBoundKeyLocalizedText().copy().formatted(Formatting.WHITE, Formatting.UNDERLINE)).append(" <").formatted(Formatting.YELLOW));
else {
this.setMessage(this.binding.getBoundKeyLocalizedText());
if (!this.binding.isUnbound()) {
for(KeyBinding keyBinding : MinecraftClient.getInstance().options.allKeys) {
if (keyBinding != this.binding && this.binding.equals(keyBinding)) {
if (hasConflicts) conflictingBindings.append(", ");
hasConflicts = true;
conflictingBindings.append(Text.translatable(keyBinding.getId()));
}
}
}
}
if (this.resetButton != null) this.resetButton.active = !this.binding.isDefault();
if (hasConflicts) {
this.setMessage(Text.literal("[ ").append(this.getMessage().copy().formatted(Formatting.WHITE)).append(" ]").formatted(Formatting.RED));
this.setTooltip(Tooltip.of(Text.translatable("controls.keybinds.duplicateKeybinds", conflictingBindings)));
} else {
this.setTooltip(null);
}
}
}
}

View File

@@ -1,16 +1,25 @@
package eu.midnightdust.fabric.example.config; package eu.midnightdust.test.config;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import eu.midnightdust.lib.config.MidnightConfigListWidget;
import eu.midnightdust.lib.config.MidnightConfigScreen;
import eu.midnightdust.test.MidnightLibExtras;
import eu.midnightdust.lib.config.MidnightConfig; import eu.midnightdust.lib.config.MidnightConfig;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.TranslatableOption;
import javax.swing.*; import javax.swing.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
/** Every option in a MidnightConfig class has to be public and static, so we can access it from other classes. /** Every option in a MidnightConfig class has to be public and static, so we can access it from other classes.
* The config class also has to extend MidnightConfig*/ * The config class also has to extend MidnightConfig*/
@SuppressWarnings("unused") @SuppressWarnings({"unused", "DefaultAnnotationParam"})
public class MidnightConfigExample extends MidnightConfig { public class MidnightConfigExample extends MidnightConfig {
public static final String TEXT = "text"; public static final String TEXT = "text";
public static final String NUMBERS = "numbers"; public static final String NUMBERS = "numbers";
@@ -18,6 +27,7 @@ public class MidnightConfigExample extends MidnightConfig {
public static final String LISTS = "lists"; public static final String LISTS = "lists";
public static final String FILES = "files"; public static final String FILES = "files";
public static final String CONDITIONS = "conditions"; public static final String CONDITIONS = "conditions";
public static final String EXTRAS = "extras";
@Comment(category = TEXT) public static Comment text1; // Comments are rendered like an option without a button and are excluded from the config file @Comment(category = TEXT) public static Comment text1; // Comments are rendered like an option without a button and are excluded from the config file
@Comment(category = TEXT, centered = true) public static Comment text2; // Centered comments are the same as normal ones - just centered! @Comment(category = TEXT, centered = true) public static Comment text2; // Centered comments are the same as normal ones - just centered!
@@ -31,6 +41,10 @@ public class MidnightConfigExample extends MidnightConfig {
public enum ModPlatform { // Enums allow the user to cycle through predefined options public enum ModPlatform { // Enums allow the user to cycle through predefined options
QUILT, FABRIC, FORGE, NEOFORGE, VANILLA QUILT, FABRIC, FORGE, NEOFORGE, VANILLA
} }
@Entry(category = TEXT) public static GraphicsSteps graphicsSteps = GraphicsSteps.FABULOUS; // Example for an enum option with TranslatableOption
@Comment(category = TEXT, name = "§nMidnightLib Wiki", centered = true, url = "https://www.midnightdust.eu/wiki/midnightlib/") public static Comment wiki; // Example for a comment with a url
@Entry(category = NUMBERS) public static int fabric = 16777215; // Example for an int option @Entry(category = NUMBERS) public static int fabric = 16777215; // Example for an int option
@Entry(category = NUMBERS) public static double world = 1.4D; // Example for a double option @Entry(category = NUMBERS) public static double world = 1.4D; // Example for a double option
@Entry(category = NUMBERS, min=69,max=420) public static int hello = 420; // - The entered number has to be larger than 69 and smaller than 420 @Entry(category = NUMBERS, min=69,max=420) public static int hello = 420; // - The entered number has to be larger than 69 and smaller than 420
@@ -113,4 +127,46 @@ public class MidnightConfigExample extends MidnightConfig {
@Comment(category = CONDITIONS, name="You disabled MidnightLib's config screen list. Why? :(", centered = true) public static Comment why; @Comment(category = CONDITIONS, name="You disabled MidnightLib's config screen list. Why? :(", centered = true) public static Comment why;
public static int imposter = 16777215; // - Entries without an @Entry or @Comment annotation are ignored public static int imposter = 16777215; // - Entries without an @Entry or @Comment annotation are ignored
public enum GraphicsSteps implements TranslatableOption {
FAST(0, "options.graphics.fast"),
FANCY(1, "options.graphics.fancy"),
FABULOUS(2, "options.graphics.fabulous");
private final int id;
private final String translationKey;
GraphicsSteps(int id, String translationKey) {
this.id = id;
this.translationKey = translationKey;
}
@Override
public Text getText() {
MutableText mutableText = Text.translatable(this.getTranslationKey());
return this == GraphicsSteps.FABULOUS ? mutableText.formatted(Formatting.ITALIC).formatted(Formatting.AQUA) : mutableText;
}
@Override
public int getId() {
return this.id;
}
@Override
public String getTranslationKey() {
return this.translationKey;
}
}
@Condition(requiredModId = "thismoddoesnotexist")
@Comment(category = EXTRAS) public static Comment iAmJustADummy; // We only have this to initialize an empty tab for the keybinds below
@Override
public void onTabInit(String tabName, MidnightConfigListWidget list, MidnightConfigScreen screen) {
if (Objects.equals(tabName, EXTRAS)) {
MidnightLibExtras.KeybindButton.add(MinecraftClient.getInstance().options.advancementsKey, list, screen);
MidnightLibExtras.KeybindButton.add(MinecraftClient.getInstance().options.dropKey, list, screen);
}
}
} }

View File

@@ -16,6 +16,7 @@
"modid.midnightconfig.enum.ModPlatform.QUILT":"Quilt", "modid.midnightconfig.enum.ModPlatform.QUILT":"Quilt",
"modid.midnightconfig.enum.ModPlatform.NEOFORGE":"NeoForge", "modid.midnightconfig.enum.ModPlatform.NEOFORGE":"NeoForge",
"modid.midnightconfig.enum.ModPlatform.VANILLA":"Vanilla", "modid.midnightconfig.enum.ModPlatform.VANILLA":"Vanilla",
"modid.midnightconfig.graphicsSteps":"I am an enum with TranslatableOption!",
"modid.midnightconfig.myFileOrDirectory.fileChooser": "Select an image or directory", "modid.midnightconfig.myFileOrDirectory.fileChooser": "Select an image or directory",
"modid.midnightconfig.myFileOrDirectory.fileFilter": "Supported Images (.png, .jpg, .jpeg)", "modid.midnightconfig.myFileOrDirectory.fileFilter": "Supported Images (.png, .jpg, .jpeg)",
"modid.midnightconfig.category.numbers": "Numbers", "modid.midnightconfig.category.numbers": "Numbers",
@@ -24,5 +25,6 @@
"modid.midnightconfig.category.lists": "Lists", "modid.midnightconfig.category.lists": "Lists",
"modid.midnightconfig.category.files": "Files", "modid.midnightconfig.category.files": "Files",
"modid.midnightconfig.category.conditions": "Quiz", "modid.midnightconfig.category.conditions": "Quiz",
"modid.midnightconfig.category.extras": "Extras",
"modid.midnightconfig.category.multiConditions": "Multi-Conditions" "modid.midnightconfig.category.multiConditions": "Multi-Conditions"
} }

View File

@@ -0,0 +1,28 @@
{
"modid.midnightconfig.title": "Soy un título",
"modid.midnightconfig.text1": "Soy un comentario *u*",
"modid.midnightconfig.text2": "Soy un comentario centrado (╯°□°)╯︵ ┻━┻",
"modid.midnightconfig.name": "¡Soy una cadena de texto!",
"modid.midnightconfig.name.label.tooltip": "Soy el tooltip de una etiqueta \n¡Wujuu!",
"modid.midnightconfig.name.tooltip": "Soy un tooltip uwu \nY una nueva línea",
"modid.midnightconfig.fabric": "Soy un entero",
"modid.midnightconfig.world": "Soy un número decimal",
"modid.midnightconfig.showInfo": "Soy un booleano",
"modid.midnightconfig.hello": "¡Soy un entero limitado!",
"modid.midnightconfig.id": "¡Soy un identificador de ítem!",
"modid.midnightconfig.modPlatform": "¡Soy un enumerador!",
"modid.midnightconfig.enum.ModPlatform.FORGE": "Forge",
"modid.midnightconfig.enum.ModPlatform.FABRIC": "Fabric",
"modid.midnightconfig.enum.ModPlatform.QUILT": "Quilt",
"modid.midnightconfig.enum.ModPlatform.NEOFORGE": "NeoForge",
"modid.midnightconfig.enum.ModPlatform.VANILLA": "Vanilla",
"modid.midnightconfig.myFileOrDirectory.fileChooser": "Seleccioná una imagen o carpeta",
"modid.midnightconfig.myFileOrDirectory.fileFilter": "Imágenes compatibles (.png, .jpg, .jpeg)",
"modid.midnightconfig.category.numbers": "Números",
"modid.midnightconfig.category.text": "Texto",
"modid.midnightconfig.category.sliders": "Deslizadores",
"modid.midnightconfig.category.lists": "Listas",
"modid.midnightconfig.category.files": "Archivos",
"modid.midnightconfig.category.conditions": "Cuestionario",
"modid.midnightconfig.category.multiConditions": "Condiciones múltiples"
}

View File

@@ -11,7 +11,32 @@ architectury {
fabric() fabric()
} }
sourceSets {
test {
compileClasspath += main.compileClasspath
runtimeClasspath += main.runtimeClasspath
java {
srcDirs.add('src/test/java' as File)
}
resources {
srcDirs.add('src/test/resources' as File)
}
}
}
loom { loom {
runs {
testClient {
client()
configName = "Test Minecraft Client"
source sourceSets.test
}
testServer {
server()
configName = "Test Minecraft Server"
source sourceSets.test
}
}
} }
configurations { configurations {
@@ -27,10 +52,12 @@ configurations {
dependencies { dependencies {
modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}" modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}"
modApi "net.fabricmc.fabric-api:fabric-api:${rootProject.fabric_api_version}" modApi "net.fabricmc.fabric-api:fabric-api:${rootProject.fabric_api_version}"
modCompileOnly ("com.terraformersmc:modmenu:${rootProject.mod_menu_version}") modCompileOnly("com.terraformersmc:modmenu:${rootProject.mod_menu_version}")
common(project(path: ":common", configuration: "namedElements")) { transitive false } common(project(path: ":common", configuration: "namedElements")) { transitive false }
shadowCommon(project(path: ":common", configuration: "transformProductionFabric")) { transitive false } shadowCommon(project(path: ":common", configuration: "transformProductionFabric")) { transitive false }
testImplementation common(project(path: ':common', configuration: 'testOutput'))
} }
processResources { processResources {
@@ -41,6 +68,14 @@ processResources {
} }
} }
processTestResources {
inputs.property "version", rootProject.version
filesMatching("fabric.mod.json") {
expand "version": rootProject.version
}
}
shadowJar { shadowJar {
exclude "architectury.common.json" exclude "architectury.common.json"
@@ -71,7 +106,7 @@ unifiedPublishing {
releaseType = "$project.release_type" releaseType = "$project.release_type"
changelog = releaseChangelog() changelog = releaseChangelog()
gameVersions = [] gameVersions = []
gameLoaders = ["fabric","quilt"] gameLoaders = ["fabric", "quilt"]
mainPublication remapJar mainPublication remapJar
relations { relations {
depends { depends {

View File

@@ -1,10 +1,11 @@
package eu.midnightdust.fabric.core; package eu.midnightdust.fabric.core;
import eu.midnightdust.core.MidnightLib; import eu.midnightdust.core.MidnightLib;
import net.fabricmc.api.*; import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.DedicatedServerModInitializer;
public class MidnightLibFabric implements DedicatedServerModInitializer, ClientModInitializer { public class MidnightLibFabric implements DedicatedServerModInitializer, ClientModInitializer {
@Override @Environment(EnvType.CLIENT) @Override
public void onInitializeClient() { public void onInitializeClient() {
MidnightLib.onInitializeClient(); MidnightLib.onInitializeClient();
MidnightLib.registerAutoCommand(); MidnightLib.registerAutoCommand();

View File

@@ -18,9 +18,10 @@ public class AutoModMenu implements ModMenuApi {
@Override @Override
public Map<String, ConfigScreenFactory<?>> getProvidedConfigScreenFactories() { public Map<String, ConfigScreenFactory<?>> getProvidedConfigScreenFactories() {
HashMap<String, ConfigScreenFactory<?>> map = new HashMap<>(); HashMap<String, ConfigScreenFactory<?>> map = new HashMap<>();
MidnightConfig.configClass.forEach((modid, cClass) -> { MidnightConfig.configInstances.forEach((modid, cClass) -> {
if (!MidnightLib.hiddenMods.contains(modid)) if (!MidnightLib.hiddenMods.contains(modid))
map.put(modid, parent -> MidnightConfig.getScreen(parent, modid)); map.put(modid, parent -> MidnightConfig.getScreen(parent, modid));
}); return map; });
return map;
} }
} }

View File

@@ -0,0 +1,12 @@
package eu.midnightdust.test.fabric;
import eu.midnightdust.test.config.MidnightConfigExample;
import eu.midnightdust.lib.config.MidnightConfig;
import net.fabricmc.api.ModInitializer;
public class MLExampleFabric implements ModInitializer {
@Override
public void onInitialize() {
MidnightConfig.init("modid", MidnightConfigExample.class);
}
}

View File

@@ -1,10 +1,10 @@
{ {
"schemaVersion": 1, "schemaVersion": 1,
"id": "midnightlib-example", "id": "modid",
"version": "${version}", "version": "${version}",
"name": "MidnightLib Example", "name": "MidnightLib Test Mod",
"description": "Wow, you can do so much.", "description": "Example Mod for Team MidnightDust's mods.",
"authors": [ "MidnightDust" ], "authors": [ "MidnightDust" ],
"license": "CC0", "license": "CC0",
@@ -13,7 +13,7 @@
"environment": "*", "environment": "*",
"entrypoints": { "entrypoints": {
"main": [ "main": [
"eu.midnightdust.fabric.example.MLExampleFabric" "eu.midnightdust.test.fabric.MLExampleFabric"
] ]
}, },
"depends": { "depends": {

View File

@@ -1,21 +1,21 @@
org.gradle.jvmargs=-Xmx4096M org.gradle.jvmargs=-Xmx3172M
minecraft_version=1.21.4 minecraft_version=1.21.9
supported_versions=1.21.5 supported_versions=
yarn_mappings=1.21.4+build.1 yarn_mappings=1.21.9+build.1
enabled_platforms=fabric,neoforge enabled_platforms=fabric,neoforge
archives_base_name=midnightlib archives_base_name=midnightlib
mod_version=1.7.2-rc.1 mod_version=1.8.3
maven_group=eu.midnightdust maven_group=eu.midnightdust
release_type=release release_type=release
curseforge_id=488090 curseforge_id=488090
modrinth_id=codAaoxh modrinth_id=codAaoxh
fabric_loader_version=0.16.9 fabric_loader_version=0.17.2
fabric_api_version=0.110.5+1.21.4 fabric_api_version=0.133.14+1.21.9
neoforge_version=21.4.3-beta neoforge_version=21.9.9-beta
yarn_mappings_patch_neoforge_version = 1.21+build.4 yarn_mappings_patch_neoforge_version = 1.21+build.4
mod_menu_version = 9.0.0 mod_menu_version = 9.0.0

Binary file not shown.

View File

@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

44
gradlew vendored
View File

@@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
# #
# Copyright © 2015-2021 the original authors. # Copyright © 2015 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
# #
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,13 +82,11 @@ do
esac esac
done done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # This is normally unused
# shellcheck disable=SC2034
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -114,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;; NONSTOP* ) nonstop=true ;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
@@ -133,22 +132,29 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
case $MAX_FD in #( case $MAX_FD in #(
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -165,7 +171,6 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java # For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" ) JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -193,16 +198,19 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
# shell script including quotes and variable substitutions, so put them in DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded. # Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available. # Stop when "xargs" is not available.

26
gradlew.bat vendored
View File

@@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@@ -26,6 +28,7 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@@ -42,11 +45,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -56,22 +59,21 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell

View File

@@ -13,11 +13,58 @@ repositories {
architectury { architectury {
platformSetupLoomIde() platformSetupLoomIde()
neoForge() neoForge {
platformPackage = "neoforge"
}
}
sourceSets {
test {
compileClasspath += main.compileClasspath
runtimeClasspath += main.runtimeClasspath
java {
srcDirs.add('src/test/java' as File)
}
resources {
srcDirs.add('src/test/resources' as File)
}
}
} }
loom { loom {
accessWidenerPath = project(":common").loom.accessWidenerPath accessWidenerPath = project(":common").loom.accessWidenerPath
runs {
testClient {
client()
name = "Test Minecraft Client"
mods {
create('midnightlib') {
sourceSet sourceSets.main
}
create('modid') { // test mod
sourceSet sourceSets.test
}
}
source sourceSets.test
}
testServer {
server()
name = "Test Minecraft Server"
mods {
create('midnightlib') {
sourceSet sourceSets.main
}
create('modid') { // test mod
sourceSet sourceSets.test
}
}
source sourceSets.test
}
}
} }
configurations { configurations {
@@ -44,6 +91,10 @@ dependencies {
common(project(path: ':common', configuration: 'namedElements')) { transitive false } common(project(path: ':common', configuration: 'namedElements')) { transitive false }
shadowBundle project(path: ':common', configuration: 'transformProductionNeoForge') shadowBundle project(path: ':common', configuration: 'transformProductionNeoForge')
// testImplementation common(project(path: ':common', configuration: 'namedElements')) { transitive false }
testImplementation common(project(path: ':common', configuration: 'testOutput')) { transitive false }
testImplementation sourceSets.main.output
} }
processResources { processResources {
@@ -54,6 +105,14 @@ processResources {
} }
} }
processTestResources {
inputs.property 'version', rootProject.version
filesMatching('META-INF/neoforge.mods.toml') {
expand version: rootProject.version
}
}
shadowJar { shadowJar {
configurations = [project.configurations.shadowBundle] configurations = [project.configurations.shadowBundle]
archiveClassifier = 'dev-shadow' archiveClassifier = 'dev-shadow'
@@ -105,4 +164,4 @@ unifiedPublishing {
} }
} }
} }
} }

View File

@@ -22,7 +22,7 @@ public class PlatformFunctionsImpl {
return FMLPaths.CONFIGDIR.get(); return FMLPaths.CONFIGDIR.get();
} }
public static boolean isClientEnv() { public static boolean isClientEnv() {
return FMLEnvironment.dist.isClient(); return FMLEnvironment.getDist().isClient();
} }
public static boolean isModLoaded(String modid) { public static boolean isModLoaded(String modid) {
return ModList.get().isLoaded(modid); return ModList.get().isLoaded(modid);

View File

@@ -23,15 +23,15 @@ public class MidnightLibNeoForge {
public static List<LiteralArgumentBuilder<ServerCommandSource>> commands = new ArrayList<>(); public static List<LiteralArgumentBuilder<ServerCommandSource>> commands = new ArrayList<>();
public MidnightLibNeoForge() { public MidnightLibNeoForge() {
if (FMLEnvironment.dist == Dist.CLIENT) MidnightLib.onInitializeClient(); if (FMLEnvironment.getDist() == Dist.CLIENT) MidnightLib.onInitializeClient();
} }
@EventBusSubscriber(modid = "midnightlib", bus = EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) @EventBusSubscriber(modid = "midnightlib", value = Dist.CLIENT)
public static class MidnightLibBusEvents { public static class MidnightLibBusEvents {
@SubscribeEvent @SubscribeEvent
public static void onPostInit(FMLClientSetupEvent event) { public static void onPostInit(FMLClientSetupEvent event) {
ModList.get().forEachModContainer((modid, modContainer) -> { ModList.get().forEachModContainer((modid, modContainer) -> {
if (MidnightConfig.configClass.containsKey(modid) && !MidnightLib.hiddenMods.contains(modid)) { if (MidnightConfig.configInstances.containsKey(modid) && !MidnightLib.hiddenMods.contains(modid)) {
modContainer.registerExtensionPoint(IConfigScreenFactory.class, (minecraftClient, screen) -> MidnightConfig.getScreen(screen, modid)); modContainer.registerExtensionPoint(IConfigScreenFactory.class, (minecraftClient, screen) -> MidnightConfig.getScreen(screen, modid));
} }
}); });

View File

@@ -0,0 +1,12 @@
package eu.midnightdust.test.neoforge;
import eu.midnightdust.test.config.MidnightConfigExample;
import net.neoforged.fml.common.Mod;
@Mod(MLExampleNeoForge.MODID)
public class MLExampleNeoForge {
public static final String MODID = "modid";
public MLExampleNeoForge() {
MidnightConfigExample.init(MODID, MidnightConfigExample.class);
}
}

View File

@@ -0,0 +1,34 @@
modLoader = "javafml"
loaderVersion = "[2,)"
#issueTrackerURL = ""
license = "MIT License"
[[mods]]
modId = "modid"
version = "${version}"
displayName = "MidnightLib Test Mod"
authors = "TeamMidnightDust, Motschen"
description = '''
Example Mod for Team MidnightDust's mods.
'''
[[dependencies.modid]]
modId = "neoforge"
mandatory = true
versionRange = "[20.5,)"
ordering = "NONE"
side = "BOTH"
[[dependencies.modid]]
modId = "minecraft"
mandatory = true
versionRange = "[1.20.5,)"
ordering = "NONE"
side = "BOTH"
[[dependencies.modid]]
modId = "midnightlib"
mandatory = true
versionRange = "[1.0,)"
ordering = "NONE"
side = "BOTH"

View File

@@ -9,9 +9,7 @@ pluginManagement {
include("common") include("common")
include("fabric") include("fabric")
include("test-fabric")
include("neoforge") include("neoforge")
include("test-neoforge")
//include("quilt") //include("quilt")
rootProject.name = "midnightlib" rootProject.name = "midnightlib"

View File

@@ -1,32 +0,0 @@
plugins {
id 'com.github.johnrengelman.shadow'
id "me.shedaniel.unified-publishing"
}
repositories {
maven { url "https://maven.terraformersmc.com/releases" }
}
architectury {
platformSetupLoomIde()
fabric()
}
loom {
}
configurations {
common
shadowCommon // Don't use shadow from the shadow plugin since it *excludes* files.
compileClasspath.extendsFrom common
runtimeClasspath.extendsFrom common
developmentFabric.extendsFrom common
archivesBaseName = rootProject.archives_base_name + "-fabric"
}
dependencies {
modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}"
modApi "net.fabricmc.fabric-api:fabric-api:${rootProject.fabric_api_version}"
implementation project(path: ":fabric", configuration: "namedElements")
common(project(path: ":common", configuration: "namedElements")) { transitive false }
}

View File

@@ -1,11 +0,0 @@
package eu.midnightdust.fabric.example;
import eu.midnightdust.fabric.example.config.MidnightConfigExample;
import net.fabricmc.api.ModInitializer;
public class MLExampleFabric implements ModInitializer {
@Override
public void onInitialize() {
MidnightConfigExample.init("modid", MidnightConfigExample.class);
}
}