From d163b9128d760e53e34fd6c08dbf782fa3d50c51 Mon Sep 17 00:00:00 2001 From: isXander Date: Sun, 27 Nov 2022 18:17:36 +0000 Subject: split sourcesets --- .../java/dev/isxander/yacl/gui/AbstractWidget.java | 108 +++++ .../dev/isxander/yacl/gui/CategoryListWidget.java | 96 +++++ .../java/dev/isxander/yacl/gui/CategoryWidget.java | 31 ++ .../isxander/yacl/gui/LowProfileButtonWidget.java | 29 ++ .../dev/isxander/yacl/gui/OptionListWidget.java | 470 +++++++++++++++++++++ .../isxander/yacl/gui/RequireRestartScreen.java | 16 + .../dev/isxander/yacl/gui/SearchFieldWidget.java | 62 +++ .../isxander/yacl/gui/TextScaledButtonWidget.java | 44 ++ .../dev/isxander/yacl/gui/TooltipButtonWidget.java | 30 ++ .../java/dev/isxander/yacl/gui/YACLScreen.java | 269 ++++++++++++ .../yacl/gui/controllers/ActionController.java | 120 ++++++ .../yacl/gui/controllers/BooleanController.java | 156 +++++++ .../yacl/gui/controllers/ColorController.java | 203 +++++++++ .../yacl/gui/controllers/ControllerWidget.java | 165 ++++++++ .../yacl/gui/controllers/LabelController.java | 144 +++++++ .../yacl/gui/controllers/TickBoxController.java | 120 ++++++ .../cycling/CyclingControllerElement.java | 60 +++ .../controllers/cycling/CyclingListController.java | 79 ++++ .../gui/controllers/cycling/EnumController.java | 60 +++ .../controllers/cycling/ICyclingController.java | 38 ++ .../yacl/gui/controllers/package-info.java | 12 + .../controllers/slider/DoubleSliderController.java | 114 +++++ .../controllers/slider/FloatSliderController.java | 114 +++++ .../gui/controllers/slider/ISliderController.java | 54 +++ .../slider/IntegerSliderController.java | 111 +++++ .../controllers/slider/LongSliderController.java | 111 +++++ .../slider/SliderControllerElement.java | 160 +++++++ .../yacl/gui/controllers/slider/package-info.java | 10 + .../gui/controllers/string/IStringController.java | 32 ++ .../gui/controllers/string/StringController.java | 45 ++ .../string/StringControllerElement.java | 283 +++++++++++++ 31 files changed, 3346 insertions(+) create mode 100644 src/client/java/dev/isxander/yacl/gui/AbstractWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/CategoryListWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/CategoryWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/LowProfileButtonWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/OptionListWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/RequireRestartScreen.java create mode 100644 src/client/java/dev/isxander/yacl/gui/SearchFieldWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/TextScaledButtonWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/TooltipButtonWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/YACLScreen.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/ActionController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/BooleanController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/ColorController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/ControllerWidget.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/LabelController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/TickBoxController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/cycling/CyclingControllerElement.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/cycling/CyclingListController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/cycling/EnumController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/cycling/ICyclingController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/package-info.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/slider/DoubleSliderController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/slider/FloatSliderController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/slider/ISliderController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/slider/IntegerSliderController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/slider/LongSliderController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/slider/SliderControllerElement.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/slider/package-info.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/string/IStringController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/string/StringController.java create mode 100644 src/client/java/dev/isxander/yacl/gui/controllers/string/StringControllerElement.java (limited to 'src/client/java/dev/isxander/yacl/gui') diff --git a/src/client/java/dev/isxander/yacl/gui/AbstractWidget.java b/src/client/java/dev/isxander/yacl/gui/AbstractWidget.java new file mode 100644 index 0000000..ffb4dec --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/AbstractWidget.java @@ -0,0 +1,108 @@ +package dev.isxander.yacl.gui; + +import com.mojang.blaze3d.systems.RenderSystem; +import dev.isxander.yacl.api.utils.Dimension; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.font.TextRenderer; +import net.minecraft.client.gui.Drawable; +import net.minecraft.client.gui.DrawableHelper; +import net.minecraft.client.gui.Element; +import net.minecraft.client.gui.Selectable; +import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; +import net.minecraft.client.gui.widget.ClickableWidget; +import net.minecraft.client.render.GameRenderer; +import net.minecraft.client.sound.PositionedSoundInstance; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.sound.SoundEvents; + +import java.awt.Color; + +public abstract class AbstractWidget implements Element, Drawable, Selectable { + protected final MinecraftClient client = MinecraftClient.getInstance(); + protected final TextRenderer textRenderer = client.textRenderer; + protected final int inactiveColor = 0xFFA0A0A0; + + private Dimension dim; + + public AbstractWidget(Dimension dim) { + this.dim = dim; + } + + public void postRender(MatrixStack matrices, int mouseX, int mouseY, float delta) { + + } + + public boolean canReset() { + return false; + } + + @Override + public boolean isMouseOver(double mouseX, double mouseY) { + if (dim == null) return false; + return this.dim.isPointInside((int) mouseX, (int) mouseY); + } + + public void setDimension(Dimension dim) { + this.dim = dim; + } + + public Dimension getDimension() { + return dim; + } + + @Override + public SelectionType getType() { + return SelectionType.NONE; + } + + public void unfocus() { + + } + + public boolean matchesSearch(String query) { + return true; + } + + @Override + public void appendNarrations(NarrationMessageBuilder builder) { + + } + + protected void drawButtonRect(MatrixStack matrices, int x1, int y1, int x2, int y2, boolean hovered, boolean enabled) { + if (x1 > x2) { + int xx1 = x1; + x1 = x2; + x2 = xx1; + } + if (y1 > y2) { + int yy1 = y1; + y1 = y2; + y2 = yy1; + } + int width = x2 - x1; + int height = y2 - y1; + + RenderSystem.setShader(GameRenderer::getPositionTexProgram); + RenderSystem.setShaderTexture(0, ClickableWidget.WIDGETS_TEXTURE); + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); + int i = !enabled ? 0 : hovered ? 2 : 1; + RenderSystem.enableBlend(); + RenderSystem.defaultBlendFunc(); + RenderSystem.enableDepthTest(); + DrawableHelper.drawTexture(matrices, x1, y1, 0, 0, 46 + i * 20, width / 2, height, 256, 256); + DrawableHelper.drawTexture(matrices, x1 + width / 2, y1, 0, 200 - width / 2f, 46 + i * 20, width / 2, height, 256, 256); + } + + protected int multiplyColor(int hex, float amount) { + Color color = new Color(hex, true); + + return new Color(Math.max((int)(color.getRed() *amount), 0), + Math.max((int)(color.getGreen()*amount), 0), + Math.max((int)(color.getBlue() *amount), 0), + color.getAlpha()).getRGB(); + } + + public void playDownSound() { + MinecraftClient.getInstance().getSoundManager().play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/CategoryListWidget.java b/src/client/java/dev/isxander/yacl/gui/CategoryListWidget.java new file mode 100644 index 0000000..46a9fdf --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/CategoryListWidget.java @@ -0,0 +1,96 @@ +package dev.isxander.yacl.gui; + +import com.google.common.collect.ImmutableList; +import com.mojang.blaze3d.systems.RenderSystem; +import dev.isxander.yacl.api.ConfigCategory; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.Element; +import net.minecraft.client.gui.Selectable; +import net.minecraft.client.gui.widget.ElementListWidget; +import net.minecraft.client.util.math.MatrixStack; + +import java.util.List; + +public class CategoryListWidget extends ElementListWidget { + private final YACLScreen yaclScreen; + + public CategoryListWidget(MinecraftClient client, YACLScreen yaclScreen, int screenWidth, int screenHeight) { + super(client, screenWidth / 3, yaclScreen.searchFieldWidget.getY() - 5, 0, yaclScreen.searchFieldWidget.getY() - 5, 21); + this.yaclScreen = yaclScreen; + setRenderBackground(false); + setRenderHorizontalShadows(false); + + for (ConfigCategory category : yaclScreen.config.categories()) { + addEntry(new CategoryEntry(category)); + } + } + + @Override + protected void renderList(MatrixStack matrices, int mouseX, int mouseY, float delta) { + double d = this.client.getWindow().getScaleFactor(); + RenderSystem.enableScissor(0, (int)((yaclScreen.height - bottom) * d), (int)(width * d), (int)(height * d)); + super.renderList(matrices, mouseX, mouseY, delta); + RenderSystem.disableScissor(); + } + + public void postRender(MatrixStack matrices, int mouseX, int mouseY, float delta) { + for (CategoryEntry entry : children()) { + entry.postRender(matrices, mouseX, mouseY, delta); + } + } + + @Override + public int getRowWidth() { + return Math.min(width - width / 10, 396); + } + + @Override + public int getRowLeft() { + return super.getRowLeft() - 2; + } + + @Override + protected int getScrollbarPositionX() { + return width - 2; + } + + public class CategoryEntry extends Entry { + private final CategoryWidget categoryButton; + public final int categoryIndex; + + public CategoryEntry(ConfigCategory category) { + this.categoryIndex = yaclScreen.config.categories().indexOf(category); + categoryButton = new CategoryWidget( + yaclScreen, + category, + categoryIndex, + getRowLeft(), 0, + getRowWidth(), 20 + ); + } + + @Override + public void render(MatrixStack matrices, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { + if (mouseY > bottom) { + mouseY = -20; + } + + categoryButton.setY(y); + categoryButton.render(matrices, mouseX, mouseY, tickDelta); + } + + private void postRender(MatrixStack matrices, int mouseX, int mouseY, float tickDelta) { + categoryButton.renderHoveredTooltip(matrices); + } + + @Override + public List children() { + return ImmutableList.of(categoryButton); + } + + @Override + public List selectableChildren() { + return ImmutableList.of(categoryButton); + } + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/CategoryWidget.java b/src/client/java/dev/isxander/yacl/gui/CategoryWidget.java new file mode 100644 index 0000000..3c5d8d2 --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/CategoryWidget.java @@ -0,0 +1,31 @@ +package dev.isxander.yacl.gui; + +import dev.isxander.yacl.api.ConfigCategory; +import net.minecraft.client.sound.SoundManager; + +public class CategoryWidget extends TooltipButtonWidget { + private final int categoryIndex; + + public CategoryWidget(YACLScreen screen, ConfigCategory category, int categoryIndex, int x, int y, int width, int height) { + super(screen, x, y, width, height, category.name(), category.tooltip(), btn -> { + screen.searchFieldWidget.setText(""); + screen.changeCategory(categoryIndex); + }); + this.categoryIndex = categoryIndex; + } + + private boolean isCurrentCategory() { + return ((YACLScreen) screen).getCurrentCategoryIdx() == categoryIndex; + } + + @Override + protected int getYImage(boolean hovered) { + return super.getYImage(hovered || isCurrentCategory()); + } + + @Override + public void playDownSound(SoundManager soundManager) { + if (!isCurrentCategory()) + super.playDownSound(soundManager); + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/LowProfileButtonWidget.java b/src/client/java/dev/isxander/yacl/gui/LowProfileButtonWidget.java new file mode 100644 index 0000000..9fa01a7 --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/LowProfileButtonWidget.java @@ -0,0 +1,29 @@ +package dev.isxander.yacl.gui; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.tooltip.Tooltip; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.Text; +import net.minecraft.util.math.MathHelper; + +public class LowProfileButtonWidget extends ButtonWidget { + public LowProfileButtonWidget(int x, int y, int width, int height, Text message, PressAction onPress) { + super(x, y, width, height, message, onPress, DEFAULT_NARRATION_SUPPLIER); + } + + public LowProfileButtonWidget(int x, int y, int width, int height, Text message, PressAction onPress, Tooltip tooltip) { + this(x, y, width, height, message, onPress); + setTooltip(tooltip); + } + + @Override + public void renderButton(MatrixStack matrices, int mouseX, int mouseY, float delta) { + if (!isHovered()) { + int j = this.active ? 0xFFFFFF : 0xA0A0A0; + drawCenteredText(matrices, MinecraftClient.getInstance().textRenderer, this.getMessage(), this.getX() + this.width / 2, this.getY() + (this.height - 8) / 2, j | MathHelper.ceil(this.alpha * 255.0F) << 24); + } else { + super.renderButton(matrices, mouseX, mouseY, delta); + } + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/OptionListWidget.java b/src/client/java/dev/isxander/yacl/gui/OptionListWidget.java new file mode 100644 index 0000000..eed3aff --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/OptionListWidget.java @@ -0,0 +1,470 @@ +package dev.isxander.yacl.gui; + +import com.google.common.collect.ImmutableList; +import dev.isxander.yacl.api.ConfigCategory; +import dev.isxander.yacl.api.Option; +import dev.isxander.yacl.api.OptionGroup; +import dev.isxander.yacl.api.utils.Dimension; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.font.MultilineText; +import net.minecraft.client.font.TextRenderer; +import net.minecraft.client.gui.Element; +import net.minecraft.client.gui.Selectable; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; +import net.minecraft.client.gui.screen.narration.NarrationPart; +import net.minecraft.client.gui.widget.ElementListWidget; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.Text; +import net.minecraft.util.math.MathHelper; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.function.Supplier; + +public class OptionListWidget extends ElementListWidget { + private final YACLScreen yaclScreen; + private boolean singleCategory = false; + + private ImmutableList viewableChildren; + + private double smoothScrollAmount = getScrollAmount(); + private boolean returnSmoothAmount = false; + + public OptionListWidget(YACLScreen screen, MinecraftClient client, int width, int height) { + super(client, width / 3 * 2, height, 0, height, 22); + this.yaclScreen = screen; + left = width - this.width; + right = width; + + refreshOptions(); + } + + public void refreshOptions() { + clearEntries(); + + List categories = new ArrayList<>(); + if (yaclScreen.getCurrentCategoryIdx() == -1) { + categories.addAll(yaclScreen.config.categories()); + } else { + categories.add(yaclScreen.config.categories().get(yaclScreen.getCurrentCategoryIdx())); + } + singleCategory = categories.size() == 1; + + for (ConfigCategory category : categories) { + for (OptionGroup group : category.groups()) { + Supplier viewableSupplier; + GroupSeparatorEntry groupSeparatorEntry = null; + if (!group.isRoot()) { + groupSeparatorEntry = new GroupSeparatorEntry(group, yaclScreen); + viewableSupplier = groupSeparatorEntry::isExpanded; + addEntry(groupSeparatorEntry); + } else { + viewableSupplier = () -> true; + } + + List optionEntries = new ArrayList<>(); + for (Option option : group.options()) { + OptionEntry entry = new OptionEntry(option, category, group, option.controller().provideWidget(yaclScreen, Dimension.ofInt(getRowLeft(), 0, getRowWidth(), 20)), viewableSupplier); + addEntry(entry); + optionEntries.add(entry); + } + + if (groupSeparatorEntry != null) { + groupSeparatorEntry.setOptionEntries(optionEntries); + } + } + } + + recacheViewableChildren(); + setScrollAmount(0); + } + + public void expandAllGroups() { + for (Entry entry : super.children()) { + if (entry instanceof GroupSeparatorEntry groupSeparatorEntry) { + groupSeparatorEntry.setExpanded(true); + } + } + } + + /* + below code is licensed from cloth-config under LGPL3 + modified to inherit vanilla's EntryListWidget and use yarn mappings + */ + + @Nullable + @Override + protected Entry getEntryAtPosition(double x, double y) { + int listMiddleX = this.left + this.width / 2; + int minX = listMiddleX - this.getRowWidth() / 2; + int maxX = listMiddleX + this.getRowWidth() / 2; + int currentY = MathHelper.floor(y - (double) this.top) - this.headerHeight + (int) this.getScrollAmount() - 4; + int itemY = 0; + int itemIndex = -1; + for (int i = 0; i < children().size(); i++) { + Entry item = children().get(i); + itemY += item.getItemHeight(); + if (itemY > currentY) { + itemIndex = i; + break; + } + } + return x < (double) this.getScrollbarPositionX() && x >= minX && y <= maxX && itemIndex >= 0 && currentY >= 0 && itemIndex < this.getEntryCount() ? this.children().get(itemIndex) : null; + } + + @Override + protected int getMaxPosition() { + return children().stream().map(Entry::getItemHeight).reduce(0, Integer::sum) + headerHeight; + } + + @Override + protected void centerScrollOn(Entry entry) { + double d = (this.bottom - this.top) / -2d; + for (int i = 0; i < this.children().indexOf(entry) && i < this.getEntryCount(); i++) + d += children().get(i).getItemHeight(); + this.setScrollAmount(d); + } + + @Override + protected int getRowTop(int index) { + int integer = top + 4 - (int) this.getScrollAmount() + headerHeight; + for (int i = 0; i < children().size() && i < index; i++) + integer += children().get(i).getItemHeight(); + return integer; + } + + @Override + protected void renderList(MatrixStack matrices, int mouseX, int mouseY, float delta) { + int left = this.getRowLeft(); + int right = this.getRowWidth(); + int count = this.getEntryCount(); + + for(int i = 0; i < count; ++i) { + Entry entry = children().get(i); + int top = this.getRowTop(i); + int bottom = top + entry.getItemHeight(); + int entryHeight = entry.getItemHeight() - 4; + if (bottom >= this.top && top <= this.bottom) { + this.renderEntry(matrices, mouseX, mouseY, delta, i, left, top, right, entryHeight); + } + } + } + + /* END cloth config code */ + + @Override + public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { + smoothScrollAmount = MathHelper.lerp(MinecraftClient.getInstance().getLastFrameDuration() * 0.5, smoothScrollAmount, getScrollAmount()); + returnSmoothAmount = true; + super.render(matrices, mouseX, mouseY, delta); + returnSmoothAmount = false; + } + + /** + * awful code to only use smooth scroll state when rendering, + * not other code that needs target scroll amount + */ + @Override + public double getScrollAmount() { + if (returnSmoothAmount) + return smoothScrollAmount; + + return super.getScrollAmount(); + } + + public void postRender(MatrixStack matrices, int mouseX, int mouseY, float delta) { + for (Entry entry : children()) { + entry.postRender(matrices, mouseX, mouseY, delta); + } + } + + @Override + public int getRowWidth() { + return Math.min(396, (int)(width / 1.3f)); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + for (Entry child : children()) { + if (child != getEntryAtPosition(mouseX, mouseY) && child instanceof OptionEntry optionEntry) + optionEntry.widget.unfocus(); + } + + return super.mouseClicked(mouseX, mouseY, button); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double amount) { + for (Entry child : children()) { + if (child.mouseScrolled(mouseX, mouseY, amount)) + return true; + } + + this.setScrollAmount(this.getScrollAmount() - amount * 20 /* * (double) (getMaxScroll() / getEntryCount()) / 2.0D */); + return true; + } + + @Override + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + for (Entry child : children()) { + if (child.keyPressed(keyCode, scanCode, modifiers)) + return true; + } + + return super.keyPressed(keyCode, scanCode, modifiers); + } + + @Override + public boolean charTyped(char chr, int modifiers) { + for (Entry child : children()) { + if (child.charTyped(chr, modifiers)) + return true; + } + + return super.charTyped(chr, modifiers); + } + + @Override + protected int getScrollbarPositionX() { + return left + width - (int)(width * 0.05f); + } + + @Override + protected void renderBackground(MatrixStack matrices) { + setRenderBackground(client.world == null); + if (client.world != null) + fill(matrices, left, top, right, bottom, 0x6B000000); + } + + public void recacheViewableChildren() { + this.viewableChildren = ImmutableList.copyOf(super.children().stream().filter(Entry::isViewable).toList()); + + // update y positions before they need to be rendered are rendered + int i = 0; + for (Entry entry : viewableChildren) { + if (entry instanceof OptionEntry optionEntry) + optionEntry.widget.setDimension(optionEntry.widget.getDimension().withY(getRowTop(i))); + i++; + } + } + + @Override + public List children() { + return viewableChildren; + } + + public abstract class Entry extends ElementListWidget.Entry { + public void postRender(MatrixStack matrices, int mouseX, int mouseY, float delta) { + + } + + public boolean isViewable() { + return true; + } + + public int getItemHeight() { + return 22; + } + + protected boolean isHovered() { + return Objects.equals(getHoveredEntry(), this); + } + } + + public class OptionEntry extends Entry { + public final Option option; + public final ConfigCategory category; + public final OptionGroup group; + + public final AbstractWidget widget; + private final Supplier viewableSupplier; + + private final TextScaledButtonWidget resetButton; + + private final String categoryName; + private final String groupName; + + private OptionEntry(Option option, ConfigCategory category, OptionGroup group, AbstractWidget widget, Supplier viewableSupplier) { + this.option = option; + this.category = category; + this.group = group; + this.widget = widget; + this.viewableSupplier = viewableSupplier; + this.categoryName = category.name().getString().toLowerCase(); + this.groupName = group.name().getString().toLowerCase(); + if (this.widget.canReset()) { + this.widget.setDimension(this.widget.getDimension().expanded(-21, 0)); + this.resetButton = new TextScaledButtonWidget(widget.getDimension().xLimit() + 1, -50, 20, 20, 2f, Text.of("\u21BB"), button -> { + option.requestSetDefault(); + }); + option.addListener((opt, val) -> this.resetButton.active = !opt.isPendingValueDefault() && opt.available()); + this.resetButton.active = !option.isPendingValueDefault() && option.available(); + } else { + this.resetButton = null; + } + } + + @Override + public void render(MatrixStack matrices, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { + widget.setDimension(widget.getDimension().withY(y)); + + widget.render(matrices, mouseX, mouseY, tickDelta); + + if (resetButton != null) { + resetButton.setY(y); + resetButton.render(matrices, mouseX, mouseY, tickDelta); + } + } + + @Override + public void postRender(MatrixStack matrices, int mouseX, int mouseY, float delta) { + widget.postRender(matrices, mouseX, mouseY, delta); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double amount) { + return widget.mouseScrolled(mouseX, mouseY, amount); + } + + @Override + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + return widget.keyPressed(keyCode, scanCode, modifiers); + } + + @Override + public boolean charTyped(char chr, int modifiers) { + return widget.charTyped(chr, modifiers); + } + + @Override + public boolean isViewable() { + String query = yaclScreen.searchFieldWidget.getText(); + return viewableSupplier.get() + && (yaclScreen.searchFieldWidget.isEmpty() + || (!singleCategory && categoryName.contains(query)) + || groupName.contains(query) + || widget.matchesSearch(query)); + } + + @Override + public int getItemHeight() { + return widget.getDimension().height() + 2; + } + + @Override + public List selectableChildren() { + if (resetButton == null) + return ImmutableList.of(widget); + + return ImmutableList.of(widget, resetButton); + } + + @Override + public List children() { + if (resetButton == null) + return ImmutableList.of(widget); + + return ImmutableList.of(widget, resetButton); + } + } + + public class GroupSeparatorEntry extends Entry { + private final OptionGroup group; + private final MultilineText wrappedName; + private final MultilineText wrappedTooltip; + + private final LowProfileButtonWidget expandMinimizeButton; + + private final Screen screen; + private final TextRenderer textRenderer = MinecraftClient.getInstance().textRenderer; + + private boolean groupExpanded; + + private List optionEntries; + + private int y; + + private GroupSeparatorEntry(OptionGroup group, Screen screen) { + this.group = group; + this.screen = screen; + this.wrappedName = MultilineText.create(textRenderer, group.name(), getRowWidth() - 45); + this.wrappedTooltip = MultilineText.create(textRenderer, group.tooltip(), screen.width / 3 * 2 - 10); + this.groupExpanded = !group.collapsed(); + this.expandMinimizeButton = new LowProfileButtonWidget(0, 0, 20, 20, Text.empty(), btn -> { + setExpanded(!isExpanded()); + recacheViewableChildren(); + }); + updateExpandMinimizeText(); + } + + @Override + public void render(MatrixStack matrices, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { + this.y = y; + + expandMinimizeButton.setX(x); + expandMinimizeButton.setY(y + entryHeight / 2 - expandMinimizeButton.getHeight() / 2); + expandMinimizeButton.render(matrices, mouseX, mouseY, tickDelta); + + wrappedName.drawCenterWithShadow(matrices, x + entryWidth / 2, y + getYPadding()); + } + + @Override + public void postRender(MatrixStack matrices, int mouseX, int mouseY, float delta) { + if (isHovered() && !expandMinimizeButton.isMouseOver(mouseX, mouseY)) { + YACLScreen.renderMultilineTooltip(matrices, textRenderer, wrappedTooltip, getRowLeft() + getRowWidth() / 2, y - 3, y + getItemHeight() + 3, screen.width, screen.height); + } + } + + public boolean isExpanded() { + return groupExpanded; + } + + public void setExpanded(boolean expanded) { + this.groupExpanded = expanded; + updateExpandMinimizeText(); + } + + private void updateExpandMinimizeText() { + expandMinimizeButton.setMessage(Text.of(isExpanded() ? "\u25BC" : "\u25B6")); + } + + public void setOptionEntries(List optionEntries) { + this.optionEntries = optionEntries; + } + + @Override + public boolean isViewable() { + return yaclScreen.searchFieldWidget.isEmpty() || optionEntries.stream().anyMatch(OptionEntry::isViewable); + } + + @Override + public int getItemHeight() { + return Math.max(wrappedName.count(), 1) * textRenderer.fontHeight + getYPadding() * 2; + } + + private int getYPadding() { + return 6; + } + + @Override + public List selectableChildren() { + return ImmutableList.of(new Selectable() { + @Override + public Selectable.SelectionType getType() { + return Selectable.SelectionType.HOVERED; + } + + @Override + public void appendNarrations(NarrationMessageBuilder builder) { + builder.put(NarrationPart.TITLE, group.name()); + } + }); + } + + @Override + public List children() { + return ImmutableList.of(expandMinimizeButton); + } + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/RequireRestartScreen.java b/src/client/java/dev/isxander/yacl/gui/RequireRestartScreen.java new file mode 100644 index 0000000..3c46738 --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/RequireRestartScreen.java @@ -0,0 +1,16 @@ +package dev.isxander.yacl.gui; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.ConfirmScreen; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; + +public class RequireRestartScreen extends ConfirmScreen { + public RequireRestartScreen(Screen parent) { + super(option -> { + if (option) MinecraftClient.getInstance().scheduleStop(); + else MinecraftClient.getInstance().setScreen(parent); + }, Text.translatable("yacl.restart.title").formatted(Formatting.RED, Formatting.BOLD), Text.translatable("yacl.restart.message"), Text.translatable("yacl.restart.yes"), Text.translatable("yacl.restart.no")); + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/SearchFieldWidget.java b/src/client/java/dev/isxander/yacl/gui/SearchFieldWidget.java new file mode 100644 index 0000000..5b7c9dc --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/SearchFieldWidget.java @@ -0,0 +1,62 @@ +package dev.isxander.yacl.gui; + +import net.minecraft.client.font.TextRenderer; +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.Text; + +public class SearchFieldWidget extends TextFieldWidget { + private Text emptyText; + private final YACLScreen yaclScreen; + private final TextRenderer textRenderer; + + private boolean isEmpty = true; + + public SearchFieldWidget(YACLScreen yaclScreen, TextRenderer textRenderer, int x, int y, int width, int height, Text text, Text emptyText) { + super(textRenderer, x, y, width, height, text); + setChangedListener(string -> update()); + setTextPredicate(string -> !string.endsWith(" ") && !string.startsWith(" ")); + this.yaclScreen = yaclScreen; + this.textRenderer = textRenderer; + this.emptyText = emptyText; + } + + @Override + public void renderButton(MatrixStack matrices, int mouseX, int mouseY, float delta) { + super.renderButton(matrices, mouseX, mouseY, delta); + if (isVisible() && isEmpty()) { + textRenderer.drawWithShadow(matrices, emptyText, getX() + 4, this.getY() + (this.height - 8) / 2f, 0x707070); + } + } + + private void update() { + boolean wasEmpty = isEmpty; + isEmpty = getText().isEmpty(); + + if (isEmpty && wasEmpty) + return; + + if (!isEmpty && yaclScreen.getCurrentCategoryIdx() != -1) + yaclScreen.changeCategory(-1); + if (isEmpty && yaclScreen.getCurrentCategoryIdx() == -1) + yaclScreen.changeCategory(0); + + yaclScreen.optionList.expandAllGroups(); + yaclScreen.optionList.recacheViewableChildren(); + + yaclScreen.optionList.setScrollAmount(0); + yaclScreen.categoryList.setScrollAmount(0); + } + + public boolean isEmpty() { + return isEmpty; + } + + public Text getEmptyText() { + return emptyText; + } + + public void setEmptyText(Text emptyText) { + this.emptyText = emptyText; + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/TextScaledButtonWidget.java b/src/client/java/dev/isxander/yacl/gui/TextScaledButtonWidget.java new file mode 100644 index 0000000..2d0a99c --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/TextScaledButtonWidget.java @@ -0,0 +1,44 @@ +package dev.isxander.yacl.gui; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.font.TextRenderer; +import net.minecraft.client.gui.tooltip.Tooltip; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.OrderedText; +import net.minecraft.text.Text; +import net.minecraft.util.math.MathHelper; + +public class TextScaledButtonWidget extends ButtonWidget { + public float textScale; + + public TextScaledButtonWidget(int x, int y, int width, int height, float textScale, Text message, PressAction onPress) { + super(x, y, width, height, message, onPress, DEFAULT_NARRATION_SUPPLIER); + this.textScale = textScale; + } + + public TextScaledButtonWidget(int x, int y, int width, int height, float textScale, Text message, PressAction onPress, Tooltip tooltip) { + this(x, y, width, height, textScale, message, onPress); + setTooltip(tooltip); + } + + @Override + public void renderButton(MatrixStack matrices, int mouseX, int mouseY, float delta) { + // prevents super from rendering text + Text message = getMessage(); + setMessage(Text.empty()); + + super.renderButton(matrices, mouseX, mouseY, delta); + + setMessage(message); + int j = this.active ? 16777215 : 10526880; + OrderedText orderedText = getMessage().asOrderedText(); + TextRenderer textRenderer = MinecraftClient.getInstance().textRenderer; + + matrices.push(); + matrices.translate(((this.getX() + this.width / 2f) - textRenderer.getWidth(orderedText) * textScale / 2), (float)this.getY() + (this.height - 8 * textScale) / 2f / textScale, 0); + matrices.scale(textScale, textScale, 1); + textRenderer.drawWithShadow(matrices, orderedText, 0, 0, j | MathHelper.ceil(this.alpha * 255.0F) << 24); + matrices.pop(); + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/TooltipButtonWidget.java b/src/client/java/dev/isxander/yacl/gui/TooltipButtonWidget.java new file mode 100644 index 0000000..b034f4b --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/TooltipButtonWidget.java @@ -0,0 +1,30 @@ +package dev.isxander.yacl.gui; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.font.MultilineText; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.Text; + +public class TooltipButtonWidget extends ButtonWidget { + + protected final Screen screen; + protected MultilineText wrappedDescription; + + public TooltipButtonWidget(Screen screen, int x, int y, int width, int height, Text message, Text tooltip, PressAction onPress) { + super(x, y, width, height, message, onPress, DEFAULT_NARRATION_SUPPLIER); + this.screen = screen; + setTooltip(tooltip); + } + + public void renderHoveredTooltip(MatrixStack matrices) { + if (isHovered()) { + YACLScreen.renderMultilineTooltip(matrices, MinecraftClient.getInstance().textRenderer, wrappedDescription, getX() + width / 2, getY() - 4, getY() + height + 4, screen.width, screen.height); + } + } + + public void setTooltip(Text tooltip) { + wrappedDescription = MultilineText.create(MinecraftClient.getInstance().textRenderer, tooltip, screen.width / 3 - 5); + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/YACLScreen.java b/src/client/java/dev/isxander/yacl/gui/YACLScreen.java new file mode 100644 index 0000000..e36c8e8 --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/YACLScreen.java @@ -0,0 +1,269 @@ +package dev.isxander.yacl.gui; + +import com.mojang.blaze3d.systems.RenderSystem; +import dev.isxander.yacl.api.*; +import dev.isxander.yacl.api.utils.Dimension; +import dev.isxander.yacl.api.utils.MutableDimension; +import dev.isxander.yacl.api.utils.OptionUtils; +import net.minecraft.client.font.MultilineText; +import net.minecraft.client.font.TextRenderer; +import net.minecraft.client.gui.Element; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.render.*; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import org.joml.Matrix4f; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +public class YACLScreen extends Screen { + public final YetAnotherConfigLib config; + private int currentCategoryIdx; + + private final Screen parent; + + public OptionListWidget optionList; + public CategoryListWidget categoryList; + public TooltipButtonWidget finishedSaveButton, cancelResetButton, undoButton; + public SearchFieldWidget searchFieldWidget; + + public Text saveButtonMessage, saveButtonTooltipMessage; + private int saveButtonMessageTime; + + + public YACLScreen(YetAnotherConfigLib config, Screen parent) { + super(config.title()); + this.config = config; + this.parent = parent; + this.currentCategoryIdx = 0; + } + + @Override + protected void init() { + int columnWidth = width / 3; + int padding = columnWidth / 20; + columnWidth = Math.min(columnWidth, 400); + int paddedWidth = columnWidth - padding * 2; + + MutableDimension actionDim = Dimension.ofInt(width / 3 / 2, height - padding - 20, paddedWidth, 20); + finishedSaveButton = new TooltipButtonWidget(this, actionDim.x() - actionDim.width() / 2, actionDim.y(), actionDim.width(), actionDim.height(), Text.empty(), Text.empty(), (btn) -> { + saveButtonMessage = null; + + if (pendingChanges()) { + Set flags = new HashSet<>(); + OptionUtils.forEachOptions(config, option -> { + if (option.applyValue()) { + flags.addAll(option.flags()); + } + }); + OptionUtils.forEachOptions(config, option -> { + if (option.changed()) { + option.forgetPendingValue(); + } + }); + config.saveFunction().run(); + + flags.forEach(flag -> flag.accept(client)); + } else close(); + }); + actionDim.expand(-actionDim.width() / 2 - 2, 0).move(-actionDim.width() / 2 - 2, -22); + cancelResetButton = new TooltipButtonWidget(this, actionDim.x() - actionDim.width() / 2, actionDim.y(), actionDim.width(), actionDim.height(), Text.empty(), Text.empty(), (btn) -> { + if (pendingChanges()) { + OptionUtils.forEachOptions(config, Option::forgetPendingValue); + close(); + } else { + OptionUtils.forEachOptions(config, Option::requestSetDefault); + } + + }); + actionDim.move(actionDim.width() + 4, 0); + undoButton = new TooltipButtonWidget(this, actionDim.x() - actionDim.width() / 2, actionDim.y(), actionDim.width(), actionDim.height(), Text.translatable("yacl.gui.undo"), Text.translatable("yacl.gui.undo.tooltip"), (btn) -> { + OptionUtils.forEachOptions(config, Option::forgetPendingValue); + }); + + searchFieldWidget = new SearchFieldWidget(this, textRenderer, width / 3 / 2 - paddedWidth / 2 + 1, undoButton.getY() - 22, paddedWidth - 2, 18, Text.translatable("gui.recipebook.search_hint"), Text.translatable("gui.recipebook.search_hint")); + + categoryList = new CategoryListWidget(client, this, width, height); + addSelectableChild(categoryList); + + updateActionAvailability(); + addDrawableChild(searchFieldWidget); + addDrawableChild(cancelResetButton); + addDrawableChild(undoButton); + addDrawableChild(finishedSaveButton); + + optionList = new OptionListWidget(this, client, width, height); + addSelectableChild(optionList); + + config.initConsumer().accept(this); + } + + @Override + public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { + renderBackground(matrices); + + super.render(matrices, mouseX, mouseY, delta); + categoryList.render(matrices, mouseX, mouseY, delta); + searchFieldWidget.render(matrices, mouseX, mouseY, delta); + optionList.render(matrices, mouseX, mouseY, delta); + + categoryList.postRender(matrices, mouseX, mouseY, delta); + optionList.postRender(matrices, mouseX, mouseY, delta); + + for (Element child : children()) { + if (child instanceof TooltipButtonWidget tooltipButtonWidget) { + tooltipButtonWidget.renderHoveredTooltip(matrices); + } + } + } + + @Override + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + if (optionList.keyPressed(keyCode, scanCode, modifiers)) { + return true; + } + + return super.keyPressed(keyCode, scanCode, modifiers); + } + + @Override + public boolean charTyped(char chr, int modifiers) { + if (optionList.charTyped(chr, modifiers)) { + return true; + } + + return super.charTyped(chr, modifiers); + } + + public void changeCategory(int idx) { + if (idx == currentCategoryIdx) + return; + + if (idx != -1 && config.categories().get(idx) instanceof PlaceholderCategory placeholderCategory) { + client.setScreen(placeholderCategory.screen().apply(client, this)); + } else { + currentCategoryIdx = idx; + optionList.refreshOptions(); + } + } + + public int getCurrentCategoryIdx() { + return currentCategoryIdx; + } + + private void updateActionAvailability() { + boolean pendingChanges = pendingChanges(); + + undoButton.active = pendingChanges; + finishedSaveButton.setMessage(pendingChanges ? Text.translatable("yacl.gui.save") : Text.translatable("gui.done")); + finishedSaveButton.setTooltip(pendingChanges ? Text.translatable("yacl.gui.save.tooltip") : Text.translatable("yacl.gui.finished.tooltip")); + cancelResetButton.setMessage(pendingChanges ? Text.translatable("gui.cancel") : Text.translatable("controls.reset")); + cancelResetButton.setTooltip(pendingChanges ? Text.translatable("yacl.gui.cancel.tooltip") : Text.translatable("yacl.gui.reset.tooltip")); + } + + @Override + public void tick() { + searchFieldWidget.tick(); + + updateActionAvailability(); + + if (saveButtonMessage != null) { + if (saveButtonMessageTime > 140) { + saveButtonMessage = null; + saveButtonTooltipMessage = null; + saveButtonMessageTime = 0; + } else { + saveButtonMessageTime++; + finishedSaveButton.setMessage(saveButtonMessage); + if (saveButtonTooltipMessage != null) { + finishedSaveButton.setTooltip(saveButtonTooltipMessage); + } + } + } + } + + private void setSaveButtonMessage(Text message, Text tooltip) { + saveButtonMessage = message; + saveButtonTooltipMessage = tooltip; + saveButtonMessageTime = 0; + } + + private boolean pendingChanges() { + AtomicBoolean pendingChanges = new AtomicBoolean(false); + OptionUtils.consumeOptions(config, (option) -> { + if (option.changed()) { + pendingChanges.set(true); + return true; + } + return false; + }); + + return pendingChanges.get(); + } + + @Override + public boolean shouldCloseOnEsc() { + if (pendingChanges()) { + setSaveButtonMessage(Text.translatable("yacl.gui.save_before_exit").formatted(Formatting.RED), Text.translatable("yacl.gui.save_before_exit.tooltip")); + return false; + } + return true; + } + + @Override + public void close() { + client.setScreen(parent); + } + + public static void renderMultilineTooltip(MatrixStack matrices, TextRenderer textRenderer, MultilineText text, int centerX, int yAbove, int yBelow, int screenWidth, int screenHeight) { + if (text.count() > 0) { + int maxWidth = text.getMaxWidth(); + int lineHeight = textRenderer.fontHeight + 1; + int height = text.count() * lineHeight - 1; + + int belowY = yBelow + 12; + int aboveY = yAbove - height + 12; + int maxBelow = screenHeight - (belowY + height); + int minAbove = aboveY - height; + int y = belowY; + if (maxBelow < -8) + y = maxBelow > minAbove ? belowY : aboveY; + + int x = Math.max(centerX - text.getMaxWidth() / 2 - 12, -6); + + int drawX = x + 12; + int drawY = y - 12; + + matrices.push(); + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder bufferBuilder = tessellator.getBuffer(); + RenderSystem.setShader(GameRenderer::getPositionColorProgram); + bufferBuilder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); + Matrix4f matrix4f = matrices.peek().getPositionMatrix(); + fillGradient(matrix4f, bufferBuilder, drawX - 3, drawY - 4, drawX + maxWidth + 3, drawY - 3, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, drawX - 3, drawY + height + 3, drawX + maxWidth + 3, drawY + height + 4, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, drawX - 3, drawY - 3, drawX + maxWidth + 3, drawY + height + 3, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, drawX - 4, drawY - 3, drawX - 3, drawY + height + 3, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, drawX + maxWidth + 3, drawY - 3, drawX + maxWidth + 4, drawY + height + 3, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, drawX - 3, drawY - 3 + 1, drawX - 3 + 1, drawY + height + 3 - 1, 400, 1347420415, 1344798847); + fillGradient(matrix4f, bufferBuilder, drawX + maxWidth + 2, drawY - 3 + 1, drawX + maxWidth + 3, drawY + height + 3 - 1, 400, 1347420415, 1344798847); + fillGradient(matrix4f, bufferBuilder, drawX - 3, drawY - 3, drawX + maxWidth + 3, drawY - 3 + 1, 400, 1347420415, 1347420415); + fillGradient(matrix4f, bufferBuilder, drawX - 3, drawY + height + 2, drawX + maxWidth + 3, drawY + height + 3, 400, 1344798847, 1344798847); + RenderSystem.enableDepthTest(); + RenderSystem.disableTexture(); + RenderSystem.enableBlend(); + RenderSystem.defaultBlendFunc(); + BufferRenderer.drawWithGlobalProgram(bufferBuilder.end()); + RenderSystem.disableBlend(); + RenderSystem.enableTexture(); + matrices.translate(0.0, 0.0, 400.0); + + text.drawWithShadow(matrices, drawX, drawY, lineHeight, -1); + + matrices.pop(); + } + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/controllers/ActionController.java b/src/client/java/dev/isxander/yacl/gui/controllers/ActionController.java new file mode 100644 index 0000000..b8e2cd1 --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/controllers/ActionController.java @@ -0,0 +1,120 @@ +package dev.isxander.yacl.gui.controllers; + +import dev.isxander.yacl.api.ButtonOption; +import dev.isxander.yacl.api.Controller; +import dev.isxander.yacl.api.utils.Dimension; +import dev.isxander.yacl.gui.AbstractWidget; +import dev.isxander.yacl.gui.YACLScreen; +import net.minecraft.text.Text; +import org.lwjgl.glfw.GLFW; + +import java.util.function.BiConsumer; + +/** + * Simple controller that simply runs the button action on press + * and renders a {@link} Text on the right. + */ +public class ActionController implements Controller> { + public static final Text DEFAULT_TEXT = Text.translatable("yacl.control.action.execute"); + + private final ButtonOption option; + private final Text text; + + /** + * Constructs an action controller + * with the default formatter of {@link ActionController#DEFAULT_TEXT} + * + * @param option bound option + */ + public ActionController(ButtonOption option) { + this(option, DEFAULT_TEXT); + } + + /** + * Constructs an action controller + * + * @param option bound option + * @param text text to display + */ + public ActionController(ButtonOption option, Text text) { + this.option = option; + this.text = text; + + } + + /** + * {@inheritDoc} + */ + @Override + public ButtonOption option() { + return option; + } + + /** + * {@inheritDoc} + */ + @Override + public Text formatValue() { + return text; + } + + /** + * {@inheritDoc} + */ + @Override + public AbstractWidget provideWidget(YACLScreen screen, Dimension widgetDimension) { + return new ActionControllerElement(this, screen, widgetDimension); + } + + public static class ActionControllerElement extends ControllerWidget { + private final String buttonString; + + public ActionControllerElement(ActionController control, YACLScreen screen, Dimension dim) { + super(control, screen, dim); + buttonString = control.formatValue().getString().toLowerCase(); + } + + public void executeAction() { + playDownSound(); + control.option().action().accept(screen, control.option()); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (isMouseOver(mouseX, mouseY) && isAvailable()) { + executeAction(); + return true; + } + return false; + } + + @Override + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + if (!focused) { + return false; + } + + if (keyCode == GLFW.GLFW_KEY_ENTER || keyCode == GLFW.GLFW_KEY_SPACE || keyCode == GLFW.GLFW_KEY_KP_ENTER) { + executeAction(); + return true; + } + + return false; + } + + @Override + protected int getHoveredControlWidth() { + return getUnhoveredControlWidth(); + } + + @Override + public boolean canReset() { + return false; + } + + @Override + public boolean matchesSearch(String query) { + return super.matchesSearch(query) || buttonString.contains(query); + } + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/controllers/BooleanController.java b/src/client/java/dev/isxander/yacl/gui/controllers/BooleanController.java new file mode 100644 index 0000000..7037ff5 --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/controllers/BooleanController.java @@ -0,0 +1,156 @@ +package dev.isxander.yacl.gui.controllers; + +import dev.isxander.yacl.api.Controller; +import dev.isxander.yacl.api.Option; +import dev.isxander.yacl.api.utils.Dimension; +import dev.isxander.yacl.gui.AbstractWidget; +import dev.isxander.yacl.gui.YACLScreen; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import org.lwjgl.glfw.GLFW; + +import java.util.function.Function; + +/** + * This controller renders a simple formatted {@link Text} + */ +public class BooleanController implements Controller { + + public static final Function ON_OFF_FORMATTER = (state) -> + state + ? Text.translatable("options.on") + : Text.translatable("options.off"); + + public static final Function TRUE_FALSE_FORMATTER = (state) -> + state + ? Text.translatable("yacl.control.boolean.true") + : Text.translatable("yacl.control.boolean.false"); + + public static final Function YES_NO_FORMATTER = (state) -> + state + ? Text.translatable("gui.yes") + : Text.translatable("gui.no"); + + private final Option option; + private final Function valueFormatter; + private final boolean coloured; + + /** + * Constructs a tickbox controller + * with the default value formatter of {@link BooleanController#ON_OFF_FORMATTER} + * + * @param option bound option + */ + public BooleanController(Option option) { + this(option, ON_OFF_FORMATTER, false); + } + + /** + * Constructs a tickbox controller + * with the default value formatter of {@link BooleanController#ON_OFF_FORMATTER} + * + * @param option bound option + * @param coloured value format is green or red depending on the state + */ + public BooleanController(Option option, boolean coloured) { + this(option, ON_OFF_FORMATTER, coloured); + } + + /** + * Constructs a tickbox controller + * + * @param option bound option + * @param valueFormatter format value into any {@link Text} + * @param coloured value format is green or red depending on the state + */ + public BooleanController(Option option, Function valueFormatter, boolean coloured) { + this.option = option; + this.valueFormatter = valueFormatter; + this.coloured = coloured; + } + + /** + * {@inheritDoc} + */ + @Override + public Option option() { + return option; + } + + /** + * {@inheritDoc} + */ + @Override + public Text formatValue() { + return valueFormatter.apply(option().pendingValue()); + } + + /** + * Value format is green or red depending on the state + */ + public boolean coloured() { + return coloured; + } + + /** + * {@inheritDoc} + */ + @Override + public AbstractWidget provideWidget(YACLScreen screen, Dimension widgetDimension) { + return new BooleanControllerElement(this, screen, widgetDimension); + } + + public static class BooleanControllerElement extends ControllerWidget { + public BooleanControllerElement(BooleanController control, YACLScreen screen, Dimension dim) { + super(control, screen, dim); + } + + @Override + protected void drawHoveredControl(MatrixStack matrices, int mouseX, int mouseY, float delta) { + + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (!isMouseOver(mouseX, mouseY) || !isAvailable()) + return false; + + toggleSetting(); + return true; + } + + @Override + protected int getHoveredControlWidth() { + return getUnhoveredControlWidth(); + } + + public void toggleSetting() { + control.option().requestSet(!control.option().pendingValue()); + playDownSound(); + } + + @Override + protected Text getValueText() { + if (control.coloured()) { + return super.getValueText().copy().formatted(control.option().pendingValue() ? Formatting.GREEN : Formatting.RED); + } + + return super.getValueText(); + } + + @Override + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + if (!focused) { + return false; + } + + if (keyCode == GLFW.GLFW_KEY_ENTER || keyCode == GLFW.GLFW_KEY_SPACE || keyCode == GLFW.GLFW_KEY_KP_ENTER) { + toggleSetting(); + return true; + } + + return false; + } + } +} diff --git a/src/client/java/dev/isxander/yacl/gui/controllers/ColorController.java b/src/client/java/dev/isxander/yacl/gui/controllers/ColorController.java new file mode 100644 index 0000000..a68475d --- /dev/null +++ b/src/client/java/dev/isxander/yacl/gui/controllers/ColorController.java @@ -0,0 +1,203 @@ +package dev.isxander.yacl.gui.controllers; + +import com.google.common.collect.ImmutableList; +import dev.isxander.yacl.api.Option; +import dev.isxander.yacl.api.utils.Dimension; +import dev.isxander.yacl.api.utils.MutableDimension; +import dev.isxander.yacl.gui.AbstractWidget; +import dev.isxander.yacl.gui.YACLScreen; +import dev.isxander.yacl.gui.controllers.string.IStringController; +import dev.isxander.yacl.gui.controllers.string.StringControllerElement; +import net.minecraft.client.gui.DrawableHelper; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.MutableText; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; + +import java.awt.Color; +import java.util.List; + +/** + * A color controller that uses a hex color field as input. + */ +public class ColorController implements IStringController { + private final Option option; + private final boolean allowAlpha; + + /** + * Constructs a color controller with {@link ColorController#allowAlpha()} defaulting to false + * + * @param option bound option + */ + public ColorController(Option option) { + this(option, false); + } + + /** + * Constructs a color controller + * + * @param option bound option + * @param allowAlpha allows the color input to accept alpha values + */ + public ColorController(Option option, boolean allowAlpha) { + this.option = option; + this.allowAlpha = allowAlpha; + } + + /** + * {@inheritDoc} + */ + @Override + public Option option() { + return option; + } + + public boolean allowAlpha() { + return allowAlpha; + } + + @Override + public String getString() { + return formatValue().getString(); + } + + @Override + public Text formatValue() { + MutableText text = Text.literal("#"); + text.append(Text.literal(toHex(option().pendingValue().getRed())).formatted(Formatting.RED)); + text.append(Text.literal(toHex(option().pendingValue().getGreen())).formatted(Formatting.GREEN)); + text.append(Text.literal(toHex(option().pendingValue().getBlue())).formatted(Formatting.BLUE)); + if (allowAlpha()) text.append(toHex(option().pendingValue().getAlpha())); + return text; + } + + private String toHex(int value) { + String hex = Integer.toString(value, 16).toUpperCase(); + if (hex.length() == 1) + hex = "0" + hex; + return hex; + } + + @Override + public void setFromString(String value) { + if (value.startsWith("#")) + value = value.substring(1); + + int red = Integer.parseInt(value.substring(0, 2), 16); + int green = Integer.parseInt(value.substring(2, 4), 16); + int blue = Integer.parseInt(value.substring(4, 6), 16); + + if (allowAlpha()) { + int alpha = Integer.parseInt(value.substring(6, 8), 16); + option().requestSet(new Color(red, green, blue, alpha)); + } else { + option().requestSet(new Color(red, green, blue)); + } + } + + @Override + public AbstractWidget provideWidget(YACLScreen screen, Dimension widgetDimension) { + return new ColorControllerElement(this, screen, widgetDimension); + } + + public static class ColorControllerElement extends