diff options
Diffstat (limited to 'src/main/java/de/hysky')
6 files changed, 225 insertions, 302 deletions
diff --git a/src/main/java/de/hysky/skyblocker/config/SkyblockerConfig.java b/src/main/java/de/hysky/skyblocker/config/SkyblockerConfig.java index fd548d6a..1bfd1b3c 100644 --- a/src/main/java/de/hysky/skyblocker/config/SkyblockerConfig.java +++ b/src/main/java/de/hysky/skyblocker/config/SkyblockerConfig.java @@ -414,30 +414,30 @@ public class SkyblockerConfig { @SerialEntry public Alignment alignment = Alignment.MIDDLE; } - public static class SearchOverlay { - @SerialEntry - public boolean enableBazaar = true; - - @SerialEntry - public boolean enableAuctionHouse = true; - @SerialEntry - public boolean keepPreviousSearches = false; - - @SerialEntry - public int maxSuggestions = 3; - - @SerialEntry - public int historyLength = 3; + public enum Direction { + HORIZONTAL, VERTICAL; - @SerialEntry - public boolean enableCommands = false; + @Override + public String toString() { + return switch (this) { + case HORIZONTAL -> "Horizontal"; + case VERTICAL -> "Vertical"; + }; + } + } - @SerialEntry - public List<String> bazaarHistory = new ArrayList<>(); + public enum Alignment { + LEFT, RIGHT, MIDDLE; - @SerialEntry - public List<String> auctionHistory = new ArrayList<>(); + @Override + public String toString() { + return switch (this) { + case LEFT -> "Left"; + case RIGHT -> "Right"; + case MIDDLE -> "Middle"; + }; + } } public static class TeleportOverlay { @@ -468,29 +468,30 @@ public class SkyblockerConfig { public float flameOpacity = 0f; } - public enum Direction { - HORIZONTAL, VERTICAL; + public static class SearchOverlay { + @SerialEntry + public boolean enableBazaar = true; - @Override - public String toString() { - return switch (this) { - case HORIZONTAL -> "Horizontal"; - case VERTICAL -> "Vertical"; - }; - } - } + @SerialEntry + public boolean enableAuctionHouse = true; - public enum Alignment { - LEFT, RIGHT, MIDDLE; + @SerialEntry + public boolean keepPreviousSearches = false; - @Override - public String toString() { - return switch (this) { - case LEFT -> "Left"; - case RIGHT -> "Right"; - case MIDDLE -> "Middle"; - }; - } + @SerialEntry + public int maxSuggestions = 3; + + @SerialEntry + public int historyLength = 3; + + @SerialEntry + public boolean enableCommands = false; + + @SerialEntry + public List<String> bazaarHistory = new ArrayList<>(); + + @SerialEntry + public List<String> auctionHistory = new ArrayList<>(); } public static class RichPresence { diff --git a/src/main/java/de/hysky/skyblocker/config/categories/GeneralCategory.java b/src/main/java/de/hysky/skyblocker/config/categories/GeneralCategory.java index 3d7f63ce..9c3b672f 100644 --- a/src/main/java/de/hysky/skyblocker/config/categories/GeneralCategory.java +++ b/src/main/java/de/hysky/skyblocker/config/categories/GeneralCategory.java @@ -642,6 +642,7 @@ public class GeneralCategory { .controller(opt -> FloatSliderControllerBuilder.create(opt).range(0.0f, 0.8f).step(0.1f)) .build()) .build()) + //Search overlay .group(OptionGroup.createBuilder() .name(Text.translatable("text.autoconfig.skyblocker.option.general.searchOverlay")) diff --git a/src/main/java/de/hysky/skyblocker/mixin/ClientPlayerEntityMixin.java b/src/main/java/de/hysky/skyblocker/mixin/ClientPlayerEntityMixin.java index bbe58d36..2a4c38a7 100644 --- a/src/main/java/de/hysky/skyblocker/mixin/ClientPlayerEntityMixin.java +++ b/src/main/java/de/hysky/skyblocker/mixin/ClientPlayerEntityMixin.java @@ -1,7 +1,6 @@ package de.hysky.skyblocker.mixin; import com.mojang.authlib.GameProfile; - import de.hysky.skyblocker.config.SkyblockerConfigManager; import de.hysky.skyblocker.skyblock.dungeon.partyfinder.PartyFinderScreen; import de.hysky.skyblocker.skyblock.item.HotbarSlotLock; @@ -10,7 +9,6 @@ import de.hysky.skyblocker.skyblock.rift.HealingMelonIndicator; import de.hysky.skyblocker.skyblock.searchOverlay.OverlayScreen; import de.hysky.skyblocker.skyblock.searchOverlay.SearchOverManager; import de.hysky.skyblocker.utils.Utils; -import net.fabricmc.loader.api.FabricLoader; import net.minecraft.block.entity.SignBlockEntity; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.AbstractClientPlayerEntity; @@ -52,30 +50,28 @@ public abstract class ClientPlayerEntityMixin extends AbstractClientPlayerEntity } @Inject(method = "openEditSignScreen", at = @At("HEAD"), cancellable = true) - public void skyblocker$partyFinderRange(SignBlockEntity sign, boolean front, CallbackInfo callbackInfo) { - if (PartyFinderScreen.isInKuudraPartyFinder) return; - if (client.currentScreen instanceof PartyFinderScreen partyFinderScreen && !partyFinderScreen.isAborted()) { - if (sign.getText(front).getMessage(3, false).getString().toLowerCase().contains("level")) { - partyFinderScreen.updateSign(sign, front); - callbackInfo.cancel(); - } + public void skyblocker$redirectEditSignScreen(SignBlockEntity sign, boolean front, CallbackInfo callbackInfo) { + // Fancy Party Finder + if (!PartyFinderScreen.isInKuudraPartyFinder && client.currentScreen instanceof PartyFinderScreen partyFinderScreen && !partyFinderScreen.isAborted() && sign.getText(front).getMessage(3, false).getString().toLowerCase().contains("level")) { + partyFinderScreen.updateSign(sign, front); + callbackInfo.cancel(); + return; } - } - @Inject(method = "openEditSignScreen", at = @At("HEAD"), cancellable = true) - public void skyblocker$searchOverlay(SignBlockEntity sign, boolean front, CallbackInfo callbackInfo) { - if (client == null) return; - if (SkyblockerConfigManager.get().general.searchOverlay.enableAuctionHouse && (FabricLoader.getInstance().isDevelopmentEnvironment() || client.currentScreen.getTitle().getString().toLowerCase().contains("auction")) ) { - if (sign.getText(front).getMessage(3, false).getString().equalsIgnoreCase("enter query")) { - SearchOverManager.updateSign(sign, front,true); - client.setScreen(new OverlayScreen(Text.of(""))); - callbackInfo.cancel(); - } - } - else if (SkyblockerConfigManager.get().general.searchOverlay.enableBazaar && (FabricLoader.getInstance().isDevelopmentEnvironment() || client.currentScreen.getTitle().getString().toLowerCase().contains("bazaar")) ) { - if (sign.getText(front).getMessage(3, false).getString().equalsIgnoreCase("enter query")) { - SearchOverManager.updateSign(sign, front,false); - client.setScreen(new OverlayScreen(Text.of(""))); - callbackInfo.cancel(); + + // Search Overlay + if (client.currentScreen != null) { + if (SkyblockerConfigManager.get().general.searchOverlay.enableAuctionHouse && client.currentScreen.getTitle().getString().toLowerCase().contains("auction")) { + if (sign.getText(front).getMessage(3, false).getString().equalsIgnoreCase("enter query")) { + SearchOverManager.updateSign(sign, front, true); + client.setScreen(new OverlayScreen(Text.of(""))); + callbackInfo.cancel(); + } + } else if (SkyblockerConfigManager.get().general.searchOverlay.enableBazaar && client.currentScreen.getTitle().getString().toLowerCase().contains("bazaar")) { + if (sign.getText(front).getMessage(3, false).getString().equalsIgnoreCase("enter query")) { + SearchOverManager.updateSign(sign, front, false); + client.setScreen(new OverlayScreen(Text.of(""))); + callbackInfo.cancel(); + } } } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/TooltipInfoType.java b/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/TooltipInfoType.java index 9b83f276..fc5c7087 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/TooltipInfoType.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/TooltipInfoType.java @@ -18,7 +18,7 @@ public enum TooltipInfoType implements Runnable { BAZAAR("https://hysky.de/api/bazaar", itemTooltip -> itemTooltip.enableBazaarPrice || SkyblockerConfigManager.get().locations.dungeons.dungeonChestProfit.enableProfitCalculator || SkyblockerConfigManager.get().general.chestValue.enableChestValue, itemTooltip -> itemTooltip.enableBazaarPrice, false), LOWEST_BINS("https://hysky.de/api/auctions/lowestbins", itemTooltip -> itemTooltip.enableLowestBIN || SkyblockerConfigManager.get().locations.dungeons.dungeonChestProfit.enableProfitCalculator || SkyblockerConfigManager.get().general.chestValue.enableChestValue, itemTooltip -> itemTooltip.enableLowestBIN, false), ONE_DAY_AVERAGE("https://moulberry.codes/auction_averages_lbin/1day.json", itemTooltip -> itemTooltip.enableAvgBIN, false), - THREE_DAY_AVERAGE("https://moulberry.codes/auction_averages_lbin/3day.json", itemTooltip -> itemTooltip.enableAvgBIN, false), + THREE_DAY_AVERAGE("https://moulberry.codes/auction_averages_lbin/3day.json", itemTooltip -> itemTooltip.enableAvgBIN || SkyblockerConfigManager.get().general.searchOverlay.enableAuctionHouse, itemTooltip -> itemTooltip.enableAvgBIN, false), MOTES("https://hysky.de/api/motesprice", itemTooltip -> itemTooltip.enableMotesPrice, itemTooltip -> itemTooltip.enableMotesPrice && Utils.isInTheRift(), true), OBTAINED(itemTooltip -> itemTooltip.enableObtainedDate), MUSEUM("https://hysky.de/api/museum", itemTooltip -> itemTooltip.enableMuseumInfo, true), diff --git a/src/main/java/de/hysky/skyblocker/skyblock/searchOverlay/OverlayScreen.java b/src/main/java/de/hysky/skyblocker/skyblock/searchOverlay/OverlayScreen.java index b10510ed..e1545c6c 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/searchOverlay/OverlayScreen.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/searchOverlay/OverlayScreen.java @@ -3,22 +3,15 @@ package de.hysky.skyblocker.skyblock.searchOverlay; import de.hysky.skyblocker.config.SkyblockerConfigManager; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.tooltip.Tooltip; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.TextFieldWidget; -import net.minecraft.client.item.TooltipContext; import net.minecraft.item.ItemStack; -import net.minecraft.text.MutableText; import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.util.Identifier; import org.lwjgl.glfw.GLFW; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - import static de.hysky.skyblocker.skyblock.itemlist.ItemRepository.getItemStack; public class OverlayScreen extends Screen { @@ -40,20 +33,18 @@ public class OverlayScreen extends Screen { @Override protected void init() { super.init(); - int rowWidth = (int)(this.width * 0.4); - int startX = (int)(this.width * 0.5) - rowWidth/2; - int startY = (int) ((int)(this.height * 0.5)- (rowHeight * (1 + SkyblockerConfigManager.get().general.searchOverlay.maxSuggestions + 0.75 + SkyblockerConfigManager.get().general.searchOverlay.historyLength)) / 2); + int rowWidth = (int) (this.width * 0.4); + int startX = (int) (this.width * 0.5) - rowWidth / 2; + int startY = (int) ((int) (this.height * 0.5) - (rowHeight * (1 + SkyblockerConfigManager.get().general.searchOverlay.maxSuggestions + 0.75 + SkyblockerConfigManager.get().general.searchOverlay.historyLength)) / 2); // Search field - this.searchField = new TextFieldWidget(textRenderer,startX, startY, rowWidth - rowHeight, rowHeight, Text.literal("Search...")); + this.searchField = new TextFieldWidget(textRenderer, startX, startY, rowWidth - rowHeight, rowHeight, Text.translatable("gui.recipebook.search_hint")); searchField.setText(SearchOverManager.search); searchField.setChangedListener(SearchOverManager::updateSearch); searchField.setMaxLength(30); // finish buttons - finishedButton = ButtonWidget.builder(Text.literal("").setStyle(Style.EMPTY.withColor(Formatting.GREEN)), (a) -> { - close(); - }) + finishedButton = ButtonWidget.builder(Text.literal("").setStyle(Style.EMPTY.withColor(Formatting.GREEN)), a -> close()) .position(startX + rowWidth - rowHeight, startY) .size(rowHeight, rowHeight).build(); @@ -62,7 +53,7 @@ public class OverlayScreen extends Screen { int totalSuggestions = SkyblockerConfigManager.get().general.searchOverlay.maxSuggestions; this.suggestionButtons = new ButtonWidget[totalSuggestions]; for (int i = 0; i < totalSuggestions; i++) { - suggestionButtons[i] = ButtonWidget.builder(Text.literal(SearchOverManager.getSuggestion(i)).setStyle(Style.EMPTY), (a) -> { + suggestionButtons[i] = ButtonWidget.builder(Text.literal(SearchOverManager.getSuggestion(i)).setStyle(Style.EMPTY), a -> { SearchOverManager.updateSearch(a.getMessage().getString()); close(); }) @@ -85,31 +76,18 @@ public class OverlayScreen extends Screen { .position(startX, startY + rowOffset) .size(rowWidth, rowHeight).build(); rowOffset += rowHeight; - - //set the tool tip - String id = SearchOverManager.getHistoryId(i); - if (id == null || id.isEmpty() || client == null) continue; - ItemStack item = getItemStack(id); - if (item == null) continue; - MutableText tooltip = Text.literal(""); - item.getTooltip(client.player, TooltipContext.BASIC).forEach(line -> { - tooltip.append(line); - tooltip.append(Text.literal("\n")); - }); - historyButtons[i].setTooltip(Tooltip.of(Text.of(tooltip))); - } - else { + } else { break; } } //add drawables in order to make tab navigation sensible addDrawableChild(searchField); - for (ButtonWidget suggestion : suggestionButtons){ + for (ButtonWidget suggestion : suggestionButtons) { addDrawableChild(suggestion); } - for (ButtonWidget historyOption : historyButtons){ - if (historyOption != null){ + for (ButtonWidget historyOption : historyButtons) { + if (historyOption != null) { addDrawableChild(historyOption); } } @@ -127,37 +105,32 @@ public class OverlayScreen extends Screen { super.render(context, mouseX, mouseY, delta); int renderOffset = (rowHeight - 16) / 2; context.drawGuiTexture(SEARCH_ICON_TEXTURE, finishedButton.getX() + renderOffset, finishedButton.getY() + renderOffset, 16, 16); - if(historyButtons.length > 0 && historyButtons[0] != null){ - context.drawText(textRenderer, Text.translatable("text.autoconfig.skyblocker.option.general.searchOverlay.historyLabel") - , historyButtons[0].getX() + renderOffset, historyButtons[0].getY() - (rowHeight / 2), 0xFFFFFFFF, true); + if (historyButtons.length > 0 && historyButtons[0] != null) { + context.drawText(textRenderer, Text.translatable("text.autoconfig.skyblocker.option.general.searchOverlay.historyLabel"), historyButtons[0].getX() + renderOffset, historyButtons[0].getY() - rowHeight / 2, 0xFFFFFFFF, true); } - //draw item stacks to buttons + //draw item stacks and tooltip to buttons for (int i = 0; i < suggestionButtons.length; i++) { - String id = SearchOverManager.getSuggestionId(i); - if (id.isEmpty()) continue; - ItemStack item = getItemStack(id); - if (item == null) continue; - context.drawItem(item,suggestionButtons[i].getX() + renderOffset,suggestionButtons[i].getY() + renderOffset); + drawItemAndTooltip(context, mouseX, mouseY, SearchOverManager.getSuggestionId(i), suggestionButtons[i], renderOffset); } for (int i = 0; i < historyButtons.length; i++) { - String id = SearchOverManager.getHistoryId(i); - if (id == null || id.isEmpty()) continue; - ItemStack item = getItemStack(id); - if (item == null) continue; - context.drawItem(item,historyButtons[i].getX() + renderOffset,historyButtons[i].getY() + renderOffset); + drawItemAndTooltip(context, mouseX, mouseY, SearchOverManager.getHistoryId(i), historyButtons[i], renderOffset); } } /** - * Closes the overlay screen and gets the manager to send a packet update about the sign + * Draws the item and tooltip for the given button */ - @Override - public void close() { - assert this.client != null; - assert this.client.player != null; - SearchOverManager.pushSearch(); - super.close(); + private void drawItemAndTooltip(DrawContext context, int mouseX, int mouseY, String id, ButtonWidget button, int renderOffset) { + if (id == null || id.isEmpty()) return; + ItemStack item = getItemStack(id); + if (item == null) return; + context.drawItem(item, button.getX() + renderOffset, button.getY() + renderOffset); + + // Draw tooltip + if (button.isMouseOver(mouseX, mouseY)) { + context.drawItemTooltip(textRenderer, item, mouseX, mouseY); + } } /** @@ -169,32 +142,14 @@ public class OverlayScreen extends Screen { //update suggestion buttons text for (int i = 0; i < SkyblockerConfigManager.get().general.searchOverlay.maxSuggestions; i++) { String text = SearchOverManager.getSuggestion(i); - if (!text.isEmpty()){ + if (!text.isEmpty()) { suggestionButtons[i].visible = true; boolean isNewText = !text.equals(suggestionButtons[i].getMessage().getString()); if (!isNewText) continue; suggestionButtons[i].setMessage(Text.literal(text).setStyle(Style.EMPTY)); - - //update the tool tip - String id = SearchOverManager.getSuggestionId(i); - if (id.isEmpty() || client == null) { - suggestionButtons[i].setTooltip(null); - continue; - } - ItemStack item = getItemStack(id); - if (item == null) { - suggestionButtons[i].setTooltip(null); - continue; - } - MutableText tooltip = Text.literal(""); - item.getTooltip(client.player, TooltipContext.BASIC).forEach(line -> { - tooltip.append(line); - tooltip.append(Text.literal("\n")); - }); - suggestionButtons[i].setTooltip(Tooltip.of(Text.of(tooltip))); - }else{ + } else { suggestionButtons[i].visible = false; } } @@ -205,11 +160,26 @@ public class OverlayScreen extends Screen { */ @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - super.keyPressed(keyCode,scanCode,modifiers); - if (keyCode == GLFW.GLFW_KEY_ENTER && searchField.isActive()){ + if (keyCode == GLFW.GLFW_KEY_ENTER && searchField.isActive()) { close(); return true; } + return super.keyPressed(keyCode, scanCode, modifiers); + } + + @Override + public boolean shouldPause() { return false; } + + /** + * Closes the overlay screen and gets the manager to send a packet update about the sign + */ + @Override + public void close() { + assert this.client != null; + assert this.client.player != null; + SearchOverManager.pushSearch(); + super.close(); + } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/searchOverlay/SearchOverManager.java b/src/main/java/de/hysky/skyblocker/skyblock/searchOverlay/SearchOverManager.java index 1b019a7f..b2a453a9 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/searchOverlay/SearchOverManager.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/searchOverlay/SearchOverManager.java @@ -1,19 +1,18 @@ package de.hysky.skyblocker.skyblock.searchOverlay; -import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.context.CommandContext; -import de.hysky.skyblocker.SkyblockerMod; +import de.hysky.skyblocker.config.SkyblockerConfig; import de.hysky.skyblocker.config.SkyblockerConfigManager; -import de.hysky.skyblocker.skyblock.dwarven.CrystalsHud; +import de.hysky.skyblocker.skyblock.item.tooltip.TooltipInfoType; import de.hysky.skyblocker.utils.Http; import de.hysky.skyblocker.utils.NEURepoManager; import de.hysky.skyblocker.utils.scheduler.MessageScheduler; import io.github.moulberry.repo.data.NEUItem; +import it.unimi.dsi.fastutil.Pair; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.minecraft.block.entity.SignBlockEntity; @@ -21,11 +20,16 @@ import net.minecraft.client.MinecraftClient; import net.minecraft.command.CommandRegistryAccess; import net.minecraft.network.packet.c2s.play.UpdateSignC2SPacket; import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.*; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -37,11 +41,6 @@ public class SearchOverManager { private static final MinecraftClient CLIENT = MinecraftClient.getInstance(); private static final Logger LOGGER = LoggerFactory.getLogger("Skyblocker Search Overlay"); - /** - * website where actionable items are stored - */ - private static final String THREE_DAY_AVERAGE = "https://moulberry.codes/auction_averages_lbin/3day.json"; - private static final Pattern BAZAAR_ENCHANTMENT_PATTERN = Pattern.compile("ENCHANTMENT_(\\D*)_(\\d+)"); private static final Pattern AUCTION_PET_AND_RUNE_PATTERN = Pattern.compile("([A-Z0-9_]+);(\\d+)"); @@ -50,20 +49,20 @@ public class SearchOverManager { */ private static final String[] ROMAN_NUMERALS = new String[]{ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", - "XII", "XIII", "XIV", "XV", "XVI", "XVII","XVIII", "XIX", "XX" + "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX" }; - private static @Nullable SignBlockEntity Sign = null; - private static boolean SignFront = true; - private static boolean IsAuction; - private static boolean IsCommand; + private static @Nullable SignBlockEntity sign = null; + private static boolean signFront = true; + private static boolean isAuction; + private static boolean isCommand; protected static String search = ""; - private static final Map<String,String> itemNameLookup = new HashMap<>(); - private static final HashSet<String> bazaarItems =new HashSet<>(); - private static final HashSet<String> auctionItems =new HashSet<>(); - private static final HashMap<String,String> namesToId =new HashMap<>(); + // Use non-final variables and swap them to prevent concurrent modification + private static HashSet<String> bazaarItems; + private static HashSet<String> auctionItems; + private static HashMap<String, String> namesToId; public static String[] suggestionsArray = {}; @@ -72,47 +71,31 @@ public class SearchOverManager { */ public static void init() { ClientCommandRegistrationCallback.EVENT.register(SearchOverManager::registerSearchCommands); - - LoadItems(); + NEURepoManager.runAsyncAfterLoad(SearchOverManager::loadItems); } private static void registerSearchCommands(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registryAccess) { if (SkyblockerConfigManager.get().general.searchOverlay.enableCommands) { - dispatcher.register(literal("ahs") - .executes(context -> startCommand(true)) - ); - dispatcher.register(literal("bzs") - .executes(context -> startCommand(false)) - ); + dispatcher.register(literal("ahs").executes(context -> startCommand(true))); + dispatcher.register(literal("bzs").executes(context -> startCommand(false))); } } private static int startCommand(boolean isAuction) { - IsCommand = true; - IsAuction = isAuction; + isCommand = true; + SearchOverManager.isAuction = isAuction; search = ""; suggestionsArray = new String[]{}; - CLIENT.send(() -> CLIENT.setScreen( new OverlayScreen(Text.of("")))); + CLIENT.send(() -> CLIENT.setScreen(new OverlayScreen(Text.of("")))); return Command.SINGLE_SUCCESS; } - private static void LoadItems(){ + private static void loadItems() { + HashSet<String> bazaarItems = new HashSet<>(); + HashSet<String> auctionItems = new HashSet<>(); + HashMap<String, String> namesToId = new HashMap<>(); + //get bazaar items - try { - String response = Http.sendGetRequest("https://api.hypixel.net/v2/resources/skyblock/items"); - JsonArray items = JsonParser.parseString(response).getAsJsonObject().getAsJsonArray("items"); - for (JsonElement entry : items) { - if (entry.isJsonObject()) { - JsonObject item = entry.getAsJsonObject(); - String itemId = item.get("id").getAsString(); - String itemName = item.get("name").getAsString(); - itemNameLookup.put(itemId,itemName); - } - } - } catch (Exception e) { - //can not get items skyblock items - LOGGER.error("[Skyblocker] skyblock items list download failed! ", e); - } try (Http.ApiResponse response = Http.sendHypixelRequest("skyblock/bazaar", "")) { JsonObject products = JsonParser.parseString(response.content()).getAsJsonObject().get("products").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : products.entrySet()) { @@ -120,7 +103,8 @@ public class SearchOverManager { JsonObject product = entry.getValue().getAsJsonObject(); String id = product.get("product_id").getAsString(); int sellVolume = product.get("quick_status").getAsJsonObject().get("sellVolume").getAsInt(); - if (sellVolume == 0) continue; //do not add items that do not sell e.g. they are not actual in the bazaar + if (sellVolume == 0) + continue; //do not add items that do not sell e.g. they are not actual in the bazaar Matcher matcher = BAZAAR_ENCHANTMENT_PATTERN.matcher(id); if (matcher.matches()) {//format enchantments //remove ultimate if in name @@ -140,9 +124,9 @@ public class SearchOverManager { continue; } //look up id for name - String name = itemNameLookup.get(product.get("product_id").getAsString()); - if (name != null){ - name = trimItemColor(name); + NEUItem neuItem = NEURepoManager.NEU_REPO.getItems().getItemBySkyblockId(id); + if (neuItem != null) { + String name = Formatting.strip(neuItem.getDisplayName()); bazaarItems.add(name); namesToId.put(name, id); continue; @@ -150,18 +134,19 @@ public class SearchOverManager { } } } catch (Exception e) { - //can not get items for bazaar search - LOGGER.error("[Skyblocker] bazaar item list download failed! ", e); + LOGGER.error("[Skyblocker] Failed to load bazaar item list! ", e); } //get auction items try { - JsonObject AuctionData = SkyblockerMod.GSON.fromJson(Http.sendGetRequest(THREE_DAY_AVERAGE), JsonObject.class); - for (Map.Entry<String, JsonElement> entry : AuctionData.entrySet()) { + if (TooltipInfoType.THREE_DAY_AVERAGE.getData() == null) { + TooltipInfoType.THREE_DAY_AVERAGE.run(); + } + for (Map.Entry<String, JsonElement> entry : TooltipInfoType.THREE_DAY_AVERAGE.getData().entrySet()) { String id = entry.getKey(); Matcher matcher = AUCTION_PET_AND_RUNE_PATTERN.matcher(id); - if (matcher.find()){//is a pet or rune convert id to name + if (matcher.find()) {//is a pet or rune convert id to name String name = matcher.group(1).replace("_", " "); name = capitalizeFully(name); auctionItems.add(name); @@ -170,19 +155,23 @@ public class SearchOverManager { } //something else look up in NEU repo. id = id.split("[+-]")[0]; - NEUItem item = NEURepoManager.NEU_REPO.getItems().getItemBySkyblockId(id); - if (item != null){ - String name = trimItemColor(item.getDisplayName()); + NEUItem neuItem = NEURepoManager.NEU_REPO.getItems().getItemBySkyblockId(id); + if (neuItem != null) { + String name = Formatting.strip(neuItem.getDisplayName()); auctionItems.add(name); namesToId.put(name, id); continue; } } } catch (Exception e) { - //can not find ah - LOGGER.error("[Skyblocker] ah item list download failed! ", e); + LOGGER.error("[Skyblocker] Failed to load auction house item list! ", e); } + + SearchOverManager.bazaarItems = bazaarItems; + SearchOverManager.auctionItems = auctionItems; + SearchOverManager.namesToId = namesToId; } + /** * Capitalizes the first letter off every word in a string * @param str string to capitalize @@ -196,35 +185,28 @@ public class SearchOverManager { .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase()) .collect(Collectors.joining(" ")); } - /** - * Removes the item color text tags from the whole of the text - * @param str string to remove color - */ - private static String trimItemColor(String str){ - if (str.isEmpty()) return str; - return str.replaceAll("ยง[0-9a-g]",""); - } + /** * Receives data when a search is started and resets values * @param sign the sign that is being edited * @param front if it's the front of the sign * @param isAuction if the sign is loaded from the auction house menu or bazaar */ - public static void updateSign(SignBlockEntity sign, boolean front, boolean isAuction) { - SignFront = front; - Sign = sign; - IsCommand = false; - IsAuction = isAuction; - if (SkyblockerConfigManager.get().general.searchOverlay.keepPreviousSearches){ - Text[] messages = Sign.getText(SignFront).getMessages(CLIENT.shouldFilterText()); + public static void updateSign(@NotNull SignBlockEntity sign, boolean front, boolean isAuction) { + signFront = front; + SearchOverManager.sign = sign; + isCommand = false; + SearchOverManager.isAuction = isAuction; + if (SkyblockerConfigManager.get().general.searchOverlay.keepPreviousSearches) { + Text[] messages = SearchOverManager.sign.getText(signFront).getMessages(CLIENT.shouldFilterText()); search = messages[0].getString(); - if(!messages[1].getString().isEmpty()){ - if (!search.endsWith(" ")){ + if (!messages[1].getString().isEmpty()) { + if (!search.endsWith(" ")) { search += " "; } - search += messages[1].getString(); + search += messages[1].getString(); } - }else{ + } else { search = ""; } suggestionsArray = new String[]{}; @@ -238,81 +220,66 @@ public class SearchOverManager { search = newValue; //update the suggestion values int totalSuggestions = SkyblockerConfigManager.get().general.searchOverlay.maxSuggestions; - suggestionsArray = new String[totalSuggestions]; if (newValue.isBlank() || totalSuggestions == 0) return; //do not search for empty value - if (IsAuction){ - suggestionsArray = auctionItems.stream().filter(item -> item.toLowerCase().contains(search.toLowerCase())).limit(totalSuggestions).toList().toArray(suggestionsArray); - }else { - suggestionsArray = bazaarItems.stream().filter(item -> item.toLowerCase().contains(search.toLowerCase())).limit(totalSuggestions).toList().toArray(suggestionsArray); - } + suggestionsArray = (isAuction ? auctionItems : bazaarItems).stream().filter(item -> item.toLowerCase().contains(search.toLowerCase())).limit(totalSuggestions).toArray(String[]::new); } /** * Gets the suggestion in the suggestion array at the index * @param index index of suggestion */ - protected static String getSuggestion(int index){ - if (suggestionsArray.length> index && suggestionsArray[index] != null){ + protected static String getSuggestion(int index) { + if (suggestionsArray.length > index && suggestionsArray[index] != null) { return suggestionsArray[index]; - }else{//there are no suggestions yet + } else {//there are no suggestions yet return ""; } } - protected static String getSuggestionId(int index){ - if (suggestionsArray.length> index && suggestionsArray[index] != null){ - return namesToId.get(suggestionsArray[index]); - }else{//there are no suggestions yet - return ""; - } + + protected static String getSuggestionId(int index) { + return namesToId.get(getSuggestion(index)); } /** * Gets the item name in the history array at the index * @param index index of suggestion */ - protected static String getHistory(int index){ - if (IsAuction){ - if (SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.size() >index){ - return SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.get(index); + protected static String getHistory(int index) { + if (isAuction) { + if (SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.size() > index) { + return SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.get(index); } - - }else{ - if (SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.size() >index){ - return SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.get(index); + } else { + if (SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.size() > index) { + return SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.get(index); } } - return null; + return null; } - protected static String getHistoryId(int index){ - if (IsAuction){ - if (SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.size() > index){ - return namesToId.get(capitalizeFully(SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.get(index))); - } - - }else{ - if (SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.size() > index){ - return namesToId.get(capitalizeFully(SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.get(index))); - } - } - return null; + protected static String getHistoryId(int index) { + return namesToId.get(getHistory(index)); } /** * Add the current search value to the start of the history list and truncate to the max history value and save this to the config */ - private static void saveHistory(){ + private static void saveHistory() { //save to history - int historyLength = SkyblockerConfigManager.get().general.searchOverlay.historyLength; - if (IsAuction){ - SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.add(0, search); - if (SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.size() > historyLength) { - SkyblockerConfigManager.get().general.searchOverlay.auctionHistory = SkyblockerConfigManager.get().general.searchOverlay.auctionHistory.subList(0, historyLength); + SkyblockerConfig.SearchOverlay config = SkyblockerConfigManager.get().general.searchOverlay; + if (isAuction) { + if (config.auctionHistory.isEmpty() || !config.auctionHistory.get(0).equals(search)) { + config.auctionHistory.add(0, search); + if (config.auctionHistory.size() > config.historyLength) { + config.auctionHistory = config.auctionHistory.subList(0, config.historyLength); + } } - }else{ - SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.add(0, search); - if (SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.size() > historyLength) { - SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory = SkyblockerConfigManager.get().general.searchOverlay.bazaarHistory.subList(0, historyLength); + } else { + if (config.bazaarHistory.isEmpty() || !config.bazaarHistory.get(0).equals(search)) { + config.bazaarHistory.add(0, search); + if (config.bazaarHistory.size() > config.historyLength) { + config.bazaarHistory = config.bazaarHistory.subList(0, config.historyLength); + } } } SkyblockerConfigManager.save(); @@ -323,18 +290,16 @@ public class SearchOverManager { */ protected static void pushSearch() { //save to history - if (!search.isEmpty()){ + if (!search.isEmpty()) { saveHistory(); } - if (IsCommand){ + if (isCommand) { pushCommand(); - } - else { + } else { pushSign(); } - - } + /** * runs the command to search for the value in ({@link SearchOverManager#search}) */ @@ -342,12 +307,12 @@ public class SearchOverManager { if (search.isEmpty()) return; String command; - if (IsAuction){ + if (isAuction) { command = "/ahSearch " + search; - }else{ - command = "/bz " + search; + } else { + command = "/bz " + search; } - MessageScheduler.INSTANCE.queueMessage(command, 0); + MessageScheduler.INSTANCE.sendMessageAfterCooldown(command); } /** @@ -355,38 +320,28 @@ public class SearchOverManager { */ private static void pushSign() { //splits text into 2 lines max = 30 chars - StringBuilder line0 = new StringBuilder(); - String line1; - if (search.length() <= 15) { - line0 = new StringBuilder(search); - line1 = ""; - }else { - String[] words = search.split(" "); - for (String word : words) { - if (line0.isEmpty()) { - line0 = new StringBuilder(word); - continue; - } - if (line0.length() + word.length() < 14) { //max 15 but including space is 14 - line0.append(" ").append(word); - } - else { - break; - } - } - line1 = search.substring(line0.length(), Math.min(search.length(), 30)); - } + Pair<String, String> split = splitString(search); // send packet to update sign - if (CLIENT.player != null || Sign != null) { - Text[] messages = Sign.getText(SignFront).getMessages(CLIENT.shouldFilterText()); - CLIENT.player.networkHandler.sendPacket(new UpdateSignC2SPacket(Sign.getPos(), SignFront, - line0.toString(), - line1, + if (CLIENT.player != null && sign != null) { + Text[] messages = sign.getText(signFront).getMessages(CLIENT.shouldFilterText()); + CLIENT.player.networkHandler.sendPacket(new UpdateSignC2SPacket(sign.getPos(), signFront, + split.left(), + split.right(), messages[2].getString(), messages[3].getString() )); } } + static Pair<String, String> splitString(String s) { + if (s.length() <= 15) { + return Pair.of(s, ""); + } + int index = s.lastIndexOf(' ', 15); + if (index == -1) { + return Pair.of(s.substring(0, 15), ""); + } + return Pair.of(s.substring(0, index), s.substring(index + 1, Math.min(index + 16, s.length())).trim()); + } } |