commit 83d02c145ff4151d684dc1feab899b6873a3b9ca Author: JFronny <33260128+jfronny@users.noreply.github.com> Date: Sun Apr 11 16:00:37 2021 +0200 Add files diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c37caf --- /dev/null +++ b/.gitignore @@ -0,0 +1,118 @@ +# User-specific stuff +.idea/ + +*.iml +*.ipr +*.iws + +# IntelliJ +out/ +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Cache of project +.gradletasknamecache + +**/build/ + +# Common working directory +run/ + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..27c2a58 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 JFronny + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..7079eb4 --- /dev/null +++ b/build.gradle @@ -0,0 +1,80 @@ +plugins { + id 'fabric-loom' version '0.7-SNAPSHOT' + id 'maven-publish' +} + +sourceCompatibility = JavaVersion.VERSION_1_8 +targetCompatibility = JavaVersion.VERSION_1_8 + +archivesBaseName = project.archives_base_name +version = project.mod_version +group = project.maven_group + +repositories { + maven { url = 'https://maven.terraformersmc.com/'; name = "ModMenu" } +} + +dependencies { + //to change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + + // PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs. + // You may need to force-disable transitiveness on them. + modImplementation "com.terraformersmc:modmenu:1.16.9" +} + +processResources { + inputs.property "version", project.version + + from(sourceSets.main.resources.srcDirs) { + include "fabric.mod.json" + expand "version": project.version + } + + from(sourceSets.main.resources.srcDirs) { + exclude "fabric.mod.json" + } +} + +// ensure that the encoding is set to UTF-8, no matter what the system default is +// this fixes some edge cases with special characters not displaying correctly +// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" +} + +// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task +// if it is present. +// If you remove this task, sources will not be generated. +task sourcesJar(type: Jar, dependsOn: classes) { + classifier = "sources" + from sourceSets.main.allSource +} + +jar { + from "LICENSE" +} + +// configure the maven publication +publishing { + publications { + mavenJava(MavenPublication) { + // add all the jars that should be included when publishing to maven + artifact(remapJar) { + builtBy remapJar + } + artifact(sourcesJar) { + builtBy remapSourcesJar + } + } + } + + // select the repositories you want to publish to + repositories { + // uncomment to publish to the local maven + // mavenLocal() + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..c052c05 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,11 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +# Fabric Properties +# check these on https://modmuss50.me/fabric.html +minecraft_version=1.16.5 +yarn_mappings=1.16.5+build.6 +loader_version=0.11.3 +# Mod Properties +mod_version=1.0.0 +maven_group=io.gitlab.jfronny +archives_base_name=libjf \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..62d4c05 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bb8b2fc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..fbd7c51 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + 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. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..5093609 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,104 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..5b60df3 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +pluginManagement { + repositories { + jcenter() + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} diff --git a/src/main/java/io/gitlab/jfronny/libjf/ExampleConfig.java b/src/main/java/io/gitlab/jfronny/libjf/ExampleConfig.java new file mode 100644 index 0000000..a2c2249 --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/libjf/ExampleConfig.java @@ -0,0 +1,36 @@ +package io.gitlab.jfronny.libjf; + +import io.gitlab.jfronny.libjf.config.Entry; +import io.gitlab.jfronny.libjf.config.EntryInfo; +import io.gitlab.jfronny.libjf.config.JfConfig; +import net.minecraft.text.LiteralText; +import net.minecraft.text.Text; + +import java.util.Collections; +import java.util.List; + +/*from https://github.com/Minenash/TinyConfig*/ +public class ExampleConfig implements JfConfig { + @Entry + public static boolean boolTest = false; + + @Entry(min = 5) + public static int intTest = 20; + + @Entry + public static double decimalTest = 20; + + @Entry(dynamicTooltip = "dieStrTooltip", max = 5) + public static String dieStr = "lolz"; + + @Entry + public static Test enumTest = Test.Test; + + private static List dieStrTooltip(List infos) { + return Collections.singletonList(new LiteralText("safbjkasf")); + } + + public enum Test { + Test, ER + } +} diff --git a/src/main/java/io/gitlab/jfronny/libjf/Libjf.java b/src/main/java/io/gitlab/jfronny/libjf/Libjf.java new file mode 100644 index 0000000..e1d3573 --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/libjf/Libjf.java @@ -0,0 +1,52 @@ +package io.gitlab.jfronny.libjf; + +import com.google.common.collect.ImmutableMap; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import io.gitlab.jfronny.libjf.config.Config; +import io.gitlab.jfronny.libjf.config.JfConfig; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.entrypoint.EntrypointContainer; +import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; + +public class Libjf implements PreLaunchEntrypoint { + public static final String MOD_ID = "libjf"; + public static final Logger LOGGER = LogManager.getLogger(MOD_ID); + public static final Gson GSON = new GsonBuilder() + .excludeFieldsWithModifiers(Modifier.TRANSIENT) + .excludeFieldsWithModifiers(Modifier.PRIVATE) + .setPrettyPrinting() + .create(); + private static final Map configs = new HashMap<>(); + + @Override + public void onPreLaunch() { + registerConfig(MOD_ID, ExampleConfig.class); + for (EntrypointContainer entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(MOD_ID + ":config", JfConfig.class)) { + String id = entrypointContainer.getProvider().getMetadata().getId(); + Libjf.registerConfig(id, entrypointContainer.getEntrypoint().getClass()); + Libjf.LOGGER.info("Registering config for " + id); + } + } + + public static void registerConfig(String modId, Class config) { + if (!isRegistered(config)) + configs.put(modId, new Config(modId, config)); + } + public static Map getConfigs() { + return ImmutableMap.copyOf(configs); + } + public static boolean isRegistered(Class config) { + for (Config value : configs.values()) { + if (value.configClass.equals(config)) + return true; + } + return false; + } +} diff --git a/src/main/java/io/gitlab/jfronny/libjf/config/Config.java b/src/main/java/io/gitlab/jfronny/libjf/config/Config.java new file mode 100644 index 0000000..a15e071 --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/libjf/config/Config.java @@ -0,0 +1,136 @@ +package io.gitlab.jfronny.libjf.config; + +import io.gitlab.jfronny.libjf.Libjf; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.text.*; +import net.minecraft.util.Formatting; + +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +/* Based on https://github.com/TeamMidnightDust/MidnightLib +* see https://github.com/TeamMidnightDust/MidnightLib/blob/main/LICENSE +*/ + +@SuppressWarnings("rawtypes") +public class Config { + private static final Pattern INTEGER_ONLY = Pattern.compile("(-?[0-9]*)"); + private static final Pattern DECIMAL_ONLY = Pattern.compile("-?([\\d]+\\.?[\\d]*|[\\d]*\\.?[\\d]+|\\.)"); + + public Class configClass; + public String translationPrefix; + public Path path; + public final List entries = new ArrayList<>(); + + public Config(String modid, Class config) { + translationPrefix = modid + ".jfconfig."; + path = FabricLoader.getInstance().getConfigDir().resolve(modid + ".json"); + configClass = config; + + for (Field field : config.getFields()) { + Class type = field.getType(); + EntryInfo info = new EntryInfo(); + + Entry e; + try { e = field.getAnnotation(Entry.class); } + catch (Exception ignored) { continue; } + + info.width = e.width(); + info.field = field; + + if (type == int.class) textField(info, Integer::parseInt, INTEGER_ONLY, e.min(), e.max(), true); + else if (type == double.class) textField(info, Double::parseDouble, DECIMAL_ONLY, e.min(), e.max(),false); + else if (type == float.class) textField(info, Float::parseFloat, DECIMAL_ONLY, e.min(), e.max(),false); + else if (type == String.class) textField(info, String::length, null, Math.min(e.min(),0), Math.max(e.max(),1),true); + else if (type == boolean.class) { + Function func = value -> new LiteralText((Boolean) value ? "True" : "False").formatted((Boolean) value ? Formatting.GREEN : Formatting.RED); + info.widget = new AbstractMap.SimpleEntry>(button -> { + info.value = !(Boolean) info.value; + button.setMessage(func.apply(info.value)); + }, func); + } + else if (type.isEnum()) { + List values = Arrays.asList(field.getType().getEnumConstants()); + Function func = value -> new TranslatableText(translationPrefix + "enum." + type.getSimpleName() + "." + info.value.toString()); + info.widget = new AbstractMap.SimpleEntry>( button -> { + int index = values.indexOf(info.value) + 1; + info.value = values.get(index >= values.size()? 0 : index); + button.setMessage(func.apply(info.value)); + }, func); + } + else + continue; + + entries.add(info); + + try { info.defaultValue = field.get(null); } + catch (IllegalAccessException ignored) {} + + try { + info.dynamicTooltip = config.getMethod(e.dynamicTooltip()); + info.dynamicTooltip.setAccessible(true); + } catch (Exception ignored) {} + + } + + try { Libjf.GSON.fromJson(Files.newBufferedReader(path), config); } + catch (Exception e) { write(); } + + for (EntryInfo info : entries) { + try { + info.value = info.field.get(null); + info.tempValue = info.value.toString(); + } + catch (IllegalAccessException ignored) {} + } + } + + private void textField(EntryInfo info, Function f, Pattern pattern, double min, double max, boolean cast) { + boolean isNumber = pattern != null; + info.widget = (BiFunction>) (t, b) -> s -> { + s = s.trim(); + if (!(s.isEmpty() || !isNumber || pattern.matcher(s).matches())) + return false; + + Number value = 0; + boolean inLimits = false; + System.out.println(((isNumber ^ s.isEmpty()))); + System.out.println(!s.equals("-") && !s.equals(".")); + info.error = null; + if (!(isNumber && s.isEmpty()) && !s.equals("-") && !s.equals(".")) { + value = f.apply(s); + inLimits = value.doubleValue() >= min && value.doubleValue() <= max; + info.error = inLimits? null : new AbstractMap.SimpleEntry<>(t, new LiteralText(value.doubleValue() < min ? + "§cMinimum " + (isNumber? "value" : "length") + (cast? " is " + (int)min : " is " + min) : + "§cMaximum " + (isNumber? "value" : "length") + (cast? " is " + (int)max : " is " + max))); + } + + info.tempValue = s; + t.setEditableColor(inLimits? 0xFFFFFFFF : 0xFFFF7777); + info.inLimits = inLimits; + b.active = entries.stream().allMatch(e -> e.inLimits); + + if (inLimits) + info.value = isNumber? value : s; + + return true; + }; + } + + public void write() { + try { + if (!Files.exists(path)) Files.createFile(path); + Files.write(path, Libjf.GSON.toJson(configClass.newInstance()).getBytes()); + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/main/java/io/gitlab/jfronny/libjf/config/ConfigScreen.java b/src/main/java/io/gitlab/jfronny/libjf/config/ConfigScreen.java new file mode 100644 index 0000000..50066f7 --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/libjf/config/ConfigScreen.java @@ -0,0 +1,132 @@ +package io.gitlab.jfronny.libjf.config; + +import io.gitlab.jfronny.libjf.Libjf; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.screen.ScreenTexts; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.client.resource.language.I18n; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.LiteralText; +import net.minecraft.text.Text; +import net.minecraft.text.TranslatableText; +import net.minecraft.util.Formatting; + +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; + +public class ConfigScreen extends Screen { + public ConfigScreen(Screen parent, Config config) { + super(new TranslatableText(config.translationPrefix + "title")); + this.parent = parent; + this.config = config; + } + private final Screen parent; + private final Config config; + + // Real Time config update // + @Override + public void tick() { + for (EntryInfo info : config.entries) + try { info.field.set(null, info.value); } + catch (IllegalAccessException ignore) {} + } + + @Override + protected void init() { + super.init(); + this.addButton(new ButtonWidget(this.width / 2 - 154, this.height - 28, 150, 20, ScreenTexts.CANCEL, button -> { + try { Libjf.GSON.fromJson(Files.newBufferedReader(config.path), config.configClass); } + catch (Exception e) { config.write(); } + + for (EntryInfo info : config.entries) { + try { + info.value = info.field.get(null); + info.tempValue = info.value.toString(); + } + catch (IllegalAccessException ignored) {} + } + Objects.requireNonNull(client).openScreen(parent); + })); + + ButtonWidget done = this.addButton(new ButtonWidget(this.width / 2 + 4, this.height - 28, 150, 20, ScreenTexts.DONE, (button) -> { + for (EntryInfo info : config.entries) + try { info.field.set(null, info.value); } + catch (IllegalAccessException ignore) {} + config.write(); + Objects.requireNonNull(client).openScreen(parent); + })); + + int y = 45; + for (EntryInfo info : config.entries) { + addButton(new ButtonWidget(width - 155, y, 40,20, new LiteralText("Reset").formatted(Formatting.RED), (button -> { + info.value = info.defaultValue; + info.tempValue = info.value.toString(); + Objects.requireNonNull(client).openScreen(this); + }))); + + if (info.widget instanceof Map.Entry) { + Map.Entry> widget = (Map.Entry>) info.widget; + addButton(new ButtonWidget(width-110,y,info.width,20, widget.getValue().apply(info.value), widget.getKey())); + } + else { + TextFieldWidget widget = addButton(new TextFieldWidget(textRenderer, width-110, y, info.width, 20, null)); + widget.setText(info.tempValue); + + Predicate processor = ((BiFunction>) info.widget).apply(widget,done); + widget.setTextPredicate(processor); + + children.add(widget); + } + y += 25; + } + + } + int aniX = this.width / 2; + @Override + public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { + this.renderBackground(matrices); + + if (aniX < this.width / 2) { + aniX = aniX +40; + } + + int stringWidth = (int) (title.getString().length() * 2.75f); + this.fillGradient(matrices, this.width / 2 - stringWidth, 10, this.width /2 + stringWidth, 29, -1072689136, -804253680); + this.fillGradient(matrices, this.width / 2 - aniX, 35, width/2 + aniX, this.height - 40, -1072689136, -804253680); + + super.render(matrices, mouseX, mouseY, delta); + drawCenteredText(matrices, textRenderer, title, width/2, 15, 0xFFFFFF); + + int y = 40; + for (EntryInfo info : config.entries) { + drawTextWithShadow(matrices, textRenderer, new TranslatableText(config.translationPrefix + info.field.getName()), 12, y + 10, 0xFFFFFF); + + if (info.error != null && info.error.getKey().isMouseOver(mouseX,mouseY)) + renderTooltip(matrices, info.error.getValue(), mouseX, mouseY); + else if (mouseY >= y && mouseY < (y + 25)) { + if (info.dynamicTooltip != null) { + try { + renderTooltip(matrices, (List) info.dynamicTooltip.invoke(null, config.entries), mouseX, mouseY); + y += 25; + continue; + } catch (Exception e) { e.printStackTrace(); } + } + String key = config.translationPrefix + info.field.getName() + ".tooltip"; + if (I18n.hasTranslation(key)) { + List list = new ArrayList<>(); + for (String str : I18n.translate(key).split("\n")) + list.add(new LiteralText(str)); + renderTooltip(matrices, list, mouseX, mouseY); + } + } + y += 25; + } + } +} diff --git a/src/main/java/io/gitlab/jfronny/libjf/config/Entry.java b/src/main/java/io/gitlab/jfronny/libjf/config/Entry.java new file mode 100644 index 0000000..23ffe0f --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/libjf/config/Entry.java @@ -0,0 +1,15 @@ +package io.gitlab.jfronny.libjf.config; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Entry { + String dynamicTooltip() default ""; + int width() default 100; + double min() default Double.MIN_NORMAL; + double max() default Double.MAX_VALUE; +} \ No newline at end of file diff --git a/src/main/java/io/gitlab/jfronny/libjf/config/EntryInfo.java b/src/main/java/io/gitlab/jfronny/libjf/config/EntryInfo.java new file mode 100644 index 0000000..512935e --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/libjf/config/EntryInfo.java @@ -0,0 +1,20 @@ +package io.gitlab.jfronny.libjf.config; + +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.text.Text; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Map; + +public class EntryInfo { + Field field; + Object widget; + int width; + Method dynamicTooltip; + Map.Entry error; + Object defaultValue; + Object value; + String tempValue; + boolean inLimits = true; +} diff --git a/src/main/java/io/gitlab/jfronny/libjf/config/JfConfig.java b/src/main/java/io/gitlab/jfronny/libjf/config/JfConfig.java new file mode 100644 index 0000000..4e8098a --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/libjf/config/JfConfig.java @@ -0,0 +1,4 @@ +package io.gitlab.jfronny.libjf.config; + +public interface JfConfig { +} diff --git a/src/main/java/io/gitlab/jfronny/libjf/config/ModMenu.java b/src/main/java/io/gitlab/jfronny/libjf/config/ModMenu.java new file mode 100644 index 0000000..ead1ff2 --- /dev/null +++ b/src/main/java/io/gitlab/jfronny/libjf/config/ModMenu.java @@ -0,0 +1,30 @@ +package io.gitlab.jfronny.libjf.config; + +import com.terraformersmc.modmenu.api.ConfigScreenFactory; +import com.terraformersmc.modmenu.api.ModMenuApi; +import io.gitlab.jfronny.libjf.Libjf; + +import java.util.HashMap; +import java.util.Map; + +public class ModMenu implements ModMenuApi { + @Override + public Map> getProvidedConfigScreenFactories() { + Map> factories = new HashMap<>(); + for (Map.Entry entry : Libjf.getConfigs().entrySet()) { + if (!Libjf.MOD_ID.equals(entry.getKey())) + factories.put(entry.getKey(), s -> new ConfigScreen(s, entry.getValue())); + } + return factories; + } + + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + for (Map.Entry entry : Libjf.getConfigs().entrySet()) { + if (Libjf.MOD_ID.equals(entry.getKey())) + return s -> new ConfigScreen(s, entry.getValue()); + } + new Exception("Could not find own config screen, this is bad").printStackTrace(); + return null; + } +} diff --git a/src/main/resources/assets/libjf/lang/en_us.json b/src/main/resources/assets/libjf/lang/en_us.json new file mode 100644 index 0000000..5c48476 --- /dev/null +++ b/src/main/resources/assets/libjf/lang/en_us.json @@ -0,0 +1,10 @@ +{ + "libjf.jfconfig.title": "JfConfig example", + "libjf.jfconfig.boolTest": "Bool Test", + "libjf.jfconfig.intTest": "Int Test", + "libjf.jfconfig.decimalTest": "Decimal Test", + "libjf.jfconfig.dieStr": "String Test", + "libjf.jfconfig.enumTest": "Enum Test", + "libjf.jfconfig.enum.Test.Test": "Test", + "libjf.jfconfig.enum.Test.ER": "ER" +} \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..4352455 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,35 @@ +{ + "schemaVersion": 1, + "id": "libjf", + "version": "${version}", + "name": "LibJF", + "description": "Library mod by JFronny", + "authors": [ + "JFronny" + ], + "contact": { + "website": "https://jfronny.gitlab.io", + "repo": "https://gitlab.com/jfmods/libjf" + }, + "license": "MIT", + "icon": "assets/libjf/icon.png", + "environment": "*", + "entrypoints": { + "preLaunch": [ + "io.gitlab.jfronny.libjf.Libjf" + ], + "modmenu": [ + "io.gitlab.jfronny.libjf.config.ModMenu" + ], + "libjf:config": [ + "io.gitlab.jfronny.libjf.ExampleConfig" + ] + }, + "mixins": [ + "libjf.mixins.json" + ], + "depends": { + "fabricloader": ">=0.11.3", + "minecraft": "1.16.5" + } +} diff --git a/src/main/resources/libjf.mixins.json b/src/main/resources/libjf.mixins.json new file mode 100644 index 0000000..77ee62b --- /dev/null +++ b/src/main/resources/libjf.mixins.json @@ -0,0 +1,13 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "io.gitlab.jfronny.libjf.mixin", + "compatibilityLevel": "JAVA_8", + "mixins": [ + ], + "client": [ + ], + "injectors": { + "defaultRequire": 1 + } +}