code cleanup

This commit is contained in:
FalsePattern committed 2022-07-31 20:41:56 +02:00
1 parent eaec528f5d
commit 316908baae
76 files changed
+691 -622

No files matched your search

@@ -12,8 +12,7 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@StableAPI(since = "0.10.0")
public @interface DeprecationDetails {
@StableAPI(since = "0.10.0")
String stableSince() default "";
@StableAPI(since = "0.10.0")
String deprecatedSince();
@StableAPI(since = "0.10.0") String stableSince() default "";
@StableAPI(since = "0.10.0") String deprecatedSince();
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -43,6 +43,5 @@ public @interface StableAPI {
/**
* The version this API was introduced/stabilized in. Used for library version tracking.
*/
@StableAPI(since = "0.6.0")
String since();
@StableAPI(since = "0.6.0") String since();
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -32,15 +32,12 @@ import com.falsepattern.lib.mapping.types.UniversalField;
import com.falsepattern.lib.mapping.types.UniversalMethod;
import lombok.SneakyThrows;
import lombok.val;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.util.CheckClassAdapter;
import java.util.Arrays;
import java.util.Objects;
@@ -65,17 +62,15 @@ public class ASMUtil {
throw new AsmClassNotFoundException("The class " + cn + " is not from Minecraft, or the mapping manager" +
"doesn't have it, cannot use findFieldFromMCP! Use findFieldStandard instead!");
}
return findFieldStandard(cn,
MappingManager.classForName(NameType.Internal, classMapping, cn.name)
.getField(MappingType.MCP, fieldName)
.getName(classMapping),
optional);
return findFieldStandard(cn, MappingManager.classForName(NameType.Internal, classMapping, cn.name)
.getField(MappingType.MCP, fieldName)
.getName(classMapping), optional);
}
public static FieldNode findFieldFromUniversal(ClassNode cn, UniversalField field, boolean optional) {
String[] possibilities = CoreLoadingPlugin.isObfuscated() ?
new String[]{field.getName(MappingType.SRG), field.getName(MappingType.Notch)} :
new String[] {field.getName(MappingType.MCP)};
String[] possibilities = CoreLoadingPlugin.isObfuscated() ? new String[]{field.getName(MappingType.SRG),
field.getName(MappingType.Notch)}
: new String[]{field.getName(MappingType.MCP)};
for (final FieldNode ret : cn.fields) {
if (anyEquals(ret.name, possibilities)) {
return ret;
@@ -84,7 +79,8 @@ public class ASMUtil {
if (optional) {
return null;
}
throw new AsmFieldNotFoundException(possibilities.length == 1 ? possibilities[0] : Arrays.toString(possibilities));
throw new AsmFieldNotFoundException(
possibilities.length == 1 ? possibilities[0] : Arrays.toString(possibilities));
}
public static MethodNode findMethodStandard(ClassNode cn, String name, String descriptor, boolean optional) {
@@ -112,12 +108,13 @@ public class ASMUtil {
}
public static MethodNode findMethodFromUniversal(ClassNode cn, UniversalMethod method, boolean optional) {
String[] possibleNames = CoreLoadingPlugin.isObfuscated() ?
new String[]{method.getName(MappingType.SRG), method.getName(MappingType.Notch)} :
new String[] {method.getName(MappingType.MCP)};
String[] possibleDescriptors = CoreLoadingPlugin.isObfuscated() ?
new String[]{method.getDescriptor(MappingType.SRG), method.getDescriptor(MappingType.Notch)} :
new String[] {method.getDescriptor(MappingType.MCP)};
String[] possibleNames = CoreLoadingPlugin.isObfuscated() ? new String[]{method.getName(MappingType.SRG),
method.getName(MappingType.Notch)}
: new String[]{method.getName(MappingType.MCP)};
String[] possibleDescriptors =
CoreLoadingPlugin.isObfuscated() ? new String[]{method.getDescriptor(MappingType.SRG),
method.getDescriptor(MappingType.Notch)}
: new String[]{method.getDescriptor(MappingType.MCP)};
for (final MethodNode ret : cn.methods) {
if (anyEquals(ret.name, possibleNames) && anyEquals(ret.desc, possibleDescriptors)) {
return ret;
@@ -126,7 +123,8 @@ public class ASMUtil {
if (optional) {
return null;
}
throw new AsmFieldNotFoundException(possibleDescriptors.length == 1 ? possibleDescriptors[0] : Arrays.toString(possibleDescriptors));
throw new AsmFieldNotFoundException(
possibleDescriptors.length == 1 ? possibleDescriptors[0] : Arrays.toString(possibleDescriptors));
}
public static MappingType discoverClassMappingType(ClassNode cn) {
@@ -175,7 +173,7 @@ public class ASMUtil {
}
public static boolean anyEquals(String str, String... options) {
for (val option: options) {
for (val option : options) {
if (Objects.equals(str, option)) {
return true;
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -24,7 +24,9 @@ import org.objectweb.asm.tree.ClassNode;
public interface IClassNodeTransformer {
String getName();
boolean shouldTransform(ClassNode cn, String transformedName, boolean obfuscated);
default int internalSortingOrder() {
return 0;
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -20,7 +20,6 @@
*/
package com.falsepattern.lib.asm;
import com.falsepattern.lib.asm.exceptions.AsmTransformException;
import com.falsepattern.lib.internal.CoreLoadingPlugin;
import lombok.val;
import org.apache.logging.log4j.Logger;
@@ -38,7 +37,9 @@ import java.util.List;
*/
public interface SmartTransformer extends IClassTransformer {
Logger logger();
List<IClassNodeTransformer> transformers();
@Override
default byte[] transform(String name, String transformedName, byte[] bytes) {
if (bytes == null) {
@@ -46,7 +47,7 @@ public interface SmartTransformer extends IClassTransformer {
}
val transformers = new ArrayList<IClassNodeTransformer>();
val cn = ASMUtil.parseClass(bytes, ClassReader.EXPAND_FRAMES);
for (val transformer: transformers()) {
for (val transformer : transformers()) {
if (transformer.shouldTransform(cn, transformedName, CoreLoadingPlugin.isObfuscated())) {
transformers.add(transformer);
}
@@ -56,7 +57,7 @@ public interface SmartTransformer extends IClassTransformer {
}
transformers.sort(Comparator.comparingInt(IClassNodeTransformer::internalSortingOrder));
val log = logger();
for (val transformer: transformers) {
for (val transformer : transformers) {
log.debug("Patching {} with {}...", transformedName, transformer.getName());
try {
transformer.transform(cn, transformedName, CoreLoadingPlugin.isObfuscated());
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -23,20 +23,22 @@ package com.falsepattern.lib.compat;
import com.falsepattern.lib.StableAPI;
import com.falsepattern.lib.util.MathUtil;
import com.google.common.collect.AbstractIterator;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.concurrent.Immutable;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.val;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.entity.Entity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Vec3;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import javax.annotation.concurrent.Immutable;
import java.util.ArrayList;
import java.util.List;
import static net.minecraft.util.EnumFacing.DOWN;
import static net.minecraft.util.EnumFacing.EAST;
@@ -105,12 +107,9 @@ public class BlockPos extends Vec3i {
* @see #getAllInBoxMutable(BlockPos, BlockPos)
*/
public static Iterable<BlockPos> getAllInBox(@NonNull BlockPos from, @NonNull BlockPos to) {
return getAllInBox(Math.min(from.getX(), to.getX()),
Math.min(from.getY(), to.getY()),
Math.min(from.getZ(), to.getZ()),
Math.max(from.getX(), to.getX()),
Math.max(from.getY(), to.getY()),
Math.max(from.getZ(), to.getZ()));
return getAllInBox(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()),
Math.min(from.getZ(), to.getZ()), Math.max(from.getX(), to.getX()),
Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ()));
}
/**
@@ -130,12 +129,7 @@ public class BlockPos extends Vec3i {
* @see #getAllInBox(BlockPos, BlockPos)
* @see #getAllInBoxMutable(BlockPos, BlockPos)
*/
public static Iterable<BlockPos> getAllInBox(final int x0,
final int y0,
final int z0,
final int x1,
final int y1,
final int z1) {
public static Iterable<BlockPos> getAllInBox(final int x0, final int y0, final int z0, final int x1, final int y1, final int z1) {
return () -> new AbstractIterator<BlockPos>() {
private boolean first = true;
private int lastX;
@@ -186,12 +180,9 @@ public class BlockPos extends Vec3i {
* @see #getAllInBoxMutable(BlockPos, BlockPos)
*/
public static Iterable<BlockPos.MutableBlockPos> getAllInBoxMutable(@NonNull BlockPos from, @NonNull BlockPos to) {
return getAllInBoxMutable(Math.min(from.getX(), to.getX()),
Math.min(from.getY(), to.getY()),
Math.min(from.getZ(), to.getZ()),
Math.max(from.getX(), to.getX()),
Math.max(from.getY(), to.getY()),
Math.max(from.getZ(), to.getZ()));
return getAllInBoxMutable(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()),
Math.min(from.getZ(), to.getZ()), Math.max(from.getX(), to.getX()),
Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ()));
}
/**
@@ -214,12 +205,7 @@ public class BlockPos extends Vec3i {
* @see #getAllInBox(int, int, int, int, int, int)
* @see #getAllInBoxMutable(BlockPos, BlockPos)
*/
public static Iterable<BlockPos.MutableBlockPos> getAllInBoxMutable(final int x0,
final int y0,
final int z0,
final int x1,
final int y1,
final int z1) {
public static Iterable<BlockPos.MutableBlockPos> getAllInBoxMutable(final int x0, final int y0, final int z0, final int x1, final int y1, final int z1) {
return () -> new AbstractIterator<MutableBlockPos>() {
private MutableBlockPos pos;
@@ -297,8 +283,7 @@ public class BlockPos extends Vec3i {
if (blocks == 0) {
return this;
}
return new BlockPos(x + facing.getFrontOffsetX() * blocks,
y + facing.getFrontOffsetY() * blocks,
return new BlockPos(x + facing.getFrontOffsetX() * blocks, y + facing.getFrontOffsetY() * blocks,
z + facing.getFrontOffsetZ() * blocks);
}
@@ -362,8 +347,7 @@ public class BlockPos extends Vec3i {
@Override
public BlockPos crossProduct(@NonNull Vec3i vec) {
return new BlockPos(y * vec.getZ() - z * vec.getY(),
z * vec.getX() - x * vec.getZ(),
return new BlockPos(y * vec.getZ() - z * vec.getY(), z * vec.getX() - x * vec.getZ(),
x * vec.getY() - y * vec.getX());
}
@@ -451,8 +435,7 @@ public class BlockPos extends Vec3i {
}
public BlockPos.MutableBlockPos move(@NonNull EnumFacing facing, int blocks) {
return this.setPos(x + facing.getFrontOffsetX() * blocks,
y + facing.getFrontOffsetY() * blocks,
return this.setPos(x + facing.getFrontOffsetX() * blocks, y + facing.getFrontOffsetY() * blocks,
z + facing.getFrontOffsetZ() * blocks);
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,13 +21,15 @@
package com.falsepattern.lib.compat;
import com.falsepattern.lib.StableAPI;
import javax.annotation.concurrent.Immutable;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.val;
import net.minecraft.entity.Entity;
import javax.annotation.concurrent.Immutable;
/**
* A functional equivalent to ChunkPos present in Minecraft 1.12.
*/
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,19 +21,21 @@
package com.falsepattern.lib.compat;
import com.falsepattern.lib.StableAPI;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.ArrayList;
import java.util.List;
import lombok.NonNull;
import lombok.val;
import lombok.var;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.resources.I18n;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.ArrayList;
import java.util.List;
/**
* A functional equivalent to GuiLabel present in Minecraft 1.12.
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -169,7 +169,7 @@ public class MathHelper {
}
/**
* Buckets an integer with specifed bucket sizes. Args: i, bucketSize
* Buckets an integer with specified bucket sizes. Args: i, bucketSize
*/
public static int bucketInt(int i, int bucketSize) {
return i < 0 ? -((-i - 1) / bucketSize) - 1 : i / bucketSize;
@@ -196,11 +196,8 @@ public class MathHelper {
public static double average(long[] values) {
long i = 0L;
long[] along1 = values;
int j = values.length;
for (int k = 0; k < j; ++k) {
long l = along1[k];
for (long l : values) {
i += l;
}
@@ -245,25 +242,23 @@ public class MathHelper {
* parses the string as integer or returns the second parameter if it fails
*/
public static int parseIntWithDefault(String str, int def) {
int j = def;
try {
j = Integer.parseInt(str);
return Integer.parseInt(str);
} catch (Throwable throwable) {
return def;
}
return j;
}
/**
* parses the string as integer or returns the second parameter if it fails. this value is capped to par2
*/
public static int parseIntWithDefaultAndMax(String str, int def, int min) {
int k = def;
int k;
try {
k = Integer.parseInt(str);
} catch (Throwable throwable) {
k = def;
}
if (k < min) {
@@ -288,11 +283,12 @@ public class MathHelper {
}
public static double parseDoubleWithDefaultAndMin(String str, double def, double min) {
double d2 = def;
double d2;
try {
d2 = Double.parseDouble(str);
} catch (Throwable throwable) {
d2 = def;
}
if (d2 < min) {
@@ -337,7 +333,7 @@ public class MathHelper {
* highest bit that is set. For example, if the number in binary is 0...100101, this will return 5.
*/
public static int calculateLogBaseTwo(int a) {
/**
/*
* Uses a B(2, 5) De Bruijn sequence and a lookup table to efficiently calculate the log-base-two of the given
* value. Optimized for cases where the input value is a power-of-two. If the input value is not a power-of-
* two, then subtract 1 from the return value.
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -22,6 +22,8 @@ package com.falsepattern.lib.compat;
import com.falsepattern.lib.StableAPI;
import lombok.NonNull;
import lombok.val;
import net.minecraft.util.EnumFacing;
@StableAPI(since = "0.6.0")
@@ -32,43 +34,8 @@ public enum Rotation {
COUNTERCLOCKWISE_90;
public Rotation add(@NonNull Rotation rotation) {
switch (rotation) {
case CLOCKWISE_180:
switch (this) {
case NONE:
return CLOCKWISE_180;
case CLOCKWISE_90:
return COUNTERCLOCKWISE_90;
case CLOCKWISE_180:
return NONE;
case COUNTERCLOCKWISE_90:
return CLOCKWISE_90;
}
case COUNTERCLOCKWISE_90:
switch (this) {
case NONE:
return COUNTERCLOCKWISE_90;
case CLOCKWISE_90:
return NONE;
case CLOCKWISE_180:
return CLOCKWISE_90;
case COUNTERCLOCKWISE_90:
return CLOCKWISE_180;
}
case CLOCKWISE_90:
switch (this) {
case NONE:
return CLOCKWISE_90;
case CLOCKWISE_90:
return CLOCKWISE_180;
case CLOCKWISE_180:
return COUNTERCLOCKWISE_90;
case COUNTERCLOCKWISE_90:
return NONE;
}
default:
return this;
}
val values = Rotation.values();
return values[(ordinal() + rotation.ordinal()) % values.length];
}
public EnumFacing rotate(@NonNull EnumFacing facing) {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,8 +21,6 @@
package com.falsepattern.lib.compat;
import com.falsepattern.lib.StableAPI;
import javax.annotation.concurrent.Immutable;
import com.falsepattern.lib.util.MathUtil;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
@@ -30,6 +28,8 @@ import lombok.Getter;
import lombok.NonNull;
import lombok.val;
import javax.annotation.concurrent.Immutable;
/**
* A functional equivalent to Vec3i present in Minecraft 1.12.
*/
@@ -71,8 +71,7 @@ public class Vec3i implements Comparable<Vec3i> {
* @return the new resulting vector
*/
public Vec3i crossProduct(@NonNull Vec3i vec) {
return new Vec3i(y * vec.getZ() - z * vec.getY(),
z * vec.getX() - x * vec.getZ(),
return new Vec3i(y * vec.getZ() - z * vec.getY(), z * vec.getX() - x * vec.getZ(),
x * vec.getY() - y * vec.getX());
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -22,6 +22,7 @@ package com.falsepattern.lib.config;
import com.falsepattern.lib.DeprecationDetails;
import com.falsepattern.lib.StableAPI;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@@ -31,7 +32,7 @@ import java.util.function.BiConsumer;
/**
* A modern configuration system to replace the old and obtuse forge config system.
*
* <p>
* Note that just annotating a configuration class with {@link Config} is not enough, you must also register it using
* {@link ConfigurationManager#initialize(Class[])} or {@link ConfigurationManager#initialize(BiConsumer, Class[])}!
*/
@@ -191,10 +192,10 @@ public @interface Config {
/**
* This annotation limits the maximum number of characters present in a string configuration.
*
* <p>
* Note: If this annotation is not present, the maximum length will be implicitly set to 256 to avoid malicious
* synchronizations that would make clients run out of memory!
*
* <p>
* When used with a string list, this limit will apply to each element individually, not to the size of the list as a whole.
*/
@StableAPI(since = "0.10.0")
@@ -265,7 +266,7 @@ public @interface Config {
}
/**
* The default value for an boolean array field. Not having a default is deprecated since 0.10, and will be strongly
* The default value for a boolean array field. Not having a default is deprecated since 0.10, and will be strongly
* enforced in 0.11+!
*/
@StableAPI(since = "0.10.0")
@@ -290,7 +291,7 @@ public @interface Config {
/**
* This annotation limits the maximum number of elements present in an array configuration. Only effective if
* {@link ListFixedLength} is NOT present.
*
* <p>
* Note: If this annotation is not present, the maximum length will be implicitly set to 256 to avoid malicious
* synchronizations that would make clients run out of memory!
*/
@@ -303,7 +304,6 @@ public @interface Config {
}
/**
* The name of this config property in the config file. If not specified, the field's name will be used instead.
*/
@@ -338,7 +338,7 @@ public @interface Config {
/**
* Signals that this configuration class should be synchronized between the client and the server when
* joining a multiplayer instance.
*
* <p>
* Note that synchronization ALWAYS happens FROM the server TO the client. The server should NEVER attempt to get
* configuration values from a client. This is to avoid malicious clients manipulating the server configs.
*/
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -49,17 +49,18 @@ public class ConfigurationManager {
}
@StableAPI(since = "0.10.0")
public static void initialize(BiConsumer<Class<?>, Field> validatorErrorCallback, Class<?>... configClasses) throws ConfigException {
for (val clazz: configClasses) {
public static void initialize(BiConsumer<Class<?>, Field> validatorErrorCallback, Class<?>... configClasses)
throws ConfigException {
for (val clazz : configClasses) {
ConfigurationManagerImpl.register(clazz);
ConfigurationManagerImpl.load(clazz);
ConfigurationManagerImpl.validateFields(validatorErrorCallback, clazz, true);
ConfigurationManagerImpl.save(clazz);
}
}
@StableAPI(since = "0.10.0")
public static boolean validate(boolean resetInvalid, Class<?>... configClasses)
throws ConfigException {
public static boolean validate(boolean resetInvalid, Class<?>... configClasses) throws ConfigException {
return validate((x, y) -> {}, resetInvalid, configClasses);
}
@@ -67,7 +68,7 @@ public class ConfigurationManager {
public static boolean validate(BiConsumer<Class<?>, Field> validatorErrorCallback, boolean resetInvalid, Class<?>... configClasses)
throws ConfigException {
boolean valid = true;
for (val clazz: configClasses) {
for (val clazz : configClasses) {
valid &= ConfigurationManagerImpl.validateFields(validatorErrorCallback, clazz, resetInvalid);
}
return valid;
@@ -75,14 +76,14 @@ public class ConfigurationManager {
@StableAPI(since = "0.10.0")
public static void loadFromFile(Class<?>... configClasses) throws ConfigException {
for (val clazz: configClasses) {
for (val clazz : configClasses) {
ConfigurationManagerImpl.load(clazz);
}
}
@StableAPI(since = "0.10.0")
public static void saveToFile(boolean validateAndResetInvalid, Class<?>... configClasses) throws ConfigException {
for (val clazz: configClasses) {
for (val clazz : configClasses) {
if (validateAndResetInvalid) {
ConfigurationManagerImpl.validateFields((a, b) -> {}, clazz, true);
}
@@ -99,7 +100,9 @@ public class ConfigurationManager {
@DeprecationDetails(stableSince = "0.6.0",
deprecatedSince = "0.10.0")
public static void registerConfig(Class<?> configClass) throws ConfigException {
FalsePatternLib.getLog().warn("A mod is using the deprecated config registration method! The following exception contains the stacktrace.", new Exception());
FalsePatternLib.getLog()
.warn("A mod is using the deprecated config registration method! The following exception contains the stacktrace.",
new Exception());
ConfigurationManagerImpl.registerLoadSaveConfig(configClass);
}
@@ -127,11 +130,13 @@ public class ConfigurationManager {
@StableAPI(since = "0.10.0")
public static List<IConfigElement> getConfigElementsMulti(Class<?>... configClasses) throws ConfigException {
switch (configClasses.length) {
case 0: return Collections.emptyList();
case 1: return getConfigElements(configClasses[0]);
case 0:
return Collections.emptyList();
case 1:
return getConfigElements(configClasses[0]);
default:
val result = new ArrayList<IConfigElement>();
for (val configClass: configClasses) {
for (val configClass : configClasses) {
result.addAll(getConfigElements(configClass));
}
return result;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -24,6 +24,7 @@ import cpw.mods.fml.client.config.ConfigGuiType;
import cpw.mods.fml.client.config.GuiConfigEntries;
import cpw.mods.fml.client.config.GuiEditArrayEntries;
import cpw.mods.fml.client.config.IConfigElement;
import java.util.List;
import java.util.regex.Pattern;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,28 +21,25 @@
package com.falsepattern.lib.config;
import com.falsepattern.lib.StableAPI;
import lombok.val;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
@StableAPI(since = "0.9.0")
public class SimpleGuiConfig extends GuiConfig {
public SimpleGuiConfig(GuiScreen parent, Class<?> configClass, String modID, String modName) throws ConfigException {
public SimpleGuiConfig(GuiScreen parent, Class<?> configClass, String modID, String modName)
throws ConfigException {
this(parent, new Class<?>[]{configClass}, modID, modName);
}
@StableAPI(since = "0.10.0")
public SimpleGuiConfig(GuiScreen parent, Class<?>[] configClasses, String modID, String modName) throws ConfigException {
super(parent, ConfigurationManager.getConfigElementsMulti(configClasses), modID, false, false, modName + " Configuration", I18n.format("falsepatternlib.gui.config.description"));
public SimpleGuiConfig(GuiScreen parent, Class<?>[] configClasses, String modID, String modName)
throws ConfigException {
super(parent, ConfigurationManager.getConfigElementsMulti(configClasses), modID, false, false,
modName + " Configuration", I18n.format("falsepatternlib.gui.config.description"));
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,10 +21,11 @@
package com.falsepattern.lib.config;
import com.falsepattern.lib.StableAPI;
import net.minecraft.client.Minecraft;
import cpw.mods.fml.client.IModGuiFactory;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import java.util.Set;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -32,7 +32,7 @@ import cpw.mods.fml.relauncher.SideOnly;
/**
* This event is pushed on the FMLCommonHandler event bus once all the config synchronizations have finished.
*
* <p>
* This is a client-only event, and is never triggered serverside!
*/
@SideOnly(Side.CLIENT)
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -32,7 +32,7 @@ import cpw.mods.fml.relauncher.SideOnly;
/**
* This event is pushed on the FMLCommonHandler event bus once each time a single config synchronization has finished.
*
* <p>
* This is a client-only event, and is never triggered serverside!
*/
@SideOnly(Side.CLIENT)
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -36,11 +36,20 @@ import java.util.List;
* You can use this event to manually trigger a synchronization request. The two different flavors are used on the two
* different game sides. If you want to trigger this on the server, use {@link #postServer}, and if on the client, use
* {@link #postClient}
*
*/
@StableAPI(since = "0.10.0")
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
public class ConfigSyncRequestEvent extends Event {
@StableAPI(since = "0.10.0")
public static void postClient() {
FMLCommonHandler.instance().bus().post(new Client());
}
@StableAPI(since = "0.10.0")
public static void postServer(List<EntityPlayerMP> players) {
FMLCommonHandler.instance().bus().post(new Server(new ArrayList<>(players)));
}
@StableAPI(since = "0.10.0")
public static class Client extends ConfigSyncRequestEvent {
@@ -55,14 +64,4 @@ public class ConfigSyncRequestEvent extends Event {
return Collections.unmodifiableList(players);
}
}
@StableAPI(since = "0.10.0")
public static void postClient() {
FMLCommonHandler.instance().bus().post(new Client());
}
@StableAPI(since = "0.10.0")
public static void postServer(List<EntityPlayerMP> players) {
FMLCommonHandler.instance().bus().post(new Server(new ArrayList<>(players)));
}
}
@@ -54,15 +54,24 @@ public abstract class ConfigValidationFailureEvent extends Event {
public final int listIndex;
public static void postNumericRangeOutOfBounds(Field field, int listIndex, String value, String min, String max) {
FMLCommonHandler.instance().bus().post(new NumericRangeOutOfBounds(field.getDeclaringClass(), field.getName(), listIndex, value, min, max));
FMLCommonHandler.instance()
.bus()
.post(new NumericRangeOutOfBounds(field.getDeclaringClass(), field.getName(), listIndex, value,
min, max));
}
public static void postSize(Field field, int requestedSize, boolean fixedSize, int maxSize, int defaultSize) {
FMLCommonHandler.instance().bus().post(new ListSizeOutOfBounds(field.getDeclaringClass(), field.getName(), requestedSize, fixedSize, maxSize, defaultSize));
FMLCommonHandler.instance()
.bus()
.post(new ListSizeOutOfBounds(field.getDeclaringClass(), field.getName(), requestedSize,
fixedSize, maxSize, defaultSize));
}
public static void postStringSizeOutOfBounds(Field field, int listIndex, String text, int maxSize) {
FMLCommonHandler.instance().bus().post(new StringSizeOutOfBounds(field.getDeclaringClass(), field.getName(), listIndex, text, maxSize));
FMLCommonHandler.instance()
.bus()
.post(new StringSizeOutOfBounds(field.getDeclaringClass(), field.getName(), listIndex, text,
maxSize));
}
public static void fieldIsNull(Field field, int listIndex) {
@@ -70,7 +79,35 @@ public abstract class ConfigValidationFailureEvent extends Event {
}
public static void postStringPatternMismatch(Field field, int listIndex, String text, String pattern) {
FMLCommonHandler.instance().bus().post(new StringPatternMismatch(field.getDeclaringClass(), field.getName(), listIndex, text, pattern));
FMLCommonHandler.instance()
.bus()
.post(new StringPatternMismatch(field.getDeclaringClass(), field.getName(), listIndex, text,
pattern));
}
@SideOnly(Side.CLIENT)
public void toast() {
val ann = configClass.getAnnotation(Config.class);
val toast = new SimpleToast(ToastBG.TOAST_DARK, null,
FormattedText.parse(EnumChatFormatting.RED + "Config validation failed")
.toChatText()
.get(0),
FormattedText.parse(ann.modid() + ":" + ann.category()).toChatText().get(0), false,
2000);
GuiToast.add(toast);
}
protected abstract void customText(StringBuilder b);
public void logWarn() {
val errorString = new StringBuilder("Error validating configuration field!");
errorString.append("\nReason: ").append(reason);
errorString.append("\nClass: ").append(configClass.getName()).append("\nField: ").append(fieldName);
if (listElement) {
errorString.append("\nArray index: ").append(listIndex);
}
customText(errorString);
FalsePatternLib.getLog().error(errorString.toString());
}
@StableAPI(since = "0.10.0")
@@ -91,9 +128,7 @@ public abstract class ConfigValidationFailureEvent extends Event {
@Override
protected void customText(StringBuilder b) {
b.append("\nValue: ").append(value)
.append("\nMin: ").append(min)
.append("\nMax: ").append(max);
b.append("\nValue: ").append(value).append("\nMin: ").append(min).append("\nMax: ").append(max);
}
}
@@ -132,6 +167,7 @@ public abstract class ConfigValidationFailureEvent extends Event {
public final String text;
@StableAPI(since = "0.10.0")
public final int maxSize;
private StringSizeOutOfBounds(Class<?> configClass, String fieldName, int listIndex, String text, int maxSize) {
super("String size out of bounds", configClass, fieldName, listIndex >= 0, listIndex);
this.text = text;
@@ -140,9 +176,12 @@ public abstract class ConfigValidationFailureEvent extends Event {
@Override
protected void customText(StringBuilder b) {
b.append("\nText: ").append(text)
.append("\nSize: ").append(text.length())
.append("\nMax size:").append(maxSize);
b.append("\nText: ")
.append(text)
.append("\nSize: ")
.append(text.length())
.append("\nMax size:")
.append(maxSize);
}
}
@@ -173,32 +212,7 @@ public abstract class ConfigValidationFailureEvent extends Event {
@Override
protected void customText(StringBuilder b) {
b.append("\nText: ").append(text)
.append("\nPattern: ").append(pattern);
b.append("\nText: ").append(text).append("\nPattern: ").append(pattern);
}
}
@SideOnly(Side.CLIENT)
public void toast() {
val ann = configClass.getAnnotation(Config.class);
val toast = new SimpleToast(ToastBG.TOAST_DARK, null,
FormattedText.parse(EnumChatFormatting.RED + "Config validation failed").toChatText().get(0),
FormattedText.parse(ann.modid() + ":" + ann.category()).toChatText().get(0),
false, 2000);
GuiToast.add(toast);
}
protected abstract void customText(StringBuilder b);
public void logWarn() {
val errorString = new StringBuilder("Error validating configuration field!");
errorString.append("\nReason: ").append(reason);
errorString.append("\nClass: ").append(configClass.getName())
.append("\nField: ").append(fieldName);
if (listElement) {
errorString.append("\nArray index: ").append(listIndex);
}
customText(errorString);
FalsePatternLib.getLog().error(errorString.toString());
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,11 +21,12 @@
package com.falsepattern.lib.dependencies;
import com.falsepattern.lib.StableAPI;
import java.util.Arrays;
import java.util.stream.Collectors;
import lombok.NonNull;
import lombok.val;
import java.util.Arrays;
import java.util.stream.Collectors;
@StableAPI(since = "0.6.0")
public class ComplexVersion extends Version {
final Version[] versions;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -34,14 +34,7 @@ public class DependencyLoader {
}
@Builder
public static void loadLibrary(@NonNull String loadingModId,
@NonNull String groupId,
@NonNull String artifactId,
@NonNull Version minVersion,
Version maxVersion,
@NonNull Version preferredVersion,
String regularSuffix,
String devSuffix) {
public static void loadLibrary(@NonNull String loadingModId, @NonNull String groupId, @NonNull String artifactId, @NonNull Version minVersion, Version maxVersion, @NonNull Version preferredVersion, String regularSuffix, String devSuffix) {
DependencyLoaderImpl.loadLibrary(loadingModId, groupId, artifactId, minVersion, maxVersion, preferredVersion,
regularSuffix, devSuffix);
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,19 +21,25 @@
package com.falsepattern.lib.dependencies;
import com.falsepattern.lib.StableAPI;
import java.util.Objects;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.val;
import java.util.Objects;
@StableAPI(since = "0.6.0")
public class SemanticVersion extends Version {
@Getter private final int majorVersion;
@Getter private final int minorVersion;
@Getter private final int patchVersion;
@Getter private final String preRelease;
@Getter private final String build;
@Getter
private final int majorVersion;
@Getter
private final int minorVersion;
@Getter
private final int patchVersion;
@Getter
private final String preRelease;
@Getter
private final String build;
public SemanticVersion(int majorVersion, int minorVersion, int patchVersion, String preRelease) {
this(majorVersion, minorVersion, patchVersion, preRelease, null);
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -27,6 +27,7 @@ import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.Name;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex;
import java.util.Map;
/**
@@ -39,6 +40,16 @@ public class CoreLoadingPlugin implements IFMLLoadingPlugin {
@Getter
private static boolean obfuscated;
static {
try {
Class.forName("thermos.Thermos");
throw skillIssue("Thermos is not supported by FalsePatternLib, please use a normal forge server.");
} catch (ClassNotFoundException ignored) {
}
}
@SuppressWarnings("SameParameterValue")
private static Error skillIssue(String message) {
int width = message.length();
String shutup = "Any bug reports concerning this message will be silently deleted.";
@@ -87,13 +98,6 @@ public class CoreLoadingPlugin implements IFMLLoadingPlugin {
skillIssue.setStackTrace(new StackTraceElement[0]);
return skillIssue;
}
static {
try {
Class.forName("thermos.Thermos");
throw skillIssue("Thermos is not supported by FalsePatternLib, please use a normal forge server.");
} catch (ClassNotFoundException ignored) {}
}
@Override
public String[] getASMTransformerClass() {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,21 +21,19 @@
package com.falsepattern.lib.internal;
import com.falsepattern.lib.internal.proxy.CommonProxy;
import lombok.Getter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cpw.mods.fml.common.*;
import net.minecraft.launchwrapper.Launch;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLConstructionEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import lombok.Getter;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Utility class used by FalsePatternLib's internal code. This can change between versions without notice, so do not use
* this in your code!
@@ -50,12 +48,14 @@ public class FalsePatternLib {
public static final String UPDATE_URL = "https://falsepattern.com/mc/versions.json";
public static final SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(Tags.MODID);
@Getter private static final Logger log = LogManager.getLogger(Tags.MODNAME);
@Getter
private static final Logger log = LogManager.getLogger(Tags.MODNAME);
@Getter private static final boolean developerEnvironment =
(boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
@Getter
private static final boolean developerEnvironment = (boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
@SidedProxy(clientSide = Tags.GROUPNAME + ".internal.proxy.ClientProxy", serverSide = Tags.GROUPNAME + ".internal.proxy.CommonProxy")
@SidedProxy(clientSide = Tags.GROUPNAME + ".internal.proxy.ClientProxy",
serverSide = Tags.GROUPNAME + ".internal.proxy.CommonProxy")
private static CommonProxy proxy;
public FalsePatternLib() {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -23,7 +23,10 @@ package com.falsepattern.lib.internal;
import lombok.val;
import lombok.var;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -19,6 +19,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.falsepattern.lib.internal;
import lombok.Getter;
import java.io.IOException;
@@ -32,8 +33,81 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
@SuppressWarnings("ALL")
@Getter
class SRGGen {
private static final Map<String, String> class_notch_srg = new HashMap<>();
private static final Map<String, String> class_notch_mcp = new HashMap<>();
private static final Map<String, String> class_srg_mcp = new HashMap<>();
private static final Map<String, String> class_mcp_srg = new HashMap<>();
private static final Map<String, String> class_mcp_notch = new HashMap<>();
private static final Map<String, String> field_notch_srg = new HashMap<>();
private static final Map<String, String> field_notch_mcp = new HashMap<>();
private static final Map<String, String> field_srg_mcp = new HashMap<>();
private static final Map<String, String> field_mcp_srg = new HashMap<>();
private static final Map<String, String> field_mcp_notch = new HashMap<>();
private static final Map<StringPair, StringPair> method_notch_srg = new HashMap<>();
private static final Map<StringPair, StringPair> method_notch_mcp = new HashMap<>();
private static final Map<StringPair, StringPair> method_srg_mcp = new HashMap<>();
private static final Map<StringPair, StringPair> method_mcp_srg = new HashMap<>();
private static final Map<StringPair, StringPair> method_mcp_notch = new HashMap<>();
public static void main(String[] args) throws IOException {
Path dir = Paths.get(args[0]);
parseLines(Files.readAllLines(dir.resolve("notch-srg.srg")), class_notch_srg, field_notch_srg,
method_notch_srg);
parseLines(Files.readAllLines(dir.resolve("notch-mcp.srg")), class_notch_mcp, field_notch_mcp,
method_notch_mcp);
parseLines(Files.readAllLines(dir.resolve("srg-mcp.srg")), class_srg_mcp, field_srg_mcp, method_srg_mcp);
parseLines(Files.readAllLines(dir.resolve("mcp-srg.srg")), class_mcp_srg, field_mcp_srg, method_mcp_srg);
parseLines(Files.readAllLines(dir.resolve("mcp-notch.srg")), class_mcp_notch, field_mcp_notch,
method_mcp_notch);
try (OutputStream output = Files.newOutputStream(dir.resolve("classes.csv"))) {
output.write("notch,srg,mcp\n".getBytes(StandardCharsets.UTF_8));
crossValidate(class_notch_srg, class_notch_mcp, class_srg_mcp, class_mcp_srg, class_mcp_notch, output);
}
try (OutputStream output = Files.newOutputStream(dir.resolve("fields.csv"))) {
output.write("notch,srg,mcp\n".getBytes(StandardCharsets.UTF_8));
crossValidate(field_notch_srg, field_notch_mcp, field_srg_mcp, field_mcp_srg, field_mcp_notch, output);
}
try (OutputStream output = Files.newOutputStream(dir.resolve("methods.csv"))) {
output.write("notch,notchdesc,srg,srgdesc,mcp,mcpdesc\n".getBytes(StandardCharsets.UTF_8));
crossValidate(method_notch_srg, method_notch_mcp, method_srg_mcp, method_mcp_srg, method_mcp_notch, output);
}
}
private static boolean crossValidate(Map<?, ?> notch_srg, Map<?, ?> notch_mcp, Map<?, ?> srg_mcp, Map<?, ?> mcp_srg, Map<?, ?> mcp_notch, OutputStream output)
throws IOException {
for (Map.Entry<?, ?> notch_srg_entry : notch_srg.entrySet()) {
Object notch = notch_srg_entry.getKey();
Object srg = notch_srg_entry.getValue();
Object mcp = notch_mcp.get(notch);
if (!srg_mcp.get(srg).equals(mcp) || !mcp_srg.get(mcp).equals(srg) || !mcp_notch.get(mcp).equals(notch)) {
throw new RuntimeException(notch + " - " + srg + " - " + mcp);
}
output.write((notch + "," + srg + "," + mcp + "\n").getBytes(StandardCharsets.UTF_8));
}
return true;
}
private static void parseLines(List<String> lines, Map<String, String> classes, Map<String, String> fields, Map<StringPair, StringPair> methods) {
for (String line : lines) {
String[] parts = line.split(" ");
switch (parts[0]) {
case "CL:":
classes.put(parts[1], parts[2]);
break;
case "FD:":
fields.put(parts[1], parts[2]);
break;
case "MD:":
methods.put(new StringPair(parts[1], parts[2]), new StringPair(parts[3], parts[4]));
break;
}
}
}
private static class StringPair {
public final String name;
public final String desc;
@@ -65,73 +139,4 @@ class SRGGen {
return name + "," + desc;
}
}
private static Map<String, String> class_notch_srg = new HashMap<>();
private static Map<String, String> class_notch_mcp = new HashMap<>();
private static Map<String, String> class_srg_mcp = new HashMap<>();
private static Map<String, String> class_mcp_srg = new HashMap<>();
private static Map<String, String> class_mcp_notch = new HashMap<>();
private static Map<String, String> field_notch_srg = new HashMap<>();
private static Map<String, String> field_notch_mcp = new HashMap<>();
private static Map<String, String> field_srg_mcp = new HashMap<>();
private static Map<String, String> field_mcp_srg = new HashMap<>();
private static Map<String, String> field_mcp_notch = new HashMap<>();
private static Map<StringPair, StringPair> method_notch_srg = new HashMap<>();
private static Map<StringPair, StringPair> method_notch_mcp = new HashMap<>();
private static Map<StringPair, StringPair> method_srg_mcp = new HashMap<>();
private static Map<StringPair, StringPair> method_mcp_srg = new HashMap<>();
private static Map<StringPair, StringPair> method_mcp_notch = new HashMap<>();
public static void main(String[] args) throws IOException {
Path dir = Paths.get(args[0]);
parseLines(Files.readAllLines(dir.resolve("notch-srg.srg")), class_notch_srg, field_notch_srg, method_notch_srg);
parseLines(Files.readAllLines(dir.resolve("notch-mcp.srg")), class_notch_mcp, field_notch_mcp, method_notch_mcp);
parseLines(Files.readAllLines(dir.resolve("srg-mcp.srg")), class_srg_mcp, field_srg_mcp, method_srg_mcp);
parseLines(Files.readAllLines(dir.resolve("mcp-srg.srg")), class_mcp_srg, field_mcp_srg, method_mcp_srg);
parseLines(Files.readAllLines(dir.resolve("mcp-notch.srg")), class_mcp_notch, field_mcp_notch, method_mcp_notch);
try (OutputStream output = Files.newOutputStream(dir.resolve("classes.csv"))) {
output.write("notch,srg,mcp\n".getBytes(StandardCharsets.UTF_8));
crossValidate(class_notch_srg, class_notch_mcp, class_srg_mcp, class_mcp_srg, class_mcp_notch, output);
}
try (OutputStream output = Files.newOutputStream(dir.resolve("fields.csv"))) {
output.write("notch,srg,mcp\n".getBytes(StandardCharsets.UTF_8));
crossValidate(field_notch_srg, field_notch_mcp, field_srg_mcp, field_mcp_srg, field_mcp_notch, output);
}
try (OutputStream output = Files.newOutputStream(dir.resolve("methods.csv"))) {
output.write("notch,notchdesc,srg,srgdesc,mcp,mcpdesc\n".getBytes(StandardCharsets.UTF_8));
crossValidate(method_notch_srg, method_notch_mcp, method_srg_mcp, method_mcp_srg, method_mcp_notch, output);
}
}
private static boolean crossValidate(Map<?, ?> notch_srg, Map<?, ?> notch_mcp, Map<?, ?> srg_mcp, Map<?, ?> mcp_srg, Map<?, ?> mcp_notch, OutputStream output)
throws IOException {
for (Map.Entry<?, ?> notch_srg_entry: notch_srg.entrySet()) {
Object notch = notch_srg_entry.getKey();
Object srg = notch_srg_entry.getValue();
Object mcp = notch_mcp.get(notch);
if (!srg_mcp.get(srg).equals(mcp) ||
!mcp_srg.get(mcp).equals(srg) ||
!mcp_notch.get(mcp).equals(notch)) {
throw new RuntimeException(notch + " - " + srg + " - " + mcp);
}
output.write((notch + "," + srg + "," + mcp + "\n").getBytes(StandardCharsets.UTF_8));
}
return true;
}
private static void parseLines(List<String> lines, Map<String, String> classes, Map<String, String> fields, Map<StringPair, StringPair> methods) {
for (String line: lines) {
String[] parts = line.split(" ");
switch (parts[0]) {
case "CL:":
classes.put(parts[1], parts[2]);
break;
case "FD:":
fields.put(parts[1], parts[2]);
break;
case "MD:":
methods.put(new StringPair(parts[1], parts[2]), new StringPair(parts[3], parts[4]));
break;
}
}
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -45,6 +45,8 @@ public class LibraryConfig {
public static ValidationLogging CONFIG_ERROR_LOUDNESS;
public enum ValidationLogging {
None, Log, LogAndToast
None,
Log,
LogAndToast
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -24,9 +24,9 @@ import com.falsepattern.lib.config.ConfigException;
import com.falsepattern.lib.config.SimpleGuiConfig;
import com.falsepattern.lib.internal.Tags;
import net.minecraft.client.gui.GuiScreen;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiScreen;
@SideOnly(Side.CLIENT)
public class LibraryGuiConfig extends SimpleGuiConfig {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,9 +21,10 @@
package com.falsepattern.lib.internal.config;
import com.falsepattern.lib.config.SimpleGuiFactory;
import net.minecraft.client.gui.GuiScreen;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiScreen;
@SideOnly(Side.CLIENT)
public class LibraryGuiFactory implements SimpleGuiFactory {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -54,6 +54,7 @@ public class ToastConfig {
}
public enum Side {
Left, Right
Left,
Right
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -73,7 +73,7 @@ import java.util.function.BiConsumer;
/**
* The actual implementation of ConfigurationManager. Migrated stuff here so that we don't unnecessarily expose
* internal-use functionality.
*
* <p>
* Do not read if you value your sanity.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@@ -116,7 +116,8 @@ public class ConfigurationManagerImpl {
parsedConfigMap.get(configClass).save();
}
public static boolean validateFields(BiConsumer<Class<?>, Field> invalidFieldHandler, Class<?> configClass, boolean resetInvalid) throws ConfigException {
public static boolean validateFields(BiConsumer<Class<?>, Field> invalidFieldHandler, Class<?> configClass, boolean resetInvalid)
throws ConfigException {
if (!parsedConfigMap.containsKey(configClass)) {
throw new ConfigException("Class " + configClass.getName() + " is not a registered configuration!");
}
@@ -133,13 +134,13 @@ public class ConfigurationManagerImpl {
public static void sendRequest(DataOutput output) throws IOException {
val synced = new ArrayList<Class<?>>();
for (val entry: parsedConfigMap.entrySet()) {
for (val entry : parsedConfigMap.entrySet()) {
if (entry.getValue().sync) {
synced.add(entry.getKey());
}
}
output.writeInt(synced.size());
for (val clazz: synced) {
for (val clazz : synced) {
output.writeUTF(clazz.getName());
}
}
@@ -151,7 +152,7 @@ public class ConfigurationManagerImpl {
for (int i = 0; i < count; i++) {
classNames.add(input.readUTF());
}
for (val entry: parsedConfigMap.keySet()) {
for (val entry : parsedConfigMap.keySet()) {
if (classNames.contains(entry.getName())) {
result.add(entry);
}
@@ -161,13 +162,13 @@ public class ConfigurationManagerImpl {
public static void sendReply(DataOutput output, List<Class<?>> requestedClasses) throws IOException {
val syncEntries = new HashMap<>(parsedConfigMap);
for (val entry: parsedConfigMap.entrySet()) {
for (val entry : parsedConfigMap.entrySet()) {
if (!entry.getValue().sync || !requestedClasses.contains(entry.getKey())) {
syncEntries.remove(entry.getKey());
}
}
output.writeInt(syncEntries.size());
for (val entry: syncEntries.entrySet()) {
for (val entry : syncEntries.entrySet()) {
output.writeUTF(entry.getKey().getName());
val b = new ByteArrayOutputStream();
val bo = new DataOutputStream(b);
@@ -187,7 +188,8 @@ public class ConfigurationManagerImpl {
for (int i = 0; i < count; i++) {
String className = input.readUTF();
int dataSize = input.readInt();
val opt = parsedConfigMap.keySet().stream().filter((clazz) -> clazz.getName().equals(className)).findFirst();
val opt =
parsedConfigMap.keySet().stream().filter((clazz) -> clazz.getName().equals(className)).findFirst();
if (!opt.isPresent()) {
input.skipBytes(dataSize);
FalsePatternLib.getLog().warn("Server tried to sync config not registered on our side: " + className);
@@ -197,7 +199,9 @@ public class ConfigurationManagerImpl {
val config = parsedConfigMap.get(clazz);
if (!config.sync) {
input.skipBytes(dataSize);
FalsePatternLib.getLog().warn("Server tried to sync config without @Synchronize annotation on our side: " + className);
FalsePatternLib.getLog()
.warn("Server tried to sync config without @Synchronize annotation on our side: " +
className);
continue;
}
if (!ConfigSyncEvent.postStart(clazz)) {
@@ -223,11 +227,11 @@ public class ConfigurationManagerImpl {
public static void loadRawConfig(Configuration rawConfig) throws ConfigException {
rawConfig.load();
for (val configClass: configToClassMap.get(rawConfig)) {
for (val configClass : configToClassMap.get(rawConfig)) {
val config = parsedConfigMap.get(configClass);
try {
config.reloadFields();
} catch (NoSuchFieldException | IllegalAccessException e) {
} catch (IllegalAccessException e) {
throw new ConfigException(e);
}
}
@@ -296,7 +300,7 @@ public class ConfigurationManagerImpl {
return;
}
val configClasses = configToClassMap.get(rawConfig);
for (val clazz: configClasses) {
for (val clazz : configClasses) {
val config = parsedConfigMap.get(clazz);
config.configChanged();
}
@@ -323,12 +327,16 @@ public class ConfigurationManagerImpl {
val cfg = e.configClass.getAnnotation(Config.class);
if (e.successful) {
GuiToast.add(new SimpleToast(ToastBG.TOAST_DARK, null,
FormattedText.parse(EnumChatFormatting.GREEN + "Synced config").toChatText().get(0),
FormattedText.parse(EnumChatFormatting.GREEN + "Synced config")
.toChatText()
.get(0),
FormattedText.parse(cfg.modid() + ":" + cfg.category()).toChatText().get(0),
false, 5000));
} else {
GuiToast.add(new SimpleToast(ToastBG.TOAST_DARK, null,
FormattedText.parse(EnumChatFormatting.RED + "Failed to sync config").toChatText().get(0),
FormattedText.parse(EnumChatFormatting.RED + "Failed to sync config")
.toChatText()
.get(0),
FormattedText.parse(cfg.modid() + ":" + cfg.category()).toChatText().get(0),
false, 5000));
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -38,7 +38,6 @@ import lombok.val;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.client.config.IConfigElement;
import java.io.DataInput;
@@ -57,15 +56,6 @@ import java.util.function.BiConsumer;
public class ParsedConfiguration {
private static final Field propField;
public final Class<?> configClass;
public final String modid;
public final String category;
public final Configuration rawConfig;
public final boolean sync;
private final Map<String, AConfigField<?>> fields = new HashMap<>();
private final Map<String, ConfigElement<?>> elements = new HashMap<>();
private int maxFieldNameLength;
static {
try {
propField = ConfigElement.class.getDeclaredField("prop");
@@ -75,6 +65,15 @@ public class ParsedConfiguration {
ReflectionUtil.jailBreak(propField);
}
public final Class<?> configClass;
public final String modid;
public final String category;
public final Configuration rawConfig;
public final boolean sync;
private final Map<String, AConfigField<?>> fields = new HashMap<>();
private final Map<String, ConfigElement<?>> elements = new HashMap<>();
private int maxFieldNameLength;
public static ParsedConfiguration parseConfig(Class<?> configClass) throws ConfigException {
val cfg = Optional.ofNullable(configClass.getAnnotation(Config.class))
.orElseThrow(() -> new ConfigException(
@@ -84,10 +83,11 @@ public class ParsedConfiguration {
.orElseThrow(() -> new ConfigException(
"Config class " + configClass.getName() + " has an empty category!"));
val rawConfig = ConfigurationManagerImpl.getForgeConfig(cfg.modid());
val parsedConfig = new ParsedConfiguration(configClass, cfg.modid(), category, rawConfig, configClass.isAnnotationPresent(Config.Synchronize.class));
val parsedConfig = new ParsedConfiguration(configClass, cfg.modid(), category, rawConfig,
configClass.isAnnotationPresent(Config.Synchronize.class));
try {
parsedConfig.reloadFields();
} catch (NoSuchFieldException | IllegalAccessException e) {
} catch (IllegalAccessException e) {
throw new ConfigException(e);
}
return parsedConfig;
@@ -102,7 +102,7 @@ public class ParsedConfiguration {
//Happens when changed through the gui
public void configChanged() {
for (val field: fields.values()) {
for (val field : fields.values()) {
field.load();
}
rawConfig.save();
@@ -110,7 +110,7 @@ public class ParsedConfiguration {
public void load() throws ConfigException {
ConfigurationManagerImpl.loadRawConfig(rawConfig);
for (val field: fields.values()) {
for (val field : fields.values()) {
field.load();
}
}
@@ -118,15 +118,17 @@ public class ParsedConfiguration {
public void receive(DataInput input) throws IOException {
if (sync) {
val syncFields = new HashMap<>(fields);
for (val key: fields.keySet()) {
for (val key : fields.keySet()) {
if (syncFields.get(key).noSync) {
syncFields.remove(key);
}
}
while (syncFields.size() > 0) {
val fieldName = StringConfigField.receiveString(input, maxFieldNameLength, "field name", configClass.getName());
val fieldName =
StringConfigField.receiveString(input, maxFieldNameLength, "field name", configClass.getName());
if (!syncFields.containsKey(fieldName)) {
throw new IOException("Invalid sync field name received: " + fieldName + " for config class " + configClass.getName());
throw new IOException("Invalid sync field name received: " + fieldName + " for config class " +
configClass.getName());
}
syncFields.remove(fieldName).receive(input);
}
@@ -136,19 +138,19 @@ public class ParsedConfiguration {
public void transmit(DataOutput output) throws IOException {
if (sync) {
val syncFields = new HashMap<>(fields);
for (val key: fields.keySet()) {
for (val key : fields.keySet()) {
if (syncFields.get(key).noSync) {
syncFields.remove(key);
}
}
for (val field: syncFields.entrySet()) {
for (val field : syncFields.entrySet()) {
StringConfigField.transmitString(output, field.getKey());
field.getValue().transmit(output);
}
}
}
public void reloadFields() throws ConfigException, NoSuchFieldException, IllegalAccessException {
public void reloadFields() throws ConfigException, IllegalAccessException {
fields.clear();
maxFieldNameLength = 0;
val cat = rawConfig.getCategory(category);
@@ -209,7 +211,7 @@ public class ParsedConfiguration {
public boolean validate(BiConsumer<Class<?>, Field> invalidFieldHandler, boolean resetInvalid) {
boolean valid = true;
for (val field: fields.values()) {
for (val field : fields.values()) {
if (!field.validateField()) {
if (resetInvalid) {
field.setToDefault();
@@ -102,6 +102,7 @@ public abstract class AConfigField<T> {
return property;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public abstract boolean validateField();
public abstract void transmit(DataOutput output) throws IOException;
@@ -112,7 +112,8 @@ public class DoubleConfigField extends AConfigField<Double> {
if (value >= min && value <= max) {
return true;
}
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, -1, Double.toString(value), Double.toString(min), Double.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, -1, Double.toString(value),
Double.toString(min), Double.toString(max));
return false;
}
@@ -107,7 +107,8 @@ public class DoubleListConfigField extends AListConfigField<double[]> {
for (int j = 0; j < doubles.length; j++) {
double d = doubles[j];
if (d < min || d > max) {
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, j, Double.toString(d), Double.toString(min), Double.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, j, Double.toString(d),
Double.toString(min), Double.toString(max));
valid = false;
}
}
@@ -57,7 +57,9 @@ public class EnumConfigField<T extends Enum<T>> extends AConfigField<T> {
.stream()
.filter((e) -> e.name().equals(defName))
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Default value \"" + defName + "\" was not found in enum " + enumClass.getName())))
.orElseThrow(() -> new IllegalArgumentException(
"Default value \"" + defName +
"\" was not found in enum " + enumClass.getName())))
.orElseGet(() -> {
FalsePatternLib.getLog()
.warn("The field " + field.getName() + " in class " +
@@ -118,7 +118,8 @@ public class FloatConfigField extends AConfigField<Float> {
if (value >= min && value <= max) {
return true;
}
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, -1, Float.toString(value), Float.toString(min), Float.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, -1, Float.toString(value),
Float.toString(min), Float.toString(max));
return false;
} else {
return true;
@@ -112,7 +112,8 @@ public class IntConfigField extends AConfigField<Integer> {
if (value >= min && value <= max) {
return true;
}
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, -1, Integer.toString(value), Integer.toString(min), Integer.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, -1, Integer.toString(value),
Integer.toString(min), Integer.toString(max));
return false;
}
@@ -107,7 +107,8 @@ public class IntListConfigField extends AListConfigField<int[]> {
for (int j = 0; j < ints.length; j++) {
int i = ints[j];
if (i < min || i > max) {
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, j, Integer.toString(i), Integer.toString(min), Integer.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, j, Integer.toString(i),
Integer.toString(min), Integer.toString(max));
valid = false;
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -24,8 +24,8 @@ import com.falsepattern.lib.dependencies.DependencyLoader;
import com.falsepattern.lib.dependencies.Version;
import com.falsepattern.lib.internal.FalsePatternLib;
import com.falsepattern.lib.internal.Internet;
import com.falsepattern.lib.internal.config.LibraryConfig;
import com.falsepattern.lib.internal.Tags;
import com.falsepattern.lib.internal.config.LibraryConfig;
import com.falsepattern.lib.util.FileUtil;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@@ -66,11 +66,9 @@ public class DependencyLoaderImpl {
mavenRepositories.add(url);
}
public static void loadLibrary(@NonNull String loadingModId, @NonNull String groupId, @NonNull String artifactId,
@NonNull Version minVersion, Version maxVersion, @NonNull Version preferredVersion,
String regularSuffix, String devSuffix) {
new DependencyLoadTask(loadingModId, groupId, artifactId, minVersion, maxVersion, preferredVersion, regularSuffix, devSuffix)
.load();
public static void loadLibrary(@NonNull String loadingModId, @NonNull String groupId, @NonNull String artifactId, @NonNull Version minVersion, Version maxVersion, @NonNull Version preferredVersion, String regularSuffix, String devSuffix) {
new DependencyLoadTask(loadingModId, groupId, artifactId, minVersion, maxVersion, preferredVersion,
regularSuffix, devSuffix).load();
}
private static String bytesToHex(byte[] hash) {
@@ -188,8 +186,8 @@ public class DependencyLoaderImpl {
private void setupLibraryNames() {
suffix = FalsePatternLib.isDeveloperEnvironment() ? devSuffix : regularSuffix;
artifactLogName =
String.format("%s:%s:%s%s", groupId, artifactId, preferredVersion, suffix != null ? "-" + suffix : "");
artifactLogName = String.format("%s:%s:%s%s", groupId, artifactId, preferredVersion,
suffix != null ? "-" + suffix : "");
log.info("Adding library {}, requested by mod {}", artifactLogName, loadingModId);
artifact = groupId + ":" + artifactId + ":" + suffix;
}
@@ -230,8 +228,8 @@ public class DependencyLoaderImpl {
}
}
val modsDir = Paths.get(homeDir, "mods").toFile();
mavenJarName = String.format("%s-%s%s.jar", artifactId, preferredVersion,
(suffix != null) ? ("-" + suffix) : "");
mavenJarName =
String.format("%s-%s%s.jar", artifactId, preferredVersion, (suffix != null) ? ("-" + suffix) : "");
jarName = groupId + "-" + mavenJarName;
libDir = new File(modsDir, "falsepattern");
if (!libDir.exists()) {
@@ -244,7 +242,9 @@ public class DependencyLoaderImpl {
}
private boolean tryLoadingExistingFile() {
if (!file.exists()) return false;
if (!file.exists()) {
return false;
}
try {
addToClasspath(file);
loadedLibraries.put(artifact, preferredVersion);
@@ -273,8 +273,8 @@ public class DependencyLoaderImpl {
if (!repo.endsWith("/")) {
repo = repo + "/";
}
val url = String.format("%s%s/%s/%s/%s", repo, groupId.replace('.', '/'), artifactId,
preferredVersion, mavenJarName);
val url = String.format("%s%s/%s/%s/%s", repo, groupId.replace('.', '/'), artifactId, preferredVersion,
mavenJarName);
String finalRepo = repo;
int retryCount = 0;
while (true) {
@@ -283,14 +283,14 @@ public class DependencyLoaderImpl {
break;
}
val success = new AtomicBoolean(false);
Internet.connect(new URL(url), (ex) -> log.debug("Artifact {} could not be downloaded from repo {}: {}",
artifactLogName, finalRepo, ex.getMessage()),
(input) -> {
log.debug("Downloading {} from {}", artifactLogName, finalRepo);
download(input, file);
log.debug("Downloaded {} from {}", artifactLogName, finalRepo);
success.set(true);
});
Internet.connect(new URL(url),
(ex) -> log.debug("Artifact {} could not be downloaded from repo {}: {}",
artifactLogName, finalRepo, ex.getMessage()), (input) -> {
log.debug("Downloading {} from {}", artifactLogName, finalRepo);
download(input, file);
log.debug("Downloaded {} from {}", artifactLogName, finalRepo);
success.set(true);
});
if (success.get()) {
log.debug("Validating checksum for {}", artifactLogName);
val hadChecksum = validateChecksum(url);
@@ -322,13 +322,13 @@ public class DependencyLoaderImpl {
log.debug("Attempting to get {} checksum...", checksumType);
val success = new AtomicBoolean(false);
Internet.connect(new URL(checksumURL),
(ex) -> log.debug("Could not get {} checksum for {}: {}", checksumType, artifactLogName, ex.getMessage()),
(input) -> {
log.debug("Downloading {} checksum for {}", checksumType, artifactLogName);
download(input, checksumFile);
log.debug("Downloaded {} checksum for {}", checksumType, artifactLogName);
success.set(true);
});
(ex) -> log.debug("Could not get {} checksum for {}: {}", checksumType,
artifactLogName, ex.getMessage()), (input) -> {
log.debug("Downloading {} checksum for {}", checksumType, artifactLogName);
download(input, checksumFile);
log.debug("Downloaded {} checksum for {}", checksumType, artifactLogName);
success.set(true);
});
if (success.get()) {
val fileHash = hash(checksumType, file);
val referenceHash = new String(Files.readAllBytes(checksumFile.toPath()));
@@ -347,7 +347,9 @@ public class DependencyLoaderImpl {
}
private enum ChecksumStatus {
OK, FAILED, MISSING
OK,
FAILED,
MISSING
}
}
}
@@ -20,7 +20,6 @@
*/
package com.falsepattern.lib.internal.impl.toast;
import com.falsepattern.lib.internal.config.LibraryConfig;
import com.falsepattern.lib.internal.config.ToastConfig;
import com.falsepattern.lib.toasts.IToast;
import com.falsepattern.lib.util.MathUtil;
@@ -45,10 +44,14 @@ import java.util.Deque;
@SideOnly(Side.CLIENT)
public class GuiToastImpl extends Gui {
private static GuiToastImpl instance;
private final Minecraft mc;
private final Deque<IToast> toastsQueue = Queues.newArrayDeque();
private ToastInstance<?>[] visible = new ToastInstance[0];
private static GuiToastImpl instance;
public GuiToastImpl(Minecraft mcIn) {
this.mc = mcIn;
}
public static void initialize(Minecraft mc) {
if (instance != null) {
@@ -64,7 +67,7 @@ public class GuiToastImpl extends Gui {
@SubscribeEvent
public void updateToasts(TickEvent.RenderTickEvent event) {
if ( event.phase != TickEvent.Phase.END) {
if (event.phase != TickEvent.Phase.END) {
return;
}
mc.mcProfiler.startSection("toasts");
@@ -72,11 +75,6 @@ public class GuiToastImpl extends Gui {
mc.mcProfiler.endSection();
}
public GuiToastImpl(Minecraft mcIn) {
this.mc = mcIn;
}
public void drawToast(ScaledResolution resolution) {
if (!this.mc.gameSettings.hideGUI) {
RenderHelper.disableStandardItemLighting();
@@ -168,9 +166,7 @@ public class GuiToastImpl extends Gui {
GL11.glPushMatrix();
val shift = toast.width() * getVisibility(sysTime);
val X = ToastConfig.leftAlign() ? shift - toast.width() : x - shift;
GL11.glTranslatef(X,
(float) (y * 32) + ToastConfig.Y_OFFSET,
(float) (500 + y));
GL11.glTranslatef(X, (float) (y * 32) + ToastConfig.Y_OFFSET, (float) (500 + y));
val visibility = this.toast.draw(GuiToastImpl.this, sysTime - this.visibleTime);
GL11.glPopMatrix();
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -25,10 +25,6 @@ import com.falsepattern.lib.config.ConfigurationManager;
import com.falsepattern.lib.internal.FalsePatternLib;
import com.falsepattern.lib.internal.Tags;
import com.falsepattern.lib.internal.config.ToastConfig;
import com.falsepattern.lib.internal.impl.config.net.SyncPrompt;
import com.falsepattern.lib.internal.impl.config.net.SyncPromptHandler;
import com.falsepattern.lib.internal.impl.config.net.SyncReply;
import com.falsepattern.lib.internal.impl.config.net.SyncReplyHandler;
import com.falsepattern.lib.internal.impl.toast.GuiToastImpl;
import com.falsepattern.lib.updates.UpdateChecker;
import lombok.val;
@@ -83,11 +79,12 @@ public class ClientProxy extends CommonProxy {
@SubscribeEvent
public void onSinglePlayer(EntityJoinWorldEvent e) {
if (chatFuture == null ||
!(e.entity instanceof EntityPlayerSP)) return;
if (chatFuture == null || !(e.entity instanceof EntityPlayerSP)) {
return;
}
val player = (EntityPlayerSP) e.entity;
try {
for (val line: chatFuture.get()) {
for (val line : chatFuture.get()) {
player.addChatMessage(line);
}
chatFuture = null;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -24,7 +24,6 @@ import com.falsepattern.lib.config.ConfigException;
import com.falsepattern.lib.config.ConfigurationManager;
import com.falsepattern.lib.internal.FalsePatternLib;
import com.falsepattern.lib.internal.config.LibraryConfig;
import com.falsepattern.lib.internal.config.ToastConfig;
import com.falsepattern.lib.internal.impl.config.ConfigurationManagerImpl;
import com.falsepattern.lib.internal.impl.config.net.SyncPrompt;
import com.falsepattern.lib.internal.impl.config.net.SyncPromptHandler;
@@ -34,14 +33,13 @@ import com.falsepattern.lib.internal.impl.config.net.SyncRequest;
import com.falsepattern.lib.internal.impl.config.net.SyncRequestHandler;
import com.falsepattern.lib.updates.ModUpdateInfo;
import com.falsepattern.lib.updates.UpdateChecker;
import lombok.val;
import cpw.mods.fml.common.event.FMLConstructionEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.relauncher.Side;
import lombok.val;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -37,20 +37,21 @@ import org.objectweb.asm.tree.MethodInsnNode;
import java.util.HashMap;
public class MappingManager {
private static boolean initialized = false;
private static final Lookup<UniversalClass> internalLookup = new Lookup<>();
private static final Lookup<UniversalClass> regularLookup = new Lookup<>();
private static boolean initialized = false;
@SneakyThrows
private static synchronized void initialize() {
if (initialized) return;
if (initialized) {
return;
}
initialized = true;
long start = System.nanoTime();
val stringPool = new HashMap<String, String>();
{
val classMappings = ResourceUtil.getResourceStringFromJar("/classes.csv", FalsePatternLib.class).split("\n");
val classMappings =
ResourceUtil.getResourceStringFromJar("/classes.csv", FalsePatternLib.class).split("\n");
for (int i = 1; i < classMappings.length; i++) {
val line = classMappings[i].split(",");
val clazz = new UniversalClass(line, stringPool);
@@ -67,7 +68,8 @@ public class MappingManager {
}
}
{
val methodMappings = ResourceUtil.getResourceStringFromJar("/methods.csv", FalsePatternLib.class).split("\n");
val methodMappings =
ResourceUtil.getResourceStringFromJar("/methods.csv", FalsePatternLib.class).split("\n");
for (int i = 1; i < methodMappings.length; i++) {
val line = methodMappings[i].split(",");
val clazz = internalLookup.get(MappingType.Notch, line[0].substring(0, line[0].lastIndexOf('/')));
@@ -78,7 +80,8 @@ public class MappingManager {
System.out.println("Parsed in " + (end - start) / 1000000 + "ms");
}
public static UniversalClass classForName(NameType nameType, MappingType mappingType, String className) throws ClassNotFoundException {
public static UniversalClass classForName(NameType nameType, MappingType mappingType, String className)
throws ClassNotFoundException {
initialize();
try {
switch (nameType) {
@@ -90,7 +93,9 @@ public class MappingManager {
throw new IllegalArgumentException("Invalid enum value " + nameType);
}
} catch (Lookup.LookupException e) {
throw new ClassNotFoundException("Could not find class \"" + className + "\" with " + nameType.name().toLowerCase() + " name in the " + mappingType.name() + " mapping.");
throw new ClassNotFoundException(
"Could not find class \"" + className + "\" with " + nameType.name().toLowerCase() +
" name in the " + mappingType.name() + " mapping.");
}
}
@@ -105,22 +110,27 @@ public class MappingManager {
}
}
public static UniversalField getField(FieldInsnNode instruction) throws ClassNotFoundException,
NoSuchFieldException {
public static UniversalField getField(FieldInsnNode instruction)
throws ClassNotFoundException, NoSuchFieldException {
if (!CoreLoadingPlugin.isObfuscated()) {
try {
return classForName(NameType.Internal, MappingType.MCP, instruction.owner).getField(MappingType.MCP, instruction.name);
return classForName(NameType.Internal, MappingType.MCP, instruction.owner).getField(MappingType.MCP,
instruction.name);
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException("Could not find the class " + instruction.owner + " in the MCP mappings. Are you sure it's a Minecraft class? (we're in dev, cannot use SRG or Notch here).");
throw new ClassNotFoundException("Could not find the class " + instruction.owner +
" in the MCP mappings. Are you sure it's a Minecraft class? (we're in dev, cannot use SRG or Notch here).");
}
} else {
try {
return classForName(NameType.Internal, MappingType.SRG, instruction.owner).getField(MappingType.SRG, instruction.name);
return classForName(NameType.Internal, MappingType.SRG, instruction.owner).getField(MappingType.SRG,
instruction.name);
} catch (ClassNotFoundException e) {
try {
return classForName(NameType.Internal, MappingType.Notch, instruction.owner).getField(MappingType.Notch, instruction.name);
return classForName(NameType.Internal, MappingType.Notch, instruction.owner).getField(
MappingType.Notch, instruction.name);
} catch (ClassNotFoundException ex) {
throw new ClassNotFoundException("Could not find the class " + instruction.owner + " neither in the SRG nor in the Notch mappings. Are you sure it's a Minecraft class? (we're in obf, cannot use MCP here)");
throw new ClassNotFoundException("Could not find the class " + instruction.owner +
" neither in the SRG nor in the Notch mappings. Are you sure it's a Minecraft class? (we're in obf, cannot use MCP here)");
}
}
}
@@ -130,18 +140,25 @@ public class MappingManager {
throws ClassNotFoundException, NoSuchMethodException {
if (!CoreLoadingPlugin.isObfuscated()) {
try {
return classForName(NameType.Internal, MappingType.MCP, instruction.owner).getMethod(MappingType.MCP, instruction.name, instruction.desc);
return classForName(NameType.Internal, MappingType.MCP, instruction.owner).getMethod(MappingType.MCP,
instruction.name,
instruction.desc);
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException("Could not find the class " + instruction.owner + " in the MCP mappings. Are you sure it's a Minecraft class? (we're in dev, cannot use SRG or Notch here).");
throw new ClassNotFoundException("Could not find the class " + instruction.owner +
" in the MCP mappings. Are you sure it's a Minecraft class? (we're in dev, cannot use SRG or Notch here).");
}
} else {
try {
return classForName(NameType.Internal, MappingType.SRG, instruction.owner).getMethod(MappingType.SRG, instruction.name, instruction.desc);
return classForName(NameType.Internal, MappingType.SRG, instruction.owner).getMethod(MappingType.SRG,
instruction.name,
instruction.desc);
} catch (ClassNotFoundException e) {
try {
return classForName(NameType.Internal, MappingType.Notch, instruction.owner).getMethod(MappingType.Notch, instruction.name, instruction.desc);
return classForName(NameType.Internal, MappingType.Notch, instruction.owner).getMethod(
MappingType.Notch, instruction.name, instruction.desc);
} catch (ClassNotFoundException ex) {
throw new ClassNotFoundException("Could not find the class " + instruction.owner + " neither in the SRG nor in the Notch mappings. Are you sure it's a Minecraft class? (we're in obf, cannot use MCP here)");
throw new ClassNotFoundException("Could not find the class " + instruction.owner +
" neither in the SRG nor in the Notch mappings. Are you sure it's a Minecraft class? (we're in obf, cannot use MCP here)");
}
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -40,6 +40,16 @@ public class Lookup<T> {
private final Map<String, T> srg = new HashMap<>();
private final Map<String, T> mcp = new HashMap<>();
private static <T> void removeFirst(Iterator<Map.Entry<String, T>> iterator, T value) {
while (iterator.hasNext()) {
val entry = iterator.next();
if (entry.getValue().equals(value)) {
iterator.remove();
return;
}
}
}
public boolean contains(T value) {
return values.contains(value);
}
@@ -92,16 +102,6 @@ public class Lookup<T> {
return result;
}
private static <T> void removeFirst(Iterator<Map.Entry<String, T>> iterator, T value) {
while (iterator.hasNext()) {
val entry = iterator.next();
if (entry.getValue().equals(value)) {
iterator.remove();
return;
}
}
}
public static class LookupException extends Exception {
public LookupException(String message) {
super(message);
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -40,16 +40,17 @@ public class MappedString {
public final String notch;
public final String srg;
public final String mcp;
public MappedString(String[] source, int offset, int stride, Function<String, String> remapper, Map<String, String> stringPool) {
notch = stringPool.computeIfAbsent(remapper.apply(source[offset ]), (str) -> str);
srg = stringPool.computeIfAbsent(remapper.apply(source[offset + stride ]), (str) -> str);
mcp = stringPool.computeIfAbsent(remapper.apply(source[offset + stride * 2]), (str) -> str);
notch = stringPool.computeIfAbsent(remapper.apply(source[offset]), (str) -> str);
srg = stringPool.computeIfAbsent(remapper.apply(source[offset + stride]), (str) -> str);
mcp = stringPool.computeIfAbsent(remapper.apply(source[offset + stride * 2]), (str) -> str);
}
public static MappedString fuse(MappedString a, MappedString b, String delimiter, Map<String, String> stringPool) {
return new MappedString(stringPool.computeIfAbsent(a.notch + delimiter + b.notch, (str) -> str),
stringPool.computeIfAbsent(a.srg + delimiter + b.srg , (str) -> str),
stringPool.computeIfAbsent(a.mcp + delimiter + b.mcp , (str) -> str));
stringPool.computeIfAbsent(a.srg + delimiter + b.srg, (str) -> str),
stringPool.computeIfAbsent(a.mcp + delimiter + b.mcp, (str) -> str));
}
public String get(MappingType type) {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -116,7 +116,8 @@ public class UniversalClass {
}
}
public UniversalMethod getMethod(MappingType mappingType, String methodName, String methodDescriptor) throws NoSuchMethodException {
public UniversalMethod getMethod(MappingType mappingType, String methodName, String methodDescriptor)
throws NoSuchMethodException {
try {
return methods.get(mappingType, methodName + methodDescriptor);
} catch (Lookup.LookupException e) {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -20,8 +20,8 @@
*/
package com.falsepattern.lib.mapping.types;
import com.falsepattern.lib.util.ReflectionUtil;
import com.falsepattern.lib.mapping.storage.MappedString;
import com.falsepattern.lib.util.ReflectionUtil;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -20,8 +20,8 @@
*/
package com.falsepattern.lib.mapping.types;
import com.falsepattern.lib.util.ReflectionUtil;
import com.falsepattern.lib.mapping.storage.MappedString;
import com.falsepattern.lib.util.ReflectionUtil;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
@@ -61,30 +61,12 @@ public class UniversalMethod {
parent.addMethod(this);
}
public String getName(MappingType mappingType) {
return name.get(mappingType);
}
public String getDescriptor(MappingType mappingType) {
return descriptor.get(mappingType);
}
public Method asJavaMethod() throws ClassNotFoundException, NoSuchMethodException {
if (javaMethodCache != null) {
return javaMethodCache;
}
val parentClass = parent.asJavaClass();
javaMethodCache = parentClass.getDeclaredMethod(getName(parent.realClassMapping()), decodeMethodDescriptor(getDescriptor(parent.realClassMapping())));
ReflectionUtil.jailBreak(javaMethodCache);
return javaMethodCache;
}
private static Class<?>[] decodeMethodDescriptor(String desc) throws ClassNotFoundException {
val result = new ArrayList<Class<?>>();
val buf = new StringBuilder();
boolean readingReference = false;
int arrayDimensions = 0;
for (val c: desc.toCharArray()) {
for (val c : desc.toCharArray()) {
Class<?> parsedClass = null;
if (readingReference) {
if (c == ';') {
@@ -95,9 +77,12 @@ public class UniversalMethod {
buf.append(c);
continue;
}
} else if (c == '(') continue;
else if (c == ')') break;
else switch (c) {
} else if (c == '(') {
continue;
} else if (c == ')') {
break;
} else {
switch (c) {
case 'B':
parsedClass = byte.class;
break;
@@ -128,6 +113,7 @@ public class UniversalMethod {
case '[':
arrayDimensions++;
continue;
}
}
for (int i = 0; i < arrayDimensions; i++) {
parsedClass = Array.newInstance(parsedClass, 0).getClass();
@@ -138,15 +124,36 @@ public class UniversalMethod {
return result.toArray(new Class[0]);
}
public String getName(MappingType mappingType) {
return name.get(mappingType);
}
public String getDescriptor(MappingType mappingType) {
return descriptor.get(mappingType);
}
public Method asJavaMethod() throws ClassNotFoundException, NoSuchMethodException {
if (javaMethodCache != null) {
return javaMethodCache;
}
val parentClass = parent.asJavaClass();
javaMethodCache = parentClass.getDeclaredMethod(getName(parent.realClassMapping()), decodeMethodDescriptor(
getDescriptor(parent.realClassMapping())));
ReflectionUtil.jailBreak(javaMethodCache);
return javaMethodCache;
}
/**
* This is only here for completeness' sake, given that MethodInsnNode itself also has a deprecated yet functional constructor.
*/
@Deprecated
public MethodInsnNode asInstruction(int opcode, MappingType mapping) {
return new MethodInsnNode(opcode, parent.getName(NameType.Internal, mapping), getName(mapping), getDescriptor(mapping));
return new MethodInsnNode(opcode, parent.getName(NameType.Internal, mapping), getName(mapping),
getDescriptor(mapping));
}
public MethodInsnNode asInstruction(int opcode, MappingType mapping, boolean itf) {
return new MethodInsnNode(opcode, parent.getName(NameType.Internal, mapping), getName(mapping), getDescriptor(mapping), itf);
return new MethodInsnNode(opcode, parent.getName(NameType.Internal, mapping), getName(mapping),
getDescriptor(mapping), itf);
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,11 +21,13 @@
package com.falsepattern.lib.mixin;
import com.falsepattern.lib.StableAPI;
import lombok.val;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Supplier;
import lombok.val;
@StableAPI(since = "0.8.0")
public interface IMixin {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,6 +21,16 @@
package com.falsepattern.lib.mixin;
import com.falsepattern.lib.StableAPI;
import com.falsepattern.lib.util.FileUtil;
import lombok.val;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import net.minecraft.launchwrapper.Launch;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -31,15 +41,6 @@ import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.falsepattern.lib.util.FileUtil;
import lombok.val;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import static java.nio.file.Files.walk;
@StableAPI(since = "0.8.0")
@@ -50,6 +51,15 @@ public interface IMixinPlugin extends IMixinConfigPlugin {
return LogManager.getLogger(modName + " Mixin Loader");
}
static File findJarOf(final ITargetedMod mod) {
try (val stream = walk(MODS_DIRECTORY_PATH)) {
return stream.filter(mod::isMatchingJar).map(Path::toFile).findFirst().orElse(null);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
default void onLoad(String mixinPackage) {
@@ -124,15 +134,6 @@ public interface IMixinPlugin extends IMixinConfigPlugin {
IMixin[] getMixinEnumValues();
static File findJarOf(final ITargetedMod mod) {
try (val stream = walk(MODS_DIRECTORY_PATH)) {
return stream.filter(mod::isMatchingJar).map(Path::toFile).findFirst().orElse(null);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
default void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -22,6 +22,7 @@ package com.falsepattern.lib.mixin;
import com.falsepattern.lib.StableAPI;
import com.google.common.io.Files;
import java.nio.file.Path;
import java.util.function.Predicate;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -20,15 +20,17 @@
*/
package com.falsepattern.lib.mixin;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModClassLoader;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.val;
import net.minecraft.launchwrapper.LaunchClassLoader;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModClassLoader;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
/**
* Backport from spongemixins 1.3 for compat with the curseforge 1.2.0 version.
@@ -47,16 +49,15 @@ public final class MinecraftURLClassPath {
static {
boolean grimoire = false;
String[] knownGrimoireClassNames = new String[]{
"io.github.crucible.grimoire.Grimoire",
"io.github.crucible.grimoire.common.GrimoireCore"
};
for (val className: knownGrimoireClassNames) {
String[] knownGrimoireClassNames =
new String[]{"io.github.crucible.grimoire.Grimoire", "io.github.crucible.grimoire.common.GrimoireCore"};
for (val className : knownGrimoireClassNames) {
try {
Class.forName(className, false, MinecraftURLClassPath.class.getClassLoader());
grimoire = true;
break;
} catch (ClassNotFoundException ignored) {}
} catch (ClassNotFoundException ignored) {
}
}
GRIMOIRE = grimoire;
if (!GRIMOIRE) {
@@ -64,8 +65,8 @@ public final class MinecraftURLClassPath {
val modClassLoaderField = Loader.class.getDeclaredField("modClassLoader");
modClassLoaderField.setAccessible(true);
val loaderinstanceField = Loader.class.getDeclaredField("instance");
loaderinstanceField.setAccessible(true);
val loaderInstanceField = Loader.class.getDeclaredField("instance");
loaderInstanceField.setAccessible(true);
val mainClassLoaderField = ModClassLoader.class.getDeclaredField("mainClassLoader");
mainClassLoaderField.setAccessible(true);
@@ -73,7 +74,7 @@ public final class MinecraftURLClassPath {
val ucpField = LaunchClassLoader.class.getSuperclass().getDeclaredField("ucp");
ucpField.setAccessible(true);
Object loader = loaderinstanceField.get(null);
Object loader = loaderInstanceField.get(null);
val modClassLoader = (ModClassLoader) modClassLoaderField.get(loader);
val mainClassLoader = (LaunchClassLoader) mainClassLoaderField.get(modClassLoader);
ucp = ucpField.get(mainClassLoader);
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,20 +21,10 @@
package com.falsepattern.lib.text;
import com.falsepattern.lib.StableAPI;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.awt.Color;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import lombok.NonNull;
import lombok.val;
import lombok.var;
import net.minecraft.client.entity.EntityOtherPlayerMP;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.FontRenderer;
@@ -47,6 +37,18 @@ import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.awt.Color;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
/**
* Universal escape sequence-based text rendering and chat messages.
@@ -132,10 +134,7 @@ public final class FormattedText {
private final boolean endLine;
private FormattedText(@NonNull String text,
@NonNull EnumChatFormatting colorStyle,
@NonNull Set<EnumChatFormatting> fancyStyles,
boolean endLine) {
private FormattedText(@NonNull String text, @NonNull EnumChatFormatting colorStyle, @NonNull Set<EnumChatFormatting> fancyStyles, boolean endLine) {
this.text = text;
this.fancyStyles.addAll(fancyStyles);
this.colorStyle = colorStyle;
@@ -51,9 +51,9 @@ public class SimpleToast implements IToast {
private float currentProgress;
@StableAPI(since = "0.10.0")
public SimpleToast(@NonNull ToastBG background, @Nullable ToastIcon icon,
IChatComponent titleComponent, @Nullable IChatComponent subtitleComponent,
boolean drawProgressBar, long timeout) {
public SimpleToast(@NonNull ToastBG background,
@Nullable ToastIcon icon, IChatComponent titleComponent,
@Nullable IChatComponent subtitleComponent, boolean drawProgressBar, long timeout) {
this.background = background;
this.icon = icon;
this.title = titleComponent.getFormattedText();
@@ -83,7 +83,8 @@ public class SimpleToast implements IToast {
if (hasProgressBar) {
val bgWidth = background.getIcon().getIconWidth();
Gui.drawRect(3, bgHeight - 4, bgWidth - 3, bgHeight - 3, 0xFFFFFFFF);
float f = (float) MathUtil.clampedLerp(displayedProgress, currentProgress, (float) (delta - lastDelta) / 100.0F);
float f = (float) MathUtil.clampedLerp(displayedProgress, currentProgress,
(float) (delta - lastDelta) / 100.0F);
int i;
if (currentProgress >= displayedProgress) {
@@ -36,17 +36,24 @@ import cpw.mods.fml.relauncher.SideOnly;
@StableAPI(since = "0.10.0")
public class ToastBG extends ToastTexture {
@StableAPI(since = "0.10.0")
public static final ToastBG TOAST_DARK = new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_dark.png"), 160, 32, 0xFFFFFFFF);
public static final ToastBG TOAST_DARK =
new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_dark.png"), 160, 32, 0xFFFFFFFF);
@StableAPI(since = "0.10.0")
public static final ToastBG TOAST_DARK_ROUNDED = new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_dark_rounded.png"), 160, 32, 0xFFFFFFFF);
public static final ToastBG TOAST_DARK_ROUNDED =
new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_dark_rounded.png"), 160, 32, 0xFFFFFFFF);
@StableAPI(since = "0.10.0")
public static final ToastBG TOAST_NARRATOR = new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_narrator.png"), 160, 32, 0xFFAAAA00);
public static final ToastBG TOAST_NARRATOR =
new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_narrator.png"), 160, 32, 0xFFAAAA00);
@StableAPI(since = "0.10.0")
public static final ToastBG TOAST_NARRATOR_ROUNDED = new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_narrator_rounded.png"), 160, 32, 0xFFAAAA00);
public static final ToastBG TOAST_NARRATOR_ROUNDED =
new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_narrator_rounded.png"), 160, 32,
0xFFAAAA00);
@StableAPI(since = "0.10.0")
public static final ToastBG TOAST_WHITE = new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_white.png"), 160, 32, 0xFF500050);
public static final ToastBG TOAST_WHITE =
new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_white.png"), 160, 32, 0xFF500050);
@StableAPI(since = "0.10.0")
public static final ToastBG TOAST_WHITE_ROUNDED = new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_white_rounded.png"), 160, 32, 0xFF500050);
public static final ToastBG TOAST_WHITE_ROUNDED =
new ToastBG(new ResourceLocation(Tags.MODID, "textures/gui/toast_white_rounded.png"), 160, 32, 0xFF500050);
@StableAPI(since = "0.10.0")
public final int defaultTextColor;
@@ -34,9 +34,9 @@ import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
@StableAPI(since = "0.10.0")
public abstract class ToastTexture {
@Getter(onMethod_={@StableAPI(since = "0.10.0")})
@Getter(onMethod_ = {@StableAPI(since = "0.10.0")})
protected final IIcon icon;
@Getter(onMethod_={@StableAPI(since = "0.10.0")})
@Getter(onMethod_ = {@StableAPI(since = "0.10.0")})
protected final ResourceLocation texture;
@StableAPI(since = "0.10.0")
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -28,17 +28,18 @@ import org.apache.logging.log4j.Logger;
@Data
@StableAPI(since = "0.8.0")
public class ModUpdateInfo {
@NonNull public final String modID;
@NonNull public final String currentVersion;
@NonNull public final String latestVersion;
@NonNull public final String updateURL;
@NonNull
public final String modID;
@NonNull
public final String currentVersion;
@NonNull
public final String latestVersion;
@NonNull
public final String updateURL;
public void log(Logger logger) {
logger.info("Updates are available for mod {}: Currently installed version is {}, " +
"latest available version is {}. Update URL: {}",
modID,
currentVersion,
latestVersion,
updateURL.isEmpty() ? "unavailable": updateURL);
"latest available version is {}. Update URL: {}", modID, currentVersion, latestVersion,
updateURL.isEmpty() ? "unavailable" : updateURL);
}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -25,14 +25,15 @@ import com.falsepattern.lib.StableAPI;
import com.falsepattern.lib.dependencies.DependencyLoader;
import com.falsepattern.lib.dependencies.SemanticVersion;
import com.falsepattern.lib.internal.Internet;
import com.falsepattern.lib.internal.config.LibraryConfig;
import com.falsepattern.lib.internal.Tags;
import com.falsepattern.lib.internal.config.LibraryConfig;
import com.falsepattern.lib.text.FormattedText;
import cpw.mods.fml.common.Loader;
import lombok.val;
import net.minecraft.client.resources.I18n;
import net.minecraft.event.ClickEvent;
import net.minecraft.util.IChatComponent;
import cpw.mods.fml.common.Loader;
import java.net.MalformedURLException;
import java.net.URL;
@@ -67,7 +68,9 @@ public class UpdateChecker {
* ...etc, one json object per mod.
* ]
* }</pre>
*
* @param url The URL to check
*
* @return A list of mods that were both available on the URL and installed
*/
public static CompletableFuture<List<ModUpdateInfo>> fetchUpdatesAsync(String url) {
@@ -93,7 +96,8 @@ public class UpdateChecker {
.preferredVersion(new SemanticVersion(0, 4, 1))
.build();
} catch (Exception e) {
throw new CompletionException(new UpdateCheckException("Failed to load json library for update checker!", e));
throw new CompletionException(
new UpdateCheckException("Failed to load json library for update checker!", e));
}
jsonLibraryLoaded.set(true);
}
@@ -102,7 +106,8 @@ public class UpdateChecker {
try {
parsed = JsonNode.parse(Internet.download(URL).thenApply(String::new).join());
} catch (CompletionException e) {
throw new CompletionException(new UpdateCheckException("Failed to download update checker JSON file!", e.getCause() == null ? e : e.getCause()));
throw new CompletionException(new UpdateCheckException("Failed to download update checker JSON file!",
e.getCause() == null ? e : e.getCause()));
}
List<JsonNode> modList;
if (parsed.isList()) {
@@ -111,12 +116,20 @@ public class UpdateChecker {
modList = Collections.singletonList(parsed);
}
val installedMods = Loader.instance().getIndexedModList();
for (val node: modList) {
if (!node.isObject()) continue;
if (!node.containsKey("modid")) continue;
if (!node.containsKey("latestVersion")) continue;
for (val node : modList) {
if (!node.isObject()) {
continue;
}
if (!node.containsKey("modid")) {
continue;
}
if (!node.containsKey("latestVersion")) {
continue;
}
val modid = node.getString("modid");
if (!installedMods.containsKey(modid)) continue;
if (!installedMods.containsKey(modid)) {
continue;
}
val mod = installedMods.get(modid);
val latestVersionsNode = node.get("latestVersion");
List<String> latestVersions;
@@ -124,16 +137,22 @@ public class UpdateChecker {
latestVersions = Collections.singletonList(latestVersionsNode.stringValue());
} else if (latestVersionsNode.isList()) {
latestVersions = new ArrayList<>();
for (val version: latestVersionsNode.getJavaList()) {
if (!version.isString()) continue;
for (val version : latestVersionsNode.getJavaList()) {
if (!version.isString()) {
continue;
}
latestVersions.add(version.stringValue());
}
} else {
continue;
}
val currentVersion = mod.getVersion();
if (latestVersions.contains(currentVersion)) continue;
val updateURL = node.containsKey("updateURL") && node.get("updateURL").isString() ? node.getString("updateURL") : "";
if (latestVersions.contains(currentVersion)) {
continue;
}
val updateURL =
node.containsKey("updateURL") && node.get("updateURL").isString() ? node.getString("updateURL")
: "";
result.add(new ModUpdateInfo(modid, currentVersion, latestVersions.get(0), updateURL));
}
return result;
@@ -142,8 +161,11 @@ public class UpdateChecker {
/**
* Same this as {@link #fetchUpdatesAsync(String)}, but returns the result in a blocking fashion.
*
* @param url The URL to check
*
* @return A future that will contain the update info about mods that were both available on the URL and installed
*
* @throws UpdateCheckException If the update checker is disabled in config, the URL is invalid, or
*/
public static List<ModUpdateInfo> fetchUpdates(String url) throws UpdateCheckException {
@@ -162,20 +184,29 @@ public class UpdateChecker {
/**
* Formats the raw list of updates into lines of chat messages you can send to players.
*
* @param initiator Who/what/which mod did this update check
* @param updates The list of updates to convert
* @param updates The list of updates to convert
*
* @return A list of chat messages that can be sent to players
*/
public static List<IChatComponent> updateListToChatMessages(String initiator, List<ModUpdateInfo> updates) {
if (updates == null || updates.size() == 0)
if (updates == null || updates.size() == 0) {
return null;
val updateText = new ArrayList<IChatComponent>(FormattedText.parse(I18n.format("falsepatternlib.chat.updatesavailable", initiator)).toChatText());
}
val updateText = new ArrayList<IChatComponent>(
FormattedText.parse(I18n.format("falsepatternlib.chat.updatesavailable", initiator)).toChatText());
val mods = Loader.instance().getIndexedModList();
for (val update : updates) {
val mod = mods.get(update.modID);
updateText.addAll(FormattedText.parse(I18n.format("falsepatternlib.chat.modname", mod.getName())).toChatText());
updateText.addAll(FormattedText.parse(I18n.format("falsepatternlib.chat.currentversion", update.currentVersion)).toChatText());
updateText.addAll(FormattedText.parse(I18n.format("falsepatternlib.chat.latestversion", update.latestVersion)).toChatText());
updateText.addAll(
FormattedText.parse(I18n.format("falsepatternlib.chat.modname", mod.getName())).toChatText());
updateText.addAll(
FormattedText.parse(I18n.format("falsepatternlib.chat.currentversion", update.currentVersion))
.toChatText());
updateText.addAll(
FormattedText.parse(I18n.format("falsepatternlib.chat.latestversion", update.latestVersion))
.toChatText());
if (!update.updateURL.isEmpty()) {
val pre = FormattedText.parse(I18n.format("falsepatternlib.chat.updateurlpre")).toChatText();
val link = FormattedText.parse(I18n.format("falsepatternlib.chat.updateurl")).toChatText();
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,6 +21,7 @@
package com.falsepattern.lib.util;
import com.falsepattern.lib.StableAPI;
import net.minecraft.launchwrapper.Launch;
import java.io.File;
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,8 +21,11 @@
package com.falsepattern.lib.util;
import com.falsepattern.lib.StableAPI;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.val;
import cpw.mods.fml.common.registry.LanguageRegistry;
import lombok.*;
import java.util.HashMap;
import java.util.Map;
@@ -40,8 +43,9 @@ public final class LangUtil {
}
public static void defaultLocalization(@NonNull String key, @NonNull String value) {
if (!LanguageRegistry.instance().getStringLocalization(key, DEFAULT_LOCALE).isEmpty())
if (!LanguageRegistry.instance().getStringLocalization(key, DEFAULT_LOCALE).isEmpty()) {
return;
}
val map = tempMap.get();
map.put(key, value);
LanguageRegistry.instance().injectLanguage(DEFAULT_LOCALE, map);
@@ -207,7 +207,7 @@ public class MathUtil {
}
/**
* Buckets an integer with specifed bucket sizes.
* Buckets an integer with specified bucket sizes.
*/
@StableAPI(since = "0.10.0")
public static int intFloorDiv(int number, int bucket) {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -28,6 +28,7 @@ import java.lang.reflect.Modifier;
public class ReflectionUtil {
private static final Field f_modifiers;
static {
try {
f_modifiers = Field.class.getDeclaredField("modifiers");
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2022 FalsePattern
* All Rights Reserved
*
@@ -21,6 +21,8 @@
package com.falsepattern.lib.util;
import com.falsepattern.lib.StableAPI;
import lombok.val;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -28,7 +30,6 @@ import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import lombok.val;
/**
* A utility class for reading resources in many ways.