baritone/src/api/java/baritone/api/utils/SettingsUtil.java

358 lines
14 KiB
Java
Raw Normal View History

2018-10-09 01:05:08 +00:00
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.utils;
2019-09-01 16:47:27 +00:00
import baritone.api.BaritoneAPI;
2018-10-09 01:05:08 +00:00
import baritone.api.Settings;
import net.minecraft.client.Minecraft;
2021-06-23 17:24:32 +00:00
import net.minecraft.core.Direction;
import net.minecraft.core.Registry;
import net.minecraft.core.Vec3i;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
2018-10-09 01:05:08 +00:00
import java.awt.*;
2019-01-07 00:49:58 +00:00
import java.io.BufferedReader;
2019-01-07 16:53:39 +00:00
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
2019-01-07 16:53:39 +00:00
import java.nio.file.Files;
2019-04-29 23:43:47 +00:00
import java.nio.file.NoSuchFileException;
2019-01-07 16:53:39 +00:00
import java.nio.file.Path;
2019-04-20 22:35:11 +00:00
import java.util.ArrayList;
2019-02-22 20:13:19 +00:00
import java.util.List;
2021-01-16 23:16:34 +00:00
import java.util.Map;
2019-05-01 19:22:47 +00:00
import java.util.Objects;
2019-01-07 16:53:39 +00:00
import java.util.function.Consumer;
2018-10-09 01:05:08 +00:00
import java.util.function.Function;
2019-01-07 16:53:39 +00:00
import java.util.regex.Matcher;
import java.util.regex.Pattern;
2018-10-09 01:05:08 +00:00
import java.util.stream.Collectors;
import java.util.stream.Stream;
2018-10-09 01:05:08 +00:00
2018-10-14 05:55:30 +00:00
2018-10-09 01:05:08 +00:00
public class SettingsUtil {
2018-10-14 05:55:30 +00:00
2021-06-23 17:24:32 +00:00
private static final Path SETTINGS_PATH = Minecraft.getInstance().gameDirectory.toPath().resolve("baritone").resolve("settings.txt");
private static final Pattern SETTING_PATTERN = Pattern.compile("^(?<setting>[^ ]+) +(?<value>.+)"); // key and value split by the first space
private static final String[] JAVA_ONLY_SETTINGS = {"logger", "notifier", "toaster"};
2018-10-09 01:05:08 +00:00
2019-01-07 06:08:46 +00:00
private static boolean isComment(String line) {
return line.startsWith("#") || line.startsWith("//");
}
private static void forEachLine(Path file, Consumer<String> consumer) throws IOException {
try (BufferedReader scan = Files.newBufferedReader(file)) {
2019-01-07 00:49:58 +00:00
String line;
while ((line = scan.readLine()) != null) {
2019-01-07 16:53:39 +00:00
if (line.isEmpty() || isComment(line)) {
continue;
}
2019-01-07 06:08:46 +00:00
consumer.accept(line);
}
}
}
2019-01-07 06:25:39 +00:00
public static void readAndApply(Settings settings) {
2019-01-07 06:08:46 +00:00
try {
2019-01-07 16:53:39 +00:00
forEachLine(SETTINGS_PATH, line -> {
2019-01-07 06:08:46 +00:00
Matcher matcher = SETTING_PATTERN.matcher(line);
if (!matcher.matches()) {
System.out.println("Invalid syntax in setting file: " + line);
return;
2018-10-09 01:05:08 +00:00
}
2019-01-07 06:08:46 +00:00
String settingName = matcher.group("setting").toLowerCase();
2019-01-07 06:16:52 +00:00
String settingValue = matcher.group("value");
2018-10-09 01:05:08 +00:00
try {
parseAndApply(settings, settingName, settingValue);
} catch (Exception ex) {
System.out.println("Unable to parse line " + line);
2019-01-07 06:08:46 +00:00
ex.printStackTrace();
2018-10-09 01:05:08 +00:00
}
2019-01-07 06:08:46 +00:00
});
2019-04-29 23:43:47 +00:00
} catch (NoSuchFileException ignored) {
System.out.println("Baritone settings file not found, resetting.");
2018-10-09 01:05:08 +00:00
} catch (Exception ex) {
System.out.println("Exception while reading Baritone settings, some settings may be reset to default values!");
2019-01-07 06:08:46 +00:00
ex.printStackTrace();
2018-10-09 01:05:08 +00:00
}
}
public static synchronized void save(Settings settings) {
2019-01-07 16:53:39 +00:00
try (BufferedWriter out = Files.newBufferedWriter(SETTINGS_PATH)) {
2019-02-22 20:13:19 +00:00
for (Settings.Setting setting : modifiedSettings(settings)) {
out.write(settingToString(setting) + "\n");
2018-10-09 01:05:08 +00:00
}
} catch (Exception ex) {
2019-01-07 06:08:46 +00:00
System.out.println("Exception thrown while saving Baritone settings!");
2018-10-09 01:05:08 +00:00
ex.printStackTrace();
}
}
2019-02-22 20:13:19 +00:00
public static List<Settings.Setting> modifiedSettings(Settings settings) {
List<Settings.Setting> modified = new ArrayList<>();
for (Settings.Setting setting : settings.allSettings) {
2019-03-05 05:30:04 +00:00
if (setting.value == null) {
2019-02-22 20:13:19 +00:00
System.out.println("NULL SETTING?" + setting.getName());
continue;
}
if (javaOnlySetting(setting)) {
2019-02-22 20:13:19 +00:00
continue; // NO
}
if (setting.value == setting.defaultValue) {
continue;
}
modified.add(setting);
}
return modified;
}
2019-09-06 10:59:10 +00:00
/**
* Gets the type of a setting and returns it as a string, with package names stripped.
2019-09-19 19:53:15 +00:00
* <p>
2019-09-06 10:59:10 +00:00
* For example, if the setting type is {@code java.util.List<java.lang.String>}, this function returns
* {@code List<String>}.
*
* @param setting The setting
* @return The type
*/
2019-08-30 18:55:25 +00:00
public static String settingTypeToString(Settings.Setting setting) {
return setting.getType().getTypeName()
2019-09-19 19:53:15 +00:00
.replaceAll("(?:\\w+\\.)+(\\w+)", "$1");
2019-08-30 18:55:25 +00:00
}
public static <T> String settingValueToString(Settings.Setting<T> setting, T value) throws IllegalArgumentException {
Parser io = Parser.getParser(setting.getType());
2019-08-30 18:55:25 +00:00
2019-02-22 20:13:19 +00:00
if (io == null) {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName());
}
2019-08-30 18:55:25 +00:00
return io.toString(new ParserContext(setting), value);
}
public static String settingValueToString(Settings.Setting setting) throws IllegalArgumentException {
//noinspection unchecked
return settingValueToString(setting, setting.value);
}
public static String settingDefaultToString(Settings.Setting setting) throws IllegalArgumentException {
//noinspection unchecked
return settingValueToString(setting, setting.defaultValue);
}
public static String maybeCensor(int coord) {
2019-09-01 16:47:27 +00:00
if (BaritoneAPI.getSettings().censorCoordinates.value) {
return "<censored>";
}
return Integer.toString(coord);
}
2019-08-30 18:55:25 +00:00
public static String settingToString(Settings.Setting setting) throws IllegalStateException {
if (javaOnlySetting(setting)) {
return setting.getName();
2019-08-30 18:55:25 +00:00
}
return setting.getName() + " " + settingValueToString(setting);
2019-02-22 20:13:19 +00:00
}
/**
* This should always be the same as whether the setting can be parsed from or serialized to a string
*
* @param setting The Setting
* @return true if the setting can not be set or read by the user
*/
public static boolean javaOnlySetting(Settings.Setting setting) {
for (String name : JAVA_ONLY_SETTINGS) { // no JAVA_ONLY_SETTINGS.contains(...) because that would be case sensitive
if (setting.getName().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
2019-02-22 20:13:19 +00:00
public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException {
2018-10-09 01:05:08 +00:00
Settings.Setting setting = settings.byLowerName.get(settingName);
if (setting == null) {
throw new IllegalStateException("No setting by that name");
}
Class intendedType = setting.getValueClass();
2019-04-20 22:35:11 +00:00
ISettingParser ioMethod = Parser.getParser(setting.getType());
Object parsed = ioMethod.parse(new ParserContext(setting), settingValue);
2018-10-09 01:05:08 +00:00
if (!intendedType.isInstance(parsed)) {
throw new IllegalStateException(ioMethod + " parser returned incorrect type, expected " + intendedType + " got " + parsed + " which is " + parsed.getClass());
}
setting.value = parsed;
}
private interface ISettingParser<T> {
T parse(ParserContext context, String raw);
String toString(ParserContext context, T value);
boolean accepts(Type type);
}
private static class ParserContext {
private final Settings.Setting<?> setting;
2019-06-29 18:56:02 +00:00
private ParserContext(Settings.Setting<?> setting) {
this.setting = setting;
}
2019-06-29 18:56:02 +00:00
private Settings.Setting<?> getSetting() {
return this.setting;
}
}
private enum Parser implements ISettingParser {
2018-10-09 01:05:08 +00:00
DOUBLE(Double.class, Double::parseDouble),
BOOLEAN(Boolean.class, Boolean::parseBoolean),
INTEGER(Integer.class, Integer::parseInt),
FLOAT(Float.class, Float::parseFloat),
LONG(Long.class, Long::parseLong),
2019-08-30 18:55:25 +00:00
STRING(String.class, String::new),
2019-10-07 00:02:41 +00:00
DIRECTION(Direction.class, Direction::byName),
COLOR(
Color.class,
str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])),
color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue()
),
2019-05-06 21:01:01 +00:00
VEC3I(
2021-06-23 17:24:32 +00:00
Vec3i.class,
str -> new Vec3i(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])),
2019-05-06 21:01:01 +00:00
vec -> vec.getX() + "," + vec.getY() + "," + vec.getZ()
),
BLOCK(
Block.class,
2019-04-20 22:35:11 +00:00
str -> BlockUtils.stringToBlockRequired(str.trim()),
BlockUtils::blockToString
),
ITEM(
Item.class,
2021-06-23 17:24:32 +00:00
str -> Registry.ITEM.get(new ResourceLocation(str.trim())), // TODO this now returns AIR on failure instead of null, is that an issue?
2019-07-23 21:12:44 +00:00
item -> Registry.ITEM.getKey(item).toString()
),
LIST() {
@Override
public Object parse(ParserContext context, String raw) {
Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Parser parser = Parser.getParser(type);
return Stream.of(raw.split(","))
.map(s -> parser.parse(context, s))
.collect(Collectors.toList());
}
2018-10-09 01:05:08 +00:00
@Override
public String toString(ParserContext context, Object value) {
Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Parser parser = Parser.getParser(type);
2018-10-09 01:05:08 +00:00
return ((List<?>) value).stream()
.map(o -> parser.toString(context, o))
.collect(Collectors.joining(","));
}
2018-10-09 01:05:08 +00:00
@Override
public boolean accepts(Type type) {
return List.class.isAssignableFrom(TypeUtils.resolveBaseClass(type));
}
2021-01-16 23:16:34 +00:00
},
MAPPING() {
@Override
public Object parse(ParserContext context, String raw) {
Type keyType = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Type valueType = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[1];
Parser keyParser = Parser.getParser(keyType);
Parser valueParser = Parser.getParser(valueType);
return Stream.of(raw.split(",(?=[^,]*->)"))
.map(s -> s.split("->"))
.collect(Collectors.toMap(s -> keyParser.parse(context, s[0]), s -> valueParser.parse(context, s[1])));
}
@Override
public String toString(ParserContext context, Object value) {
Type keyType = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Type valueType = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[1];
Parser keyParser = Parser.getParser(keyType);
Parser valueParser = Parser.getParser(valueType);
2023-01-15 09:02:52 +00:00
return ((Map<?, ?>) value).entrySet().stream()
2021-01-16 23:16:34 +00:00
.map(o -> keyParser.toString(context, o.getKey()) + "->" + valueParser.toString(context, o.getValue()))
.collect(Collectors.joining(","));
}
@Override
public boolean accepts(Type type) {
return Map.class.isAssignableFrom(TypeUtils.resolveBaseClass(type));
}
};
2019-08-29 00:37:05 +00:00
private final Class<?> cla$$;
private final Function<String, Object> parser;
private final Function<Object, String> toString;
Parser() {
2019-08-29 00:37:05 +00:00
this.cla$$ = null;
this.parser = null;
this.toString = null;
}
2018-10-09 01:05:08 +00:00
2019-08-29 00:37:05 +00:00
<T> Parser(Class<T> cla$$, Function<String, T> parser) {
this(cla$$, parser, Object::toString);
2018-10-09 01:05:08 +00:00
}
2019-08-29 00:37:05 +00:00
<T> Parser(Class<T> cla$$, Function<String, T> parser, Function<T, String> toString) {
this.cla$$ = cla$$;
2018-10-09 01:05:08 +00:00
this.parser = parser::apply;
this.toString = x -> toString.apply((T) x);
}
@Override
public Object parse(ParserContext context, String raw) {
2019-05-01 19:22:47 +00:00
Object parsed = this.parser.apply(raw);
Objects.requireNonNull(parsed);
return parsed;
}
@Override
public String toString(ParserContext context, Object value) {
return this.toString.apply(value);
}
@Override
public boolean accepts(Type type) {
2019-08-29 00:37:05 +00:00
return type instanceof Class && this.cla$$.isAssignableFrom((Class) type);
}
public static Parser getParser(Type type) {
return Stream.of(values())
.filter(parser -> parser.accepts(type))
.findFirst().orElse(null);
2018-10-09 01:05:08 +00:00
}
}
}