diff --git a/src/main/java/com/minecrafttas/mctcommon/file/AbstractDataFile.java b/src/main/java/com/minecrafttas/mctcommon/file/AbstractDataFile.java index 9929075d..132beba3 100644 --- a/src/main/java/com/minecrafttas/mctcommon/file/AbstractDataFile.java +++ b/src/main/java/com/minecrafttas/mctcommon/file/AbstractDataFile.java @@ -55,19 +55,33 @@ protected AbstractDataFile(Path file, String name, String comment) { this.comment = comment; this.properties = new Properties(); - createDirectory(file); + try { + createDirectory(file.getParent()); + } catch (IOException e) { + MCTCommon.LOGGER.catching(e); + } } /** * Creates the directory for the file if it doesn't exist - * @param file The file to create the directory for + * @param directory The file to create the directory for */ - protected void createDirectory(Path file) { - try { - Files.createDirectories(file.getParent()); - } catch (IOException e) { - MCTCommon.LOGGER.catching(e); + public static void createDirectory(Path directory) throws IOException { + /* + * Test if the directory is a file, + * but named like the target directory. + * + * For example, naming a file "tasfiles" and + * putting it in the saves folder will succeed the "Files.exists" check, + * but fail everywhere, where a directory is required... + * + * If this is the case, delete the file and create a directory instead. + */ + if (Files.exists(directory) && !Files.isDirectory(directory)) { + Files.delete(directory); } + + Files.createDirectories(directory); } public void load() { diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 04382371..e53462e0 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -2,7 +2,6 @@ import static com.minecrafttas.tasmod.TASmod.LOGGER; -import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -18,6 +17,7 @@ import com.minecrafttas.mctcommon.events.EventClient.EventOpenGui; import com.minecrafttas.mctcommon.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.mctcommon.events.EventListenerRegistry; +import com.minecrafttas.mctcommon.file.AbstractDataFile; import com.minecrafttas.mctcommon.networking.Client; import com.minecrafttas.mctcommon.networking.PacketHandlerRegistry; import com.minecrafttas.mctcommon.networking.Server; @@ -60,9 +60,9 @@ public class TASmodClient implements ClientModInitializer, EventClientInit, Even public static TickSyncClient ticksyncClient; - public static final String tasdirectory = Minecraft.getMinecraft().mcDataDir.getAbsolutePath() + File.separator + "saves" + File.separator + "tasfiles"; + public final static Path tasfiledirectory = Minecraft.getMinecraft().mcDataDir.toPath().resolve("saves").resolve("tasfiles"); - public static final String savestatedirectory = Minecraft.getMinecraft().mcDataDir.getAbsolutePath() + File.separator + "saves" + File.separator + "savestates"; + public final static Path savestatedirectory = Minecraft.getMinecraft().mcDataDir.toPath().resolve("saves").resolve("savestates"); public static InfoHud hud; @@ -95,17 +95,19 @@ public class TASmodClient implements ClientModInitializer, EventClientInit, Even */ public static PlaybackControllerClient controller = new PlaybackControllerClient(); - public static void createTASDir() { - File tasDir = new File(tasdirectory); - if (!tasDir.exists()) { - tasDir.mkdir(); + public static void createTASfileDir() { + try { + AbstractDataFile.createDirectory(tasfiledirectory); + } catch (IOException e) { + TASmod.LOGGER.catching(e); } } public static void createSavestatesDir() { - File savestateDir = new File(savestatedirectory); - if (!savestateDir.exists()) { - savestateDir.mkdir(); + try { + AbstractDataFile.createDirectory(savestatedirectory); + } catch (IOException e) { + TASmod.LOGGER.catching(e); } } @@ -114,6 +116,8 @@ public void onInitializeClient() { LanguageManager.registerMod("tasmod"); + createFolders(); + registerConfigValues(); loadConfig(Minecraft.getMinecraft()); @@ -131,6 +135,11 @@ public void onInitializeClient() { // Initialize keybind manager keybindManager = new KeybindManager(VirtualKeybindings::isKeyDownExceptTextfield); + // Create them here so they are created after the folders have been created, since they depend on the tasfiles folder + desyncMonitorFileCommandExtension = new DesyncMonitorFileCommandExtension(); + optionsFileCommandExtension = new OptionsFileCommandExtension(); + labelFileCommandExtension = new LabelFileCommandExtension(); + registerEventListeners(); registerNetworkPacketHandlers(); @@ -144,6 +153,11 @@ public void onInitializeClient() { } + private void createFolders() { + createTASfileDir(); + createSavestatesDir(); + } + private void registerNetworkPacketHandlers() { // Register packet handlers LOGGER.info(LoggerMarkers.Networking, "Registering network handlers on client"); @@ -185,9 +199,6 @@ public void onClientInit(Minecraft mc) { registerPlaybackMetadata(mc); registerSerialiserFlavors(mc); registerFileCommands(); - - createTASDir(); - createSavestatesDir(); } boolean waszero; @@ -308,9 +319,9 @@ private void registerSerialiserFlavors(Minecraft mc) { TASmodAPIRegistry.SERIALISER_FLAVOR.register(betaFlavor); } - public static DesyncMonitorFileCommandExtension desyncMonitorFileCommandExtension = new DesyncMonitorFileCommandExtension(); - public static OptionsFileCommandExtension optionsFileCommandExtension = new OptionsFileCommandExtension(); - public static LabelFileCommandExtension labelFileCommandExtension = new LabelFileCommandExtension(); + public static DesyncMonitorFileCommandExtension desyncMonitorFileCommandExtension; + public static OptionsFileCommandExtension optionsFileCommandExtension; + public static LabelFileCommandExtension labelFileCommandExtension; private void registerFileCommands() { TASmodAPIRegistry.PLAYBACK_FILE_COMMAND.register(desyncMonitorFileCommandExtension); diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java index eae277ed..94497364 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java @@ -3,8 +3,8 @@ import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.awt.Desktop; -import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -30,13 +30,13 @@ public String getName() { @Override public String getUsage(ICommandSender sender) { return "/folder "; - } + } @Override public int getRequiredPermissionLevel() { return 0; } - + @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length == 1) { @@ -66,26 +66,24 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen } public static void openTASFolder() { - File file = new File(TASmodClient.tasdirectory); + Path file = TASmodClient.tasfiledirectory; try { - if (!file.exists()) - file.mkdir(); - Desktop.getDesktop().open(file); + TASmodClient.createTASfileDir(); + Desktop.getDesktop().open(file.toFile()); } catch (IOException e) { - LOGGER.error("Something went wrong while opening ", file.getPath()); - e.printStackTrace(); + LOGGER.error("Something went wrong while opening ", file); + LOGGER.catching(e); } } public static void openSavestates() { - File file = new File(TASmodClient.savestatedirectory); + Path file = TASmodClient.savestatedirectory; try { - if (!file.exists()) - file.mkdir(); - Desktop.getDesktop().open(file); + TASmodClient.createSavestatesDir(); + Desktop.getDesktop().open(file.toFile()); } catch (IOException e) { - LOGGER.error("Something went wrong while opening ", file.getPath()); - e.printStackTrace(); + LOGGER.error("Something went wrong while opening ", file); + LOGGER.catching(e); } } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java index 12b7f5ec..08cca459 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java @@ -14,9 +14,12 @@ import java.io.IOException; import java.io.Serializable; import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; +import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.Display; import com.dselent.bigarraylist.BigArrayList; @@ -28,6 +31,7 @@ import com.minecrafttas.mctcommon.networking.exception.WrongSideException; import com.minecrafttas.mctcommon.networking.interfaces.ClientPacketHandler; import com.minecrafttas.mctcommon.networking.interfaces.PacketID; +import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.EventClient.EventClientTickPost; import com.minecrafttas.tasmod.events.EventPlaybackClient; @@ -80,6 +84,8 @@ */ public class PlaybackControllerClient implements ClientPacketHandler, EventClientInit, EventVirtualInput.EventVirtualKeyboardTick, EventVirtualInput.EventVirtualMouseTick, EventVirtualInput.EventVirtualCameraAngleTick, EventClientTickPost { + private Logger logger = TASmod.LOGGER; + /** * The current state of the controller. */ @@ -101,12 +107,19 @@ public class PlaybackControllerClient implements ClientPacketHandler, EventClien private VirtualCameraAngle camera = new VirtualCameraAngle(); - public final File directory = new File(Minecraft.getMinecraft().mcDataDir.getAbsolutePath() + File.separator + "saves" + File.separator + "tasfiles"); + /** + * The directory where to store the tasfiles + */ + public final Path tasFileDirectory; + /** + * The file ending of the TASfiles + */ + public final Path fileEnding = Paths.get(".mctas"); /** * The place where all inputs get stored */ - private BigArrayList inputs = new BigArrayList(directory + File.separator + "temp"); + private BigArrayList inputs; // private long startSeed = TASmod.ktrngHandler.getGlobalSeedClient(); // TODO Replace with Metadata extension @@ -114,6 +127,12 @@ public class PlaybackControllerClient implements ClientPacketHandler, EventClien private Integer playUntil = null; // TODO Replace with event + public PlaybackControllerClient() { + tasFileDirectory = TASmodClient.tasfiledirectory; + + inputs = new BigArrayList(tasFileDirectory.resolve("temp").toAbsolutePath().toString()); + } + /** * Sets the current {@link TASstate} * @@ -127,7 +146,7 @@ public void setTASState(TASstate stateIn) { try { TASmodClient.client.send(new TASmodBufferBuilder(PLAYBACK_STATE).writeTASState(stateIn)); } catch (Exception e) { - e.printStackTrace(); + logger.catching(e); } } @@ -478,7 +497,7 @@ public void setInputs(BigArrayList inputs, long index) { } catch (IOException e) { e.printStackTrace(); } - this.inputs = new BigArrayList(directory + File.separator + "temp"); + this.inputs = new BigArrayList(tasFileDirectory + File.separator + "temp"); SerialiserFlavorBase.addAll(this.inputs, inputs); setIndex(index); } @@ -522,7 +541,7 @@ public void clear() { } catch (IOException e) { e.printStackTrace(); } - inputs = new BigArrayList(directory + File.separator + "temp"); + inputs = new BigArrayList(tasFileDirectory + File.separator + "temp"); index = 0; } @@ -778,7 +797,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws flavor = TASmodBufferBuilder.readString(buf); try { - PlaybackSerialiser.saveToFile(new File(directory, name + ".mctas"), this, flavor); + PlaybackSerialiser.saveToFile(tasFileDirectory.resolve(name + fileEnding), this, flavor); } catch (PlaybackSaveException e) { if (mc.world != null) mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); @@ -804,7 +823,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws flavor = TASmodBufferBuilder.readString(buf); try { - TASmodClient.controller.setInputs(PlaybackSerialiser.loadFromFile(new File(directory, name + ".mctas"), flavor)); + TASmodClient.controller.setInputs(PlaybackSerialiser.loadFromFile(tasFileDirectory.resolve(name + fileEnding), flavor)); } catch (PlaybackLoadException e) { if (mc.world != null) { TextComponentString textComponent = new TextComponentString(e.getMessage()); diff --git a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/PlaybackFileCommand.java b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/PlaybackFileCommand.java index 9aed7f28..21a66872 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/PlaybackFileCommand.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/PlaybackFileCommand.java @@ -1,12 +1,17 @@ package com.minecrafttas.tasmod.playback.filecommands; +import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import com.dselent.bigarraylist.BigArrayList; +import com.minecrafttas.mctcommon.file.AbstractDataFile; import com.minecrafttas.mctcommon.registry.Registerable; +import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TickContainer; public class PlaybackFileCommand { @@ -30,7 +35,7 @@ public PlaybackFileCommand(String name, String... args) { public String getName() { return name; } - + public String[] getArgs() { return args; } @@ -49,7 +54,32 @@ public String toString() { return String.format("$%s(%s);", name, String.join(", ", args)); } - public static abstract class PlaybackFileCommandExtension implements Registerable{ + public static abstract class PlaybackFileCommandExtension implements Registerable { + + protected final Path tempDir; + + public PlaybackFileCommandExtension() { + this(null); + } + + /** + *

Creates a FileCommandExtension and creates a temp folder with
+ * the specified name for the {@link BigArrayList} files in the correct location + * + * @param tempFolderName The name of the temp folder + */ + public PlaybackFileCommandExtension(String tempFolderName) { + if (tempFolderName == null) { + tempDir = null; + return; + } + this.tempDir = TASmodClient.tasfiledirectory.resolve("temp").resolve(tempFolderName); + try { + AbstractDataFile.createDirectory(tempDir); + } catch (IOException e) { + e.printStackTrace(); + } + } protected boolean enabled = false; @@ -95,7 +125,7 @@ public void setEnabled(boolean enabled) { onDisable(); this.enabled = enabled; } - + @Override public String toString() { return getExtensionName(); @@ -200,8 +230,8 @@ public boolean equals(Object o) { return super.equals(o); } } - + public static class PlaybackFileCommandLine extends ArrayList { - + } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/DesyncMonitorFileCommandExtension.java b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/DesyncMonitorFileCommandExtension.java index 7c3fed4d..045e377a 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/DesyncMonitorFileCommandExtension.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/DesyncMonitorFileCommandExtension.java @@ -1,6 +1,5 @@ package com.minecrafttas.tasmod.playback.filecommands.integrated; -import java.io.File; import java.io.IOException; import java.io.Serializable; import java.text.NumberFormat; @@ -30,13 +29,20 @@ */ public class DesyncMonitorFileCommandExtension extends PlaybackFileCommandExtension implements EventPlaybackClient.EventControllerStateChange { - private File tempDir = new File(Minecraft.getMinecraft().mcDataDir.getAbsolutePath() + File.separator + "saves" + File.separator + "tasfiles" + File.separator + "temp" + File.separator + "monitoring"); - - private BigArrayList monitorContainer = new BigArrayList(tempDir.toString()); + /** + * List containing {@link MonitorContainer MonitorContainers} in a TASfile + */ + private BigArrayList monitorContainer; + /** + * The {@link MonitorContainer} for the current tick + */ private MonitorContainer currentValues; public DesyncMonitorFileCommandExtension() { + super("monitoring"); + this.monitorContainer = new BigArrayList(tempDir.toString()); + // Is enabled by default enabled = true; } @@ -160,7 +166,7 @@ public String getStatus(EntityPlayerSP player) { playervalues[3] = player.motionX; playervalues[4] = player.motionY; playervalues[5] = player.motionZ; - DesyncStatus status = currentValues.getSeverity(TASmodClient.controller.index(), playervalues); + DesyncStatus status = currentValues.getSeverity(playervalues); lastStatus = status.getFormat() + status.getText(); } else { lastStatus = TextFormatting.GRAY + "Empty"; @@ -211,6 +217,11 @@ private String getFormattedString(double delta) { return out; } + /** + * Storage class containing the position and velocity of a player at a given tick. + * + * @author Scribble + */ public class MonitorContainer implements Serializable { private static final long serialVersionUID = -3138791930493647885L; @@ -245,7 +256,12 @@ public String toString() { return String.format(Locale.ENGLISH, "%d, %d, %d, %d, %d, %d", values[0], values[1], values[2], values[3], values[4], values[5]); } - public DesyncStatus getSeverity(long index, double[] playerValues) { + /** + * Compares the values in this {@link MonitorContainer} with other values + * @param playerValues The values to compare to + * @return The {@link DesyncStatus}, how severe the playback is currently drifting apart + */ + public DesyncStatus getSeverity(double[] playerValues) { DesyncStatus out = null; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/LabelFileCommandExtension.java b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/LabelFileCommandExtension.java index 15fae616..97a523f3 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/LabelFileCommandExtension.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/LabelFileCommandExtension.java @@ -16,9 +16,11 @@ public class LabelFileCommandExtension extends PlaybackFileCommandExtension { BigArrayList label = new BigArrayList<>(); public LabelFileCommandExtension() { + super("label"); + this.label = new BigArrayList<>(tempDir.toString()); enabled = true; } - + @Override public String getExtensionName() { return "tasmod_label@v1"; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/OptionsFileCommandExtension.java b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/OptionsFileCommandExtension.java index 4ad9f7b9..2a1a5ef1 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/OptionsFileCommandExtension.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/integrated/OptionsFileCommandExtension.java @@ -15,9 +15,11 @@ public class OptionsFileCommandExtension extends PlaybackFileCommandExtension { private boolean shouldRenderHud = true; - BigArrayList hud = new BigArrayList<>(); + BigArrayList hud; public OptionsFileCommandExtension() { + super("hud"); + hud = new BigArrayList<>(tempDir.toString()); enabled = true; } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/PlaybackSerialiser.java b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/PlaybackSerialiser.java index d2a61054..8a03969a 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/PlaybackSerialiser.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/PlaybackSerialiser.java @@ -1,10 +1,11 @@ package com.minecrafttas.tasmod.playback.tasfile; import java.io.BufferedReader; -import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -34,7 +35,7 @@ public class PlaybackSerialiser { * @param flavorName The name of the {@link SerialiserFlavorBase flavor} to use for the tasfile * @throws PlaybackSaveException When a saving operation fails */ - public static void saveToFile(File file, PlaybackControllerClient controller, String flavorName) throws PlaybackSaveException { + public static void saveToFile(Path file, PlaybackControllerClient controller, String flavorName) throws PlaybackSaveException { saveToFile(file, controller, flavorName, -1L); } @@ -47,7 +48,7 @@ public static void saveToFile(File file, PlaybackControllerClient controller, St * @param stopIndex The index at which the serialiser stops. Use -1L to parse the entire file * @throws PlaybackSaveException When a saving operation fails */ - public static void saveToFile(File file, PlaybackControllerClient controller, String flavorName, long stopIndex) throws PlaybackSaveException { + public static void saveToFile(Path file, PlaybackControllerClient controller, String flavorName, long stopIndex) throws PlaybackSaveException { if (controller == null) { throw new PlaybackSaveException("Save to file failed. No controller specified"); } @@ -62,20 +63,20 @@ public static void saveToFile(File file, PlaybackControllerClient controller, St * @param flavorName The name of the {@link SerialiserFlavorBase flavor} to use for the tasfile * @throws PlaybackSaveException When a saving operation fails */ - public static void saveToFile(File file, BigArrayList container, String flavorName) throws PlaybackSaveException { + public static void saveToFile(Path file, BigArrayList container, String flavorName) throws PlaybackSaveException { saveToFile(file, container, flavorName, -1); } /** * Saves a BigArrayList of {@link TickContainer TickContainers} partially to a file - * @param file The file to save the serialised inputs to + * @param path The file to save the serialised inputs to * @param container The list of {@link TickContainer TickContainers} to use * @param flavorName The name of the {@link SerialiserFlavorBase flavor} to use for the tasfile * @param stopIndex The index at which the serialiser stops. Use -1L to parse the entire file * @throws PlaybackSaveException When a saving operation fails */ - public static void saveToFile(File file, BigArrayList container, String flavorName, long stopIndex) throws PlaybackSaveException { - if (file == null) { + public static void saveToFile(Path path, BigArrayList container, String flavorName, long stopIndex) throws PlaybackSaveException { + if (path == null) { throw new PlaybackSaveException("Save to file failed. No file specified"); } @@ -91,9 +92,9 @@ public static void saveToFile(File file, BigArrayList container, FileThread writerThread; try { - writerThread = new FileThread(file, false); - } catch (FileNotFoundException e) { - throw new PlaybackSaveException(e, "Trying to save the file %s, but the file can't be created", file.getName()); + writerThread = new FileThread(path, false); + } catch (IOException e) { + throw new PlaybackSaveException(e, "Trying to save the file %s, but the file can't be created", path.getFileName().toString()); } writerThread.start(); @@ -127,16 +128,16 @@ public static void saveToFile(File file, BigArrayList container, * @throws PlaybackLoadException If the file contains errors * @throws IOException If the file could not be read */ - public static BigArrayList loadFromFile(File file) throws PlaybackLoadException, IOException { + public static BigArrayList loadFromFile(Path file) throws PlaybackLoadException, IOException { return loadFromFile(file, true); } - public static BigArrayList loadFromFile(File file, boolean processExtensions) throws PlaybackLoadException, IOException { + public static BigArrayList loadFromFile(Path file, boolean processExtensions) throws PlaybackLoadException, IOException { if (file == null) { throw new PlaybackLoadException("Load from file failed. No file specified"); } - if (!file.exists()) { - throw new PlaybackLoadException("Trying to load %s but the file doesn't exist", file.getName()); + if (!Files.exists(file)) { + throw new PlaybackLoadException("Trying to load %s but the file doesn't exist", file.getFileName().toString()); } SerialiserFlavorBase flavor = readFlavor(file); @@ -155,11 +156,11 @@ public static BigArrayList loadFromFile(File file, boolean proces * @throws PlaybackLoadException If the file contains errors * @throws IOException If the file could not be read */ - public static BigArrayList loadFromFile(File file, String flavorName) throws PlaybackLoadException, IOException { + public static BigArrayList loadFromFile(Path file, String flavorName) throws PlaybackLoadException, IOException { return loadFromFile(file, flavorName, true); } - public static BigArrayList loadFromFile(File file, String flavorName, boolean processExtensions) throws PlaybackLoadException, IOException { + public static BigArrayList loadFromFile(Path file, String flavorName, boolean processExtensions) throws PlaybackLoadException, IOException { // If the flavor is null or empty, try to determine the flavor by reading the header if (flavorName == null || flavorName.isEmpty()) { @@ -193,7 +194,7 @@ public static BigArrayList loadFromFile(File file, String flavorN * @throws PlaybackLoadException If the file contains errors * @throws IOException If the file could not be read */ - public static BigArrayList loadFromFile(File file, SerialiserFlavorBase flavor) throws PlaybackLoadException, IOException { + public static BigArrayList loadFromFile(Path file, SerialiserFlavorBase flavor) throws PlaybackLoadException, IOException { if (file == null) { throw new PlaybackLoadException("Load from file failed. No file specified"); } @@ -202,9 +203,9 @@ public static BigArrayList loadFromFile(File file, SerialiserFlav BufferedReader reader = null; try { - reader = new BufferedReader(new FileReader(file)); + reader = new BufferedReader(new FileReader(file.toFile())); } catch (FileNotFoundException e) { - throw new PlaybackLoadException("Trying to load %s, but the file doesn't exist", file.getName()); + throw new PlaybackLoadException("Trying to load %s, but the file doesn't exist", file.getFileName().toString()); } BigArrayList lines = new BigArrayList<>(); @@ -247,14 +248,14 @@ public static SerialiserFlavorBase searchForFlavor(List lines, List lines = new ArrayList<>(); diff --git a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/PlaybackSerialiserOld.java b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/PlaybackSerialiserOld.java index 589f3afd..79e2805c 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/PlaybackSerialiserOld.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/PlaybackSerialiserOld.java @@ -35,49 +35,49 @@ */ @Deprecated public class PlaybackSerialiserOld { - + /** * A list of sections to check for in the playback file * @author ScribbleLP * */ - public enum SectionsV1{ + public enum SectionsV1 { TICKS("Ticks", ""), KEYBOARD("Keyboard", "(\\|Keyboard:)"), MOUSE("Mouse", "(\\|Mouse:)"), CAMERA("Camera", "(\\|Camera:)"); - + private String name; private String regex; - + private SectionsV1(String nameIn, String regexIn) { - name=nameIn; - regex=regexIn; + name = nameIn; + regex = regexIn; } - + public String getName() { return name; } - + public String getRegex() { return regex; } - + public static String getRegexString() { - String out=""; - for(SectionsV1 section : values()) { - if(!section.getRegex().isEmpty()) { - String seperator="|"; - if(values().length-1==section.ordinal()) { - seperator=""; + String out = ""; + for (SectionsV1 section : values()) { + if (!section.getRegex().isEmpty()) { + String seperator = "|"; + if (values().length - 1 == section.ordinal()) { + seperator = ""; } - out=out.concat(section.getRegex()+seperator); + out = out.concat(section.getRegex() + seperator); } } return out; } } - + /** * Saves all inputs of the input container * @param file Where to save the container @@ -87,7 +87,7 @@ public static String getRegexString() { public void saveToFileV1(File file, PlaybackControllerClient container) throws IOException { saveToFileV1Until(file, container, -1); } - + /** * Saves inputs up to a certain index of the input container * @param file Where to save the container @@ -95,17 +95,17 @@ public void saveToFileV1(File file, PlaybackControllerClient container) throws I * @param index index until the inputs get saved * @throws IOException When the input container is empty */ - public void saveToFileV1Until(File file, PlaybackControllerClient container, long index) throws IOException{ + public void saveToFileV1Until(File file, PlaybackControllerClient container, long index) throws IOException { LOGGER.debug(LoggerMarkers.Playback, "Saving playback controller to file {}", file); if (container.size() == 0) { throw new IOException("There are no inputs to save to a file"); } - FileThread fileThread = new FileThread(file, false); + FileThread fileThread = new FileThread(file.toPath(), false); // FileThread monitorThread= new FileThread(new File(file, "../"+file.getName().replace(".mctas", "")+".mon"), false); fileThread.start(); // monitorThread.start(); - + // fileThread.addLine("################################################# TASFile ###################################################\n" // + "# Version:1 #\n" // + "# This file was generated using the Minecraft TASMod #\n" @@ -127,11 +127,11 @@ public void saveToFileV1Until(File file, PlaybackControllerClient container, lon // + "#StartSeed:" + container.getStartSeed() + "\n" // + "#############################################################################################################\n" // + "#Comments start with \"//\" at the start of the line, comments with # will not be saved\n"); - + BigArrayList ticks = container.getInputs(); // Map>> cbytes= container.getControlBytes(); // Map> comments = container.getComments(); - + // for (int i = 0; i < ticks.size(); i++) { // if(i==index) { // break; @@ -144,8 +144,8 @@ public void saveToFileV1Until(File file, PlaybackControllerClient container, lon // fileThread.addLine("//"+comment+"\n"); // }); // } - - // Add controlbytes + + // Add controlbytes // if(cbytes.containsKey(i)) { // List> cbytelist= cbytes.get(i); // String cbyteString= ControlByteHandler.toString(cbytelist); @@ -167,11 +167,11 @@ public int getFileVersion(File file) throws IOException { for (String line : lines) { if (line.contains("Version")) { String trimmed = line.replaceAll("#|\t", ""); - int tick=0; + int tick = 0; try { - tick=Integer.parseInt(trimmed.split(":")[1]); + tick = Integer.parseInt(trimmed.split(":")[1]); } catch (NumberFormatException e) { - throw new IOException("Can't read the file version: "+trimmed); + throw new IOException("Can't read the file version: " + trimmed); } return tick; } @@ -182,17 +182,17 @@ public int getFileVersion(File file) throws IOException { public PlaybackControllerClient fromEntireFileV1(File file) throws IOException { LOGGER.debug(LoggerMarkers.Playback, "Loading playback controller to file {}", file); List lines = FileUtils.readLines(file, StandardCharsets.UTF_8); - - File monitorFile=new File(file, "../"+file.getName().replace(".mctas", "")+".mon"); - - List monitorLines=new ArrayList<>(); - + + File monitorFile = new File(file, "../" + file.getName().replace(".mctas", "") + ".mon"); + + List monitorLines = new ArrayList<>(); + // Read the legacy monitoring file system. Still reads the file but deletes it afterwards - if(monitorFile.exists()) { + if (monitorFile.exists()) { monitorLines = FileUtils.readLines(monitorFile, StandardCharsets.UTF_8); monitorFile.delete(); } - boolean oldmonfileLoaded=!monitorLines.isEmpty(); + boolean oldmonfileLoaded = !monitorLines.isEmpty(); PlaybackControllerClient controller = new PlaybackControllerClient(); @@ -203,10 +203,10 @@ public PlaybackControllerClient fromEntireFileV1(File file) throws IOException { String playtime = "00:00.0"; int rerecords = 0; - + // No default start location - String startLocation=""; - + String startLocation = ""; + // Default the start seed to the current global ktrng seed. If KTRNG is not loaded, defaults to 0 long startSeed/*=TASmod.ktrngHandler.getGlobalSeedClient()*/; @@ -214,32 +214,32 @@ public PlaybackControllerClient fromEntireFileV1(File file) throws IOException { controller.clear(); int linenumber = 0; //The current line number - + for (String line : lines) { linenumber++; - int tickcount=(int) controller.getInputs().size(); + int tickcount = (int) controller.getInputs().size(); // Read out header if (line.startsWith("#")) { // Read author tag if (line.startsWith("#Author:")) { author = line.split(":")[1]; - // Read title tag + // Read title tag } else if (line.startsWith("#Title:")) { title = line.split(":")[1]; - // Read playtime + // Read playtime } else if (line.startsWith("#Playing Time:")) { playtime = line.split("Playing Time:")[1]; - // Read rerecords + // Read rerecords } else if (line.startsWith("#Rerecords:")) { rerecords = Integer.parseInt(line.split(":")[1]); - // Read start position + // Read start position } else if (line.startsWith("#StartPosition:")) { startLocation = line.replace("#StartPosition:", ""); - // Read start seed + // Read start seed } else if (line.startsWith("#StartSeed:")) { startSeed = Long.parseLong(line.replace("#StartSeed:", "")); } - // Read control bytes + // Read control bytes } else if (line.startsWith("$") && line.replace('$', ' ').trim().contains(" ")) { String[] sections = line.replace('$', ' ').trim().split(" ", 2); if (sections.length == 0) @@ -249,33 +249,33 @@ public PlaybackControllerClient fromEntireFileV1(File file) throws IOException { // List> cbytes = controller.getControlBytes().getOrDefault(tickcount, new ArrayList<>()); // cbytes.add(Pair.of(control, params)); // controller.getControlBytes().put(tickcount, cbytes); - //Read comments + //Read comments } else if (line.startsWith("//")) { // List commentList = controller.getComments().getOrDefault(tickcount, new ArrayList<>()); // commentList.add(line.replace("//", "")); // controller.getComments().put(tickcount, commentList); - //Read data + //Read data } else { - + // Splitting the line into a data- and commentPart, the comment part will most likely contain the Monitoring - String dataPart=line; - String commentPart=""; - if(line.contains("~&")) { - String[] splitComments=line.split("~&"); - dataPart=splitComments[0]; - commentPart=splitComments[1]; + String dataPart = line; + String commentPart = ""; + if (line.contains("~&")) { + String[] splitComments = line.split("~&"); + dataPart = splitComments[0]; + commentPart = splitComments[1]; } String[] sections = dataPart.split(SectionsV1.getRegexString()); if (sections.length != SectionsV1.values().length) { throw new IOException("Error in line " + linenumber + ". Cannot read the line correctly"); } - + // controller.getInputs().add(new TickInputContainer(readTicks(sections[0], linenumber), readKeyboard(sections[1], linenumber), readMouse(sections[2], linenumber), readSubtick(sections[3], linenumber))); - - if(!oldmonfileLoaded) { + + if (!oldmonfileLoaded) { String[] commentData = commentPart.split("Monitoring:"); - if(commentData.length==2) { + if (commentData.length == 2) { monitorLines.add(commentData[1]); } } @@ -287,15 +287,15 @@ public PlaybackControllerClient fromEntireFileV1(File file) throws IOException { // controller.setRerecords(rerecords); // controller.setStartLocation(startLocation); // controller.setStartSeed(startSeed); - if(!monitorLines.isEmpty()) { + if (!monitorLines.isEmpty()) { // controller.desyncMonitor = new DesyncMonitoringFileCommand(controller, monitorLines); } - + //If an old monitoring file is loaded, save the file immediately to not loose any data. - if(oldmonfileLoaded) { + if (oldmonfileLoaded) { saveToFileV1(file, controller); } - + return controller; } @@ -308,7 +308,7 @@ private int readTicks(String section, int linenumber) throws IOException { } return ticks; } - + private VirtualKeyboard readKeyboard(String section, int linenumber) throws IOException { VirtualKeyboard keyboard = new VirtualKeyboard(); @@ -346,13 +346,13 @@ private VirtualKeyboard readKeyboard(String section, int linenumber) throws IOEx // vkey.setPressed(true); } } - + char[] chars = {}; //Check if the characterlist is empty if (keys.length == 2) { chars = keys[1].replace("\\n", "\n").toCharArray(); //Replacing the "\n" in lines to the character \n } - + for (char onechar : chars) { // keyboard.addChar(onechar); } @@ -361,21 +361,21 @@ private VirtualKeyboard readKeyboard(String section, int linenumber) throws IOEx private VirtualMouse readMouse(String section, int linenumber) throws IOException { VirtualMouse mouse = new VirtualMouse(); - + // Remove the prefix section = section.replace("Mouse:", ""); - + //Split into buttons and paths... String buttons = section.split(";")[0]; String path = section.split(";")[1]; - + //Check whether the button is empty - if(!buttons.isEmpty()) { - + if (!buttons.isEmpty()) { + //Splitting multiple buttons - String[] splitButtons=buttons.split(","); + String[] splitButtons = buttons.split(","); for (String button : splitButtons) { - + // VirtualKey vkey = null; // // Check if the key is a keycode // if (isNumeric(button)) { @@ -428,25 +428,23 @@ private VirtualMouse readMouse(String section, int linenumber) throws IOExceptio // } // return path; // } - + private VirtualCameraAngle readSubtick(String section, int linenumber) throws IOException { section = section.replace("Camera:", ""); - String[] split=section.split(";"); - - float x=0F; - float y=0F; - + String[] split = section.split(";"); + + float x = 0F; + float y = 0F; + try { - x=Float.parseFloat(split[0]); - y=Float.parseFloat(split[1]); - } catch (NumberFormatException e){ - throw new IOException(split[0]+" or/and "+split[1]+" are not float numbers in line "+ linenumber); + x = Float.parseFloat(split[0]); + y = Float.parseFloat(split[1]); + } catch (NumberFormatException e) { + throw new IOException(split[0] + " or/and " + split[1] + " are not float numbers in line " + linenumber); } - + return new VirtualCameraAngle(x, y); } - - // private String getStartLocation() { // Minecraft mc = Minecraft.getMinecraft(); @@ -458,8 +456,8 @@ private VirtualCameraAngle readSubtick(String section, int linenumber) throws IO // String yaw = Float.toString(mc.player.rotationYaw); // return pos + "," + yaw + "," + pitch; // } - - private boolean isNumeric(String in){ + + private boolean isNumeric(String in) { try { Integer.parseInt(in); } catch (NumberFormatException e) { diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index 159a5259..85b2f581 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -50,7 +50,7 @@ */ public class SavestateHandlerClient implements ClientPacketHandler, EventSavestate.EventClientCompleteLoadstate, EventSavestate.EventClientLoadPlayer { - public final static File savestateDirectory = new File(TASmodClient.tasdirectory + File.separator + "savestates"); + public final static File savestateDirectory = TASmodClient.savestatedirectory.toFile(); //TODO Change to path... don't want to deal with this rn ._. /** * A bug occurs when unloading the client world. The client world has a @@ -128,9 +128,9 @@ public static void savestate(String nameOfSavestate) throws SavestateException, PlaybackControllerClient container = TASmodClient.controller; if (container.isRecording()) { - PlaybackSerialiser.saveToFile(targetfile, container, ""); // If the container is recording, store it entirely + PlaybackSerialiser.saveToFile(targetfile.toPath(), container, ""); // If the container is recording, store it entirely } else if (container.isPlayingback()) { - PlaybackSerialiser.saveToFile(targetfile, container, "", container.index()); // If the container is playing, store it until the current index + PlaybackSerialiser.saveToFile(targetfile.toPath(), container, "", container.index()); // If the container is playing, store it until the current index } } @@ -169,7 +169,7 @@ public static void loadstate(String nameOfSavestate) throws Exception { BigArrayList savestateContainerList; if (targetfile.exists()) { - savestateContainerList = PlaybackSerialiser.loadFromFile(targetfile, state != TASstate.PLAYBACK); + savestateContainerList = PlaybackSerialiser.loadFromFile(targetfile.toPath(), state != TASstate.PLAYBACK); } else { controller.setTASStateClient(TASstate.NONE, false); Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + "Inputs could not be loaded for this savestate,")); diff --git a/src/main/java/com/minecrafttas/tasmod/util/FileThread.java b/src/main/java/com/minecrafttas/tasmod/util/FileThread.java index 1ac9c31c..56f649b6 100644 --- a/src/main/java/com/minecrafttas/tasmod/util/FileThread.java +++ b/src/main/java/com/minecrafttas/tasmod/util/FileThread.java @@ -1,11 +1,13 @@ package com.minecrafttas.tasmod.util; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; @@ -15,22 +17,23 @@ * @author Pancake */ public class FileThread extends Thread { - + private final PrintWriter stream; private boolean end = false; - + private final List output = new ArrayList<>(); - - public FileThread(File fileLocation, boolean append) throws FileNotFoundException { - stream = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileLocation, append), StandardCharsets.UTF_8)); + + public FileThread(Path fileLocation, boolean append) throws IOException { + OutputStream outStream = Files.newOutputStream(fileLocation, StandardOpenOption.CREATE, StandardOpenOption.APPEND); + stream = new PrintWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8)); } - + public void addLine(String line) { synchronized (output) { output.add(line + "\n"); } } - + @Override public void run() { while (!end) { @@ -45,10 +48,11 @@ public void run() { stream.flush(); stream.close(); } - + public void close() { end = true; } + public void flush() { stream.flush(); } diff --git a/src/test/java/mctcommon/TestConfiguration.java b/src/test/java/mctcommon/TestConfiguration.java index 1aac0e79..27444d11 100644 --- a/src/test/java/mctcommon/TestConfiguration.java +++ b/src/test/java/mctcommon/TestConfiguration.java @@ -50,7 +50,7 @@ public String getExtensionName() { ConfigurationRegistry registry = new ConfigurationRegistry(); - private static final Path configPath = Paths.get("src/test/resources/config.xml"); + private static final Path configPath = Paths.get("src").resolve("test").resolve("resources").resolve("config.xml"); @BeforeEach void beforeEach() { diff --git a/src/test/java/tasmod/playback/tasfile/PlaybackSerialiserTest.java b/src/test/java/tasmod/playback/tasfile/PlaybackSerialiserTest.java index a640e3fe..e2678aba 100644 --- a/src/test/java/tasmod/playback/tasfile/PlaybackSerialiserTest.java +++ b/src/test/java/tasmod/playback/tasfile/PlaybackSerialiserTest.java @@ -6,13 +6,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.File; import java.io.IOException; import java.io.Serializable; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; -import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -118,7 +119,7 @@ public void onClear() { } } - File file; + Path file; private static TestFlavor testFlavor = new TestFlavor(); private static TestMetadatada testMetadata = new TestMetadatada(); @@ -132,9 +133,9 @@ static void register() { } @AfterEach - void afterEach() { + void afterEach() throws IOException { if (file != null) { - file.delete(); + Files.delete(file); } testMetadata.onClear(); @@ -152,7 +153,7 @@ static void unregister() { void testSerialiser() { BigArrayList expected = new BigArrayList<>(); - file = new File("src/test/resources/serialiser/PlaybackSerialiserTest.mctas"); + file = Paths.get("src/test/resources/serialiser/PlaybackSerialiserTest.mctas"); testMetadata.testValue = "testing"; TASmodAPIRegistry.PLAYBACK_FILE_COMMAND.setEnabled("tasmod_testFileExtension", true); @@ -202,6 +203,12 @@ void testSerialiser() { e.printStackTrace(); } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + try { BigArrayList actual = PlaybackSerialiser.loadFromFile(file, testFlavor); assertBigArrayList(expected, actual); @@ -229,9 +236,9 @@ void testDeserialiser() throws PlaybackLoadException, IOException { lines.add("3|;|-101;0,~1,~1|~1;~1"); lines.add("\t1|;|-101;0,~1,~1|~1;~1"); - file = new File("src/test/resources/serialiser/PlaybackSerialiserTest2.mctas"); + file = Paths.get("src/test/resources/serialiser/PlaybackSerialiserTest2.mctas"); try { - FileUtils.writeLines(file, lines); + Files.write(file, lines); } catch (IOException e) { e.printStackTrace(); } @@ -318,9 +325,9 @@ void testDeserialiserNoExtensions() throws PlaybackLoadException, IOException { lines.add("3|;|-101;0,~1,~1|~1;~1"); lines.add("\t1|;|-101;0,~1,~1|~1;~1"); - file = new File("src/test/resources/serialiser/PlaybackSerialiserTest3.mctas"); + file = Paths.get("src/test/resources/serialiser/PlaybackSerialiserTest3.mctas"); try { - FileUtils.writeLines(file, lines); + Files.write(file, lines); } catch (IOException e) { e.printStackTrace(); } @@ -374,9 +381,9 @@ void testFlavorNotFound() { lines.add("Test"); } - file = new File("src/test/resources/serialiser/PlaybackSerialiserTest3.mctas"); + file = Paths.get("src/test/resources/serialiser/PlaybackSerialiserTest3.mctas"); try { - FileUtils.writeLines(file, lines); + Files.write(file, lines); } catch (IOException e) { e.printStackTrace(); }