Refactored and reformatted code to use less static variables

This commit is contained in:
CrushedPixel
2015-04-23 14:09:54 +02:00
parent f22416be2c
commit 0003f040ed
109 changed files with 9037 additions and 10229 deletions

View File

@@ -1,69 +1,73 @@
package eu.crushedpixel.replaymod.utils;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.*;
import java.awt.image.BufferedImage;
public class ImageUtils {
public static BufferedImage scaleImage(BufferedImage img, Dimension d) {
img = scaleByHalf(img, d);
img = scaleExact(img, d);
return img;
}
public static BufferedImage scaleImage(BufferedImage img, Dimension d) {
img = scaleByHalf(img, d);
img = scaleExact(img, d);
return img;
}
private static BufferedImage scaleByHalf(BufferedImage img, Dimension d) {
int w = img.getWidth();
int h = img.getHeight();
float factor = getBinFactor(w, h, d);
private static BufferedImage scaleByHalf(BufferedImage img, Dimension d) {
int w = img.getWidth();
int h = img.getHeight();
float factor = getBinFactor(w, h, d);
// make new size
w *= factor;
h *= factor;
BufferedImage scaled = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaled.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.drawImage(img, 0, 0, w, h, null);
g.dispose();
return scaled;
}
// make new size
w *= factor;
h *= factor;
BufferedImage scaled = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaled.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.drawImage(img, 0, 0, w, h, null);
g.dispose();
return scaled;
}
private static BufferedImage scaleExact(BufferedImage img, Dimension d) {
float factor = getFactor(img.getWidth(), img.getHeight(), d);
private static BufferedImage scaleExact(BufferedImage img, Dimension d) {
float factor = getFactor(img.getWidth(), img.getHeight(), d);
// create the image
int w = (int) (img.getWidth() * factor);
int h = (int) (img.getHeight() * factor);
BufferedImage scaled = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
// create the image
int w = (int) (img.getWidth() * factor);
int h = (int) (img.getHeight() * factor);
BufferedImage scaled = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaled.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, w, h, null);
g.dispose();
return scaled;
}
Graphics2D g = scaled.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, w, h, null);
g.dispose();
return scaled;
}
static float getBinFactor(int width, int height, Dimension dim) {
float factor = 1;
float target = getFactor(width, height, dim);
if (target <= 1) { while (factor / 2 > target) { factor /= 2; }
} else { while (factor * 2 < target) { factor *= 2; } }
return factor;
}
static float getBinFactor(int width, int height, Dimension dim) {
float factor = 1;
float target = getFactor(width, height, dim);
if(target <= 1) {
while(factor / 2 > target) {
factor /= 2;
}
} else {
while(factor * 2 < target) {
factor *= 2;
}
}
return factor;
}
static float getFactor(int width, int height, Dimension dim) {
float sx = dim.width / (float) width;
float sy = dim.height / (float) height;
return Math.min(sx, sy);
}
static float getFactor(int width, int height, Dimension dim) {
float sx = dim.width / (float) width;
float sy = dim.height / (float) height;
return Math.min(sx, sy);
}
public static BufferedImage cropImage(BufferedImage src, Rectangle rect) {
return src.getSubimage(rect.x, rect.y, rect.width, rect.height);
}
public static BufferedImage cropImage(BufferedImage src, Rectangle rect) {
return src.getSubimage(rect.x, rect.y, rect.width, rect.height);
}
}

View File

@@ -1,32 +1,31 @@
package eu.crushedpixel.replaymod.utils;
import java.awt.Point;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import org.lwjgl.input.Mouse;
import java.awt.*;
public class MouseUtils {
private static final Minecraft mc = Minecraft.getMinecraft();
public static Point getMousePos() {
Point scaled = getScaledDimensions();
int width = (int)scaled.getX();
int height = (int)scaled.getY();
private static final Minecraft mc = Minecraft.getMinecraft();
final int mouseX = (Mouse.getX() * width / mc.displayWidth);
final int mouseY = (height - Mouse.getY() * height / mc.displayHeight);
return new Point(mouseX, mouseY);
}
public static Point getScaledDimensions() {
ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
final int width = sr.getScaledWidth();
final int heigth = sr.getScaledHeight();
return new Point(width, heigth);
}
public static Point getMousePos() {
Point scaled = getScaledDimensions();
int width = (int) scaled.getX();
int height = (int) scaled.getY();
final int mouseX = (Mouse.getX() * width / mc.displayWidth);
final int mouseY = (height - Mouse.getY() * height / mc.displayHeight);
return new Point(mouseX, mouseY);
}
public static Point getScaledDimensions() {
ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
final int width = sr.getScaledWidth();
final int heigth = sr.getScaledHeight();
return new Point(width, heigth);
}
}

View File

@@ -7,7 +7,6 @@ import eu.crushedpixel.replaymod.holders.PacketData;
import eu.crushedpixel.replaymod.recording.ConnectionEventHandler;
import eu.crushedpixel.replaymod.recording.PacketSerializer;
import eu.crushedpixel.replaymod.recording.ReplayMetaData;
import eu.crushedpixel.replaymod.replay.PacketDeserializer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.network.EnumConnectionState;
@@ -21,9 +20,6 @@ import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.FilenameUtils;
import java.io.*;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -34,329 +30,328 @@ import java.util.zip.ZipOutputStream;
@SuppressWarnings("resource") //Gets handled by finalizer
public class ReplayFileIO {
public static File getRenderFolder() {
File folder = new File(ReplayMod.replaySettings.getRenderPath());
folder.mkdirs();
return folder;
}
private static final PacketSerializer packetSerializer = new PacketSerializer(EnumPacketDirection.CLIENTBOUND);
private static final byte[] uniqueBytes = new byte[]{0, 1, 1, 2, 3, 5, 8};
private static File lastReplayFile = null;
private static boolean lastContainsJoinPacket = false;
public static File getReplayFolder() {
String path = ReplayMod.replaySettings.getRecordingPath();
File folder = new File(path);
folder.mkdirs();
return folder;
}
public static File getRenderFolder() {
File folder = new File(ReplayMod.replaySettings.getRenderPath());
folder.mkdirs();
return folder;
}
public static List<File> getAllReplayFiles() {
List<File> files = new ArrayList<File>();
File folder = getReplayFolder();
for(File file : folder.listFiles()) {
if(("."+FilenameUtils.getExtension(file.getAbsolutePath())).equals(
ConnectionEventHandler.ZIP_FILE_EXTENSION)) {
files.add(file);
}
}
return files;
}
public static File getReplayFolder() {
String path = ReplayMod.replaySettings.getRecordingPath();
File folder = new File(path);
folder.mkdirs();
return folder;
}
private static DataInputStream getMetaDataInputStream(File replayFile) throws IOException {
ZipFile archive = null;
public static List<File> getAllReplayFiles() {
List<File> files = new ArrayList<File>();
File folder = getReplayFolder();
for(File file : folder.listFiles()) {
if(("." + FilenameUtils.getExtension(file.getAbsolutePath())).equals(
ConnectionEventHandler.ZIP_FILE_EXTENSION)) {
files.add(file);
}
}
return files;
}
try {
archive = new ZipFile(replayFile);
ZipArchiveEntry tmcpr = archive.getEntry("metaData"+
ConnectionEventHandler.JSON_FILE_EXTENSION);
private static DataInputStream getMetaDataInputStream(File replayFile) throws IOException {
ZipFile archive = null;
return new DataInputStream(archive.getInputStream(tmcpr));
} catch(IOException e) {
throw e;
}
}
try {
archive = new ZipFile(replayFile);
ZipArchiveEntry tmcpr = archive.getEntry("metaData" +
ConnectionEventHandler.JSON_FILE_EXTENSION);
public static void writeReplayFile(File replayFile, File tempFile, ReplayMetaData metaData) throws IOException {
byte[] buffer = new byte[1024];
return new DataInputStream(archive.getInputStream(tmcpr));
} catch(IOException e) {
throw e;
}
}
if(!replayFile.exists()) {
replayFile.createNewFile();
}
public static void writeReplayFile(File replayFile, File tempFile, ReplayMetaData metaData) throws IOException {
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(replayFile);
ZipOutputStream zos = new ZipOutputStream(fos);
if(!replayFile.exists()) {
replayFile.createNewFile();
}
String json = new Gson().toJson(metaData);
FileOutputStream fos = new FileOutputStream(replayFile);
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("metaData.json"));
PrintWriter pw = new PrintWriter(zos);
pw.write(json);
pw.flush();
zos.closeEntry();
String json = new Gson().toJson(metaData);
zos.putNextEntry(new ZipEntry("recording"+ConnectionEventHandler.TEMP_FILE_EXTENSION));
FileInputStream fis = new FileInputStream(tempFile);
int len;
while((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.putNextEntry(new ZipEntry("metaData.json"));
PrintWriter pw = new PrintWriter(zos);
pw.write(json);
pw.flush();
zos.closeEntry();
fis.close();
zos.closeEntry();
zos.putNextEntry(new ZipEntry("recording" + ConnectionEventHandler.TEMP_FILE_EXTENSION));
FileInputStream fis = new FileInputStream(tempFile);
int len;
while((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.close();
}
fis.close();
zos.closeEntry();
private static Pair<Long, DataInputStream> getTempFileInputStream(File replayFile) throws Exception {
ZipFile archive = null;
zos.close();
}
try {
archive = new ZipFile(replayFile);
ZipArchiveEntry tmcpr = archive.getEntry("recording"+
ConnectionEventHandler.TEMP_FILE_EXTENSION);
long size = tmcpr.getSize();
private static Pair<Long, DataInputStream> getTempFileInputStream(File replayFile) throws Exception {
ZipFile archive = null;
return new Pair<Long, DataInputStream>(size, new DataInputStream(archive.getInputStream(tmcpr)));
} catch(Exception e) {
throw e;
}
}
try {
archive = new ZipFile(replayFile);
ZipArchiveEntry tmcpr = archive.getEntry("recording" +
ConnectionEventHandler.TEMP_FILE_EXTENSION);
long size = tmcpr.getSize();
public static ReplayMetaData getMetaData(File replayFile) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(getMetaDataInputStream(replayFile)));
String json = br.readLine();
return new Pair<Long, DataInputStream>(size, new DataInputStream(archive.getInputStream(tmcpr)));
} catch(Exception e) {
throw e;
}
}
return new Gson().fromJson(json, ReplayMetaData.class);
}
public static ReplayMetaData getMetaData(File replayFile) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(getMetaDataInputStream(replayFile)));
String json = br.readLine();
/**
* @param replayFile
* @return Whether the given Replay File contains a {@link S01PacketJoinGame}.
*/
public static boolean containsJoinPacket(File replayFile) {
DataInputStream dis = null;
if(replayFile == lastReplayFile) {
return lastContainsJoinPacket;
}
return new Gson().fromJson(json, ReplayMetaData.class);
}
lastReplayFile = replayFile;
lastContainsJoinPacket = false;
try {
Pair<Long, DataInputStream> pair = getTempFileInputStream(replayFile);
dis = pair.second();
PacketData pd = readPacketData(dis);
while(dis.available() > 0) {
Packet p = deserializePacket(pd.getByteArray());
if(p instanceof S01PacketJoinGame) {
lastContainsJoinPacket = true;
return lastContainsJoinPacket;
} if(p instanceof S08PacketPlayerPosLook) {
lastContainsJoinPacket = false;
return lastContainsJoinPacket;
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(dis != null) {
dis.close();
}
} catch(Exception e) {}
}
/**
* @param replayFile
* @return Whether the given Replay File contains a {@link S01PacketJoinGame}.
*/
public static boolean containsJoinPacket(File replayFile) {
DataInputStream dis = null;
if(replayFile == lastReplayFile) {
return lastContainsJoinPacket;
}
return false;
}
lastReplayFile = replayFile;
lastContainsJoinPacket = false;
try {
Pair<Long, DataInputStream> pair = getTempFileInputStream(replayFile);
dis = pair.second();
PacketData pd = readPacketData(dis);
while(dis.available() > 0) {
Packet p = deserializePacket(pd.getByteArray());
if(p instanceof S01PacketJoinGame) {
lastContainsJoinPacket = true;
return lastContainsJoinPacket;
}
if(p instanceof S08PacketPlayerPosLook) {
lastContainsJoinPacket = false;
return lastContainsJoinPacket;
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(dis != null) {
dis.close();
}
} catch(Exception e) {
}
}
public static PacketData readPacketData(DataInputStream dis) throws IOException {
int timestamp = dis.readInt();
int bytes = dis.readInt();
byte[] bb = new byte[bytes];
dis.readFully(bb);
return false;
}
return new PacketData(bb, timestamp);
}
public static PacketData readPacketData(DataInputStream dis) throws IOException {
int timestamp = dis.readInt();
int bytes = dis.readInt();
byte[] bb = new byte[bytes];
dis.readFully(bb);
public static Packet deserializePacket(byte[] bytes) throws InstantiationException, IllegalAccessException, IOException {
try {
ByteBuf bb = Unpooled.wrappedBuffer(bytes);
PacketBuffer pb = new PacketBuffer(bb);
return new PacketData(bb, timestamp);
}
int i = pb.readVarIntFromBuffer();
public static Packet deserializePacket(byte[] bytes) throws InstantiationException, IllegalAccessException, IOException {
try {
ByteBuf bb = Unpooled.wrappedBuffer(bytes);
PacketBuffer pb = new PacketBuffer(bb);
Packet p = EnumConnectionState.PLAY.getPacket(EnumPacketDirection.CLIENTBOUND, i);
p.readPacketData(pb);
int i = pb.readVarIntFromBuffer();
return p;
} catch(Exception e) {
return null;
}
}
Packet p = EnumConnectionState.PLAY.getPacket(EnumPacketDirection.CLIENTBOUND, i);
p.readPacketData(pb);
public static byte[] serializePacket(Packet packet) throws IOException {
ByteBuf bb = Unpooled.buffer();
packetSerializer.encode(EnumConnectionState.PLAY, packet, bb);
bb.readerIndex(0);
byte[] array = new byte[bb.readableBytes()];
bb.readBytes(array);
return p;
} catch(Exception e) {
return null;
}
}
bb.readerIndex(0);
public static byte[] serializePacket(Packet packet) throws IOException {
ByteBuf bb = Unpooled.buffer();
packetSerializer.encode(EnumConnectionState.PLAY, packet, bb);
bb.readerIndex(0);
byte[] array = new byte[bb.readableBytes()];
bb.readBytes(array);
return array;
}
bb.readerIndex(0);
public static void writePacket(PacketData pd, DataOutput out) throws IOException {
out.writeInt(pd.getTimestamp());
out.writeInt(pd.getByteArray().length);
out.write(pd.getByteArray());
}
return array;
}
public static int getWrittenByteSize(PacketData pd) {
return (2*4)+pd.getByteArray().length;
}
public static void writePacket(PacketData pd, DataOutput out) throws IOException {
out.writeInt(pd.getTimestamp());
out.writeInt(pd.getByteArray().length);
out.write(pd.getByteArray());
}
public static void writePackets(Collection<PacketData> p, DataOutput out) throws IOException {
for(PacketData pd : p) {
writePacket(pd, out);
}
}
public static int getWrittenByteSize(PacketData pd) {
return (2 * 4) + pd.getByteArray().length;
}
private static final PacketSerializer packetSerializer = new PacketSerializer(EnumPacketDirection.CLIENTBOUND);
private static final PacketDeserializer deserializer = new PacketDeserializer(EnumPacketDirection.SERVERBOUND);
public static void writePackets(Collection<PacketData> p, DataOutput out) throws IOException {
for(PacketData pd : p) {
writePacket(pd, out);
}
}
private static File lastReplayFile = null;
private static boolean lastContainsJoinPacket = false;
/**
* @param replayFile The File to reverse
* @param outputFile The File to save the reversed Packets in
* @param seekJoinPacket Whether a {@link S01PacketJoinGame} should be seeked in the Replay File. If containsJoinPacket is being
* called with the same File directly afterwards, this will reduce the amount of calculations. Only use if needed,
* because this consumes a significant amount of time!
* @param boundaries Two timestamps which make a boundary for excluded Packets
* @return Whether the action was successful
*/
public static boolean reversePackets(File replayFile, File outputFile, boolean seekJoinPacket, int... boundaries) {
lastReplayFile = replayFile;
lastContainsJoinPacket = false;
/**
*
* @param replayFile The File to reverse
* @param outputFile The File to save the reversed Packets in
* @param seekJoinPacket Whether a {@link S01PacketJoinGame} should be seeked in the Replay File. If containsJoinPacket is being
* called with the same File directly afterwards, this will reduce the amount of calculations. Only use if needed,
* because this consumes a significant amount of time!
* @param boundaries Two timestamps which make a boundary for excluded Packets
* @return Whether the action was successful
*/
public static boolean reversePackets(File replayFile, File outputFile, boolean seekJoinPacket, int... boundaries) {
lastReplayFile = replayFile;
lastContainsJoinPacket = false;
RandomAccessFile raf = null;
DataInputStream dis = null;
RandomAccessFile raf = null;
DataInputStream dis = null;
boolean bounds = false;
int lower = 0, upper = 0;
if(boundaries.length >= 2) {
if(boundaries[0] > boundaries[1]) {
upper = boundaries[0];
lower = boundaries[1];
} else {
upper = boundaries[1];
lower = boundaries[0];
}
}
try {
if(!outputFile.exists()) {
outputFile.createNewFile();
}
raf = new RandomAccessFile(outputFile, "rw");
boolean bounds = false;
int lower = 0, upper = 0;
if(boundaries.length >= 2) {
if(boundaries[0] > boundaries[1]) {
upper = boundaries[0];
lower = boundaries[1];
} else {
upper = boundaries[1];
lower = boundaries[0];
}
}
try {
if(!outputFile.exists()) {
outputFile.createNewFile();
}
raf = new RandomAccessFile(outputFile, "rw");
Pair<Long, DataInputStream> pair = getTempFileInputStream(replayFile);
dis = pair.second();
long fileLength = pair.first();
Pair<Long, DataInputStream> pair = getTempFileInputStream(replayFile);
dis = pair.second();
long fileLength = pair.first();
raf.setLength(fileLength);
raf.setLength(fileLength);
long pointerBefore = fileLength;
long pointerBefore = fileLength;
while(dis.available() > 0) {
try {
PacketData pd = readPacketData(dis);
while(dis.available() > 0) {
try {
PacketData pd = readPacketData(dis);
boolean write = true;
if(bounds) {
if(pd.getTimestamp() < lower || pd.getTimestamp() > upper) {
write = false;
}
}
boolean write = true;
if(bounds) {
if(pd.getTimestamp() < lower || pd.getTimestamp() > upper) {
write = false;
}
}
if(write) {
if(seekJoinPacket && !lastContainsJoinPacket) {
Packet p = deserializePacket(pd.getByteArray());
if(p instanceof S01PacketJoinGame) lastContainsJoinPacket = true;
}
pointerBefore = pointerBefore - getWrittenByteSize(pd);
raf.seek(pointerBefore);
writePacket(pd, raf);
}
} catch(EOFException e) {
e.printStackTrace();
break;
}
}
return true;
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(raf != null) {
raf.close();
}
if(dis != null) {
dis.close();
}
} catch(Exception e) {
}
}
if(write) {
if(seekJoinPacket && !lastContainsJoinPacket) {
Packet p = deserializePacket(pd.getByteArray());
if(p instanceof S01PacketJoinGame) lastContainsJoinPacket = true;
}
pointerBefore = pointerBefore - getWrittenByteSize(pd);
raf.seek(pointerBefore);
writePacket(pd, raf);
}
} catch(EOFException e) {
e.printStackTrace();
break;
}
}
return true;
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(raf != null) {
raf.close();
}
if(dis != null) {
dis.close();
}
} catch(Exception e) {}
}
return false;
}
return false;
}
public static void addThumbToZip(File zipFile, File thumb) throws IOException {
// get a temp file
File tempFile = File.createTempFile(zipFile.getName(), null, zipFile.getParentFile());
// delete it, otherwise you cannot rename your existing zip to it.
private static final byte[] uniqueBytes = new byte[]{0,1,1,2,3,5,8};
byte[] buf = new byte[1024];
public static void addThumbToZip(File zipFile, File thumb) throws IOException {
// get a temp file
File tempFile = File.createTempFile(zipFile.getName(), null, zipFile.getParentFile());
// delete it, otherwise you cannot rename your existing zip to it.
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tempFile));
byte[] buf = new byte[1024];
ZipEntry entry = zin.getNextEntry();
while(entry != null) {
String name = entry.getName();
boolean isThumb = name.contains("thumb");
if(!isThumb) {
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while((len = zin.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the files
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tempFile));
InputStream in = new FileInputStream(thumb);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry("thumb"));
// Transfer bytes from the file to the ZIP file
int len;
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
String name = entry.getName();
boolean isThumb = name.contains("thumb");
if (!isThumb) {
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the files
out.write(uniqueBytes);
InputStream in = new FileInputStream(thumb);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry("thumb"));
// Transfer bytes from the file to the ZIP file
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
out.write(uniqueBytes);
// Complete the ZIP file
out.close();
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
// Complete the ZIP file
out.close();
ReplayMod.fileCopyHandler.registerModifiedFile(tempFile, zipFile);
}
ReplayMod.fileCopyHandler.registerModifiedFile(tempFile, zipFile);
}
}

View File

@@ -1,47 +1,46 @@
package eu.crushedpixel.replaymod.utils;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import eu.crushedpixel.replaymod.reflection.MCPNames;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
public class ResourceHelper {
private static BufferedImage defaultThumb;
private static BufferedImage defaultThumb;
private static List<ResourceLocation> openResources = new ArrayList<ResourceLocation>();
static {
try {
defaultThumb = ImageIO.read(MCPNames.class.getClassLoader().getResourceAsStream("default_thumb.jpg"));
} catch(Exception e) {
defaultThumb = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR);
e.printStackTrace();
}
}
private static List<ResourceLocation> openResources = new ArrayList<ResourceLocation>();
static {
try {
defaultThumb = ImageIO.read(MCPNames.class.getClassLoader().getResourceAsStream("default_thumb.jpg"));
} catch(Exception e) {
defaultThumb = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR);
e.printStackTrace();
}
}
public static void registerResource(ResourceLocation loc) {
openResources.add(loc);
}
public static void registerResource(ResourceLocation loc) {
openResources.add(loc);
}
public static void freeResource(ResourceLocation loc) {
Minecraft.getMinecraft().getTextureManager().deleteTexture(loc);
openResources.remove(loc);
}
public static void freeResource(ResourceLocation loc) {
Minecraft.getMinecraft().getTextureManager().deleteTexture(loc);
openResources.remove(loc);
}
public static void freeAllResources() {
for(ResourceLocation loc : openResources) {
Minecraft.getMinecraft().getTextureManager().deleteTexture(loc);
}
public static void freeAllResources() {
for(ResourceLocation loc : openResources) {
Minecraft.getMinecraft().getTextureManager().deleteTexture(loc);
}
openResources = new ArrayList<ResourceLocation>();
}
openResources = new ArrayList<ResourceLocation>();
}
public static BufferedImage getDefaultThumbnail() {
return defaultThumb;
}
public static BufferedImage getDefaultThumbnail() {
return defaultThumb;
}
}

View File

@@ -17,21 +17,13 @@
*/
package eu.crushedpixel.replaymod.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
*
* @author Marc Schunk, created on 21.06.2004
*
* <p/>
* A Class to provide helpers of commonly user operations with binary
* and character Streams, such as read to an OutputStream/Writer,
* String, ByteArray. In addition streams can be compressed.
@@ -39,209 +31,196 @@ import java.util.zip.GZIPOutputStream;
public class StreamTools {
/**
* Checks weather the given array is contained in the first array
*
* @param ar1
* - the containing array
* @param index1
* - the index where the search starts
* @param ar2
* - the array that schould be contained
* @return - true of ar2 is contained in ar1
*/
public static final boolean arrayMatch(char[] ar1, int index1, char[] ar2) {
if((ar1.length - index1 - ar2.length) < 0)
return false;
for(int i = 0; i < ar2.length; i++) {
if(ar1[index1 + i] != ar2[i])
return false;
}
return true;
}
public static final String[] umlauteString = {"&amp;", "&#223;", "&auml;",
"&Auml;", "&ouml;", "&Ouml;", "&uuml;", "&Uuml;", "&szlig;"};
public static final String[] umlauteReplacement = {"&", "ß", "ä", "Ä", "ö",
"Ö", "ü", "Ü", "ß"};
/**
* Reads inStream completly and writes it to outStream. Streams will not be
* closed.
*
* @param inStream
* - an InputStream to be read completely
* @param outStream
* - the destination Stream
* @throws IOException
*/
public static void readStream(InputStream inStream, OutputStream outStream)
throws IOException {
byte[] buffer = new byte[4096];
int len = 0;
while((len = inStream.read(buffer, 0, buffer.length)) > -1) {
outStream.write(buffer, 0, len);
}
}
/**
* Checks weather the given array is contained in the first array
*
* @param ar1 - the containing array
* @param index1 - the index where the search starts
* @param ar2 - the array that schould be contained
* @return - true of ar2 is contained in ar1
*/
public static final boolean arrayMatch(char[] ar1, int index1, char[] ar2) {
if((ar1.length - index1 - ar2.length) < 0)
return false;
for(int i = 0; i < ar2.length; i++) {
if(ar1[index1 + i] != ar2[i])
return false;
}
return true;
}
/**
* Reads inStream completly into an byte[]. Streams will not be closed.
*
* @param inStream
* - an InputStream to be read completely
* @param outStream
* - the destination Stream
* @throws IOException
*/
public static byte[] readStream(InputStream inStream) throws IOException {
byte[] buffer = new byte[4096];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len = inStream.read(buffer, 0, buffer.length)) > -1) {
baos.write(buffer, 0, len);
}
return baos.toByteArray();
}
/**
* Reads inStream completly and writes it to outStream. Streams will not be
* closed.
*
* @param inStream - an InputStream to be read completely
* @param outStream - the destination Stream
* @throws IOException
*/
public static void readStream(InputStream inStream, OutputStream outStream)
throws IOException {
byte[] buffer = new byte[4096];
int len = 0;
while((len = inStream.read(buffer, 0, buffer.length)) > -1) {
outStream.write(buffer, 0, len);
}
}
/**
* Reads the given Steam into an String *
*
* @throws IOException
*/
public static String readStreamtoString(InputStream inStream)
throws IOException {
StringWriter sw = new StringWriter();
InputStreamReader isr = new InputStreamReader(inStream);
/**
* Reads inStream completly into an byte[]. Streams will not be closed.
*
* @param inStream - an InputStream to be read completely
* @param outStream - the destination Stream
* @throws IOException
*/
public static byte[] readStream(InputStream inStream) throws IOException {
byte[] buffer = new byte[4096];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len = inStream.read(buffer, 0, buffer.length)) > -1) {
baos.write(buffer, 0, len);
}
return baos.toByteArray();
}
char[] buffer = new char[4096];
int len = 0;
while((len = isr.read(buffer, 0, buffer.length)) > -1) {
sw.write(buffer, 0, len);
}
return sw.toString();
}
/**
* Reads the given Steam into an String *
*
* @throws IOException
*/
public static String readStreamtoString(InputStream inStream)
throws IOException {
StringWriter sw = new StringWriter();
InputStreamReader isr = new InputStreamReader(inStream);
/**
* Reads the given Steam into an String using the given encoding
*
* @throws IOException
*/
public static String readStreamtoString(InputStream inStream, String charSet)
throws IOException {
StringWriter sw = new StringWriter();
InputStreamReader isr = new InputStreamReader(inStream, charSet);
char[] buffer = new char[4096];
int len = 0;
while((len = isr.read(buffer, 0, buffer.length)) > -1) {
sw.write(buffer, 0, len);
}
return sw.toString();
}
char[] buffer = new char[4096];
int len = 0;
while((len = isr.read(buffer, 0, buffer.length)) > -1) {
sw.write(buffer, 0, len);
}
return sw.toString();
}
/**
* Reads the given Steam into an String using the given encoding
*
* @throws IOException
*/
public static String readStreamtoString(InputStream inStream, String charSet)
throws IOException {
StringWriter sw = new StringWriter();
InputStreamReader isr = new InputStreamReader(inStream, charSet);
public static String stripComments(String inString, String newLineDelimiter)
throws IOException {
StringWriter sw = new StringWriter();
// use both windows and linux/unix line seperators to be independent of the file orgin
String[] lines = inString.split("\r\n|\n");
for(String line : lines) {
if((line.indexOf("#") == -1) && (line.trim().length() > 0)) {
sw.append(line).append(newLineDelimiter);
}
}
return sw.toString();
}
char[] buffer = new char[4096];
int len = 0;
while((len = isr.read(buffer, 0, buffer.length)) > -1) {
sw.write(buffer, 0, len);
}
return sw.toString();
}
public static final String[] umlauteString = {"&amp;", "&#223;", "&auml;",
"&Auml;", "&ouml;", "&Ouml;", "&uuml;", "&Uuml;", "&szlig;"};
public static final String[] umlauteReplacement = {"&", "ß", "ä", "Ä", "ö",
"Ö", "ü", "Ü", "ß"};
public static String stripComments(String inString, String newLineDelimiter)
throws IOException {
StringWriter sw = new StringWriter();
// use both windows and linux/unix line seperators to be independent of the file orgin
String[] lines = inString.split("\r\n|\n");
for(String line : lines) {
if((line.indexOf("#") == -1) && (line.trim().length() > 0)) {
sw.append(line).append(newLineDelimiter);
}
}
return sw.toString();
}
public static String replaceSpecialCharacters(String s) {
for(int i = 0; i < umlauteString.length; i++) {
s = s.replaceAll(umlauteString[i], umlauteReplacement[i]);
}
return s;
}
public static String replaceSpecialCharacters(String s) {
for(int i = 0; i < umlauteString.length; i++) {
s = s.replaceAll(umlauteString[i], umlauteReplacement[i]);
}
return s;
}
/**
* Stores the given Stream in an byte[]. Stream is compressed on the fly.
* Streams will not be closed.
*
* @param inStream
* - an InputStream to be read completely
* @param outStream
* - the destination Stream
* @throws IOException
*/
public static byte[] compressStreamToByteArray(InputStream inStream)
throws IOException {
byte[] buffer = new byte[4096];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
/**
* Stores the given Stream in an byte[]. Stream is compressed on the fly.
* Streams will not be closed.
*
* @param inStream - an InputStream to be read completely
* @param outStream - the destination Stream
* @throws IOException
*/
public static byte[] compressStreamToByteArray(InputStream inStream)
throws IOException {
byte[] buffer = new byte[4096];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream zos = new GZIPOutputStream(baos);
while((len = inStream.read(buffer, 0, buffer.length)) > -1) {
zos.write(buffer, 0, len);
}
zos.close();
return baos.toByteArray();
}
GZIPOutputStream zos = new GZIPOutputStream(baos);
while((len = inStream.read(buffer, 0, buffer.length)) > -1) {
zos.write(buffer, 0, len);
}
zos.close();
return baos.toByteArray();
}
/**
* Stores the given Stream in an byte[]. Stream is compressed on the fly.
* Streams will not be closed.
*
* @param inStream
* - an InputStream to be read completely
* @param outStream
* - the destination Stream
* @throws IOException
*/
public static byte[] compress(byte[] uncompressed) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(uncompressed);
return compressStreamToByteArray(bais);
}
/**
* Stores the given Stream in an byte[]. Stream is compressed on the fly.
* Streams will not be closed.
*
* @param inStream - an InputStream to be read completely
* @param outStream - the destination Stream
* @throws IOException
*/
public static byte[] compress(byte[] uncompressed) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(uncompressed);
return compressStreamToByteArray(bais);
}
/**
* Stores the given Stream in an byte[]. Stream is decompressed on the fly.
* Thus, the input stream should contain compressed content. Streams will
* not be closed.
*
* @param inStream
* - an InputStream to be read completely
* @param outStream
* - the destination Stream
* @throws IOException
*/
public static byte[] decompressStreamToByteArray(InputStream inStream)
throws IOException {
byte[] buffer = new byte[4096];
int len = 0;
/**
* Stores the given Stream in an byte[]. Stream is decompressed on the fly.
* Thus, the input stream should contain compressed content. Streams will
* not be closed.
*
* @param inStream - an InputStream to be read completely
* @param outStream - the destination Stream
* @throws IOException
*/
public static byte[] decompressStreamToByteArray(InputStream inStream)
throws IOException {
byte[] buffer = new byte[4096];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPInputStream gzis = new GZIPInputStream(inStream);
while((len = gzis.read(buffer, 0, buffer.length)) > -1) {
baos.write(buffer, 0, len);
}
inStream.close();
return baos.toByteArray();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPInputStream gzis = new GZIPInputStream(inStream);
while((len = gzis.read(buffer, 0, buffer.length)) > -1) {
baos.write(buffer, 0, len);
}
inStream.close();
return baos.toByteArray();
}
public static byte[] decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
return decompressStreamToByteArray(bais);
}
public static byte[] decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
return decompressStreamToByteArray(bais);
}
/**
* Reads the given Steam into an String *
*
* @throws IOException
*/
public static String readReaderToString(Reader reader) throws IOException {
StringBuffer sb = new StringBuffer();
/**
* Reads the given Steam into an String *
*
* @throws IOException
*/
public static String readReaderToString(Reader reader) throws IOException {
StringBuffer sb = new StringBuffer();
char[] buffer = new char[4096];
int len = 0;
while((len = reader.read(buffer, 0, buffer.length)) > -1) {
sb.append(buffer, 0, len);
}
return sb.toString();
}
char[] buffer = new char[4096];
int len = 0;
while((len = reader.read(buffer, 0, buffer.length)) > -1) {
sb.append(buffer, 0, len);
}
return sb.toString();
}
}

View File

@@ -10,50 +10,49 @@ import java.util.zip.ZipOutputStream;
public class ZipFileUtils {
public static void deleteZipEntry(File zipFile,
String[] files) throws IOException {
// get a temp file
File tempFile = File.createTempFile(zipFile.getName(), null);
// delete it, otherwise you cannot rename your existing zip to it.
tempFile.delete();
tempFile.deleteOnExit();
boolean renameOk=zipFile.renameTo(tempFile);
if (!renameOk)
{
throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
}
byte[] buf = new byte[1024];
public static void deleteZipEntry(File zipFile,
String[] files) throws IOException {
// get a temp file
File tempFile = File.createTempFile(zipFile.getName(), null);
// delete it, otherwise you cannot rename your existing zip to it.
tempFile.delete();
tempFile.deleteOnExit();
boolean renameOk = zipFile.renameTo(tempFile);
if(!renameOk) {
throw new RuntimeException("could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
}
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile));
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while(entry != null) {
String name = entry.getName();
boolean toBeDeleted = false;
for(String f : files) {
if(f.equals(name)) {
toBeDeleted = true;
break;
}
}
if(!toBeDeleted) {
// Add ZIP entry to output stream.
zout.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while((len = zin.read(buf)) > 0) {
zout.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the files
// Complete the ZIP file
zout.close();
tempFile.delete();
}
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
String name = entry.getName();
boolean toBeDeleted = false;
for (String f : files) {
if (f.equals(name)) {
toBeDeleted = true;
break;
}
}
if (!toBeDeleted) {
// Add ZIP entry to output stream.
zout.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
zout.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the files
// Complete the ZIP file
zout.close();
tempFile.delete();
}
}