Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove WorldEdit hard-dependency #212

Merged
merged 13 commits into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.slf4j.LoggerFactory;
import rip.hippo.inject.Doctor;
import rip.hippo.inject.Injector;
import tools.redstone.redstonetools.utils.DependencyLookup;
import tools.redstone.redstonetools.utils.ReflectionUtils;

public class RedstoneToolsClient implements ClientModInitializer {
Expand All @@ -23,8 +24,12 @@ public void onInitializeClient() {

// Register features
ReflectionUtils.getFeatures().forEach(feature -> {
LOGGER.trace("Registering feature {}", feature);
LOGGER.trace("Registering feature {}", feature.getClass().getName());

if (feature.requiresWorldEdit() && !DependencyLookup.WORLDEDIT_PRESENT) {
LOGGER.warn("Feature {} requires WorldEdit, but WorldEdit is not loaded. Skipping registration.", feature.getName());
return;
}
feature.register();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import net.fabricmc.fabric.api.gamerule.v1.GameRuleFactory;
import net.fabricmc.fabric.api.gamerule.v1.GameRuleRegistry;
import net.minecraft.world.GameRules;
import tools.redstone.redstonetools.utils.DependencyLookup;


public class RedstoneToolsGameRules {
Expand All @@ -14,6 +15,9 @@ private RedstoneToolsGameRules() {

public static void register() {
DO_CONTAINER_DROPS = GameRuleRegistry.register("doContainerDrops", GameRules.Category.DROPS, GameRuleFactory.createBooleanRule(true));
DO_BLOCK_UPDATES_AFTER_EDIT = GameRuleRegistry.register("doBlockUpdatesAfterEdit", GameRules.Category.UPDATES, GameRuleFactory.createBooleanRule(false));

if (DependencyLookup.WORLDEDIT_PRESENT) {
DO_BLOCK_UPDATES_AFTER_EDIT = GameRuleRegistry.register("doBlockUpdatesAfterEdit", GameRules.Category.UPDATES, GameRuleFactory.createBooleanRule(false));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ public String getCommand() {
return feature.command();
}

public boolean requiresWorldEdit() {
return feature.worldedit();
}

/**
* Register this feature.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@
String name();
String description();
String command();
boolean worldedit() default false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import static tools.redstone.redstonetools.features.arguments.serializers.NumberBaseSerializer.numberBase;

@AutoService(AbstractFeature.class)
@Feature(name = "Binary Block Read", description = "Interprets your WorldEdit selection as a binary number.", command = "/read")
@Feature(name = "Binary Block Read", description = "Interprets your WorldEdit selection as a binary number.", command = "/read", worldedit = true)
public class BinaryBlockReadFeature extends CommandFeature {
private static final BlockStateArgument LIT_LAMP_ARG = new BlockStateArgument(
Blocks.REDSTONE_LAMP.getDefaultState().with(RedstoneLampBlock.LIT, true),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import static tools.redstone.redstonetools.features.arguments.serializers.BlockColorSerializer.blockColor;

@AutoService(AbstractFeature.class)
@Feature(name = "Color Code", description = "Color codes all color-able blocks in your WorldEdit selection.", command = "/colorcode")
@Feature(name = "Color Code", description = "Color codes all color-able blocks in your WorldEdit selection.", command = "/colorcode", worldedit = true)
public class ColorCodeFeature extends CommandFeature {
public static final Argument<BlockColor> color = Argument
.ofType(blockColor());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import java.util.List;

@AutoService(AbstractFeature.class)
@Feature(command = "/minsel", description = "Removes all air-only layers from a selection", name = "Minimize Selection")
@Feature(command = "/minsel", description = "Removes all air-only layers from a selection", name = "Minimize Selection", worldedit = true)
public class MinSelectionFeature extends CommandFeature {

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import static tools.redstone.redstonetools.utils.DirectionUtils.matchDirection;

@AutoService(AbstractFeature.class)
@Feature(name = "RStack", description = "Stacks with custom distance", command = "/rstack")
@Feature(name = "RStack", description = "Stacks with custom distance", command = "/rstack", worldedit = true)
public class RStackFeature extends CommandFeature {
public static final Argument<Integer> count = Argument
.ofType(integer())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package tools.redstone.redstonetools.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DependencyLookup {
private static final Logger LOGGER =
LoggerFactory.getLogger(DependencyLookup.class);
public static final boolean WORLDEDIT_PRESENT =
require("com.sk89q.worldedit.WorldEdit");

private static boolean require(String... classNames) {
for (String className : classNames) {
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
return false;
} catch (Throwable t) {
LOGGER.warn("Unexpected error while checking for dependency {}", className, t);
return false;
}
}
return true;
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
package tools.redstone.redstonetools.utils;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import rip.hippo.inject.DoctorModule;
import tools.redstone.redstonetools.features.AbstractFeature;
import tools.redstone.redstonetools.features.Feature;
import tools.redstone.redstonetools.features.arguments.Argument;

import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

public class ReflectionUtils {
private static final ServiceLoader<DoctorModule> modulesLoader =
ServiceLoader.load(DoctorModule.class);
private static final ServiceLoader<AbstractFeature> featuresLoader =
ServiceLoader.load(AbstractFeature.class);
private static final Logger LOGGER = LogManager.getLogger();
private static DoctorModule[] modules;
private static Set<? extends AbstractFeature> features;

Expand All @@ -26,22 +26,65 @@ private ReflectionUtils() {

public static DoctorModule[] getModules() {
if (modules == null) {
modules = modulesLoader.stream()
.map(ServiceLoader.Provider::get)
.toArray(DoctorModule[]::new);
try {
modules = serviceLoad(DoctorModule.class)
.toArray(DoctorModule[]::new);
} catch (IOException e) {
throw new RuntimeException("Failed to load modules", e);
}
}
return modules;
}

public static Set<? extends AbstractFeature> getFeatures() {
if (features == null) {
features = featuresLoader.stream()
.map(ServiceLoader.Provider::get)
.collect(Collectors.toSet());
try {
features = serviceLoad(AbstractFeature.class);
} catch (IOException e) {
throw new RuntimeException("Failed to load features", e);
}
}
return features;
}

private static <T> Set<? extends T> serviceLoad(Class<T> clazz) throws IOException {
ClassLoader cl = ReflectionUtils.class.getClassLoader();
Enumeration<URL> serviceFiles = cl.getResources("META-INF/services/" + clazz.getName());
Set<String> classNames = new HashSet<>();
while (serviceFiles.hasMoreElements()) {
URL serviceFile = serviceFiles.nextElement();
try (var reader = serviceFile.openStream()) {
classNames.addAll(IOUtils.readLines(reader, "UTF-8"));
}
}
return classNames.stream()
.filter(it -> !it.isEmpty() && !it.isBlank())
.map(ReflectionUtils::loadClass)
.filter(Objects::nonNull)
.filter(clazz::isAssignableFrom)
.map(it -> {
try {
return it.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Failed to instantiate " + it, e);
}
})
.map(clazz::cast)
.collect(Collectors.toSet());
}

@SuppressWarnings("unchecked")
private static <T> @Nullable Class<? extends T> loadClass(String className) {
try {
return (Class<? extends T>) Class.forName(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Failed to load class " + className, e);
} catch (NoClassDefFoundError e) {
LOGGER.warn("Failed to load class {}, required {}", className, e.getMessage());
}
return null;
}

public static List<Argument<?>> getArguments(Class<? extends AbstractFeature> featureClass) {
return Arrays.stream(featureClass.getFields())
.filter(field -> Argument.class.isAssignableFrom(field.getType()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ public class WorldEditUtils {
*/
public static void forEachBlockInRegion(Region region,
Consumer<BlockVector3> consumer) {
if (!DependencyLookup.WORLDEDIT_PRESENT) {
throw new IllegalStateException("WorldEdit is not loaded.");
}

CuboidRegion bb = region.getBoundingBox();
BlockVector3 min = bb.getMinimumPoint();
BlockVector3 max = bb.getMaximumPoint();
Expand All @@ -44,6 +48,10 @@ public static void forEachBlockInRegion(Region region,
}

public static Either<Region, Feedback> getSelection(ServerPlayerEntity player) {
if (!DependencyLookup.WORLDEDIT_PRESENT) {
throw new IllegalStateException("WorldEdit is not loaded.");
}

var actor = FabricAdapter.adaptPlayer(player);

var localSession = WorldEdit.getInstance()
Expand Down
8 changes: 5 additions & 3 deletions src/main/resources/fabric.mod.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@
],

"depends": {
"fabricloader": ">=0.14.6",
"fabricloader": ">=0.13.0",
"fabric": "*",
"minecraft": "~1.18.2",
"java": ">=17",
"worldedit": "7.2.10"
"java": ">=17"
},
"recommends": {
"worldedit": "*"
}
}