From 88fa6e03a7abfdb2801675d43abba6a88c6ab9bc Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Wed, 31 Jul 2024 10:01:26 -0500 Subject: [PATCH 01/17] Update Sidebar Icons to use Codecs & Grid Alignment Code --- .../ftb/mods/ftblibrary/FTBLibraryClient.java | 13 +- .../mods/ftblibrary/FTBLibraryCommands.java | 2 +- .../dev/ftb/mods/ftblibrary/icon/Icon.java | 12 + .../integration/REIIntegration.java | 412 +++++++++--------- .../ftblibrary/sidebar/SidebarButton.java | 286 ++++++------ .../sidebar/SidebarButtonGroup.java | 41 +- .../sidebar/SidebarButtonManager.java | 328 ++++++++------ .../sidebar/SidebarGroupGuiButton.java | 209 +++++++-- .../ftblibrary/sidebar/SidebarGuiButton.java | 33 +- .../assets/ftblibrary/sidebar_buttons.json | 2 +- .../sidebar_buttons/buttons/day.json | 14 + .../sidebar_buttons/buttons/gamemode.json | 10 + .../sidebar_buttons/buttons/night.json | 13 + .../sidebar_buttons/buttons/rain.json | 10 + .../sidebar_buttons/groups/cheat.json | 3 + .../sidebar_buttons/groups/info.json | 3 + .../sidebar_buttons/groups/util.json | 3 + .../neoforge/REINeoforgePluginStub.java | 16 +- 18 files changed, 833 insertions(+), 577 deletions(-) create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/day.json create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/gamemode.json create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/night.json create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/rain.json create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/cheat.json create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/info.json create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/util.json diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java index 3dabcb60..a91d8cc8 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java @@ -15,6 +15,7 @@ import dev.ftb.mods.ftblibrary.util.client.ClientUtils; import me.shedaniel.rei.api.client.config.ConfigObject; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.gui.screens.inventory.EffectRenderingInventoryScreen; @@ -73,6 +74,16 @@ private static void clientTick(Minecraft client) { ClientUtils.RUN_LATER.clear(); } + + + if(areButtonsVisible(client.screen)) { + for (GuiEventListener child : client.screen.children()) { + if(child instanceof SidebarGroupGuiButton button) { + button.tick(); + } + } + } + } public static boolean areButtonsVisible(@Nullable Screen gui) { @@ -90,7 +101,7 @@ public static boolean areButtonsVisible(@Nullable Screen gui) { } } - return gui instanceof AbstractContainerScreen && !SidebarButtonManager.INSTANCE.getGroups().isEmpty(); + return gui instanceof AbstractContainerScreen && !SidebarButtonManager.INSTANCE.getButtons().isEmpty(); } public static void editConfig(boolean isClientConfig) { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryCommands.java b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryCommands.java index c62e84fa..305ba786 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryCommands.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryCommands.java @@ -45,7 +45,7 @@ private interface NBTEditCallback { public static void registerCommands(CommandDispatcher dispatcher, CommandBuildContext commandBuildContext, Commands.CommandSelection type) { var command = Commands.literal("ftblibrary") .requires(commandSource -> commandSource.hasPermission(2)) - .then(Commands.literal("gamemode") + .then(Commands.literal("gamemode.json") .executes(context -> { if (!context.getSource().getPlayerOrException().isCreative()) { context.getSource().getPlayerOrException().setGameMode(GameType.CREATIVE); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/icon/Icon.java b/common/src/main/java/dev/ftb/mods/ftblibrary/icon/Icon.java index 55eba3a4..704a9858 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/icon/Icon.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/icon/Icon.java @@ -2,11 +2,20 @@ import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; +import com.mojang.datafixers.FunctionType; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.Decoder; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.Encoder; import dev.ftb.mods.ftblibrary.config.ImageResourceConfig; import dev.ftb.mods.ftblibrary.math.PixelBuffer; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.ExtraCodecs; import org.jetbrains.annotations.Nullable; import java.net.URI; @@ -20,6 +29,9 @@ public static Color4I empty() { return Color4I.EMPTY_ICON; } + //Todo Fix me + public static final Codec CODEC = ExtraCodecs.JSON.xmap(Icon::getIcon, Icon::getJson); + public static final StreamCodec STREAM_CODEC = new StreamCodec<>() { @Override public Icon decode(FriendlyByteBuf buf) { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java index f49413d9..c8ccbb8c 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java @@ -1,206 +1,206 @@ -package dev.ftb.mods.ftblibrary.integration; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.Lifecycle; -import dev.ftb.mods.ftblibrary.FTBLibrary; -import dev.ftb.mods.ftblibrary.config.ui.SelectItemStackScreen; -import dev.ftb.mods.ftblibrary.config.ui.ResourceSearchMode; -import dev.ftb.mods.ftblibrary.config.ui.SelectableResource; -import dev.ftb.mods.ftblibrary.icon.Color4I; -import dev.ftb.mods.ftblibrary.icon.Icon; -import dev.ftb.mods.ftblibrary.icon.ItemIcon; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButton; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonCreatedEvent; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonGroup; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonManager; -import dev.ftb.mods.ftblibrary.ui.GuiHelper; -import me.shedaniel.math.Rectangle; -import me.shedaniel.rei.api.client.favorites.FavoriteEntry; -import me.shedaniel.rei.api.client.favorites.FavoriteEntryType; -import me.shedaniel.rei.api.client.gui.Renderer; -import me.shedaniel.rei.api.client.gui.widgets.Tooltip; -import me.shedaniel.rei.api.client.gui.widgets.TooltipContext; -import me.shedaniel.rei.api.client.plugins.REIClientPlugin; -import me.shedaniel.rei.api.client.registry.entry.EntryRegistry; -import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; -import me.shedaniel.rei.api.common.util.CollectionUtils; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.resources.language.I18n; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class REIIntegration implements REIClientPlugin { - public static final ResourceLocation ID = FTBLibrary.rl("sidebar_button"); - - private static final ResourceSearchMode REI_ITEMS = new ResourceSearchMode<>() { - @Override - public Icon getIcon() { - return ItemIcon.getItemIcon(Items.GLOW_BERRIES); - } - - @Override - public MutableComponent getDisplayName() { - return Component.translatable("ftblibrary.select_item.list_mode.rei"); - } - - @Override - public Collection> getAllResources() { - return CollectionUtils.filterAndMap( - EntryRegistry.getInstance().getPreFilteredList(), - stack -> stack.getType().equals(VanillaEntryTypes.ITEM), - stack -> SelectableResource.item(stack.castValue()) - ); - } - }; - - static { - SelectItemStackScreen.KNOWN_MODES.prependMode(REI_ITEMS); - } - - @Override - public void registerFavorites(FavoriteEntryType.Registry registry) { - registry.register(ID, SidebarButtonType.INSTANCE); - for (var group : SidebarButtonManager.INSTANCE.getGroups()) { - List buttons = CollectionUtils.map(group.getButtons(), SidebarButtonEntry::new); - if (!buttons.isEmpty()) { - registry.getOrCrateSection(Component.translatable(group.getLangKey())) - .add(group.isPinned(), buttons.toArray(new SidebarButtonEntry[0])); - } - } - } - - private static SidebarButton createSidebarButton(ResourceLocation id, SidebarButtonGroup g, JsonObject json) { - SidebarButton b = new SidebarButton(id, g, json); - SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(b)); - return b; - } - - private enum SidebarButtonType implements FavoriteEntryType { - INSTANCE; - - @Override - public CompoundTag save(SidebarButtonEntry entry, CompoundTag tag) { - tag.putString("id", entry.button.getId().toString()); - tag.putString("json", new Gson().toJson(entry.button.getJson())); - return tag; - } - - @Override - public DataResult read(CompoundTag object) { - var id = ResourceLocation.parse(object.getString("id")); - var json = (JsonObject) JsonParser.parseString(object.getString("json")); - return DataResult.success(new SidebarButtonEntry(createSidebarButton(id, null, json)), Lifecycle.stable()); - } - - @Override - public DataResult fromArgs(Object... args) { - if (args.length == 0) { - return DataResult.error(() -> "Cannot create SidebarButtonEntry from empty args!"); - } - if (!(args[0] instanceof ResourceLocation id)) { - return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected ResourceLocation as the first argument!"); - } - if (!(args[1] instanceof SidebarButton) && !(args[1] instanceof JsonObject)) { - return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected SidebarButton or JsonObject as the second argument!"); - } - return DataResult.success(new SidebarButtonEntry(args[1] instanceof SidebarButton button ? button : createSidebarButton(id, null, (JsonObject) args[1])), Lifecycle.stable()); - } - } - - private static class SidebarButtonEntry extends FavoriteEntry { - private final SidebarButton button; - - public SidebarButtonEntry(SidebarButton button) { - this.button = button; - } - - @Override - public boolean isInvalid() { - for (var group : SidebarButtonManager.INSTANCE.getGroups()) { - for (var groupButton : group.getButtons()) { - if (groupButton.getId().equals(button.getId()) && groupButton.isActuallyVisible()) { - return false; - } - } - } - return true; - } - - @Override - public Renderer getRenderer(boolean showcase) { - return new Renderer() { - @Override - public void render(GuiGraphics graphics, Rectangle bounds, int mouseX, int mouseY, float delta) { - GuiHelper.setupDrawing(); - button.getIcon().draw(graphics, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); - if (button.getCustomTextHandler() != null) { - String text = button.getCustomTextHandler().get(); - Font font = Minecraft.getInstance().font; - if (!text.isEmpty()) { - var width = font.width(text); - Color4I.LIGHT_RED.draw(graphics, bounds.getX() + bounds.getWidth() - width, bounds.getY() - 1, width + 1, font.lineHeight); - graphics.drawString(font, text, bounds.getX() + bounds.getWidth() - width + 1, bounds.getY(), 0xFFFFFFFF); - } - } - } - - @Override - @Nullable - public Tooltip getTooltip(TooltipContext context) { - List list = new ArrayList<>(); - list.add(I18n.get(button.getLangKey())); - - if (button.getTooltipHandler() != null) { - button.getTooltipHandler().accept(list); - } - - return Tooltip.create(context.getPoint(), CollectionUtils.map(list, Component::literal)); - } - }; - } - - @Override - public boolean doAction(int button) { - this.button.onClicked(Screen.hasShiftDown()); - return true; - } - - @Override - public long hashIgnoreAmount() { - return this.button.getId().hashCode(); - } - - @Override - public FavoriteEntry copy() { - return new SidebarButtonEntry(createSidebarButton(button.getId(), null, button.getJson())); - } - - @Override - public ResourceLocation getType() { - return ID; - } - - @Override - public boolean isSame(FavoriteEntry other) { - if (other instanceof SidebarButtonEntry entry) { - return entry.button.getId().equals(button.getId()); - } - return false; - } - } -} +//package dev.ftb.mods.ftblibrary.integration; +// +//import com.google.gson.Gson; +//import com.google.gson.JsonObject; +//import com.google.gson.JsonParser; +//import com.mojang.serialization.DataResult; +//import com.mojang.serialization.Lifecycle; +//import dev.ftb.mods.ftblibrary.FTBLibrary; +//import dev.ftb.mods.ftblibrary.config.ui.SelectItemStackScreen; +//import dev.ftb.mods.ftblibrary.config.ui.ResourceSearchMode; +//import dev.ftb.mods.ftblibrary.config.ui.SelectableResource; +//import dev.ftb.mods.ftblibrary.icon.Color4I; +//import dev.ftb.mods.ftblibrary.icon.Icon; +//import dev.ftb.mods.ftblibrary.icon.ItemIcon; +//import dev.ftb.mods.ftblibrary.sidebar.SidebarButton; +//import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonCreatedEvent; +//import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonGroup; +//import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonManager; +//import dev.ftb.mods.ftblibrary.ui.GuiHelper; +//import me.shedaniel.math.Rectangle; +//import me.shedaniel.rei.api.client.favorites.FavoriteEntry; +//import me.shedaniel.rei.api.client.favorites.FavoriteEntryType; +//import me.shedaniel.rei.api.client.gui.Renderer; +//import me.shedaniel.rei.api.client.gui.widgets.Tooltip; +//import me.shedaniel.rei.api.client.gui.widgets.TooltipContext; +//import me.shedaniel.rei.api.client.plugins.REIClientPlugin; +//import me.shedaniel.rei.api.client.registry.entry.EntryRegistry; +//import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; +//import me.shedaniel.rei.api.common.util.CollectionUtils; +//import net.minecraft.client.Minecraft; +//import net.minecraft.client.gui.Font; +//import net.minecraft.client.gui.GuiGraphics; +//import net.minecraft.client.gui.screens.Screen; +//import net.minecraft.client.resources.language.I18n; +//import net.minecraft.nbt.CompoundTag; +//import net.minecraft.network.chat.Component; +//import net.minecraft.network.chat.MutableComponent; +//import net.minecraft.resources.ResourceLocation; +//import net.minecraft.world.item.ItemStack; +//import net.minecraft.world.item.Items; +//import org.jetbrains.annotations.Nullable; +// +//import java.util.ArrayList; +//import java.util.Collection; +//import java.util.List; +// +//public class REIIntegration implements REIClientPlugin { +// public static final ResourceLocation ID = FTBLibrary.rl("sidebar_button"); +// +// private static final ResourceSearchMode REI_ITEMS = new ResourceSearchMode<>() { +// @Override +// public Icon getIcon() { +// return ItemIcon.getItemIcon(Items.GLOW_BERRIES); +// } +// +// @Override +// public MutableComponent getDisplayName() { +// return Component.translatable("ftblibrary.select_item.list_mode.rei"); +// } +// +// @Override +// public Collection> getAllResources() { +// return CollectionUtils.filterAndMap( +// EntryRegistry.getInstance().getPreFilteredList(), +// stack -> stack.getType().equals(VanillaEntryTypes.ITEM), +// stack -> SelectableResource.item(stack.castValue()) +// ); +// } +// }; +// +// static { +// SelectItemStackScreen.KNOWN_MODES.prependMode(REI_ITEMS); +// } +// +// @Override +// public void registerFavorites(FavoriteEntryType.Registry registry) { +// registry.register(ID, SidebarButtonType.INSTANCE); +// for (var group : SidebarButtonManager.INSTANCE.getGroups()) { +// List buttons = CollectionUtils.map(group.getButtons(), SidebarButtonEntry::new); +// if (!buttons.isEmpty()) { +// registry.getOrCrateSection(Component.translatable(group.getLangKey())) +// .add(group.isPinned(), buttons.toArray(new SidebarButtonEntry[0])); +// } +// } +// } +// +// private static SidebarButton createSidebarButton(ResourceLocation id, SidebarButtonGroup g, JsonObject json) { +// SidebarButton b = new SidebarButton(id, g, json); +// SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(b)); +// return b; +// } +// +// private enum SidebarButtonType implements FavoriteEntryType { +// INSTANCE; +// +// @Override +// public CompoundTag save(SidebarButtonEntry entry, CompoundTag tag) { +// tag.putString("id", entry.button.getId().toString()); +// tag.putString("json", new Gson().toJson(entry.button.getJson())); +// return tag; +// } +// +// @Override +// public DataResult read(CompoundTag object) { +// var id = ResourceLocation.parse(object.getString("id")); +// var json = (JsonObject) JsonParser.parseString(object.getString("json")); +// return DataResult.success(new SidebarButtonEntry(createSidebarButton(id, null, json)), Lifecycle.stable()); +// } +// +// @Override +// public DataResult fromArgs(Object... args) { +// if (args.length == 0) { +// return DataResult.error(() -> "Cannot create SidebarButtonEntry from empty args!"); +// } +// if (!(args[0] instanceof ResourceLocation id)) { +// return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected ResourceLocation as the first argument!"); +// } +// if (!(args[1] instanceof SidebarButton) && !(args[1] instanceof JsonObject)) { +// return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected SidebarButton or JsonObject as the second argument!"); +// } +// return DataResult.success(new SidebarButtonEntry(args[1] instanceof SidebarButton button ? button : createSidebarButton(id, null, (JsonObject) args[1])), Lifecycle.stable()); +// } +// } +// +// private static class SidebarButtonEntry extends FavoriteEntry { +// private final SidebarButton button; +// +// public SidebarButtonEntry(SidebarButton button) { +// this.button = button; +// } +// +// @Override +// public boolean isInvalid() { +// for (var group : SidebarButtonManager.INSTANCE.getGroups()) { +// for (var groupButton : group.getButtons()) { +// if (groupButton.getId().equals(button.getId()) && groupButton.isActuallyVisible()) { +// return false; +// } +// } +// } +// return true; +// } +// +// @Override +// public Renderer getRenderer(boolean showcase) { +// return new Renderer() { +// @Override +// public void render(GuiGraphics graphics, Rectangle bounds, int mouseX, int mouseY, float delta) { +// GuiHelper.setupDrawing(); +// button.getIcon().draw(graphics, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); +// if (button.getCustomTextHandler() != null) { +// String text = button.getCustomTextHandler().get(); +// Font font = Minecraft.getInstance().font; +// if (!text.isEmpty()) { +// var width = font.width(text); +// Color4I.LIGHT_RED.draw(graphics, bounds.getX() + bounds.getWidth() - width, bounds.getY() - 1, width + 1, font.lineHeight); +// graphics.drawString(font, text, bounds.getX() + bounds.getWidth() - width + 1, bounds.getY(), 0xFFFFFFFF); +// } +// } +// } +// +// @Override +// @Nullable +// public Tooltip getTooltip(TooltipContext context) { +// List list = new ArrayList<>(); +// list.add(I18n.get(button.getLangKey())); +// +// if (button.getTooltipHandler() != null) { +// button.getTooltipHandler().accept(list); +// } +// +// return Tooltip.create(context.getPoint(), CollectionUtils.map(list, Component::literal)); +// } +// }; +// } +// +// @Override +// public boolean doAction(int button) { +// this.button.onClicked(Screen.hasShiftDown()); +// return true; +// } +// +// @Override +// public long hashIgnoreAmount() { +// return this.button.getId().hashCode(); +// } +// +// @Override +// public FavoriteEntry copy() { +// return new SidebarButtonEntry(createSidebarButton(button.getId(), null, button.getJson())); +// } +// +// @Override +// public ResourceLocation getType() { +// return ID; +// } +// +// @Override +// public boolean isSame(FavoriteEntry other) { +// if (other instanceof SidebarButtonEntry entry) { +// return entry.button.getId().equals(button.getId()); +// } +// return false; +// } +// } +//} diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java index 8dd8ca96..6cf1fafa 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java @@ -1,213 +1,175 @@ package dev.ftb.mods.ftblibrary.sidebar; -import com.google.gson.JsonObject; -import dev.architectury.platform.Platform; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import dev.ftb.mods.ftblibrary.FTBLibraryClient; import dev.ftb.mods.ftblibrary.icon.Icon; -import dev.ftb.mods.ftblibrary.icon.Icons; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import dev.ftb.mods.ftblibrary.ui.misc.LoadingScreen; -import dev.ftb.mods.ftblibrary.util.ChainedBooleanSupplier; -import dev.ftb.mods.ftblibrary.util.client.ClientUtils; import net.minecraft.Util; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashSet; import java.util.List; -import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; -public class SidebarButton implements Comparable { - private static final BooleanSupplier NEI_NOT_LOADED = () -> !Platform.isModLoaded("notenoughitems"); - - private final ResourceLocation id; - private final JsonObject json; - private final SidebarButtonGroup group; - - private Icon icon = Icon.empty(); - private int x = 0; - private boolean defaultConfig = true; - private boolean configValue = true; - private final List clickEvents = new ArrayList<>(); - private final List shiftClickEvents = new ArrayList<>(); - private final boolean loadingScreen; - private ChainedBooleanSupplier visible = ChainedBooleanSupplier.TRUE; - private Supplier customTextHandler = null; - private Consumer> tooltipHandler = null; - - public SidebarButton(ResourceLocation id, SidebarButtonGroup group, JsonObject json) { - this.group = group; - this.id = id; - this.json = json; - - if (json.has("icon")) { - icon = Icon.getIcon(json.get("icon")); - } - - if (icon.isEmpty()) { - icon = Icons.ACCEPT_GRAY; - } - - if (json.has("click")) { - var j = json.get("click"); - for (var e : j.isJsonArray() ? j.getAsJsonArray() : Collections.singleton(j)) { - if (e.isJsonPrimitive()) { - clickEvents.add(e.getAsString()); - } - } - } - if (json.has("shift_click")) { - var j = json.get("shift_click"); - for (var e : j.isJsonArray() ? j.getAsJsonArray() : Collections.singleton(j)) { - if (e.isJsonPrimitive()) { - shiftClickEvents.add(e.getAsString()); - } - } - } - if (json.has("config")) { - defaultConfig = configValue = json.get("config").getAsBoolean(); - } - - if (json.has("x")) { - x = json.get("x").getAsInt(); - } - - if (json.has("requires_op") && json.get("requires_op").getAsBoolean()) { - addVisibilityCondition(ClientUtils.IS_CLIENT_OP); - } - - if (json.has("hide_with_nei") && json.get("hide_with_nei").getAsBoolean()) { - addVisibilityCondition(NEI_NOT_LOADED); - } - - if (json.has("required_mods")) { - var requiredServerMods = new LinkedHashSet(); - - for (var e : json.get("required_mods").getAsJsonArray()) { - requiredServerMods.add(e.getAsString()); - } - - addVisibilityCondition(() -> { - for (var s : requiredServerMods) { - if (!Platform.isModLoaded(s)) { - return false; - } - } - - return true; - }); - } - - loadingScreen = json.has("loading_screen") && json.get("loading_screen").getAsBoolean(); - } - - public static SidebarButton copyWithoutGroup(SidebarButton toCopy) { - return new SidebarButton(toCopy.id, null, toCopy.json); - } - - public ResourceLocation getId() { - return id; - } - - public SidebarButtonGroup getGroup() { - return group; - } - - public JsonObject getJson() { - return json; - } - - public void addVisibilityCondition(BooleanSupplier supplier) { - visible = visible.and(supplier); - } +public record SidebarButton( + ResourceLocation group, + Icon icon, + int x, + boolean defaultEnabled, + List clickEvents, + List shiftClickEvent, + boolean loadingScreen, + List tooltips, + boolean requiresOp) implements Comparable { + + public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( + ResourceLocation.CODEC.fieldOf("group").forGetter(SidebarButton::group), + Icon.CODEC.fieldOf("icon").forGetter(SidebarButton::icon), + Codec.BOOL.fieldOf("requires_op").orElse(false).forGetter(SidebarButton::requiresOp), + Codec.STRING.listOf(1, Integer.MAX_VALUE).fieldOf("click").orElse(List.of()).forGetter(SidebarButton::clickEvents), + Codec.STRING.listOf().fieldOf("shift_click").orElse(List.of()).forGetter(SidebarButton::shiftClickEvent), + Codec.BOOL.fieldOf("loading_screen").orElse(false).forGetter(SidebarButton::loadingScreen), + Codec.BOOL.fieldOf("default_enabled").orElse(true).forGetter(SidebarButton::defaultEnabled), + Codec.STRING.listOf().fieldOf("text").orElse(List.of()).forGetter(SidebarButton::tooltips) + ).apply(builder, SidebarButton::of)); +// +// + public static SidebarButton of(ResourceLocation group, + Icon icon, + boolean requiresOp, + List clickEvents, + List shiftClickEvents, + boolean loadingScreen, + boolean defaultEnabled, + List tooltips) { + return new SidebarButton( group, icon, 0, defaultEnabled, clickEvents, shiftClickEvents, loadingScreen, tooltips, requiresOp); + } + + +// public SidebarButton(ResourceLocation id, SidebarButtonGroup group, JsonObject json) { +// this.group = group; +// this.id = id; +// this.json = json; +// +// if (json.has("icon")) { +// icon = Icon.getIcon(json.get("icon")); +// } +// +// if (icon.isEmpty()) { +// icon = Icons.ACCEPT_GRAY; +// } +// +// if (json.has("click")) { +// var j = json.get("click"); +// for (var e : j.isJsonArray() ? j.getAsJsonArray() : Collections.singleton(j)) { +// if (e.isJsonPrimitive()) { +// clickEvents.add(e.getAsString()); +// } +// } +// } +// if (json.has("shift_click")) { +// var j = json.get("shift_click"); +// for (var e : j.isJsonArray() ? j.getAsJsonArray() : Collections.singleton(j)) { +// if (e.isJsonPrimitive()) { +// shiftClickEvents.add(e.getAsString()); +// } +// } +// } +// if (json.has("config")) { +// defaultEnabled = configValue = json.get("config").getAsBoolean(); +// } +// +// if (json.has("x")) { +// x = json.get("x").getAsInt(); +// } +// +// if (json.has("requires_op") && json.get("requires_op").getAsBoolean()) { +// addVisibilityCondition(ClientUtils.IS_CLIENT_OP); +// } +// +// if (json.has("required_mods")) { +// var requiredServerMods = new LinkedHashSet(); +// +// for (var e : json.get("required_mods").getAsJsonArray()) { +// requiredServerMods.add(e.getAsString()); +// } +// +// addVisibilityCondition(() -> { +// for (var s : requiredServerMods) { +// if (!Platform.isModLoaded(s)) { +// return false; +// } +// } +// +// return true; +// }); +// } +// +// loadingScreen = json.has("loading_screen") && json.get("loading_screen").getAsBoolean(); +// } + + +// public ResourceLocation getId() { +// return id; +// } +// +// public SidebarButtonGroup getGroup() { +// return group; +// } +// +// public JsonObject getJson() { +// return json; +// } +// +// public void addVisibilityCondition(BooleanSupplier supplier) { +// visible = visible.and(supplier); +// } public String getLangKey() { - return Util.makeDescriptionId("sidebar_button", id); + //Todo -unreal + return Util.makeDescriptionId("sidebar_button", ResourceLocation.fromNamespaceAndPath("ftbquests", "sidebar_button")); } public String getTooltipLangKey() { return getLangKey() + ".tooltip"; } - @Override - public String toString() { - return id.toString(); - } - - @Override - public final int hashCode() { - return id.hashCode(); - } - - @Override - public final boolean equals(Object o) { - return o == this || o instanceof SidebarButton && id.equals(((SidebarButton) o).id); - } - - public Icon getIcon() { - return icon; - } - - public int getX() { - return x; - } - - public boolean getDefaultConfig() { - return defaultConfig; - } - public void onClicked(boolean shift) { if (loadingScreen) { new LoadingScreen(Component.translatable(getLangKey())).openGui(); } - for (var event : (shift && !shiftClickEvents.isEmpty() ? shiftClickEvents : clickEvents)) { + for (var event : (shift && !shiftClickEvent.isEmpty() ? shiftClickEvent : clickEvents)) { GuiHelper.BLANK_GUI.handleClick(event); } } - public boolean isActuallyVisible() { - return configValue && FTBLibraryClient.showButtons != 0 && isVisible(); - } - public boolean isVisible() { - return visible.getAsBoolean(); - } - - public boolean getConfig() { - return configValue; + return true; } - public void setConfig(boolean value) { - configValue = value; - } @Nullable public Supplier getCustomTextHandler() { - return customTextHandler; + return () -> ""; } - public void setCustomTextHandler(Supplier text) { - customTextHandler = text; - } @Nullable public Consumer> getTooltipHandler() { - return tooltipHandler; + return s -> {}; } - public void setTooltipHandler(Consumer> text) { - tooltipHandler = text; - } + @Override public int compareTo(SidebarButton button) { - return getX() - button.getX(); + return x - button.x; } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java index 9160533b..1061b714 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java @@ -1,5 +1,9 @@ package dev.ftb.mods.ftblibrary.sidebar; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import dev.ftb.mods.ftblibrary.icon.Icon; import net.minecraft.Util; import net.minecraft.resources.ResourceLocation; @@ -7,41 +11,22 @@ import java.util.List; -public class SidebarButtonGroup implements Comparable { - private final ResourceLocation id; - private final int y; - private final boolean isPinned; - private final List buttons; +public record SidebarButtonGroup(int y, boolean isPinned) implements Comparable { - public SidebarButtonGroup(ResourceLocation id, int y, boolean isPinned) { - this.id = id; - this.y = y; - this.isPinned = isPinned; - buttons = new ArrayList<>(); - } - public ResourceLocation getId() { - return id; - } + public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( + Codec.INT.fieldOf("y").forGetter(SidebarButtonGroup::y), + Codec.BOOL.fieldOf("isPinned").orElse(false).forGetter(SidebarButtonGroup::isPinned) + ).apply(builder, SidebarButtonGroup::new)); - public String getLangKey() { - return Util.makeDescriptionId("sidebar_group", id); - } - public boolean isPinned() { - return isPinned; - } - - public int getY() { - return y; - } - - public List getButtons() { - return buttons; + public String getLangKey() { + //Todo -unreal + return Util.makeDescriptionId("sidebar_group", ResourceLocation.fromNamespaceAndPath("ftbquests", "sidebar_group_" + y)); } @Override public int compareTo(SidebarButtonGroup group) { - return getY() - group.getY(); + return y - group.y; } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index b885ea84..7ae367ca 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -2,186 +2,238 @@ import com.google.gson.*; import com.google.gson.stream.JsonWriter; +import com.mojang.logging.LogUtils; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JsonOps; import dev.architectury.platform.Platform; import dev.ftb.mods.ftblibrary.FTBLibrary; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; public enum SidebarButtonManager implements ResourceManagerReloadListener { INSTANCE; - private final List groups = new ArrayList<>(); + private static final Logger LOGGER = LogUtils.getLogger(); - public List getGroups() { - return groups; - } + private final Map groups = new HashMap<>(); + private final Map buttons = new HashMap<>(); private JsonElement readJson(Resource resource) { - try (var reader = resource.openAsReader()) { + try (BufferedReader reader = resource.openAsReader()) { return JsonParser.parseReader(reader); } catch (JsonParseException | IOException e) { - FTBLibrary.LOGGER.warn("can't read {}: {}", resource.sourcePackId(), e.getMessage()); + LOGGER.error("can't read {}: {}", resource.sourcePackId(), e.getMessage()); } - return JsonNull.INSTANCE; } - private JsonElement readJson(File file) { - try (var reader = new FileReader(file)) { - return JsonParser.parseReader(reader); - } catch (JsonParseException | IOException e) { - FTBLibrary.LOGGER.warn("can't read {}: {}", file.getAbsolutePath(), e.getMessage()); - } - - return JsonNull.INSTANCE; + public Map getButtons() { + return buttons; } - @Override - public void onResourceManagerReload(ResourceManager manager) { - groups.clear(); - - var element = readJson(Platform.getConfigFolder().resolve("sidebar_buttons.json").toFile()); - JsonObject sidebarButtonConfig; - - if (element.isJsonObject()) { - sidebarButtonConfig = element.getAsJsonObject(); - } else { - sidebarButtonConfig = new JsonObject(); - } - - Map groupMap = new HashMap<>(); - - for (var domain : manager.getNamespaces()) { - try { - // TODO: Use an alternative way to register sidebar groups because jsons are a bit messy - for (var resource : manager.getResourceStack(ResourceLocation.fromNamespaceAndPath(domain, "sidebar_button_groups.json"))) { - var json = readJson(resource); - - for (var entry : json.getAsJsonObject().entrySet()) { - if (entry.getValue().isJsonObject()) { - var groupJson = entry.getValue().getAsJsonObject(); - var y = 0; - var pinned = true; - - if (groupJson.has("y")) { - y = groupJson.get("y").getAsInt(); - } - - if(groupJson.has("pinned")) { - pinned = groupJson.get("pinned").getAsBoolean(); - } - - var group = new SidebarButtonGroup(ResourceLocation.fromNamespaceAndPath(domain, entry.getKey()), y, pinned); - groupMap.put(group.getId(), group); - } - } + public Map> getButtonGroups() { + Map> map = new HashMap<>(); + for (SidebarButton value : buttons.values()) { + SidebarButtonGroup group = groups.get(value.group()); + if(group != null) { + if(!map.containsKey(group)) { + map.put(group, new ArrayList<>()); } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - for (var domain : manager.getNamespaces()) { - try { - for (var resource : manager.getResourceStack(ResourceLocation.fromNamespaceAndPath(domain, "sidebar_buttons.json"))) { - var json = readJson(resource); - - if (json.isJsonObject()) { - for (var entry : json.getAsJsonObject().entrySet()) { - if (entry.getValue().isJsonObject()) { - var buttonJson = entry.getValue().getAsJsonObject(); - - if (!buttonJson.has("group")) { - continue; - } + map.get(group).add(value); - if (/*!FTBLibConfig.debugging.dev_sidebar_buttons && */buttonJson.has("dev_only") && buttonJson.get("dev_only").getAsBoolean()) { - continue; - } - - var group = groupMap.get(ResourceLocation.parse(buttonJson.get("group").getAsString())); - - if (group == null) { - continue; - } - - var button = new SidebarButton(ResourceLocation.fromNamespaceAndPath(domain, entry.getKey()), group, buttonJson); - - group.getButtons().add(button); - - if (sidebarButtonConfig.has(button.getId().getNamespace())) { - var e = sidebarButtonConfig.get(button.getId().getNamespace()); - - if (e.isJsonObject() && e.getAsJsonObject().has(button.getId().getPath())) { - button.setConfig(e.getAsJsonObject().get(button.getId().getPath()).getAsBoolean()); - } - } else if (sidebarButtonConfig.has(button.getId().toString())) { - button.setConfig(sidebarButtonConfig.get(button.getId().toString()).getAsBoolean()); - } - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - for (var group : groupMap.values()) { - if (!group.getButtons().isEmpty()) { - group.getButtons().sort(null); - groups.add(group); + }else { + //Todo This should never happen in theory } } + return map.entrySet().stream().sorted(Comparator.comparingInt(o -> o.getKey().y())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); + } - groups.sort(null); - - for (var group : groups) { - for (var button : group.getButtons()) { - SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(button)); + @Override + public void onResourceManagerReload(ResourceManager manager) { + groups.clear(); + buttons.clear(); + + loadResources(manager, "sidebar_buttons/groups", SidebarButtonGroup.CODEC, groups::put); + loadResources(manager, "sidebar_buttons/buttons", SidebarButton.CODEC, (fixed, result) -> { + if (groups.containsKey(result.group())) { + buttons.put(fixed, result); + } else { + LOGGER.error("Can't load Sidebar Button {} because group {} not found", fixed, result.group()); } - } - - saveConfig(); + }); } - public void saveConfig() { - var o = new JsonObject(); - - for (var group : groups) { - for (var button : group.getButtons()) { - var o1 = o.getAsJsonObject(button.getId().getNamespace()); - if (o1 == null) { - o1 = new JsonObject(); - o.add(button.getId().getNamespace(), o1); - } - - o1.addProperty(button.getId().getPath(), button.getConfig()); +// var element = readJson(Platform.getConfigFolder().resolve("sidebar_buttons.json").toFile()); +// JsonObject sidebarButtonConfig; +// +// if (element.isJsonObject()) { +// sidebarButtonConfig = element.getAsJsonObject(); +// } else { +// sidebarButtonConfig = new JsonObject(); +// } +// +// Map groupMap = new HashMap<>(); +// +// for (var domain : manager.getNamespaces()) { +// try { +// // TODO: Use an alternative way to register sidebar groups because jsons are a bit messy +// for (var resource : manager.getResourceStack(ResourceLocation.fromNamespaceAndPath(domain, "sidebar_button_groups.json"))) { +// var json = readJson(resource); +// +// for (var entry : json.getAsJsonObject().entrySet()) { +// if (entry.getValue().isJsonObject()) { +// var groupJson = entry.getValue().getAsJsonObject(); +// var y = 0; +// var pinned = true; +// +// if (groupJson.has("y")) { +// y = groupJson.get("y").getAsInt(); +// } +// +// if(groupJson.has("pinned")) { +// pinned = groupJson.get("pinned").getAsBoolean(); +// } +// +// var group = new SidebarButtonGroup(ResourceLocation.fromNamespaceAndPath(domain, entry.getKey()), y, pinned); +// groupMap.put(group.getId(), group); +// } +// } +// } +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// } +// +// for (String domain : manager.getNamespaces()) { +// try { +// for (Resource resource : manager.getResourceStack(ResourceLocation.fromNamespaceAndPath(domain, "sidebar_buttons.json"))) { +// JsonElement json = readJson(resource); +// +// if (json.isJsonObject()) { +// for (var entry : json.getAsJsonObject().entrySet()) { +// if (entry.getValue().isJsonObject()) { +// var buttonJson = entry.getValue().getAsJsonObject(); +// +// if (!buttonJson.has("group")) { +// continue; +// } +// +// if (/*!FTBLibConfig.debugging.dev_sidebar_buttons && */buttonJson.has("dev_only") && buttonJson.get("dev_only").getAsBoolean()) { +// continue; +// } +// +// var group = groupMap.get(ResourceLocation.parse(buttonJson.get("group").getAsString())); +// +// if (group == null) { +// continue; +// } +// +// var button = new SidebarButton(ResourceLocation.fromNamespaceAndPath(domain, entry.getKey()), group, buttonJson); +// +// group.getButtons().add(button); +// +// if (sidebarButtonConfig.has(button.getId().getNamespace())) { +// var e = sidebarButtonConfig.get(button.getId().getNamespace()); +// +// if (e.isJsonObject() && e.getAsJsonObject().has(button.getId().getPath())) { +// button.setConfig(e.getAsJsonObject().get(button.getId().getPath()).getAsBoolean()); +// } +// } else if (sidebarButtonConfig.has(button.getId().toString())) { +// button.setConfig(sidebarButtonConfig.get(button.getId().toString()).getAsBoolean()); +// } +// } +// } +// } +// } +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// } +// +// for (var group : groupMap.values()) { +// if (!group.getButtons().isEmpty()) { +// group.getButtons().sort(null); +// groups.add(group); +// } +// } +// +// groups.sort(null); +// +// for (var group : groups) { +// for (var button : group.getButtons()) { +// SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(button)); +// } +// } +// +// saveConfig(); + + private void loadResources(ResourceManager manager, String path, Codec codec, BiConsumer consumer) { + Map resourceLocationResourceMap = manager.listResources(path, name -> name.getPath().endsWith(".json")); + for (Map.Entry resource : resourceLocationResourceMap.entrySet()) { + JsonElement jsonElement = readJson(resource.getValue()); + DataResult parse = codec.parse(JsonOps.INSTANCE, jsonElement); + if (parse.error().isPresent()) { + FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); + } else { + T result = parse.result().get(); + ResourceLocation key = resource.getKey(); + ResourceLocation fixed = ResourceLocation.fromNamespaceAndPath(key.getNamespace(), key.getPath().replace(path + "/", "").replace(".json", "")); + consumer.accept(fixed, result); } } + } - var file = Platform.getConfigFolder().resolve("sidebar_buttons.json").toFile(); - - try (var writer = new FileWriter(file)) { - var gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); - var jsonWriter = new JsonWriter(writer); - jsonWriter.setIndent("\t"); - gson.toJson(o, jsonWriter); - } catch (Exception ex) { - ex.printStackTrace(); - } + public void saveConfig() { } +// var o = new JsonObject(); +// +// for (var group : groups) { +// for (var button : group.getButtons()) { +// var o1 = o.getAsJsonObject(button.getId().getNamespace()); +// +// if (o1 == null) { +// o1 = new JsonObject(); +// o.add(button.getId().getNamespace(), o1); +// } +// +// o1.addProperty(button.getId().getPath(), button.getConfig()); +// } +// } +// +// var file = Platform.getConfigFolder().resolve("sidebar_buttons.json").toFile(); +// +// try (var writer = new FileWriter(file)) { +// var gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); +// var jsonWriter = new JsonWriter(writer); +// jsonWriter.setIndent("\t"); +// gson.toJson(o, jsonWriter); +// } catch (Exception ex) { +// ex.printStackTrace(); +// } + + + @Nullable + public SidebarButtonGroup getGroup(ResourceLocation group) { + return groups.get(group); } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index d01a602a..e6cde412 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -1,7 +1,11 @@ package dev.ftb.mods.ftblibrary.sidebar; +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.math.Axis; import dev.ftb.mods.ftblibrary.icon.Color4I; +import dev.ftb.mods.ftblibrary.ui.Button; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; @@ -11,36 +15,52 @@ import net.minecraft.client.renderer.Rect2i; import net.minecraft.client.resources.language.I18n; import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import org.joml.Quaternionf; import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; public class SidebarGroupGuiButton extends AbstractButton { public static Rect2i lastDrawnArea = new Rect2i(0, 0, 0, 0); + private static final int BUTTON_SPACING = 17; + + private final List buttons = new ArrayList<>(); - private final List buttons; private SidebarGuiButton mouseOver; + private SidebarGuiButton selectedButton; + private GridLocation selectedLocation; + private boolean isMouseDown; + private int mouseDownTime; + private boolean isEditMode; + private int currentMouseX; + private int currentMouseY; + + private int mouseOffsetX; + private int mouseOffsetY; + public SidebarGroupGuiButton() { super(0, 0, 0, 0, Component.empty()); - buttons = new ArrayList<>(); - } - - @Override - public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { - buttons.clear(); - mouseOver = null; int rx, ry = 0; boolean addedAny; - for (var group : SidebarButtonManager.INSTANCE.getGroups()) { + for (Map.Entry> buttonEntry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { rx = 0; addedAny = false; - for (var button : group.getButtons()) { - if (button.isActuallyVisible()) { - buttons.add(new SidebarGuiButton(rx, ry, button)); + SidebarButtonGroup group = buttonEntry.getKey(); + for (SidebarButton sidebarButton : buttonEntry.getValue()) { + if(sidebarButton.isVisible()) { + SidebarGuiButton e = new SidebarGuiButton(rx, ry, sidebarButton); + buttons.add(e); rx++; addedAny = true; } @@ -51,12 +71,17 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick } } - for (var button : buttons) { - button.x = 1 + button.buttonX * 17; - button.y = 1 + button.buttonY * 17; - } + isMouseDown = false; + } + + @Override + public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { + currentMouseX = mx; + currentMouseY = my; + + mouseOver = null; - setX(Integer.MAX_VALUE); + setX(Integer.MAX_VALUE); setY(Integer.MAX_VALUE); var maxX = Integer.MIN_VALUE; var maxY = Integer.MIN_VALUE; @@ -88,33 +113,84 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick height = maxY - getY(); //zLevel = 0F; + if (isEditMode) { + //draw box with one extra spot of 16x16 on each side with current + int maxWidth = buttons + .stream().max(Comparator.comparingInt(SidebarGuiButton::getGridX)) + .map(SidebarGuiButton::getGridX) + .orElse(1) + 2; + int maxHeight = buttons + .stream() + .max(Comparator.comparingInt(SidebarGuiButton::getGridY)) + .map(SidebarGuiButton::getGridY) + .orElse(1) + 2; + + //Don't show extra row on bottom if everything is vertically aligned + if(maxHeight == buttons.size() + 1) { + maxHeight--; + } + //Don't show extra column on right if everything is horizontally aligned + if(maxWidth == buttons.size() + 1) { + maxWidth--; + } + + Color4I.GRAY.draw(graphics, 0, 0, maxWidth * BUTTON_SPACING, maxHeight * BUTTON_SPACING); + //draw black grid lines + for (var i = 0; i < maxWidth + 1; i++) { + Color4I.BLACK.draw(graphics, i * BUTTON_SPACING, 0, 1, maxHeight * BUTTON_SPACING); + } + for (var i = 0; i < maxHeight + 1; i++) { + Color4I.BLACK.draw(graphics, 0, i * BUTTON_SPACING, maxWidth * BUTTON_SPACING, 1); + } + + if(selectedButton != null) { + GridLocation gridLocation = getGridLocation(mx, my); + gridLocation = new GridLocation(Math.min(maxWidth - 1, Math.max(0, gridLocation.x)), Math.min(maxHeight - 1, Math.max(0, gridLocation.y))); + Color4I.WHITE.draw(graphics, gridLocation.x * BUTTON_SPACING + 1, gridLocation.y * BUTTON_SPACING + 1, 16, 16); + } + } + graphics.pose().pushPose(); graphics.pose().translate(0, 0, 500); var font = Minecraft.getInstance().font; - for (var b : buttons) { + //Todo better way? + List sortedButtons = new ArrayList<>(buttons); + if(selectedButton != null) { + sortedButtons.remove(selectedButton); + sortedButtons.addLast(selectedButton); + } + + for (SidebarGuiButton button : sortedButtons) { + if (isEditMode && button == selectedButton) { + button.x = mx - mouseOffsetX; + button.y = my - mouseOffsetY; + }else { + button.x = 1 + button.getGridX() * BUTTON_SPACING; + button.y = 1 + button.getGridY() * BUTTON_SPACING; + } GuiHelper.setupDrawing(); - b.button.getIcon().draw(graphics, b.x, b.y, 16, 16); + button.button.icon().draw(graphics, button.x, button.y, 16, 16); - if (b == mouseOver) { - Color4I.WHITE.withAlpha(33).draw(graphics, b.x, b.y, 16, 16); + if (button == mouseOver) { + Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); } - if (b.button.getCustomTextHandler() != null) { - var text = b.button.getCustomTextHandler().get(); + if (button.button.getCustomTextHandler() != null) { + var text = button.button.getCustomTextHandler().get(); if (!text.isEmpty()) { var nw = font.width(text); var width = 16; - Color4I.LIGHT_RED.draw(graphics, b.x + width - nw, b.y - 1, nw + 1, 9); - graphics.drawString(font, text, b.x + width - nw + 1, b.y, 0xFFFFFFFF); + Color4I.LIGHT_RED.draw(graphics, button.x + width - nw, button.y - 1, nw + 1, 9); + graphics.drawString(font, text, button.x + width - nw + 1, button.y, 0xFFFFFFFF); RenderSystem.setShaderColor(1F, 1F, 1F, 1F); } } } - if (mouseOver != null) { + if (!isEditMode && mouseOver != null) { GuiHelper.setupDrawing(); var mx1 = mx + 10; var my1 = Math.max(3, my - 9); @@ -146,12 +222,69 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick lastDrawnArea = new Rect2i(getX(), getY(), width, height); graphics.pose().popPose(); + } @Override - public void onPress() { - if (mouseOver != null) { + public void onRelease(double d, double e) { + super.onRelease(d, e); + isMouseDown = false; + if (!isEditMode && mouseOver != null) { mouseOver.button.onClicked(Screen.hasShiftDown()); + } else { + if (selectedButton != null) { + GridLocation gLocation = getGridLocation(currentMouseX, currentMouseY); + //Checks if the icon is placed in the same location picked up from, if so do nothing + if (!gLocation.equals(selectedLocation)) { + //Checks for any icon at the place location and to left of that and moves them over one + for (SidebarGuiButton button : buttons) { + if(!selectedButton.equals(button)) { + if (button.getGridY() == gLocation.y && button.getGridX() >= gLocation.x) { + button.setGrid(button.getGridX() + 1, button.getGridY()); + } + } + } + selectedButton.setGrid(gLocation.x, gLocation.y); + } + selectedButton = null; + + //Makes sure everything on the grid and far left and top that it can be + Map> gridMap = new HashMap<>(); + for (SidebarGuiButton button : buttons) { + if(!gridMap.containsKey(button.getGridY())) { + gridMap.put(button.getGridY(), new ArrayList<>()); + } + gridMap.get(button.getGridY()).add(button); + } + int y = 0; + for (Map.Entry> entry : gridMap.entrySet()) { + List sorted = entry.getValue().stream().sorted(Comparator.comparingInt(SidebarGuiButton::getGridX)).toList(); + for (int i = 0; i < sorted.size(); i++) { + sorted.get(i).setGrid(i, y); + } + y++; + } + } + } + } + + private GridLocation getGridLocation(int x, int y) { + int gridX = (currentMouseX - 1) / BUTTON_SPACING; + int gridY = (currentMouseY - 1) / BUTTON_SPACING; + return new GridLocation(gridX, gridY); + } + + @Override + public void onPress() { + if(mouseOver != null) { + isMouseDown = true; + mouseOffsetX = currentMouseX - mouseOver.x; + mouseOffsetY = currentMouseY - mouseOver.y; + + if(isEditMode) { + selectedButton = mouseOver; + selectedLocation = new GridLocation(selectedButton.getGridX(), selectedButton.getGridY()); + } } } @@ -159,4 +292,24 @@ public void onPress() { public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) { defaultButtonNarrationText(narrationElementOutput); } + + public record GridLocation(int x, int y) {} + + + public void tick() { + if(isMouseDown) { + mouseDownTime++; + if(mouseDownTime > 20) { + isEditMode = true; + mouseOver = null; + } + } else { + //Todo +// if(mouseDownTime <= 0) { +// isEditMode = false; +// }else { +// mouseDownTime--; +// } + } + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java index 67234e37..f2a8553b 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java @@ -2,13 +2,38 @@ public class SidebarGuiButton { - public final int buttonX, buttonY; + public final SidebarButton button; public int x, y; + private int gridX; + private int gridY; - public SidebarGuiButton(int x, int y, SidebarButton b) { - buttonX = x; - buttonY = y; + public SidebarGuiButton(int gridX, int gridY, SidebarButton b) { button = b; + x = 0; + y = 0; + this.gridX = gridX; + this.gridY = gridY; + } + + public int getGridX() { + return gridX; + } + + public int getGridY() { + return gridY; + } + + public void setGridX(int gridX) { + this.gridX = gridX; + } + + public void setGridY(int gridY) { + this.gridY = gridY; + } + + public void setGrid(int gridX, int gridY) { + this.gridX = gridX; + this.gridY = gridY; } } diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons.json index aa1d8da1..25622204 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons.json @@ -16,7 +16,7 @@ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_rain.png" ], - "x": 110, + "x": 80, "click": "command:/ftblibrary rain", "config": true, "hide_with_nei": true, diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/day.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/day.json new file mode 100644 index 00000000..b0f42f5f --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/day.json @@ -0,0 +1,14 @@ +{ + "group": "ftblibrary:cheat", + "icon": [ + "ftblibrary:icons/blue_button", + "ftblibrary:textures/icons/toggle_day.png" + ], + "x": 120, + "click": "command:/ftblibrary day", + "required_server_mods": [ + "ftblibrary" + ], + "hide_with_nei": true, + "requires_op": true +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/gamemode.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/gamemode.json new file mode 100644 index 00000000..e38856ec --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/gamemode.json @@ -0,0 +1,10 @@ +{ + "group": "ftblibrary:cheat", + "icon": [ + "ftblibrary:icons/blue_button", + "ftblibrary:textures/icons/toggle_gamemode.png" + ], + "x": 100, + "click": "command:/ftblibrary gamemode", + "requires_op": true +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/night.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/night.json new file mode 100644 index 00000000..019f4355 --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/night.json @@ -0,0 +1,13 @@ +{ + "group": "ftblibrary:cheat", + "icon": [ + "ftblibrary:icons/blue_button", + "ftblibrary:textures/icons/toggle_night.png" + ], + "x": 130, + "click": "command:/ftblibrary night", + "required_server_mods": [ + "ftblibrary" + ], + "requires_op": true +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/rain.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/rain.json new file mode 100644 index 00000000..599ddca7 --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/rain.json @@ -0,0 +1,10 @@ +{ + "group": "ftblibrary:cheat", + "icon": [ + "ftblibrary:icons/blue_button", + "ftblibrary:textures/icons/toggle_rain.png" + ], + "x": 80, + "click": "command:/ftblibrary rain", + "requires_op": true +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/cheat.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/cheat.json new file mode 100644 index 00000000..aeb1983d --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/cheat.json @@ -0,0 +1,3 @@ +{ + "y": 100 +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/info.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/info.json new file mode 100644 index 00000000..aa39d60f --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/info.json @@ -0,0 +1,3 @@ +{ + "y": 0 +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/util.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/util.json new file mode 100644 index 00000000..9de532d4 --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/util.json @@ -0,0 +1,3 @@ +{ + "y": 200 +} \ No newline at end of file diff --git a/neoforge/src/main/java/dev/ftb/mods/ftblibrary/integration/neoforge/REINeoforgePluginStub.java b/neoforge/src/main/java/dev/ftb/mods/ftblibrary/integration/neoforge/REINeoforgePluginStub.java index 0f76af2e..28340434 100644 --- a/neoforge/src/main/java/dev/ftb/mods/ftblibrary/integration/neoforge/REINeoforgePluginStub.java +++ b/neoforge/src/main/java/dev/ftb/mods/ftblibrary/integration/neoforge/REINeoforgePluginStub.java @@ -1,8 +1,8 @@ -package dev.ftb.mods.ftblibrary.integration.neoforge; - -import dev.ftb.mods.ftblibrary.integration.REIIntegration; -import me.shedaniel.rei.forge.REIPluginCommon; - -@REIPluginCommon -public class REINeoforgePluginStub extends REIIntegration { -} +//package dev.ftb.mods.ftblibrary.integration.neoforge; +// +//import dev.ftb.mods.ftblibrary.integration.REIIntegration; +//import me.shedaniel.rei.forge.REIPluginCommon; +// +//@REIPluginCommon +//public class REINeoforgePluginStub extends REIIntegration { +//} From 92fb861b58e8623764c880470ac58b716979bdcc Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Wed, 31 Jul 2024 13:36:30 -0500 Subject: [PATCH 02/17] Save changes made in gui, add option to remove buttons --- .../config/FTBLibraryClientConfig.java | 9 +- .../sidebar/SidebarButtonManager.java | 168 +++++++++++++----- .../sidebar/SidebarGroupGuiButton.java | 124 +++++++------ .../ftblibrary/sidebar/SidebarGuiButton.java | 20 ++- .../snbt/config/StringSidebarMapValue.java | 51 ++++++ 5 files changed, 274 insertions(+), 98 deletions(-) create mode 100644 common/src/main/java/dev/ftb/mods/ftblibrary/snbt/config/StringSidebarMapValue.java diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java b/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java index 56eec8d4..0ecfead1 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java @@ -1,8 +1,8 @@ package dev.ftb.mods.ftblibrary.config; -import dev.ftb.mods.ftblibrary.snbt.config.BooleanValue; -import dev.ftb.mods.ftblibrary.snbt.config.IntArrayValue; -import dev.ftb.mods.ftblibrary.snbt.config.SNBTConfig; +import dev.ftb.mods.ftblibrary.snbt.config.*; + +import java.util.HashMap; import static dev.ftb.mods.ftblibrary.FTBLibrary.MOD_ID; import static dev.ftb.mods.ftblibrary.snbt.config.ConfigUtil.LOCAL_DIR; @@ -26,6 +26,9 @@ public interface FTBLibraryClientConfig { IntArrayValue RECENT = COLOR.addIntArray("recents", new int[0]) .comment("Colors recently selected in the color selector"); + SNBTConfig SIDEBAR = CONFIG.addGroup("sidebar"); + StringSidebarMapValue SIDEBAR_BUTTONS = SIDEBAR.add(new StringSidebarMapValue(SIDEBAR, "buttons", new HashMap<>())); + static void load() { loadDefaulted(CONFIG, LOCAL_DIR, MOD_ID); } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index 7ae367ca..d074e0c0 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -1,33 +1,28 @@ package dev.ftb.mods.ftblibrary.sidebar; import com.google.gson.*; -import com.google.gson.stream.JsonWriter; import com.mojang.logging.LogUtils; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; -import dev.architectury.platform.Platform; import dev.ftb.mods.ftblibrary.FTBLibrary; +import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; +import dev.ftb.mods.ftblibrary.snbt.config.StringSidebarMapValue; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.BiConsumer; +import java.util.function.Consumer; import java.util.stream.Collectors; -import java.util.stream.Stream; public enum SidebarButtonManager implements ResourceManagerReloadListener { @@ -35,8 +30,8 @@ public enum SidebarButtonManager implements ResourceManagerReloadListener { private static final Logger LOGGER = LogUtils.getLogger(); - private final Map groups = new HashMap<>(); - private final Map buttons = new HashMap<>(); + private final List> groups = new ArrayList<>(); + private final List> buttons = new ArrayList<>(); private JsonElement readJson(Resource resource) { try (BufferedReader reader = resource.openAsReader()) { @@ -47,40 +42,79 @@ private JsonElement readJson(Resource resource) { return JsonNull.INSTANCE; } - public Map getButtons() { + public List> getButtons() { return buttons; } - public Map> getButtonGroups() { - Map> map = new HashMap<>(); - for (SidebarButton value : buttons.values()) { - SidebarButtonGroup group = groups.get(value.group()); - if(group != null) { - if(!map.containsKey(group)) { - map.put(group, new ArrayList<>()); - } - map.get(group).add(value); +// public Map> getButtonGroups() { +// Map> map = new HashMap<>(); +// for (SidebarButton value : buttons.values()) { +// SidebarButtonGroup group = groups.get(value.group()); +// if(group != null) { +// if(!map.containsKey(group)) { +// map.put(group, new ArrayList<>()); +// } +// map.get(group).add(value); +// +// }else { +// //Todo This should never happen in theory +// } +// } +// return map.entrySet().stream().sorted(Comparator.comparingInt(o -> o.getKey().y())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); +// } - }else { - //Todo This should never happen in theory - } - } - return map.entrySet().stream().sorted(Comparator.comparingInt(o -> o.getKey().y())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); - } + public SidebarButtonGroup getGroup(ResourceLocation id) { + return groups.stream() + .filter(group -> group.id().equals(id)) + .findFirst() + .map(StoredInfo::value) + .orElse(null); + } @Override public void onResourceManagerReload(ResourceManager manager) { groups.clear(); buttons.clear(); - loadResources(manager, "sidebar_buttons/groups", SidebarButtonGroup.CODEC, groups::put); - loadResources(manager, "sidebar_buttons/buttons", SidebarButton.CODEC, (fixed, result) -> { - if (groups.containsKey(result.group())) { - buttons.put(fixed, result); - } else { - LOGGER.error("Can't load Sidebar Button {} because group {} not found", fixed, result.group()); + loadResources(manager, "sidebar_buttons/groups", SidebarButtonGroup.CODEC, groups::add); + loadResources(manager, "sidebar_buttons/buttons", SidebarButton.CODEC, (result) -> { + SidebarButtonGroup group = getGroup(result.value().group()); + if(group != null) { + buttons.add(result); + }else { + LOGGER.error("Button {} not found in config", result.id()); } }); + + Map>> buttonMap = new HashMap<>(); + for (StoredInfo storedInfo : this.buttons) { + buttonMap.computeIfAbsent(getGroup(storedInfo.value().group()).y(), k -> new ArrayList<>()).add(storedInfo); + } + + //sort buttonMap by key + buttonMap = buttonMap.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getKey)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); + + int y = 0; + for (List> storedInfoList : buttonMap.values()) { + int x = 0; + storedInfoList.sort(Comparator.comparingInt(o -> o.value().x())); + for (StoredInfo sidebarButtonStoredInfo : storedInfoList) { + SidebarButton button = sidebarButtonStoredInfo.value(); + SidebarButtonGroup group = getGroup(button.group()); + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(sidebarButtonStoredInfo.id().toString()); + if (buttonSettings == null) { + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(sidebarButtonStoredInfo.id().toString(), new StringSidebarMapValue.SideButtonInfo(true, x, y)); + } + x++; + } + if(x != 0) { + y++; + } + } + + FTBLibraryClientConfig.save(); + + refreshButtonList(); } @@ -188,7 +222,7 @@ public void onResourceManagerReload(ResourceManager manager) { // // saveConfig(); - private void loadResources(ResourceManager manager, String path, Codec codec, BiConsumer consumer) { + private void loadResources(ResourceManager manager, String path, Codec codec, Consumer> consumer) { Map resourceLocationResourceMap = manager.listResources(path, name -> name.getPath().endsWith(".json")); for (Map.Entry resource : resourceLocationResourceMap.entrySet()) { JsonElement jsonElement = readJson(resource.getValue()); @@ -199,13 +233,70 @@ private void loadResources(ResourceManager manager, String path, Codec co T result = parse.result().get(); ResourceLocation key = resource.getKey(); ResourceLocation fixed = ResourceLocation.fromNamespaceAndPath(key.getNamespace(), key.getPath().replace(path + "/", "").replace(".json", "")); - consumer.accept(fixed, result); + consumer.accept(new StoredInfo<>(fixed, result)); + } + } + } + + + private final List buttonList = new ArrayList<>(); + + public void refreshButtonList() { + buttonList.clear(); + for (StoredInfo buttonEntry : getButtons()) { + ResourceLocation id = buttonEntry.id(); + SidebarButton button = buttonEntry.value(); + + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(id.toString()); + if(buttonSettings != null) { + if(buttonSettings.enabled()) { + SidebarGuiButton e = new SidebarGuiButton(buttonSettings.xPos(), buttonSettings.yPos(), true, id, button); + buttonList.add(e); + } + + }else { + //Todo this should not be possable + LOGGER.error("Button {} not found in config", id); } } + + for (Map.Entry stringSideButtonInfoEntry : FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().entrySet()) { + StringSidebarMapValue.SideButtonInfo buttonSettings = stringSideButtonInfoEntry.getValue(); + if(buttonSettings != null && buttonSettings.enabled()) { + for (SidebarGuiButton button : buttonList) { + if(button.isEnabled()) { + if(!button.getButtonId().toString().equals(stringSideButtonInfoEntry.getKey())) { + if(button.getGridY() == buttonSettings.yPos() && button.getGridX() == buttonSettings.xPos()) { + button.setGrid(button.getGridX() + 1, button.getGridY()); + } + } + + } + } + } + } + + FTBLibraryClientConfig.save(); } - public void saveConfig() { } -// var o = new JsonObject(); + public void saveConfigFromButtonList() { + for (SidebarGuiButton button : buttonList) { + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getButtonId().toString()); + if(buttonSettings != null) { + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getButtonId().toString(), new StringSidebarMapValue.SideButtonInfo(button.isEnabled(), button.getGridX(), button.getGridY())); + } + } + FTBLibraryClientConfig.save(); + refreshButtonList(); + + } + + public List getButtonList() { + return buttonList; + } + + + // var o = new JsonObject(); // // for (var group : groups) { // for (var button : group.getButtons()) { @@ -231,9 +322,6 @@ public void saveConfig() { } // ex.printStackTrace(); // } + public record StoredInfo(ResourceLocation id, T value) {} - @Nullable - public SidebarButtonGroup getGroup(ResourceLocation group) { - return groups.get(group); - } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index e6cde412..f9bb2c59 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -5,6 +5,8 @@ import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.math.Axis; import dev.ftb.mods.ftblibrary.icon.Color4I; +import dev.ftb.mods.ftblibrary.icon.Icon; +import dev.ftb.mods.ftblibrary.icon.Icons; import dev.ftb.mods.ftblibrary.ui.Button; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import net.minecraft.client.Minecraft; @@ -32,8 +34,6 @@ public class SidebarGroupGuiButton extends AbstractButton { public static Rect2i lastDrawnArea = new Rect2i(0, 0, 0, 0); private static final int BUTTON_SPACING = 17; - private final List buttons = new ArrayList<>(); - private SidebarGuiButton mouseOver; private SidebarGuiButton selectedButton; private GridLocation selectedLocation; @@ -46,31 +46,15 @@ public class SidebarGroupGuiButton extends AbstractButton { private int mouseOffsetX; private int mouseOffsetY; + private int maxGridWith = 1; + private int maxGridHeight = 1; + + private boolean addBoxOpen; public SidebarGroupGuiButton() { super(0, 0, 0, 0, Component.empty()); - int rx, ry = 0; - boolean addedAny; - - for (Map.Entry> buttonEntry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { - rx = 0; - addedAny = false; - - SidebarButtonGroup group = buttonEntry.getKey(); - for (SidebarButton sidebarButton : buttonEntry.getValue()) { - if(sidebarButton.isVisible()) { - SidebarGuiButton e = new SidebarGuiButton(rx, ry, sidebarButton); - buttons.add(e); - rx++; - addedAny = true; - } - } - - if (addedAny) { - ry++; - } - } + ensureGridAlignment(); isMouseDown = false; } @@ -86,7 +70,7 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick var maxX = Integer.MIN_VALUE; var maxY = Integer.MIN_VALUE; - for (var b : buttons) { + for (var b : SidebarButtonManager.INSTANCE.getButtonList()) { if (b.x >= 0 && b.y >= 0) { setX(Math.min(getX(), b.x)); setY(Math.min(getY(), b.y)); @@ -115,48 +99,55 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick if (isEditMode) { //draw box with one extra spot of 16x16 on each side with current - int maxWidth = buttons + maxGridWith = SidebarButtonManager.INSTANCE.getButtonList() .stream().max(Comparator.comparingInt(SidebarGuiButton::getGridX)) .map(SidebarGuiButton::getGridX) .orElse(1) + 2; - int maxHeight = buttons + maxGridHeight = SidebarButtonManager.INSTANCE.getButtonList() .stream() .max(Comparator.comparingInt(SidebarGuiButton::getGridY)) .map(SidebarGuiButton::getGridY) .orElse(1) + 2; //Don't show extra row on bottom if everything is vertically aligned - if(maxHeight == buttons.size() + 1) { - maxHeight--; + if(maxGridHeight == SidebarButtonManager.INSTANCE.getButtonList().size() + 1) { + maxGridHeight--; } //Don't show extra column on right if everything is horizontally aligned - if(maxWidth == buttons.size() + 1) { - maxWidth--; + if(maxGridWith == SidebarButtonManager.INSTANCE.getButtonList().size() + 1) { + maxGridWith--; } - Color4I.GRAY.draw(graphics, 0, 0, maxWidth * BUTTON_SPACING, maxHeight * BUTTON_SPACING); + Color4I.GRAY.draw(graphics, 0, 0, maxGridWith * BUTTON_SPACING, maxGridHeight * BUTTON_SPACING); //draw black grid lines - for (var i = 0; i < maxWidth + 1; i++) { - Color4I.BLACK.draw(graphics, i * BUTTON_SPACING, 0, 1, maxHeight * BUTTON_SPACING); + for (var i = 0; i < maxGridWith + 1; i++) { + Color4I.BLACK.draw(graphics, i * BUTTON_SPACING, 0, 1, maxGridHeight * BUTTON_SPACING); } - for (var i = 0; i < maxHeight + 1; i++) { - Color4I.BLACK.draw(graphics, 0, i * BUTTON_SPACING, maxWidth * BUTTON_SPACING, 1); + for (var i = 0; i < maxGridHeight + 1; i++) { + Color4I.BLACK.draw(graphics, 0, i * BUTTON_SPACING, maxGridWith * BUTTON_SPACING, 1); } if(selectedButton != null) { GridLocation gridLocation = getGridLocation(mx, my); - gridLocation = new GridLocation(Math.min(maxWidth - 1, Math.max(0, gridLocation.x)), Math.min(maxHeight - 1, Math.max(0, gridLocation.y))); + gridLocation = new GridLocation(Math.min(maxGridWith - 1, Math.max(0, gridLocation.x)), Math.min(maxGridHeight - 1, Math.max(0, gridLocation.y))); Color4I.WHITE.draw(graphics, gridLocation.x * BUTTON_SPACING + 1, gridLocation.y * BUTTON_SPACING + 1, 16, 16); } + Icons.ADD.draw(graphics, (maxGridWith - 1) * BUTTON_SPACING + 1, (maxGridHeight - 1) * BUTTON_SPACING + 1, 16, 16); + + if(addBoxOpen) { + + } } + + graphics.pose().pushPose(); graphics.pose().translate(0, 0, 500); var font = Minecraft.getInstance().font; //Todo better way? - List sortedButtons = new ArrayList<>(buttons); + List sortedButtons = new ArrayList<>(SidebarButtonManager.INSTANCE.getButtonList()); if(selectedButton != null) { sortedButtons.remove(selectedButton); sortedButtons.addLast(selectedButton); @@ -172,6 +163,9 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick } GuiHelper.setupDrawing(); button.button.icon().draw(graphics, button.x, button.y, 16, 16); + if(isEditMode) { + Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); + } if (button == mouseOver) { Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); @@ -237,7 +231,7 @@ public void onRelease(double d, double e) { //Checks if the icon is placed in the same location picked up from, if so do nothing if (!gLocation.equals(selectedLocation)) { //Checks for any icon at the place location and to left of that and moves them over one - for (SidebarGuiButton button : buttons) { + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { if(!selectedButton.equals(button)) { if (button.getGridY() == gLocation.y && button.getGridX() >= gLocation.x) { button.setGrid(button.getGridX() + 1, button.getGridY()); @@ -247,27 +241,33 @@ public void onRelease(double d, double e) { selectedButton.setGrid(gLocation.x, gLocation.y); } selectedButton = null; + ensureGridAlignment(); - //Makes sure everything on the grid and far left and top that it can be - Map> gridMap = new HashMap<>(); - for (SidebarGuiButton button : buttons) { - if(!gridMap.containsKey(button.getGridY())) { - gridMap.put(button.getGridY(), new ArrayList<>()); - } - gridMap.get(button.getGridY()).add(button); - } - int y = 0; - for (Map.Entry> entry : gridMap.entrySet()) { - List sorted = entry.getValue().stream().sorted(Comparator.comparingInt(SidebarGuiButton::getGridX)).toList(); - for (int i = 0; i < sorted.size(); i++) { - sorted.get(i).setGrid(i, y); - } - y++; - } } } } + private void ensureGridAlignment() { + //Makes sure everything on the grid and far left and top that it can be + Map> gridMap = new HashMap<>(); + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { + if(!gridMap.containsKey(button.getGridY())) { + gridMap.put(button.getGridY(), new ArrayList<>()); + } + gridMap.get(button.getGridY()).add(button); + } + int y = 0; + for (Map.Entry> entry : gridMap.entrySet()) { + List sorted = entry.getValue().stream().sorted(Comparator.comparingInt(SidebarGuiButton::getGridX)).toList(); + for (int i = 0; i < sorted.size(); i++) { + sorted.get(i).setGrid(i, y); + } + y++; + } + + SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); + } + private GridLocation getGridLocation(int x, int y) { int gridX = (currentMouseX - 1) / BUTTON_SPACING; int gridY = (currentMouseY - 1) / BUTTON_SPACING; @@ -282,6 +282,22 @@ public void onPress() { mouseOffsetY = currentMouseY - mouseOver.y; if(isEditMode) { + //Check if clicked the remove button + if(currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4) { + mouseOver.setEnabled(false); + mouseOver = null; + SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); + ensureGridAlignment(); + return; + } + + + //if clicked the bottom right grid spot + if(currentMouseX >= (maxGridWith - 1) * BUTTON_SPACING + 1 && currentMouseY >= (maxGridHeight - 1) * BUTTON_SPACING + 1) { + addBoxOpen = !addBoxOpen; + return; + } + selectedButton = mouseOver; selectedLocation = new GridLocation(selectedButton.getGridX(), selectedButton.getGridY()); } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java index f2a8553b..ab79bbdf 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java @@ -1,19 +1,37 @@ package dev.ftb.mods.ftblibrary.sidebar; +import net.minecraft.resources.ResourceLocation; + public class SidebarGuiButton { + private final ResourceLocation buttonId; public final SidebarButton button; public int x, y; private int gridX; private int gridY; + private boolean enabled; - public SidebarGuiButton(int gridX, int gridY, SidebarButton b) { + public SidebarGuiButton(int gridX, int gridY, boolean enabled, ResourceLocation buttonId, SidebarButton b) { button = b; x = 0; y = 0; this.gridX = gridX; this.gridY = gridY; + this.buttonId = buttonId; + this.enabled = enabled; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public ResourceLocation getButtonId() { + return buttonId; } public int getGridX() { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/snbt/config/StringSidebarMapValue.java b/common/src/main/java/dev/ftb/mods/ftblibrary/snbt/config/StringSidebarMapValue.java new file mode 100644 index 00000000..e7147608 --- /dev/null +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/snbt/config/StringSidebarMapValue.java @@ -0,0 +1,51 @@ +package dev.ftb.mods.ftblibrary.snbt.config; + +import dev.ftb.mods.ftblibrary.snbt.SNBTCompoundTag; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; + +public class StringSidebarMapValue extends BaseValue> { + public StringSidebarMapValue(@Nullable SNBTConfig c, String n, Map def) { + super(c, n, def); + super.set(new HashMap<>(def)); + } + + @Override + public void write(SNBTCompoundTag tag) { + Map map = get(); + SNBTCompoundTag mapTag = new SNBTCompoundTag(); + + for (Map.Entry entry : map.entrySet()) { + SNBTCompoundTag buttonTag = new SNBTCompoundTag(); + buttonTag.putBoolean("enabled", entry.getValue().enabled()); + buttonTag.putInt("x", entry.getValue().xPos()); + buttonTag.putInt("y", entry.getValue().yPos()); + mapTag.put(entry.getKey(), buttonTag); + } + + tag.put(key, mapTag); + } + + @Override + public void read(SNBTCompoundTag tag) { + Map map = new HashMap<>(); + + SNBTCompoundTag compound = tag.getCompound(key); + for (String key : compound.getAllKeys()) { + SNBTCompoundTag buttonTag = compound.getCompound(key); + map.put(key, new SideButtonInfo( + buttonTag.getBoolean("enabled"), + buttonTag.getInt("x"), + buttonTag.getInt("y") + )); + } + + set(map); + } + + + public record SideButtonInfo(boolean enabled, int xPos, int yPos) {} +} From e7c4eb615942b68d9694aba8faaadb6b405469ac Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Wed, 31 Jul 2024 15:12:01 -0500 Subject: [PATCH 03/17] More work on gui dragging and a little code clenaup --- .../integration/REIIntegration.java | 18 +- .../sidebar/SidebarButtonManager.java | 17 +- .../sidebar/SidebarGroupGuiButton.java | 216 +++++++++++------- .../ftblibrary/sidebar/SidebarGuiButton.java | 4 +- 4 files changed, 157 insertions(+), 98 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java index c8ccbb8c..c0728c64 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java @@ -3,6 +3,7 @@ //import com.google.gson.Gson; //import com.google.gson.JsonObject; //import com.google.gson.JsonParser; +//import com.mojang.datafixers.util.Pair; //import com.mojang.serialization.DataResult; //import com.mojang.serialization.Lifecycle; //import dev.ftb.mods.ftblibrary.FTBLibrary; @@ -33,6 +34,8 @@ //import net.minecraft.client.gui.screens.Screen; //import net.minecraft.client.resources.language.I18n; //import net.minecraft.nbt.CompoundTag; +//import net.minecraft.nbt.NbtOps; +//import net.minecraft.nbt.Tag; //import net.minecraft.network.chat.Component; //import net.minecraft.network.chat.MutableComponent; //import net.minecraft.resources.ResourceLocation; @@ -43,6 +46,7 @@ //import java.util.ArrayList; //import java.util.Collection; //import java.util.List; +//import java.util.Map; // //public class REIIntegration implements REIClientPlugin { // public static final ResourceLocation ID = FTBLibrary.rl("sidebar_button"); @@ -75,8 +79,9 @@ // @Override // public void registerFavorites(FavoriteEntryType.Registry registry) { // registry.register(ID, SidebarButtonType.INSTANCE); -// for (var group : SidebarButtonManager.INSTANCE.getGroups()) { -// List buttons = CollectionUtils.map(group.getButtons(), SidebarButtonEntry::new); +// for (Map.Entry> entry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { +// List buttons = CollectionUtils.map(entry.getValue(), SidebarButtonEntry::new); +// SidebarButtonGroup group = entry.getKey(); // if (!buttons.isEmpty()) { // registry.getOrCrateSection(Component.translatable(group.getLangKey())) // .add(group.isPinned(), buttons.toArray(new SidebarButtonEntry[0])); @@ -95,16 +100,15 @@ // // @Override // public CompoundTag save(SidebarButtonEntry entry, CompoundTag tag) { -// tag.putString("id", entry.button.getId().toString()); -// tag.putString("json", new Gson().toJson(entry.button.getJson())); +// DataResult encode = SidebarButton.CODEC.encode(entry.button, NbtOps.INSTANCE, null); +// encode.result().ifPresent(t -> tag.put("json", t)); // return tag; // } // // @Override // public DataResult read(CompoundTag object) { -// var id = ResourceLocation.parse(object.getString("id")); -// var json = (JsonObject) JsonParser.parseString(object.getString("json")); -// return DataResult.success(new SidebarButtonEntry(createSidebarButton(id, null, json)), Lifecycle.stable()); +// DataResult> json = SidebarButton.CODEC.decode(NbtOps.INSTANCE, object.get("json")); +// return json.map(pair -> new SidebarButtonEntry(pair.getFirst())); // } // // @Override diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index d074e0c0..e6da90e3 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -249,11 +249,8 @@ public void refreshButtonList() { StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(id.toString()); if(buttonSettings != null) { - if(buttonSettings.enabled()) { - SidebarGuiButton e = new SidebarGuiButton(buttonSettings.xPos(), buttonSettings.yPos(), true, id, button); - buttonList.add(e); - } - + SidebarGuiButton e = new SidebarGuiButton(buttonSettings.xPos(), buttonSettings.yPos(), buttonSettings.enabled(), id, button); + buttonList.add(e); }else { //Todo this should not be possable LOGGER.error("Button {} not found in config", id); @@ -290,11 +287,19 @@ public void saveConfigFromButtonList() { refreshButtonList(); } - +// public List getButtonList() { return buttonList; } + public List getEnabledButtonList() { + return buttonList.stream().filter(SidebarGuiButton::isEnabled).collect(Collectors.toList()); + } + + public List getDisabledButtonList() { + return buttonList.stream().filter(button -> !button.isEnabled()).collect(Collectors.toList()); + } + // var o = new JsonObject(); // diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index f9bb2c59..a2e8db56 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -65,78 +65,55 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick mouseOver = null; - setX(Integer.MAX_VALUE); - setY(Integer.MAX_VALUE); - var maxX = Integer.MIN_VALUE; - var maxY = Integer.MIN_VALUE; - - for (var b : SidebarButtonManager.INSTANCE.getButtonList()) { - if (b.x >= 0 && b.y >= 0) { - setX(Math.min(getX(), b.x)); - setY(Math.min(getY(), b.y)); - maxX = Math.max(maxX, b.x + 16); - maxY = Math.max(maxY, b.y + 16); - } + GridLocation gridLocation = getGridLocation(mx, my); + - if (mx >= b.x && my >= b.y && mx < b.x + 16 && my < b.y + 16) { - mouseOver = b; + List enabledButtonList = SidebarButtonManager.INSTANCE.getEnabledButtonList(); + for (SidebarGuiButton button : enabledButtonList) { + if(button.getGridX() == gridLocation.x && button.getGridY() == gridLocation.y) { + mouseOver = button; } } - // Important: JEI doesn't like negative X/Y values and will silently clamp them, - // leading it to think the values have changed every frame, and do unnecessary updating - // of its GUI areas, including resetting the filter textfield's selection - // https://github.com/FTBTeam/FTB-Mods-Issues/issues/262 - // https://github.com/mezz/JustEnoughItems/issues/2938 - setX(Math.max(0, getX() - 2)); - setY(Math.max(0, getY() - 2)); - maxX += 2; - maxY += 2; + maxGridWith = enabledButtonList + .stream().max(Comparator.comparingInt(SidebarGuiButton::getGridX)) + .map(SidebarGuiButton::getGridX) + .orElse(1) + 2; + maxGridHeight = enabledButtonList + .stream() + .max(Comparator.comparingInt(SidebarGuiButton::getGridY)) + .map(SidebarGuiButton::getGridY) + .orElse(1) + 2; - width = maxX - getX(); - height = maxY - getY(); - //zLevel = 0F; if (isEditMode) { - //draw box with one extra spot of 16x16 on each side with current - maxGridWith = SidebarButtonManager.INSTANCE.getButtonList() - .stream().max(Comparator.comparingInt(SidebarGuiButton::getGridX)) - .map(SidebarGuiButton::getGridX) - .orElse(1) + 2; - maxGridHeight = SidebarButtonManager.INSTANCE.getButtonList() - .stream() - .max(Comparator.comparingInt(SidebarGuiButton::getGridY)) - .map(SidebarGuiButton::getGridY) - .orElse(1) + 2; - - //Don't show extra row on bottom if everything is vertically aligned - if(maxGridHeight == SidebarButtonManager.INSTANCE.getButtonList().size() + 1) { - maxGridHeight--; - } - //Don't show extra column on right if everything is horizontally aligned - if(maxGridWith == SidebarButtonManager.INSTANCE.getButtonList().size() + 1) { - maxGridWith--; - } - Color4I.GRAY.draw(graphics, 0, 0, maxGridWith * BUTTON_SPACING, maxGridHeight * BUTTON_SPACING); - //draw black grid lines - for (var i = 0; i < maxGridWith + 1; i++) { - Color4I.BLACK.draw(graphics, i * BUTTON_SPACING, 0, 1, maxGridHeight * BUTTON_SPACING); - } - for (var i = 0; i < maxGridHeight + 1; i++) { - Color4I.BLACK.draw(graphics, 0, i * BUTTON_SPACING, maxGridWith * BUTTON_SPACING, 1); - } + drawHoveredGrid(graphics, 0, 0, maxGridWith, maxGridHeight, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my); - if(selectedButton != null) { - GridLocation gridLocation = getGridLocation(mx, my); - gridLocation = new GridLocation(Math.min(maxGridWith - 1, Math.max(0, gridLocation.x)), Math.min(maxGridHeight - 1, Math.max(0, gridLocation.y))); - Color4I.WHITE.draw(graphics, gridLocation.x * BUTTON_SPACING + 1, gridLocation.y * BUTTON_SPACING + 1, 16, 16); - } - Icons.ADD.draw(graphics, (maxGridWith - 1) * BUTTON_SPACING + 1, (maxGridHeight - 1) * BUTTON_SPACING + 1, 16, 16); + List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(); + if(!disabledButtonList.isEmpty()) { + Icons.ADD.draw(graphics, (maxGridWith - 1) * BUTTON_SPACING + 1, (maxGridHeight - 1) * BUTTON_SPACING + 1, 16, 16); + + if(addBoxOpen) { + drawHoveredGrid(graphics, ( maxGridWith - 0) * BUTTON_SPACING, (maxGridHeight - 1) * BUTTON_SPACING, disabledButtonList.size(), 1, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my); + for (int i = 0; i < disabledButtonList.size(); i++) { + SidebarGuiButton button = disabledButtonList.get(i); + if(selectedButton != null && selectedButton == button) { + continue; + } + button.x = (maxGridWith - 0) * BUTTON_SPACING + i * BUTTON_SPACING; + button.y = (maxGridHeight - 1) * BUTTON_SPACING; + GuiHelper.setupDrawing(); + button.button.icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); - if(addBoxOpen) { - + if(mx >= button.x && mx < button.x + 16 && my >= button.y && my < button.y + 16) { + mouseOver = button; + } + } + + } } + } @@ -147,7 +124,7 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick var font = Minecraft.getInstance().font; //Todo better way? - List sortedButtons = new ArrayList<>(SidebarButtonManager.INSTANCE.getButtonList()); + List sortedButtons = new ArrayList<>(enabledButtonList); if(selectedButton != null) { sortedButtons.remove(selectedButton); sortedButtons.addLast(selectedButton); @@ -163,7 +140,7 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick } GuiHelper.setupDrawing(); button.button.icon().draw(graphics, button.x, button.y, 16, 16); - if(isEditMode) { + if(isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList().size() > 1) { Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); } @@ -229,17 +206,23 @@ public void onRelease(double d, double e) { if (selectedButton != null) { GridLocation gLocation = getGridLocation(currentMouseX, currentMouseY); //Checks if the icon is placed in the same location picked up from, if so do nothing - if (!gLocation.equals(selectedLocation)) { - //Checks for any icon at the place location and to left of that and moves them over one - for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { - if(!selectedButton.equals(button)) { - if (button.getGridY() == gLocation.y && button.getGridX() >= gLocation.x) { - button.setGrid(button.getGridX() + 1, button.getGridY()); - } - } - } - selectedButton.setGrid(gLocation.x, gLocation.y); - } + if (!gLocation.isOutOfBounds()) + if (!gLocation.equals(selectedLocation)) { + //Checks for any icon at the place location and to left of that and moves them over one + List buttonList = SidebarButtonManager.INSTANCE.getButtonList(); + for (SidebarGuiButton button : buttonList) { + if (!selectedButton.equals(button)) { + if (button.getGridY() == gLocation.y && button.getGridX() >= gLocation.x) { + button.setGrid(button.getGridX() + 1, button.getGridY()); + } + } + } + selectedButton.setGrid(gLocation.x, gLocation.y); + if (!selectedButton.isEnabled()) { + selectedButton.setEnabled(true); + SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); + } + } selectedButton = null; ensureGridAlignment(); @@ -250,7 +233,7 @@ public void onRelease(double d, double e) { private void ensureGridAlignment() { //Makes sure everything on the grid and far left and top that it can be Map> gridMap = new HashMap<>(); - for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getEnabledButtonList()) { if(!gridMap.containsKey(button.getGridY())) { gridMap.put(button.getGridY(), new ArrayList<>()); } @@ -265,25 +248,68 @@ private void ensureGridAlignment() { y++; } + + + + SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); + + setX(0); + setY(0); + // Important: JEI doesn't like negative X/Y values and will silently clamp them, + // leading it to think the values have changed every frame, and do unnecessary updating + // of its GUI areas, including resetting the filter textfield's selection + // https://github.com/FTBTeam/FTB-Mods-Issues/issues/262 + // https://github.com/mezz/JustEnoughItems/issues/2938 + var maxGirdX = 2; + var maxGirdY = 2; + for (SidebarGuiButton b : SidebarButtonManager.INSTANCE.getEnabledButtonList()) { + maxGirdX = Math.max(maxGirdX, b.getGridX() + 1); + maxGirdY = Math.max(maxGirdY, b.getGridY() + 1); + } + + if(isEditMode && addBoxOpen) { + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getDisabledButtonList()) { + maxGirdX++; + } + } + + width = (maxGirdX + 1) * BUTTON_SPACING; + height = (maxGirdY + 1) * BUTTON_SPACING; } private GridLocation getGridLocation(int x, int y) { int gridX = (currentMouseX - 1) / BUTTON_SPACING; int gridY = (currentMouseY - 1) / BUTTON_SPACING; + if(gridX >= maxGridWith || gridY >= maxGridHeight) { + return new GridLocation(- 1, - 1); + } return new GridLocation(gridX, gridY); } @Override public void onPress() { + if(isEditMode) { + //if clicked the bottom right grid spot + GridLocation gridLocation = getGridLocation(currentMouseX, currentMouseY); + if(gridLocation.x == maxGridWith - 1 && gridLocation.y == maxGridHeight - 1) { + addBoxOpen = !addBoxOpen; + return; + } + } + if(mouseOver != null) { isMouseDown = true; mouseOffsetX = currentMouseX - mouseOver.x; mouseOffsetY = currentMouseY - mouseOver.y; if(isEditMode) { + + + + //Check if clicked the remove button - if(currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4) { + if(SidebarButtonManager.INSTANCE.getEnabledButtonList().size() > 1 && currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4) { mouseOver.setEnabled(false); mouseOver = null; SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); @@ -292,14 +318,14 @@ public void onPress() { } - //if clicked the bottom right grid spot - if(currentMouseX >= (maxGridWith - 1) * BUTTON_SPACING + 1 && currentMouseY >= (maxGridHeight - 1) * BUTTON_SPACING + 1) { - addBoxOpen = !addBoxOpen; - return; - } + selectedButton = mouseOver; - selectedLocation = new GridLocation(selectedButton.getGridX(), selectedButton.getGridY()); + if(!selectedButton.isEnabled()) { + selectedLocation = new GridLocation(selectedButton.getGridX(), selectedButton.getGridY()); + }else { + selectedLocation = GridLocation.OUT_OF_BOUNDS; + } } } } @@ -309,7 +335,14 @@ public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) defaultButtonNarrationText(narrationElementOutput); } - public record GridLocation(int x, int y) {} + public record GridLocation(int x, int y) { + + public static final GridLocation OUT_OF_BOUNDS = new GridLocation(-1, -1); + + public boolean isOutOfBounds() { + return x < 0 || y < 0; + } + } public void tick() { @@ -328,4 +361,21 @@ public void tick() { // } } } + + public static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor) { + backgroundColor.draw(graphics, x, y, width * spacing, height * spacing); + for (var i = 0; i < width + 1; i++) { + gridColor.draw(graphics, x + i * spacing, y, 1, height * spacing); + } + for (var i = 0; i < height + 1; i++) { + gridColor.draw(graphics, x, y + i * spacing, width * spacing, 1); + } + } + + public static void drawHoveredGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor, int mx, int my) { + drawGrid(graphics, x, y, width, height, spacing, backgroundColor, gridColor); + if (mx >= x && my >= y && mx < x + width * spacing && my < y + height * spacing) { + Color4I.WHITE.draw(graphics, (mx / spacing) * spacing + 1, (my / spacing) * spacing + 1, spacing - 1, spacing - 1); + } + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java index ab79bbdf..5bc02043 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java @@ -35,11 +35,11 @@ public ResourceLocation getButtonId() { } public int getGridX() { - return gridX; + return enabled ? gridX : -1; } public int getGridY() { - return gridY; + return enabled ? gridY : -1; } public void setGridX(int gridX) { From fa20cecfb404b32fe0b813c78b313967f5589b3d Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Thu, 1 Aug 2024 16:29:47 -0500 Subject: [PATCH 04/17] Fix Rei Integration, Cleanup Code, Better Add Button handling --- .../mods/ftblibrary/FTBLibraryCommands.java | 2 +- .../integration/REIIntegration.java | 415 +++++++++--------- .../mods/ftblibrary/sidebar/GridLocation.java | 10 + .../ftblibrary/sidebar/SidebarButton.java | 231 +++------- .../sidebar/SidebarButtonCreatedEvent.java | 9 +- .../ftblibrary/sidebar/SidebarButtonData.java | 44 ++ .../sidebar/SidebarButtonGroup.java | 1 + .../sidebar/SidebarButtonManager.java | 177 ++++---- .../sidebar/SidebarGroupGuiButton.java | 170 ++++--- .../ftblibrary/sidebar/SidebarGuiButton.java | 37 +- .../sidebar_buttons/buttons/test.json | 14 + .../buttons/{ => toggle}/day.json | 5 +- .../buttons/{ => toggle}/gamemode.json | 2 +- .../buttons/{ => toggle}/night.json | 4 +- .../buttons/{ => toggle}/rain.json | 2 +- gradle.properties | 2 +- .../neoforge/REINeoforgePluginStub.java | 16 +- 17 files changed, 562 insertions(+), 579 deletions(-) create mode 100644 common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java create mode 100644 common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/test.json rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/{ => toggle}/day.json (67%) rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/{ => toggle}/gamemode.json (79%) rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/{ => toggle}/night.json (73%) rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/{ => toggle}/rain.json (80%) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryCommands.java b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryCommands.java index 305ba786..c62e84fa 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryCommands.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryCommands.java @@ -45,7 +45,7 @@ private interface NBTEditCallback { public static void registerCommands(CommandDispatcher dispatcher, CommandBuildContext commandBuildContext, Commands.CommandSelection type) { var command = Commands.literal("ftblibrary") .requires(commandSource -> commandSource.hasPermission(2)) - .then(Commands.literal("gamemode.json") + .then(Commands.literal("gamemode") .executes(context -> { if (!context.getSource().getPlayerOrException().isCreative()) { context.getSource().getPlayerOrException().setGameMode(GameType.CREATIVE); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java index c0728c64..92733a5e 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java @@ -1,210 +1,205 @@ -//package dev.ftb.mods.ftblibrary.integration; -// -//import com.google.gson.Gson; -//import com.google.gson.JsonObject; -//import com.google.gson.JsonParser; -//import com.mojang.datafixers.util.Pair; -//import com.mojang.serialization.DataResult; -//import com.mojang.serialization.Lifecycle; -//import dev.ftb.mods.ftblibrary.FTBLibrary; -//import dev.ftb.mods.ftblibrary.config.ui.SelectItemStackScreen; -//import dev.ftb.mods.ftblibrary.config.ui.ResourceSearchMode; -//import dev.ftb.mods.ftblibrary.config.ui.SelectableResource; -//import dev.ftb.mods.ftblibrary.icon.Color4I; -//import dev.ftb.mods.ftblibrary.icon.Icon; -//import dev.ftb.mods.ftblibrary.icon.ItemIcon; -//import dev.ftb.mods.ftblibrary.sidebar.SidebarButton; -//import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonCreatedEvent; -//import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonGroup; -//import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonManager; -//import dev.ftb.mods.ftblibrary.ui.GuiHelper; -//import me.shedaniel.math.Rectangle; -//import me.shedaniel.rei.api.client.favorites.FavoriteEntry; -//import me.shedaniel.rei.api.client.favorites.FavoriteEntryType; -//import me.shedaniel.rei.api.client.gui.Renderer; -//import me.shedaniel.rei.api.client.gui.widgets.Tooltip; -//import me.shedaniel.rei.api.client.gui.widgets.TooltipContext; -//import me.shedaniel.rei.api.client.plugins.REIClientPlugin; -//import me.shedaniel.rei.api.client.registry.entry.EntryRegistry; -//import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; -//import me.shedaniel.rei.api.common.util.CollectionUtils; -//import net.minecraft.client.Minecraft; -//import net.minecraft.client.gui.Font; -//import net.minecraft.client.gui.GuiGraphics; -//import net.minecraft.client.gui.screens.Screen; -//import net.minecraft.client.resources.language.I18n; -//import net.minecraft.nbt.CompoundTag; -//import net.minecraft.nbt.NbtOps; -//import net.minecraft.nbt.Tag; -//import net.minecraft.network.chat.Component; -//import net.minecraft.network.chat.MutableComponent; -//import net.minecraft.resources.ResourceLocation; -//import net.minecraft.world.item.ItemStack; -//import net.minecraft.world.item.Items; -//import org.jetbrains.annotations.Nullable; -// -//import java.util.ArrayList; -//import java.util.Collection; -//import java.util.List; -//import java.util.Map; -// -//public class REIIntegration implements REIClientPlugin { -// public static final ResourceLocation ID = FTBLibrary.rl("sidebar_button"); -// -// private static final ResourceSearchMode REI_ITEMS = new ResourceSearchMode<>() { -// @Override -// public Icon getIcon() { -// return ItemIcon.getItemIcon(Items.GLOW_BERRIES); -// } -// -// @Override -// public MutableComponent getDisplayName() { -// return Component.translatable("ftblibrary.select_item.list_mode.rei"); -// } -// -// @Override -// public Collection> getAllResources() { -// return CollectionUtils.filterAndMap( -// EntryRegistry.getInstance().getPreFilteredList(), -// stack -> stack.getType().equals(VanillaEntryTypes.ITEM), -// stack -> SelectableResource.item(stack.castValue()) -// ); -// } -// }; -// -// static { -// SelectItemStackScreen.KNOWN_MODES.prependMode(REI_ITEMS); -// } -// -// @Override -// public void registerFavorites(FavoriteEntryType.Registry registry) { -// registry.register(ID, SidebarButtonType.INSTANCE); -// for (Map.Entry> entry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { -// List buttons = CollectionUtils.map(entry.getValue(), SidebarButtonEntry::new); -// SidebarButtonGroup group = entry.getKey(); -// if (!buttons.isEmpty()) { -// registry.getOrCrateSection(Component.translatable(group.getLangKey())) -// .add(group.isPinned(), buttons.toArray(new SidebarButtonEntry[0])); -// } -// } -// } -// -// private static SidebarButton createSidebarButton(ResourceLocation id, SidebarButtonGroup g, JsonObject json) { -// SidebarButton b = new SidebarButton(id, g, json); -// SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(b)); -// return b; -// } -// -// private enum SidebarButtonType implements FavoriteEntryType { -// INSTANCE; -// -// @Override -// public CompoundTag save(SidebarButtonEntry entry, CompoundTag tag) { -// DataResult encode = SidebarButton.CODEC.encode(entry.button, NbtOps.INSTANCE, null); -// encode.result().ifPresent(t -> tag.put("json", t)); -// return tag; -// } -// -// @Override -// public DataResult read(CompoundTag object) { -// DataResult> json = SidebarButton.CODEC.decode(NbtOps.INSTANCE, object.get("json")); -// return json.map(pair -> new SidebarButtonEntry(pair.getFirst())); -// } -// -// @Override -// public DataResult fromArgs(Object... args) { -// if (args.length == 0) { -// return DataResult.error(() -> "Cannot create SidebarButtonEntry from empty args!"); -// } -// if (!(args[0] instanceof ResourceLocation id)) { -// return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected ResourceLocation as the first argument!"); -// } -// if (!(args[1] instanceof SidebarButton) && !(args[1] instanceof JsonObject)) { -// return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected SidebarButton or JsonObject as the second argument!"); -// } -// return DataResult.success(new SidebarButtonEntry(args[1] instanceof SidebarButton button ? button : createSidebarButton(id, null, (JsonObject) args[1])), Lifecycle.stable()); -// } -// } -// -// private static class SidebarButtonEntry extends FavoriteEntry { -// private final SidebarButton button; -// -// public SidebarButtonEntry(SidebarButton button) { -// this.button = button; -// } -// -// @Override -// public boolean isInvalid() { -// for (var group : SidebarButtonManager.INSTANCE.getGroups()) { -// for (var groupButton : group.getButtons()) { -// if (groupButton.getId().equals(button.getId()) && groupButton.isActuallyVisible()) { -// return false; -// } -// } -// } -// return true; -// } -// -// @Override -// public Renderer getRenderer(boolean showcase) { -// return new Renderer() { -// @Override -// public void render(GuiGraphics graphics, Rectangle bounds, int mouseX, int mouseY, float delta) { -// GuiHelper.setupDrawing(); -// button.getIcon().draw(graphics, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); -// if (button.getCustomTextHandler() != null) { -// String text = button.getCustomTextHandler().get(); -// Font font = Minecraft.getInstance().font; -// if (!text.isEmpty()) { -// var width = font.width(text); -// Color4I.LIGHT_RED.draw(graphics, bounds.getX() + bounds.getWidth() - width, bounds.getY() - 1, width + 1, font.lineHeight); -// graphics.drawString(font, text, bounds.getX() + bounds.getWidth() - width + 1, bounds.getY(), 0xFFFFFFFF); -// } -// } -// } -// -// @Override -// @Nullable -// public Tooltip getTooltip(TooltipContext context) { -// List list = new ArrayList<>(); -// list.add(I18n.get(button.getLangKey())); -// -// if (button.getTooltipHandler() != null) { -// button.getTooltipHandler().accept(list); -// } -// -// return Tooltip.create(context.getPoint(), CollectionUtils.map(list, Component::literal)); -// } -// }; -// } -// -// @Override -// public boolean doAction(int button) { -// this.button.onClicked(Screen.hasShiftDown()); -// return true; -// } -// -// @Override -// public long hashIgnoreAmount() { -// return this.button.getId().hashCode(); -// } -// -// @Override -// public FavoriteEntry copy() { -// return new SidebarButtonEntry(createSidebarButton(button.getId(), null, button.getJson())); -// } -// -// @Override -// public ResourceLocation getType() { -// return ID; -// } -// -// @Override -// public boolean isSame(FavoriteEntry other) { -// if (other instanceof SidebarButtonEntry entry) { -// return entry.button.getId().equals(button.getId()); -// } -// return false; -// } -// } -//} +package dev.ftb.mods.ftblibrary.integration; + +import com.google.gson.JsonObject; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JsonOps; +import com.mojang.serialization.Lifecycle; +import dev.ftb.mods.ftblibrary.FTBLibrary; +import dev.ftb.mods.ftblibrary.config.ui.SelectItemStackScreen; +import dev.ftb.mods.ftblibrary.config.ui.ResourceSearchMode; +import dev.ftb.mods.ftblibrary.config.ui.SelectableResource; +import dev.ftb.mods.ftblibrary.icon.Color4I; +import dev.ftb.mods.ftblibrary.icon.Icon; +import dev.ftb.mods.ftblibrary.icon.ItemIcon; +import dev.ftb.mods.ftblibrary.sidebar.SidebarButton; +import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonData; +import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonCreatedEvent; +import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonGroup; +import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonManager; +import dev.ftb.mods.ftblibrary.ui.GuiHelper; +import me.shedaniel.math.Rectangle; +import me.shedaniel.rei.api.client.favorites.FavoriteEntry; +import me.shedaniel.rei.api.client.favorites.FavoriteEntryType; +import me.shedaniel.rei.api.client.gui.Renderer; +import me.shedaniel.rei.api.client.gui.widgets.Tooltip; +import me.shedaniel.rei.api.client.gui.widgets.TooltipContext; +import me.shedaniel.rei.api.client.plugins.REIClientPlugin; +import me.shedaniel.rei.api.client.registry.entry.EntryRegistry; +import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; +import me.shedaniel.rei.api.common.util.CollectionUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtOps; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class REIIntegration implements REIClientPlugin { + public static final ResourceLocation ID = FTBLibrary.rl("sidebar_button"); + + private static final ResourceSearchMode REI_ITEMS = new ResourceSearchMode<>() { + @Override + public Icon getIcon() { + return ItemIcon.getItemIcon(Items.GLOW_BERRIES); + } + + @Override + public MutableComponent getDisplayName() { + return Component.translatable("ftblibrary.select_item.list_mode.rei"); + } + + @Override + public Collection> getAllResources() { + return CollectionUtils.filterAndMap( + EntryRegistry.getInstance().getPreFilteredList(), + stack -> stack.getType().equals(VanillaEntryTypes.ITEM), + stack -> SelectableResource.item(stack.castValue()) + ); + } + }; + + static { + SelectItemStackScreen.KNOWN_MODES.prependMode(REI_ITEMS); + } + + @Override + public void registerFavorites(FavoriteEntryType.Registry registry) { + registry.register(ID, SidebarButtonType.INSTANCE); + for (Map.Entry> entry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { + List buttons = entry.getValue() + .stream().map(SidebarButtonEntry::new).toList(); + SidebarButtonGroup group = entry.getKey(); + if (!buttons.isEmpty()) { + registry.getOrCrateSection(Component.translatable(group.getLangKey())) + .add(group.isPinned(), buttons.toArray(new SidebarButtonEntry[0])); + } + } + } + + private static SidebarButton createSidebarButton(ResourceLocation id, JsonObject json) { + DataResult parse = SidebarButtonData.CODEC.parse(JsonOps.INSTANCE, json); + if (parse.error().isPresent()) { + FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); + } else { + SidebarButtonData sidebarButton = parse.result().get(); + SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(sidebarButton)); + return new SidebarButton(id, sidebarButton); + } + return null; + } + + private enum SidebarButtonType implements FavoriteEntryType { + INSTANCE; + + @Override + public CompoundTag save(SidebarButtonEntry entry, CompoundTag tag) { + tag.putString("id", entry.button.getId().toString()); + DataResult encode = SidebarButtonData.CODEC.encode(entry.button.getData(), NbtOps.INSTANCE, null); + encode.result().ifPresent(t -> tag.put("json", t)); + return tag; + } + + @Override + public DataResult read(CompoundTag object) { + ResourceLocation id = ResourceLocation.parse(object.getString("id")); + DataResult> json = SidebarButtonData.CODEC.decode(NbtOps.INSTANCE, object.get("json")); + return json.map(pair -> new SidebarButtonEntry(new SidebarButton(id, pair.getFirst()))); + } + + @Override + //Todo fix this + public DataResult fromArgs(Object... args) { + if (args.length == 0) { + return DataResult.error(() -> "Cannot create SidebarButtonEntry from empty args!"); + } + if (!(args[0] instanceof ResourceLocation id)) { + return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected ResourceLocation as the first argument!"); + } + if (!(args[1] instanceof SidebarButton button) && !(args[1] instanceof JsonObject)) { + return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected SidebarButton or JsonObject as the second argument!"); + } + return DataResult.success(new SidebarButtonEntry(args[1] instanceof SidebarButton button ? button : createSidebarButton(id, (JsonObject) args[1])), Lifecycle.stable()); + } + } + + private static class SidebarButtonEntry extends FavoriteEntry { + private final SidebarButton button; + + public SidebarButtonEntry(SidebarButton button) { + this.button = button; + } + + @Override + public boolean isInvalid() { + return button.canSee(); + } + + @Override + public Renderer getRenderer(boolean showcase) { + return new Renderer() { + @Override + public void render(GuiGraphics graphics, Rectangle bounds, int mouseX, int mouseY, float delta) { + GuiHelper.setupDrawing(); + button.getData().icon().draw(graphics, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); + if (button.getCustomTextHandler() != null) { + String text = button.getCustomTextHandler().get(); + Font font = Minecraft.getInstance().font; + if (!text.isEmpty()) { + var width = font.width(text); + Color4I.LIGHT_RED.draw(graphics, bounds.getX() + bounds.getWidth() - width, bounds.getY() - 1, width + 1, font.lineHeight); + graphics.drawString(font, text, bounds.getX() + bounds.getWidth() - width + 1, bounds.getY(), 0xFFFFFFFF); + } + } + } + + @Override + @Nullable + public Tooltip getTooltip(TooltipContext context) { + return Tooltip.create(context.getPoint(), button.getTooltip()); + } + }; + } + + @Override + public boolean doAction(int button) { + this.button.clickButton(Screen.hasShiftDown()); + return true; + } + + @Override + public long hashIgnoreAmount() { + return this.button.getId().hashCode(); + } + + @Override + public FavoriteEntry copy() { + //Todo fix this? + return new SidebarButtonEntry(button); + } + + @Override + public ResourceLocation getType() { + return ID; + } + + @Override + public boolean isSame(FavoriteEntry other) { + if (other instanceof SidebarButtonEntry entry) { + return entry.button.getId().equals(button.getId()); + } + return false; + } + } +} diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java new file mode 100644 index 00000000..ac47b318 --- /dev/null +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java @@ -0,0 +1,10 @@ +package dev.ftb.mods.ftblibrary.sidebar; + +public record GridLocation(int x, int y) { + + public static final GridLocation OUT_OF_BOUNDS = new GridLocation(-1, -1); + + public boolean isOutOfBounds() { + return x < 0 || y < 0; + } + } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java index 6cf1fafa..9ed8c598 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java @@ -1,175 +1,84 @@ package dev.ftb.mods.ftblibrary.sidebar; -import com.mojang.serialization.Codec; -import com.mojang.serialization.MapCodec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import dev.ftb.mods.ftblibrary.FTBLibraryClient; -import dev.ftb.mods.ftblibrary.icon.Icon; +import dev.architectury.platform.Platform; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import dev.ftb.mods.ftblibrary.ui.misc.LoadingScreen; +import dev.ftb.mods.ftblibrary.util.ChainedBooleanSupplier; +import dev.ftb.mods.ftblibrary.util.client.ClientUtils; import net.minecraft.Util; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; import java.util.List; +import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; +public class SidebarButton { -public record SidebarButton( - ResourceLocation group, - Icon icon, - int x, - boolean defaultEnabled, - List clickEvents, - List shiftClickEvent, - boolean loadingScreen, - List tooltips, - boolean requiresOp) implements Comparable { - - public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( - ResourceLocation.CODEC.fieldOf("group").forGetter(SidebarButton::group), - Icon.CODEC.fieldOf("icon").forGetter(SidebarButton::icon), - Codec.BOOL.fieldOf("requires_op").orElse(false).forGetter(SidebarButton::requiresOp), - Codec.STRING.listOf(1, Integer.MAX_VALUE).fieldOf("click").orElse(List.of()).forGetter(SidebarButton::clickEvents), - Codec.STRING.listOf().fieldOf("shift_click").orElse(List.of()).forGetter(SidebarButton::shiftClickEvent), - Codec.BOOL.fieldOf("loading_screen").orElse(false).forGetter(SidebarButton::loadingScreen), - Codec.BOOL.fieldOf("default_enabled").orElse(true).forGetter(SidebarButton::defaultEnabled), - Codec.STRING.listOf().fieldOf("text").orElse(List.of()).forGetter(SidebarButton::tooltips) - ).apply(builder, SidebarButton::of)); -// -// - public static SidebarButton of(ResourceLocation group, - Icon icon, - boolean requiresOp, - List clickEvents, - List shiftClickEvents, - boolean loadingScreen, - boolean defaultEnabled, - List tooltips) { - return new SidebarButton( group, icon, 0, defaultEnabled, clickEvents, shiftClickEvents, loadingScreen, tooltips, requiresOp); - } - - -// public SidebarButton(ResourceLocation id, SidebarButtonGroup group, JsonObject json) { -// this.group = group; -// this.id = id; -// this.json = json; -// -// if (json.has("icon")) { -// icon = Icon.getIcon(json.get("icon")); -// } -// -// if (icon.isEmpty()) { -// icon = Icons.ACCEPT_GRAY; -// } -// -// if (json.has("click")) { -// var j = json.get("click"); -// for (var e : j.isJsonArray() ? j.getAsJsonArray() : Collections.singleton(j)) { -// if (e.isJsonPrimitive()) { -// clickEvents.add(e.getAsString()); -// } -// } -// } -// if (json.has("shift_click")) { -// var j = json.get("shift_click"); -// for (var e : j.isJsonArray() ? j.getAsJsonArray() : Collections.singleton(j)) { -// if (e.isJsonPrimitive()) { -// shiftClickEvents.add(e.getAsString()); -// } -// } -// } -// if (json.has("config")) { -// defaultEnabled = configValue = json.get("config").getAsBoolean(); -// } -// -// if (json.has("x")) { -// x = json.get("x").getAsInt(); -// } -// -// if (json.has("requires_op") && json.get("requires_op").getAsBoolean()) { -// addVisibilityCondition(ClientUtils.IS_CLIENT_OP); -// } -// -// if (json.has("required_mods")) { -// var requiredServerMods = new LinkedHashSet(); -// -// for (var e : json.get("required_mods").getAsJsonArray()) { -// requiredServerMods.add(e.getAsString()); -// } -// -// addVisibilityCondition(() -> { -// for (var s : requiredServerMods) { -// if (!Platform.isModLoaded(s)) { -// return false; -// } -// } -// -// return true; -// }); -// } -// -// loadingScreen = json.has("loading_screen") && json.get("loading_screen").getAsBoolean(); -// } - - -// public ResourceLocation getId() { -// return id; -// } -// -// public SidebarButtonGroup getGroup() { -// return group; -// } -// -// public JsonObject getJson() { -// return json; -// } -// -// public void addVisibilityCondition(BooleanSupplier supplier) { -// visible = visible.and(supplier); -// } - - public String getLangKey() { - //Todo -unreal - return Util.makeDescriptionId("sidebar_button", ResourceLocation.fromNamespaceAndPath("ftbquests", "sidebar_button")); - } - - public String getTooltipLangKey() { - return getLangKey() + ".tooltip"; - } - - public void onClicked(boolean shift) { - if (loadingScreen) { - new LoadingScreen(Component.translatable(getLangKey())).openGui(); - } - - for (var event : (shift && !shiftClickEvent.isEmpty() ? shiftClickEvent : clickEvents)) { - GuiHelper.BLANK_GUI.handleClick(event); - } - } - - public boolean isVisible() { - return true; - } - - - @Nullable - public Supplier getCustomTextHandler() { - return () -> ""; - } - - - @Nullable - public Consumer> getTooltipHandler() { - return s -> {}; - } - - - - @Override - public int compareTo(SidebarButton button) { - return x - button.x; - } + private final SidebarButtonData data; + private final ResourceLocation id; + private final String langKey; + private final Component basicTooltip; + private Supplier tooltipOverride; + private ChainedBooleanSupplier visible = ChainedBooleanSupplier.TRUE; + + + public SidebarButton(ResourceLocation id, SidebarButtonData data) { + this.id = id; + this.data = data; + this.langKey = Util.makeDescriptionId("sidebar_button", id); + basicTooltip = Component.translatable(langKey + ".tooltip"); + if(data.requiresOp()) { + addVisibilityCondition(ClientUtils.IS_CLIENT_OP); + } + data.requiredMods().ifPresent(mods -> addVisibilityCondition(() -> mods.stream().allMatch(Platform::isModLoaded))); + } + + + public void addVisibilityCondition(BooleanSupplier condition) { + visible = visible.and(condition); + } + + + public SidebarButtonData getData() { + return data; + } + + public ResourceLocation getId() { + return id; + } + + public String getLangKey() { + return langKey; + } + + public List getTooltip() { + return tooltipOverride == null ? List.of(basicTooltip) : List.of(basicTooltip, tooltipOverride.get()); + } + + public void clickButton(boolean shift) { + if (data.loadingScreen()) { + new LoadingScreen(Component.translatable(getLangKey())).openGui(); + } + + for (String event : (shift && data.shiftClickEvent().isPresent() ? data.shiftClickEvent().get() : data.clickEvents())) { + GuiHelper.BLANK_GUI.handleClick(event); + } + } + + //Todo mods + public boolean canSee() { + return visible.getAsBoolean(); + } + + //Todo fix both of these + public Supplier getCustomTextHandler() { + return null; + } + + public Consumer> getTooltipHandler() { + return null; + } } + diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java index 83875f4e..032c883e 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java @@ -1,23 +1,24 @@ package dev.ftb.mods.ftblibrary.sidebar; -import dev.architectury.annotations.ForgeEvent; import dev.architectury.event.Event; import dev.architectury.event.EventFactory; import java.util.function.Consumer; +//Todo - UnReal Expose a way for other mod to reigster custom text handlers as that what this event is for +//Todo WE DO NOT ALLOW EDITING BUTTONS AFTER CREATION ANYMORE // TODO currently broken for neoforge, uncomment when there's a fix in architectury //@ForgeEvent public class SidebarButtonCreatedEvent { public static final Event> EVENT = EventFactory.createConsumerLoop(SidebarButtonCreatedEvent.class); - private final SidebarButton button; + private final SidebarButtonData button; - public SidebarButtonCreatedEvent(SidebarButton b) { + public SidebarButtonCreatedEvent(SidebarButtonData b) { button = b; } - public SidebarButton getButton() { + public SidebarButtonData getButton() { return button; } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java new file mode 100644 index 00000000..7a0bb386 --- /dev/null +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java @@ -0,0 +1,44 @@ +package dev.ftb.mods.ftblibrary.sidebar; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import dev.ftb.mods.ftblibrary.icon.Icon; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentSerialization; +import net.minecraft.resources.ResourceLocation; + +import java.util.List; +import java.util.Optional; + + +public record SidebarButtonData( + ResourceLocation group, + Icon icon, + int x, + boolean defaultEnabled, + List clickEvents, + Optional> shiftClickEvent, + boolean loadingScreen, + Optional tooltip, + boolean requiresOp, + Optional> requiredMods) implements Comparable { + + public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( + ResourceLocation.CODEC.fieldOf("group").forGetter(SidebarButtonData::group), + Icon.CODEC.fieldOf("icon").forGetter(SidebarButtonData::icon), + Codec.INT.fieldOf("x").forGetter(SidebarButtonData::x), + Codec.BOOL.fieldOf("default_enabled").orElse(true).forGetter(SidebarButtonData::defaultEnabled), + Codec.STRING.listOf(1, Integer.MAX_VALUE).fieldOf("click").forGetter(SidebarButtonData::clickEvents), + Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("shift_click").forGetter(SidebarButtonData::shiftClickEvent), + Codec.BOOL.fieldOf("loading_screen").orElse(false).forGetter(SidebarButtonData::loadingScreen), + ComponentSerialization.CODEC.optionalFieldOf("tooltip").forGetter(SidebarButtonData::tooltip), + Codec.BOOL.fieldOf("requires_op").orElse(false).forGetter(SidebarButtonData::requiresOp), + Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("required_mods").forGetter(SidebarButtonData::requiredMods) + ).apply(builder, SidebarButtonData::new)); + + + @Override + public int compareTo(SidebarButtonData button) { + return x - button.x; + } +} diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java index 1061b714..49b97c2a 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java @@ -8,6 +8,7 @@ import net.minecraft.resources.ResourceLocation; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index e6da90e3..0db4023a 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -17,11 +17,12 @@ import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; +import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.Consumer; +import java.util.function.BiConsumer; import java.util.stream.Collectors; @@ -30,8 +31,8 @@ public enum SidebarButtonManager implements ResourceManagerReloadListener { private static final Logger LOGGER = LogUtils.getLogger(); - private final List> groups = new ArrayList<>(); - private final List> buttons = new ArrayList<>(); + private final Map groups = new HashMap<>(); + private final Map buttons = new HashMap<>(); private JsonElement readJson(Resource resource) { try (BufferedReader reader = resource.openAsReader()) { @@ -42,68 +43,37 @@ private JsonElement readJson(Resource resource) { return JsonNull.INSTANCE; } - public List> getButtons() { - return buttons; + public Collection getButtons() { + return buttons.values(); } -// public Map> getButtonGroups() { -// Map> map = new HashMap<>(); -// for (SidebarButton value : buttons.values()) { -// SidebarButtonGroup group = groups.get(value.group()); -// if(group != null) { -// if(!map.containsKey(group)) { -// map.put(group, new ArrayList<>()); -// } -// map.get(group).add(value); -// -// }else { -// //Todo This should never happen in theory -// } -// } -// return map.entrySet().stream().sorted(Comparator.comparingInt(o -> o.getKey().y())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); -// } - - public SidebarButtonGroup getGroup(ResourceLocation id) { - return groups.stream() - .filter(group -> group.id().equals(id)) - .findFirst() - .map(StoredInfo::value) - .orElse(null); - } - @Override public void onResourceManagerReload(ResourceManager manager) { groups.clear(); buttons.clear(); - loadResources(manager, "sidebar_buttons/groups", SidebarButtonGroup.CODEC, groups::add); - loadResources(manager, "sidebar_buttons/buttons", SidebarButton.CODEC, (result) -> { - SidebarButtonGroup group = getGroup(result.value().group()); + //Read the button and group json files and register them to their 'registry' map + loadResources(manager, "sidebar_buttons/groups", SidebarButtonGroup.CODEC, groups::put); + loadResources(manager, "sidebar_buttons/buttons", SidebarButtonData.CODEC, (id, buttonData) -> { + SidebarButtonGroup group = groups.get(buttonData.group()); if(group != null) { - buttons.add(result); + buttons.put(id, new SidebarButton(id, buttonData)); }else { - LOGGER.error("Button {} not found in config", result.id()); + LOGGER.error("Could not register button {} as group {} does not exist", id, buttonData.group()); } }); - Map>> buttonMap = new HashMap<>(); - for (StoredInfo storedInfo : this.buttons) { - buttonMap.computeIfAbsent(getGroup(storedInfo.value().group()).y(), k -> new ArrayList<>()).add(storedInfo); - } - - //sort buttonMap by key - buttonMap = buttonMap.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getKey)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); + Map> buttonMap = getButtonGroups(); int y = 0; - for (List> storedInfoList : buttonMap.values()) { + for (Map.Entry> buttonGroupListEntry : buttonMap.entrySet()) { int x = 0; - storedInfoList.sort(Comparator.comparingInt(o -> o.value().x())); - for (StoredInfo sidebarButtonStoredInfo : storedInfoList) { - SidebarButton button = sidebarButtonStoredInfo.value(); - SidebarButtonGroup group = getGroup(button.group()); - StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(sidebarButtonStoredInfo.id().toString()); + buttonGroupListEntry.getValue().sort(Comparator.comparingInt(button -> button.getData().x())); + for (SidebarButton sidebarButton : buttonGroupListEntry.getValue()) { + SidebarButtonData button = sidebarButton.getData(); + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(sidebarButton.getId().toString()); if (buttonSettings == null) { - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(sidebarButtonStoredInfo.id().toString(), new StringSidebarMapValue.SideButtonInfo(true, x, y)); + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(sidebarButton.getId().toString(), new StringSidebarMapValue.SideButtonInfo(button.defaultEnabled(), x, y)); } x++; } @@ -222,7 +192,7 @@ public void onResourceManagerReload(ResourceManager manager) { // // saveConfig(); - private void loadResources(ResourceManager manager, String path, Codec codec, Consumer> consumer) { + private void loadResources(ResourceManager manager, String path, Codec codec, BiConsumer consumer) { Map resourceLocationResourceMap = manager.listResources(path, name -> name.getPath().endsWith(".json")); for (Map.Entry resource : resourceLocationResourceMap.entrySet()) { JsonElement jsonElement = readJson(resource.getValue()); @@ -232,8 +202,9 @@ private void loadResources(ResourceManager manager, String path, Codec co } else { T result = parse.result().get(); ResourceLocation key = resource.getKey(); - ResourceLocation fixed = ResourceLocation.fromNamespaceAndPath(key.getNamespace(), key.getPath().replace(path + "/", "").replace(".json", "")); - consumer.accept(new StoredInfo<>(fixed, result)); + String path1 = key.getPath(); + ResourceLocation fixed = ResourceLocation.fromNamespaceAndPath(key.getNamespace(), path1.replace(path + "/", "").replace(".json", "")); + consumer.accept(fixed, result); } } } @@ -243,26 +214,31 @@ private void loadResources(ResourceManager manager, String path, Codec co public void refreshButtonList() { buttonList.clear(); - for (StoredInfo buttonEntry : getButtons()) { - ResourceLocation id = buttonEntry.id(); - SidebarButton button = buttonEntry.value(); - - StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(id.toString()); - if(buttonSettings != null) { - SidebarGuiButton e = new SidebarGuiButton(buttonSettings.xPos(), buttonSettings.yPos(), buttonSettings.enabled(), id, button); - buttonList.add(e); - }else { - //Todo this should not be possable - LOGGER.error("Button {} not found in config", id); - } + for (SidebarButton buttonEntry : getButtons()) { +// if(buttonEntry.canSee()) { + ResourceLocation id = buttonEntry.getId(); + SidebarButtonData button = buttonEntry.getData(); + + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(id.toString()); + if(buttonSettings != null) { + SidebarGuiButton e = new SidebarGuiButton(new GridLocation(buttonSettings.xPos(), buttonSettings.yPos()), buttonSettings.enabled(), buttonEntry); + buttonList.add(e); + }else { + //Todo this should not be possable + LOGGER.error("Button {} not found in config", id); + } +// } } for (Map.Entry stringSideButtonInfoEntry : FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().entrySet()) { + if(!isRegistered(ResourceLocation.parse(stringSideButtonInfoEntry.getKey()))) { + continue; + } StringSidebarMapValue.SideButtonInfo buttonSettings = stringSideButtonInfoEntry.getValue(); if(buttonSettings != null && buttonSettings.enabled()) { for (SidebarGuiButton button : buttonList) { - if(button.isEnabled()) { - if(!button.getButtonId().toString().equals(stringSideButtonInfoEntry.getKey())) { + if(button.getSidebarButton().canSee() && button.isEnabled()) { + if(!button.getSidebarButton().getId().toString().equals(stringSideButtonInfoEntry.getKey())) { if(button.getGridY() == buttonSettings.yPos() && button.getGridX() == buttonSettings.xPos()) { button.setGrid(button.getGridX() + 1, button.getGridY()); } @@ -276,11 +252,15 @@ public void refreshButtonList() { FTBLibraryClientConfig.save(); } + private boolean isRegistered(ResourceLocation id) { + return buttons.values().stream().anyMatch(button -> button.getId().equals(id)); + } + public void saveConfigFromButtonList() { for (SidebarGuiButton button : buttonList) { - StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getButtonId().toString()); + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getSidebarButton().getId().toString()); if(buttonSettings != null) { - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getButtonId().toString(), new StringSidebarMapValue.SideButtonInfo(button.isEnabled(), button.getGridX(), button.getGridY())); + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(button.isEnabled(), button.getGridX(), button.getGridY())); } } FTBLibraryClientConfig.save(); @@ -301,32 +281,41 @@ public List getDisabledButtonList() { } - // var o = new JsonObject(); -// -// for (var group : groups) { -// for (var button : group.getButtons()) { -// var o1 = o.getAsJsonObject(button.getId().getNamespace()); -// -// if (o1 == null) { -// o1 = new JsonObject(); -// o.add(button.getId().getNamespace(), o1); -// } -// -// o1.addProperty(button.getId().getPath(), button.getConfig()); -// } -// } -// -// var file = Platform.getConfigFolder().resolve("sidebar_buttons.json").toFile(); -// -// try (var writer = new FileWriter(file)) { -// var gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); -// var jsonWriter = new JsonWriter(writer); -// jsonWriter.setIndent("\t"); -// gson.toJson(o, jsonWriter); -// } catch (Exception ex) { -// ex.printStackTrace(); -// } + public Map> getButtonGroups() { + Map> buttonMap = new HashMap<>(); + for (SidebarButton buttonData : this.buttons.values()) { + buttonMap.computeIfAbsent(groups.get(buttonData.getData().group()), k -> new ArrayList<>()).add(buttonData); + } - public record StoredInfo(ResourceLocation id, T value) {} + return Utils.sortMapByKey(buttonMap); + } + + + + //Todo cleanup + public static class Utils { + + public static Map sortMapByKey(Map map, Comparator comparator) { + return map.entrySet().stream() + .sorted(Map.Entry.comparingByKey(comparator)) + .collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (a, b) -> a, + HashMap::new + )); + } + + public static, V> Map sortMapByKey(Map map) { + return map.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (a, b) -> a, + HashMap::new + )); + } + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index a2e8db56..50046195 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -1,13 +1,8 @@ package dev.ftb.mods.ftblibrary.sidebar; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.Table; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.math.Axis; import dev.ftb.mods.ftblibrary.icon.Color4I; -import dev.ftb.mods.ftblibrary.icon.Icon; import dev.ftb.mods.ftblibrary.icon.Icons; -import dev.ftb.mods.ftblibrary.ui.Button; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; @@ -17,18 +12,12 @@ import net.minecraft.client.renderer.Rect2i; import net.minecraft.client.resources.language.I18n; import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import org.joml.Quaternionf; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; - public class SidebarGroupGuiButton extends AbstractButton { public static Rect2i lastDrawnArea = new Rect2i(0, 0, 0, 0); @@ -60,23 +49,25 @@ public SidebarGroupGuiButton() { @Override public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { + graphics.pose().translate(0,0,5000); currentMouseX = mx; currentMouseY = my; mouseOver = null; - GridLocation gridLocation = getGridLocation(mx, my); + GridLocation gridLocation = getGridLocation(); List enabledButtonList = SidebarButtonManager.INSTANCE.getEnabledButtonList(); for (SidebarGuiButton button : enabledButtonList) { - if(button.getGridX() == gridLocation.x && button.getGridY() == gridLocation.y) { + if(button.getGridX() == gridLocation.x() && button.getGridY() == gridLocation.y()) { mouseOver = button; } } maxGridWith = enabledButtonList - .stream().max(Comparator.comparingInt(SidebarGuiButton::getGridX)) + .stream() + .max(Comparator.comparingInt(SidebarGuiButton::getGridX)) .map(SidebarGuiButton::getGridX) .orElse(1) + 2; maxGridHeight = enabledButtonList @@ -92,19 +83,37 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(); if(!disabledButtonList.isEmpty()) { - Icons.ADD.draw(graphics, (maxGridWith - 1) * BUTTON_SPACING + 1, (maxGridHeight - 1) * BUTTON_SPACING + 1, 16, 16); + drawGrid(graphics, ( maxGridWith + 1) * BUTTON_SPACING, 0, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + Icons.ADD.draw(graphics, (maxGridWith + 1) * BUTTON_SPACING + 1, 1, 16, 16); if(addBoxOpen) { - drawHoveredGrid(graphics, ( maxGridWith - 0) * BUTTON_SPACING, (maxGridHeight - 1) * BUTTON_SPACING, disabledButtonList.size(), 1, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my); + + + int maxWidth = 0; + for (SidebarGuiButton button : disabledButtonList) { + String s = I18n.get(button.getSidebarButton().getLangKey()); + int width = Minecraft.getInstance().font.width(s); + maxWidth = Math.max(maxWidth, width); + } + + +// drawHoveredGrid(graphics, ( maxGridWith + 2) * BUTTON_SPACING, 0, disabledButtonList.size(), 1, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my); +// Color4I.GRAY.draw(graphics, ( maxGridWith + 1) * BUTTON_SPACING, BUTTON_SPACING, 1 + BUTTON_SPACING * 5, BUTTON_SPACING * disabledButtonList.size()); + //draw black border + drawGrid(graphics, ( maxGridWith + 1) * BUTTON_SPACING, BUTTON_SPACING, 1, disabledButtonList.size(), maxWidth + BUTTON_SPACING + 4, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + + + for (int i = 0; i < disabledButtonList.size(); i++) { SidebarGuiButton button = disabledButtonList.get(i); if(selectedButton != null && selectedButton == button) { continue; } - button.x = (maxGridWith - 0) * BUTTON_SPACING + i * BUTTON_SPACING; - button.y = (maxGridHeight - 1) * BUTTON_SPACING; + button.x = ( maxGridWith + 1) * BUTTON_SPACING; + button.y = BUTTON_SPACING + BUTTON_SPACING * i; GuiHelper.setupDrawing(); - button.button.icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); + button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); + graphics.drawString(Minecraft.getInstance().font, I18n.get(button.getSidebarButton().getLangKey()), button.x + 20, button.y + 4, 0xFFFFFFFF); if(mx >= button.x && mx < button.x + 16 && my >= button.y && my < button.y + 16) { mouseOver = button; @@ -117,10 +126,6 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick } - - graphics.pose().pushPose(); - graphics.pose().translate(0, 0, 500); - var font = Minecraft.getInstance().font; //Todo better way? @@ -139,17 +144,23 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick button.y = 1 + button.getGridY() * BUTTON_SPACING; } GuiHelper.setupDrawing(); - button.button.icon().draw(graphics, button.x, button.y, 16, 16); + button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); + if(isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList().size() > 1) { - Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); + //if mouse if over cancle + if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { + Icons.CANCEL.draw(graphics, button.x + 12, button.y, 6, 6); + }else { + Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); + } } if (button == mouseOver) { Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); } - if (button.button.getCustomTextHandler() != null) { - var text = button.button.getCustomTextHandler().get(); + if (button.getSidebarButton().getCustomTextHandler() != null) { + var text = button.getSidebarButton().getCustomTextHandler().get(); if (!text.isEmpty()) { var nw = font.width(text); @@ -167,10 +178,10 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick var my1 = Math.max(3, my - 9); List list = new ArrayList<>(); - list.add(I18n.get(mouseOver.button.getLangKey())); + list.add(I18n.get(mouseOver.getSidebarButton().getLangKey())); - if (mouseOver.button.getTooltipHandler() != null) { - mouseOver.button.getTooltipHandler().accept(list); + if (mouseOver.getSidebarButton().getTooltipHandler() != null) { + mouseOver.getSidebarButton().getTooltipHandler().accept(list); } var tw = 0; @@ -179,8 +190,6 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick tw = Math.max(tw, font.width(s)); } - graphics.pose().translate(0, 0, 500); - Color4I.DARK_GRAY.draw(graphics, mx1 - 3, my1 - 2, tw + 6, 2 + list.size() * 10); for (var i = 0; i < list.size(); i++) { @@ -188,10 +197,10 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick } } - GuiHelper.setupDrawing(); +// GuiHelper.setupDrawing(); //zLevel = 0F; - lastDrawnArea = new Rect2i(getX(), getY(), width, height); + graphics.pose().popPose(); } @@ -201,10 +210,10 @@ public void onRelease(double d, double e) { super.onRelease(d, e); isMouseDown = false; if (!isEditMode && mouseOver != null) { - mouseOver.button.onClicked(Screen.hasShiftDown()); + mouseOver.getSidebarButton().clickButton(Screen.hasShiftDown()); } else { if (selectedButton != null) { - GridLocation gLocation = getGridLocation(currentMouseX, currentMouseY); + GridLocation gLocation = getGridLocation(); //Checks if the icon is placed in the same location picked up from, if so do nothing if (!gLocation.isOutOfBounds()) if (!gLocation.equals(selectedLocation)) { @@ -212,15 +221,18 @@ public void onRelease(double d, double e) { List buttonList = SidebarButtonManager.INSTANCE.getButtonList(); for (SidebarGuiButton button : buttonList) { if (!selectedButton.equals(button)) { - if (button.getGridY() == gLocation.y && button.getGridX() >= gLocation.x) { + if (button.getGridY() == gLocation.y() && button.getGridX() >= gLocation.x()) { button.setGrid(button.getGridX() + 1, button.getGridY()); } } } - selectedButton.setGrid(gLocation.x, gLocation.y); + selectedButton.setGrid(gLocation.x(), gLocation.y()); if (!selectedButton.isEnabled()) { selectedButton.setEnabled(true); SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); + if (SidebarButtonManager.INSTANCE.getDisabledButtonList().isEmpty()) { + addBoxOpen = false; + } } } selectedButton = null; @@ -253,7 +265,11 @@ private void ensureGridAlignment() { SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); + updateWidgetSize(); + + } + private void updateWidgetSize() { setX(0); setY(0); // Important: JEI doesn't like negative X/Y values and will silently clamp them, @@ -261,24 +277,32 @@ private void ensureGridAlignment() { // of its GUI areas, including resetting the filter textfield's selection // https://github.com/FTBTeam/FTB-Mods-Issues/issues/262 // https://github.com/mezz/JustEnoughItems/issues/2938 - var maxGirdX = 2; - var maxGirdY = 2; + var maxGirdX = 1; + var maxGirdY = 1; for (SidebarGuiButton b : SidebarButtonManager.INSTANCE.getEnabledButtonList()) { maxGirdX = Math.max(maxGirdX, b.getGridX() + 1); maxGirdY = Math.max(maxGirdY, b.getGridY() + 1); } + int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList().size(); if(isEditMode && addBoxOpen) { - for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getDisabledButtonList()) { - maxGirdX++; - } - } + maxGirdX += 4; + int size = disabledList; + maxGirdY = Math.max(maxGirdY, size); + } + if(isEditMode) { + maxGirdX += 3; + maxGirdY += 1; + } + + + width = (maxGirdX) * BUTTON_SPACING; + height = (maxGirdY) * BUTTON_SPACING; - width = (maxGirdX + 1) * BUTTON_SPACING; - height = (maxGirdY + 1) * BUTTON_SPACING; + lastDrawnArea = new Rect2i(getX(), getY(), width, height); } - private GridLocation getGridLocation(int x, int y) { + private GridLocation getGridLocation() { int gridX = (currentMouseX - 1) / BUTTON_SPACING; int gridY = (currentMouseY - 1) / BUTTON_SPACING; if(gridX >= maxGridWith || gridY >= maxGridHeight) { @@ -291,11 +315,21 @@ private GridLocation getGridLocation(int x, int y) { public void onPress() { if(isEditMode) { //if clicked the bottom right grid spot - GridLocation gridLocation = getGridLocation(currentMouseX, currentMouseY); - if(gridLocation.x == maxGridWith - 1 && gridLocation.y == maxGridHeight - 1) { + //check if mouse clicked in same spot as the plus button + // drawGrid(graphics, ( maxGridWith + 1) * BUTTON_SPACING, 0, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + if(currentMouseX >= ( maxGridWith + 1) * BUTTON_SPACING && currentMouseY <= BUTTON_SPACING) { addBoxOpen = !addBoxOpen; + updateWidgetSize(); return; } + + +// GridLocation gridLocation = getGridLocation(currentMouseX, currentMouseY); +// if(gridLocation.x() == maxGridWith - 1 && gridLocation.y() == maxGridHeight - 1) { +// addBoxOpen = !addBoxOpen; +// updateWidgetSize(); +// return; +// } } if(mouseOver != null) { @@ -335,43 +369,45 @@ public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) defaultButtonNarrationText(narrationElementOutput); } - public record GridLocation(int x, int y) { - - public static final GridLocation OUT_OF_BOUNDS = new GridLocation(-1, -1); - public boolean isOutOfBounds() { - return x < 0 || y < 0; - } + @Override + protected boolean isValidClickButton(int i) { + //Todo don't just allow edit mode try and be more specific + return super.isValidClickButton(i) && (isEditMode || !getGridLocation().isOutOfBounds()); } - public void tick() { if(isMouseDown) { mouseDownTime++; if(mouseDownTime > 20) { isEditMode = true; mouseOver = null; + updateWidgetSize(); } - } else { - //Todo -// if(mouseDownTime <= 0) { -// isEditMode = false; -// }else { -// mouseDownTime--; -// } } } - public static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor) { - backgroundColor.draw(graphics, x, y, width * spacing, height * spacing); + private static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacingWidth, int spacingHeight, Color4I backgroundColor, Color4I gridColor) { + backgroundColor.draw(graphics, x, y, width * spacingWidth, height * spacingHeight); for (var i = 0; i < width + 1; i++) { - gridColor.draw(graphics, x + i * spacing, y, 1, height * spacing); + gridColor.draw(graphics, x + i * spacingWidth, y, 1, height * spacingHeight); } for (var i = 0; i < height + 1; i++) { - gridColor.draw(graphics, x, y + i * spacing, width * spacing, 1); + gridColor.draw(graphics, x, y + i * spacingHeight, width * spacingWidth, 1); } } + public static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor) { + drawGrid(graphics, x, y, width, height, spacing, spacing, backgroundColor, gridColor); +// backgroundColor.draw(graphics, x, y, width * spacing, height * spacing); +// for (var i = 0; i < width + 1; i++) { +// gridColor.draw(graphics, x + i * spacing, y, 1, height * spacing); +// } +// for (var i = 0; i < height + 1; i++) { +// gridColor.draw(graphics, x, y + i * spacing, width * spacing, 1); +// } + } + public static void drawHoveredGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor, int mx, int my) { drawGrid(graphics, x, y, width, height, spacing, backgroundColor, gridColor); if (mx >= x && my >= y && mx < x + width * spacing && my < y + height * spacing) { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java index 5bc02043..be899bff 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java @@ -1,24 +1,17 @@ package dev.ftb.mods.ftblibrary.sidebar; - -import net.minecraft.resources.ResourceLocation; - public class SidebarGuiButton { - private final ResourceLocation buttonId; - public final SidebarButton button; + private final SidebarButton sidebarButton; public int x, y; - private int gridX; - private int gridY; + private GridLocation gridLocation; private boolean enabled; - public SidebarGuiButton(int gridX, int gridY, boolean enabled, ResourceLocation buttonId, SidebarButton b) { - button = b; + public SidebarGuiButton(GridLocation girdLocation, boolean enabled, SidebarButton sidebarButton) { x = 0; y = 0; - this.gridX = gridX; - this.gridY = gridY; - this.buttonId = buttonId; + this.gridLocation = girdLocation; + this.sidebarButton = sidebarButton; this.enabled = enabled; } @@ -30,28 +23,20 @@ public void setEnabled(boolean enabled) { this.enabled = enabled; } - public ResourceLocation getButtonId() { - return buttonId; + public SidebarButton getSidebarButton() { + return sidebarButton; } public int getGridX() { - return enabled ? gridX : -1; + return enabled ? gridLocation.x() : -1; } public int getGridY() { - return enabled ? gridY : -1; - } - - public void setGridX(int gridX) { - this.gridX = gridX; - } - - public void setGridY(int gridY) { - this.gridY = gridY; + return enabled ? gridLocation.y() : -1; } public void setGrid(int gridX, int gridY) { - this.gridX = gridX; - this.gridY = gridY; + this.gridLocation = new GridLocation(gridX, gridY); } + } diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/test.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/test.json new file mode 100644 index 00000000..7c869978 --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/test.json @@ -0,0 +1,14 @@ +{ + "group": "ftblibrary:cheat", + "icon": [ + "ftblibrary:icons/blue_button", + "ftblibrary:textures/icons/camera.png" + ], + "x": 120, + "click": ["command:/say hi"], + "required_mods": [ + "ftblibrary", + "neotech" + ], + "requires_op": true +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/day.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/day.json similarity index 67% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/day.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/day.json index b0f42f5f..4a18f734 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/day.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/day.json @@ -5,10 +5,9 @@ "ftblibrary:textures/icons/toggle_day.png" ], "x": 120, - "click": "command:/ftblibrary day", - "required_server_mods": [ + "click": ["command:/ftblibrary day"], + "required_mods": [ "ftblibrary" ], - "hide_with_nei": true, "requires_op": true } \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/gamemode.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/gamemode.json similarity index 79% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/gamemode.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/gamemode.json index e38856ec..a4ff3e19 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/gamemode.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/gamemode.json @@ -5,6 +5,6 @@ "ftblibrary:textures/icons/toggle_gamemode.png" ], "x": 100, - "click": "command:/ftblibrary gamemode", + "click": ["command:/ftblibrary gamemode"], "requires_op": true } \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/night.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/night.json similarity index 73% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/night.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/night.json index 019f4355..028676ad 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/night.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/night.json @@ -5,8 +5,8 @@ "ftblibrary:textures/icons/toggle_night.png" ], "x": 130, - "click": "command:/ftblibrary night", - "required_server_mods": [ + "click": ["command:/ftblibrary night"], + "required_mods": [ "ftblibrary" ], "requires_op": true diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/rain.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/rain.json similarity index 80% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/rain.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/rain.json index 599ddca7..3175127d 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/rain.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/rain.json @@ -5,6 +5,6 @@ "ftblibrary:textures/icons/toggle_rain.png" ], "x": 80, - "click": "command:/ftblibrary rain", + "click": ["command:/ftblibrary rain"], "requires_op": true } \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index ad511ad3..38d7e7db 100644 --- a/gradle.properties +++ b/gradle.properties @@ -16,7 +16,7 @@ minecraft_version=1.21 # Deps forge_version=49.0.31 -neoforge_version=21.0.109-beta +neoforge_version=21.0.147 neoforge_loader_version=4 fabric_loader_version=0.15.11 fabric_api_version=0.100.1+1.21 diff --git a/neoforge/src/main/java/dev/ftb/mods/ftblibrary/integration/neoforge/REINeoforgePluginStub.java b/neoforge/src/main/java/dev/ftb/mods/ftblibrary/integration/neoforge/REINeoforgePluginStub.java index 28340434..0f76af2e 100644 --- a/neoforge/src/main/java/dev/ftb/mods/ftblibrary/integration/neoforge/REINeoforgePluginStub.java +++ b/neoforge/src/main/java/dev/ftb/mods/ftblibrary/integration/neoforge/REINeoforgePluginStub.java @@ -1,8 +1,8 @@ -//package dev.ftb.mods.ftblibrary.integration.neoforge; -// -//import dev.ftb.mods.ftblibrary.integration.REIIntegration; -//import me.shedaniel.rei.forge.REIPluginCommon; -// -//@REIPluginCommon -//public class REINeoforgePluginStub extends REIIntegration { -//} +package dev.ftb.mods.ftblibrary.integration.neoforge; + +import dev.ftb.mods.ftblibrary.integration.REIIntegration; +import me.shedaniel.rei.forge.REIPluginCommon; + +@REIPluginCommon +public class REINeoforgePluginStub extends REIIntegration { +} From 6db8e7a8893552ffb770a45ae3ec6ee16a700a74 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Fri, 2 Aug 2024 19:44:48 -0500 Subject: [PATCH 05/17] More work moving stuff in grid --- .../mods/ftblibrary/sidebar/GridLocation.java | 10 +- .../ftblibrary/sidebar/SidebarButton.java | 1 - .../sidebar/SidebarButtonManager.java | 225 ++++--------- .../sidebar/SidebarGroupGuiButton.java | 307 ++++++++++-------- .../ftblibrary/sidebar/SidebarGuiButton.java | 19 +- 5 files changed, 250 insertions(+), 312 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java index ac47b318..4e93a21e 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java @@ -5,6 +5,14 @@ public record GridLocation(int x, int y) { public static final GridLocation OUT_OF_BOUNDS = new GridLocation(-1, -1); public boolean isOutOfBounds() { - return x < 0 || y < 0; + return x < 0 || y < 0; + } + + public boolean isLatterInRow(GridLocation other) { + return x == other.x && y <= other.y; + } + + public boolean isLatterInColumn(GridLocation other) { + return x <= other.x && y == other.y; } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java index 9ed8c598..9bf96788 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java @@ -67,7 +67,6 @@ public void clickButton(boolean shift) { } } - //Todo mods public boolean canSee() { return visible.getAsBoolean(); } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index 0db4023a..9aaec3ba 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -6,6 +6,7 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; import dev.ftb.mods.ftblibrary.FTBLibrary; +import dev.ftb.mods.ftblibrary.FTBLibraryClient; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.snbt.config.StringSidebarMapValue; import net.minecraft.resources.ResourceLocation; @@ -20,6 +21,7 @@ import java.util.Collection; import java.util.Comparator; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; @@ -34,6 +36,9 @@ public enum SidebarButtonManager implements ResourceManagerReloadListener { private final Map groups = new HashMap<>(); private final Map buttons = new HashMap<>(); + private final List buttonList = new ArrayList<>(); + + private JsonElement readJson(Resource resource) { try (BufferedReader reader = resource.openAsReader()) { return JsonParser.parseReader(reader); @@ -63,135 +68,16 @@ public void onResourceManagerReload(ResourceManager manager) { } }); - Map> buttonMap = getButtonGroups(); - - int y = 0; - for (Map.Entry> buttonGroupListEntry : buttonMap.entrySet()) { - int x = 0; - buttonGroupListEntry.getValue().sort(Comparator.comparingInt(button -> button.getData().x())); - for (SidebarButton sidebarButton : buttonGroupListEntry.getValue()) { - SidebarButtonData button = sidebarButton.getData(); - StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(sidebarButton.getId().toString()); - if (buttonSettings == null) { - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(sidebarButton.getId().toString(), new StringSidebarMapValue.SideButtonInfo(button.defaultEnabled(), x, y)); - } - x++; - } - if(x != 0) { - y++; - } - } + buttonList.clear(); + for (SidebarButton buttonEntry : getButtons()) { + StringSidebarMapValue.SideButtonInfo buttonSettings = getOrCreateButtonSettings(buttonEntry); + buttonList.add(new SidebarGuiButton(new GridLocation(buttonSettings.xPos(), buttonSettings.yPos()), buttonSettings.enabled(), buttonEntry)); + } FTBLibraryClientConfig.save(); - refreshButtonList(); } - -// var element = readJson(Platform.getConfigFolder().resolve("sidebar_buttons.json").toFile()); -// JsonObject sidebarButtonConfig; -// -// if (element.isJsonObject()) { -// sidebarButtonConfig = element.getAsJsonObject(); -// } else { -// sidebarButtonConfig = new JsonObject(); -// } -// -// Map groupMap = new HashMap<>(); -// -// for (var domain : manager.getNamespaces()) { -// try { -// // TODO: Use an alternative way to register sidebar groups because jsons are a bit messy -// for (var resource : manager.getResourceStack(ResourceLocation.fromNamespaceAndPath(domain, "sidebar_button_groups.json"))) { -// var json = readJson(resource); -// -// for (var entry : json.getAsJsonObject().entrySet()) { -// if (entry.getValue().isJsonObject()) { -// var groupJson = entry.getValue().getAsJsonObject(); -// var y = 0; -// var pinned = true; -// -// if (groupJson.has("y")) { -// y = groupJson.get("y").getAsInt(); -// } -// -// if(groupJson.has("pinned")) { -// pinned = groupJson.get("pinned").getAsBoolean(); -// } -// -// var group = new SidebarButtonGroup(ResourceLocation.fromNamespaceAndPath(domain, entry.getKey()), y, pinned); -// groupMap.put(group.getId(), group); -// } -// } -// } -// } catch (Exception ex) { -// ex.printStackTrace(); -// } -// } -// -// for (String domain : manager.getNamespaces()) { -// try { -// for (Resource resource : manager.getResourceStack(ResourceLocation.fromNamespaceAndPath(domain, "sidebar_buttons.json"))) { -// JsonElement json = readJson(resource); -// -// if (json.isJsonObject()) { -// for (var entry : json.getAsJsonObject().entrySet()) { -// if (entry.getValue().isJsonObject()) { -// var buttonJson = entry.getValue().getAsJsonObject(); -// -// if (!buttonJson.has("group")) { -// continue; -// } -// -// if (/*!FTBLibConfig.debugging.dev_sidebar_buttons && */buttonJson.has("dev_only") && buttonJson.get("dev_only").getAsBoolean()) { -// continue; -// } -// -// var group = groupMap.get(ResourceLocation.parse(buttonJson.get("group").getAsString())); -// -// if (group == null) { -// continue; -// } -// -// var button = new SidebarButton(ResourceLocation.fromNamespaceAndPath(domain, entry.getKey()), group, buttonJson); -// -// group.getButtons().add(button); -// -// if (sidebarButtonConfig.has(button.getId().getNamespace())) { -// var e = sidebarButtonConfig.get(button.getId().getNamespace()); -// -// if (e.isJsonObject() && e.getAsJsonObject().has(button.getId().getPath())) { -// button.setConfig(e.getAsJsonObject().get(button.getId().getPath()).getAsBoolean()); -// } -// } else if (sidebarButtonConfig.has(button.getId().toString())) { -// button.setConfig(sidebarButtonConfig.get(button.getId().toString()).getAsBoolean()); -// } -// } -// } -// } -// } -// } catch (Exception ex) { -// ex.printStackTrace(); -// } -// } -// -// for (var group : groupMap.values()) { -// if (!group.getButtons().isEmpty()) { -// group.getButtons().sort(null); -// groups.add(group); -// } -// } -// -// groups.sort(null); -// -// for (var group : groups) { -// for (var button : group.getButtons()) { -// SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(button)); -// } -// } -// -// saveConfig(); - private void loadResources(ResourceManager manager, String path, Codec codec, BiConsumer consumer) { Map resourceLocationResourceMap = manager.listResources(path, name -> name.getPath().endsWith(".json")); for (Map.Entry resource : resourceLocationResourceMap.entrySet()) { @@ -210,61 +96,58 @@ private void loadResources(ResourceManager manager, String path, Codec co } - private final List buttonList = new ArrayList<>(); + private StringSidebarMapValue.SideButtonInfo getOrCreateButtonSettings(SidebarButton button) { + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getId().toString()); + if(buttonSettings == null) { + buttonSettings = new StringSidebarMapValue.SideButtonInfo(true, button.getData().x(), groups.get(button.getData().group()).y()); + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getId().toString(), buttonSettings); + FTBLibraryClientConfig.save(); + } + return buttonSettings; + } - public void refreshButtonList() { - buttonList.clear(); - for (SidebarButton buttonEntry : getButtons()) { -// if(buttonEntry.canSee()) { - ResourceLocation id = buttonEntry.getId(); - SidebarButtonData button = buttonEntry.getData(); - - StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(id.toString()); - if(buttonSettings != null) { - SidebarGuiButton e = new SidebarGuiButton(new GridLocation(buttonSettings.xPos(), buttonSettings.yPos()), buttonSettings.enabled(), buttonEntry); - buttonList.add(e); - }else { - //Todo this should not be possable - LOGGER.error("Button {} not found in config", id); - } -// } + private boolean isRegistered(ResourceLocation id) { + return buttons.values().stream().anyMatch(button -> button.getId().equals(id)); + } + + public void saveConfigFromButtonList() { + + Map> buttonMap = new HashMap<>(); + for (SidebarGuiButton button : getButtonList()) { + int y = button.isEnabled() ? button.getGirdLocation().y() : -1; + buttonMap.computeIfAbsent(y, k -> new LinkedList<>()).add(button); } - for (Map.Entry stringSideButtonInfoEntry : FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().entrySet()) { - if(!isRegistered(ResourceLocation.parse(stringSideButtonInfoEntry.getKey()))) { - continue; + int y = 0; + for (Map.Entry> integerListEntry : Utils.sortMapByKey(buttonMap).entrySet()) { + if(integerListEntry.getKey() == -1) { + for (SidebarGuiButton button : integerListEntry.getValue()) { + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(false, -1, -1)); + } } - StringSidebarMapValue.SideButtonInfo buttonSettings = stringSideButtonInfoEntry.getValue(); - if(buttonSettings != null && buttonSettings.enabled()) { - for (SidebarGuiButton button : buttonList) { - if(button.getSidebarButton().canSee() && button.isEnabled()) { - if(!button.getSidebarButton().getId().toString().equals(stringSideButtonInfoEntry.getKey())) { - if(button.getGridY() == buttonSettings.yPos() && button.getGridX() == buttonSettings.xPos()) { - button.setGrid(button.getGridX() + 1, button.getGridY()); - } - } - - } + int x = 0; + integerListEntry.getValue() + .sort(Comparator.comparingInt((SidebarGuiButton button) -> button.getGirdLocation().x())); + List value = integerListEntry.getValue(); + for (SidebarGuiButton sidebarButton : value) { + if(sidebarButton.isEnabled()) { + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(sidebarButton.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(sidebarButton.isEnabled(), x, y)); + x++; } } + if(x != 0) { + y++; + } } - FTBLibraryClientConfig.save(); - } - private boolean isRegistered(ResourceLocation id) { - return buttons.values().stream().anyMatch(button -> button.getId().equals(id)); - } - - public void saveConfigFromButtonList() { for (SidebarGuiButton button : buttonList) { StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getSidebarButton().getId().toString()); if(buttonSettings != null) { - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(button.isEnabled(), button.getGridX(), button.getGridY())); + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(button.isEnabled(), button.getGirdLocation().x(), button.getGirdLocation().y())); } } FTBLibraryClientConfig.save(); - refreshButtonList(); } // @@ -272,12 +155,18 @@ public List getButtonList() { return buttonList; } - public List getEnabledButtonList() { - return buttonList.stream().filter(SidebarGuiButton::isEnabled).collect(Collectors.toList()); + public List getEnabledButtonList(boolean all) { + return buttonList.stream() + .filter(SidebarGuiButton::isEnabled) + .filter(button -> all || button.getSidebarButton().canSee()) + .toList(); } - public List getDisabledButtonList() { - return buttonList.stream().filter(button -> !button.isEnabled()).collect(Collectors.toList()); + public List getDisabledButtonList(boolean all) { + return buttonList.stream() + .filter(button -> !button.isEnabled()) + .filter(button -> all || button.getSidebarButton().canSee()) + .collect(Collectors.toList()); } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index 50046195..dcc6a506 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -1,8 +1,11 @@ package dev.ftb.mods.ftblibrary.sidebar; import com.mojang.blaze3d.systems.RenderSystem; +import dev.ftb.mods.ftblibrary.FTBLibrary; +import dev.ftb.mods.ftblibrary.FTBLibraryClient; import dev.ftb.mods.ftblibrary.icon.Color4I; import dev.ftb.mods.ftblibrary.icon.Icons; +import dev.ftb.mods.ftblibrary.ui.Button; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; @@ -16,8 +19,10 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.TreeMap; public class SidebarGroupGuiButton extends AbstractButton { public static Rect2i lastDrawnArea = new Rect2i(0, 0, 0, 0); @@ -40,6 +45,8 @@ public class SidebarGroupGuiButton extends AbstractButton { private boolean addBoxOpen; + private final Map realLocationMap = new HashMap<>(); + public SidebarGroupGuiButton() { super(0, 0, 0, 0, Component.empty()); @@ -49,7 +56,11 @@ public SidebarGroupGuiButton() { @Override public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { - graphics.pose().translate(0,0,5000); + + addBoxOpen = true; + + graphics.pose().pushPose(); + graphics.pose().translate(0, 0, 5000); currentMouseX = mx; currentMouseY = my; @@ -58,35 +69,35 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick GridLocation gridLocation = getGridLocation(); - List enabledButtonList = SidebarButtonManager.INSTANCE.getEnabledButtonList(); - for (SidebarGuiButton button : enabledButtonList) { - if(button.getGridX() == gridLocation.x() && button.getGridY() == gridLocation.y()) { + + + for (Map.Entry entry : realLocationMap.entrySet()) { + SidebarGuiButton button = entry.getKey(); + if (entry.getValue().equals(gridLocation)) { mouseOver = button; } } - maxGridWith = enabledButtonList - .stream() - .max(Comparator.comparingInt(SidebarGuiButton::getGridX)) - .map(SidebarGuiButton::getGridX) - .orElse(1) + 2; - maxGridHeight = enabledButtonList - .stream() - .max(Comparator.comparingInt(SidebarGuiButton::getGridY)) - .map(SidebarGuiButton::getGridY) - .orElse(1) + 2; - + maxGridWith = 1; + maxGridHeight = 1; + for (Map.Entry value : realLocationMap.entrySet()) { + GridLocation location = value.getValue(); + maxGridWith = Math.max(maxGridWith, location.x() + 1); + maxGridHeight = Math.max(maxGridHeight, location.y() + 1); + } if (isEditMode) { + maxGridWith += 1; + maxGridHeight += 1; - drawHoveredGrid(graphics, 0, 0, maxGridWith, maxGridHeight, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my); + drawHoveredGrid(graphics, 0, 0, maxGridWith, maxGridHeight, BUTTON_SPACING, Color4I.GRAY.withAlpha(70), Color4I.BLACK.withAlpha(90), mx, my); - List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(); - if(!disabledButtonList.isEmpty()) { - drawGrid(graphics, ( maxGridWith + 1) * BUTTON_SPACING, 0, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode); + if (!disabledButtonList.isEmpty()) { + drawGrid(graphics, (maxGridWith + 1) * BUTTON_SPACING, 0, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); Icons.ADD.draw(graphics, (maxGridWith + 1) * BUTTON_SPACING + 1, 1, 16, 16); - if(addBoxOpen) { + if (addBoxOpen) { int maxWidth = 0; @@ -100,22 +111,21 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick // drawHoveredGrid(graphics, ( maxGridWith + 2) * BUTTON_SPACING, 0, disabledButtonList.size(), 1, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my); // Color4I.GRAY.draw(graphics, ( maxGridWith + 1) * BUTTON_SPACING, BUTTON_SPACING, 1 + BUTTON_SPACING * 5, BUTTON_SPACING * disabledButtonList.size()); //draw black border - drawGrid(graphics, ( maxGridWith + 1) * BUTTON_SPACING, BUTTON_SPACING, 1, disabledButtonList.size(), maxWidth + BUTTON_SPACING + 4, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); - + drawGrid(graphics, (maxGridWith + 1) * BUTTON_SPACING, BUTTON_SPACING, 1, disabledButtonList.size(), maxWidth + BUTTON_SPACING + 4, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); for (int i = 0; i < disabledButtonList.size(); i++) { SidebarGuiButton button = disabledButtonList.get(i); - if(selectedButton != null && selectedButton == button) { + if (selectedButton != null && selectedButton == button) { continue; } - button.x = ( maxGridWith + 1) * BUTTON_SPACING; + button.x = (maxGridWith + 1) * BUTTON_SPACING; button.y = BUTTON_SPACING + BUTTON_SPACING * i; GuiHelper.setupDrawing(); button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); graphics.drawString(Minecraft.getInstance().font, I18n.get(button.getSidebarButton().getLangKey()), button.x + 20, button.y + 4, 0xFFFFFFFF); - if(mx >= button.x && mx < button.x + 16 && my >= button.y && my < button.y + 16) { + if (mx >= button.x && mx < button.x + 16 && my >= button.y && my < button.y + 16) { mouseOver = button; } } @@ -128,79 +138,79 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick var font = Minecraft.getInstance().font; - //Todo better way? - List sortedButtons = new ArrayList<>(enabledButtonList); - if(selectedButton != null) { - sortedButtons.remove(selectedButton); - sortedButtons.addLast(selectedButton); - } - - for (SidebarGuiButton button : sortedButtons) { - if (isEditMode && button == selectedButton) { - button.x = mx - mouseOffsetX; - button.y = my - mouseOffsetY; - }else { - button.x = 1 + button.getGridX() * BUTTON_SPACING; - button.y = 1 + button.getGridY() * BUTTON_SPACING; + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { + GridLocation realGridLocation = realLocationMap.get(button); + if(button.getSidebarButton().getId().toString().equals("ftblibrary:test")) { +// continue; } - GuiHelper.setupDrawing(); - button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); - - if(isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList().size() > 1) { - //if mouse if over cancle - if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { - Icons.CANCEL.draw(graphics, button.x + 12, button.y, 6, 6); - }else { - Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); + if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { + graphics.pose().pushPose(); + if (isEditMode && button == selectedButton) { + graphics.pose().translate(0, 0, 5000); + button.x = mx - mouseOffsetX; + button.y = my - mouseOffsetY; + } else { + if(realGridLocation == null) { + continue; + } + button.x = 1 + realGridLocation.x() * BUTTON_SPACING; + button.y = 1 + realGridLocation.y() * BUTTON_SPACING; + } + GuiHelper.setupDrawing(); + button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); + + if (isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1) { + //if mouse if over cancle + if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { + Icons.CANCEL.draw(graphics, button.x + 11, button.y - 1, 6, 6); + } else { + Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); + } } - } - if (button == mouseOver) { - Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); - } + if (button == mouseOver) { + Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); + } - if (button.getSidebarButton().getCustomTextHandler() != null) { - var text = button.getSidebarButton().getCustomTextHandler().get(); + if (button.getSidebarButton().getCustomTextHandler() != null) { + var text = button.getSidebarButton().getCustomTextHandler().get(); - if (!text.isEmpty()) { - var nw = font.width(text); - var width = 16; - Color4I.LIGHT_RED.draw(graphics, button.x + width - nw, button.y - 1, nw + 1, 9); - graphics.drawString(font, text, button.x + width - nw + 1, button.y, 0xFFFFFFFF); - RenderSystem.setShaderColor(1F, 1F, 1F, 1F); + if (!text.isEmpty()) { + var nw = font.width(text); + var width = 16; + Color4I.LIGHT_RED.draw(graphics, button.x + width - nw, button.y - 1, nw + 1, 9); + graphics.drawString(font, text, button.x + width - nw + 1, button.y, 0xFFFFFFFF); + RenderSystem.setShaderColor(1F, 1F, 1F, 1F); + } } + graphics.pose().popPose(); } - } + if(!isEditMode && mouseOver == button) { + GuiHelper.setupDrawing(); + var mx1 = mx + 10; + var my1 = Math.max(3, my - 9); - if (!isEditMode && mouseOver != null) { - GuiHelper.setupDrawing(); - var mx1 = mx + 10; - var my1 = Math.max(3, my - 9); + List list = new ArrayList<>(); + list.add(I18n.get(mouseOver.getSidebarButton().getLangKey())); - List list = new ArrayList<>(); - list.add(I18n.get(mouseOver.getSidebarButton().getLangKey())); - - if (mouseOver.getSidebarButton().getTooltipHandler() != null) { - mouseOver.getSidebarButton().getTooltipHandler().accept(list); - } + if (mouseOver.getSidebarButton().getTooltipHandler() != null) { + mouseOver.getSidebarButton().getTooltipHandler().accept(list); + } - var tw = 0; + var tw = 0; - for (var s : list) { - tw = Math.max(tw, font.width(s)); - } + for (String s : list) { + tw = Math.max(tw, font.width(s)); + } - Color4I.DARK_GRAY.draw(graphics, mx1 - 3, my1 - 2, tw + 6, 2 + list.size() * 10); + Color4I.DARK_GRAY.draw(graphics, mx1 - 3, my1 - 2, tw + 6, 2 + list.size() * 10); - for (var i = 0; i < list.size(); i++) { - graphics.drawString(font, list.get(i), mx1, my1 + i * 10, 0xFFFFFFFF); + for (var i = 0; i < list.size(); i++) { + graphics.drawString(font, list.get(i), mx1, my1 + i * 10, 0xFFFFFFFF); + } } } -// GuiHelper.setupDrawing(); - //zLevel = 0F; - - graphics.pose().popPose(); } @@ -214,27 +224,37 @@ public void onRelease(double d, double e) { } else { if (selectedButton != null) { GridLocation gLocation = getGridLocation(); - //Checks if the icon is placed in the same location picked up from, if so do nothing - if (!gLocation.isOutOfBounds()) - if (!gLocation.equals(selectedLocation)) { - //Checks for any icon at the place location and to left of that and moves them over one - List buttonList = SidebarButtonManager.INSTANCE.getButtonList(); + if (!gLocation.isOutOfBounds()) { + //Checks if the icon is placed in the same location picked up from, if so do nothing + if (!gLocation.equals(selectedLocation)) { + int x = gLocation.y() != selectedButton.getGirdLocation().y() ? selectedButton.getGirdLocation().x() : -1; + selectedButton.setGridLocation(gLocation.x(), gLocation.y()); + //Checks for any icon at the place location and to left of that and moves them over one + List buttonList = SidebarButtonManager.INSTANCE.getButtonList(); for (SidebarGuiButton button : buttonList) { - if (!selectedButton.equals(button)) { - if (button.getGridY() == gLocation.y() && button.getGridX() >= gLocation.x()) { - button.setGrid(button.getGridX() + 1, button.getGridY()); - } - } + GridLocation realGridLocation = realLocationMap.get(button); + if(realGridLocation != null) { + if (!selectedButton.getSidebarButton().getId().equals(button.getSidebarButton().getId())) { + if (gLocation.isLatterInColumn(realGridLocation)) { + int moveAmount = x == 0 && realGridLocation.x() == 1 ? -1 : 1; + button.setGridLocation(realGridLocation.x() + moveAmount, realGridLocation.y()); + } + } + } } - selectedButton.setGrid(gLocation.x(), gLocation.y()); +// selectedButton.setGridLocation(gLocation.x(), gLocation.y()); if (!selectedButton.isEnabled()) { selectedButton.setEnabled(true); - SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); - if (SidebarButtonManager.INSTANCE.getDisabledButtonList().isEmpty()) { + if (SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).isEmpty()) { addBoxOpen = false; } } - } + }else { + FTBLibrary.LOGGER.info("Same location"); + } + }else { + FTBLibrary.LOGGER.info("Out of bounds"); + } selectedButton = null; ensureGridAlignment(); @@ -243,32 +263,49 @@ public void onRelease(double d, double e) { } private void ensureGridAlignment() { - //Makes sure everything on the grid and far left and top that it can be - Map> gridMap = new HashMap<>(); - for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getEnabledButtonList()) { - if(!gridMap.containsKey(button.getGridY())) { - gridMap.put(button.getGridY(), new ArrayList<>()); + + List enabledButtonList = SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode); + + // Create a TreeMap to sort buttons by their y-coordinate + Map> buttonMap = new TreeMap<>(); + + // Populate the TreeMap + for (SidebarGuiButton button : enabledButtonList) { + if(button.isEnabled()) { + buttonMap.computeIfAbsent(button.getGirdLocation().y(), k -> new LinkedList<>()).add(button); } - gridMap.get(button.getGridY()).add(button); } + + // Clear the realLocationMap + realLocationMap.clear(); + + // Iterate through the sorted entries and update the realLocationMap int y = 0; - for (Map.Entry> entry : gridMap.entrySet()) { - List sorted = entry.getValue().stream().sorted(Comparator.comparingInt(SidebarGuiButton::getGridX)).toList(); - for (int i = 0; i < sorted.size(); i++) { - sorted.get(i).setGrid(i, y); + for (Map.Entry> entry : buttonMap.entrySet()) { + entry.getValue().sort(Comparator.comparingInt(b -> b.getGirdLocation().x())); + int x = 0; + for (SidebarGuiButton button : entry.getValue()) { + realLocationMap.put(button, new GridLocation(x, y)); + x++; + } + if (x != 0) { + y++; } - y++; } + SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); + updateWidgetSize(); + + + - SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); - updateWidgetSize(); } + //Todo fix numbers in this private void updateWidgetSize() { setX(0); setY(0); @@ -279,12 +316,12 @@ private void updateWidgetSize() { // https://github.com/mezz/JustEnoughItems/issues/2938 var maxGirdX = 1; var maxGirdY = 1; - for (SidebarGuiButton b : SidebarButtonManager.INSTANCE.getEnabledButtonList()) { - maxGirdX = Math.max(maxGirdX, b.getGridX() + 1); - maxGirdY = Math.max(maxGirdY, b.getGridY() + 1); + for (SidebarGuiButton b : SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode)) { + maxGirdX = Math.max(maxGirdX, b.getGirdLocation().x() + 1); + maxGirdY = Math.max(maxGirdY, b.getGirdLocation().y() + 1); } - int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList().size(); + int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).size(); if(isEditMode && addBoxOpen) { maxGirdX += 4; int size = disabledList; @@ -333,20 +370,17 @@ public void onPress() { } if(mouseOver != null) { + Minecraft.getInstance().player.sendSystemMessage(Component.literal(mouseOver.getGirdLocation().x() + " " + mouseOver.getGirdLocation().y())); isMouseDown = true; mouseOffsetX = currentMouseX - mouseOver.x; mouseOffsetY = currentMouseY - mouseOver.y; if(isEditMode) { - - - //Check if clicked the remove button - if(SidebarButtonManager.INSTANCE.getEnabledButtonList().size() > 1 && currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4) { + if(SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1 && currentMouseX >= mouseOver.x + 11 && currentMouseY <= mouseOver.y + 3) { mouseOver.setEnabled(false); mouseOver = null; - SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); ensureGridAlignment(); return; } @@ -355,11 +389,11 @@ public void onPress() { selectedButton = mouseOver; - if(!selectedButton.isEnabled()) { - selectedLocation = new GridLocation(selectedButton.getGridX(), selectedButton.getGridY()); - }else { - selectedLocation = GridLocation.OUT_OF_BOUNDS; - } + selectedLocation = realLocationMap.get(selectedButton); +// if(!selectedButton.isEnabled()) { +// }else { +// selectedLocation = GridLocation.OUT_OF_BOUNDS; +// } } } } @@ -373,24 +407,36 @@ public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) @Override protected boolean isValidClickButton(int i) { //Todo don't just allow edit mode try and be more specific - return super.isValidClickButton(i) && (isEditMode || !getGridLocation().isOutOfBounds()); +// if ( super.isValidClickButton(i)) { +// if(isEditMode) { +// //Todo let be nice and only play click sounds allow click at the right times "clean" stuff lol +// return true; +// }else { +// return mouseOver != null; +// } +// } +// return false; + return true; } public void tick() { if(isMouseDown) { mouseDownTime++; - if(mouseDownTime > 20) { + if(!isEditMode && mouseDownTime > 20) { isEditMode = true; mouseOver = null; + ensureGridAlignment(); updateWidgetSize(); } + }else { + mouseDownTime = 0; } } private static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacingWidth, int spacingHeight, Color4I backgroundColor, Color4I gridColor) { backgroundColor.draw(graphics, x, y, width * spacingWidth, height * spacingHeight); for (var i = 0; i < width + 1; i++) { - gridColor.draw(graphics, x + i * spacingWidth, y, 1, height * spacingHeight); + gridColor.draw(graphics, x + i * spacingWidth, y, 1, height * spacingHeight + 1); } for (var i = 0; i < height + 1; i++) { gridColor.draw(graphics, x, y + i * spacingHeight, width * spacingWidth, 1); @@ -399,19 +445,12 @@ private static void drawGrid(GuiGraphics graphics, int x, int y, int width, int public static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor) { drawGrid(graphics, x, y, width, height, spacing, spacing, backgroundColor, gridColor); -// backgroundColor.draw(graphics, x, y, width * spacing, height * spacing); -// for (var i = 0; i < width + 1; i++) { -// gridColor.draw(graphics, x + i * spacing, y, 1, height * spacing); -// } -// for (var i = 0; i < height + 1; i++) { -// gridColor.draw(graphics, x, y + i * spacing, width * spacing, 1); -// } } public static void drawHoveredGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor, int mx, int my) { drawGrid(graphics, x, y, width, height, spacing, backgroundColor, gridColor); if (mx >= x && my >= y && mx < x + width * spacing && my < y + height * spacing) { - Color4I.WHITE.draw(graphics, (mx / spacing) * spacing + 1, (my / spacing) * spacing + 1, spacing - 1, spacing - 1); + Color4I.WHITE.withAlpha(127).draw(graphics, (mx / spacing) * spacing + 1, (my / spacing) * spacing + 1, spacing - 1, spacing - 1); } } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java index be899bff..f36df8fa 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java @@ -4,13 +4,14 @@ public class SidebarGuiButton { private final SidebarButton sidebarButton; public int x, y; - private GridLocation gridLocation; + private int gridX, gridY; private boolean enabled; public SidebarGuiButton(GridLocation girdLocation, boolean enabled, SidebarButton sidebarButton) { x = 0; y = 0; - this.gridLocation = girdLocation; + gridX = girdLocation.x(); + gridY = girdLocation.y(); this.sidebarButton = sidebarButton; this.enabled = enabled; } @@ -27,16 +28,18 @@ public SidebarButton getSidebarButton() { return sidebarButton; } - public int getGridX() { - return enabled ? gridLocation.x() : -1; + public GridLocation getGirdLocation() { + return new GridLocation(gridX, gridY); } - public int getGridY() { - return enabled ? gridLocation.y() : -1; + public void setGridLocation(GridLocation gridLocation) { + this.gridX = gridLocation.x(); + this.gridY = gridLocation.y(); } - public void setGrid(int gridX, int gridY) { - this.gridLocation = new GridLocation(gridX, gridY); + public void setGridLocation(int x, int y) { + this.gridX = x; + this.gridY = y; } } From 46b8406666c64842a47f680faf384e06e1368758 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Sat, 3 Aug 2024 09:42:03 -0500 Subject: [PATCH 06/17] Fix Grid Code, and more code comments --- .../sidebar/SidebarButtonManager.java | 2 + .../sidebar/SidebarGroupGuiButton.java | 125 +++++------------- 2 files changed, 37 insertions(+), 90 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index 9aaec3ba..b4ed75ba 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -122,6 +122,7 @@ public void saveConfigFromButtonList() { for (Map.Entry> integerListEntry : Utils.sortMapByKey(buttonMap).entrySet()) { if(integerListEntry.getKey() == -1) { for (SidebarGuiButton button : integerListEntry.getValue()) { + button.setGridLocation(-1, -1); FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(false, -1, -1)); } } @@ -131,6 +132,7 @@ public void saveConfigFromButtonList() { List value = integerListEntry.getValue(); for (SidebarGuiButton sidebarButton : value) { if(sidebarButton.isEnabled()) { + sidebarButton.setGridLocation(x, y); FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(sidebarButton.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(sidebarButton.isEnabled(), x, y)); x++; } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index dcc6a506..508a74ee 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -23,6 +23,7 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import java.util.stream.Collectors; public class SidebarGroupGuiButton extends AbstractButton { public static Rect2i lastDrawnArea = new Rect2i(0, 0, 0, 0); @@ -56,21 +57,15 @@ public SidebarGroupGuiButton() { @Override public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { - - addBoxOpen = true; - graphics.pose().pushPose(); graphics.pose().translate(0, 0, 5000); + //Todo always? + addBoxOpen = true; currentMouseX = mx; currentMouseY = my; - mouseOver = null; - GridLocation gridLocation = getGridLocation(); - - - for (Map.Entry entry : realLocationMap.entrySet()) { SidebarGuiButton button = entry.getKey(); if (entry.getValue().equals(gridLocation)) { @@ -98,8 +93,6 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick Icons.ADD.draw(graphics, (maxGridWith + 1) * BUTTON_SPACING + 1, 1, 16, 16); if (addBoxOpen) { - - int maxWidth = 0; for (SidebarGuiButton button : disabledButtonList) { String s = I18n.get(button.getSidebarButton().getLangKey()); @@ -107,13 +100,8 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick maxWidth = Math.max(maxWidth, width); } - -// drawHoveredGrid(graphics, ( maxGridWith + 2) * BUTTON_SPACING, 0, disabledButtonList.size(), 1, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my); -// Color4I.GRAY.draw(graphics, ( maxGridWith + 1) * BUTTON_SPACING, BUTTON_SPACING, 1 + BUTTON_SPACING * 5, BUTTON_SPACING * disabledButtonList.size()); - //draw black border drawGrid(graphics, (maxGridWith + 1) * BUTTON_SPACING, BUTTON_SPACING, 1, disabledButtonList.size(), maxWidth + BUTTON_SPACING + 4, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); - for (int i = 0; i < disabledButtonList.size(); i++) { SidebarGuiButton button = disabledButtonList.get(i); if (selectedButton != null && selectedButton == button) { @@ -140,9 +128,6 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { GridLocation realGridLocation = realLocationMap.get(button); - if(button.getSidebarButton().getId().toString().equals("ftblibrary:test")) { -// continue; - } if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { graphics.pose().pushPose(); if (isEditMode && button == selectedButton) { @@ -160,7 +145,6 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); if (isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1) { - //if mouse if over cancle if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { Icons.CANCEL.draw(graphics, button.x + 11, button.y - 1, 6, 6); } else { @@ -219,67 +203,57 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick public void onRelease(double d, double e) { super.onRelease(d, e); isMouseDown = false; + //Normal click action if (!isEditMode && mouseOver != null) { mouseOver.getSidebarButton().clickButton(Screen.hasShiftDown()); } else { if (selectedButton != null) { GridLocation gLocation = getGridLocation(); + //Make sure the placement is in grid if (!gLocation.isOutOfBounds()) { //Checks if the icon is placed in the same location picked up from, if so do nothing if (!gLocation.equals(selectedLocation)) { - int x = gLocation.y() != selectedButton.getGirdLocation().y() ? selectedButton.getGirdLocation().x() : -1; + //checks if moved from the first spot, so we can move other icons over but only as the same row + boolean isFrom0XTo1X = selectedLocation.y() == gLocation.y() && selectedLocation.x() == 0 && gLocation.x() == 1; selectedButton.setGridLocation(gLocation.x(), gLocation.y()); - //Checks for any icon at the place location and to left of that and moves them over one + //Checks for icon that needs to be moved over List buttonList = SidebarButtonManager.INSTANCE.getButtonList(); for (SidebarGuiButton button : buttonList) { GridLocation realGridLocation = realLocationMap.get(button); if(realGridLocation != null) { if (!selectedButton.getSidebarButton().getId().equals(button.getSidebarButton().getId())) { if (gLocation.isLatterInColumn(realGridLocation)) { - int moveAmount = x == 0 && realGridLocation.x() == 1 ? -1 : 1; + int moveAmount = isFrom0XTo1X && realGridLocation.x() == 1 ? -1 : 1; button.setGridLocation(realGridLocation.x() + moveAmount, realGridLocation.y()); } } } } -// selectedButton.setGridLocation(gLocation.x(), gLocation.y()); + //If the icon was disabled enable it if (!selectedButton.isEnabled()) { selectedButton.setEnabled(true); + //Todo do we want this if (SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).isEmpty()) { addBoxOpen = false; } } - }else { - FTBLibrary.LOGGER.info("Same location"); - } - }else { - FTBLibrary.LOGGER.info("Out of bounds"); - } + } + } selectedButton = null; ensureGridAlignment(); - } } } private void ensureGridAlignment() { - List enabledButtonList = SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode); + Map> buttonMap = enabledButtonList + .stream() + .filter(SidebarGuiButton::isEnabled) + .collect(Collectors.groupingBy(button -> button.getGirdLocation().y(), TreeMap::new, Collectors.toCollection(LinkedList::new))); - // Create a TreeMap to sort buttons by their y-coordinate - Map> buttonMap = new TreeMap<>(); - - // Populate the TreeMap - for (SidebarGuiButton button : enabledButtonList) { - if(button.isEnabled()) { - buttonMap.computeIfAbsent(button.getGirdLocation().y(), k -> new LinkedList<>()).add(button); - } - } - - // Clear the realLocationMap - realLocationMap.clear(); + realLocationMap.clear(); - // Iterate through the sorted entries and update the realLocationMap int y = 0; for (Map.Entry> entry : buttonMap.entrySet()) { entry.getValue().sort(Comparator.comparingInt(b -> b.getGirdLocation().x())); @@ -296,19 +270,9 @@ private void ensureGridAlignment() { SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); updateWidgetSize(); - - - - - - - } - //Todo fix numbers in this private void updateWidgetSize() { - setX(0); - setY(0); // Important: JEI doesn't like negative X/Y values and will silently clamp them, // leading it to think the values have changed every frame, and do unnecessary updating // of its GUI areas, including resetting the filter textfield's selection @@ -324,8 +288,7 @@ private void updateWidgetSize() { int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).size(); if(isEditMode && addBoxOpen) { maxGirdX += 4; - int size = disabledList; - maxGirdY = Math.max(maxGirdY, size); + maxGirdY = Math.max(maxGirdY, disabledList); } if(isEditMode) { maxGirdX += 3; @@ -336,6 +299,10 @@ private void updateWidgetSize() { width = (maxGirdX) * BUTTON_SPACING; height = (maxGirdY) * BUTTON_SPACING; + + setX(0); + setY(0); + lastDrawnArea = new Rect2i(getX(), getY(), width, height); } @@ -343,7 +310,7 @@ private GridLocation getGridLocation() { int gridX = (currentMouseX - 1) / BUTTON_SPACING; int gridY = (currentMouseY - 1) / BUTTON_SPACING; if(gridX >= maxGridWith || gridY >= maxGridHeight) { - return new GridLocation(- 1, - 1); + return GridLocation.OUT_OF_BOUNDS; } return new GridLocation(gridX, gridY); } @@ -351,33 +318,19 @@ private GridLocation getGridLocation() { @Override public void onPress() { if(isEditMode) { - //if clicked the bottom right grid spot - //check if mouse clicked in same spot as the plus button - // drawGrid(graphics, ( maxGridWith + 1) * BUTTON_SPACING, 0, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); if(currentMouseX >= ( maxGridWith + 1) * BUTTON_SPACING && currentMouseY <= BUTTON_SPACING) { addBoxOpen = !addBoxOpen; updateWidgetSize(); return; } - - -// GridLocation gridLocation = getGridLocation(currentMouseX, currentMouseY); -// if(gridLocation.x() == maxGridWith - 1 && gridLocation.y() == maxGridHeight - 1) { -// addBoxOpen = !addBoxOpen; -// updateWidgetSize(); -// return; -// } } if(mouseOver != null) { - Minecraft.getInstance().player.sendSystemMessage(Component.literal(mouseOver.getGirdLocation().x() + " " + mouseOver.getGirdLocation().y())); isMouseDown = true; mouseOffsetX = currentMouseX - mouseOver.x; mouseOffsetY = currentMouseY - mouseOver.y; if(isEditMode) { - - //Check if clicked the remove button if(SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1 && currentMouseX >= mouseOver.x + 11 && currentMouseY <= mouseOver.y + 3) { mouseOver.setEnabled(false); mouseOver = null; @@ -385,15 +338,9 @@ public void onPress() { return; } - - - selectedButton = mouseOver; - selectedLocation = realLocationMap.get(selectedButton); -// if(!selectedButton.isEnabled()) { -// }else { -// selectedLocation = GridLocation.OUT_OF_BOUNDS; -// } + GridLocation realGridLocation = realLocationMap.get(selectedButton); + selectedLocation = realGridLocation == null ? selectedButton.getGirdLocation() : realGridLocation; } } } @@ -404,19 +351,17 @@ public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) } + //Custom handling so our button click locations are where a buttons are not just a box @Override protected boolean isValidClickButton(int i) { - //Todo don't just allow edit mode try and be more specific -// if ( super.isValidClickButton(i)) { -// if(isEditMode) { -// //Todo let be nice and only play click sounds allow click at the right times "clean" stuff lol -// return true; -// }else { -// return mouseOver != null; -// } -// } -// return false; - return true; + if (super.isValidClickButton(i)) { + if (isEditMode) { + return selectedButton != null || mouseOver != null; + } else { + return mouseOver != null; + } + } + return false; } public void tick() { From e7f6728da21a0be64befd0f7d16cc7edf33bb0f6 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Mon, 5 Aug 2024 16:47:17 -0500 Subject: [PATCH 07/17] Start on work on moving grid --- .../config/FTBLibraryClientConfig.java | 28 ++ .../integration/REIIntegration.java | 5 +- .../ftblibrary/sidebar/SidebarButton.java | 33 ++ .../sidebar/SidebarButtonCreatedEvent.java | 8 +- .../sidebar/SidebarGroupGuiButton.java | 376 +++++++++++------- 5 files changed, 307 insertions(+), 143 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java b/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java index 0ecfead1..64a71af5 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java @@ -27,6 +27,9 @@ public interface FTBLibraryClientConfig { .comment("Colors recently selected in the color selector"); SNBTConfig SIDEBAR = CONFIG.addGroup("sidebar"); + EnumValue POSITION = SIDEBAR.addEnum("position", SidebarPosition.NAME_MAP, SidebarPosition.TOP_LEFT) + .comment("Position of the sidebar"); + StringSidebarMapValue SIDEBAR_BUTTONS = SIDEBAR.add(new StringSidebarMapValue(SIDEBAR, "buttons", new HashMap<>())); static void load() { @@ -47,4 +50,29 @@ static ConfigGroup getConfigGroup() { return group; } + + public enum SidebarPosition { + TOP_LEFT(false, false), + TOP_RIGHT(false, true), + BOTTOM_LEFT(true, false), + BOTTOM_RIGHT(true, true); + + private final boolean isBottom; + private final boolean isRight; + + SidebarPosition(boolean isBottom, boolean isRight) { + this.isBottom = isBottom; + this.isRight = isRight; + } + + public boolean isBottom() { + return isBottom; + } + + public boolean isRight() { + return isRight; + } + + public static final NameMap NAME_MAP = NameMap.of(TOP_LEFT, SidebarPosition.values()).create(); + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java index 92733a5e..f9bd50c9 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java @@ -93,9 +93,10 @@ private static SidebarButton createSidebarButton(ResourceLocation id, JsonObject if (parse.error().isPresent()) { FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); } else { - SidebarButtonData sidebarButton = parse.result().get(); + SidebarButtonData sidebarButtonData = parse.result().get(); + SidebarButton sidebarButton = new SidebarButton(id, sidebarButtonData); SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(sidebarButton)); - return new SidebarButton(id, sidebarButton); + return sidebarButton; } return null; } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java index 9bf96788..1ad27407 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java @@ -1,14 +1,19 @@ package dev.ftb.mods.ftblibrary.sidebar; +import com.mojang.blaze3d.systems.RenderSystem; import dev.architectury.platform.Platform; +import dev.ftb.mods.ftblibrary.icon.Color4I; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import dev.ftb.mods.ftblibrary.ui.misc.LoadingScreen; import dev.ftb.mods.ftblibrary.util.ChainedBooleanSupplier; import dev.ftb.mods.ftblibrary.util.client.ClientUtils; import net.minecraft.Util; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; +import java.util.ArrayList; import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Consumer; @@ -20,6 +25,7 @@ public class SidebarButton { private final ResourceLocation id; private final String langKey; private final Component basicTooltip; + private final List extraRenderers; private Supplier tooltipOverride; private ChainedBooleanSupplier visible = ChainedBooleanSupplier.TRUE; @@ -33,6 +39,7 @@ public SidebarButton(ResourceLocation id, SidebarButtonData data) { addVisibilityCondition(ClientUtils.IS_CLIENT_OP); } data.requiredMods().ifPresent(mods -> addVisibilityCondition(() -> mods.stream().allMatch(Platform::isModLoaded))); + extraRenderers = new ArrayList<>(); } @@ -71,6 +78,19 @@ public boolean canSee() { return visible.getAsBoolean(); } + @Deprecated + public void setCustomTextHandler(Supplier customTextHandler) { + addExtraRenderer((graphics, font, buttonSize) -> { + String text = customTextHandler.get(); + if (!text.isEmpty()) { + var nw = font.width(text); + Color4I.LIGHT_RED.draw(graphics, buttonSize - nw, -1, nw + 1, 9); + graphics.drawString(font, text, buttonSize - nw + 1, 0, 0xFFFFFFFF); + RenderSystem.setShaderColor(1F, 1F, 1F, 1F); + } + }); + } + //Todo fix both of these public Supplier getCustomTextHandler() { return null; @@ -79,5 +99,18 @@ public Supplier getCustomTextHandler() { public Consumer> getTooltipHandler() { return null; } + + public void addExtraRenderer(ExtraRenderer renderer) { + extraRenderers.add(renderer); + } + + + public List getExtraRenderers() { + return extraRenderers; + } + + public interface ExtraRenderer { + void render(GuiGraphics graphics, Font font, int buttonSize); + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java index 032c883e..7933ce73 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java @@ -12,13 +12,13 @@ public class SidebarButtonCreatedEvent { public static final Event> EVENT = EventFactory.createConsumerLoop(SidebarButtonCreatedEvent.class); - private final SidebarButtonData button; + private final SidebarButton button; - public SidebarButtonCreatedEvent(SidebarButtonData b) { - button = b; + public SidebarButtonCreatedEvent(SidebarButton button) { + this.button = button; } - public SidebarButtonData getButton() { + public SidebarButton getButton() { return button; } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index 508a74ee..22e695e1 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -1,8 +1,10 @@ package dev.ftb.mods.ftblibrary.sidebar; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; import dev.ftb.mods.ftblibrary.FTBLibrary; import dev.ftb.mods.ftblibrary.FTBLibraryClient; +import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.icon.Color4I; import dev.ftb.mods.ftblibrary.icon.Icons; import dev.ftb.mods.ftblibrary.ui.Button; @@ -46,157 +48,183 @@ public class SidebarGroupGuiButton extends AbstractButton { private boolean addBoxOpen; + boolean gridStartBottom = false; + boolean gridStartRight = false; + + int yRenderStart; + int xRenderStart; + + + private int maxGirdAmountX; + private int maxGirdAmountY; + + + private final Map realLocationMap = new HashMap<>(); public SidebarGroupGuiButton() { super(0, 0, 0, 0, Component.empty()); - - ensureGridAlignment(); isMouseDown = false; + ensureGridAlignment(); + } @Override public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { graphics.pose().pushPose(); - graphics.pose().translate(0, 0, 5000); - //Todo always? - addBoxOpen = true; - currentMouseX = mx; - currentMouseY = my; - mouseOver = null; - GridLocation gridLocation = getGridLocation(); - - for (Map.Entry entry : realLocationMap.entrySet()) { - SidebarGuiButton button = entry.getKey(); - if (entry.getValue().equals(gridLocation)) { - mouseOver = button; + { + graphics.pose().translate(0, 0, 5000); + + currentMouseX = mx; + currentMouseY = my; + mouseOver = null; + + GridLocation gridLocation = getGridLocation(); + + for (Map.Entry entry : realLocationMap.entrySet()) { + SidebarGuiButton button = entry.getKey(); + if (entry.getValue().equals(gridLocation)) { + mouseOver = button; + } } - } - maxGridWith = 1; - maxGridHeight = 1; - for (Map.Entry value : realLocationMap.entrySet()) { - GridLocation location = value.getValue(); - maxGridWith = Math.max(maxGridWith, location.x() + 1); - maxGridHeight = Math.max(maxGridHeight, location.y() + 1); - } - if (isEditMode) { - maxGridWith += 1; - maxGridHeight += 1; + if (isEditMode) { +// - drawHoveredGrid(graphics, 0, 0, maxGridWith, maxGridHeight, BUTTON_SPACING, Color4I.GRAY.withAlpha(70), Color4I.BLACK.withAlpha(90), mx, my); - List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode); - if (!disabledButtonList.isEmpty()) { - drawGrid(graphics, (maxGridWith + 1) * BUTTON_SPACING, 0, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); - Icons.ADD.draw(graphics, (maxGridWith + 1) * BUTTON_SPACING + 1, 1, 16, 16); - if (addBoxOpen) { - int maxWidth = 0; - for (SidebarGuiButton button : disabledButtonList) { - String s = I18n.get(button.getSidebarButton().getLangKey()); - int width = Minecraft.getInstance().font.width(s); - maxWidth = Math.max(maxWidth, width); - } + drawHoveredGrid(graphics, xRenderStart, yRenderStart , maxGridWith, maxGridHeight, BUTTON_SPACING, Color4I.GRAY.withAlpha(70), Color4I.BLACK.withAlpha(90), mx, my, gridStartBottom, gridStartRight, getX(), getY()); - drawGrid(graphics, (maxGridWith + 1) * BUTTON_SPACING, BUTTON_SPACING, 1, disabledButtonList.size(), maxWidth + BUTTON_SPACING + 4, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode); + if (!disabledButtonList.isEmpty()) { + int addIconY = gridStartBottom ? yRenderStart + maxGirdAmountY * BUTTON_SPACING - 4 : 0; + int addIconX = gridStartRight ? maxGridWith * BUTTON_SPACING : 0; + addIconX += (maxGridWith + 1) * BUTTON_SPACING; + drawGrid(graphics, addIconX, addIconY, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + Icons.ADD.draw(graphics, addIconX + 1, addIconY + 1, 16, 16); - for (int i = 0; i < disabledButtonList.size(); i++) { - SidebarGuiButton button = disabledButtonList.get(i); - if (selectedButton != null && selectedButton == button) { - continue; + if (addBoxOpen) { + int maxWidth = 0; + for (SidebarGuiButton button : disabledButtonList) { + String s = I18n.get(button.getSidebarButton().getLangKey()); + int width = Minecraft.getInstance().font.width(s); + maxWidth = Math.max(maxWidth, width); } - button.x = (maxGridWith + 1) * BUTTON_SPACING; - button.y = BUTTON_SPACING + BUTTON_SPACING * i; - GuiHelper.setupDrawing(); - button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); - graphics.drawString(Minecraft.getInstance().font, I18n.get(button.getSidebarButton().getLangKey()), button.x + 20, button.y + 4, 0xFFFFFFFF); - if (mx >= button.x && mx < button.x + 16 && my >= button.y && my < button.y + 16) { - mouseOver = button; + int startY = gridStartBottom ? addIconY : 1; + int gridY = (gridStartBottom ? startY - disabledButtonList.size() * BUTTON_SPACING : BUTTON_SPACING); + drawGrid(graphics, (maxGridWith + 1) * BUTTON_SPACING, gridY, 1, disabledButtonList.size(), maxWidth + BUTTON_SPACING + 4, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + Color4I.BLACK.withAlpha(90).draw(graphics, (maxGridWith + 1) * BUTTON_SPACING + BUTTON_SPACING, gridY, 1, disabledButtonList.size() * BUTTON_SPACING); + + + for (int i = 0; i < disabledButtonList.size(); i++) { + SidebarGuiButton button = disabledButtonList.get(i); + if (selectedButton != null && selectedButton == button) { + continue; + } + int buttonY = gridY + BUTTON_SPACING * i; + button.x = (maxGridWith + 1) * BUTTON_SPACING; + button.y = buttonY; + GuiHelper.setupDrawing(); + + if (mx >= button.x && my >= button.y && mx < button.x + 16 && my < button.y + 16) { + Color4I.WHITE.withAlpha(137).draw(graphics, button.x + 1, button.y + 1, 16, 16); + mouseOver = button; + } + + button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); + + graphics.drawString(Minecraft.getInstance().font, I18n.get(button.getSidebarButton().getLangKey()), button.x + 20, button.y + 4, 0xFFFFFFFF); + } - } + } } + } - } - var font = Minecraft.getInstance().font; + var font = Minecraft.getInstance().font; - for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { - GridLocation realGridLocation = realLocationMap.get(button); - if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { - graphics.pose().pushPose(); - if (isEditMode && button == selectedButton) { - graphics.pose().translate(0, 0, 5000); - button.x = mx - mouseOffsetX; - button.y = my - mouseOffsetY; - } else { - if(realGridLocation == null) { - continue; - } - button.x = 1 + realGridLocation.x() * BUTTON_SPACING; - button.y = 1 + realGridLocation.y() * BUTTON_SPACING; - } - GuiHelper.setupDrawing(); - button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); - - if (isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1) { - if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { - Icons.CANCEL.draw(graphics, button.x + 11, button.y - 1, 6, 6); - } else { - Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); - } - } + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { + GridLocation realGridLocation = realLocationMap.get(button); + if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { + { + boolean isThing = false; + if (isEditMode && button == selectedButton) { + graphics.pose().translate(0, 0, 5000); + isThing = true; + button.x = mx - mouseOffsetX; + button.y = my - mouseOffsetY; + } else { + if (realGridLocation == null) { + continue; + } + int adjustedX = gridStartRight ? xRenderStart + (maxGridWith - realGridLocation.x() - 1) * BUTTON_SPACING : xRenderStart + realGridLocation.x() * BUTTON_SPACING; + int adjustedY = gridStartBottom ? yRenderStart + (maxGridHeight - realGridLocation.y() - 1) * BUTTON_SPACING : yRenderStart + realGridLocation.y() * BUTTON_SPACING; - if (button == mouseOver) { - Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); - } + button.x = adjustedX + 1; + button.y = adjustedY + 1; + } + GuiHelper.setupDrawing(); + button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); - if (button.getSidebarButton().getCustomTextHandler() != null) { - var text = button.getSidebarButton().getCustomTextHandler().get(); + if (isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1) { + if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { + Icons.CANCEL.draw(graphics, button.x + 11, button.y - 1, 6, 6); + } else { + Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); + } + } - if (!text.isEmpty()) { - var nw = font.width(text); - var width = 16; - Color4I.LIGHT_RED.draw(graphics, button.x + width - nw, button.y - 1, nw + 1, 9); - graphics.drawString(font, text, button.x + width - nw + 1, button.y, 0xFFFFFFFF); - RenderSystem.setShaderColor(1F, 1F, 1F, 1F); - } - } - graphics.pose().popPose(); - } - if(!isEditMode && mouseOver == button) { - GuiHelper.setupDrawing(); - var mx1 = mx + 10; - var my1 = Math.max(3, my - 9); + if (button == mouseOver) { + Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); + } - List list = new ArrayList<>(); - list.add(I18n.get(mouseOver.getSidebarButton().getLangKey())); +// pose.pushPose(); + { + graphics.pose().translate(button.x, button.y, 0); + for (SidebarButton.ExtraRenderer extraRenderer : button.getSidebarButton().getExtraRenderers()) { + extraRenderer.render(graphics, font, 16); + } + graphics.pose().translate(-button.x, -button.y, 0); - if (mouseOver.getSidebarButton().getTooltipHandler() != null) { - mouseOver.getSidebarButton().getTooltipHandler().accept(list); + } + if(isThing) { + graphics.pose().translate(0, 0, -5000); + } + } } + if (!isEditMode && mouseOver == button) { + GuiHelper.setupDrawing(); + var mx1 = mx + 10; + var my1 = Math.max(3, my - 9); - var tw = 0; + List list = new ArrayList<>(); + list.add(I18n.get(mouseOver.getSidebarButton().getLangKey())); - for (String s : list) { - tw = Math.max(tw, font.width(s)); - } + if (mouseOver.getSidebarButton().getTooltipHandler() != null) { + mouseOver.getSidebarButton().getTooltipHandler().accept(list); + } - Color4I.DARK_GRAY.draw(graphics, mx1 - 3, my1 - 2, tw + 6, 2 + list.size() * 10); + var tw = 0; - for (var i = 0; i < list.size(); i++) { - graphics.drawString(font, list.get(i), mx1, my1 + i * 10, 0xFFFFFFFF); + for (String s : list) { + tw = Math.max(tw, font.width(s)); + } + int fixedMouseX = gridStartRight ? mx1 - tw - 6 : mx1; + Color4I.DARK_GRAY.draw(graphics, fixedMouseX - 3, my1 - 2, tw + 6, 2 + list.size() * 10); + + for (var i = 0; i < list.size(); i++) { + graphics.drawString(font, list.get(i), fixedMouseX, my1 + i * 10, 0xFFFFFFFF); + } } } - } + } graphics.pose().popPose(); - } @Override @@ -268,6 +296,7 @@ private void ensureGridAlignment() { } + SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); updateWidgetSize(); } @@ -278,47 +307,106 @@ private void updateWidgetSize() { // of its GUI areas, including resetting the filter textfield's selection // https://github.com/FTBTeam/FTB-Mods-Issues/issues/262 // https://github.com/mezz/JustEnoughItems/issues/2938 - var maxGirdX = 1; - var maxGirdY = 1; + int girdAmountX = 1; + int girdAmountY = 1; for (SidebarGuiButton b : SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode)) { - maxGirdX = Math.max(maxGirdX, b.getGirdLocation().x() + 1); - maxGirdY = Math.max(maxGirdY, b.getGirdLocation().y() + 1); + girdAmountX = Math.max(girdAmountX, b.getGirdLocation().x() + 1); + girdAmountY = Math.max(girdAmountY, b.getGirdLocation().y() + 1); } int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).size(); if(isEditMode && addBoxOpen) { - maxGirdX += 4; - maxGirdY = Math.max(maxGirdY, disabledList); + girdAmountX += 4; + girdAmountY = Math.max(girdAmountY, disabledList); } if(isEditMode) { - maxGirdX += 3; - maxGirdY += 1; + girdAmountX += 3; + girdAmountY += 1; } + int screenWidth = Minecraft.getInstance().getWindow().getGuiScaledWidth(); + int screenHeight = Minecraft.getInstance().getWindow().getGuiScaledHeight(); - width = (maxGirdX) * BUTTON_SPACING; - height = (maxGirdY) * BUTTON_SPACING; + maxGirdAmountX = screenWidth / BUTTON_SPACING; + maxGirdAmountY = screenHeight / BUTTON_SPACING; + girdAmountX = Math.min(girdAmountX, maxGirdAmountX); + girdAmountY = Math.min(girdAmountY, maxGirdAmountY); - setX(0); - setY(0); + width = (girdAmountX) * BUTTON_SPACING; + height = (girdAmountY) * BUTTON_SPACING; + + FTBLibraryClientConfig.SidebarPosition sidebarPosition = FTBLibraryClientConfig.POSITION.get(); + if (sidebarPosition.isBottom()) { + setY(screenHeight - height - 2); + gridStartBottom = true; + } else { + setY(0); + gridStartBottom = false; + } + if(sidebarPosition.isRight()) { + setX(screenWidth - width - 2); + gridStartRight = true; + } else { + setX(0); + gridStartRight = false; + } + + maxGridWith = 1; + maxGridHeight = 1; + for (Map.Entry value : realLocationMap.entrySet()) { + GridLocation location = value.getValue(); + maxGridWith = Math.max(maxGridWith, location.x() + 1); + maxGridHeight = Math.max(maxGridHeight, location.y() + 1); + } + + if(isEditMode) { + maxGridWith += 1; + maxGridHeight += 1; + } + + + xRenderStart = (gridStartRight ? maxGirdAmountX - maxGridWith : 0) * BUTTON_SPACING; + yRenderStart = (gridStartBottom ? maxGirdAmountY - maxGridHeight + 1 : 0) * BUTTON_SPACING; + if(gridStartBottom) { + yRenderStart -= 4; + } + if(gridStartRight) { + xRenderStart += 3; + } lastDrawnArea = new Rect2i(getX(), getY(), width, height); } private GridLocation getGridLocation() { - int gridX = (currentMouseX - 1) / BUTTON_SPACING; - int gridY = (currentMouseY - 1) / BUTTON_SPACING; - if(gridX >= maxGridWith || gridY >= maxGridHeight) { + + int gridX = (currentMouseX - xRenderStart - 1) / BUTTON_SPACING; + int gridY = (currentMouseY - yRenderStart - 1) / BUTTON_SPACING; + + if (gridStartRight) { + gridX = maxGridWith - gridX - 1; + } + + if (gridStartBottom) { + gridY = maxGridHeight - gridY - 1; + } + + if (gridX >= maxGridWith || gridY >= maxGridHeight || gridX < 0 || gridY < 0) { return GridLocation.OUT_OF_BOUNDS; } + return new GridLocation(gridX, gridY); } @Override public void onPress() { +// lastX = currentMouseX; +// lastY = currentMouseY; +// updateWidgetSize(); if(isEditMode) { - if(currentMouseX >= ( maxGridWith + 1) * BUTTON_SPACING && currentMouseY <= BUTTON_SPACING) { + int adjustedY = gridStartBottom ? height - BUTTON_SPACING : 0; + if (currentMouseX >= getX() + (maxGridWith + 1) * BUTTON_SPACING && currentMouseX < getX() + (maxGridWith + 1) * BUTTON_SPACING + 16 && + currentMouseY <= getY() + adjustedY + BUTTON_SPACING && currentMouseY > getY() + adjustedY + BUTTON_SPACING - 16) { addBoxOpen = !addBoxOpen; updateWidgetSize(); return; @@ -331,7 +419,7 @@ public void onPress() { mouseOffsetY = currentMouseY - mouseOver.y; if(isEditMode) { - if(SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1 && currentMouseX >= mouseOver.x + 11 && currentMouseY <= mouseOver.y + 3) { + if(SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1 && currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4 && currentMouseX < mouseOver.x + 16 && currentMouseY >= mouseOver.y) { mouseOver.setEnabled(false); mouseOver = null; ensureGridAlignment(); @@ -354,14 +442,14 @@ public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) //Custom handling so our button click locations are where a buttons are not just a box @Override protected boolean isValidClickButton(int i) { - if (super.isValidClickButton(i)) { - if (isEditMode) { - return selectedButton != null || mouseOver != null; - } else { - return mouseOver != null; - } - } - return false; +// if (super.isValidClickButton(i)) { +// if (isEditMode) { +// return selectedButton != null || mouseOver != null; +// } else { +// return mouseOver != null; +// } +// } + return true; } public void tick() { @@ -392,10 +480,24 @@ public static void drawGrid(GuiGraphics graphics, int x, int y, int width, int h drawGrid(graphics, x, y, width, height, spacing, spacing, backgroundColor, gridColor); } - public static void drawHoveredGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor, int mx, int my) { + private static void drawHoveredGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor, int mx, int my, boolean gridStartBottom, boolean gridStartRight, int posX, int posY) { drawGrid(graphics, x, y, width, height, spacing, backgroundColor, gridColor); - if (mx >= x && my >= y && mx < x + width * spacing && my < y + height * spacing) { - Color4I.WHITE.withAlpha(127).draw(graphics, (mx / spacing) * spacing + 1, (my / spacing) * spacing + 1, spacing - 1, spacing - 1); + + int adjustedMx = mx; + int adjustedMy = my; + + if (gridStartRight) { + adjustedMx = x + width * spacing - (mx - x); + } + + if (gridStartBottom) { + adjustedMy = y + height * spacing - (my - y); + } + + if (adjustedMx >= x + posX && adjustedMy >= y + posY && adjustedMx < x + posX + width * spacing && adjustedMy < y + posY + height * spacing) { + int gridX = (adjustedMx - x - posX) / spacing; + int gridY = (adjustedMy - y - posY) / spacing; + Color4I.WHITE.withAlpha(127).draw(graphics, gridX * BUTTON_SPACING + 1, gridY * BUTTON_SPACING + 1, spacing - 1, spacing - 1); } } } From 67526db61145573dd2bdf90899a575891e3af2fb Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Tue, 6 Aug 2024 10:45:19 -0500 Subject: [PATCH 08/17] Hopefully finish grid alignment code --- .../api/sidebar/ButtonOverlayRender.java | 24 ++ .../ftblibrary/api/sidebar/SidebarButton.java | 42 +++ .../integration/REIIntegration.java | 11 +- .../ftblibrary/sidebar/SidebarButton.java | 60 ++-- .../sidebar/SidebarButtonCreatedEvent.java | 3 +- .../sidebar/SidebarButtonManager.java | 1 - .../sidebar/SidebarGroupGuiButton.java | 294 +++++++++--------- .../ftblibrary/sidebar/SidebarGuiButton.java | 13 +- 8 files changed, 240 insertions(+), 208 deletions(-) create mode 100644 common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java create mode 100644 common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java new file mode 100644 index 00000000..b509ef17 --- /dev/null +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java @@ -0,0 +1,24 @@ +package dev.ftb.mods.ftblibrary.api.sidebar; + +import com.mojang.blaze3d.systems.RenderSystem; +import dev.ftb.mods.ftblibrary.icon.Color4I; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; + +import java.util.function.Supplier; + +public interface ButtonOverlayRender { + void render(GuiGraphics graphics, Font font, int buttonSize); + + static ButtonOverlayRender ofSimpleString(Supplier customTextHandler) { + return (graphics, font, buttonSize) -> { + String text = customTextHandler.get(); + if (!text.isEmpty()) { + var nw = font.width(text); + Color4I.LIGHT_RED.draw(graphics, buttonSize - nw, -1, nw + 1, 9); + graphics.drawString(font, text, buttonSize - nw + 1, 0, 0xFFFFFFFF); + RenderSystem.setShaderColor(1F, 1F, 1F, 1F); + } + }; + } +} diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java new file mode 100644 index 00000000..24f3669f --- /dev/null +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java @@ -0,0 +1,42 @@ +package dev.ftb.mods.ftblibrary.api.sidebar; + +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +import java.util.List; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +public interface SidebarButton +{ + + /** + * @return the id of the button + */ + ResourceLocation getId(); + + /** + * @param customTextHandler A supplier that returns the text to be displayed on the button + * @deprecated Use {@link #addOverlayRender(ButtonOverlayRender)} instead + */ + @Deprecated(forRemoval = true) + default void setCustomTextHandler(Supplier customTextHandler) { + addOverlayRender(ButtonOverlayRender.ofSimpleString(customTextHandler)); + } + + /** + * @param condition a condition that must be met for the button to be visible + */ + void addVisibilityCondition(BooleanSupplier condition); + + /** + * @param renderer register a custom button overlay renderer to render on top of the button icon + */ + void addOverlayRender(ButtonOverlayRender renderer); + + /** + * @param tooltipOverride a supplier that returns the tooltip to be displayed when hovering over the button + */ + void setTooltipOverride(Supplier> tooltipOverride); + +} diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java index f9bd50c9..3e8e8338 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java @@ -6,6 +6,7 @@ import com.mojang.serialization.JsonOps; import com.mojang.serialization.Lifecycle; import dev.ftb.mods.ftblibrary.FTBLibrary; +import dev.ftb.mods.ftblibrary.api.sidebar.ButtonOverlayRender; import dev.ftb.mods.ftblibrary.config.ui.SelectItemStackScreen; import dev.ftb.mods.ftblibrary.config.ui.ResourceSearchMode; import dev.ftb.mods.ftblibrary.config.ui.SelectableResource; @@ -154,14 +155,8 @@ public Renderer getRenderer(boolean showcase) { public void render(GuiGraphics graphics, Rectangle bounds, int mouseX, int mouseY, float delta) { GuiHelper.setupDrawing(); button.getData().icon().draw(graphics, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); - if (button.getCustomTextHandler() != null) { - String text = button.getCustomTextHandler().get(); - Font font = Minecraft.getInstance().font; - if (!text.isEmpty()) { - var width = font.width(text); - Color4I.LIGHT_RED.draw(graphics, bounds.getX() + bounds.getWidth() - width, bounds.getY() - 1, width + 1, font.lineHeight); - graphics.drawString(font, text, bounds.getX() + bounds.getWidth() - width + 1, bounds.getY(), 0xFFFFFFFF); - } + for (ButtonOverlayRender extraRenderer : button.getExtraRenderers()) { + extraRenderer.render(graphics, Minecraft.getInstance().font, 16); } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java index 1ad27407..4c337234 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java @@ -1,32 +1,29 @@ package dev.ftb.mods.ftblibrary.sidebar; -import com.mojang.blaze3d.systems.RenderSystem; import dev.architectury.platform.Platform; -import dev.ftb.mods.ftblibrary.icon.Color4I; +import dev.ftb.mods.ftblibrary.api.sidebar.ButtonOverlayRender; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import dev.ftb.mods.ftblibrary.ui.misc.LoadingScreen; import dev.ftb.mods.ftblibrary.util.ChainedBooleanSupplier; import dev.ftb.mods.ftblibrary.util.client.ClientUtils; import net.minecraft.Util; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import java.util.ArrayList; import java.util.List; import java.util.function.BooleanSupplier; -import java.util.function.Consumer; import java.util.function.Supplier; -public class SidebarButton { +//Todo better name? +public class SidebarButton implements dev.ftb.mods.ftblibrary.api.sidebar.SidebarButton { private final SidebarButtonData data; private final ResourceLocation id; private final String langKey; private final Component basicTooltip; - private final List extraRenderers; - private Supplier tooltipOverride; + private final List extraRenderers; + private Supplier> tooltipOverride; private ChainedBooleanSupplier visible = ChainedBooleanSupplier.TRUE; @@ -43,15 +40,11 @@ public SidebarButton(ResourceLocation id, SidebarButtonData data) { } - public void addVisibilityCondition(BooleanSupplier condition) { - visible = visible.and(condition); - } - - public SidebarButtonData getData() { return data; } + @Override public ResourceLocation getId() { return id; } @@ -61,7 +54,7 @@ public String getLangKey() { } public List getTooltip() { - return tooltipOverride == null ? List.of(basicTooltip) : List.of(basicTooltip, tooltipOverride.get()); + return tooltipOverride == null ? List.of(basicTooltip) : tooltipOverride.get(); } public void clickButton(boolean shift) { @@ -78,39 +71,26 @@ public boolean canSee() { return visible.getAsBoolean(); } - @Deprecated - public void setCustomTextHandler(Supplier customTextHandler) { - addExtraRenderer((graphics, font, buttonSize) -> { - String text = customTextHandler.get(); - if (!text.isEmpty()) { - var nw = font.width(text); - Color4I.LIGHT_RED.draw(graphics, buttonSize - nw, -1, nw + 1, 9); - graphics.drawString(font, text, buttonSize - nw + 1, 0, 0xFFFFFFFF); - RenderSystem.setShaderColor(1F, 1F, 1F, 1F); - } - }); - } - - //Todo fix both of these - public Supplier getCustomTextHandler() { - return null; - } - - public Consumer> getTooltipHandler() { - return null; + @Override + public void addVisibilityCondition(BooleanSupplier condition) { + visible = visible.and(condition); } - public void addExtraRenderer(ExtraRenderer renderer) { + @Override + public void addOverlayRender(ButtonOverlayRender renderer) { extraRenderers.add(renderer); } - - public List getExtraRenderers() { - return extraRenderers; + @Override + public void setTooltipOverride(Supplier> tooltipOverride) { + this.tooltipOverride = tooltipOverride; } - public interface ExtraRenderer { - void render(GuiGraphics graphics, Font font, int buttonSize); + /** + * @return a list of custom button overlay renderers to render on top of the button icon + */ + public List getExtraRenderers() { + return extraRenderers; } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java index 7933ce73..cde569c4 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java @@ -5,8 +5,7 @@ import java.util.function.Consumer; -//Todo - UnReal Expose a way for other mod to reigster custom text handlers as that what this event is for -//Todo WE DO NOT ALLOW EDITING BUTTONS AFTER CREATION ANYMORE +//Todo move this to api class // TODO currently broken for neoforge, uncomment when there's a fix in architectury //@ForgeEvent public class SidebarButtonCreatedEvent { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index b4ed75ba..ab489a0f 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -6,7 +6,6 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; import dev.ftb.mods.ftblibrary.FTBLibrary; -import dev.ftb.mods.ftblibrary.FTBLibraryClient; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.snbt.config.StringSidebarMapValue; import net.minecraft.resources.ResourceLocation; diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index 22e695e1..16bd1a49 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -1,13 +1,9 @@ package dev.ftb.mods.ftblibrary.sidebar; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import dev.ftb.mods.ftblibrary.FTBLibrary; -import dev.ftb.mods.ftblibrary.FTBLibraryClient; +import dev.ftb.mods.ftblibrary.api.sidebar.ButtonOverlayRender; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.icon.Color4I; import dev.ftb.mods.ftblibrary.icon.Icons; -import dev.ftb.mods.ftblibrary.ui.Button; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; @@ -37,14 +33,15 @@ public class SidebarGroupGuiButton extends AbstractButton { private boolean isMouseDown; private int mouseDownTime; private boolean isEditMode; + private int currentMouseX; private int currentMouseY; private int mouseOffsetX; private int mouseOffsetY; - private int maxGridWith = 1; - private int maxGridHeight = 1; + private int currentGirdWidth = 1; + private int currentGridHeight = 1; private boolean addBoxOpen; @@ -54,13 +51,9 @@ public class SidebarGroupGuiButton extends AbstractButton { int yRenderStart; int xRenderStart; + private boolean isMouseOverAdd; - private int maxGirdAmountX; - private int maxGirdAmountY; - - - - private final Map realLocationMap = new HashMap<>(); + private final Map realLocationMap = new HashMap<>(); public SidebarGroupGuiButton() { super(0, 0, 0, 0, Component.empty()); @@ -78,6 +71,7 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick currentMouseX = mx; currentMouseY = my; mouseOver = null; + isMouseOverAdd = false; GridLocation gridLocation = getGridLocation(); @@ -88,143 +82,147 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick } } - if (isEditMode) { -// - - + renderEditMode(graphics, mx, my); + } - drawHoveredGrid(graphics, xRenderStart, yRenderStart , maxGridWith, maxGridHeight, BUTTON_SPACING, Color4I.GRAY.withAlpha(70), Color4I.BLACK.withAlpha(90), mx, my, gridStartBottom, gridStartRight, getX(), getY()); + renderSidebarButtons(graphics, mx, my); - List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode); - if (!disabledButtonList.isEmpty()) { - int addIconY = gridStartBottom ? yRenderStart + maxGirdAmountY * BUTTON_SPACING - 4 : 0; - int addIconX = gridStartRight ? maxGridWith * BUTTON_SPACING : 0; - addIconX += (maxGridWith + 1) * BUTTON_SPACING; - drawGrid(graphics, addIconX, addIconY, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); - Icons.ADD.draw(graphics, addIconX + 1, addIconY + 1, 16, 16); + } + graphics.pose().popPose(); + } - if (addBoxOpen) { - int maxWidth = 0; - for (SidebarGuiButton button : disabledButtonList) { - String s = I18n.get(button.getSidebarButton().getLangKey()); - int width = Minecraft.getInstance().font.width(s); - maxWidth = Math.max(maxWidth, width); - } + private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { + var font = Minecraft.getInstance().font; + + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { + graphics.pose().pushPose(); + GridLocation realGridLocation = realLocationMap.get(button); + if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { + if (isEditMode && button == selectedButton) { + graphics.pose().translate(0, 0, 50); + button.x = mx - mouseOffsetX; + button.y = my - mouseOffsetY; + } else { + if (realGridLocation == null) { + continue; + } + int adjustedX = gridStartRight ? xRenderStart + (currentGirdWidth - realGridLocation.x() - 1) * BUTTON_SPACING : xRenderStart + realGridLocation.x() * BUTTON_SPACING; + int adjustedY = gridStartBottom ? yRenderStart + (currentGridHeight - realGridLocation.y() - 1) * BUTTON_SPACING : yRenderStart + realGridLocation.y() * BUTTON_SPACING; - int startY = gridStartBottom ? addIconY : 1; - int gridY = (gridStartBottom ? startY - disabledButtonList.size() * BUTTON_SPACING : BUTTON_SPACING); - drawGrid(graphics, (maxGridWith + 1) * BUTTON_SPACING, gridY, 1, disabledButtonList.size(), maxWidth + BUTTON_SPACING + 4, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); - Color4I.BLACK.withAlpha(90).draw(graphics, (maxGridWith + 1) * BUTTON_SPACING + BUTTON_SPACING, gridY, 1, disabledButtonList.size() * BUTTON_SPACING); + button.x = adjustedX + 1; + button.y = adjustedY + 1; + } + GuiHelper.setupDrawing(); + button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); + + if (isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1) { + if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { + Icons.CANCEL.draw(graphics, button.x + 11, button.y - 1, 6, 6); + } else { + Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); + } + } + if (button == mouseOver) { + Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); + } - for (int i = 0; i < disabledButtonList.size(); i++) { - SidebarGuiButton button = disabledButtonList.get(i); - if (selectedButton != null && selectedButton == button) { - continue; - } - int buttonY = gridY + BUTTON_SPACING * i; - button.x = (maxGridWith + 1) * BUTTON_SPACING; - button.y = buttonY; - GuiHelper.setupDrawing(); - - if (mx >= button.x && my >= button.y && mx < button.x + 16 && my < button.y + 16) { - Color4I.WHITE.withAlpha(137).draw(graphics, button.x + 1, button.y + 1, 16, 16); - mouseOver = button; - } + graphics.pose().translate(button.x, button.y, 0); + for (ButtonOverlayRender buttonOverlayRender : button.getSidebarButton().getExtraRenderers()) { + buttonOverlayRender.render(graphics, font, 16); + } + graphics.pose().translate(-button.x, -button.y, 0); - button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); + } + if (!isEditMode && mouseOver == button) { + graphics.pose().pushPose(); + graphics.pose().translate(0, 0, 50); + GuiHelper.setupDrawing(); + var mx1 = mx + 10; + var my1 = Math.max(3, my - 9); - graphics.drawString(Minecraft.getInstance().font, I18n.get(button.getSidebarButton().getLangKey()), button.x + 20, button.y + 4, 0xFFFFFFFF); + List list = new ArrayList<>(); + list.add(I18n.get(mouseOver.getSidebarButton().getLangKey())); - } + var tw = 0; - } + for (String s : list) { + tw = Math.max(tw, font.width(s)); } + int fixedMouseX = gridStartRight ? mx1 - tw - 6 : mx1; + Color4I.DARK_GRAY.draw(graphics, fixedMouseX - 3, my1 - 2, tw + 6, 2 + list.size() * 10); + for (var i = 0; i < list.size(); i++) { + graphics.drawString(font, list.get(i), fixedMouseX, my1 + i * 10, 0xFFFFFFFF); + } + graphics.pose().popPose(); } + graphics.pose().popPose(); + } + } + private void renderEditMode(GuiGraphics graphics, int mx, int my) { + drawHoveredGrid(graphics, xRenderStart, yRenderStart, currentGirdWidth, currentGridHeight, BUTTON_SPACING, Color4I.GRAY.withAlpha(70), Color4I.BLACK.withAlpha(90), mx, my, gridStartBottom, gridStartRight, getX(), getY()); + List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode); + if (!disabledButtonList.isEmpty()) { + int addIconY = gridStartBottom ? yRenderStart + ((currentGridHeight - 1) * BUTTON_SPACING) : 0; + int addIconX = gridStartRight ? xRenderStart - (2 * BUTTON_SPACING) : (currentGirdWidth + 1) * BUTTON_SPACING; + drawGrid(graphics, addIconX, addIconY, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + Icons.ADD.draw(graphics, addIconX + 1, addIconY + 1, 16, 16); - var font = Minecraft.getInstance().font; - - for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { - GridLocation realGridLocation = realLocationMap.get(button); - if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { - { - boolean isThing = false; - if (isEditMode && button == selectedButton) { - graphics.pose().translate(0, 0, 5000); - isThing = true; - button.x = mx - mouseOffsetX; - button.y = my - mouseOffsetY; - } else { - if (realGridLocation == null) { - continue; - } - int adjustedX = gridStartRight ? xRenderStart + (maxGridWith - realGridLocation.x() - 1) * BUTTON_SPACING : xRenderStart + realGridLocation.x() * BUTTON_SPACING; - int adjustedY = gridStartBottom ? yRenderStart + (maxGridHeight - realGridLocation.y() - 1) * BUTTON_SPACING : yRenderStart + realGridLocation.y() * BUTTON_SPACING; - - button.x = adjustedX + 1; - button.y = adjustedY + 1; - } - GuiHelper.setupDrawing(); - button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); - - if (isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1) { - if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { - Icons.CANCEL.draw(graphics, button.x + 11, button.y - 1, 6, 6); - } else { - Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); - } - } + if (mx >= addIconX && my >= addIconY && mx < addIconX + 16 && my < addIconY + 16) { + isMouseOverAdd = true; + Color4I.WHITE.withAlpha(137).draw(graphics, addIconX + 1, addIconY + 1, 16, 16); + } - if (button == mouseOver) { - Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); - } + if (addBoxOpen) { + int maxWidth = 0; + for (SidebarGuiButton button : disabledButtonList) { + String s = I18n.get(button.getSidebarButton().getLangKey()); + int width = Minecraft.getInstance().font.width(s); + maxWidth = Math.max(maxWidth, width); + } -// pose.pushPose(); - { - graphics.pose().translate(button.x, button.y, 0); - for (SidebarButton.ExtraRenderer extraRenderer : button.getSidebarButton().getExtraRenderers()) { - extraRenderer.render(graphics, font, 16); - } - graphics.pose().translate(-button.x, -button.y, 0); + int gridY = gridStartBottom ? addIconY - disabledButtonList.size() * BUTTON_SPACING : BUTTON_SPACING; + int gridX = gridStartRight ? addIconX - maxWidth - 6 : (currentGirdWidth + 1) * BUTTON_SPACING; + + graphics.pose().pushPose(); + graphics.pose().translate(0, 0, 1000); + if (gridStartRight) { + drawHoveredGrid(graphics, addIconX, gridY, 1, disabledButtonList.size(), BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my, gridStartBottom, gridStartRight, gridX, gridY); + drawGrid(graphics, addIconX - maxWidth - 6, gridY, 1, disabledButtonList.size(), maxWidth + 6, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + } else { + drawHoveredGrid(graphics, gridX, gridY, 1, disabledButtonList.size(), BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my, gridStartBottom, gridStartRight, gridX, gridY); + drawGrid(graphics, gridX + BUTTON_SPACING, gridY, 1, disabledButtonList.size(), maxWidth + 6, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + } - } - if(isThing) { - graphics.pose().translate(0, 0, -5000); - } + for (int i = 0; i < disabledButtonList.size(); i++) { + SidebarGuiButton button = disabledButtonList.get(i); + if (selectedButton != null && selectedButton == button) { + continue; } - } - if (!isEditMode && mouseOver == button) { + int buttonY = gridY + BUTTON_SPACING * i; + button.x = gridStartRight ? addIconX : gridX + BUTTON_SPACING; + button.y = buttonY; GuiHelper.setupDrawing(); - var mx1 = mx + 10; - var my1 = Math.max(3, my - 9); - List list = new ArrayList<>(); - list.add(I18n.get(mouseOver.getSidebarButton().getLangKey())); - - if (mouseOver.getSidebarButton().getTooltipHandler() != null) { - mouseOver.getSidebarButton().getTooltipHandler().accept(list); + if (mx >= button.x && my >= button.y && mx < button.x + 16 && my < button.y + 16) { + Color4I.WHITE.withAlpha(137).draw(graphics, button.x + 1, button.y + 1, 16, 16); + mouseOver = button; } - var tw = 0; - - for (String s : list) { - tw = Math.max(tw, font.width(s)); - } - int fixedMouseX = gridStartRight ? mx1 - tw - 6 : mx1; - Color4I.DARK_GRAY.draw(graphics, fixedMouseX - 3, my1 - 2, tw + 6, 2 + list.size() * 10); + button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); - for (var i = 0; i < list.size(); i++) { - graphics.drawString(font, list.get(i), fixedMouseX, my1 + i * 10, 0xFFFFFFFF); - } + String langText = I18n.get(button.getSidebarButton().getLangKey()); + int textXPos = gridStartRight ? addIconX - Minecraft.getInstance().font.width(langText) - 2 : gridX + BUTTON_SPACING; + graphics.drawString(Minecraft.getInstance().font, langText, textXPos, buttonY + 4, 0xFFFFFFFF); } - } + graphics.pose().popPose(); + } } - graphics.pose().popPose(); } @Override @@ -260,7 +258,6 @@ public void onRelease(double d, double e) { //If the icon was disabled enable it if (!selectedButton.isEnabled()) { selectedButton.setEnabled(true); - //Todo do we want this if (SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).isEmpty()) { addBoxOpen = false; } @@ -327,8 +324,8 @@ private void updateWidgetSize() { int screenWidth = Minecraft.getInstance().getWindow().getGuiScaledWidth(); int screenHeight = Minecraft.getInstance().getWindow().getGuiScaledHeight(); - maxGirdAmountX = screenWidth / BUTTON_SPACING; - maxGirdAmountY = screenHeight / BUTTON_SPACING; + int maxGirdAmountX = screenWidth / BUTTON_SPACING; + int maxGirdAmountY = screenHeight / BUTTON_SPACING; girdAmountX = Math.min(girdAmountX, maxGirdAmountX); girdAmountY = Math.min(girdAmountY, maxGirdAmountY); @@ -337,6 +334,7 @@ private void updateWidgetSize() { height = (girdAmountY) * BUTTON_SPACING; FTBLibraryClientConfig.SidebarPosition sidebarPosition = FTBLibraryClientConfig.POSITION.get(); + if (sidebarPosition.isBottom()) { setY(screenHeight - height - 2); gridStartBottom = true; @@ -352,22 +350,24 @@ private void updateWidgetSize() { gridStartRight = false; } - maxGridWith = 1; - maxGridHeight = 1; + currentGirdWidth = 1; + currentGridHeight = 1; + for (Map.Entry value : realLocationMap.entrySet()) { GridLocation location = value.getValue(); - maxGridWith = Math.max(maxGridWith, location.x() + 1); - maxGridHeight = Math.max(maxGridHeight, location.y() + 1); + currentGirdWidth = Math.max(currentGirdWidth, location.x() + 1); + currentGridHeight = Math.max(currentGridHeight, location.y() + 1); } if(isEditMode) { - maxGridWith += 1; - maxGridHeight += 1; + currentGirdWidth += 1; + currentGridHeight += 1; } - xRenderStart = (gridStartRight ? maxGirdAmountX - maxGridWith : 0) * BUTTON_SPACING; - yRenderStart = (gridStartBottom ? maxGirdAmountY - maxGridHeight + 1 : 0) * BUTTON_SPACING; + xRenderStart = (gridStartRight ? maxGirdAmountX - currentGirdWidth : 0) * BUTTON_SPACING; + yRenderStart = (gridStartBottom ? maxGirdAmountY - currentGridHeight + 1 : 0) * BUTTON_SPACING; + if(gridStartBottom) { yRenderStart -= 4; } @@ -384,14 +384,14 @@ private GridLocation getGridLocation() { int gridY = (currentMouseY - yRenderStart - 1) / BUTTON_SPACING; if (gridStartRight) { - gridX = maxGridWith - gridX - 1; + gridX = currentGirdWidth - gridX - 1; } if (gridStartBottom) { - gridY = maxGridHeight - gridY - 1; + gridY = currentGridHeight - gridY - 1; } - if (gridX >= maxGridWith || gridY >= maxGridHeight || gridX < 0 || gridY < 0) { + if (gridX >= currentGirdWidth || gridY >= currentGridHeight || gridX < 0 || gridY < 0) { return GridLocation.OUT_OF_BOUNDS; } @@ -400,13 +400,8 @@ private GridLocation getGridLocation() { @Override public void onPress() { -// lastX = currentMouseX; -// lastY = currentMouseY; -// updateWidgetSize(); if(isEditMode) { - int adjustedY = gridStartBottom ? height - BUTTON_SPACING : 0; - if (currentMouseX >= getX() + (maxGridWith + 1) * BUTTON_SPACING && currentMouseX < getX() + (maxGridWith + 1) * BUTTON_SPACING + 16 && - currentMouseY <= getY() + adjustedY + BUTTON_SPACING && currentMouseY > getY() + adjustedY + BUTTON_SPACING - 16) { + if (isMouseOverAdd) { addBoxOpen = !addBoxOpen; updateWidgetSize(); return; @@ -442,16 +437,17 @@ public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) //Custom handling so our button click locations are where a buttons are not just a box @Override protected boolean isValidClickButton(int i) { -// if (super.isValidClickButton(i)) { -// if (isEditMode) { -// return selectedButton != null || mouseOver != null; -// } else { -// return mouseOver != null; -// } -// } - return true; + if (super.isValidClickButton(i)) { + if (isEditMode) { + return isMouseOverAdd || selectedButton != null || mouseOver != null; + } else { + return mouseOver != null; + } + } + return false; } + //Check if mouse is down for 1 second and if so enter edit mode public void tick() { if(isMouseDown) { mouseDownTime++; diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java index f36df8fa..ce77cfc4 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java @@ -4,14 +4,13 @@ public class SidebarGuiButton { private final SidebarButton sidebarButton; public int x, y; - private int gridX, gridY; + private GridLocation gridLocation; private boolean enabled; public SidebarGuiButton(GridLocation girdLocation, boolean enabled, SidebarButton sidebarButton) { x = 0; y = 0; - gridX = girdLocation.x(); - gridY = girdLocation.y(); + this.gridLocation = girdLocation; this.sidebarButton = sidebarButton; this.enabled = enabled; } @@ -29,17 +28,15 @@ public SidebarButton getSidebarButton() { } public GridLocation getGirdLocation() { - return new GridLocation(gridX, gridY); + return gridLocation; } public void setGridLocation(GridLocation gridLocation) { - this.gridX = gridLocation.x(); - this.gridY = gridLocation.y(); + this.gridLocation = gridLocation; } public void setGridLocation(int x, int y) { - this.gridX = x; - this.gridY = y; + this.gridLocation = new GridLocation(x, y); } } From a15cf57bf1fdb6c9528b0837dfc11eda1f0f0184 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Tue, 6 Aug 2024 11:05:09 -0500 Subject: [PATCH 09/17] Fix rendering of tooltip and Sidebar buttons on the right --- .../mods/ftblibrary/sidebar/SidebarGroupGuiButton.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index 16bd1a49..7134e696 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -95,12 +95,14 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { var font = Minecraft.getInstance().font; + graphics.pose().translate(0, 0, 50); + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { graphics.pose().pushPose(); GridLocation realGridLocation = realLocationMap.get(button); if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { if (isEditMode && button == selectedButton) { - graphics.pose().translate(0, 0, 50); + graphics.pose().translate(0, 0, 1000); button.x = mx - mouseOffsetX; button.y = my - mouseOffsetY; } else { @@ -137,7 +139,6 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { } if (!isEditMode && mouseOver == button) { graphics.pose().pushPose(); - graphics.pose().translate(0, 0, 50); GuiHelper.setupDrawing(); var mx1 = mx + 10; var my1 = Math.max(3, my - 9); @@ -151,6 +152,7 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { tw = Math.max(tw, font.width(s)); } int fixedMouseX = gridStartRight ? mx1 - tw - 6 : mx1; + graphics.pose().translate(0, 0, 50); Color4I.DARK_GRAY.draw(graphics, fixedMouseX - 3, my1 - 2, tw + 6, 2 + list.size() * 10); for (var i = 0; i < list.size(); i++) { @@ -204,7 +206,7 @@ private void renderEditMode(GuiGraphics graphics, int mx, int my) { continue; } int buttonY = gridY + BUTTON_SPACING * i; - button.x = gridStartRight ? addIconX : gridX + BUTTON_SPACING; + button.x = gridStartRight ? addIconX : gridX; button.y = buttonY; GuiHelper.setupDrawing(); @@ -364,7 +366,6 @@ private void updateWidgetSize() { currentGridHeight += 1; } - xRenderStart = (gridStartRight ? maxGirdAmountX - currentGirdWidth : 0) * BUTTON_SPACING; yRenderStart = (gridStartBottom ? maxGirdAmountY - currentGridHeight + 1 : 0) * BUTTON_SPACING; From 249e90572f5c8482e5ca40f17688d4e6a6a63517 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Wed, 7 Aug 2024 13:59:59 -0500 Subject: [PATCH 10/17] Remove Groups, Info Button, Remove REI Integration for buttons --- .../ftb/mods/ftblibrary/FTBLibraryClient.java | 23 +- .../config/FTBLibraryClientConfig.java | 4 +- .../integration/REIIntegration.java | 277 ++++++++---------- .../ftblibrary/sidebar/SidebarButton.java | 3 - .../ftblibrary/sidebar/SidebarButtonData.java | 12 +- .../sidebar/SidebarButtonGroup.java | 33 --- .../sidebar/SidebarButtonManager.java | 92 ++---- .../sidebar/SidebarGroupGuiButton.java | 146 ++++----- .../ftb/mods/ftblibrary/util/MapUtils.java | 31 ++ .../assets/ftblibrary/lang/en_us.json | 4 +- .../sidebar_buttons/groups/cheat.json | 3 - .../sidebar_buttons/groups/info.json | 3 - .../sidebar_buttons/groups/util.json | 3 - .../sidebar_buttons/{buttons => }/test.json | 1 - .../{buttons => }/toggle/day.json | 2 - .../{buttons => }/toggle/gamemode.json | 2 - .../{buttons => }/toggle/night.json | 2 - .../{buttons => }/toggle/rain.json | 2 - .../fabric/AbstractContainerScreenMixin.java | 24 ++ .../resources/ftblibrary-fabric.mixins.json | 1 + gradle.properties | 2 +- 21 files changed, 286 insertions(+), 384 deletions(-) delete mode 100644 common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java create mode 100644 common/src/main/java/dev/ftb/mods/ftblibrary/util/MapUtils.java delete mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/cheat.json delete mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/info.json delete mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/util.json rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/{buttons => }/test.json (95%) rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/{buttons => }/toggle/day.json (82%) rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/{buttons => }/toggle/gamemode.json (80%) rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/{buttons => }/toggle/night.json (83%) rename common/src/main/resources/assets/ftblibrary/sidebar_buttons/{buttons => }/toggle/rain.json (79%) create mode 100644 fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java index a91d8cc8..22964828 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java @@ -3,7 +3,6 @@ import dev.architectury.event.events.client.ClientGuiEvent; import dev.architectury.event.events.client.ClientTickEvent; import dev.architectury.hooks.client.screen.ScreenAccess; -import dev.architectury.platform.Platform; import dev.architectury.registry.ReloadListenerRegistry; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.config.ui.EditConfigScreen; @@ -13,34 +12,22 @@ import dev.ftb.mods.ftblibrary.ui.CursorType; import dev.ftb.mods.ftblibrary.ui.IScreenWrapper; import dev.ftb.mods.ftblibrary.util.client.ClientUtils; -import me.shedaniel.rei.api.client.config.ConfigObject; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; -import net.minecraft.client.gui.screens.inventory.EffectRenderingInventoryScreen; import net.minecraft.server.packs.PackType; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; public class FTBLibraryClient { - /** - * Meaning of the different values: 0 = No, 1 = Yes, 2 = Only in inventory, 3 = Managed by integration - * (should this be an enum instead at this point?) - */ - public static int showButtons = 1; + public static CursorType lastCursorType = null; public static void init() { FTBLibraryClientConfig.load(); - // when using REI >= 6, disable the regular sidebar buttons, - // we'll be using REI's system favourites instead. - if (Platform.isModLoaded("roughlyenoughitems")) { - showButtons = 3; - } - // Datagens hahayes if (Minecraft.getInstance() == null) { return; @@ -91,16 +78,10 @@ public static boolean areButtonsVisible(@Nullable Screen gui) { return false; } - if (showButtons == 0 || showButtons == 2 && !(gui instanceof EffectRenderingInventoryScreen)) { + if(!FTBLibraryClientConfig.SIDEBAR_ENABLED.get()) { return false; } - if(showButtons == 3 && Platform.isModLoaded("roughlyenoughitems")) { - if (ConfigObject.getInstance().isFavoritesEnabled()) { - return false; - } - } - return gui instanceof AbstractContainerScreen && !SidebarButtonManager.INSTANCE.getButtons().isEmpty(); } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java b/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java index 64a71af5..cd10e806 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java @@ -27,7 +27,9 @@ public interface FTBLibraryClientConfig { .comment("Colors recently selected in the color selector"); SNBTConfig SIDEBAR = CONFIG.addGroup("sidebar"); - EnumValue POSITION = SIDEBAR.addEnum("position", SidebarPosition.NAME_MAP, SidebarPosition.TOP_LEFT) + BooleanValue SIDEBAR_ENABLED = SIDEBAR.addBoolean("enabled", true) + .comment("Enable the sidebar"); + EnumValue SIDEBAR_POSITION = SIDEBAR.addEnum("position", SidebarPosition.NAME_MAP, SidebarPosition.TOP_LEFT) .comment("Position of the sidebar"); StringSidebarMapValue SIDEBAR_BUTTONS = SIDEBAR.add(new StringSidebarMapValue(SIDEBAR, "buttons", new HashMap<>())); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java index 3e8e8338..d91b414a 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java @@ -1,51 +1,22 @@ package dev.ftb.mods.ftblibrary.integration; -import com.google.gson.JsonObject; -import com.mojang.datafixers.util.Pair; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.JsonOps; -import com.mojang.serialization.Lifecycle; import dev.ftb.mods.ftblibrary.FTBLibrary; -import dev.ftb.mods.ftblibrary.api.sidebar.ButtonOverlayRender; import dev.ftb.mods.ftblibrary.config.ui.SelectItemStackScreen; import dev.ftb.mods.ftblibrary.config.ui.ResourceSearchMode; import dev.ftb.mods.ftblibrary.config.ui.SelectableResource; -import dev.ftb.mods.ftblibrary.icon.Color4I; import dev.ftb.mods.ftblibrary.icon.Icon; import dev.ftb.mods.ftblibrary.icon.ItemIcon; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButton; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonData; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonCreatedEvent; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonGroup; -import dev.ftb.mods.ftblibrary.sidebar.SidebarButtonManager; -import dev.ftb.mods.ftblibrary.ui.GuiHelper; -import me.shedaniel.math.Rectangle; -import me.shedaniel.rei.api.client.favorites.FavoriteEntry; -import me.shedaniel.rei.api.client.favorites.FavoriteEntryType; -import me.shedaniel.rei.api.client.gui.Renderer; -import me.shedaniel.rei.api.client.gui.widgets.Tooltip; -import me.shedaniel.rei.api.client.gui.widgets.TooltipContext; import me.shedaniel.rei.api.client.plugins.REIClientPlugin; import me.shedaniel.rei.api.client.registry.entry.EntryRegistry; import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; import me.shedaniel.rei.api.common.util.CollectionUtils; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import org.jetbrains.annotations.Nullable; import java.util.Collection; -import java.util.List; -import java.util.Map; public class REIIntegration implements REIClientPlugin { public static final ResourceLocation ID = FTBLibrary.rl("sidebar_button"); @@ -75,127 +46,129 @@ public Collection> getAllResources() { SelectItemStackScreen.KNOWN_MODES.prependMode(REI_ITEMS); } - @Override - public void registerFavorites(FavoriteEntryType.Registry registry) { - registry.register(ID, SidebarButtonType.INSTANCE); - for (Map.Entry> entry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { - List buttons = entry.getValue() - .stream().map(SidebarButtonEntry::new).toList(); - SidebarButtonGroup group = entry.getKey(); - if (!buttons.isEmpty()) { - registry.getOrCrateSection(Component.translatable(group.getLangKey())) - .add(group.isPinned(), buttons.toArray(new SidebarButtonEntry[0])); - } - } - } - - private static SidebarButton createSidebarButton(ResourceLocation id, JsonObject json) { - DataResult parse = SidebarButtonData.CODEC.parse(JsonOps.INSTANCE, json); - if (parse.error().isPresent()) { - FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); - } else { - SidebarButtonData sidebarButtonData = parse.result().get(); - SidebarButton sidebarButton = new SidebarButton(id, sidebarButtonData); - SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(sidebarButton)); - return sidebarButton; - } - return null; - } - - private enum SidebarButtonType implements FavoriteEntryType { - INSTANCE; - - @Override - public CompoundTag save(SidebarButtonEntry entry, CompoundTag tag) { - tag.putString("id", entry.button.getId().toString()); - DataResult encode = SidebarButtonData.CODEC.encode(entry.button.getData(), NbtOps.INSTANCE, null); - encode.result().ifPresent(t -> tag.put("json", t)); - return tag; - } - - @Override - public DataResult read(CompoundTag object) { - ResourceLocation id = ResourceLocation.parse(object.getString("id")); - DataResult> json = SidebarButtonData.CODEC.decode(NbtOps.INSTANCE, object.get("json")); - return json.map(pair -> new SidebarButtonEntry(new SidebarButton(id, pair.getFirst()))); - } - - @Override - //Todo fix this - public DataResult fromArgs(Object... args) { - if (args.length == 0) { - return DataResult.error(() -> "Cannot create SidebarButtonEntry from empty args!"); - } - if (!(args[0] instanceof ResourceLocation id)) { - return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected ResourceLocation as the first argument!"); - } - if (!(args[1] instanceof SidebarButton button) && !(args[1] instanceof JsonObject)) { - return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected SidebarButton or JsonObject as the second argument!"); - } - return DataResult.success(new SidebarButtonEntry(args[1] instanceof SidebarButton button ? button : createSidebarButton(id, (JsonObject) args[1])), Lifecycle.stable()); - } - } - - private static class SidebarButtonEntry extends FavoriteEntry { - private final SidebarButton button; - - public SidebarButtonEntry(SidebarButton button) { - this.button = button; - } - - @Override - public boolean isInvalid() { - return button.canSee(); - } - - @Override - public Renderer getRenderer(boolean showcase) { - return new Renderer() { - @Override - public void render(GuiGraphics graphics, Rectangle bounds, int mouseX, int mouseY, float delta) { - GuiHelper.setupDrawing(); - button.getData().icon().draw(graphics, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); - for (ButtonOverlayRender extraRenderer : button.getExtraRenderers()) { - extraRenderer.render(graphics, Minecraft.getInstance().font, 16); - } - } - - @Override - @Nullable - public Tooltip getTooltip(TooltipContext context) { - return Tooltip.create(context.getPoint(), button.getTooltip()); - } - }; - } - - @Override - public boolean doAction(int button) { - this.button.clickButton(Screen.hasShiftDown()); - return true; - } - - @Override - public long hashIgnoreAmount() { - return this.button.getId().hashCode(); - } - - @Override - public FavoriteEntry copy() { - //Todo fix this? - return new SidebarButtonEntry(button); - } - - @Override - public ResourceLocation getType() { - return ID; - } - - @Override - public boolean isSame(FavoriteEntry other) { - if (other instanceof SidebarButtonEntry entry) { - return entry.button.getId().equals(button.getId()); - } - return false; - } - } +// @Override +// public void registerFavorites(FavoriteEntryType.Registry registry) { +// registry.register(ID, SidebarButtonType.INSTANCE); +// for (Map.Entry> entry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { +// List buttons = entry.getValue() +// .stream().map(SidebarButtonEntry::new).toList(); +// SidebarButtonGroup group = entry.getKey(); +// if (!buttons.isEmpty()) { +// registry.getOrCrateSection(Component.translatable(group.getLangKey())) +// .add(group.isPinned(), buttons.toArray(new SidebarButtonEntry[0])); +// } +// } +// } +// +// private static SidebarButton createSidebarButton(ResourceLocation id, JsonObject json) { +// DataResult parse = SidebarButtonData.CODEC.parse(JsonOps.INSTANCE, json); +// if (parse.error().isPresent()) { +// FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); +// } else { +// SidebarButtonData sidebarButtonData = parse.result().get(); +// SidebarButton sidebarButton = new SidebarButton(id, sidebarButtonData); +// SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(sidebarButton)); +// return sidebarButton; +// } +// return null; +// } +// +// private enum SidebarButtonType implements FavoriteEntryType { +// INSTANCE; +// +// @Override +// public CompoundTag save(SidebarButtonEntry entry, CompoundTag tag) { +// tag.putString("id", entry.button.getId().toString()); +// DataResult encode = SidebarButtonData.CODEC.encode(entry.button.getData(), NbtOps.INSTANCE, null); +// encode.result().ifPresent(t -> tag.put("json", t)); +// return tag; +// } +// +// @Override +// public DataResult read(CompoundTag object) { +// ResourceLocation id = ResourceLocation.parse(object.getString("id")); +// DataResult> json = SidebarButtonData.CODEC.decode(NbtOps.INSTANCE, object.get("json")); +// return json.map(pair -> new SidebarButtonEntry(new SidebarButton(id, pair.getFirst()))); +// } +// +// @Override +// //Todo fix this +// public DataResult fromArgs(Object... args) { +// if (args.length == 0) { +// return DataResult.error(() -> "Cannot create SidebarButtonEntry from empty args!"); +// } +// if (!(args[0] instanceof ResourceLocation id)) { +// return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected ResourceLocation as the first argument!"); +// } +// if (!(args[1] instanceof SidebarButton button) && !(args[1] instanceof JsonObject)) { +// return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected SidebarButton or JsonObject as the second argument!"); +// } +// return DataResult.success(new SidebarButtonEntry(args[1] instanceof SidebarButton button ? button : createSidebarButton(id, (JsonObject) args[1])), Lifecycle.stable()); +// } +// } +// +// private static class SidebarButtonEntry extends FavoriteEntry { +// private final SidebarButton button; +// +// public SidebarButtonEntry(SidebarButton button) { +// this.button = button; +// } +// +// @Override +// public boolean isInvalid() { +// return button.canSee(); +// } +// +// @Override +// public Renderer getRenderer(boolean showcase) { +// return new Renderer() { +// @Override +// public void render(GuiGraphics graphics, Rectangle bounds, int mouseX, int mouseY, float delta) { +// GuiHelper.setupDrawing(); +// if(bounds.getWidth() > 0 && bounds.getHeight() > 0) { +// button.getData().icon().draw(graphics, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); +// for (ButtonOverlayRender extraRenderer : button.getExtraRenderers()) { +// extraRenderer.render(graphics, Minecraft.getInstance().font, 16); +// } +// } +// } +// +// @Override +// @Nullable +// public Tooltip getTooltip(TooltipContext context) { +// return Tooltip.create(context.getPoint(), button.getTooltip()); +// } +// }; +// } +// +// @Override +// public boolean doAction(int button) { +// this.button.clickButton(Screen.hasShiftDown()); +// return true; +// } +// +// @Override +// public long hashIgnoreAmount() { +// return this.button.getId().hashCode(); +// } +// +// @Override +// public FavoriteEntry copy() { +// //Todo fix this? +// return new SidebarButtonEntry(button); +// } +// +// @Override +// public ResourceLocation getType() { +// return ID; +// } +// +// @Override +// public boolean isSame(FavoriteEntry other) { +// if (other instanceof SidebarButtonEntry entry) { +// return entry.button.getId().equals(button.getId()); +// } +// return false; +// } +// } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java index 4c337234..827fc360 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java @@ -86,9 +86,6 @@ public void setTooltipOverride(Supplier> tooltipOverride) { this.tooltipOverride = tooltipOverride; } - /** - * @return a list of custom button overlay renderers to render on top of the button icon - */ public List getExtraRenderers() { return extraRenderers; } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java index 7a0bb386..c021f48e 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java @@ -5,28 +5,23 @@ import dev.ftb.mods.ftblibrary.icon.Icon; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.ComponentSerialization; -import net.minecraft.resources.ResourceLocation; import java.util.List; import java.util.Optional; public record SidebarButtonData( - ResourceLocation group, Icon icon, - int x, boolean defaultEnabled, List clickEvents, Optional> shiftClickEvent, boolean loadingScreen, Optional tooltip, boolean requiresOp, - Optional> requiredMods) implements Comparable { + Optional> requiredMods) { public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( - ResourceLocation.CODEC.fieldOf("group").forGetter(SidebarButtonData::group), Icon.CODEC.fieldOf("icon").forGetter(SidebarButtonData::icon), - Codec.INT.fieldOf("x").forGetter(SidebarButtonData::x), Codec.BOOL.fieldOf("default_enabled").orElse(true).forGetter(SidebarButtonData::defaultEnabled), Codec.STRING.listOf(1, Integer.MAX_VALUE).fieldOf("click").forGetter(SidebarButtonData::clickEvents), Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("shift_click").forGetter(SidebarButtonData::shiftClickEvent), @@ -36,9 +31,4 @@ public record SidebarButtonData( Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("required_mods").forGetter(SidebarButtonData::requiredMods) ).apply(builder, SidebarButtonData::new)); - - @Override - public int compareTo(SidebarButtonData button) { - return x - button.x; - } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java deleted file mode 100644 index 49b97c2a..00000000 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonGroup.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.ftb.mods.ftblibrary.sidebar; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.MapCodec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import dev.ftb.mods.ftblibrary.icon.Icon; -import net.minecraft.Util; -import net.minecraft.resources.ResourceLocation; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - - -public record SidebarButtonGroup(int y, boolean isPinned) implements Comparable { - - - public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( - Codec.INT.fieldOf("y").forGetter(SidebarButtonGroup::y), - Codec.BOOL.fieldOf("isPinned").orElse(false).forGetter(SidebarButtonGroup::isPinned) - ).apply(builder, SidebarButtonGroup::new)); - - - public String getLangKey() { - //Todo -unreal - return Util.makeDescriptionId("sidebar_group", ResourceLocation.fromNamespaceAndPath("ftbquests", "sidebar_group_" + y)); - } - - @Override - public int compareTo(SidebarButtonGroup group) { - return y - group.y; - } -} diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index ab489a0f..631c02cd 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -8,6 +8,7 @@ import dev.ftb.mods.ftblibrary.FTBLibrary; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.snbt.config.StringSidebarMapValue; +import dev.ftb.mods.ftblibrary.util.MapUtils; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; @@ -32,12 +33,10 @@ public enum SidebarButtonManager implements ResourceManagerReloadListener { private static final Logger LOGGER = LogUtils.getLogger(); - private final Map groups = new HashMap<>(); private final Map buttons = new HashMap<>(); private final List buttonList = new ArrayList<>(); - private JsonElement readJson(Resource resource) { try (BufferedReader reader = resource.openAsReader()) { return JsonParser.parseReader(reader); @@ -53,28 +52,29 @@ public Collection getButtons() { @Override public void onResourceManagerReload(ResourceManager manager) { - groups.clear(); buttons.clear(); //Read the button and group json files and register them to their 'registry' map - loadResources(manager, "sidebar_buttons/groups", SidebarButtonGroup.CODEC, groups::put); - loadResources(manager, "sidebar_buttons/buttons", SidebarButtonData.CODEC, (id, buttonData) -> { - SidebarButtonGroup group = groups.get(buttonData.group()); - if(group != null) { - buttons.put(id, new SidebarButton(id, buttonData)); - }else { - LOGGER.error("Could not register button {} as group {} does not exist", id, buttonData.group()); - } - }); + loadResources(manager, "sidebar_buttons", SidebarButtonData.CODEC, (id, buttonData) -> buttons.put(id, new SidebarButton(id, buttonData))); buttonList.clear(); - for (SidebarButton buttonEntry : getButtons()) { - StringSidebarMapValue.SideButtonInfo buttonSettings = getOrCreateButtonSettings(buttonEntry); + int y = 0; + int x = 0; + for (SidebarButton buttonEntry : buttons.values()) { + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(buttonEntry.getId().toString()); + if(buttonSettings == null) { + buttonSettings = new StringSidebarMapValue.SideButtonInfo(true, x, y); + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(buttonEntry.getId().toString(), buttonSettings); + FTBLibraryClientConfig.save(); + } buttonList.add(new SidebarGuiButton(new GridLocation(buttonSettings.xPos(), buttonSettings.yPos()), buttonSettings.enabled(), buttonEntry)); + x++; + if(x >= 4) { + x = 0; + y++; + } } - FTBLibraryClientConfig.save(); - } private void loadResources(ResourceManager manager, String path, Codec codec, BiConsumer consumer) { @@ -94,23 +94,7 @@ private void loadResources(ResourceManager manager, String path, Codec co } } - - private StringSidebarMapValue.SideButtonInfo getOrCreateButtonSettings(SidebarButton button) { - StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getId().toString()); - if(buttonSettings == null) { - buttonSettings = new StringSidebarMapValue.SideButtonInfo(true, button.getData().x(), groups.get(button.getData().group()).y()); - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getId().toString(), buttonSettings); - FTBLibraryClientConfig.save(); - } - return buttonSettings; - } - - private boolean isRegistered(ResourceLocation id) { - return buttons.values().stream().anyMatch(button -> button.getId().equals(id)); - } - public void saveConfigFromButtonList() { - Map> buttonMap = new HashMap<>(); for (SidebarGuiButton button : getButtonList()) { int y = button.isEnabled() ? button.getGirdLocation().y() : -1; @@ -118,7 +102,7 @@ public void saveConfigFromButtonList() { } int y = 0; - for (Map.Entry> integerListEntry : Utils.sortMapByKey(buttonMap).entrySet()) { + for (Map.Entry> integerListEntry : MapUtils.sortMapByKey(buttonMap).entrySet()) { if(integerListEntry.getKey() == -1) { for (SidebarGuiButton button : integerListEntry.getValue()) { button.setGridLocation(-1, -1); @@ -141,7 +125,6 @@ public void saveConfigFromButtonList() { } } - for (SidebarGuiButton button : buttonList) { StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getSidebarButton().getId().toString()); if(buttonSettings != null) { @@ -149,9 +132,8 @@ public void saveConfigFromButtonList() { } } FTBLibraryClientConfig.save(); - } -// + public List getButtonList() { return buttonList; } @@ -170,42 +152,4 @@ public List getDisabledButtonList(boolean all) { .collect(Collectors.toList()); } - - public Map> getButtonGroups() { - Map> buttonMap = new HashMap<>(); - for (SidebarButton buttonData : this.buttons.values()) { - buttonMap.computeIfAbsent(groups.get(buttonData.getData().group()), k -> new ArrayList<>()).add(buttonData); - } - - return Utils.sortMapByKey(buttonMap); - } - - - - //Todo cleanup - public static class Utils { - - public static Map sortMapByKey(Map map, Comparator comparator) { - return map.entrySet().stream() - .sorted(Map.Entry.comparingByKey(comparator)) - .collect(Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue, - (a, b) -> a, - HashMap::new - )); - } - - public static, V> Map sortMapByKey(Map map) { - return map.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .collect(Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue, - (a, b) -> a, - HashMap::new - )); - } - } - } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index 7134e696..985fd9d8 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -3,6 +3,7 @@ import dev.ftb.mods.ftblibrary.api.sidebar.ButtonOverlayRender; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.icon.Color4I; +import dev.ftb.mods.ftblibrary.icon.Icon; import dev.ftb.mods.ftblibrary.icon.Icons; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import net.minecraft.client.Minecraft; @@ -10,9 +11,11 @@ import net.minecraft.client.gui.components.AbstractButton; import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.client.renderer.Rect2i; import net.minecraft.client.resources.language.I18n; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; import java.util.ArrayList; import java.util.Comparator; @@ -20,6 +23,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.TreeMap; import java.util.stream.Collectors; @@ -97,72 +101,69 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { graphics.pose().translate(0, 0, 50); - for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { - graphics.pose().pushPose(); - GridLocation realGridLocation = realLocationMap.get(button); - if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { - if (isEditMode && button == selectedButton) { - graphics.pose().translate(0, 0, 1000); - button.x = mx - mouseOffsetX; - button.y = my - mouseOffsetY; - } else { - if (realGridLocation == null) { - continue; - } - int adjustedX = gridStartRight ? xRenderStart + (currentGirdWidth - realGridLocation.x() - 1) * BUTTON_SPACING : xRenderStart + realGridLocation.x() * BUTTON_SPACING; - int adjustedY = gridStartBottom ? yRenderStart + (currentGridHeight - realGridLocation.y() - 1) * BUTTON_SPACING : yRenderStart + realGridLocation.y() * BUTTON_SPACING; - - button.x = adjustedX + 1; - button.y = adjustedY + 1; - } - GuiHelper.setupDrawing(); - button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); - - if (isEditMode && button != selectedButton && SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1) { - if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { - Icons.CANCEL.draw(graphics, button.x + 11, button.y - 1, 6, 6); - } else { - Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); - } - } - - if (button == mouseOver) { - Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); - } - - graphics.pose().translate(button.x, button.y, 0); - for (ButtonOverlayRender buttonOverlayRender : button.getSidebarButton().getExtraRenderers()) { - buttonOverlayRender.render(graphics, font, 16); - } - graphics.pose().translate(-button.x, -button.y, 0); - - } - if (!isEditMode && mouseOver == button) { - graphics.pose().pushPose(); - GuiHelper.setupDrawing(); - var mx1 = mx + 10; - var my1 = Math.max(3, my - 9); + //If there are no sidebar buttons enabled render "fake" button + if (!isEditMode && SidebarButtonManager.INSTANCE.getEnabledButtonList(false).isEmpty()) { + + if(mx >= xRenderStart + 2 && my >= yRenderStart + 2 && mx < xRenderStart + 18 && my < yRenderStart + 18) { + String enabledText = I18n.get("ftblibrary.sidebar.no_buttons.enabled"); + String infoText = I18n.get("ftblibrary.sidebar.no_buttons.info"); + int maxWidth = Math.max(font.width(enabledText), font.width(infoText)); + graphics.drawString(font, enabledText, xRenderStart + 20, yRenderStart + 4, 0xFFFFFFFF); + graphics.drawString(font, infoText, xRenderStart + 20, yRenderStart + 12, 0xFFFFFFFF); + Color4I.DARK_GRAY.draw(graphics, xRenderStart + 2, yRenderStart + 2, maxWidth + 16, 16); + graphics.renderTooltip(font, List.of(Component.translatable("ftblibrary.sidebar.no_buttons.enabled"), Component.translatable("ftblibrary.sidebar.no_buttons.info")), Optional.empty(), mx, my + 5); + } + Icons.INFO.draw(graphics, xRenderStart + 2, yRenderStart + 2, 16, 16); + + } else { + for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { + graphics.pose().pushPose(); + GridLocation realGridLocation = realLocationMap.get(button); + if (isEditMode || (button.equals(selectedButton) || button.isEnabled())) { + if (isEditMode && button == selectedButton) { + graphics.pose().translate(0, 0, 1000); + button.x = mx - mouseOffsetX; + button.y = my - mouseOffsetY; + } else { + if (realGridLocation == null) { + continue; + } + int adjustedX = gridStartRight ? xRenderStart + (currentGirdWidth - realGridLocation.x() - 1) * BUTTON_SPACING : xRenderStart + realGridLocation.x() * BUTTON_SPACING; + int adjustedY = gridStartBottom ? yRenderStart + (currentGridHeight - realGridLocation.y() - 1) * BUTTON_SPACING : yRenderStart + realGridLocation.y() * BUTTON_SPACING; - List list = new ArrayList<>(); - list.add(I18n.get(mouseOver.getSidebarButton().getLangKey())); + button.x = adjustedX + 1; + button.y = adjustedY + 1; + } + GuiHelper.setupDrawing(); + button.getSidebarButton().getData().icon().draw(graphics, button.x, button.y, 16, 16); + + if (isEditMode) { + if (mx >= button.x + 12 && my <= button.y + 4 && mx < button.x + 16 && my >= button.y) { + Icons.CANCEL.draw(graphics, button.x + 11, button.y - 1, 6, 6); + } else { + Icons.CANCEL.draw(graphics, button.x + 12, button.y, 4, 4); + } + } - var tw = 0; + if (button == mouseOver) { + Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); + } - for (String s : list) { - tw = Math.max(tw, font.width(s)); - } - int fixedMouseX = gridStartRight ? mx1 - tw - 6 : mx1; - graphics.pose().translate(0, 0, 50); - Color4I.DARK_GRAY.draw(graphics, fixedMouseX - 3, my1 - 2, tw + 6, 2 + list.size() * 10); + graphics.pose().translate(button.x, button.y, 0); + for (ButtonOverlayRender buttonOverlayRender : button.getSidebarButton().getExtraRenderers()) { + buttonOverlayRender.render(graphics, font, 16); + } + graphics.pose().translate(-button.x, -button.y, 0); - for (var i = 0; i < list.size(); i++) { - graphics.drawString(font, list.get(i), fixedMouseX, my1 + i * 10, 0xFFFFFFFF); - } - graphics.pose().popPose(); - } - graphics.pose().popPose(); - } - } + } + if (!isEditMode && mouseOver == button) { + MutableComponent translatable = Component.translatable(mouseOver.getSidebarButton().getLangKey()); + graphics.renderTooltip(font, translatable, mx, Math.max(7, my - 9) + 10); + } + graphics.pose().popPose(); + } + } + } private void renderEditMode(GuiGraphics graphics, int mx, int my) { drawHoveredGrid(graphics, xRenderStart, yRenderStart, currentGirdWidth, currentGridHeight, BUTTON_SPACING, Color4I.GRAY.withAlpha(70), Color4I.BLACK.withAlpha(90), mx, my, gridStartBottom, gridStartRight, getX(), getY()); @@ -272,6 +273,7 @@ public void onRelease(double d, double e) { } } + //Aligns icons to a 'realLocationMap' this uses the button config as base, but checks if button is "visible" then aligns it to the grid private void ensureGridAlignment() { List enabledButtonList = SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode); Map> buttonMap = enabledButtonList @@ -295,7 +297,6 @@ private void ensureGridAlignment() { } - SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); updateWidgetSize(); } @@ -306,6 +307,7 @@ private void updateWidgetSize() { // of its GUI areas, including resetting the filter textfield's selection // https://github.com/FTBTeam/FTB-Mods-Issues/issues/262 // https://github.com/mezz/JustEnoughItems/issues/2938 + //This calculates the grid size int girdAmountX = 1; int girdAmountY = 1; for (SidebarGuiButton b : SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode)) { @@ -313,16 +315,19 @@ private void updateWidgetSize() { girdAmountY = Math.max(girdAmountY, b.getGirdLocation().y() + 1); } - int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).size(); if(isEditMode && addBoxOpen) { + int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).size(); girdAmountX += 4; girdAmountY = Math.max(girdAmountY, disabledList); } if(isEditMode) { + //Add 3 extra to the x so that add button is clickable girdAmountX += 3; + //Add one extra y, so you can place widgets at the bottom girdAmountY += 1; } + //ensure the grid size is not bigger than the screen int screenWidth = Minecraft.getInstance().getWindow().getGuiScaledWidth(); int screenHeight = Minecraft.getInstance().getWindow().getGuiScaledHeight(); @@ -335,7 +340,7 @@ private void updateWidgetSize() { width = (girdAmountX) * BUTTON_SPACING; height = (girdAmountY) * BUTTON_SPACING; - FTBLibraryClientConfig.SidebarPosition sidebarPosition = FTBLibraryClientConfig.POSITION.get(); + FTBLibraryClientConfig.SidebarPosition sidebarPosition = FTBLibraryClientConfig.SIDEBAR_POSITION.get(); if (sidebarPosition.isBottom()) { setY(screenHeight - height - 2); @@ -376,6 +381,7 @@ private void updateWidgetSize() { xRenderStart += 3; } + //Set the last drawn area so recipe viewer knows where we are and we can move it out the way lastDrawnArea = new Rect2i(getX(), getY(), width, height); } @@ -408,14 +414,14 @@ public void onPress() { return; } } - + isMouseDown = true; if(mouseOver != null) { - isMouseDown = true; + mouseOffsetX = currentMouseX - mouseOver.x; mouseOffsetY = currentMouseY - mouseOver.y; if(isEditMode) { - if(SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode).size() > 1 && currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4 && currentMouseX < mouseOver.x + 16 && currentMouseY >= mouseOver.y) { + if(currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4 && currentMouseX < mouseOver.x + 16 && currentMouseY >= mouseOver.y) { mouseOver.setEnabled(false); mouseOver = null; ensureGridAlignment(); @@ -442,7 +448,8 @@ protected boolean isValidClickButton(int i) { if (isEditMode) { return isMouseOverAdd || selectedButton != null || mouseOver != null; } else { - return mouseOver != null; + GridLocation gridLocation = getGridLocation(); + return (gridLocation.y() == 0 && gridLocation.x() == 0) || mouseOver != null; } } return false; @@ -497,4 +504,5 @@ private static void drawHoveredGrid(GuiGraphics graphics, int x, int y, int widt Color4I.WHITE.withAlpha(127).draw(graphics, gridX * BUTTON_SPACING + 1, gridY * BUTTON_SPACING + 1, spacing - 1, spacing - 1); } } + } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/util/MapUtils.java b/common/src/main/java/dev/ftb/mods/ftblibrary/util/MapUtils.java new file mode 100644 index 00000000..62a71996 --- /dev/null +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/util/MapUtils.java @@ -0,0 +1,31 @@ +package dev.ftb.mods.ftblibrary.util; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +public class MapUtils { + + public static Map sortMapByKey(Map map, Comparator comparator) { + return map.entrySet().stream() + .sorted(Map.Entry.comparingByKey(comparator)) + .collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (a, b) -> a, + HashMap::new + )); + } + + public static , V> Map sortMapByKey(Map map) { + return map.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (a, b) -> a, + HashMap::new + )); + } +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/lang/en_us.json b/common/src/main/resources/assets/ftblibrary/lang/en_us.json index c539bb2c..67af51bd 100644 --- a/common/src/main/resources/assets/ftblibrary/lang/en_us.json +++ b/common/src/main/resources/assets/ftblibrary/lang/en_us.json @@ -100,5 +100,7 @@ "dimension.hyperbox.hyperbox": "Hyperbox", "dimension.ae2.spatial_storage": "AE2 Spatial Storage", "itemGroup.ftbsuite.creative_tab": "FTB Suite", - "item.ftblibrary.icon_item": "FTB Icon" + "item.ftblibrary.icon_item": "FTB Icon", + "ftblibrary.sidebar.no_buttons.enabled": "No Sidebar Buttons Enabled", + "ftblibrary.sidebar.no_buttons.info": "You can disabled sidebar buttons in the FTB Client Library config" } diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/cheat.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/cheat.json deleted file mode 100644 index aeb1983d..00000000 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/cheat.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "y": 100 -} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/info.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/info.json deleted file mode 100644 index aa39d60f..00000000 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/info.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "y": 0 -} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/util.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/util.json deleted file mode 100644 index 9de532d4..00000000 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/groups/util.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "y": 200 -} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/test.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json similarity index 95% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/test.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json index 7c869978..820fa37c 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/test.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json @@ -4,7 +4,6 @@ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/camera.png" ], - "x": 120, "click": ["command:/say hi"], "required_mods": [ "ftblibrary", diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/day.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/day.json similarity index 82% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/day.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/day.json index 4a18f734..2b469f04 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/day.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/day.json @@ -1,10 +1,8 @@ { - "group": "ftblibrary:cheat", "icon": [ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_day.png" ], - "x": 120, "click": ["command:/ftblibrary day"], "required_mods": [ "ftblibrary" diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/gamemode.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/gamemode.json similarity index 80% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/gamemode.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/gamemode.json index a4ff3e19..827062ea 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/gamemode.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/gamemode.json @@ -1,10 +1,8 @@ { - "group": "ftblibrary:cheat", "icon": [ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_gamemode.png" ], - "x": 100, "click": ["command:/ftblibrary gamemode"], "requires_op": true } \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/night.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/night.json similarity index 83% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/night.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/night.json index 028676ad..e8329c6e 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/night.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/night.json @@ -1,10 +1,8 @@ { - "group": "ftblibrary:cheat", "icon": [ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_night.png" ], - "x": 130, "click": ["command:/ftblibrary night"], "required_mods": [ "ftblibrary" diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/rain.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/rain.json similarity index 79% rename from common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/rain.json rename to common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/rain.json index 3175127d..2dc545e3 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/buttons/toggle/rain.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/rain.json @@ -1,10 +1,8 @@ { - "group": "ftblibrary:cheat", "icon": [ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_rain.png" ], - "x": 80, "click": ["command:/ftblibrary rain"], "requires_op": true } \ No newline at end of file diff --git a/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java b/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java new file mode 100644 index 00000000..da910c34 --- /dev/null +++ b/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java @@ -0,0 +1,24 @@ +package dev.ftb.mods.ftblibrary.core.mixin.fabric; + +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.network.chat.Component; +import org.spongepowered.asm.mixin.Debug; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(AbstractContainerScreen.class) +@Debug(export = true) +public abstract class AbstractContainerScreenMixin extends Screen { + + protected AbstractContainerScreenMixin(Component component) { + super(component); + } + + @Inject(at = @At("HEAD"), method = "mouseReleased") + public void onMouseReleased(double mouseX, double mouseY, int button, CallbackInfoReturnable info) { + super.mouseReleased(mouseX, mouseY, button); + } +} diff --git a/fabric/src/main/resources/ftblibrary-fabric.mixins.json b/fabric/src/main/resources/ftblibrary-fabric.mixins.json index 71041dcc..a961dbb9 100644 --- a/fabric/src/main/resources/ftblibrary-fabric.mixins.json +++ b/fabric/src/main/resources/ftblibrary-fabric.mixins.json @@ -6,6 +6,7 @@ "PlayerMixin" ], "client": [ + "AbstractContainerScreenMixin", "KeyMappingAccessor" ], "injectors": { diff --git a/gradle.properties b/gradle.properties index 2b7f0750..9cf3a21e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -20,7 +20,7 @@ neoforge_version=21.0.146 neoforge_version_range=[21.0.143,) neoforge_loader_version=4 fabric_loader_version=0.15.11 -fabric_api_version=0.100.8+1.21 +fabric_api_version=0.101.2+1.21 fabric_api_version_range=>=0.100.1+1.21 architectury_version=13.0.2 From 5fe38dff8bd2fe9d3c436594f34e2e9c7d88991b Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Wed, 7 Aug 2024 16:38:04 -0500 Subject: [PATCH 11/17] Add REI exclude zone, more code comments --- .../api/sidebar/ButtonOverlayRender.java | 8 ++++++ .../integration/REIIntegration.java | 18 ++++++++++++- .../sidebar/SidebarGroupGuiButton.java | 26 +++++++++---------- 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java index b509ef17..d8f9f0aa 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java @@ -8,6 +8,14 @@ import java.util.function.Supplier; public interface ButtonOverlayRender { + + /** + * @param graphics The graphics object + * @param font The font object + * @param buttonSize The size of the button + * Called when the button is rendering + * graphics is aligned so that 0, 0 is the top left corner of the button + */ void render(GuiGraphics graphics, Font font, int buttonSize); static ButtonOverlayRender ofSimpleString(Supplier customTextHandler) { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java index d91b414a..2519c440 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java @@ -6,10 +6,16 @@ import dev.ftb.mods.ftblibrary.config.ui.SelectableResource; import dev.ftb.mods.ftblibrary.icon.Icon; import dev.ftb.mods.ftblibrary.icon.ItemIcon; +import dev.ftb.mods.ftblibrary.sidebar.SidebarGroupGuiButton; +import me.shedaniel.math.Rectangle; import me.shedaniel.rei.api.client.plugins.REIClientPlugin; import me.shedaniel.rei.api.client.registry.entry.EntryRegistry; +import me.shedaniel.rei.api.client.registry.screen.ExclusionZones; +import me.shedaniel.rei.api.client.registry.screen.ExclusionZonesProvider; import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; import me.shedaniel.rei.api.common.util.CollectionUtils; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.renderer.Rect2i; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; @@ -17,6 +23,7 @@ import net.minecraft.world.item.Items; import java.util.Collection; +import java.util.List; public class REIIntegration implements REIClientPlugin { public static final ResourceLocation ID = FTBLibrary.rl("sidebar_button"); @@ -46,7 +53,16 @@ public Collection> getAllResources() { SelectItemStackScreen.KNOWN_MODES.prependMode(REI_ITEMS); } -// @Override + @Override + public void registerExclusionZones(ExclusionZones zones) { + zones.register(AbstractContainerScreen.class, screen -> { + Rect2i lastDrawnArea = SidebarGroupGuiButton.lastDrawnArea; + Rectangle sidebar = new Rectangle(lastDrawnArea.getX(), lastDrawnArea.getY(), lastDrawnArea.getWidth(), lastDrawnArea.getHeight()); + return List.of(sidebar); + }); + } + + // @Override // public void registerFavorites(FavoriteEntryType.Registry registry) { // registry.register(ID, SidebarButtonType.INSTANCE); // for (Map.Entry> entry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index 985fd9d8..526b45c5 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -3,7 +3,6 @@ import dev.ftb.mods.ftblibrary.api.sidebar.ButtonOverlayRender; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.icon.Color4I; -import dev.ftb.mods.ftblibrary.icon.Icon; import dev.ftb.mods.ftblibrary.icon.Icons; import dev.ftb.mods.ftblibrary.ui.GuiHelper; import net.minecraft.client.Minecraft; @@ -11,13 +10,11 @@ import net.minecraft.client.gui.components.AbstractButton; import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.client.renderer.Rect2i; import net.minecraft.client.resources.language.I18n; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; -import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; @@ -28,9 +25,15 @@ import java.util.stream.Collectors; public class SidebarGroupGuiButton extends AbstractButton { + public static Rect2i lastDrawnArea = new Rect2i(0, 0, 0, 0); private static final int BUTTON_SPACING = 17; + private static final List noButtonComponents = List.of( + Component.translatable("ftblibrary.sidebar.no_buttons.enabled"), + Component.translatable("ftblibrary.sidebar.no_buttons.info")); + + private SidebarGuiButton mouseOver; private SidebarGuiButton selectedButton; private GridLocation selectedLocation; @@ -103,17 +106,11 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { //If there are no sidebar buttons enabled render "fake" button if (!isEditMode && SidebarButtonManager.INSTANCE.getEnabledButtonList(false).isEmpty()) { - - if(mx >= xRenderStart + 2 && my >= yRenderStart + 2 && mx < xRenderStart + 18 && my < yRenderStart + 18) { - String enabledText = I18n.get("ftblibrary.sidebar.no_buttons.enabled"); - String infoText = I18n.get("ftblibrary.sidebar.no_buttons.info"); - int maxWidth = Math.max(font.width(enabledText), font.width(infoText)); - graphics.drawString(font, enabledText, xRenderStart + 20, yRenderStart + 4, 0xFFFFFFFF); - graphics.drawString(font, infoText, xRenderStart + 20, yRenderStart + 12, 0xFFFFFFFF); - Color4I.DARK_GRAY.draw(graphics, xRenderStart + 2, yRenderStart + 2, maxWidth + 16, 16); - graphics.renderTooltip(font, List.of(Component.translatable("ftblibrary.sidebar.no_buttons.enabled"), Component.translatable("ftblibrary.sidebar.no_buttons.info")), Optional.empty(), mx, my + 5); + if(mx >= xRenderStart + 2 && my >= yRenderStart + 2 && mx < xRenderStart + 18 && my < yRenderStart + 18) { + graphics.renderTooltip(font, noButtonComponents, Optional.empty(), mx, my + 5); + Color4I.WHITE.withAlpha(33).draw(graphics, xRenderStart + 1, yRenderStart + 1, 16, 16); } - Icons.INFO.draw(graphics, xRenderStart + 2, yRenderStart + 2, 16, 16); + Icons.INFO.draw(graphics, xRenderStart + 1, yRenderStart + 1, 16, 16); } else { for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { @@ -149,11 +146,12 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); } + graphics.pose().pushPose(); graphics.pose().translate(button.x, button.y, 0); for (ButtonOverlayRender buttonOverlayRender : button.getSidebarButton().getExtraRenderers()) { buttonOverlayRender.render(graphics, font, 16); } - graphics.pose().translate(-button.x, -button.y, 0); + graphics.pose().popPose(); } if (!isEditMode && mouseOver == button) { From a8b4f644c1edbf724d2ab69aac60523fda2a5370 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Thu, 8 Aug 2024 10:38:40 -0500 Subject: [PATCH 12/17] Add Setting sidebar button, Change edit mode enable to right click --- .../ftb/mods/ftblibrary/FTBLibraryClient.java | 9 --- .../config/FTBLibraryClientConfig.java | 2 +- .../ftblibrary/sidebar/SidebarButton.java | 22 +++++-- .../ftblibrary/sidebar/SidebarButtonData.java | 17 ++++-- .../sidebar/SidebarButtonManager.java | 7 ++- .../sidebar/SidebarGroupGuiButton.java | 61 +++++++++++-------- .../assets/ftblibrary/lang/en_us.json | 14 +++-- .../ftblibrary/sidebar_button_groups.json | 12 ---- .../assets/ftblibrary/sidebar_buttons.json | 53 ---------------- .../ftblibrary/sidebar_buttons/config.json | 13 ++++ .../ftblibrary/sidebar_buttons/test.json | 2 +- .../sidebar_buttons/toggle/day.json | 1 + .../sidebar_buttons/toggle/gamemode.json | 1 + .../sidebar_buttons/toggle/night.json | 1 + .../sidebar_buttons/toggle/rain.json | 1 + .../fabric/AbstractContainerScreenMixin.java | 10 +-- 16 files changed, 103 insertions(+), 123 deletions(-) delete mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_button_groups.json delete mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons.json create mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/config.json diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java index 22964828..c4a09456 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java @@ -62,15 +62,6 @@ private static void clientTick(Minecraft client) { ClientUtils.RUN_LATER.clear(); } - - if(areButtonsVisible(client.screen)) { - for (GuiEventListener child : client.screen.children()) { - if(child instanceof SidebarGroupGuiButton button) { - button.tick(); - } - } - } - } public static boolean areButtonsVisible(@Nullable Screen gui) { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java b/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java index cd10e806..63bc54df 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/config/FTBLibraryClientConfig.java @@ -75,6 +75,6 @@ public boolean isRight() { return isRight; } - public static final NameMap NAME_MAP = NameMap.of(TOP_LEFT, SidebarPosition.values()).create(); + public static final NameMap NAME_MAP = NameMap.of(TOP_LEFT, SidebarPosition.values()).baseNameKey("ftblibrary.panel.position").create(); } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java index 827fc360..3058b0c0 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java @@ -11,7 +11,9 @@ import net.minecraft.resources.ResourceLocation; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; +import java.util.Optional; import java.util.function.BooleanSupplier; import java.util.function.Supplier; @@ -21,17 +23,16 @@ public class SidebarButton implements dev.ftb.mods.ftblibrary.api.sidebar.Sideba private final SidebarButtonData data; private final ResourceLocation id; private final String langKey; - private final Component basicTooltip; + private final Component tooltip; private final List extraRenderers; private Supplier> tooltipOverride; private ChainedBooleanSupplier visible = ChainedBooleanSupplier.TRUE; - public SidebarButton(ResourceLocation id, SidebarButtonData data) { this.id = id; this.data = data; this.langKey = Util.makeDescriptionId("sidebar_button", id); - basicTooltip = Component.translatable(langKey + ".tooltip"); + tooltip = Component.translatable(langKey + ".tooltip"); if(data.requiresOp()) { addVisibilityCondition(ClientUtils.IS_CLIENT_OP); } @@ -53,8 +54,19 @@ public String getLangKey() { return langKey; } - public List getTooltip() { - return tooltipOverride == null ? List.of(basicTooltip) : tooltipOverride.get(); + public List getTooltip(boolean shift) { + if(tooltipOverride != null) { + return tooltipOverride.get(); + }else { + List tooltips = new ArrayList<>(); + tooltips.add(Component.translatable(langKey)); + if(shift) { + tooltips.add(tooltip); + } + Optional> components = shift ? data.shiftTooltip() : data.tooltip(); + components.ifPresent(tooltips::addAll); + return tooltips; + } } public void clickButton(boolean shift) { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java index c021f48e..b2df2f38 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java @@ -5,6 +5,7 @@ import dev.ftb.mods.ftblibrary.icon.Icon; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.ComponentSerialization; +import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Optional; @@ -16,9 +17,11 @@ public record SidebarButtonData( List clickEvents, Optional> shiftClickEvent, boolean loadingScreen, - Optional tooltip, + Optional> tooltip, + Optional> shiftTooltip, boolean requiresOp, - Optional> requiredMods) { + Optional> requiredMods, + int sortIndex) implements Comparable { public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( Icon.CODEC.fieldOf("icon").forGetter(SidebarButtonData::icon), @@ -26,9 +29,15 @@ public record SidebarButtonData( Codec.STRING.listOf(1, Integer.MAX_VALUE).fieldOf("click").forGetter(SidebarButtonData::clickEvents), Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("shift_click").forGetter(SidebarButtonData::shiftClickEvent), Codec.BOOL.fieldOf("loading_screen").orElse(false).forGetter(SidebarButtonData::loadingScreen), - ComponentSerialization.CODEC.optionalFieldOf("tooltip").forGetter(SidebarButtonData::tooltip), + ComponentSerialization.CODEC.listOf().optionalFieldOf("tooltip").forGetter(SidebarButtonData::tooltip), + ComponentSerialization.CODEC.listOf().optionalFieldOf("shift_tooltip").forGetter(SidebarButtonData::shiftTooltip), Codec.BOOL.fieldOf("requires_op").orElse(false).forGetter(SidebarButtonData::requiresOp), - Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("required_mods").forGetter(SidebarButtonData::requiredMods) + Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("required_mods").forGetter(SidebarButtonData::requiredMods), + Codec.INT.fieldOf("sort_index").orElse(0).forGetter(SidebarButtonData::sortIndex) ).apply(builder, SidebarButtonData::new)); + @Override + public int compareTo(@NotNull SidebarButtonData o) { + return Integer.compare(sortIndex, o.sortIndex); + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index 631c02cd..7431c595 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.ToIntFunction; import java.util.stream.Collectors; @@ -58,9 +59,10 @@ public void onResourceManagerReload(ResourceManager manager) { loadResources(manager, "sidebar_buttons", SidebarButtonData.CODEC, (id, buttonData) -> buttons.put(id, new SidebarButton(id, buttonData))); buttonList.clear(); + List sortedButtons = buttons.values().stream().sorted(Comparator.comparingInt(value -> value.getData().sortIndex())).toList(); int y = 0; int x = 0; - for (SidebarButton buttonEntry : buttons.values()) { + for (SidebarButton buttonEntry : sortedButtons) { StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(buttonEntry.getId().toString()); if(buttonSettings == null) { buttonSettings = new StringSidebarMapValue.SideButtonInfo(true, x, y); @@ -74,6 +76,9 @@ public void onResourceManagerReload(ResourceManager manager) { y++; } } + for (SidebarButton value : buttons.values()) { + SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(value)); + } FTBLibraryClientConfig.save(); } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index 526b45c5..a516e40a 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -1,5 +1,6 @@ package dev.ftb.mods.ftblibrary.sidebar; +import dev.ftb.mods.ftblibrary.FTBLibraryClient; import dev.ftb.mods.ftblibrary.api.sidebar.ButtonOverlayRender; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.icon.Color4I; @@ -15,6 +16,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; +import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; @@ -30,15 +32,14 @@ public class SidebarGroupGuiButton extends AbstractButton { private static final int BUTTON_SPACING = 17; private static final List noButtonComponents = List.of( - Component.translatable("ftblibrary.sidebar.no_buttons.enabled"), - Component.translatable("ftblibrary.sidebar.no_buttons.info")); + Component.translatable("sidebar_button.ftblibrary.config"), + Component.translatable("sidebar_button.ftblibrary.config.enter_edit_mode")); private SidebarGuiButton mouseOver; private SidebarGuiButton selectedButton; private GridLocation selectedLocation; - private boolean isMouseDown; - private int mouseDownTime; + private int lastMouseClickButton = 0; private boolean isEditMode; private int currentMouseX; @@ -59,12 +60,12 @@ public class SidebarGroupGuiButton extends AbstractButton { int xRenderStart; private boolean isMouseOverAdd; + private boolean mouseOverSettingsIcon; private final Map realLocationMap = new HashMap<>(); public SidebarGroupGuiButton() { super(0, 0, 0, 0, Component.empty()); - isMouseDown = false; ensureGridAlignment(); } @@ -79,6 +80,7 @@ public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTick currentMouseY = my; mouseOver = null; isMouseOverAdd = false; + mouseOverSettingsIcon = false; GridLocation gridLocation = getGridLocation(); @@ -109,8 +111,9 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { if(mx >= xRenderStart + 2 && my >= yRenderStart + 2 && mx < xRenderStart + 18 && my < yRenderStart + 18) { graphics.renderTooltip(font, noButtonComponents, Optional.empty(), mx, my + 5); Color4I.WHITE.withAlpha(33).draw(graphics, xRenderStart + 1, yRenderStart + 1, 16, 16); + mouseOverSettingsIcon = true; } - Icons.INFO.draw(graphics, xRenderStart + 1, yRenderStart + 1, 16, 16); + Icons.SETTINGS.draw(graphics, xRenderStart + 1, yRenderStart + 1, 16, 16); } else { for (SidebarGuiButton button : SidebarButtonManager.INSTANCE.getButtonList()) { @@ -155,8 +158,7 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { } if (!isEditMode && mouseOver == button) { - MutableComponent translatable = Component.translatable(mouseOver.getSidebarButton().getLangKey()); - graphics.renderTooltip(font, translatable, mx, Math.max(7, my - 9) + 10); + graphics.renderTooltip(font, button.getSidebarButton().getTooltip(Screen.hasShiftDown()), Optional.empty(), mx, Math.max(7, my - 9) + 10); } graphics.pose().popPose(); } @@ -217,8 +219,8 @@ private void renderEditMode(GuiGraphics graphics, int mx, int my) { button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); String langText = I18n.get(button.getSidebarButton().getLangKey()); - int textXPos = gridStartRight ? addIconX - Minecraft.getInstance().font.width(langText) - 2 : gridX + BUTTON_SPACING; - graphics.drawString(Minecraft.getInstance().font, langText, textXPos, buttonY + 4, 0xFFFFFFFF); + int textXPos = gridStartRight ? addIconX - Minecraft.getInstance().font.width(langText) - 2 : gridX + BUTTON_SPACING + 3; + graphics.drawString(Minecraft.getInstance().font, langText, textXPos, buttonY + 5, 0xFFFFFFFF); } graphics.pose().popPose(); @@ -228,8 +230,10 @@ private void renderEditMode(GuiGraphics graphics, int mx, int my) { @Override public void onRelease(double d, double e) { + if(lastMouseClickButton == 1) { + return; + } super.onRelease(d, e); - isMouseDown = false; //Normal click action if (!isEditMode && mouseOver != null) { mouseOver.getSidebarButton().clickButton(Screen.hasShiftDown()); @@ -403,8 +407,18 @@ private GridLocation getGridLocation() { return new GridLocation(gridX, gridY); } + @Override public void onPress() { + if(lastMouseClickButton == 1) { + isEditMode = !isEditMode; + ensureGridAlignment(); + return; + } + if(mouseOverSettingsIcon) { + FTBLibraryClient.editConfig(true); + return; + } if(isEditMode) { if (isMouseOverAdd) { addBoxOpen = !addBoxOpen; @@ -412,7 +426,6 @@ public void onPress() { return; } } - isMouseDown = true; if(mouseOver != null) { mouseOffsetX = currentMouseX - mouseOver.x; @@ -442,6 +455,15 @@ public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) //Custom handling so our button click locations are where a buttons are not just a box @Override protected boolean isValidClickButton(int i) { + boolean inBounds = clicked(currentMouseX, currentMouseY); + if(!inBounds && isEditMode) { + isEditMode = false; + return false; + } + lastMouseClickButton = i; + if(i == 1) { + return inBounds; + } if (super.isValidClickButton(i)) { if (isEditMode) { return isMouseOverAdd || selectedButton != null || mouseOver != null; @@ -453,21 +475,6 @@ protected boolean isValidClickButton(int i) { return false; } - //Check if mouse is down for 1 second and if so enter edit mode - public void tick() { - if(isMouseDown) { - mouseDownTime++; - if(!isEditMode && mouseDownTime > 20) { - isEditMode = true; - mouseOver = null; - ensureGridAlignment(); - updateWidgetSize(); - } - }else { - mouseDownTime = 0; - } - } - private static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacingWidth, int spacingHeight, Color4I backgroundColor, Color4I gridColor) { backgroundColor.draw(graphics, x, y, width * spacingWidth, height * spacingHeight); for (var i = 0; i < width + 1; i++) { diff --git a/common/src/main/resources/assets/ftblibrary/lang/en_us.json b/common/src/main/resources/assets/ftblibrary/lang/en_us.json index 67af51bd..f98cfee0 100644 --- a/common/src/main/resources/assets/ftblibrary/lang/en_us.json +++ b/common/src/main/resources/assets/ftblibrary/lang/en_us.json @@ -60,9 +60,9 @@ "sidebar_button.ftblibrary.toggle.day.tooltip": "Sets daytime", "sidebar_button.ftblibrary.toggle.night": "Set time to Night", "sidebar_button.ftblibrary.toggle.night.tooltip": "Sets nighttime", - "sidebar_group.ftblibrary.info": "FTB Library — Info", - "sidebar_group.ftblibrary.cheat": "FTB Library — Cheats", - "sidebar_group.ftblibrary.util": "FTB Library — Utilities", + "sidebar_button.ftblibrary.config": "Open Client Config", + "sidebar_button.ftblibrary.config.tooltip": "Open FTB Client Library config", + "sidebar_button.ftblibrary.config.enter_edit_mode": "Right-click to enter edit mode", "item.ftblibrary.fluid_container": "Fluid Container", "item.ftblibrary.fluid_container.use": "Right-click on a tank to empty the container", "ftblibrary.mb": "%d mB of %s", @@ -76,9 +76,13 @@ "ftblibrary.gui.no_selection": "Nothing Selected", "ftblibrary.gui.key_reference": "Key Reference", "ftblibrary.client_settings": "Client Config", + "ftblibrary.client_settings.tooltips": "Tooltips", "ftblibrary.client_settings.tooltips.item_modname": "Show Mod Name in Item Select GUI", "ftblibrary.client_settings.tooltips.fluid_modname": "Show Mod Name in Fluid Select GUI", "ftblibrary.client_settings.tooltips.image_modname": "Show Mod Name in Image Select GUI", + "ftblibrary.client_settings.sidebar": "Sidebar Buttons", + "ftblibrary.client_settings.sidebar.enabled": "Enable Sidebar Buttons", + "ftblibrary.client_settings.sidebar.position": "Position of Sidebar Buttons", "ftblibrary.palette.chat": "Chat Colors", "ftblibrary.palette.dye": "Dye Colors", "ftblibrary.palette.nord": "Nord Theme", @@ -100,7 +104,5 @@ "dimension.hyperbox.hyperbox": "Hyperbox", "dimension.ae2.spatial_storage": "AE2 Spatial Storage", "itemGroup.ftbsuite.creative_tab": "FTB Suite", - "item.ftblibrary.icon_item": "FTB Icon", - "ftblibrary.sidebar.no_buttons.enabled": "No Sidebar Buttons Enabled", - "ftblibrary.sidebar.no_buttons.info": "You can disabled sidebar buttons in the FTB Client Library config" + "item.ftblibrary.icon_item": "FTB Icon" } diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_button_groups.json b/common/src/main/resources/assets/ftblibrary/sidebar_button_groups.json deleted file mode 100644 index 0128c381..00000000 --- a/common/src/main/resources/assets/ftblibrary/sidebar_button_groups.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "info": { - "y": 0 - }, - "cheat": { - "y": 100, - "pinned": false - }, - "util": { - "y": 200 - } -} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons.json deleted file mode 100644 index 25622204..00000000 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "toggle.gamemode": { - "group": "ftblibrary:cheat", - "icon": [ - "ftblibrary:icons/blue_button", - "ftblibrary:textures/icons/toggle_gamemode.png" - ], - "x": 100, - "click": "command:/ftblibrary gamemode", - "hide_with_nei": true, - "requires_op": true - }, - "toggle.rain": { - "group": "ftblibrary:cheat", - "icon": [ - "ftblibrary:icons/blue_button", - "ftblibrary:textures/icons/toggle_rain.png" - ], - "x": 80, - "click": "command:/ftblibrary rain", - "config": true, - "hide_with_nei": true, - "requires_op": true - }, - "toggle.day": { - "group": "ftblibrary:cheat", - "icon": [ - "ftblibrary:icons/blue_button", - "ftblibrary:textures/icons/toggle_day.png" - ], - "x": 120, - "click": "command:/ftblibrary day", - "required_server_mods": [ - "ftblibrary" - ], - "hide_with_nei": true, - "requires_op": true - }, - "toggle.night": { - "group": "ftblibrary:cheat", - "icon": [ - "ftblibrary:icons/blue_button", - "ftblibrary:textures/icons/toggle_night.png" - ], - "x": 130, - "click": "command:/ftblibrary night", - "required_server_mods": [ - "ftblibrary" - ], - "hide_with_nei": true, - "requires_op": true - } -} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/config.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/config.json new file mode 100644 index 00000000..9dc92cc2 --- /dev/null +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/config.json @@ -0,0 +1,13 @@ +{ + "icon": [ + "ftblibrary:icons/settings" + ], + "sort_index": 500, + "click": ["command:/ftblibrary clientconfig"], + "required_mods": [ + "ftblibrary" + ], + "tooltip": [ + {"translate": "sidebar_button.ftblibrary.config.enter_edit_mode" } + ] +} \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json index 820fa37c..f8dc8e2b 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json @@ -1,9 +1,9 @@ { - "group": "ftblibrary:cheat", "icon": [ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/camera.png" ], + "sort_index": 5000, "click": ["command:/say hi"], "required_mods": [ "ftblibrary", diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/day.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/day.json index 2b469f04..5ba64be8 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/day.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/day.json @@ -3,6 +3,7 @@ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_day.png" ], + "sort_index": 200, "click": ["command:/ftblibrary day"], "required_mods": [ "ftblibrary" diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/gamemode.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/gamemode.json index 827062ea..176508d3 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/gamemode.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/gamemode.json @@ -3,6 +3,7 @@ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_gamemode.png" ], + "sort_index": 100, "click": ["command:/ftblibrary gamemode"], "requires_op": true } \ No newline at end of file diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/night.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/night.json index e8329c6e..742a753c 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/night.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/night.json @@ -3,6 +3,7 @@ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_night.png" ], + "sort_index": 300, "click": ["command:/ftblibrary night"], "required_mods": [ "ftblibrary" diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/rain.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/rain.json index 2dc545e3..7a7d4506 100644 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/rain.json +++ b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/toggle/rain.json @@ -3,6 +3,7 @@ "ftblibrary:icons/blue_button", "ftblibrary:textures/icons/toggle_rain.png" ], + "sort_index": 400, "click": ["command:/ftblibrary rain"], "requires_op": true } \ No newline at end of file diff --git a/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java b/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java index da910c34..5da77bf4 100644 --- a/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java +++ b/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java @@ -3,22 +3,24 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.network.chat.Component; -import org.spongepowered.asm.mixin.Debug; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +//Need to make sure mouseReleased is called for widgets +//See https://github.com/FabricMC/fabric/pull/4010 @Mixin(AbstractContainerScreen.class) -@Debug(export = true) public abstract class AbstractContainerScreenMixin extends Screen { protected AbstractContainerScreenMixin(Component component) { super(component); } - @Inject(at = @At("HEAD"), method = "mouseReleased") + @Inject(at = @At("HEAD"), method = "mouseReleased", cancellable = true) public void onMouseReleased(double mouseX, double mouseY, int button, CallbackInfoReturnable info) { - super.mouseReleased(mouseX, mouseY, button); + if(super.mouseReleased(mouseX, mouseY, button)) { + info.cancel(); + } } } From 26d627d164a30e82a8b1ec42ded8667a5fa202d5 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Thu, 8 Aug 2024 10:40:54 -0500 Subject: [PATCH 13/17] Fix todo messages --- .../dev/ftb/mods/ftblibrary/icon/Icon.java | 1 - .../integration/REIIntegration.java | 129 ------------------ .../ftblibrary/sidebar/SidebarButton.java | 3 +- .../sidebar/SidebarButtonCreatedEvent.java | 2 +- .../sidebar/SidebarGroupGuiButton.java | 1 - 5 files changed, 2 insertions(+), 134 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/icon/Icon.java b/common/src/main/java/dev/ftb/mods/ftblibrary/icon/Icon.java index 704a9858..080c1fe3 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/icon/Icon.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/icon/Icon.java @@ -29,7 +29,6 @@ public static Color4I empty() { return Color4I.EMPTY_ICON; } - //Todo Fix me public static final Codec CODEC = ExtraCodecs.JSON.xmap(Icon::getIcon, Icon::getJson); public static final StreamCodec STREAM_CODEC = new StreamCodec<>() { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java index 2519c440..0e68b1c7 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/integration/REIIntegration.java @@ -1,6 +1,5 @@ package dev.ftb.mods.ftblibrary.integration; -import dev.ftb.mods.ftblibrary.FTBLibrary; import dev.ftb.mods.ftblibrary.config.ui.SelectItemStackScreen; import dev.ftb.mods.ftblibrary.config.ui.ResourceSearchMode; import dev.ftb.mods.ftblibrary.config.ui.SelectableResource; @@ -11,14 +10,12 @@ import me.shedaniel.rei.api.client.plugins.REIClientPlugin; import me.shedaniel.rei.api.client.registry.entry.EntryRegistry; import me.shedaniel.rei.api.client.registry.screen.ExclusionZones; -import me.shedaniel.rei.api.client.registry.screen.ExclusionZonesProvider; import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; import me.shedaniel.rei.api.common.util.CollectionUtils; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.renderer.Rect2i; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; @@ -26,7 +23,6 @@ import java.util.List; public class REIIntegration implements REIClientPlugin { - public static final ResourceLocation ID = FTBLibrary.rl("sidebar_button"); private static final ResourceSearchMode REI_ITEMS = new ResourceSearchMode<>() { @Override @@ -62,129 +58,4 @@ public void registerExclusionZones(ExclusionZones zones) { }); } - // @Override -// public void registerFavorites(FavoriteEntryType.Registry registry) { -// registry.register(ID, SidebarButtonType.INSTANCE); -// for (Map.Entry> entry : SidebarButtonManager.INSTANCE.getButtonGroups().entrySet()) { -// List buttons = entry.getValue() -// .stream().map(SidebarButtonEntry::new).toList(); -// SidebarButtonGroup group = entry.getKey(); -// if (!buttons.isEmpty()) { -// registry.getOrCrateSection(Component.translatable(group.getLangKey())) -// .add(group.isPinned(), buttons.toArray(new SidebarButtonEntry[0])); -// } -// } -// } -// -// private static SidebarButton createSidebarButton(ResourceLocation id, JsonObject json) { -// DataResult parse = SidebarButtonData.CODEC.parse(JsonOps.INSTANCE, json); -// if (parse.error().isPresent()) { -// FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); -// } else { -// SidebarButtonData sidebarButtonData = parse.result().get(); -// SidebarButton sidebarButton = new SidebarButton(id, sidebarButtonData); -// SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(sidebarButton)); -// return sidebarButton; -// } -// return null; -// } -// -// private enum SidebarButtonType implements FavoriteEntryType { -// INSTANCE; -// -// @Override -// public CompoundTag save(SidebarButtonEntry entry, CompoundTag tag) { -// tag.putString("id", entry.button.getId().toString()); -// DataResult encode = SidebarButtonData.CODEC.encode(entry.button.getData(), NbtOps.INSTANCE, null); -// encode.result().ifPresent(t -> tag.put("json", t)); -// return tag; -// } -// -// @Override -// public DataResult read(CompoundTag object) { -// ResourceLocation id = ResourceLocation.parse(object.getString("id")); -// DataResult> json = SidebarButtonData.CODEC.decode(NbtOps.INSTANCE, object.get("json")); -// return json.map(pair -> new SidebarButtonEntry(new SidebarButton(id, pair.getFirst()))); -// } -// -// @Override -// //Todo fix this -// public DataResult fromArgs(Object... args) { -// if (args.length == 0) { -// return DataResult.error(() -> "Cannot create SidebarButtonEntry from empty args!"); -// } -// if (!(args[0] instanceof ResourceLocation id)) { -// return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected ResourceLocation as the first argument!"); -// } -// if (!(args[1] instanceof SidebarButton button) && !(args[1] instanceof JsonObject)) { -// return DataResult.error(() -> "Creation of SidebarButtonEntry from args expected SidebarButton or JsonObject as the second argument!"); -// } -// return DataResult.success(new SidebarButtonEntry(args[1] instanceof SidebarButton button ? button : createSidebarButton(id, (JsonObject) args[1])), Lifecycle.stable()); -// } -// } -// -// private static class SidebarButtonEntry extends FavoriteEntry { -// private final SidebarButton button; -// -// public SidebarButtonEntry(SidebarButton button) { -// this.button = button; -// } -// -// @Override -// public boolean isInvalid() { -// return button.canSee(); -// } -// -// @Override -// public Renderer getRenderer(boolean showcase) { -// return new Renderer() { -// @Override -// public void render(GuiGraphics graphics, Rectangle bounds, int mouseX, int mouseY, float delta) { -// GuiHelper.setupDrawing(); -// if(bounds.getWidth() > 0 && bounds.getHeight() > 0) { -// button.getData().icon().draw(graphics, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); -// for (ButtonOverlayRender extraRenderer : button.getExtraRenderers()) { -// extraRenderer.render(graphics, Minecraft.getInstance().font, 16); -// } -// } -// } -// -// @Override -// @Nullable -// public Tooltip getTooltip(TooltipContext context) { -// return Tooltip.create(context.getPoint(), button.getTooltip()); -// } -// }; -// } -// -// @Override -// public boolean doAction(int button) { -// this.button.clickButton(Screen.hasShiftDown()); -// return true; -// } -// -// @Override -// public long hashIgnoreAmount() { -// return this.button.getId().hashCode(); -// } -// -// @Override -// public FavoriteEntry copy() { -// //Todo fix this? -// return new SidebarButtonEntry(button); -// } -// -// @Override -// public ResourceLocation getType() { -// return ID; -// } -// -// @Override -// public boolean isSame(FavoriteEntry other) { -// if (other instanceof SidebarButtonEntry entry) { -// return entry.button.getId().equals(button.getId()); -// } -// return false; -// } -// } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java index 3058b0c0..e8dd782d 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java @@ -11,13 +11,12 @@ import net.minecraft.resources.ResourceLocation; import java.util.ArrayList; -import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.function.BooleanSupplier; import java.util.function.Supplier; -//Todo better name? +//Todo better name? - unreal public class SidebarButton implements dev.ftb.mods.ftblibrary.api.sidebar.SidebarButton { private final SidebarButtonData data; diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java index cde569c4..2899ac27 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java @@ -5,7 +5,7 @@ import java.util.function.Consumer; -//Todo move this to api class +//Todo move this to api class in the future - unreal // TODO currently broken for neoforge, uncomment when there's a fix in architectury //@ForgeEvent public class SidebarButtonCreatedEvent { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index a516e40a..0a1eb25a 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -35,7 +35,6 @@ public class SidebarGroupGuiButton extends AbstractButton { Component.translatable("sidebar_button.ftblibrary.config"), Component.translatable("sidebar_button.ftblibrary.config.enter_edit_mode")); - private SidebarGuiButton mouseOver; private SidebarGuiButton selectedButton; private GridLocation selectedLocation; From 34b746b45128f16fb5ff406d8e2dd3c406f1a03c Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Thu, 8 Aug 2024 11:46:34 -0500 Subject: [PATCH 14/17] Resolve a bunch of formatting issues --- .../ftb/mods/ftblibrary/FTBLibraryClient.java | 2 +- .../api/sidebar/ButtonOverlayRender.java | 4 +- .../ftblibrary/api/sidebar/SidebarButton.java | 10 +- .../mods/ftblibrary/sidebar/GridLocation.java | 22 +- ...tton.java => RegisteredSidebarButton.java} | 17 +- .../sidebar/SidebarButtonCreatedEvent.java | 18 +- .../ftblibrary/sidebar/SidebarButtonData.java | 50 +- .../sidebar/SidebarButtonManager.java | 251 +++--- .../sidebar/SidebarGroupGuiButton.java | 795 +++++++++--------- .../ftblibrary/sidebar/SidebarGuiButton.java | 73 +- .../ftblibrary/sidebar_buttons/test.json | 13 - .../fabric/AbstractContainerScreenMixin.java | 4 +- gradle.properties | 2 +- 13 files changed, 625 insertions(+), 636 deletions(-) rename common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/{SidebarButton.java => RegisteredSidebarButton.java} (85%) delete mode 100644 common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java index c4a09456..da578483 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/FTBLibraryClient.java @@ -69,7 +69,7 @@ public static boolean areButtonsVisible(@Nullable Screen gui) { return false; } - if(!FTBLibraryClientConfig.SIDEBAR_ENABLED.get()) { + if (!FTBLibraryClientConfig.SIDEBAR_ENABLED.get()) { return false; } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java index d8f9f0aa..0e81774b 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/ButtonOverlayRender.java @@ -10,11 +10,11 @@ public interface ButtonOverlayRender { /** + * Called when the button is rendering + * graphics is aligned so that 0, 0 is the top left corner of the button * @param graphics The graphics object * @param font The font object * @param buttonSize The size of the button - * Called when the button is rendering - * graphics is aligned so that 0, 0 is the top left corner of the button */ void render(GuiGraphics graphics, Font font, int buttonSize); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java index 24f3669f..9e87f7ea 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java @@ -7,11 +7,10 @@ import java.util.function.BooleanSupplier; import java.util.function.Supplier; -public interface SidebarButton -{ +public interface SidebarButton { /** - * @return the id of the button + * @return id of button used for storing */ ResourceLocation getId(); @@ -25,16 +24,19 @@ default void setCustomTextHandler(Supplier customTextHandler) { } /** + * Register a condition that must be met for the button to be visible * @param condition a condition that must be met for the button to be visible */ void addVisibilityCondition(BooleanSupplier condition); /** - * @param renderer register a custom button overlay renderer to render on top of the button icon + * Register a custom overlay renderer to render on top of the button icon + * @param renderer the renderer to render on top of the button icon */ void addOverlayRender(ButtonOverlayRender renderer); /** + * Override the default tooltip displayed when hovering over the button * @param tooltipOverride a supplier that returns the tooltip to be displayed when hovering over the button */ void setTooltipOverride(Supplier> tooltipOverride); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java index 4e93a21e..2aa86e39 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java @@ -2,17 +2,17 @@ public record GridLocation(int x, int y) { - public static final GridLocation OUT_OF_BOUNDS = new GridLocation(-1, -1); + public static final GridLocation OUT_OF_BOUNDS = new GridLocation(-1, -1); - public boolean isOutOfBounds() { - return x < 0 || y < 0; - } + public boolean isOutOfBounds() { + return x < 0 || y < 0; + } - public boolean isLatterInRow(GridLocation other) { - return x == other.x && y <= other.y; - } + public boolean isLatterInRow(GridLocation other) { + return x == other.x && y <= other.y; + } - public boolean isLatterInColumn(GridLocation other) { - return x <= other.x && y == other.y; - } - } \ No newline at end of file + public boolean isLatterInColumn(GridLocation other) { + return x <= other.x && y == other.y; + } +} \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/RegisteredSidebarButton.java similarity index 85% rename from common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java rename to common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/RegisteredSidebarButton.java index e8dd782d..f8078b89 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/RegisteredSidebarButton.java @@ -16,8 +16,7 @@ import java.util.function.BooleanSupplier; import java.util.function.Supplier; -//Todo better name? - unreal -public class SidebarButton implements dev.ftb.mods.ftblibrary.api.sidebar.SidebarButton { +public class RegisteredSidebarButton implements dev.ftb.mods.ftblibrary.api.sidebar.SidebarButton { private final SidebarButtonData data; private final ResourceLocation id; @@ -27,12 +26,12 @@ public class SidebarButton implements dev.ftb.mods.ftblibrary.api.sidebar.Sideba private Supplier> tooltipOverride; private ChainedBooleanSupplier visible = ChainedBooleanSupplier.TRUE; - public SidebarButton(ResourceLocation id, SidebarButtonData data) { + public RegisteredSidebarButton(ResourceLocation id, SidebarButtonData data) { this.id = id; this.data = data; this.langKey = Util.makeDescriptionId("sidebar_button", id); tooltip = Component.translatable(langKey + ".tooltip"); - if(data.requiresOp()) { + if (data.requiresOp()) { addVisibilityCondition(ClientUtils.IS_CLIENT_OP); } data.requiredMods().ifPresent(mods -> addVisibilityCondition(() -> mods.stream().allMatch(Platform::isModLoaded))); @@ -54,12 +53,12 @@ public String getLangKey() { } public List getTooltip(boolean shift) { - if(tooltipOverride != null) { + if (tooltipOverride != null) { return tooltipOverride.get(); - }else { + } else { List tooltips = new ArrayList<>(); tooltips.add(Component.translatable(langKey)); - if(shift) { + if (shift) { tooltips.add(tooltip); } Optional> components = shift ? data.shiftTooltip() : data.tooltip(); @@ -73,7 +72,9 @@ public void clickButton(boolean shift) { new LoadingScreen(Component.translatable(getLangKey())).openGui(); } - for (String event : (shift && data.shiftClickEvent().isPresent() ? data.shiftClickEvent().get() : data.clickEvents())) { + boolean canShift = data.shiftClickEvent().isPresent(); + List clickEvents = canShift ? data.shiftClickEvent().get() : data.clickEvents(); + for (String event : clickEvents) { GuiHelper.BLANK_GUI.handleClick(event); } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java index 2899ac27..2d2764e2 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java @@ -5,19 +5,19 @@ import java.util.function.Consumer; -//Todo move this to api class in the future - unreal +// Todo move this to api class in the future - unreal // TODO currently broken for neoforge, uncomment when there's a fix in architectury //@ForgeEvent public class SidebarButtonCreatedEvent { - public static final Event> EVENT = EventFactory.createConsumerLoop(SidebarButtonCreatedEvent.class); + public static final Event> EVENT = EventFactory.createConsumerLoop(SidebarButtonCreatedEvent.class); - private final SidebarButton button; + private final RegisteredSidebarButton button; - public SidebarButtonCreatedEvent(SidebarButton button) { - this.button = button; - } + public SidebarButtonCreatedEvent(RegisteredSidebarButton button) { + this.button = button; + } - public SidebarButton getButton() { - return button; - } + public RegisteredSidebarButton getButton() { + return button; + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java index b2df2f38..ee28db26 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonData.java @@ -12,32 +12,32 @@ public record SidebarButtonData( - Icon icon, - boolean defaultEnabled, - List clickEvents, - Optional> shiftClickEvent, - boolean loadingScreen, - Optional> tooltip, - Optional> shiftTooltip, - boolean requiresOp, - Optional> requiredMods, - int sortIndex) implements Comparable { + Icon icon, + boolean defaultEnabled, + List clickEvents, + Optional> shiftClickEvent, + boolean loadingScreen, + Optional> tooltip, + Optional> shiftTooltip, + boolean requiresOp, + Optional> requiredMods, + int sortIndex) implements Comparable { - public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( - Icon.CODEC.fieldOf("icon").forGetter(SidebarButtonData::icon), - Codec.BOOL.fieldOf("default_enabled").orElse(true).forGetter(SidebarButtonData::defaultEnabled), - Codec.STRING.listOf(1, Integer.MAX_VALUE).fieldOf("click").forGetter(SidebarButtonData::clickEvents), - Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("shift_click").forGetter(SidebarButtonData::shiftClickEvent), - Codec.BOOL.fieldOf("loading_screen").orElse(false).forGetter(SidebarButtonData::loadingScreen), - ComponentSerialization.CODEC.listOf().optionalFieldOf("tooltip").forGetter(SidebarButtonData::tooltip), - ComponentSerialization.CODEC.listOf().optionalFieldOf("shift_tooltip").forGetter(SidebarButtonData::shiftTooltip), - Codec.BOOL.fieldOf("requires_op").orElse(false).forGetter(SidebarButtonData::requiresOp), - Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("required_mods").forGetter(SidebarButtonData::requiredMods), - Codec.INT.fieldOf("sort_index").orElse(0).forGetter(SidebarButtonData::sortIndex) + public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( + Icon.CODEC.fieldOf("icon").forGetter(SidebarButtonData::icon), + Codec.BOOL.fieldOf("default_enabled").orElse(true).forGetter(SidebarButtonData::defaultEnabled), + Codec.STRING.listOf(1, Integer.MAX_VALUE).fieldOf("click").forGetter(SidebarButtonData::clickEvents), + Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("shift_click").forGetter(SidebarButtonData::shiftClickEvent), + Codec.BOOL.fieldOf("loading_screen").orElse(false).forGetter(SidebarButtonData::loadingScreen), + ComponentSerialization.CODEC.listOf().optionalFieldOf("tooltip").forGetter(SidebarButtonData::tooltip), + ComponentSerialization.CODEC.listOf().optionalFieldOf("shift_tooltip").forGetter(SidebarButtonData::shiftTooltip), + Codec.BOOL.fieldOf("requires_op").orElse(false).forGetter(SidebarButtonData::requiresOp), + Codec.STRING.listOf(1, Integer.MAX_VALUE).optionalFieldOf("required_mods").forGetter(SidebarButtonData::requiredMods), + Codec.INT.fieldOf("sort_index").orElse(0).forGetter(SidebarButtonData::sortIndex) ).apply(builder, SidebarButtonData::new)); - @Override - public int compareTo(@NotNull SidebarButtonData o) { - return Integer.compare(sortIndex, o.sortIndex); - } + @Override + public int compareTo(@NotNull SidebarButtonData o) { + return Integer.compare(sortIndex, o.sortIndex); + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index 7431c595..5a8a9e96 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -1,6 +1,9 @@ package dev.ftb.mods.ftblibrary.sidebar; -import com.google.gson.*; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; import com.mojang.logging.LogUtils; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; @@ -25,136 +28,134 @@ import java.util.List; import java.util.Map; import java.util.function.BiConsumer; -import java.util.function.ToIntFunction; import java.util.stream.Collectors; public enum SidebarButtonManager implements ResourceManagerReloadListener { - INSTANCE; - - private static final Logger LOGGER = LogUtils.getLogger(); - - private final Map buttons = new HashMap<>(); - - private final List buttonList = new ArrayList<>(); - - private JsonElement readJson(Resource resource) { - try (BufferedReader reader = resource.openAsReader()) { - return JsonParser.parseReader(reader); - } catch (JsonParseException | IOException e) { - LOGGER.error("can't read {}: {}", resource.sourcePackId(), e.getMessage()); - } - return JsonNull.INSTANCE; - } - - public Collection getButtons() { - return buttons.values(); - } - - @Override - public void onResourceManagerReload(ResourceManager manager) { - buttons.clear(); - - //Read the button and group json files and register them to their 'registry' map - loadResources(manager, "sidebar_buttons", SidebarButtonData.CODEC, (id, buttonData) -> buttons.put(id, new SidebarButton(id, buttonData))); - - buttonList.clear(); - List sortedButtons = buttons.values().stream().sorted(Comparator.comparingInt(value -> value.getData().sortIndex())).toList(); - int y = 0; - int x = 0; - for (SidebarButton buttonEntry : sortedButtons) { - StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(buttonEntry.getId().toString()); - if(buttonSettings == null) { - buttonSettings = new StringSidebarMapValue.SideButtonInfo(true, x, y); - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(buttonEntry.getId().toString(), buttonSettings); - FTBLibraryClientConfig.save(); - } + INSTANCE; + + private static final Logger LOGGER = LogUtils.getLogger(); + + private final Map buttons = new HashMap<>(); + + private final List buttonList = new ArrayList<>(); + + private JsonElement readJson(Resource resource) { + try (BufferedReader reader = resource.openAsReader()) { + return JsonParser.parseReader(reader); + } catch (JsonParseException | IOException e) { + LOGGER.error("can't read {}: {}", resource.sourcePackId(), e.getMessage()); + } + return JsonNull.INSTANCE; + } + + public Collection getButtons() { + return buttons.values(); + } + + @Override + public void onResourceManagerReload(ResourceManager manager) { + buttons.clear(); + + // Read the button and group json files and register them to their 'registry' map + loadResources(manager, "sidebar_buttons", SidebarButtonData.CODEC, (id, buttonData) -> buttons.put(id, new RegisteredSidebarButton(id, buttonData))); + + buttonList.clear(); + List sortedButtons = buttons.values().stream().sorted(Comparator.comparingInt(value -> value.getData().sortIndex())).toList(); + int y = 0; + int x = 0; + for (RegisteredSidebarButton buttonEntry : sortedButtons) { + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(buttonEntry.getId().toString()); + if (buttonSettings == null) { + buttonSettings = new StringSidebarMapValue.SideButtonInfo(true, x, y); + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(buttonEntry.getId().toString(), buttonSettings); + FTBLibraryClientConfig.save(); + } buttonList.add(new SidebarGuiButton(new GridLocation(buttonSettings.xPos(), buttonSettings.yPos()), buttonSettings.enabled(), buttonEntry)); - x++; - if(x >= 4) { - x = 0; - y++; - } + x++; + if (x >= 4) { + x = 0; + y++; + } + } + for (RegisteredSidebarButton value : buttons.values()) { + SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(value)); } - for (SidebarButton value : buttons.values()) { - SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(value)); - } - FTBLibraryClientConfig.save(); - } - - private void loadResources(ResourceManager manager, String path, Codec codec, BiConsumer consumer) { - Map resourceLocationResourceMap = manager.listResources(path, name -> name.getPath().endsWith(".json")); - for (Map.Entry resource : resourceLocationResourceMap.entrySet()) { - JsonElement jsonElement = readJson(resource.getValue()); - DataResult parse = codec.parse(JsonOps.INSTANCE, jsonElement); - if (parse.error().isPresent()) { - FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); - } else { - T result = parse.result().get(); - ResourceLocation key = resource.getKey(); - String path1 = key.getPath(); - ResourceLocation fixed = ResourceLocation.fromNamespaceAndPath(key.getNamespace(), path1.replace(path + "/", "").replace(".json", "")); - consumer.accept(fixed, result); - } - } - } - - public void saveConfigFromButtonList() { - Map> buttonMap = new HashMap<>(); - for (SidebarGuiButton button : getButtonList()) { - int y = button.isEnabled() ? button.getGirdLocation().y() : -1; + FTBLibraryClientConfig.save(); + } + + private void loadResources(ResourceManager manager, String path, Codec codec, BiConsumer consumer) { + Map resourceLocationResourceMap = manager.listResources(path, name -> name.getPath().endsWith(".json")); + for (Map.Entry resource : resourceLocationResourceMap.entrySet()) { + JsonElement jsonElement = readJson(resource.getValue()); + DataResult parse = codec.parse(JsonOps.INSTANCE, jsonElement); + if (parse.error().isPresent()) { + FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); + } else { + T result = parse.result().get(); + ResourceLocation key = resource.getKey(); + String path1 = key.getPath(); + ResourceLocation fixed = ResourceLocation.fromNamespaceAndPath(key.getNamespace(), path1.replace(path + "/", "").replace(".json", "")); + consumer.accept(fixed, result); + } + } + } + + public void saveConfigFromButtonList() { + Map> buttonMap = new HashMap<>(); + for (SidebarGuiButton button : getButtonList()) { + int y = button.isEnabled() ? button.getGirdLocation().y() : -1; buttonMap.computeIfAbsent(y, k -> new LinkedList<>()).add(button); - } - - int y = 0; - for (Map.Entry> integerListEntry : MapUtils.sortMapByKey(buttonMap).entrySet()) { - if(integerListEntry.getKey() == -1) { - for (SidebarGuiButton button : integerListEntry.getValue()) { - button.setGridLocation(-1, -1); - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(false, -1, -1)); - } - } - int x = 0; - integerListEntry.getValue() - .sort(Comparator.comparingInt((SidebarGuiButton button) -> button.getGirdLocation().x())); - List value = integerListEntry.getValue(); - for (SidebarGuiButton sidebarButton : value) { - if(sidebarButton.isEnabled()) { - sidebarButton.setGridLocation(x, y); - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(sidebarButton.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(sidebarButton.isEnabled(), x, y)); - x++; - } - } - if(x != 0) { - y++; - } - } - - for (SidebarGuiButton button : buttonList) { - StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getSidebarButton().getId().toString()); - if(buttonSettings != null) { - FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(button.isEnabled(), button.getGirdLocation().x(), button.getGirdLocation().y())); - } - } - FTBLibraryClientConfig.save(); - } - - public List getButtonList() { - return buttonList; - } - - public List getEnabledButtonList(boolean all) { - return buttonList.stream() - .filter(SidebarGuiButton::isEnabled) - .filter(button -> all || button.getSidebarButton().canSee()) - .toList(); - } - - public List getDisabledButtonList(boolean all) { - return buttonList.stream() - .filter(button -> !button.isEnabled()) - .filter(button -> all || button.getSidebarButton().canSee()) - .collect(Collectors.toList()); - } + } + int y = 0; + for (Map.Entry> integerListEntry : MapUtils.sortMapByKey(buttonMap).entrySet()) { + if (integerListEntry.getKey() == -1) { + for (SidebarGuiButton button : integerListEntry.getValue()) { + button.setGridLocation(-1, -1); + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(false, -1, -1)); + } + } + int x = 0; + integerListEntry.getValue() + .sort(Comparator.comparingInt((SidebarGuiButton button) -> button.getGirdLocation().x())); + List value = integerListEntry.getValue(); + for (SidebarGuiButton sidebarButton : value) { + if (sidebarButton.isEnabled()) { + sidebarButton.setGridLocation(x, y); + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(sidebarButton.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(sidebarButton.isEnabled(), x, y)); + x++; + } + } + if (x != 0) { + y++; + } + } + + for (SidebarGuiButton button : buttonList) { + StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(button.getSidebarButton().getId().toString()); + if (buttonSettings != null) { + FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(button.isEnabled(), button.getGirdLocation().x(), button.getGirdLocation().y())); + } + } + FTBLibraryClientConfig.save(); + } + + public List getButtonList() { + return buttonList; + } + + public List getEnabledButtonList(boolean all) { + return buttonList.stream() + .filter(SidebarGuiButton::isEnabled) + .filter(button -> all || button.getSidebarButton().canSee()) + .toList(); + } + + public List getDisabledButtonList(boolean all) { + return buttonList.stream() + .filter(button -> !button.isEnabled()) + .filter(button -> all || button.getSidebarButton().canSee()) + .collect(Collectors.toList()); + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index 0a1eb25a..c7de1e68 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -28,89 +28,88 @@ public class SidebarGroupGuiButton extends AbstractButton { - public static Rect2i lastDrawnArea = new Rect2i(0, 0, 0, 0); - private static final int BUTTON_SPACING = 17; + public static Rect2i lastDrawnArea = new Rect2i(0, 0, 0, 0); + private static final int BUTTON_SPACING = 17; - private static final List noButtonComponents = List.of( - Component.translatable("sidebar_button.ftblibrary.config"), - Component.translatable("sidebar_button.ftblibrary.config.enter_edit_mode")); + private static final List noButtonComponents = List.of( + Component.translatable("sidebar_button.ftblibrary.config"), + Component.translatable("sidebar_button.ftblibrary.config.enter_edit_mode")); - private SidebarGuiButton mouseOver; - private SidebarGuiButton selectedButton; - private GridLocation selectedLocation; - private int lastMouseClickButton = 0; - private boolean isEditMode; + private SidebarGuiButton mouseOver; + private SidebarGuiButton selectedButton; + private GridLocation selectedLocation; + private int lastMouseClickButton = 0; + private boolean isEditMode; - private int currentMouseX; - private int currentMouseY; + private int currentMouseX; + private int currentMouseY; - private int mouseOffsetX; - private int mouseOffsetY; + private int mouseOffsetX; + private int mouseOffsetY; - private int currentGirdWidth = 1; - private int currentGridHeight = 1; + private int currentGirdWidth = 1; + private int currentGridHeight = 1; - private boolean addBoxOpen; + private boolean addBoxOpen; - boolean gridStartBottom = false; - boolean gridStartRight = false; + boolean gridStartBottom = false; + boolean gridStartRight = false; - int yRenderStart; - int xRenderStart; + int yRenderStart; + int xRenderStart; - private boolean isMouseOverAdd; - private boolean mouseOverSettingsIcon; + private boolean isMouseOverAdd; + private boolean mouseOverSettingsIcon; private final Map realLocationMap = new HashMap<>(); - public SidebarGroupGuiButton() { - super(0, 0, 0, 0, Component.empty()); - ensureGridAlignment(); - - } + public SidebarGroupGuiButton() { + super(0, 0, 0, 0, Component.empty()); + ensureGridAlignment(); + } - @Override - public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { - graphics.pose().pushPose(); - { - graphics.pose().translate(0, 0, 5000); + @Override + public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { + graphics.pose().pushPose(); + { + graphics.pose().translate(0, 0, 5000); - currentMouseX = mx; - currentMouseY = my; - mouseOver = null; - isMouseOverAdd = false; - mouseOverSettingsIcon = false; + currentMouseX = mx; + currentMouseY = my; + mouseOver = null; + isMouseOverAdd = false; + mouseOverSettingsIcon = false; - GridLocation gridLocation = getGridLocation(); + GridLocation gridLocation = getGridLocation(); - for (Map.Entry entry : realLocationMap.entrySet()) { - SidebarGuiButton button = entry.getKey(); - if (entry.getValue().equals(gridLocation)) { - mouseOver = button; - } - } + for (Map.Entry entry : realLocationMap.entrySet()) { + SidebarGuiButton button = entry.getKey(); + if (entry.getValue().equals(gridLocation)) { + mouseOver = button; + } + } - if (isEditMode) { - renderEditMode(graphics, mx, my); - } + if (isEditMode) { + renderEditMode(graphics, mx, my); + } - renderSidebarButtons(graphics, mx, my); + renderSidebarButtons(graphics, mx, my); - } - graphics.pose().popPose(); - } + } + graphics.pose().popPose(); + } - private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { - var font = Minecraft.getInstance().font; + private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { + var font = Minecraft.getInstance().font; - graphics.pose().translate(0, 0, 50); + graphics.pose().translate(0, 0, 50); - //If there are no sidebar buttons enabled render "fake" button + //If there are no sidebar buttons enabled render "fake" button if (!isEditMode && SidebarButtonManager.INSTANCE.getEnabledButtonList(false).isEmpty()) { - if(mx >= xRenderStart + 2 && my >= yRenderStart + 2 && mx < xRenderStart + 18 && my < yRenderStart + 18) { - graphics.renderTooltip(font, noButtonComponents, Optional.empty(), mx, my + 5); - Color4I.WHITE.withAlpha(33).draw(graphics, xRenderStart + 1, yRenderStart + 1, 16, 16); - mouseOverSettingsIcon = true; + if (mx >= xRenderStart + 2 && my >= yRenderStart + 2 && mx < xRenderStart + 18 && my < yRenderStart + 18) { + graphics.renderTooltip(font, noButtonComponents, Optional.empty(), mx, my + 5); + Color4I.WHITE.withAlpha(33).draw(graphics, xRenderStart + 1, yRenderStart + 1, 16, 16); + mouseOverSettingsIcon = true; } Icons.SETTINGS.draw(graphics, xRenderStart + 1, yRenderStart + 1, 16, 16); @@ -148,365 +147,365 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { Color4I.WHITE.withAlpha(33).draw(graphics, button.x, button.y, 16, 16); } - graphics.pose().pushPose(); + graphics.pose().pushPose(); graphics.pose().translate(button.x, button.y, 0); for (ButtonOverlayRender buttonOverlayRender : button.getSidebarButton().getExtraRenderers()) { buttonOverlayRender.render(graphics, font, 16); } - graphics.pose().popPose(); + graphics.pose().popPose(); } if (!isEditMode && mouseOver == button) { - graphics.renderTooltip(font, button.getSidebarButton().getTooltip(Screen.hasShiftDown()), Optional.empty(), mx, Math.max(7, my - 9) + 10); + graphics.renderTooltip(font, button.getSidebarButton().getTooltip(Screen.hasShiftDown()), Optional.empty(), mx, Math.max(7, my - 9) + 10); } graphics.pose().popPose(); } } } - private void renderEditMode(GuiGraphics graphics, int mx, int my) { - drawHoveredGrid(graphics, xRenderStart, yRenderStart, currentGirdWidth, currentGridHeight, BUTTON_SPACING, Color4I.GRAY.withAlpha(70), Color4I.BLACK.withAlpha(90), mx, my, gridStartBottom, gridStartRight, getX(), getY()); - - List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode); - if (!disabledButtonList.isEmpty()) { - int addIconY = gridStartBottom ? yRenderStart + ((currentGridHeight - 1) * BUTTON_SPACING) : 0; - int addIconX = gridStartRight ? xRenderStart - (2 * BUTTON_SPACING) : (currentGirdWidth + 1) * BUTTON_SPACING; - drawGrid(graphics, addIconX, addIconY, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); - Icons.ADD.draw(graphics, addIconX + 1, addIconY + 1, 16, 16); - - if (mx >= addIconX && my >= addIconY && mx < addIconX + 16 && my < addIconY + 16) { - isMouseOverAdd = true; - Color4I.WHITE.withAlpha(137).draw(graphics, addIconX + 1, addIconY + 1, 16, 16); - } - - if (addBoxOpen) { - int maxWidth = 0; - for (SidebarGuiButton button : disabledButtonList) { - String s = I18n.get(button.getSidebarButton().getLangKey()); - int width = Minecraft.getInstance().font.width(s); - maxWidth = Math.max(maxWidth, width); - } - - int gridY = gridStartBottom ? addIconY - disabledButtonList.size() * BUTTON_SPACING : BUTTON_SPACING; - int gridX = gridStartRight ? addIconX - maxWidth - 6 : (currentGirdWidth + 1) * BUTTON_SPACING; - - graphics.pose().pushPose(); - graphics.pose().translate(0, 0, 1000); - if (gridStartRight) { - drawHoveredGrid(graphics, addIconX, gridY, 1, disabledButtonList.size(), BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my, gridStartBottom, gridStartRight, gridX, gridY); - drawGrid(graphics, addIconX - maxWidth - 6, gridY, 1, disabledButtonList.size(), maxWidth + 6, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); - } else { - drawHoveredGrid(graphics, gridX, gridY, 1, disabledButtonList.size(), BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my, gridStartBottom, gridStartRight, gridX, gridY); - drawGrid(graphics, gridX + BUTTON_SPACING, gridY, 1, disabledButtonList.size(), maxWidth + 6, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); - } - - for (int i = 0; i < disabledButtonList.size(); i++) { - SidebarGuiButton button = disabledButtonList.get(i); - if (selectedButton != null && selectedButton == button) { - continue; - } - int buttonY = gridY + BUTTON_SPACING * i; - button.x = gridStartRight ? addIconX : gridX; - button.y = buttonY; - GuiHelper.setupDrawing(); - - if (mx >= button.x && my >= button.y && mx < button.x + 16 && my < button.y + 16) { - Color4I.WHITE.withAlpha(137).draw(graphics, button.x + 1, button.y + 1, 16, 16); - mouseOver = button; - } - - button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); - - String langText = I18n.get(button.getSidebarButton().getLangKey()); - int textXPos = gridStartRight ? addIconX - Minecraft.getInstance().font.width(langText) - 2 : gridX + BUTTON_SPACING + 3; - graphics.drawString(Minecraft.getInstance().font, langText, textXPos, buttonY + 5, 0xFFFFFFFF); - } - graphics.pose().popPose(); - - } - } - } - - @Override - public void onRelease(double d, double e) { - if(lastMouseClickButton == 1) { - return; - } - super.onRelease(d, e); - //Normal click action - if (!isEditMode && mouseOver != null) { - mouseOver.getSidebarButton().clickButton(Screen.hasShiftDown()); - } else { - if (selectedButton != null) { - GridLocation gLocation = getGridLocation(); - //Make sure the placement is in grid - if (!gLocation.isOutOfBounds()) { - //Checks if the icon is placed in the same location picked up from, if so do nothing - if (!gLocation.equals(selectedLocation)) { - //checks if moved from the first spot, so we can move other icons over but only as the same row - boolean isFrom0XTo1X = selectedLocation.y() == gLocation.y() && selectedLocation.x() == 0 && gLocation.x() == 1; - selectedButton.setGridLocation(gLocation.x(), gLocation.y()); - //Checks for icon that needs to be moved over - List buttonList = SidebarButtonManager.INSTANCE.getButtonList(); - for (SidebarGuiButton button : buttonList) { - GridLocation realGridLocation = realLocationMap.get(button); - if(realGridLocation != null) { - if (!selectedButton.getSidebarButton().getId().equals(button.getSidebarButton().getId())) { - if (gLocation.isLatterInColumn(realGridLocation)) { - int moveAmount = isFrom0XTo1X && realGridLocation.x() == 1 ? -1 : 1; - button.setGridLocation(realGridLocation.x() + moveAmount, realGridLocation.y()); - } - } - } - } - //If the icon was disabled enable it - if (!selectedButton.isEnabled()) { - selectedButton.setEnabled(true); - if (SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).isEmpty()) { - addBoxOpen = false; - } - } + private void renderEditMode(GuiGraphics graphics, int mx, int my) { + drawHoveredGrid(graphics, xRenderStart, yRenderStart, currentGirdWidth, currentGridHeight, BUTTON_SPACING, Color4I.GRAY.withAlpha(70), Color4I.BLACK.withAlpha(90), mx, my, gridStartBottom, gridStartRight, getX(), getY()); + + List disabledButtonList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode); + if (!disabledButtonList.isEmpty()) { + int addIconY = gridStartBottom ? yRenderStart + ((currentGridHeight - 1) * BUTTON_SPACING) : 0; + int addIconX = gridStartRight ? xRenderStart - (2 * BUTTON_SPACING) : (currentGirdWidth + 1) * BUTTON_SPACING; + drawGrid(graphics, addIconX, addIconY, 1, 1, BUTTON_SPACING, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + Icons.ADD.draw(graphics, addIconX + 1, addIconY + 1, 16, 16); + + if (mx >= addIconX && my >= addIconY && mx < addIconX + 16 && my < addIconY + 16) { + isMouseOverAdd = true; + Color4I.WHITE.withAlpha(137).draw(graphics, addIconX + 1, addIconY + 1, 16, 16); + } + + if (addBoxOpen) { + int maxWidth = 0; + for (SidebarGuiButton button : disabledButtonList) { + String s = I18n.get(button.getSidebarButton().getLangKey()); + int width = Minecraft.getInstance().font.width(s); + maxWidth = Math.max(maxWidth, width); + } + + int gridY = gridStartBottom ? addIconY - disabledButtonList.size() * BUTTON_SPACING : BUTTON_SPACING; + int gridX = gridStartRight ? addIconX - maxWidth - 6 : (currentGirdWidth + 1) * BUTTON_SPACING; + + graphics.pose().pushPose(); + graphics.pose().translate(0, 0, 1000); + if (gridStartRight) { + drawHoveredGrid(graphics, addIconX, gridY, 1, disabledButtonList.size(), BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my, gridStartBottom, gridStartRight, gridX, gridY); + drawGrid(graphics, addIconX - maxWidth - 6, gridY, 1, disabledButtonList.size(), maxWidth + 6, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + } else { + drawHoveredGrid(graphics, gridX, gridY, 1, disabledButtonList.size(), BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my, gridStartBottom, gridStartRight, gridX, gridY); + drawGrid(graphics, gridX + BUTTON_SPACING, gridY, 1, disabledButtonList.size(), maxWidth + 6, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); + } + + for (int i = 0; i < disabledButtonList.size(); i++) { + SidebarGuiButton button = disabledButtonList.get(i); + if (selectedButton != null && selectedButton == button) { + continue; } + int buttonY = gridY + BUTTON_SPACING * i; + button.x = gridStartRight ? addIconX : gridX; + button.y = buttonY; + GuiHelper.setupDrawing(); + + if (mx >= button.x && my >= button.y && mx < button.x + 16 && my < button.y + 16) { + Color4I.WHITE.withAlpha(137).draw(graphics, button.x + 1, button.y + 1, 16, 16); + mouseOver = button; + } + + button.getSidebarButton().getData().icon().draw(graphics, button.x + 1, button.y + 1, 16, 16); + + String langText = I18n.get(button.getSidebarButton().getLangKey()); + int textXPos = gridStartRight ? addIconX - Minecraft.getInstance().font.width(langText) - 2 : gridX + BUTTON_SPACING + 3; + graphics.drawString(Minecraft.getInstance().font, langText, textXPos, buttonY + 5, 0xFFFFFFFF); } - selectedButton = null; - ensureGridAlignment(); - } - } - } - - //Aligns icons to a 'realLocationMap' this uses the button config as base, but checks if button is "visible" then aligns it to the grid - private void ensureGridAlignment() { - List enabledButtonList = SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode); - Map> buttonMap = enabledButtonList - .stream() - .filter(SidebarGuiButton::isEnabled) - .collect(Collectors.groupingBy(button -> button.getGirdLocation().y(), TreeMap::new, Collectors.toCollection(LinkedList::new))); + graphics.pose().popPose(); + + } + } + } + + @Override + public void onRelease(double d, double e) { + if (lastMouseClickButton == 1) { + return; + } + super.onRelease(d, e); + //Normal click action + if (!isEditMode && mouseOver != null) { + mouseOver.getSidebarButton().clickButton(Screen.hasShiftDown()); + } else if (selectedButton != null) { + GridLocation gLocation = getGridLocation(); + // Make sure the placement is in grid and that is not in the same location + if (!gLocation.isOutOfBounds() && !gLocation.equals(selectedLocation)) { + updateButtonLocations(gLocation); + } + selectedButton = null; + ensureGridAlignment(); + } + } + + private void updateButtonLocations(GridLocation gLocation) { + // checks if moved from the first spot, so we can move other icons over but only as the same row + + boolean isFrom0XTo1X = selectedLocation.y() == gLocation.y() && selectedLocation.x() == 0 && gLocation.x() == 1; + selectedButton.setGridLocation(gLocation.x(), gLocation.y()); + + // Checks for icon that needs to be moved over + List buttonList = SidebarButtonManager.INSTANCE.getButtonList(); + for (SidebarGuiButton button : buttonList) { + GridLocation realGridLocation = realLocationMap.get(button); + if (realGridLocation != null) { + if (!selectedButton.getSidebarButton().getId().equals(button.getSidebarButton().getId())) { + if (gLocation.isLatterInColumn(realGridLocation)) { + int moveAmount = isFrom0XTo1X && realGridLocation.x() == 1 ? -1 : 1; + button.setGridLocation(realGridLocation.x() + moveAmount, realGridLocation.y()); + } + } + } + } + + // If the icon was disabled enable it + if (!selectedButton.isEnabled()) { + selectedButton.setEnabled(true); + if (SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).isEmpty()) { + addBoxOpen = false; + } + } + } + + // Aligns icons to a 'realLocationMap' this uses the button config as base, but checks if button is "visible" then aligns it to the grid + private void ensureGridAlignment() { + List enabledButtonList = SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode); + Map> buttonMap = enabledButtonList + .stream() + .filter(SidebarGuiButton::isEnabled) + .collect(Collectors.groupingBy(button -> button.getGirdLocation().y(), TreeMap::new, Collectors.toCollection(LinkedList::new))); realLocationMap.clear(); - int y = 0; - for (Map.Entry> entry : buttonMap.entrySet()) { - entry.getValue().sort(Comparator.comparingInt(b -> b.getGirdLocation().x())); - int x = 0; - for (SidebarGuiButton button : entry.getValue()) { - realLocationMap.put(button, new GridLocation(x, y)); - x++; - } - if (x != 0) { - y++; - } - } - - - SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); - updateWidgetSize(); - } - - private void updateWidgetSize() { - // Important: JEI doesn't like negative X/Y values and will silently clamp them, - // leading it to think the values have changed every frame, and do unnecessary updating - // of its GUI areas, including resetting the filter textfield's selection - // https://github.com/FTBTeam/FTB-Mods-Issues/issues/262 - // https://github.com/mezz/JustEnoughItems/issues/2938 - //This calculates the grid size - int girdAmountX = 1; - int girdAmountY = 1; - for (SidebarGuiButton b : SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode)) { - girdAmountX = Math.max(girdAmountX, b.getGirdLocation().x() + 1); - girdAmountY = Math.max(girdAmountY, b.getGirdLocation().y() + 1); - } - - if(isEditMode && addBoxOpen) { - int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).size(); - girdAmountX += 4; + int y = 0; + for (Map.Entry> entry : buttonMap.entrySet()) { + entry.getValue().sort(Comparator.comparingInt(b -> b.getGirdLocation().x())); + int x = 0; + for (SidebarGuiButton button : entry.getValue()) { + realLocationMap.put(button, new GridLocation(x, y)); + x++; + } + if (x != 0) { + y++; + } + } + + + SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); + updateWidgetSize(); + } + + private void updateWidgetSize() { + // Important: JEI doesn't like negative X/Y values and will silently clamp them, + // leading it to think the values have changed every frame, and do unnecessary updating + // of its GUI areas, including resetting the filter textfield's selection + // https://github.com/FTBTeam/FTB-Mods-Issues/issues/262 + // https://github.com/mezz/JustEnoughItems/issues/2938 + // This calculates the grid size + int girdAmountX = 1; + int girdAmountY = 1; + for (SidebarGuiButton b : SidebarButtonManager.INSTANCE.getEnabledButtonList(isEditMode)) { + girdAmountX = Math.max(girdAmountX, b.getGirdLocation().x() + 1); + girdAmountY = Math.max(girdAmountY, b.getGirdLocation().y() + 1); + } + + if (isEditMode && addBoxOpen) { + int disabledList = SidebarButtonManager.INSTANCE.getDisabledButtonList(isEditMode).size(); + girdAmountX += 4; girdAmountY = Math.max(girdAmountY, disabledList); - } - if(isEditMode) { - //Add 3 extra to the x so that add button is clickable - girdAmountX += 3; - //Add one extra y, so you can place widgets at the bottom - girdAmountY += 1; - } - - //ensure the grid size is not bigger than the screen - int screenWidth = Minecraft.getInstance().getWindow().getGuiScaledWidth(); - int screenHeight = Minecraft.getInstance().getWindow().getGuiScaledHeight(); + } + if (isEditMode) { + // Add 3 extra to the x so that add button is clickable + girdAmountX += 3; + // Add one extra y, so you can place widgets at the bottom + girdAmountY += 1; + } + + // ensure the grid size is not bigger than the screen + int screenWidth = Minecraft.getInstance().getWindow().getGuiScaledWidth(); + int screenHeight = Minecraft.getInstance().getWindow().getGuiScaledHeight(); int maxGirdAmountX = screenWidth / BUTTON_SPACING; int maxGirdAmountY = screenHeight / BUTTON_SPACING; - girdAmountX = Math.min(girdAmountX, maxGirdAmountX); - girdAmountY = Math.min(girdAmountY, maxGirdAmountY); - - - width = (girdAmountX) * BUTTON_SPACING; - height = (girdAmountY) * BUTTON_SPACING; - - FTBLibraryClientConfig.SidebarPosition sidebarPosition = FTBLibraryClientConfig.SIDEBAR_POSITION.get(); - - if (sidebarPosition.isBottom()) { - setY(screenHeight - height - 2); - gridStartBottom = true; - } else { - setY(0); - gridStartBottom = false; - } - if(sidebarPosition.isRight()) { - setX(screenWidth - width - 2); - gridStartRight = true; - } else { - setX(0); - gridStartRight = false; - } - - currentGirdWidth = 1; - currentGridHeight = 1; - - for (Map.Entry value : realLocationMap.entrySet()) { - GridLocation location = value.getValue(); - currentGirdWidth = Math.max(currentGirdWidth, location.x() + 1); - currentGridHeight = Math.max(currentGridHeight, location.y() + 1); - } - - if(isEditMode) { - currentGirdWidth += 1; - currentGridHeight += 1; - } - - xRenderStart = (gridStartRight ? maxGirdAmountX - currentGirdWidth : 0) * BUTTON_SPACING; - yRenderStart = (gridStartBottom ? maxGirdAmountY - currentGridHeight + 1 : 0) * BUTTON_SPACING; - - if(gridStartBottom) { - yRenderStart -= 4; - } - if(gridStartRight) { - xRenderStart += 3; - } - - //Set the last drawn area so recipe viewer knows where we are and we can move it out the way - lastDrawnArea = new Rect2i(getX(), getY(), width, height); - } - - private GridLocation getGridLocation() { - - int gridX = (currentMouseX - xRenderStart - 1) / BUTTON_SPACING; - int gridY = (currentMouseY - yRenderStart - 1) / BUTTON_SPACING; - - if (gridStartRight) { - gridX = currentGirdWidth - gridX - 1; - } - - if (gridStartBottom) { - gridY = currentGridHeight - gridY - 1; - } - - if (gridX >= currentGirdWidth || gridY >= currentGridHeight || gridX < 0 || gridY < 0) { - return GridLocation.OUT_OF_BOUNDS; - } - - return new GridLocation(gridX, gridY); - } - - - @Override - public void onPress() { - if(lastMouseClickButton == 1) { - isEditMode = !isEditMode; - ensureGridAlignment(); - return; - } - if(mouseOverSettingsIcon) { - FTBLibraryClient.editConfig(true); - return; - } - if(isEditMode) { - if (isMouseOverAdd) { - addBoxOpen = !addBoxOpen; - updateWidgetSize(); - return; - } - } - if(mouseOver != null) { - - mouseOffsetX = currentMouseX - mouseOver.x; - mouseOffsetY = currentMouseY - mouseOver.y; - - if(isEditMode) { - if(currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4 && currentMouseX < mouseOver.x + 16 && currentMouseY >= mouseOver.y) { - mouseOver.setEnabled(false); - mouseOver = null; - ensureGridAlignment(); - return; - } - - selectedButton = mouseOver; - GridLocation realGridLocation = realLocationMap.get(selectedButton); - selectedLocation = realGridLocation == null ? selectedButton.getGirdLocation() : realGridLocation; - } - } - } - - @Override - public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) { - defaultButtonNarrationText(narrationElementOutput); - } - - - //Custom handling so our button click locations are where a buttons are not just a box - @Override - protected boolean isValidClickButton(int i) { - boolean inBounds = clicked(currentMouseX, currentMouseY); - if(!inBounds && isEditMode) { - isEditMode = false; - return false; - } - lastMouseClickButton = i; - if(i == 1) { - return inBounds; - } - if (super.isValidClickButton(i)) { - if (isEditMode) { - return isMouseOverAdd || selectedButton != null || mouseOver != null; - } else { - GridLocation gridLocation = getGridLocation(); - return (gridLocation.y() == 0 && gridLocation.x() == 0) || mouseOver != null; - } - } - return false; - } - - private static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacingWidth, int spacingHeight, Color4I backgroundColor, Color4I gridColor) { - backgroundColor.draw(graphics, x, y, width * spacingWidth, height * spacingHeight); - for (var i = 0; i < width + 1; i++) { - gridColor.draw(graphics, x + i * spacingWidth, y, 1, height * spacingHeight + 1); - } - for (var i = 0; i < height + 1; i++) { - gridColor.draw(graphics, x, y + i * spacingHeight, width * spacingWidth, 1); - } - } - - public static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor) { - drawGrid(graphics, x, y, width, height, spacing, spacing, backgroundColor, gridColor); - } - - private static void drawHoveredGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor, int mx, int my, boolean gridStartBottom, boolean gridStartRight, int posX, int posY) { - drawGrid(graphics, x, y, width, height, spacing, backgroundColor, gridColor); - - int adjustedMx = mx; - int adjustedMy = my; - - if (gridStartRight) { - adjustedMx = x + width * spacing - (mx - x); - } - - if (gridStartBottom) { - adjustedMy = y + height * spacing - (my - y); - } - - if (adjustedMx >= x + posX && adjustedMy >= y + posY && adjustedMx < x + posX + width * spacing && adjustedMy < y + posY + height * spacing) { - int gridX = (adjustedMx - x - posX) / spacing; - int gridY = (adjustedMy - y - posY) / spacing; - Color4I.WHITE.withAlpha(127).draw(graphics, gridX * BUTTON_SPACING + 1, gridY * BUTTON_SPACING + 1, spacing - 1, spacing - 1); - } - } + girdAmountX = Math.min(girdAmountX, maxGirdAmountX); + girdAmountY = Math.min(girdAmountY, maxGirdAmountY); + + + width = (girdAmountX) * BUTTON_SPACING; + height = (girdAmountY) * BUTTON_SPACING; + + FTBLibraryClientConfig.SidebarPosition sidebarPosition = FTBLibraryClientConfig.SIDEBAR_POSITION.get(); + + if (sidebarPosition.isBottom()) { + setY(screenHeight - height - 2); + gridStartBottom = true; + } else { + setY(0); + gridStartBottom = false; + } + if (sidebarPosition.isRight()) { + setX(screenWidth - width - 2); + gridStartRight = true; + } else { + setX(0); + gridStartRight = false; + } + + currentGirdWidth = 1; + currentGridHeight = 1; + + for (Map.Entry value : realLocationMap.entrySet()) { + GridLocation location = value.getValue(); + currentGirdWidth = Math.max(currentGirdWidth, location.x() + 1); + currentGridHeight = Math.max(currentGridHeight, location.y() + 1); + } + + if (isEditMode) { + currentGirdWidth += 1; + currentGridHeight += 1; + } + + xRenderStart = (gridStartRight ? maxGirdAmountX - currentGirdWidth : 0) * BUTTON_SPACING; + yRenderStart = (gridStartBottom ? maxGirdAmountY - currentGridHeight + 1 : 0) * BUTTON_SPACING; + + if (gridStartBottom) { + yRenderStart -= 4; + } + if (gridStartRight) { + xRenderStart += 3; + } + + // Set the last drawn area so recipe viewer knows where we are and we can move it out the way + lastDrawnArea = new Rect2i(getX(), getY(), width, height); + } + + private GridLocation getGridLocation() { + + int gridX = (currentMouseX - xRenderStart - 1) / BUTTON_SPACING; + int gridY = (currentMouseY - yRenderStart - 1) / BUTTON_SPACING; + + if (gridStartRight) { + gridX = currentGirdWidth - gridX - 1; + } + + if (gridStartBottom) { + gridY = currentGridHeight - gridY - 1; + } + + if (gridX >= currentGirdWidth || gridY >= currentGridHeight || gridX < 0 || gridY < 0) { + return GridLocation.OUT_OF_BOUNDS; + } + + return new GridLocation(gridX, gridY); + } + + + @Override + public void onPress() { + if (lastMouseClickButton == 1) { + isEditMode = !isEditMode; + ensureGridAlignment(); + return; + } + if (mouseOverSettingsIcon) { + FTBLibraryClient.editConfig(true); + return; + } + if (isEditMode && isMouseOverAdd) { + addBoxOpen = !addBoxOpen; + updateWidgetSize(); + return; + } + if (mouseOver != null) { + + mouseOffsetX = currentMouseX - mouseOver.x; + mouseOffsetY = currentMouseY - mouseOver.y; + + if (isEditMode) { + // if the mouse is over the cancel icon + if (currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4 && currentMouseX < mouseOver.x + 16 && currentMouseY >= mouseOver.y) { + mouseOver.setEnabled(false); + mouseOver = null; + ensureGridAlignment(); + return; + } + + selectedButton = mouseOver; + GridLocation realGridLocation = realLocationMap.get(selectedButton); + selectedLocation = realGridLocation == null ? selectedButton.getGirdLocation() : realGridLocation; + } + } + } + + @Override + public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) { + defaultButtonNarrationText(narrationElementOutput); + } + + // Custom handling so our button click locations are where a buttons are not just a box + @Override + protected boolean isValidClickButton(int i) { + boolean inBounds = clicked(currentMouseX, currentMouseY); + if (!inBounds && isEditMode) { + isEditMode = false; + return false; + } + lastMouseClickButton = i; + if (i == 1) { + return inBounds; + } + if (super.isValidClickButton(i)) { + if (isEditMode) { + return isMouseOverAdd || selectedButton != null || mouseOver != null; + } else { + GridLocation gridLocation = getGridLocation(); + return (gridLocation.y() == 0 && gridLocation.x() == 0) || mouseOver != null; + } + } + return false; + } + + private static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacingWidth, int spacingHeight, Color4I backgroundColor, Color4I gridColor) { + backgroundColor.draw(graphics, x, y, width * spacingWidth, height * spacingHeight); + for (var i = 0; i < width + 1; i++) { + gridColor.draw(graphics, x + i * spacingWidth, y, 1, height * spacingHeight + 1); + } + for (var i = 0; i < height + 1; i++) { + gridColor.draw(graphics, x, y + i * spacingHeight, width * spacingWidth, 1); + } + } + + public static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor) { + drawGrid(graphics, x, y, width, height, spacing, spacing, backgroundColor, gridColor); + } + + private static void drawHoveredGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacing, Color4I backgroundColor, Color4I gridColor, int mx, int my, boolean gridStartBottom, boolean gridStartRight, int posX, int posY) { + drawGrid(graphics, x, y, width, height, spacing, backgroundColor, gridColor); + + int adjustedMx = mx; + int adjustedMy = my; + + if (gridStartRight) { + adjustedMx = x + width * spacing - (mx - x); + } + + if (gridStartBottom) { + adjustedMy = y + height * spacing - (my - y); + } + + if (adjustedMx >= x + posX && adjustedMy >= y + posY && adjustedMx < x + posX + width * spacing && adjustedMy < y + posY + height * spacing) { + int gridX = (adjustedMx - x - posX) / spacing; + int gridY = (adjustedMy - y - posY) / spacing; + Color4I.WHITE.withAlpha(127).draw(graphics, gridX * BUTTON_SPACING + 1, gridY * BUTTON_SPACING + 1, spacing - 1, spacing - 1); + } + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java index ce77cfc4..4108aa28 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGuiButton.java @@ -2,41 +2,40 @@ public class SidebarGuiButton { - private final SidebarButton sidebarButton; - public int x, y; - private GridLocation gridLocation; - private boolean enabled; - - public SidebarGuiButton(GridLocation girdLocation, boolean enabled, SidebarButton sidebarButton) { - x = 0; - y = 0; - this.gridLocation = girdLocation; - this.sidebarButton = sidebarButton; - this.enabled = enabled; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public SidebarButton getSidebarButton() { - return sidebarButton; - } - - public GridLocation getGirdLocation() { - return gridLocation; - } - - public void setGridLocation(GridLocation gridLocation) { - this.gridLocation = gridLocation; - } - - public void setGridLocation(int x, int y) { - this.gridLocation = new GridLocation(x, y); - } - + private final RegisteredSidebarButton sidebarButton; + public int x, y; + private GridLocation gridLocation; + private boolean enabled; + + public SidebarGuiButton(GridLocation girdLocation, boolean enabled, RegisteredSidebarButton sidebarButton) { + x = 0; + y = 0; + this.gridLocation = girdLocation; + this.sidebarButton = sidebarButton; + this.enabled = enabled; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public RegisteredSidebarButton getSidebarButton() { + return sidebarButton; + } + + public GridLocation getGirdLocation() { + return gridLocation; + } + + public void setGridLocation(GridLocation gridLocation) { + this.gridLocation = gridLocation; + } + + public void setGridLocation(int x, int y) { + this.gridLocation = new GridLocation(x, y); + } } diff --git a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json b/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json deleted file mode 100644 index f8dc8e2b..00000000 --- a/common/src/main/resources/assets/ftblibrary/sidebar_buttons/test.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "icon": [ - "ftblibrary:icons/blue_button", - "ftblibrary:textures/icons/camera.png" - ], - "sort_index": 5000, - "click": ["command:/say hi"], - "required_mods": [ - "ftblibrary", - "neotech" - ], - "requires_op": true -} \ No newline at end of file diff --git a/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java b/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java index 5da77bf4..057af2be 100644 --- a/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java +++ b/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java @@ -8,8 +8,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -//Need to make sure mouseReleased is called for widgets -//See https://github.com/FabricMC/fabric/pull/4010 +// Need to make sure mouseReleased is called for widgets +// See https://github.com/FabricMC/fabric/pull/4010 @Mixin(AbstractContainerScreen.class) public abstract class AbstractContainerScreenMixin extends Screen { diff --git a/gradle.properties b/gradle.properties index 9cf3a21e..b92505a2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ org.gradle.daemon=false # Mod mod_id=ftblibrary readable_name=FTB Library -mod_version=2100.1.4 +mod_version=2100.1.5 mod_author=FTB Team # Maven From 9f7f2079440c2764f4b84f8eed29e69b26214f30 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Thu, 8 Aug 2024 11:59:51 -0500 Subject: [PATCH 15/17] Another pass at formatting issues --- .../ftblibrary/api/sidebar/SidebarButton.java | 2 +- .../sidebar/RegisteredSidebarButton.java | 2 +- .../sidebar/SidebarGroupGuiButton.java | 41 +++++++++---------- 3 files changed, 22 insertions(+), 23 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java index 9e87f7ea..68e893a2 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java @@ -10,7 +10,7 @@ public interface SidebarButton { /** - * @return id of button used for storing + * @return the id of the button used for saving config data created from the location button in resource path */ ResourceLocation getId(); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/RegisteredSidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/RegisteredSidebarButton.java index f8078b89..613027d8 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/RegisteredSidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/RegisteredSidebarButton.java @@ -72,7 +72,7 @@ public void clickButton(boolean shift) { new LoadingScreen(Component.translatable(getLangKey())).openGui(); } - boolean canShift = data.shiftClickEvent().isPresent(); + boolean canShift = shift && data.shiftClickEvent().isPresent(); List clickEvents = canShift ? data.shiftClickEvent().get() : data.clickEvents(); for (String event : clickEvents) { GuiHelper.BLANK_GUI.handleClick(event); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index c7de1e68..a5cc273e 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -33,7 +33,8 @@ public class SidebarGroupGuiButton extends AbstractButton { private static final List noButtonComponents = List.of( Component.translatable("sidebar_button.ftblibrary.config"), - Component.translatable("sidebar_button.ftblibrary.config.enter_edit_mode")); + Component.translatable("sidebar_button.ftblibrary.config.enter_edit_mode") + ); private SidebarGuiButton mouseOver; private SidebarGuiButton selectedButton; @@ -71,31 +72,29 @@ public SidebarGroupGuiButton() { @Override public void renderWidget(GuiGraphics graphics, int mx, int my, float partialTicks) { graphics.pose().pushPose(); - { - graphics.pose().translate(0, 0, 5000); + graphics.pose().translate(0, 0, 5000); - currentMouseX = mx; - currentMouseY = my; - mouseOver = null; - isMouseOverAdd = false; - mouseOverSettingsIcon = false; + currentMouseX = mx; + currentMouseY = my; + mouseOver = null; + isMouseOverAdd = false; + mouseOverSettingsIcon = false; - GridLocation gridLocation = getGridLocation(); + GridLocation gridLocation = getGridLocation(); - for (Map.Entry entry : realLocationMap.entrySet()) { - SidebarGuiButton button = entry.getKey(); - if (entry.getValue().equals(gridLocation)) { - mouseOver = button; - } + for (Map.Entry entry : realLocationMap.entrySet()) { + SidebarGuiButton button = entry.getKey(); + if (entry.getValue().equals(gridLocation)) { + mouseOver = button; } + } - if (isEditMode) { - renderEditMode(graphics, mx, my); - } + if (isEditMode) { + renderEditMode(graphics, mx, my); + } - renderSidebarButtons(graphics, mx, my); + renderSidebarButtons(graphics, mx, my); - } graphics.pose().popPose(); } @@ -237,7 +236,7 @@ public void onRelease(double d, double e) { mouseOver.getSidebarButton().clickButton(Screen.hasShiftDown()); } else if (selectedButton != null) { GridLocation gLocation = getGridLocation(); - // Make sure the placement is in grid and that is not in the same location + // Make sure the placement is in grid and that is not in the same location that it was picked up from if (!gLocation.isOutOfBounds() && !gLocation.equals(selectedLocation)) { updateButtonLocations(gLocation); } @@ -247,7 +246,7 @@ public void onRelease(double d, double e) { } private void updateButtonLocations(GridLocation gLocation) { - // checks if moved from the first spot, so we can move other icons over but only as the same row + // Checks if moved from the first spot, so we can move other icons over but only as the same row boolean isFrom0XTo1X = selectedLocation.y() == gLocation.y() && selectedLocation.x() == 0 && gLocation.x() == 1; selectedButton.setGridLocation(gLocation.x(), gLocation.y()); From 6ba93c69e11af4fd4362fa58849a629cf9d6fad9 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Thu, 8 Aug 2024 12:20:57 -0500 Subject: [PATCH 16/17] move SidebarCreatedEvent and Code Cleanup --- .../ftblibrary/api/sidebar/SidebarButton.java | 9 --- .../sidebar/SidebarButtonCreatedEvent.java | 4 +- .../sidebar/SidebarButtonManager.java | 8 +++ .../sidebar/SidebarGroupGuiButton.java | 65 ++++++++++++------- 4 files changed, 50 insertions(+), 36 deletions(-) rename common/src/main/java/dev/ftb/mods/ftblibrary/{ => api}/sidebar/SidebarButtonCreatedEvent.java (85%) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java index 68e893a2..eefe69bf 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButton.java @@ -14,15 +14,6 @@ public interface SidebarButton { */ ResourceLocation getId(); - /** - * @param customTextHandler A supplier that returns the text to be displayed on the button - * @deprecated Use {@link #addOverlayRender(ButtonOverlayRender)} instead - */ - @Deprecated(forRemoval = true) - default void setCustomTextHandler(Supplier customTextHandler) { - addOverlayRender(ButtonOverlayRender.ofSimpleString(customTextHandler)); - } - /** * Register a condition that must be met for the button to be visible * @param condition a condition that must be met for the button to be visible diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButtonCreatedEvent.java similarity index 85% rename from common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java rename to common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButtonCreatedEvent.java index 2d2764e2..ac878bc3 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonCreatedEvent.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButtonCreatedEvent.java @@ -1,11 +1,11 @@ -package dev.ftb.mods.ftblibrary.sidebar; +package dev.ftb.mods.ftblibrary.api.sidebar; import dev.architectury.event.Event; import dev.architectury.event.EventFactory; +import dev.ftb.mods.ftblibrary.sidebar.RegisteredSidebarButton; import java.util.function.Consumer; -// Todo move this to api class in the future - unreal // TODO currently broken for neoforge, uncomment when there's a fix in architectury //@ForgeEvent public class SidebarButtonCreatedEvent { diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index 5a8a9e96..0f33b529 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -9,6 +9,7 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; import dev.ftb.mods.ftblibrary.FTBLibrary; +import dev.ftb.mods.ftblibrary.api.sidebar.SidebarButtonCreatedEvent; import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import dev.ftb.mods.ftblibrary.snbt.config.StringSidebarMapValue; import dev.ftb.mods.ftblibrary.util.MapUtils; @@ -62,8 +63,10 @@ public void onResourceManagerReload(ResourceManager manager) { buttonList.clear(); List sortedButtons = buttons.values().stream().sorted(Comparator.comparingInt(value -> value.getData().sortIndex())).toList(); + int y = 0; int x = 0; + for (RegisteredSidebarButton buttonEntry : sortedButtons) { StringSidebarMapValue.SideButtonInfo buttonSettings = FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().get(buttonEntry.getId().toString()); if (buttonSettings == null) { @@ -72,12 +75,14 @@ public void onResourceManagerReload(ResourceManager manager) { FTBLibraryClientConfig.save(); } buttonList.add(new SidebarGuiButton(new GridLocation(buttonSettings.xPos(), buttonSettings.yPos()), buttonSettings.enabled(), buttonEntry)); + x++; if (x >= 4) { x = 0; y++; } } + for (RegisteredSidebarButton value : buttons.values()) { SidebarButtonCreatedEvent.EVENT.invoker().accept(new SidebarButtonCreatedEvent(value)); } @@ -89,6 +94,7 @@ private void loadResources(ResourceManager manager, String path, Codec co for (Map.Entry resource : resourceLocationResourceMap.entrySet()) { JsonElement jsonElement = readJson(resource.getValue()); DataResult parse = codec.parse(JsonOps.INSTANCE, jsonElement); + if (parse.error().isPresent()) { FTBLibrary.LOGGER.error("Failed to parse json: {}", parse.error().get().message()); } else { @@ -116,10 +122,12 @@ public void saveConfigFromButtonList() { FTBLibraryClientConfig.SIDEBAR_BUTTONS.get().put(button.getSidebarButton().getId().toString(), new StringSidebarMapValue.SideButtonInfo(false, -1, -1)); } } + int x = 0; integerListEntry.getValue() .sort(Comparator.comparingInt((SidebarGuiButton button) -> button.getGirdLocation().x())); List value = integerListEntry.getValue(); + for (SidebarGuiButton sidebarButton : value) { if (sidebarButton.isEnabled()) { sidebarButton.setGridLocation(x, y); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index a5cc273e..d89080df 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -125,9 +125,9 @@ private void renderSidebarButtons(GuiGraphics graphics, int mx, int my) { if (realGridLocation == null) { continue; } + int adjustedX = gridStartRight ? xRenderStart + (currentGirdWidth - realGridLocation.x() - 1) * BUTTON_SPACING : xRenderStart + realGridLocation.x() * BUTTON_SPACING; int adjustedY = gridStartBottom ? yRenderStart + (currentGridHeight - realGridLocation.y() - 1) * BUTTON_SPACING : yRenderStart + realGridLocation.y() * BUTTON_SPACING; - button.x = adjustedX + 1; button.y = adjustedY + 1; } @@ -190,6 +190,7 @@ private void renderEditMode(GuiGraphics graphics, int mx, int my) { graphics.pose().pushPose(); graphics.pose().translate(0, 0, 1000); + if (gridStartRight) { drawHoveredGrid(graphics, addIconX, gridY, 1, disabledButtonList.size(), BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK, mx, my, gridStartBottom, gridStartRight, gridX, gridY); drawGrid(graphics, addIconX - maxWidth - 6, gridY, 1, disabledButtonList.size(), maxWidth + 6, BUTTON_SPACING, Color4I.GRAY, Color4I.BLACK); @@ -203,6 +204,7 @@ private void renderEditMode(GuiGraphics graphics, int mx, int my) { if (selectedButton != null && selectedButton == button) { continue; } + int buttonY = gridY + BUTTON_SPACING * i; button.x = gridStartRight ? addIconX : gridX; button.y = buttonY; @@ -236,6 +238,7 @@ public void onRelease(double d, double e) { mouseOver.getSidebarButton().clickButton(Screen.hasShiftDown()); } else if (selectedButton != null) { GridLocation gLocation = getGridLocation(); + // Make sure the placement is in grid and that is not in the same location that it was picked up from if (!gLocation.isOutOfBounds() && !gLocation.equals(selectedLocation)) { updateButtonLocations(gLocation); @@ -255,14 +258,16 @@ private void updateButtonLocations(GridLocation gLocation) { List buttonList = SidebarButtonManager.INSTANCE.getButtonList(); for (SidebarGuiButton button : buttonList) { GridLocation realGridLocation = realLocationMap.get(button); - if (realGridLocation != null) { - if (!selectedButton.getSidebarButton().getId().equals(button.getSidebarButton().getId())) { - if (gLocation.isLatterInColumn(realGridLocation)) { - int moveAmount = isFrom0XTo1X && realGridLocation.x() == 1 ? -1 : 1; - button.setGridLocation(realGridLocation.x() + moveAmount, realGridLocation.y()); - } - } + if (realGridLocation == null || selectedButton.getSidebarButton().getId().equals(button.getSidebarButton().getId())) { + continue; + } + + if (!gLocation.isLatterInColumn(realGridLocation)) { + continue; } + + int moveAmount = isFrom0XTo1X && realGridLocation.x() == 1 ? -1 : 1; + button.setGridLocation(realGridLocation.x() + moveAmount, realGridLocation.y()); } // If the icon was disabled enable it @@ -287,6 +292,7 @@ private void ensureGridAlignment() { int y = 0; for (Map.Entry> entry : buttonMap.entrySet()) { entry.getValue().sort(Comparator.comparingInt(b -> b.getGirdLocation().x())); + int x = 0; for (SidebarGuiButton button : entry.getValue()) { realLocationMap.put(button, new GridLocation(x, y)); @@ -297,7 +303,6 @@ private void ensureGridAlignment() { } } - SidebarButtonManager.INSTANCE.saveConfigFromButtonList(); updateWidgetSize(); } @@ -350,6 +355,7 @@ private void updateWidgetSize() { setY(0); gridStartBottom = false; } + if (sidebarPosition.isRight()) { setX(screenWidth - width - 2); gridStartRight = true; @@ -387,7 +393,6 @@ private void updateWidgetSize() { } private GridLocation getGridLocation() { - int gridX = (currentMouseX - xRenderStart - 1) / BUTTON_SPACING; int gridY = (currentMouseY - yRenderStart - 1) / BUTTON_SPACING; @@ -414,34 +419,40 @@ public void onPress() { ensureGridAlignment(); return; } + if (mouseOverSettingsIcon) { FTBLibraryClient.editConfig(true); return; } + if (isEditMode && isMouseOverAdd) { addBoxOpen = !addBoxOpen; updateWidgetSize(); return; } - if (mouseOver != null) { - mouseOffsetX = currentMouseX - mouseOver.x; - mouseOffsetY = currentMouseY - mouseOver.y; + if (mouseOver == null) { + return; + } - if (isEditMode) { - // if the mouse is over the cancel icon - if (currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4 && currentMouseX < mouseOver.x + 16 && currentMouseY >= mouseOver.y) { - mouseOver.setEnabled(false); - mouseOver = null; - ensureGridAlignment(); - return; - } + mouseOffsetX = currentMouseX - mouseOver.x; + mouseOffsetY = currentMouseY - mouseOver.y; - selectedButton = mouseOver; - GridLocation realGridLocation = realLocationMap.get(selectedButton); - selectedLocation = realGridLocation == null ? selectedButton.getGirdLocation() : realGridLocation; - } + if (!isEditMode) { + return; } + + // if the mouse is over the cancel icon + if (currentMouseX >= mouseOver.x + 12 && currentMouseY <= mouseOver.y + 4 && currentMouseX < mouseOver.x + 16 && currentMouseY >= mouseOver.y) { + mouseOver.setEnabled(false); + mouseOver = null; + ensureGridAlignment(); + return; + } + + selectedButton = mouseOver; + GridLocation realGridLocation = realLocationMap.get(selectedButton); + selectedLocation = realGridLocation == null ? selectedButton.getGirdLocation() : realGridLocation; } @Override @@ -457,10 +468,12 @@ protected boolean isValidClickButton(int i) { isEditMode = false; return false; } + lastMouseClickButton = i; if (i == 1) { return inBounds; } + if (super.isValidClickButton(i)) { if (isEditMode) { return isMouseOverAdd || selectedButton != null || mouseOver != null; @@ -474,9 +487,11 @@ protected boolean isValidClickButton(int i) { private static void drawGrid(GuiGraphics graphics, int x, int y, int width, int height, int spacingWidth, int spacingHeight, Color4I backgroundColor, Color4I gridColor) { backgroundColor.draw(graphics, x, y, width * spacingWidth, height * spacingHeight); + for (var i = 0; i < width + 1; i++) { gridColor.draw(graphics, x + i * spacingWidth, y, 1, height * spacingHeight + 1); } + for (var i = 0; i < height + 1; i++) { gridColor.draw(graphics, x, y + i * spacingHeight, width * spacingWidth, 1); } From b6fb15ef33b4b5f0b3559af15a2e685f216b37a3 Mon Sep 17 00:00:00 2001 From: UnRealDinnerbone Date: Fri, 9 Aug 2024 08:47:57 -0500 Subject: [PATCH 17/17] Convert to SimpleJsonResourceReloadListener and basic code cleanup --- .../sidebar/SidebarButtonCreatedEvent.java | 2 - .../mods/ftblibrary/sidebar/GridLocation.java | 4 +- .../sidebar/SidebarButtonManager.java | 41 +++++++++---------- .../sidebar/SidebarGroupGuiButton.java | 4 +- .../ftb/mods/ftblibrary/util/MapUtils.java | 6 +-- .../fabric/AbstractContainerScreenMixin.java | 2 +- 6 files changed, 26 insertions(+), 33 deletions(-) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButtonCreatedEvent.java b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButtonCreatedEvent.java index ac878bc3..502a3850 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButtonCreatedEvent.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/api/sidebar/SidebarButtonCreatedEvent.java @@ -6,8 +6,6 @@ import java.util.function.Consumer; -// TODO currently broken for neoforge, uncomment when there's a fix in architectury -//@ForgeEvent public class SidebarButtonCreatedEvent { public static final Event> EVENT = EventFactory.createConsumerLoop(SidebarButtonCreatedEvent.class); diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java index 2aa86e39..04d553be 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/GridLocation.java @@ -8,11 +8,11 @@ public boolean isOutOfBounds() { return x < 0 || y < 0; } - public boolean isLatterInRow(GridLocation other) { + public boolean isLaterInRow(GridLocation other) { return x == other.x && y <= other.y; } - public boolean isLatterInColumn(GridLocation other) { + public boolean isLaterInColumn(GridLocation other) { return x <= other.x && y == other.y; } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java index 0f33b529..948825bd 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarButtonManager.java @@ -1,5 +1,7 @@ package dev.ftb.mods.ftblibrary.sidebar; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonParseException; @@ -17,6 +19,8 @@ import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; +import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener; +import net.minecraft.util.profiling.ProfilerFiller; import org.slf4j.Logger; import java.io.BufferedReader; @@ -32,34 +36,24 @@ import java.util.stream.Collectors; -public enum SidebarButtonManager implements ResourceManagerReloadListener { - INSTANCE; +public class SidebarButtonManager extends SimpleJsonResourceReloadListener { - private static final Logger LOGGER = LogUtils.getLogger(); + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + public static final SidebarButtonManager INSTANCE = new SidebarButtonManager(); private final Map buttons = new HashMap<>(); - private final List buttonList = new ArrayList<>(); - private JsonElement readJson(Resource resource) { - try (BufferedReader reader = resource.openAsReader()) { - return JsonParser.parseReader(reader); - } catch (JsonParseException | IOException e) { - LOGGER.error("can't read {}: {}", resource.sourcePackId(), e.getMessage()); - } - return JsonNull.INSTANCE; - } - - public Collection getButtons() { - return buttons.values(); + public SidebarButtonManager() { + super(GSON, "sidebar_buttons"); } @Override - public void onResourceManagerReload(ResourceManager manager) { + protected void apply(Map object, ResourceManager resourceManager, ProfilerFiller profilerFiller) { buttons.clear(); // Read the button and group json files and register them to their 'registry' map - loadResources(manager, "sidebar_buttons", SidebarButtonData.CODEC, (id, buttonData) -> buttons.put(id, new RegisteredSidebarButton(id, buttonData))); + loadResources(object, SidebarButtonData.CODEC, (id, buttonData) -> buttons.put(id, new RegisteredSidebarButton(id, buttonData))); buttonList.clear(); List sortedButtons = buttons.values().stream().sorted(Comparator.comparingInt(value -> value.getData().sortIndex())).toList(); @@ -89,10 +83,9 @@ public void onResourceManagerReload(ResourceManager manager) { FTBLibraryClientConfig.save(); } - private void loadResources(ResourceManager manager, String path, Codec codec, BiConsumer consumer) { - Map resourceLocationResourceMap = manager.listResources(path, name -> name.getPath().endsWith(".json")); - for (Map.Entry resource : resourceLocationResourceMap.entrySet()) { - JsonElement jsonElement = readJson(resource.getValue()); + private void loadResources(Map objects, Codec codec, BiConsumer consumer) { + for (Map.Entry resource : objects.entrySet()) { + JsonElement jsonElement = resource.getValue(); DataResult parse = codec.parse(JsonOps.INSTANCE, jsonElement); if (parse.error().isPresent()) { @@ -101,7 +94,7 @@ private void loadResources(ResourceManager manager, String path, Codec co T result = parse.result().get(); ResourceLocation key = resource.getKey(); String path1 = key.getPath(); - ResourceLocation fixed = ResourceLocation.fromNamespaceAndPath(key.getNamespace(), path1.replace(path + "/", "").replace(".json", "")); + ResourceLocation fixed = ResourceLocation.fromNamespaceAndPath(key.getNamespace(), key.getPath()); consumer.accept(fixed, result); } } @@ -166,4 +159,8 @@ public List getDisabledButtonList(boolean all) { .filter(button -> all || button.getSidebarButton().canSee()) .collect(Collectors.toList()); } + + public Collection getButtons() { + return buttons.values(); + } } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java index d89080df..0266390b 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/sidebar/SidebarGroupGuiButton.java @@ -14,9 +14,7 @@ import net.minecraft.client.renderer.Rect2i; import net.minecraft.client.resources.language.I18n; import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; @@ -262,7 +260,7 @@ private void updateButtonLocations(GridLocation gLocation) { continue; } - if (!gLocation.isLatterInColumn(realGridLocation)) { + if (!gLocation.isLaterInColumn(realGridLocation)) { continue; } diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/util/MapUtils.java b/common/src/main/java/dev/ftb/mods/ftblibrary/util/MapUtils.java index 62a71996..7421189c 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/util/MapUtils.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/util/MapUtils.java @@ -1,7 +1,7 @@ package dev.ftb.mods.ftblibrary.util; import java.util.Comparator; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; @@ -14,7 +14,7 @@ public static Map sortMapByKey(Map map, Comparator compara Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, - HashMap::new + LinkedHashMap::new )); } @@ -25,7 +25,7 @@ public static , V> Map sortMapByKey(Map a, - HashMap::new + LinkedHashMap::new )); } } \ No newline at end of file diff --git a/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java b/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java index 057af2be..1bf21844 100644 --- a/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java +++ b/fabric/src/main/java/dev/ftb/mods/ftblibrary/core/mixin/fabric/AbstractContainerScreenMixin.java @@ -20,7 +20,7 @@ protected AbstractContainerScreenMixin(Component component) { @Inject(at = @At("HEAD"), method = "mouseReleased", cancellable = true) public void onMouseReleased(double mouseX, double mouseY, int button, CallbackInfoReturnable info) { if(super.mouseReleased(mouseX, mouseY, button)) { - info.cancel(); + info.setReturnValue(true); } } }