From 8f3bce7d6fe41e85f2654f7557bbb564305e58b5 Mon Sep 17 00:00:00 2001 From: matthias-luger <58751503+matthias-luger@users.noreply.github.com> Date: Fri, 17 Feb 2023 17:32:26 +0100 Subject: Add TFM Purchase UI to Mod (#78) * Add TFM Purchase UI to Mod * fix up opening flips by hotkey fix up flip message in tfm ui * readded check if the auction should be drawn mod doesnt crash anymore if a non flip auction is opened * added /cofl set gui command changed gui title * added /fc toggle command dont store toggle locally * rename purchaseOverlay config removed unused code renamed gui command to /cofl set ahbuygui * fix message not available if flip opened by mouse fix old message shown for non flip auctions * added /cofl setGui command added cofl purchase gui * Add sound on flip * Fixed new flip sound Optimized cofl gui Removed flickering of default mc gui Move mouse to middle on screen open * remove unused code * remove debug code * don't open guis if not in skyblock * fix sound being null * fix bed flips fix opening /cofl blocked * remove logging * Rewrote cofl gui to render before the chest gui opens * - fix bed flips - invalidate best flips after open * - fix scrolling * - fix description not updating - case insensitive commands - fix up , at the end of the message * - add gui if item was already bought - fix bug that invalidated too many flips - added missing "break" * fix merge error * add .vscode to gitignore formatting * fix formatting issue * - remove comment - remove emty line --- src/main/java/de/torui/coflsky/CoflSky.java | 82 ++-- src/main/java/de/torui/coflsky/CoflSkyCommand.java | 432 ++++++++++++--------- src/main/java/de/torui/coflsky/FlipHandler.java | 235 +++++------ .../java/de/torui/coflsky/FlipperChatCommand.java | 86 ++-- .../java/de/torui/coflsky/WSCommandHandler.java | 383 +++++++++--------- .../de/torui/coflsky/commands/models/FlipData.java | 22 +- .../torui/coflsky/configuration/LocalConfig.java | 12 +- src/main/java/de/torui/coflsky/gui/GUIType.java | 6 + .../de/torui/coflsky/gui/bingui/BinGuiCurrent.java | 415 ++++++++++++++++++++ .../de/torui/coflsky/gui/bingui/BinGuiManager.java | 19 + .../java/de/torui/coflsky/gui/bingui/BuyState.java | 8 + .../coflsky/gui/bingui/helper/ColorPallet.java | 25 ++ .../coflsky/gui/bingui/helper/GuiUtilsClone.java | 349 +++++++++++++++++ .../coflsky/gui/bingui/helper/RenderUtils.java | 367 +++++++++++++++++ .../de/torui/coflsky/gui/tfm/ButtonRemapper.java | 338 ++++++++++++++++ .../coflsky/gui/tfm/ChatMessageSendHandler.java | 32 ++ .../de/torui/coflsky/gui/tfm/ToolTipHelper.java | 55 +++ .../de/torui/coflsky/handlers/EventRegistry.java | 394 +++++++++---------- 18 files changed, 2471 insertions(+), 789 deletions(-) create mode 100644 src/main/java/de/torui/coflsky/gui/GUIType.java create mode 100644 src/main/java/de/torui/coflsky/gui/bingui/BinGuiCurrent.java create mode 100644 src/main/java/de/torui/coflsky/gui/bingui/BinGuiManager.java create mode 100644 src/main/java/de/torui/coflsky/gui/bingui/BuyState.java create mode 100644 src/main/java/de/torui/coflsky/gui/bingui/helper/ColorPallet.java create mode 100644 src/main/java/de/torui/coflsky/gui/bingui/helper/GuiUtilsClone.java create mode 100644 src/main/java/de/torui/coflsky/gui/bingui/helper/RenderUtils.java create mode 100644 src/main/java/de/torui/coflsky/gui/tfm/ButtonRemapper.java create mode 100644 src/main/java/de/torui/coflsky/gui/tfm/ChatMessageSendHandler.java create mode 100644 src/main/java/de/torui/coflsky/gui/tfm/ToolTipHelper.java (limited to 'src/main/java/de') diff --git a/src/main/java/de/torui/coflsky/CoflSky.java b/src/main/java/de/torui/coflsky/CoflSky.java index 7eba195..a1498ba 100644 --- a/src/main/java/de/torui/coflsky/CoflSky.java +++ b/src/main/java/de/torui/coflsky/CoflSky.java @@ -6,15 +6,16 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; - import com.google.gson.Gson; import de.torui.coflsky.configuration.LocalConfig; +import de.torui.coflsky.gui.GUIType; import de.torui.coflsky.handlers.EventRegistry; import de.torui.coflsky.listeners.ChatListener; import de.torui.coflsky.proxy.APIKeyManager; +import de.torui.coflsky.gui.tfm.ButtonRemapper; +import de.torui.coflsky.gui.tfm.ChatMessageSendHandler; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.lwjgl.input.Keyboard; - import de.torui.coflsky.network.WSClientWrapper; import net.minecraft.client.settings.KeyBinding; import net.minecraftforge.client.ClientCommandHandler; @@ -26,11 +27,10 @@ import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.relauncher.Side; @Mod(modid = CoflSky.MODID, version = CoflSky.VERSION) -public class CoflSky -{ +public class CoflSky { public static final String MODID = "CoflSky"; - public static final String VERSION = "1.4.4-Alpha"; - + public static final String VERSION = "1.5.0-Alpha"; + public static WSClientWrapper Wrapper; public static KeyBinding[] keyBindings; @@ -38,14 +38,14 @@ public class CoflSky public static File configFile; private File coflDir; public static LocalConfig config; - - public static final String[] webSocketURIPrefix = new String [] { - "wss://sky.coflnet.com/modsocket", - "wss://sky-mod.coflnet.com/modsocket", - "ws://sky.coflnet.com/modsocket", - "ws://sky-mod.coflnet.com/modsocket", + + public static final String[] webSocketURIPrefix = new String[]{ + "wss://sky.coflnet.com/modsocket", + "wss://sky-mod.coflnet.com/modsocket", + "ws://sky.coflnet.com/modsocket", + "ws://sky-mod.coflnet.com/modsocket", }; - + public static String CommandUri = Config.BaseUrl + "/api/mod/commands"; private final static APIKeyManager apiKeyManager = new APIKeyManager(); @@ -66,12 +66,12 @@ public class CoflSky e.printStackTrace(); } if (config == null) { - config = LocalConfig.createDefaultConfig(); + config = LocalConfig.createDefaultConfig(); } try { this.apiKeyManager.loadIfExists(); - }catch (Exception exception){ + } catch (Exception exception) { exception.printStackTrace(); } @@ -82,44 +82,42 @@ public class CoflSky } @EventHandler - public void init(FMLInitializationEvent event) throws URISyntaxException - { - System.out.println(">>>Started"); - + public void init(FMLInitializationEvent event) { CoflSky.Wrapper = new WSClientWrapper(webSocketURIPrefix); - - keyBindings = new KeyBinding[] { - new KeyBinding("key.replay_last.onclick", Keyboard.KEY_NONE, "SkyCofl"), - new KeyBinding("key.start_highest_bid", Keyboard.KEY_NONE, "SkyCofl") + + keyBindings = new KeyBinding[]{ + new KeyBinding("key.replay_last.onclick", Keyboard.KEY_NONE, "SkyCofl"), + new KeyBinding("key.start_highest_bid", Keyboard.KEY_NONE, "SkyCofl") }; - - if(event.getSide() == Side.CLIENT) { - ClientCommandHandler.instance.registerCommand(new CoflSkyCommand()); - ClientCommandHandler.instance.registerCommand(new ColfCommand()); - ClientCommandHandler.instance.registerCommand(new FlipperChatCommand()); - - for (int i = 0; i < keyBindings.length; ++i) - { - ClientRegistry.registerKeyBinding(keyBindings[i]); - } - - - } + + if (event.getSide() == Side.CLIENT) { + ClientCommandHandler.instance.registerCommand(new CoflSkyCommand()); + ClientCommandHandler.instance.registerCommand(new ColfCommand()); + ClientCommandHandler.instance.registerCommand(new FlipperChatCommand()); + + for (int i = 0; i < keyBindings.length; ++i) { + ClientRegistry.registerKeyBinding(keyBindings[i]); + } + + + } Events = new EventRegistry(); MinecraftForge.EVENT_BUS.register(Events); - + if (config.purchaseOverlay == GUIType.TFM) { + MinecraftForge.EVENT_BUS.register(ButtonRemapper.getInstance()); + } + MinecraftForge.EVENT_BUS.register(new ChatMessageSendHandler()); Runtime.getRuntime().addShutdownHook(new Thread(() -> { - config.saveConfig(configFile , config); + config.saveConfig(configFile, config); try { apiKeyManager.saveKey(); - }catch (Exception exception){ + } catch (Exception exception) { exception.printStackTrace(); } })); - } - + } - public static APIKeyManager getAPIKeyManager(){ + public static APIKeyManager getAPIKeyManager() { return apiKeyManager; } diff --git a/src/main/java/de/torui/coflsky/CoflSkyCommand.java b/src/main/java/de/torui/coflsky/CoflSkyCommand.java index de82f12..880127c 100644 --- a/src/main/java/de/torui/coflsky/CoflSkyCommand.java +++ b/src/main/java/de/torui/coflsky/CoflSkyCommand.java @@ -1,14 +1,16 @@ package de.torui.coflsky; import java.io.IOException; -import java.util.Arrays; -import java.util.Base64; -import java.util.List; +import java.util.*; import de.torui.coflsky.commands.Command; import de.torui.coflsky.commands.CommandType; import de.torui.coflsky.commands.JsonStringCommand; import de.torui.coflsky.commands.RawCommand; +import de.torui.coflsky.commands.models.FlipData; +import de.torui.coflsky.gui.GUIType; +import de.torui.coflsky.gui.bingui.BinGuiManager; +import de.torui.coflsky.gui.tfm.ButtonRemapper; import de.torui.coflsky.minecraft_integration.CoflSessionManager; import de.torui.coflsky.minecraft_integration.CoflSessionManager.CoflSession; import de.torui.coflsky.network.QueryServerCommands; @@ -20,201 +22,245 @@ import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.event.ClickEvent; import net.minecraft.event.ClickEvent.Action; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; -import java.util.ArrayList; +import net.minecraftforge.common.MinecraftForge; public class CoflSkyCommand extends CommandBase { - - @Override - public int getRequiredPermissionLevel() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public String getCommandName() { - return "cofl"; - } - @Override - public List getCommandAliases() - { - ArrayList al = new ArrayList(); - al.add("Cofl"); - al.add("coflnet"); - al.add("cl"); - return al; - } - - @Override - public String getCommandUsage(ICommandSender sender) { - return HelpText; - } - - public static final String HelpText = "Available local sub-commands:\n" - + "§bstart: §7starts a new connection\n" - + "§bstop: §7stops the connection\n" - + "§bconnect: §7Connects to a different server\n" - + "§breset: §7resets all local session information and stops the connection\n" - + "§bstatus: §7Emits status information\nServer-Only Commands:"; - @Override - public void processCommand(ICommandSender sender, String[] args) throws CommandException { - new Thread(()->{ - System.out.println(Arrays.toString(args)); - - if(args.length >= 1) { - switch(args[0]) { - case "start": - //todo: start - //possible workaround for https://github.com/Coflnet/SkyblockMod/issues/48 - CoflSky.Wrapper.stop(); - sender.addChatMessage(new ChatComponentText("starting connection...")); - CoflSky.Wrapper.startConnection(); - break; - case "stop": - CoflSky.Wrapper.stop(); - sender.addChatMessage(new ChatComponentText("you stopped the connection to ") - .appendSibling(new ChatComponentText("C").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_BLUE))) - .appendSibling(new ChatComponentText("oflnet").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GOLD))) - .appendSibling(new ChatComponentText(".\n To reconnect enter ")) - .appendSibling(new ChatComponentText("\"").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA))) - .appendSibling(new ChatComponentText("/cofl start")) - .appendSibling(new ChatComponentText("\"").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA))) - .appendSibling(new ChatComponentText(" or click this message")) - .setChatStyle(new ChatStyle().setChatClickEvent(new ClickEvent(Action.RUN_COMMAND, "/cofl start"))) - ); - break; - case "debug": - // WSCommandHandler.HandleCommand(new Command(CommandType.Execute, "/me hewwo"), sender.getCommandSenderEntity()); - // WSCommandHandler.HandleCommand(new Command(CommandType.WriteToChat, " {\"type\":\"writeToChat\",\"data\":\"{\\\"text\\\":\\\"\\\\nFLIP: º9Goblin Eg\r\n" - // + "g º87,000 -> 13,999 ºg[BUY]\\\",\\\"onClick\\\":\\\"/viewauction f7d7295ca72f43e9876bf6da7424000c\\\",\\\"hover\\\":\\\"\\\"}\"}"), sender.getCommandSenderEntity()); - //WSCommandHandler.HandleCommand(new Command(CommandType.PlaySound, "{\"name\":\"random.orb\",\"pitch\":0.5}"), sender.getCommandSenderEntity()); - break; - case "callback": - CallbackCommand(args); - break; - case "dev": - if(Config.BaseUrl.contains("localhost")) { - CoflSky.Wrapper.startConnection(); - Config.BaseUrl = "https://sky.coflnet.com"; - } else { - CoflSky.Wrapper.initializeNewSocket("ws://localhost:8009/modsocket"); - Config.BaseUrl = "http://localhost:5005"; - } - sender.addChatMessage(new ChatComponentText("toggled dev mode, now using " + Config.BaseUrl)); - break; - case "status": - sender.addChatMessage(new ChatComponentText(StatusMessage())); - break; - case "reset": - HandleReset(); - break; - case "connect": - - if(args.length == 2) { - String destination = args[1]; - - if(!destination.contains("://")) { - destination = new String(Base64.getDecoder().decode(destination)); - } - sender.addChatMessage(new ChatComponentText("Stopping connection!")); - CoflSky.Wrapper.stop(); - sender.addChatMessage(new ChatComponentText("Opening connection to " + destination)); - if(CoflSky.Wrapper.initializeNewSocket(destination)) { - sender.addChatMessage(new ChatComponentText("Success")); - } else { - sender.addChatMessage(new ChatComponentText("Could not open connection, please check the logs")); - } - } else { - sender.addChatMessage(new ChatComponentText("§cPleace specify a server to connect to")); - } - break; - default: - SendCommandToServer(args, sender); - return; - } - } - - else { - ListHelp(sender); - } - }).start(); - } - - private void HandleReset() { - CoflSky.Wrapper.SendMessage(new Command(CommandType.Reset,"")); - CoflSky.Wrapper.stop(); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Stopping Connection to CoflNet")); - CoflSessionManager.DeleteAllCoflSessions(); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Deleting CoflNet sessions...")); - if(CoflSky.Wrapper.startConnection()) - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Started the Connection to CoflNet")); - } - - public String StatusMessage() { - - String vendor = System.getProperty("java.vm.vendor"); - String name = System.getProperty("java.vm.name"); - String version = System.getProperty("java.version"); - String detailedVersion = System.getProperty("java.vm.version"); - - String status = vendor + " " + name + " " + version + " " + detailedVersion + "|Connection = " + (CoflSky.Wrapper!=null?CoflSky.Wrapper.GetStatus():"UNINITIALIZED_WRAPPER"); - try { - status += " uri=" + CoflSky.Wrapper.socket.uri.toString(); - } catch(NullPointerException npe) {} - - - try { - CoflSession session = CoflSessionManager.GetCoflSession(PlayerDataProvider.getUsername()); - String sessionString = CoflSessionManager.gson.toJson(session); - status += " session=" + sessionString; - } catch (IOException e) { - } - - return status; - } - - public void SendCommandToServer(String[] args, ICommandSender sender) { - String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); - - //JsonStringCommand sc = new JsonStringCommand(args[0], WSClient.gson.toJson(command)); - RawCommand rc = new RawCommand(args[0], WSClient.gson.toJson(command)); - if(CoflSky.Wrapper.isRunning) { - CoflSky.Wrapper.SendMessage(rc); - } else { - SendAfterStart(sender, rc); - } - } - - private static synchronized void SendAfterStart(ICommandSender sender, RawCommand rc) { - sender.addChatMessage(new ChatComponentText("CoflSky wasn't active.").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); - //CoflSky.Wrapper.stop(); - CoflSky.Wrapper.startConnection(); - CoflSky.Wrapper.SendMessage(rc); - } - - public void ListHelp(ICommandSender sender) { - sender.addChatMessage(new ChatComponentText(HelpText)); - sender.addChatMessage(new ChatComponentText(QueryServerCommands.QueryCommands())); - } - - public void CallbackCommand(String[] args) { - - String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); - System.out.println("CallbackData: " + command); - //new Thread(()->{ - System.out.println("Callback: " + command); - WSCommandHandler.HandleCommand(new JsonStringCommand(CommandType.Execute, WSClient.gson.toJson(command)), Minecraft.getMinecraft().thePlayer); - CoflSky.Wrapper.SendMessage(new JsonStringCommand(CommandType.Clicked, WSClient.gson.toJson(command))); - - System.out.println("Sent!"); - //}).start(); - - } + + @Override + public int getRequiredPermissionLevel() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getCommandName() { + return "cofl"; + } + + @Override + public List getCommandAliases() { + ArrayList al = new ArrayList(); + al.add("Cofl"); + al.add("coflnet"); + al.add("cl"); + return al; + } + + @Override + public String getCommandUsage(ICommandSender sender) { + return HelpText; + } + + public static final String HelpText = "Available local sub-commands:\n" + + "§bstart: §7starts a new connection\n" + + "§bstop: §7stops the connection\n" + + "§bconnect: §7Connects to a different server\n" + + "§breset: §7resets all local session information and stops the connection\n" + + "§bstatus: §7Emits status information\nServer-Only Commands:"; + + @Override + public void processCommand(ICommandSender sender, String[] args) throws CommandException { + new Thread(() -> { + System.out.println(Arrays.toString(args)); + + if (args.length >= 1) { + switch (args[0].toLowerCase()) { + case "start": + //todo: start + //possible workaround for https://github.com/Coflnet/SkyblockMod/issues/48 + CoflSky.Wrapper.stop(); + sender.addChatMessage(new ChatComponentText("starting connection...")); + CoflSky.Wrapper.startConnection(); + break; + case "stop": + CoflSky.Wrapper.stop(); + sender.addChatMessage(new ChatComponentText("you stopped the connection to ") + .appendSibling(new ChatComponentText("C").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_BLUE))) + .appendSibling(new ChatComponentText("oflnet").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GOLD))) + .appendSibling(new ChatComponentText(".\n To reconnect enter ")) + .appendSibling(new ChatComponentText("\"").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA))) + .appendSibling(new ChatComponentText("/cofl start")) + .appendSibling(new ChatComponentText("\"").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA))) + .appendSibling(new ChatComponentText(" or click this message")) + .setChatStyle(new ChatStyle().setChatClickEvent(new ClickEvent(Action.RUN_COMMAND, "/cofl start"))) + ); + break; + case "debug": + // WSCommandHandler.HandleCommand(new Command(CommandType.Execute, "/me hewwo"), sender.getCommandSenderEntity()); + // WSCommandHandler.HandleCommand(new Command(CommandType.WriteToChat, " {\"type\":\"writeToChat\",\"data\":\"{\\\"text\\\":\\\"\\\\nFLIP: º9Goblin Eg\r\n" + // + "g º87,000 -> 13,999 ºg[BUY]\\\",\\\"onClick\\\":\\\"/viewauction f7d7295ca72f43e9876bf6da7424000c\\\",\\\"hover\\\":\\\"\\\"}\"}"), sender.getCommandSenderEntity()); + //WSCommandHandler.HandleCommand(new Command(CommandType.PlaySound, "{\"name\":\"random.orb\",\"pitch\":0.5}"), sender.getCommandSenderEntity()); + break; + case "callback": + CallbackCommand(args); + break; + case "dev": + if (Config.BaseUrl.contains("localhost")) { + CoflSky.Wrapper.startConnection(); + Config.BaseUrl = "https://sky.coflnet.com"; + } else { + CoflSky.Wrapper.initializeNewSocket("ws://localhost:8009/modsocket"); + Config.BaseUrl = "http://localhost:5005"; + } + sender.addChatMessage(new ChatComponentText("toggled dev mode, now using " + Config.BaseUrl)); + break; + case "status": + sender.addChatMessage(new ChatComponentText(StatusMessage())); + break; + case "reset": + HandleReset(); + break; + case "connect": + if (args.length == 2) { + String destination = args[1]; + + if (!destination.contains("://")) { + destination = new String(Base64.getDecoder().decode(destination)); + } + sender.addChatMessage(new ChatComponentText("Stopping connection!")); + CoflSky.Wrapper.stop(); + sender.addChatMessage(new ChatComponentText("Opening connection to " + destination)); + if (CoflSky.Wrapper.initializeNewSocket(destination)) { + sender.addChatMessage(new ChatComponentText("Success")); + } else { + sender.addChatMessage(new ChatComponentText("Could not open connection, please check the logs")); + } + } else { + sender.addChatMessage(new ChatComponentText("§cPleace specify a server to connect to")); + } + break; + case "openauctiongui": + FlipData flip = WSCommandHandler.flipHandler.fds.getFlipById(args[1]); + boolean shouldInvalidate = args.length >= 3 && args[2].equals("true"); + + + // Is not a stored flip -> just open the auction + if (flip == null) { + WSCommandHandler.flipHandler.lastClickedFlipMessage = ""; + Minecraft.getMinecraft().thePlayer.sendChatMessage("/viewauction " + args[1]); + return; + } + + String oneLineMessage = String.join(" ", flip.getMessageAsString()).replaceAll("\n", "").split(",§7 sellers ah")[0]; + + if (shouldInvalidate) { + WSCommandHandler.flipHandler.fds.InvalidateFlip(flip); + } + + WSCommandHandler.flipHandler.lastClickedFlipMessage = oneLineMessage; + + BinGuiManager.openNewFlipGui(oneLineMessage, flip.Render); + + Minecraft.getMinecraft().thePlayer.sendChatMessage("/viewauction " + flip.Id); + break; + case "setgui": + if (args.length != 2) { + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Available GUIs:")); + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Cofl")); + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7TFM")); + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Off")); + return; + } + + if (args[1].equalsIgnoreCase("cofl")) { + CoflSky.config.purchaseOverlay = GUIType.COFL; + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Set §bPurchase Overlay §7to: §fCofl")); + MinecraftForge.EVENT_BUS.unregister(ButtonRemapper.getInstance()); + } + if (args[1].equalsIgnoreCase("tfm")) { + CoflSky.config.purchaseOverlay = GUIType.TFM; + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Set §bPurchase Overlay §7to: §fTFM")); + MinecraftForge.EVENT_BUS.register(ButtonRemapper.getInstance()); + } + if (args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("false")) { + CoflSky.config.purchaseOverlay = null; + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Set §bPurchase Overlay §7to: §fOff")); + MinecraftForge.EVENT_BUS.unregister(ButtonRemapper.getInstance()); + } + break; + default: + SendCommandToServer(args, sender); + } + } else { + ListHelp(sender); + } + }).start(); + } + + private void HandleReset() { + CoflSky.Wrapper.SendMessage(new Command(CommandType.Reset, "")); + CoflSky.Wrapper.stop(); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Stopping Connection to CoflNet")); + CoflSessionManager.DeleteAllCoflSessions(); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Deleting CoflNet sessions...")); + if (CoflSky.Wrapper.startConnection()) + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Started the Connection to CoflNet")); + } + + public String StatusMessage() { + + String vendor = System.getProperty("java.vm.vendor"); + String name = System.getProperty("java.vm.name"); + String version = System.getProperty("java.version"); + String detailedVersion = System.getProperty("java.vm.version"); + + String status = vendor + " " + name + " " + version + " " + detailedVersion + "|Connection = " + (CoflSky.Wrapper != null ? CoflSky.Wrapper.GetStatus() : "UNINITIALIZED_WRAPPER"); + try { + status += " uri=" + CoflSky.Wrapper.socket.uri.toString(); + } catch (NullPointerException npe) { + } + + + try { + CoflSession session = CoflSessionManager.GetCoflSession(PlayerDataProvider.getUsername()); + String sessionString = CoflSessionManager.gson.toJson(session); + status += " session=" + sessionString; + } catch (IOException e) { + } + + return status; + } + + public void SendCommandToServer(String[] args, ICommandSender sender) { + String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); + + //JsonStringCommand sc = new JsonStringCommand(args[0], WSClient.gson.toJson(command)); + RawCommand rc = new RawCommand(args[0], WSClient.gson.toJson(command)); + if (CoflSky.Wrapper.isRunning) { + CoflSky.Wrapper.SendMessage(rc); + } else { + SendAfterStart(sender, rc); + } + } + + private static synchronized void SendAfterStart(ICommandSender sender, RawCommand rc) { + sender.addChatMessage(new ChatComponentText("CoflSky wasn't active.").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); + //CoflSky.Wrapper.stop(); + CoflSky.Wrapper.startConnection(); + CoflSky.Wrapper.SendMessage(rc); + } + + public void ListHelp(ICommandSender sender) { + sender.addChatMessage(new ChatComponentText(HelpText)); + sender.addChatMessage(new ChatComponentText(QueryServerCommands.QueryCommands())); + } + + public void CallbackCommand(String[] args) { + + String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); + System.out.println("CallbackData: " + command); + //new Thread(()->{ + System.out.println("Callback: " + command); + WSCommandHandler.HandleCommand(new JsonStringCommand(CommandType.Execute, WSClient.gson.toJson(command)), Minecraft.getMinecraft().thePlayer); + CoflSky.Wrapper.SendMessage(new JsonStringCommand(CommandType.Clicked, WSClient.gson.toJson(command))); + + System.out.println("Sent!"); + //}).start(); + + } } diff --git a/src/main/java/de/torui/coflsky/FlipHandler.java b/src/main/java/de/torui/coflsky/FlipHandler.java index 0c89f21..d3b683e 100644 --- a/src/main/java/de/torui/coflsky/FlipHandler.java +++ b/src/main/java/de/torui/coflsky/FlipHandler.java @@ -1,122 +1,127 @@ package de.torui.coflsky; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; +import de.torui.coflsky.commands.models.FlipData; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class FlipHandler { - public static class Flip { - public String id; - public int worth; - - public Flip(String id, int worth) { - super(); - this.id = id; - this.worth = worth; - } - - public Flip() { - - } - - } - - public static class FlipDataStructure { - - private Map Flips = new ConcurrentHashMap <>(); - private Map ReverseMap = new ConcurrentHashMap <>(); - - private Flip HighestFlip = null; - - private Timer t = new Timer(); - private TimerTask CurrentTask = null; - - public synchronized void RunHouseKeeping() { - synchronized (Flips) { - - Long RemoveAllPrior = System.currentTimeMillis() - (Config.KeepFlipsForSeconds*1000); - Flips.keySet().stream().filter(l -> l <= RemoveAllPrior).forEach(l -> RemoveLong(l)); - if (!Flips.isEmpty()) { - HighestFlip = Flips.values().stream().max((f1, f2) -> f1.worth - f2.worth).orElse(null); - } else { - HighestFlip = null; - } - } - - if (CurrentTask != null) { - CurrentTask.cancel(); - CurrentTask = null; - t.purge(); - } - if (!Flips.isEmpty()) { - CurrentTask = new TimerTask() { - @Override - public void run() { - RunHouseKeeping(); - } - }; - t.schedule(CurrentTask, Config.KeepFlipsForSeconds * 1000 + /* small arbitrary delay */150); - } - } - - public synchronized void Insert(Flip flip) { - Long l = System.currentTimeMillis(); - - synchronized(Flips) { - Flips.put(l, flip); - ReverseMap.put(flip, l); - } - - RunHouseKeeping(); - } - - private void RemoveLong(Long l) { - if (l == null) - return; - synchronized(Flips) { - Flip f = Flips.get(l); - if (f != null) { - ReverseMap.remove(f); - Flips.remove(l); - } - } - } - - private void RemoveFlip(Flip f) { - if (f == null) - return; - - synchronized(Flips) { - Long l = ReverseMap.get(f); - if (l != null) { - Flips.remove(l); - ReverseMap.remove(f); - } - } - } - - public Flip GetHighestFlip() { - return HighestFlip; - } - - public void InvalidateFlip(Flip flip) { - RemoveFlip(flip); - RunHouseKeeping(); - } - - public int CurrentFlips() { - return Flips.size(); - } - - } - - public FlipDataStructure fds; - - public FlipHandler() { - fds = new FlipDataStructure(); - } + + public static class FlipDataStructure { + + private Map Flips = new ConcurrentHashMap<>(); + private Map ReverseMap = new ConcurrentHashMap<>(); + + private FlipData HighestFlip = null; + private FlipData LastFlip = null; + + private Timer t = new Timer(); + private TimerTask CurrentTask = null; + + public synchronized void RunHouseKeeping() { + synchronized (Flips) { + + Long RemoveAllPrior = System.currentTimeMillis() - (Config.KeepFlipsForSeconds * 1000); + Flips.keySet().stream().filter(l -> l <= RemoveAllPrior).forEach(l -> RemoveLong(l)); + if (!Flips.isEmpty()) { + HighestFlip = Flips.values().stream().max((f1, f2) -> f1.Worth - f2.Worth).orElse(null); + } else { + HighestFlip = null; + } + } + + if (CurrentTask != null) { + CurrentTask.cancel(); + CurrentTask = null; + t.purge(); + } + if (!Flips.isEmpty()) { + CurrentTask = new TimerTask() { + @Override + public void run() { + RunHouseKeeping(); + } + }; + t.schedule(CurrentTask, Config.KeepFlipsForSeconds * 1000 + /* small arbitrary delay */150); + } + } + + public synchronized void Insert(FlipData flip) { + Long l = System.currentTimeMillis(); + LastFlip = flip; + + synchronized (Flips) { + Flips.put(l, flip); + ReverseMap.put(flip, l); + } + + RunHouseKeeping(); + } + + private void RemoveLong(Long l) { + if (l == null) + return; + synchronized (Flips) { + FlipData f = Flips.get(l); + if (f != null) { + ReverseMap.remove(f); + Flips.remove(l); + } + } + } + + private void RemoveFlip(FlipData f) { + if (f == null) + return; + + synchronized (Flips) { + Long l = ReverseMap.get(f); + if (l != null) { + Flips.remove(l); + ReverseMap.remove(f); + } + } + } + + public FlipData GetHighestFlip() { + return HighestFlip; + } + + public FlipData GetLastFlip() { + if (LastFlip == null) { + return null; + } + Long l = ReverseMap.get(LastFlip); + if (l == null) { + LastFlip = null; + } + return LastFlip; + } + + public FlipData getFlipById(String id) { + FlipData[] flips = Flips.values().stream().filter(flipData -> flipData.Id.equals(id)).toArray(FlipData[]::new); + Flips.forEach((key, value) -> System.out.println(value.Id)); + if (flips.length == 0) { + return null; + } + return flips[0]; + } + + public void InvalidateFlip(FlipData flip) { + RemoveFlip(flip); + RunHouseKeeping(); + } + + public int CurrentFlips() { + return Flips.size(); + } + + } + + public FlipDataStructure fds; + public String lastClickedFlipMessage; + + public FlipHandler() { + fds = new FlipDataStructure(); + } } diff --git a/src/main/java/de/torui/coflsky/FlipperChatCommand.java b/src/main/java/de/torui/coflsky/FlipperChatCommand.java index 618348e..9fe597f 100644 --- a/src/main/java/de/torui/coflsky/FlipperChatCommand.java +++ b/src/main/java/de/torui/coflsky/FlipperChatCommand.java @@ -1,61 +1,47 @@ package de.torui.coflsky; -import java.io.IOException; -import java.util.Arrays; -import java.util.Base64; import java.util.List; - -import de.torui.coflsky.commands.Command; -import de.torui.coflsky.commands.CommandType; -import de.torui.coflsky.commands.JsonStringCommand; -import de.torui.coflsky.commands.RawCommand; -import de.torui.coflsky.minecraft_integration.CoflSessionManager; -import de.torui.coflsky.minecraft_integration.CoflSessionManager.CoflSession; -import de.torui.coflsky.network.QueryServerCommands; -import de.torui.coflsky.network.WSClient; -import de.torui.coflsky.minecraft_integration.PlayerDataProvider; -import net.minecraft.client.Minecraft; -import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; -import net.minecraft.event.ClickEvent; -import net.minecraft.event.ClickEvent.Action; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentText; -import net.minecraft.util.ChatStyle; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; + import java.util.ArrayList; public class FlipperChatCommand extends CoflSkyCommand { - - @Override - public String getCommandName() { - return "fc"; - } - - @Override - public List getCommandAliases() - { - ArrayList al = new ArrayList(); - al.add("coflchat"); - return al; - } - - @Override - public String getCommandUsage(ICommandSender sender) { - return "Shorthand for /cofl chat"; - } - - @Override - public void processCommand(ICommandSender sender, String[] args) throws CommandException { - new Thread(()->{ - String[] newArgs = new String[args.length +1]; - System.arraycopy(args, 0, newArgs, 1, args.length); - newArgs[0] = "chat"; - SendCommandToServer(newArgs, sender); - }).start(); - } + public static boolean useChatOnlyMode = false; + + + @Override + public String getCommandName() { + return "fc"; + } + + @Override + public List getCommandAliases() { + ArrayList al = new ArrayList(); + al.add("coflchat"); + return al; + } + + @Override + public String getCommandUsage(ICommandSender sender) { + return "Shorthand for /cofl chat"; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) throws CommandException { + new Thread(() -> { + + if (args.length == 1 && args[0].equals("toggle")) { + FlipperChatCommand.useChatOnlyMode = !FlipperChatCommand.useChatOnlyMode; + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Set §bChat only mode §7to: §f" + (FlipperChatCommand.useChatOnlyMode ? "true" : "false"))); + } else { + String[] newArgs = new String[args.length + 1]; + System.arraycopy(args, 0, newArgs, 1, args.length); + newArgs[0] = "chat"; + SendCommandToServer(newArgs, sender); + } + }).start(); + } } diff --git a/src/main/java/de/torui/coflsky/WSCommandHandler.java b/src/main/java/de/torui/coflsky/WSCommandHandler.java index 0d37851..83e9222 100644 --- a/src/main/java/de/torui/coflsky/WSCommandHandler.java +++ b/src/main/java/de/torui/coflsky/WSCommandHandler.java @@ -12,6 +12,7 @@ import de.torui.coflsky.configuration.ConfigurationManager; import de.torui.coflsky.handlers.EventRegistry; import de.torui.coflsky.proxy.ProxyManager; import de.torui.coflsky.utils.FileUtils; +import de.torui.coflsky.commands.models.TimerData; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.audio.SoundHandler; @@ -30,190 +31,206 @@ import net.minecraftforge.fml.common.ModContainer; import java.io.File; +import java.util.Arrays; +import java.util.stream.Stream; + public class WSCommandHandler { - public static transient String lastOnClickEvent; - public static FlipHandler flipHandler = new FlipHandler(); - private static final ModListData modListData = new ModListData(); - private static final Gson gson = new Gson(); - private static final ProxyManager proxyManager = new ProxyManager(); - - public static boolean HandleCommand(JsonStringCommand cmd, Entity sender) { - // Entity sender = Minecraft.getMinecraft().thePlayer; - System.out.println("Handling Command=" + cmd.toString()); - - switch (cmd.getType()) { - case WriteToChat: - WriteToChat(cmd.GetAs(new TypeToken() {})); - break; - case Execute: - Execute(cmd.GetAs(new TypeToken() {}), sender); - break; - case PlaySound: - PlaySound(cmd.GetAs(new TypeToken() {}), sender); - break; - case ChatMessage: - ChatMessage(cmd.GetAs(new TypeToken() {})); - break; - case Flip: - Flip(cmd.GetAs(new TypeToken() {})); - break; - case PrivacySettings: - new ConfigurationManager().UpdateConfiguration(cmd.getData()); - case Countdown: - StartTimer(cmd.GetAs(new TypeToken() {})); - break; - case GetMods: - getMods(); - break; - case ProxyRequest: - handleProxyRequest(cmd.GetAs(new TypeToken() {}).getData()); - break; - default: - break; - } - - return true; - } - - private static void handleProxyRequest(ProxyRequest[] request){ - for(ProxyRequest req : request){ - proxyManager.handleRequestAsync(req); - } - } - - - public static void cacheMods(){ - File modFolder = new File(Minecraft.getMinecraft().mcDataDir, "mods"); - for(File mods : modFolder.listFiles()){ - modListData.addFilename(mods.getName()); - try { - modListData.addFileHashes(FileUtils.getMD5Checksum(mods)); - } catch (Exception exception){ - // Highly less likely to happen unless something goes wrong - exception.printStackTrace(); - } - } - - for(ModContainer mod : Loader.instance().getModList()){ - modListData.addModname(mod.getName()); - modListData.addModname(mod.getModId()); - } - } - - private static void getMods(){ - // the Cofl server has asked for an mod list now let's respond with all the info - CoflSky.Wrapper.SendMessage(new RawCommand("foundMods",gson.toJson(modListData))); - } - - - private static void Flip(Command cmd) { - //handle chat message - ChatMessageData[] messages = cmd.getData().Messages; - Command showCmd = new Command(CommandType.ChatMessage, messages); - ChatMessage(showCmd); - flipHandler.fds.Insert(new de.torui.coflsky.FlipHandler.Flip(cmd.getData().Id, cmd.getData().Worth)); - - // trigger the keyevent to execute the event handler - CoflSky.Events.onKeyEvent(null); - } - - private static void PlaySound(Command cmd, Entity sender) { - - SoundData sc = cmd.getData(); - - SoundHandler handler = Minecraft.getMinecraft().getSoundHandler(); - - // random.explode - PositionedSoundRecord psr = PositionedSoundRecord - .create(new ResourceLocation(sc.Name), sc.Pitch); - - handler.playSound(psr); - } - - private static void Execute(Command cmd, Entity sender) { - System.out.println("Execute: " + cmd.getData() + " sender:" + sender); - //String dummy = WSClient.gson.fromJson(cmd.getData(), String.class); - Execute(cmd.getData(),sender); - } - - /** - * Starts a countdown - */ - private static void StartTimer(Command cmd) { - de.torui.coflsky.CountdownTimer.startCountdown(cmd.getData()); - } - - public static void Execute(String cmd, Entity sender) - { - if(cmd.startsWith("/viewauction")){ - String[] args = cmd.split(" "); - - String uuid = args[args.length-1]; - EventRegistry.LastViewAuctionUUID = uuid; - EventRegistry.LastViewAuctionInvocation = System.currentTimeMillis(); - } - - if(cmd.startsWith("/cofl") || cmd.startsWith("http")) { - ClientCommandHandler.instance.executeCommand(sender, cmd); - } else { - Minecraft.getMinecraft().thePlayer.sendChatMessage(cmd); - } - } - - - private static IChatComponent CommandToChatComponent(ChatMessageData wcmd) { - if(wcmd.OnClick != null) - lastOnClickEvent = "/cofl callback " + wcmd.OnClick; - if (wcmd.Text != null) { - IChatComponent comp = new ChatComponentText(wcmd.Text); - - ChatStyle style; - if (wcmd.OnClick != null) { - if (wcmd.OnClick.startsWith("http")) { - style = new ChatStyle().setChatClickEvent(new ClickEvent(Action.OPEN_URL, wcmd.OnClick)); - } else { - style = new ChatStyle() - .setChatClickEvent(new ClickEvent(Action.RUN_COMMAND, "/cofl callback " + wcmd.OnClick)); - } - comp.setChatStyle(style); - } - - if (wcmd.Hover != null && !wcmd.Hover.isEmpty()) { - if (comp.getChatStyle() == null) - comp.setChatStyle(new ChatStyle()); - comp.getChatStyle().setChatHoverEvent( - new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText(wcmd.Hover))); - } - return comp; - } - return null; - } - - private static void ChatMessage(Command cmd) { - ChatMessageData[] list = cmd.getData() ;//WSClient.gson.fromJson(cmd.getData(), WriteToChatCommand[].class); - - IChatComponent master = new ChatComponentText(""); - - for (ChatMessageData wcmd : list) { - IChatComponent comp = CommandToChatComponent(wcmd); - if (comp != null) - master.appendSibling(comp); - } - Minecraft.getMinecraft().thePlayer.addChatMessage(master); - } - - - - private static void WriteToChat(Command cmd) { - ChatMessageData wcmd = cmd.getData(); - - IChatComponent comp = CommandToChatComponent(wcmd); - if (comp != null) - { - Minecraft.getMinecraft().thePlayer.addChatMessage(comp); - } - - } + public static transient String lastOnClickEvent; + public static FlipHandler flipHandler = new FlipHandler(); + private static final ModListData modListData = new ModListData(); + private static final Gson gson = new Gson(); + private static final ProxyManager proxyManager = new ProxyManager(); + + public static boolean HandleCommand(JsonStringCommand cmd, Entity sender) { + System.out.println("Handling Command=" + cmd.toString()); + + switch (cmd.getType()) { + case WriteToChat: + WriteToChat(cmd.GetAs(new TypeToken() { + })); + break; + case Execute: + Execute(cmd.GetAs(new TypeToken() { + }), sender); + break; + case PlaySound: + SoundData sc = cmd.GetAs(new TypeToken() { + }).getData(); + PlaySound(sc.Name, sc.Pitch); + break; + case ChatMessage: + ChatMessage(cmd.GetAs(new TypeToken() { + })); + break; + case Flip: + Flip(cmd.GetAs(new TypeToken() { + })); + break; + case PrivacySettings: + new ConfigurationManager().UpdateConfiguration(cmd.getData()); + case Countdown: + StartTimer(cmd.GetAs(new TypeToken() { + })); + break; + case GetMods: + getMods(); + break; + case ProxyRequest: + handleProxyRequest(cmd.GetAs(new TypeToken() { + }).getData()); + break; + default: + break; + } + + return true; + } + + private static void Flip(Command cmd) { + //handle chat message + ChatMessageData[] messages = cmd.getData().Messages; + SoundData sound = cmd.getData().Sound; + if (sound != null && sound.Name != null) { + PlaySound(sound.Name, sound.Pitch); + } + Command showCmd = new Command(CommandType.ChatMessage, messages); + ChatMessage(showCmd); + flipHandler.fds.Insert(cmd.getData()); + // trigger the keyevent to execute the event handler + CoflSky.Events.onKeyEvent(null); + } + + private static void handleProxyRequest(ProxyRequest[] request) { + for (ProxyRequest req : request) { + proxyManager.handleRequestAsync(req); + } + } + + + public static void cacheMods() { + File modFolder = new File(Minecraft.getMinecraft().mcDataDir, "mods"); + for (File mods : modFolder.listFiles()) { + modListData.addFilename(mods.getName()); + try { + modListData.addFileHashes(FileUtils.getMD5Checksum(mods)); + } catch (Exception exception) { + // Highly less likely to happen unless something goes wrong + exception.printStackTrace(); + } + } + + for (ModContainer mod : Loader.instance().getModList()) { + modListData.addModname(mod.getName()); + modListData.addModname(mod.getModId()); + } + } + + private static void getMods() { + // the Cofl server has asked for an mod list now let's respond with all the info + CoflSky.Wrapper.SendMessage(new RawCommand("foundMods", gson.toJson(modListData))); + } + + private static void PlaySound(String soundName, float pitch) { + SoundHandler handler = Minecraft.getMinecraft().getSoundHandler(); + + // random.explode + PositionedSoundRecord psr = PositionedSoundRecord + .create(new ResourceLocation(soundName), pitch); + + handler.playSound(psr); + } + + private static void Execute(Command cmd, Entity sender) { + System.out.println("Execute: " + cmd.getData() + " sender:" + sender); + //String dummy = WSClient.gson.fromJson(cmd.getData(), String.class); + Execute(cmd.getData(), sender); + } + + /** + * Starts a countdown + */ + private static void StartTimer(Command cmd) { + de.torui.coflsky.CountdownTimer.startCountdown(cmd.getData()); + } + + public static void Execute(String cmd, Entity sender) { + if (cmd.startsWith("/cofl") || cmd.startsWith("http")) { + ClientCommandHandler.instance.executeCommand(sender, cmd); + } else { + Minecraft.getMinecraft().thePlayer.sendChatMessage(cmd); + } + } + + + private static IChatComponent CommandToChatComponent(ChatMessageData wcmd, String fullMessage) { + if (wcmd.OnClick != null) { + if (wcmd.Text != null && wcmd.OnClick.startsWith("/viewauction")) { + lastOnClickEvent = "/cofl openAuctionGUI " + wcmd.OnClick.split(" ")[1] + " false"; + } else { + lastOnClickEvent = "/cofl callback " + wcmd.OnClick; + } + } + if (wcmd.Text != null) { + IChatComponent comp = new ChatComponentText(wcmd.Text); + + ChatStyle style; + if (wcmd.OnClick != null) { + if (wcmd.OnClick.startsWith("http")) { + style = new ChatStyle().setChatClickEvent(new ClickEvent(Action.OPEN_URL, wcmd.OnClick)); + } else { + style = new ChatStyle() + .setChatClickEvent(new ClickEvent(Action.RUN_COMMAND, lastOnClickEvent)); + } + comp.setChatStyle(style); + } + + if (wcmd.Hover != null && !wcmd.Hover.isEmpty()) { + if (comp.getChatStyle() == null) + comp.setChatStyle(new ChatStyle()); + comp.getChatStyle().setChatHoverEvent( + new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText(wcmd.Hover))); + } + return comp; + } + return null; + } + + public static void sendChatMessage(IChatComponent message) { + Minecraft.getMinecraft().thePlayer.addChatMessage(message); + } + + public static IChatComponent ChatMessage(Command cmd) { + ChatMessageData[] list = cmd.getData(); + + IChatComponent master = new ChatComponentText(""); + String fullMessage = ChatMessageDataToString(list); + + for (ChatMessageData wcmd : list) { + IChatComponent comp = CommandToChatComponent(wcmd, fullMessage); + if (comp != null) + master.appendSibling(comp); + } + Minecraft.getMinecraft().thePlayer.addChatMessage(master); + return master; + } + + + private static void WriteToChat(Command cmd) { + ChatMessageData wcmd = cmd.getData(); + + IChatComponent comp = CommandToChatComponent(wcmd, wcmd.Text); + if (comp != null) { + Minecraft.getMinecraft().thePlayer.addChatMessage(comp); + } + + } + + public static String ChatMessageDataToString(ChatMessageData[] messages) { + Stream stream = Arrays.stream(messages).map(message -> message.Text); + String s = String.join(",", stream.toArray(String[]::new)); + stream.close(); + return s; + } } diff --git a/src/main/java/de/torui/coflsky/commands/models/FlipData.java b/src/main/java/de/torui/coflsky/commands/models/FlipData.java index 88836d2..0fb9357 100644 --- a/src/main/java/de/torui/coflsky/commands/models/FlipData.java +++ b/src/main/java/de/torui/coflsky/commands/models/FlipData.java @@ -1,24 +1,34 @@ package de.torui.coflsky.commands.models; import com.google.gson.annotations.SerializedName; +import de.torui.coflsky.WSCommandHandler; public class FlipData { - + @SerializedName("messages") public ChatMessageData[] Messages; - @SerializedName("id") public String Id; - @SerializedName("worth") public int Worth; - - public FlipData() {} + @SerializedName("sound") + public SoundData Sound; + @SerializedName("render") + public String Render; + + public FlipData() { + } - public FlipData(ChatMessageData[] messages, String id, int worth) { + public FlipData(ChatMessageData[] messages, String id, int worth, SoundData sound, String render) { super(); Messages = messages; Id = id; Worth = worth; + Sound = sound; + Render = render; + } + + public String getMessageAsString(){ + return WSCommandHandler.ChatMessageDataToString(this.Messages); } } diff --git a/src/main/java/de/torui/coflsky/configuration/LocalConfig.java b/src/main/java/de/torui/coflsky/configuration/LocalConfig.java index 749d0bc..7e3c5f9 100644 --- a/src/main/java/de/torui/coflsky/configuration/LocalConfig.java +++ b/src/main/java/de/torui/coflsky/configuration/LocalConfig.java @@ -1,7 +1,7 @@ package de.torui.coflsky.configuration; import com.google.gson.Gson; -import com.google.gson.JsonObject; +import de.torui.coflsky.gui.GUIType; import java.io.File; import java.io.IOException; @@ -12,10 +12,14 @@ import java.nio.file.Paths; public class LocalConfig { public boolean autoStart; public boolean extendedtooltips; - public LocalConfig(boolean autoStart,boolean extendedtooltips) { + public GUIType purchaseOverlay; + + public LocalConfig(boolean autoStart, boolean extendedtooltips, GUIType purchaseOverlay) { this.autoStart = autoStart; this.extendedtooltips = extendedtooltips; + this.purchaseOverlay = purchaseOverlay; } + public static void saveConfig(File file, LocalConfig Config) { Gson gson = new Gson(); try { @@ -24,12 +28,12 @@ public class LocalConfig { } Files.write(Paths.get(file.getAbsolutePath()), gson.toJson(Config).getBytes(StandardCharsets.UTF_8)); - }catch (IOException e){ + } catch (IOException e) { e.printStackTrace(); } } public static LocalConfig createDefaultConfig() { - return new LocalConfig(true,true); + return new LocalConfig(true, true, null); } } diff --git a/src/main/java/de/torui/coflsky/gui/GUIType.java b/src/main/java/de/torui/coflsky/gui/GUIType.java new file mode 100644 index 0000000..586ac72 --- /dev/null +++ b/src/main/java/de/torui/coflsky/gui/GUIType.java @@ -0,0 +1,6 @@ +package de.torui.coflsky.gui; + +public enum GUIType { + TFM, + COFL +} diff --git a/src/main/java/de/torui/coflsky/gui/bingui/BinGuiCurrent.java b/src/main/java/de/torui/coflsky/gui/bingui/BinGuiCurrent.java new file mode 100644 index 0000000..ef5ec9c --- /dev/null +++ b/src/main/java/de/torui/coflsky/gui/bingui/BinGuiCurrent.java @@ -0,0 +1,415 @@ +package de.torui.coflsky.gui.bingui; + + +import de.torui.coflsky.CoflSky; +import de.torui.coflsky.gui.GUIType; +import de.torui.coflsky.gui.bingui.helper.ColorPallet; +import de.torui.coflsky.gui.bingui.helper.RenderUtils; +import de.torui.coflsky.handlers.EventHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.inventory.GuiChest; +import net.minecraft.command.NumberInvalidException; +import net.minecraft.init.Items; +import net.minecraft.inventory.ContainerChest; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemArmor; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.client.event.ClientChatReceivedEvent; +import net.minecraftforge.client.event.GuiOpenEvent; +import net.minecraftforge.client.event.GuiScreenEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import org.lwjgl.input.Mouse; + +import java.awt.event.MouseWheelEvent; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class BinGuiCurrent extends GuiChest { + private String message; + private String[] lore; + private ItemStack itemStack; + private String buyText = "Buy(You can click anywhere)"; + private BuyState buyState = BuyState.INIT; + private int pixelsScrolled = 0; + private boolean wasMouseDown; + private boolean isRendered = false; + private boolean hasInitialMouseSet = false; + + // set if the auction was already bought + private String buyer = null; + + private static final Pattern CAN_BUY_IN_MATCHER = Pattern.compile("Can buy in: (.*)"); + private static final Pattern BUYER_MATCHER = Pattern.compile("Buyer: (.*)"); + + private GuiChest chestGui; + + public BinGuiCurrent(IInventory playerInventory, IInventory chestInventory, String message, String extraData) { + super(chestInventory, playerInventory); + this.message = message; + this.lore = new String[]{"Loading..."}; + if (extraData.length() >= 32) { + itemStack = getSkull("Name", "00000000-0000-0000-0000-000000000000", extraData); + } else { + itemStack = new ItemStack(getItemByText(extraData)); + //if it is an armor item, we color it black + if (itemStack.getItem() == null) return; + if (itemStack.getItem() instanceof ItemArmor && (itemStack.getItem() == Items.leather_helmet || itemStack.getItem() == Items.leather_chestplate || itemStack.getItem() == Items.leather_leggings || itemStack.getItem() == Items.leather_boots)) { + ((ItemArmor) itemStack.getItem()).setColor(itemStack, 0); + } + } + MinecraftForge.EVENT_BUS.register(this); + } + + private boolean shouldSkip(GuiScreen screen) { + return !(screen instanceof GuiChest) || CoflSky.config.purchaseOverlay != GUIType.COFL || !EventHandler.isInSkyblock; + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public void onGuiOpen(GuiOpenEvent event) { + + if (event.gui == null) { + resetGUI(); + } + + isRendered = false; + GuiScreen gui = event.gui; + + if (message == null || message.isEmpty()) { + return; + } + + if (shouldSkip(gui)) { + return; + } + + GuiChest chest = (GuiChest) gui; + + IInventory inventory = ((ContainerChest) chest.inventorySlots).getLowerChestInventory(); + if (inventory == null) return; + + String guiName = inventory.getDisplayName().getUnformattedText().trim(); + if (guiName.equalsIgnoreCase("BIN Auction View") || guiName.equalsIgnoreCase("Confirm Purchase")) { + this.chestGui = (GuiChest) event.gui; + this.inventorySlots = ((GuiChest) event.gui).inventorySlots; + event.gui = this; + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public void onDrawGuiScreen(GuiScreenEvent.DrawScreenEvent.Pre event) { + isRendered = false; + GuiScreen gui = event.gui; + + if (message == null || message.isEmpty()) { + return; + } + + if (shouldSkip(gui)) { + return; + } + + GuiChest chest = (GuiChest) gui; + + IInventory inventory = ((ContainerChest) chest.inventorySlots).getLowerChestInventory(); + if (inventory == null) return; + + String guiName = inventory.getDisplayName().getUnformattedText().trim(); + if (guiName.equalsIgnoreCase("auction view")) { + return; + } + + ItemStack item = inventory.getStackInSlot(13); + if (item == null) return; + + String[] tooltip = item.getTooltip(mc.thePlayer, false).toArray(new String[0]); + + itemStack = item; + + if (guiName.equalsIgnoreCase("BIN Auction View")) { + lore = tooltip; + buyer = isAlreadyBought(tooltip); + } + if (guiName.equalsIgnoreCase("BIN Auction View") && buyState == BuyState.PURCHASE) { + if (waitingForBed(chest)) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §cBed is not purchasable yet.")); + buyState = BuyState.INIT; + } else { + mc.playerController.windowClick(this.chestGui.inventorySlots.windowId, 31, 2, 3, mc.thePlayer); + wasMouseDown = false; + buyState = BuyState.CONFIRM; + } + } else if (guiName.equalsIgnoreCase("Confirm Purchase") && buyState == BuyState.BUYING) { + mc.playerController.windowClick(this.chestGui.inventorySlots.windowId, 11, 2, 3, mc.thePlayer); + resetGUI(); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + Mouse.setGrabbed(false); + isRendered = true; + + int screenWidth = this.width; + int screenHeight = this.height; + + int width = mc.fontRendererObj.getStringWidth(message) > 500 ? mc.fontRendererObj.getStringWidth(message) + 5 : 500; + int height = 300; + + //RenderUtils.drawRoundedRect(screenWidth / 2, 10 + 5 + 14 + 5 + (height - 100) + 5, (width - 10) / 2 + 20, 60, 5, ColorPallet.SUCCESS.getColor()); + if (!hasInitialMouseSet) { + Mouse.setCursorPosition(mc.displayWidth / 2, mc.displayHeight / 2); + hasInitialMouseSet = true; + } + + //if (lore.length > 25) { + // height = 300 + (lore.length - 2