Skip to content

Commit

Permalink
Merge branch 'java-17-compat' into 1.13.2-fabricated-v2
Browse files Browse the repository at this point in the history
  • Loading branch information
thecatcore committed Jun 4, 2023
2 parents d4cd5af + 9e80d36 commit b6e75ce
Show file tree
Hide file tree
Showing 4 changed files with 148 additions and 70 deletions.
119 changes: 72 additions & 47 deletions src/main/java/org/dimdev/rift/resources/ModPack.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package org.dimdev.rift.resources;

import com.google.common.collect.Lists;
import net.fabricmc.loader.impl.util.FileSystemUtil;
import net.fabricmc.loader.impl.util.UrlUtil;
import net.minecraft.resources.AbstractResourcePack;
import net.minecraft.resources.ResourcePackType;
import net.minecraft.util.ResourceLocation;
Expand All @@ -19,28 +21,63 @@
import java.util.function.Predicate;

public class ModPack extends AbstractResourcePack {
private final String root;
private final Path root;
private final String name;
private Logger LOGGER = LogManager.getLogger();
private final String separator;

public ModPack(String name, URL root) {
this(name, Objects.requireNonNull(getRootAsPath(root)));
}

public ModPack(String name, Path root) {
super(null);
this.name = name;
this.root = root.toString();
this.root = root;
this.separator = root.getFileSystem().getSeparator();
}

@Override
protected InputStream getInputStream(String path) throws IOException {
return new URL(root + path).openStream();
private static Path getRootAsPath(URL root) {
try {
FileSystemUtil.FileSystemDelegate delegate = FileSystemUtil.getJarFileSystem(root.toURI(), false);
FileSystem fs = delegate.get();

if (fs == null) {
throw new RuntimeException("Could not open JAR file " + root + " for NIO reading!");
}

return fs.getRootDirectories().iterator().next();
} catch (Throwable e) {
return null;
}
}

private Path getPath(String filename) {
Path childPath = root.resolve(filename.replace("/", separator)).toAbsolutePath().normalize();

if (childPath.startsWith(root) && Files.exists(childPath)) {
return childPath;
} else {
return null;
}
}

@Override
protected boolean resourceExists(String path) {
try (InputStream ignored = getInputStream(path)) {
return true;
} catch (IOException e) {
return false;
protected InputStream getInputStream(String filename) throws IOException {
Path path = getPath(filename);

if (path != null && Files.isRegularFile(path)) {
return Files.newInputStream(path);
}

// ReloadableResourceManagerImpl gets away with FileNotFoundException.
throw new FileNotFoundException("\"" + filename + "\" in Rift mod \"" + this.name + "\"");
}

@Override
protected boolean resourceExists(String filename) {
Path path = getPath(filename);
return path != null && Files.isRegularFile(path);
}

@Override
Expand All @@ -54,22 +91,15 @@ public Collection<ResourceLocation> getAllResourceLocations(ResourcePackType typ

public Collection<ResourceLocation> getAllResourceLocations(ResourcePackType type, ResourceLocation location, int maxDepth, Predicate<String> filter) {
Set<ResourceLocation> resourceLocations = new HashSet<>();
String path = String.format("%s/%s/%s", type.getDirectoryName(), location.getNamespace(), location.getPath());

try {
String path = String.format("%s/%s/%s", type.getDirectoryName(), location.getNamespace(), location.getPath());
URI url = new URL(root + path).toURI();
if ("file".equals(url.getScheme())) {
resourceLocations.addAll(getAllResourceLocations(maxDepth, location, Paths.get(url), filter));
} else if ("jar".equals(url.getScheme())) {
try (FileSystem fileSystem = FileSystems.newFileSystem(url, Collections.emptyMap())) {
resourceLocations.addAll(getAllResourceLocations(maxDepth, location, fileSystem.getPath(path), filter));
}
} else {
LOGGER.error("Unsupported scheme " + url + " trying to list mod resources");
Path url = getPath(path);
if (url != null && Files.exists(url)) {
resourceLocations.addAll(getAllResourceLocations(maxDepth, location, url, filter));
}
} catch (NoSuchFileException | FileNotFoundException ignored) {
} catch (IOException | URISyntaxException e) {
LOGGER.error("Couldn't get a list of all resources of '" + getName() + "'", e);
} catch (IOException e) {
LOGGER.error("Couldn't get a list of all resources of '" + getName() + "' of type " + path, e);
}

return resourceLocations;
Expand All @@ -81,7 +111,7 @@ private static Collection<ResourceLocation> getAllResourceLocations(int maxDepth

while (pathIterator.hasNext()) {
Path path = pathIterator.next();
if (!path.endsWith(".mcmeta") && Files.isRegularFile(path) && filter.test(path.getFileName().toString())) {
if (path != null && !path.endsWith(".mcmeta") && Files.isRegularFile(path) && filter.test(path.getFileName().toString())) {
resourceLocations.add(new ResourceLocation(rootLocation.getNamespace(), rootLocation.getPath() + "/" + rootPath.toAbsolutePath().relativize(path).toString().replaceAll("\\\\", "/")));
}
}
Expand All @@ -92,31 +122,26 @@ private static Collection<ResourceLocation> getAllResourceLocations(int maxDepth
@Override
public Set<String> getResourceNamespaces(ResourcePackType type) {
try {
URI uri = new URL(root + type.getDirectoryName() + "/").toURI();
if ("file".equals(uri.getScheme())) {
Set<String> namespaces = new HashSet<>();
File rootFile = new File(uri);
if (rootFile.isDirectory()) {
for (File file : rootFile.listFiles()) {
namespaces.add(file.getName());
}
}
return namespaces;
} else if ("jar".equals(uri.getScheme())) {
try (FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap());
DirectoryStream<Path> directoryStream = fileSystem.provider().newDirectoryStream(fileSystem.getPath(type.getDirectoryName()), x -> true)) {
Set<String> namespaces = new HashSet<>();
for (Path p : directoryStream) {
String fileName = p.getFileName().toString();
namespaces.add(fileName.substring(0, fileName.length() - 1));
}
return namespaces;
Path typePath = getPath(type.getDirectoryName());

if (typePath == null || !(Files.isDirectory(typePath))) {
return Collections.emptySet();
}

Set<String> namespaces = new HashSet<>();

try (DirectoryStream<Path> stream = Files.newDirectoryStream(typePath, Files::isDirectory)) {
for (Path path : stream) {
String s = path.getFileName().toString();
// s may contain trailing slashes, remove them
s = s.replace(separator, "");

namespaces.add(s);
}
} else {
LOGGER.error("Unsupported scheme " + uri + " trying to list mod resource namespaces");
}
} catch (NoSuchFileException | FileNotFoundException | NotDirectoryException ignored) {
} catch (IOException | URISyntaxException e) {

return namespaces;
} catch (IOException e) {
LOGGER.error("Couldn't get a list of resource namespaces of '" + getName() + "'", e);
}

Expand Down
30 changes: 24 additions & 6 deletions src/main/java/org/dimdev/rift/resources/ModPackFinder.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.dimdev.rift.resources;

import net.fabricmc.loader.impl.util.FileSystemUtil;
import net.minecraft.resources.IPackFinder;
import net.minecraft.resources.ResourcePackInfo;
import net.minecraft.resources.ResourcePackType;
Expand All @@ -10,6 +11,9 @@
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.Path;
import java.util.Map;

public class ModPackFinder implements IPackFinder {
Expand All @@ -22,14 +26,28 @@ public ModPackFinder(ResourcePackType type) {
@Override
public <T extends ResourcePackInfo> void addPackInfosToMap(Map<String, T> nameToPackMap, ResourcePackInfo.IFactory<T> packInfoFactory) {
for (ModInfo mod : RiftLoader.instance.getMods()) {
URL root = getRootUrl(mod);
if (mod.id.equals("rift")) continue;
try {
FileSystemUtil.FileSystemDelegate delegate = FileSystemUtil.getJarFileSystem(mod.source.toPath().toAbsolutePath().normalize(), false);
FileSystem fs = delegate.get();

try (ModPack pack = new ModPack(mod.name != null ? mod.name : mod.id, root)) {
PackMetadataSection meta = pack.getMetadata(PackMetadataSection.SERIALIZER);
if (meta != null && !pack.getResourceNamespaces(type).isEmpty()) {
nameToPackMap.put(mod.id, packInfoFactory.create(mod.id, type == ResourcePackType.field_14188, () -> pack, pack, meta, ResourcePackInfo.Priority.field_14280));
if (fs == null) {
throw new RuntimeException("Could not open JAR file " + mod.source + " for NIO reading!");
}
} catch (IOException ignored) {}

Path rootPath = fs.getRootDirectories().iterator().next();

try (ModPack pack = new ModPack(mod.name != null ? mod.name : mod.id, rootPath)) {
PackMetadataSection meta = pack.getMetadata(PackMetadataSection.SERIALIZER);
if (meta != null && !pack.getResourceNamespaces(type).isEmpty()) {
nameToPackMap.put(mod.id, packInfoFactory.create(mod.id, type == ResourcePackType.field_14188, () -> pack, pack, meta, ResourcePackInfo.Priority.field_14280));
}
} catch (IOException ignored) {
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (FileSystemAlreadyExistsException ignored) {
}
}
}

Expand Down
48 changes: 48 additions & 0 deletions src/main/java/org/dimdev/riftloader/ModInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,54 @@ public class ModInfo {
if (listener.side == null) listener.side = Side.BOTH;
return listener;
})
.registerTypeAdapter(ModInfo.class, (JsonDeserializer<ModInfo>) (json, type, context) -> {
ModInfo modInfo = new ModInfo();

if (!json.isJsonObject()) {
throw new JsonSyntaxException("ModInfo is not an Object!");
}

JsonObject object = json.getAsJsonObject();

if (object.has("id")) {
modInfo.id = object.get("id").getAsString();
} else {
throw new JsonSyntaxException("ModInfo with no id!");
}

if (object.has("name")) {
modInfo.name = object.get("name").getAsString();
} else {
modInfo.name = modInfo.id;
}

if (object.has("authors")) {
JsonElement authors = object.get("authors");
if (authors.isJsonArray()) {
JsonArray array = authors.getAsJsonArray();
for (JsonElement author : array) {
if (author.isJsonPrimitive()) {
modInfo.authors.add(author.getAsString());
}
}
} else if (authors.isJsonPrimitive()) {
modInfo.authors.add(authors.getAsString());
}
}

if (object.has("listeners")) {
JsonElement listeners = object.get("listeners");
if (listeners.isJsonArray()) {
JsonArray array = listeners.getAsJsonArray();

for (JsonElement listenerElement : array) {
modInfo.listeners.add(ModInfo.GSON.fromJson(listenerElement, Listener.class));
}
}
}

return modInfo;
})
.create();

public static class Listener {
Expand Down
21 changes: 4 additions & 17 deletions src/main/java/org/dimdev/utils/ReflectionUtils.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package org.dimdev.utils;

import net.fabricmc.loader.impl.launch.FabricLauncherBase;
import net.fabricmc.loader.impl.util.UrlUtil;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
Expand All @@ -10,18 +13,6 @@
import java.util.Arrays;

public class ReflectionUtils {
private static final MethodHandle addURLHandle;

static {
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
addURLHandle = MethodHandles.lookup().unreflect(method);
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}

public static <T> T makeEnumInstance(Class<T> enumClass, Object... constructorArgs) {
try {
Constructor<?> constructor = enumClass.getDeclaredConstructors()[0];
Expand Down Expand Up @@ -57,10 +48,6 @@ public static Method findMethod(Class<?> target, Class<?> returnType, Class<?>..
}

public static void addURLToClasspath(URL url) {
try {
addURLHandle.invoke(ClassLoader.getSystemClassLoader(), url);
} catch (Throwable t) {
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
FabricLauncherBase.getLauncher().addToClassPath(UrlUtil.asPath(url));
}
}

0 comments on commit b6e75ce

Please sign in to comment.