From b7c0f348e87d048d72ec19a8edd1199e554972e7 Mon Sep 17 00:00:00 2001 From: Chicken Bones Date: Wed, 24 Jul 2013 21:41:47 +1000 Subject: [PATCH] Added dependancy loader, versions and mcmod.info --- MANIFEST.MF | 2 + codechicken/core/launch/DepLoader.java | 596 ++++++++++++++++++ .../microblock/handler/ModContainer.scala | 2 +- .../multipart/handler/ModContainer.scala | 2 +- .../minecraft/MinecraftMultipartMod.java | 3 +- dependancies.info | 6 + mcmod.info | 29 + mcversion.txt | 1 + version.txt | 1 + 9 files changed, 638 insertions(+), 4 deletions(-) create mode 100644 MANIFEST.MF create mode 100644 codechicken/core/launch/DepLoader.java create mode 100644 dependancies.info create mode 100644 mcmod.info create mode 100644 mcversion.txt create mode 100644 version.txt diff --git a/MANIFEST.MF b/MANIFEST.MF new file mode 100644 index 0000000..4b6e9b3 --- /dev/null +++ b/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +FMLCorePlugin: codechicken.core.launch.DepLoader diff --git a/codechicken/core/launch/DepLoader.java b/codechicken/core/launch/DepLoader.java new file mode 100644 index 0000000..314b853 --- /dev/null +++ b/codechicken/core/launch/DepLoader.java @@ -0,0 +1,596 @@ +package codechicken.core.launch; + +import java.awt.Dimension; +import java.awt.Dialog.ModalityType; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.InterruptedIOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import javax.swing.Box; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JProgressBar; +import javax.swing.WindowConstants; + +import argo.jdom.JdomParser; +import argo.jdom.JsonNode; +import argo.jdom.JsonRootNode; +import argo.jdom.JsonStringNode; +import argo.saj.InvalidSyntaxException; + +import net.minecraft.launchwrapper.LaunchClassLoader; + +import cpw.mods.fml.common.versioning.ComparableVersion; +import cpw.mods.fml.relauncher.FMLLaunchHandler; +import cpw.mods.fml.relauncher.IFMLCallHook; +import cpw.mods.fml.relauncher.IFMLLoadingPlugin; + +/** + * For autodownloading stuff. + * This is really unoriginal, mostly ripped off FML, credits to cpw. + */ +public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook +{ + private static ByteBuffer downloadBuffer = ByteBuffer.allocateDirect(1 << 23); + private static final String owner = "CodeChickenCore"; + private static DepLoadInst inst; + + public interface IDownloadDisplay + { + void resetProgress(int sizeGuess); + + void setPokeThread(Thread currentThread); + + void updateProgress(int fullLength); + + boolean shouldStopIt(); + + void updateProgressString(String string, Object ... data); + + Object makeDialog(); + + void makeHeadless(); + } + + @SuppressWarnings("serial") + public static class Downloader extends JOptionPane implements IDownloadDisplay + { + private JDialog container; + private JLabel currentActivity; + private JProgressBar progress; + boolean stopIt; + Thread pokeThread; + + private Box makeProgressPanel() + { + Box box = Box.createVerticalBox(); + box.add(Box.createRigidArea(new Dimension(0,10))); + JLabel welcomeLabel = new JLabel(""+owner+" is setting up your minecraft environment"); + box.add(welcomeLabel); + welcomeLabel.setAlignmentY(LEFT_ALIGNMENT); + welcomeLabel = new JLabel("Please wait, "+owner+" has some tasks to do before you can play"); + welcomeLabel.setAlignmentY(LEFT_ALIGNMENT); + box.add(welcomeLabel); + box.add(Box.createRigidArea(new Dimension(0,10))); + currentActivity = new JLabel("Currently doing ..."); + box.add(currentActivity); + box.add(Box.createRigidArea(new Dimension(0,10))); + progress = new JProgressBar(0, 100); + progress.setStringPainted(true); + box.add(progress); + box.add(Box.createRigidArea(new Dimension(0,30))); + return box; + } + + @Override + public JDialog makeDialog() + { + setMessageType(JOptionPane.INFORMATION_MESSAGE); + setMessage(makeProgressPanel()); + setOptions(new Object[] { "Stop" }); + addPropertyChangeListener(new PropertyChangeListener() + { + @Override + public void propertyChange(PropertyChangeEvent evt) + { + if (evt.getSource() == Downloader.this && evt.getPropertyName()==VALUE_PROPERTY) + { + requestClose("This will stop minecraft from launching\nAre you sure you want to do this?"); + } + } + }); + container = new JDialog(null, "Hello", ModalityType.MODELESS); + container.setResizable(false); + container.setLocationRelativeTo(null); + container.add(this); + this.updateUI(); + container.pack(); + container.setMinimumSize(container.getPreferredSize()); + container.setVisible(true); + container.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + container.addWindowListener(new WindowAdapter() + { + @Override + public void windowClosing(WindowEvent e) + { + requestClose("Closing this window will stop minecraft from launching\nAre you sure you wish to do this?"); + } + }); + return container; + } + + protected void requestClose(String message) + { + int shouldClose = JOptionPane.showConfirmDialog(container, message, "Are you sure you want to stop?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); + if (shouldClose == JOptionPane.YES_OPTION) + { + container.dispose(); + } + stopIt = true; + if (pokeThread != null) + { + pokeThread.interrupt(); + } + } + + @Override + public void updateProgressString(String progressUpdate, Object... data) + { + //FMLLog.finest(progressUpdate, data); + if (currentActivity!=null) + { + currentActivity.setText(String.format(progressUpdate,data)); + } + } + + @Override + public void resetProgress(int sizeGuess) + { + if (progress!=null) + { + progress.getModel().setRangeProperties(0, 0, 0, sizeGuess, false); + } + } + + @Override + public void updateProgress(int fullLength) + { + if (progress!=null) + { + progress.getModel().setValue(fullLength); + } + } + + @Override + public void makeHeadless() + { + container = null; + progress = null; + currentActivity = null; + } + + @Override + public void setPokeThread(Thread currentThread) + { + this.pokeThread = currentThread; + } + + @Override + public boolean shouldStopIt() + { + return stopIt; + } + } + + public static class DummyDownloader implements IDownloadDisplay + { + @Override + public void resetProgress(int sizeGuess) + { + } + + @Override + public void setPokeThread(Thread currentThread) + { + } + + @Override + public void updateProgress(int fullLength) + { + } + + @Override + public boolean shouldStopIt() + { + return false; + } + + @Override + public void updateProgressString(String string, Object... data) + { + } + + @Override + public Object makeDialog() + { + return null; + } + + @Override + public void makeHeadless() + { + } + } + + public class Dependancy + { + public String url; + public String[] filesplit; + public ComparableVersion version; + + public Dependancy(String url, String[] filesplit) + { + this.url = url; + this.filesplit = filesplit; + version = new ComparableVersion(filesplit[1]); + } + + public String getName() + { + return filesplit[0]; + } + + public String fileName() + { + return filesplit[0]+filesplit[1]+filesplit[2]; + } + } + + public class DepLoadInst + { + private File modsDir; + private IDownloadDisplay downloadMonitor; + private JDialog popupWindow; + + private Map dependancies = new HashMap(); + + public DepLoadInst() + { + modsDir = new File(mcDir, "mods"); + } + + public void load(Dependancy dep) + { + downloadMonitor = FMLLaunchHandler.side().isClient() ? new Downloader() : new DummyDownloader(); + + try + { + String existing = checkExisting(dep.filesplit); + if(existing == null)//download dep + { + download(dep); + existing = dep.fileName(); + } + addClasspath(existing); + } + finally + { + if (popupWindow != null) + { + popupWindow.setVisible(false); + popupWindow.dispose(); + } + } + } + + private void addClasspath(String name) + { + try + { + ((LaunchClassLoader)DepLoader.class.getClassLoader()).addURL(new File(modsDir, name).toURI().toURL()); + } + catch(MalformedURLException e) + { + throw new RuntimeException(e); + } + } + + private void download(Dependancy dep) + { + popupWindow = (JDialog) downloadMonitor.makeDialog(); + File libFile = new File(modsDir, dep.fileName()); + try + { + URL libDownload = new URL(dep.url+'/'+dep.fileName()); + downloadMonitor.updateProgressString("Downloading file %s", libDownload.toString()); + System.out.format("Downloading file %s\n", libDownload.toString()); + URLConnection connection = libDownload.openConnection(); + connection.setConnectTimeout(5000); + connection.setReadTimeout(5000); + connection.setRequestProperty("User-Agent", ""+owner+" Downloader"); + int sizeGuess = connection.getContentLength(); + download(connection.getInputStream(), sizeGuess, libFile); + downloadMonitor.updateProgressString("Download complete"); + System.out.println("Download complete"); + } + catch (Exception e) + { + if (downloadMonitor.shouldStopIt()) + { + System.err.println("You have stopped the downloading operation before it could complete"); + return; + } + if (e instanceof RuntimeException) throw (RuntimeException)e; + System.err.format("There was a problem downloading the file %s automatically. Perhaps you " + + "have an environment without internet access. You will need to download " + + "the file manually or restart and let it try again\n", libFile.getName()); + libFile.delete(); + throw new RuntimeException("A download error occured", e); + } + } + + private void download(InputStream is, int sizeGuess, File target) + { + if (sizeGuess > downloadBuffer.capacity()) + { + throw new RuntimeException(String.format("The file %s is too large to be downloaded by "+owner+" - the coremod is invalid", target.getName())); + } + downloadBuffer.clear(); + + int bytesRead, fullLength = 0; + + downloadMonitor.resetProgress(sizeGuess); + try + { + downloadMonitor.setPokeThread(Thread.currentThread()); + byte[] smallBuffer = new byte[1024]; + while ((bytesRead = is.read(smallBuffer)) >= 0) { + downloadBuffer.put(smallBuffer, 0, bytesRead); + fullLength += bytesRead; + if (downloadMonitor.shouldStopIt()) + { + break; + } + downloadMonitor.updateProgress(fullLength); + } + is.close(); + downloadMonitor.setPokeThread(null); + downloadBuffer.limit(fullLength); + downloadBuffer.position(0); + } + catch (InterruptedIOException e) + { + // We were interrupted by the stop button. We're stopping now.. clear interruption flag. + Thread.interrupted(); + return; + } + catch (IOException e) + { + throw new RuntimeException(e); + } + + try + { + /*String cksum = generateChecksum(downloadBuffer); + if (cksum.equals(validationHash)) + {*/ + if(!target.exists()) + target.createNewFile(); + + + downloadBuffer.position(0); + FileOutputStream fos = new FileOutputStream(target); + fos.getChannel().write(downloadBuffer); + fos.close(); + /*} + else + { + throw new RuntimeException(String.format("The downloaded file %s has an invalid checksum %s (expecting %s). The download did not succeed correctly and the file has been deleted. Please try launching again.", target.getName(), cksum, validationHash)); + }*/ + } + catch (Exception e) + { + if (e instanceof RuntimeException) throw (RuntimeException)e; + throw new RuntimeException(e); + } + } + + private String checkExisting(String[] dependancy) + { + for(File f : modsDir.listFiles()) + { + String[] split = splitFileName(f.getName()); + if(split == null || !split[0].equals(dependancy[0])) + continue; + + ComparableVersion found = new ComparableVersion(split[1]); + ComparableVersion requested = new ComparableVersion(dependancy[1]); + + int cmp = found.compareTo(requested); + if(cmp < 0) + { + System.out.println("Deleted old version "+f.getName()); + f.delete(); + return null; + } + if(cmp > 0) + { + System.err.println("Warning: version of "+dependancy[0]+", "+split[1]+" is newer than request "+dependancy[1]); + return f.getName(); + } + return f.getName();//found dependancy + } + return null; + } + + public void load() + { + scanDepInfos(); + loadDeps(); + } + + private void loadDeps() + { + for(Dependancy dep : dependancies.values()) + load(dep); + } + + private void scanDepInfos() + { + File modsDir = new File(mcDir, "mods"); + for(File file : modsDir.listFiles()) + { + if(!file.getName().endsWith(".jar") && !file.getName().endsWith(".zip")) + continue; + + try + { + ZipFile zip = new ZipFile(file); + ZipEntry e = zip.getEntry("dependancies.info"); + if(e != null) + loadJSon(zip.getInputStream(e)); + zip.close(); + } + catch(Exception e) + { + throw new RuntimeException("Failed to load dependancies.info from "+file.getName()+" as JSON", e); + } + } + } + + private void loadJSon(InputStream input) throws IOException, InvalidSyntaxException + { + InputStreamReader reader = new InputStreamReader(input); + JsonRootNode root = new JdomParser().parse(reader); + if(root.hasElements()) + loadJSonArr(root); + else + loadJson(root); + reader.close(); + } + + private void loadJSonArr(JsonRootNode root) throws IOException + { + for(JsonNode node : root.getElements()) + loadJson(node); + } + + private void loadJson(JsonNode node) throws IOException + { + boolean obfuscated = ((LaunchClassLoader)DepLoader.class.getClassLoader()) + .getClassBytes("net.minecraft.world.World") == null; + + String testClass = node.getStringValue("class"); + if(DepLoader.class.getResource("/"+testClass.replace('.', '/')+".class") != null) + return; + + String repo = node.getStringValue("repo"); + String file = node.getStringValue("file"); + if(!obfuscated && node.isNode("dev")) + file = node.getStringValue("dev"); + + List reserved = Arrays.asList("repo", "file", "class", "dev"); + for(Entry e : node.getFields().entrySet()) + { + String s = e.getKey().getText(); + if(!e.getValue().hasText() || reserved.contains(s)) + continue; + + file = file.replaceAll("@"+s.toUpperCase()+"@", e.getValue().getText()); + } + + String[] split = splitFileName(file); + if(split == null) + throw new RuntimeException("Invalid filename format for dependancy: "+file); + + addDep(new Dependancy(repo, split)); + } + + private void addDep(Dependancy dep) + { + Dependancy old = dependancies.get(dep.getName()); + if(old == null || dep.version.compareTo(old.version) > 0) + dependancies.put(dep.getName(), dep); + } + } + + public static void load(File mcDir) + { + DepLoader inst = new DepLoader(); + inst.mcDir = mcDir; + inst.call(); + } + + private static String[] splitFileName(String filename) + { + Pattern p = Pattern.compile("(.+?)([\\d\\.\\w]+)(\\.[^\\d]+)"); + Matcher m = p.matcher(filename); + if(!m.matches()) + return null; + + return new String[]{m.group(1), m.group(2), m.group(3)}; + } + + @Override + public String[] getASMTransformerClass() + { + return null; + } + + @Override + public String getModContainerClass() + { + return null; + } + + @Override + public String getSetupClass() + { + return getClass().getName(); + } + + private File mcDir; + @Override + public void injectData(Map data) + { + mcDir = (File) data.get("mcLocation"); + } + + @Override + public Void call() + { + if(inst == null) + { + inst = new DepLoadInst(); + inst.load(); + } + return null; + } + + @Override + public String[] getLibraryRequestClass() + { + return null; + } +} diff --git a/codechicken/microblock/handler/ModContainer.scala b/codechicken/microblock/handler/ModContainer.scala index 644d2e2..62ea00d 100644 --- a/codechicken/microblock/handler/ModContainer.scala +++ b/codechicken/microblock/handler/ModContainer.scala @@ -15,7 +15,7 @@ import codechicken.microblock.MicroMaterialRegistry import codechicken.microblock.DefaultContent import cpw.mods.fml.common.event.FMLPostInitializationEvent -@Mod(name="Microblocks", version="b.0.0.0", useMetadata = false, modid = "ForgeMicroblock", acceptedMinecraftVersions = "[1.6.2]", +@Mod(modid = "ForgeMicroblock", acceptedMinecraftVersions = "[1.6.2]", dependencies="required-after:ForgeMultipart", modLanguage="scala") object MicroblockMod { diff --git a/codechicken/multipart/handler/ModContainer.scala b/codechicken/multipart/handler/ModContainer.scala index 8cf6c91..d5a680b 100644 --- a/codechicken/multipart/handler/ModContainer.scala +++ b/codechicken/multipart/handler/ModContainer.scala @@ -12,7 +12,7 @@ import codechicken.multipart.MultiPartRegistry import cpw.mods.fml.relauncher.SideOnly import codechicken.lib.packet.PacketCustom.CustomTinyPacketHandler -@Mod(name="Multipart API", version="b.0.0.0", useMetadata = false, modid = "ForgeMultipart", acceptedMinecraftVersions = "[1.6.2]", +@Mod(modid = "ForgeMultipart", acceptedMinecraftVersions = "[1.6.2]", modLanguage="scala") @NetworkMod(clientSideRequired = true, serverSideRequired = true, tinyPacketHandler=classOf[CustomTinyPacketHandler]) object MultipartMod diff --git a/codechicken/multipart/minecraft/MinecraftMultipartMod.java b/codechicken/multipart/minecraft/MinecraftMultipartMod.java index b7c8af9..3329e0e 100644 --- a/codechicken/multipart/minecraft/MinecraftMultipartMod.java +++ b/codechicken/multipart/minecraft/MinecraftMultipartMod.java @@ -8,9 +8,8 @@ import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; -import cpw.mods.fml.relauncher.Side; -@Mod(name="Minecraft Multipart", version="1.0.0.0", useMetadata = false, modid = "McMultipart", acceptedMinecraftVersions="[1.6.2]") +@Mod(modid = "McMultipart", acceptedMinecraftVersions="[1.6.2]") @NetworkMod(clientSideRequired = true, serverSideRequired = true, tinyPacketHandler=CustomTinyPacketHandler.class) public class MinecraftMultipartMod { diff --git a/dependancies.info b/dependancies.info new file mode 100644 index 0000000..d9be58a --- /dev/null +++ b/dependancies.info @@ -0,0 +1,6 @@ +{ + "repo": "http://files.minecraftforge.net/CodeChickenLib/", + "file": "CodeChickenLib-universal-@MCVERSION@-@VERSION@.jar", + "dev": "CodeChickenLib-dev-@MCVERSION@-@VERSION@.jar", + "class": "codechicken.lib.asm.ASMHelper" +} \ No newline at end of file diff --git a/mcmod.info b/mcmod.info new file mode 100644 index 0000000..1e237f5 --- /dev/null +++ b/mcmod.info @@ -0,0 +1,29 @@ +[ +{ + "modid": "ForgeMultipart", + "name": "Forge Multipart", + "description": "Open source library for facilitation of multiple functional parts in the one block space.", + "version": "@VERSION@", + "mcversion": "@MCVERSION@", + "url": "https://github.com/Chicken-Bones/ForgeMultipart", + "authors": [ "ChickenBones" ] +}, +{ + "modid": "McMultipart", + "name": "Minecraft Multipart Plugin", + "description": "Provides multipart versions of some vanilla blocks like torches and buttons.", + "version": "@VERSION@", + "mcversion": "@MCVERSION@", + "url": "https://github.com/Chicken-Bones/ForgeMultipart", + "authors": [ "ChickenBones" ] +}, +{ + "modid": "ForgeMicroblock", + "name": "Forge Microblocks", + "description": "Microblocks for Forge Multipart.", + "version": "@VERSION@", + "mcversion": "@MCVERSION@", + "url": "https://github.com/Chicken-Bones/ForgeMultipart", + "authors": [ "ChickenBones" ] +} +] \ No newline at end of file diff --git a/mcversion.txt b/mcversion.txt new file mode 100644 index 0000000..308b6fa --- /dev/null +++ b/mcversion.txt @@ -0,0 +1 @@ +1.6.2 \ No newline at end of file diff --git a/version.txt b/version.txt new file mode 100644 index 0000000..afaf360 --- /dev/null +++ b/version.txt @@ -0,0 +1 @@ +1.0.0 \ No newline at end of file