diff options
author | isxander <xander@isxander.dev> | 2024-04-11 18:43:06 +0100 |
---|---|---|
committer | isxander <xander@isxander.dev> | 2024-04-11 18:43:06 +0100 |
commit | 04fe933f4c24817100f3101f088accf55a621f8a (patch) | |
tree | feff94ca3ab4484160e69a24f4ee38522381950e /common/src/main/java/dev/isxander/yacl3/gui | |
parent | 831b894fdb7fe3e173d81387c8f6a2402b8ccfa9 (diff) | |
download | YetAnotherConfigLib-04fe933f4c24817100f3101f088accf55a621f8a.tar.gz YetAnotherConfigLib-04fe933f4c24817100f3101f088accf55a621f8a.tar.bz2 YetAnotherConfigLib-04fe933f4c24817100f3101f088accf55a621f8a.zip |
Extremely fragile and broken multiversion build with stonecutter
Diffstat (limited to 'common/src/main/java/dev/isxander/yacl3/gui')
62 files changed, 0 insertions, 6671 deletions
diff --git a/common/src/main/java/dev/isxander/yacl3/gui/AbstractWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/AbstractWidget.java deleted file mode 100644 index 0c3afdd..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/AbstractWidget.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.isxander.yacl3.gui; - -import dev.isxander.yacl3.api.utils.Dimension; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.Renderable; -import net.minecraft.client.gui.components.WidgetSprites; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.gui.narration.NarratableEntry; -import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.resources.sounds.SimpleSoundInstance; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.sounds.SoundEvents; - -import java.awt.*; - -public abstract class AbstractWidget implements GuiEventListener, Renderable, NarratableEntry { - private static final WidgetSprites SPRITES = new WidgetSprites( - new ResourceLocation("widget/button"), // normal - new ResourceLocation("widget/button_disabled"), // disabled & !focused - new ResourceLocation("widget/button_highlighted"), // !disabled & focused - new ResourceLocation("widget/slider_highlighted") // disabled & focused - ); - - protected final Minecraft client = Minecraft.getInstance(); - protected final Font textRenderer = client.font; - protected final int inactiveColor = 0xFFA0A0A0; - - private Dimension<Integer> dim; - - public AbstractWidget(Dimension<Integer> dim) { - this.dim = dim; - } - - 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<Integer> dim) { - this.dim = dim; - } - - public Dimension<Integer> getDimension() { - return dim; - } - - @Override - public NarrationPriority narrationPriority() { - return NarrationPriority.NONE; - } - - public void unfocus() { - - } - - public boolean matchesSearch(String query) { - return true; - } - - @Override - public void updateNarration(NarrationElementOutput builder) { - - } - - protected void drawButtonRect(GuiGraphics graphics, 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; - - graphics.blitSprite(SPRITES.get(enabled, hovered), x1, y1, width, height); - } - - protected void drawOutline(GuiGraphics graphics, int x1, int y1, int x2, int y2, int width, int color) { - graphics.fill(x1, y1, x2, y1 + width, color); - graphics.fill(x2, y1, x2 - width, y2, color); - graphics.fill(x1, y2, x2, y2 - width, color); - graphics.fill(x1, y1, x1 + width, y2, color); - } - - 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() { - Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/DescriptionWithName.java b/common/src/main/java/dev/isxander/yacl3/gui/DescriptionWithName.java deleted file mode 100644 index 6ad72e8..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/DescriptionWithName.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.isxander.yacl3.gui; - -import dev.isxander.yacl3.api.OptionDescription; -import net.minecraft.ChatFormatting; -import net.minecraft.network.chat.Component; - -public record DescriptionWithName(Component name, OptionDescription description) { - public static DescriptionWithName of(Component name, OptionDescription description) { - return new DescriptionWithName(name.copy().withStyle(ChatFormatting.BOLD), description); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/ElementListWidgetExt.java b/common/src/main/java/dev/isxander/yacl3/gui/ElementListWidgetExt.java deleted file mode 100644 index 02fc6ad..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/ElementListWidgetExt.java +++ /dev/null @@ -1,216 +0,0 @@ -package dev.isxander.yacl3.gui; - -import com.mojang.blaze3d.platform.InputConstants; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.components.ContainerObjectSelectionList; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.gui.layouts.LayoutElement; -import net.minecraft.client.gui.navigation.ScreenRectangle; -import net.minecraft.util.Mth; -import org.jetbrains.annotations.Nullable; - -import java.util.function.Consumer; - -public class ElementListWidgetExt<E extends ElementListWidgetExt.Entry<E>> extends ContainerObjectSelectionList<E> implements LayoutElement { - protected static final int SCROLLBAR_WIDTH = 6; - - private double smoothScrollAmount = getScrollAmount(); - private boolean returnSmoothAmount = false; - private final boolean doSmoothScrolling; - private boolean usingScrollbar; - - public ElementListWidgetExt(Minecraft client, int x, int y, int width, int height, boolean smoothScrolling) { - super(client, x, y, width, height); - this.doSmoothScrolling = smoothScrolling; - setRenderHeader(false, 0); - } - - @Override - public boolean mouseScrolled(double mouseX, double mouseY, double horizontal, double vertical) { - // default implementation bases scroll step from total height of entries, this is constant - this.setScrollAmount(this.getScrollAmount() - (vertical + horizontal) * 20); - return true; - } - - @Override - protected int getScrollbarPosition() { - // default implementation does not respect left/right - return this.getRight() - SCROLLBAR_WIDTH; - } - - @Override - public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - if (usingScrollbar) { - resetSmoothScrolling(); - } - - smoothScrollAmount = Mth.lerp(Minecraft.getInstance().getDeltaFrameTime() * 0.5, smoothScrollAmount, getScrollAmount()); - returnSmoothAmount = true; - - graphics.enableScissor(this.getX(), this.getY(), this.getX() + this.getWidth(), this.getY() + this.getHeight()); - - super.renderWidget(graphics, mouseX, mouseY, delta); - - graphics.disableScissor(); - - returnSmoothAmount = false; - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (button == 0 && mouseX >= getScrollbarPosition() && mouseX < getScrollbarPosition() + SCROLLBAR_WIDTH) { - usingScrollbar = true; - } - - return super.mouseClicked(mouseX, mouseY, button); - } - - @Override - public boolean mouseReleased(double mouseX, double mouseY, int button) { - if (button == 0) { - usingScrollbar = false; - } - - return super.mouseReleased(mouseX, mouseY, button); - } - - public void updateDimensions(ScreenRectangle rectangle) { - this.setX(rectangle.left()); - this.setY(rectangle.top()); - this.setWidth(rectangle.width()); - this.setHeight(rectangle.height()); - } - - /** - * awful code to only use smooth scroll state when rendering, - * not other code that needs target scroll amount - */ - @Override - public double getScrollAmount() { - if (returnSmoothAmount && doSmoothScrolling) - return smoothScrollAmount; - - return super.getScrollAmount(); - } - - protected void resetSmoothScrolling() { - this.smoothScrollAmount = super.getScrollAmount(); - } - - @Nullable - @Override - protected E getEntryAtPosition(double x, double y) { - y += getScrollAmount(); - - if (x < this.getX() || x > this.getX() + this.getWidth()) - return null; - - int currentY = this.getY() - headerHeight + 4; - for (E entry : children()) { - if (y >= currentY && y <= currentY + entry.getItemHeight()) { - return entry; - } - - currentY += entry.getItemHeight(); - } - - return null; - } - - /* - below code is licensed from cloth-config under LGPL3 - modified to inherit vanilla's EntryListWidget and use yarn mappings - - code is responsible for having dynamic item heights - */ - - @Override - protected int getMaxPosition() { - return children().stream().map(E::getItemHeight).reduce(0, Integer::sum) + headerHeight; - } - - @Override - protected void centerScrollOn(E entry) { - double d = (this.height) / -2d; - for (int i = 0; i < this.children().indexOf(entry) && i < this.getItemCount(); i++) - d += children().get(i).getItemHeight(); - this.setScrollAmount(d); - } - - @Override - protected int getRowTop(int index) { - int integer = getY() + 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 ensureVisible(E entry) { - int i = this.getRowTop(this.children().indexOf(entry)); - int j = i - this.getY() - 4 - entry.getItemHeight(); - if (j < 0) { - this.setScrollAmount(this.getScrollAmount() + j); - } - - int k = this.getBottom() - i - entry.getItemHeight() * 2; - if (k < 0) { - this.setScrollAmount(this.getScrollAmount() - k); - } - } - - @Override - protected void renderListItems(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - int left = this.getRowLeft(); - int right = this.getRowWidth(); - int count = this.getItemCount(); - - for(int i = 0; i < count; ++i) { - E entry = children().get(i); - int top = this.getRowTop(i); - int bottom = top + entry.getItemHeight(); - int entryHeight = entry.getItemHeight() - 4; - if (bottom >= this.getY() && top <= this.getY() + this.getHeight()) { - this.renderItem(graphics, mouseX, mouseY, delta, i, left, top, right, entryHeight); - } - } - } - - /* END cloth config code */ - - @Override - public void visitWidgets(Consumer<AbstractWidget> consumer) { - } - - public abstract static class Entry<E extends Entry<E>> extends ContainerObjectSelectionList.Entry<E> { - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - for (GuiEventListener child : this.children()) { - if (child.mouseClicked(mouseX, mouseY, button)) { - if (button == InputConstants.MOUSE_BUTTON_LEFT) - this.setDragging(true); - return true; - } - } - - return false; - } - - @Override - public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { - if (isDragging() && button == InputConstants.MOUSE_BUTTON_LEFT) { - for (GuiEventListener child : this.children()) { - if (child.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)) - return true; - } - } - return false; - } - - public int getItemHeight() { - return 22; - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/LowProfileButtonWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/LowProfileButtonWidget.java deleted file mode 100644 index 3f5822f..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/LowProfileButtonWidget.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.isxander.yacl3.gui; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.Tooltip; -import net.minecraft.network.chat.Component; - -public class LowProfileButtonWidget extends Button { - public LowProfileButtonWidget(int x, int y, int width, int height, Component message, OnPress onPress) { - super(x, y, width, height, message, onPress, DEFAULT_NARRATION); - } - - public LowProfileButtonWidget(int x, int y, int width, int height, Component message, OnPress onPress, Tooltip tooltip) { - this(x, y, width, height, message, onPress); - setTooltip(tooltip); - } - - @Override - public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float deltaTicks) { - if (!isHoveredOrFocused() || !active) { - int j = this.active ? 0xFFFFFF : 0xA0A0A0; - this.renderString(graphics, Minecraft.getInstance().font, j); - } else { - super.renderWidget(graphics, mouseX, mouseY, deltaTicks); - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/OptionDescriptionWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/OptionDescriptionWidget.java deleted file mode 100644 index 7aa3715..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/OptionDescriptionWidget.java +++ /dev/null @@ -1,222 +0,0 @@ -package dev.isxander.yacl3.gui; - -import com.mojang.blaze3d.Blaze3D; -import com.mojang.blaze3d.platform.InputConstants; -import dev.isxander.yacl3.gui.image.ImageRenderer; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.ComponentPath; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.narration.NarratedElementType; -import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.gui.navigation.FocusNavigationEvent; -import net.minecraft.client.gui.navigation.ScreenRectangle; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.Style; -import net.minecraft.util.FormattedCharSequence; -import net.minecraft.util.Mth; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Optional; -import java.util.function.Supplier; - -public class OptionDescriptionWidget extends AbstractWidget { - private static final int AUTO_SCROLL_TIMER = 1500; - private static final float AUTO_SCROLL_SPEED = 1; // lines per second - - private @Nullable DescriptionWithName description; - private List<FormattedCharSequence> wrappedText; - - private static final Minecraft minecraft = Minecraft.getInstance(); - private static final Font font = minecraft.font; - - private Supplier<ScreenRectangle> dimensions; - - private float targetScrollAmount, currentScrollAmount; - private int maxScrollAmount; - private int descriptionY; - - private int lastInteractionTime; - private boolean scrollingBackward; - - public OptionDescriptionWidget(Supplier<ScreenRectangle> dimensions, @Nullable DescriptionWithName description) { - super(0, 0, 0, 0, description == null ? Component.empty() : description.name()); - this.dimensions = dimensions; - this.setOptionDescription(description); - } - - @Override - public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - if (description == null) return; - - currentScrollAmount = Mth.lerp(delta * 0.5f, currentScrollAmount, targetScrollAmount); - - ScreenRectangle dimensions = this.dimensions.get(); - this.setX(dimensions.left()); - this.setY(dimensions.top()); - this.width = dimensions.width(); - this.height = dimensions.height(); - - int y = getY(); - - int nameWidth = font.width(description.name()); - if (nameWidth > getWidth()) { - renderScrollingString(graphics, font, description.name(), getX(), y, getX() + getWidth(), y + font.lineHeight, -1); - } else { - graphics.drawString(font, description.name(), getX(), y, 0xFFFFFF); - } - - y += 5 + font.lineHeight; - - graphics.enableScissor(getX(), y, getX() + getWidth(), getY() + getHeight()); - - y -= (int)currentScrollAmount; - - if (description.description().image().isDone()) { - var image = description.description().image().join(); - if (image.isPresent()) { - y += image.get().render(graphics, getX(), y, getWidth(), delta) + 5; - } - } - - if (wrappedText == null) - wrappedText = font.split(description.description().text(), getWidth()); - - descriptionY = y; - for (var line : wrappedText) { - graphics.drawString(font, line, getX(), y, 0xFFFFFF); - y += font.lineHeight; - } - - graphics.disableScissor(); - - maxScrollAmount = Math.max(0, y + (int)currentScrollAmount - getY() - getHeight()); - - if (isHoveredOrFocused()) { - lastInteractionTime = currentTimeMS(); - } - Style hoveredStyle = getDescStyle(mouseX, mouseY); - if (hoveredStyle != null && hoveredStyle.getHoverEvent() != null) { - graphics.renderComponentHoverEffect(font, hoveredStyle, mouseX, mouseY); - } - - if (isFocused()) { - graphics.renderOutline(getX(), getY(), getWidth(), getHeight(), -1); - } - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - Style clickedStyle = getDescStyle((int) mouseX, (int) mouseY); - if (clickedStyle != null && clickedStyle.getClickEvent() != null) { - if (minecraft.screen.handleComponentClicked(clickedStyle)) { - playDownSound(minecraft.getSoundManager()); - return true; - } - return false; - } - - return false; - } - - @Override - public boolean mouseScrolled(double mouseX, double mouseY, double horizontal, double vertical) { - if (isMouseOver(mouseX, mouseY)) { - targetScrollAmount = Mth.clamp(targetScrollAmount - (int) vertical * 10, 0, maxScrollAmount); - lastInteractionTime = currentTimeMS(); - return true; - } - return false; - } - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if (isFocused()) { - switch (keyCode) { - case InputConstants.KEY_UP -> - targetScrollAmount = Mth.clamp(targetScrollAmount - 10, 0, maxScrollAmount); - case InputConstants.KEY_DOWN -> - targetScrollAmount = Mth.clamp(targetScrollAmount + 10, 0, maxScrollAmount); - default -> { - return false; - } - } - return true; - } - return false; - } - - public void tick() { - if (description != null) { - description.description().image() - .getNow(Optional.empty()) - .ifPresent(ImageRenderer::tick); - } - - float pxPerTick = AUTO_SCROLL_SPEED / 20f * font.lineHeight; - if (maxScrollAmount > 0 && currentTimeMS() - lastInteractionTime > AUTO_SCROLL_TIMER) { - if (scrollingBackward) { - pxPerTick *= -1; - if (targetScrollAmount + pxPerTick < 0) { - scrollingBackward = false; - lastInteractionTime = currentTimeMS(); - } - } else { - if (targetScrollAmount + pxPerTick > maxScrollAmount) { - scrollingBackward = true; - lastInteractionTime = currentTimeMS(); - } - } - - targetScrollAmount = Mth.clamp(targetScrollAmount + pxPerTick, 0, maxScrollAmount); - } - } - - private Style getDescStyle(int mouseX, int mouseY) { - if (!clicked(mouseX, mouseY)) - return null; - - int x = mouseX - getX(); - int y = mouseY - descriptionY; - - if (x < 0 || x > getX() + getWidth()) return null; - if (y < 0 || y > getY() + getHeight()) return null; - - int line = y / font.lineHeight; - - if (line >= wrappedText.size()) return null; - - return font.getSplitter().componentStyleAtWidth(wrappedText.get(line), x); - } - - @Override - protected void updateWidgetNarration(NarrationElementOutput builder) { - if (description != null) { - builder.add(NarratedElementType.TITLE, description.name()); - builder.add(NarratedElementType.HINT, description.description().text()); - } - - } - - public void setOptionDescription(DescriptionWithName description) { - this.description = description; - this.wrappedText = null; - this.targetScrollAmount = 0; - this.currentScrollAmount = 0; - this.lastInteractionTime = currentTimeMS(); - } - - private int currentTimeMS() { - return (int)(Blaze3D.getTime() * 1000); - } - - @Nullable - @Override - public ComponentPath nextFocusPath(FocusNavigationEvent event) { - // prevents focusing on this widget - return null; - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/OptionListWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/OptionListWidget.java deleted file mode 100644 index 9e1931f..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/OptionListWidget.java +++ /dev/null @@ -1,577 +0,0 @@ -package dev.isxander.yacl3.gui; - -import com.google.common.collect.ImmutableList; -import dev.isxander.yacl3.api.*; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.impl.utils.YACLConstants; -import net.minecraft.ChatFormatting; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.gui.narration.NarratableEntry; -import net.minecraft.client.gui.narration.NarratedElementType; -import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.function.Consumer; - -public class OptionListWidget extends ElementListWidgetExt<OptionListWidget.Entry> { - private final YACLScreen yaclScreen; - private final ConfigCategory category; - private ImmutableList<Entry> viewableChildren; - private String searchQuery = ""; - private final Consumer<DescriptionWithName> hoverEvent; - private DescriptionWithName lastHoveredOption; - - public OptionListWidget(YACLScreen screen, ConfigCategory category, Minecraft client, int x, int y, int width, int height, Consumer<DescriptionWithName> hoverEvent) { - super(client, width, height, x, y, true); - this.yaclScreen = screen; - this.category = category; - this.hoverEvent = hoverEvent; - - refreshOptions(); - - for (OptionGroup group : category.groups()) { - if (group instanceof ListOption<?> listOption) { - listOption.addRefreshListener(() -> refreshListEntries(listOption, category)); - } - } - } - - public void refreshOptions() { - clearEntries(); - - for (OptionGroup group : category.groups()) { - GroupSeparatorEntry groupSeparatorEntry; - if (!group.isRoot()) { - groupSeparatorEntry = group instanceof ListOption<?> listOption - ? new ListGroupSeparatorEntry(listOption, yaclScreen) - : new GroupSeparatorEntry(group, yaclScreen); - addEntry(groupSeparatorEntry); - } else { - groupSeparatorEntry = null; - } - - List<Entry> optionEntries = new ArrayList<>(); - - // add empty entry to make sure users know it's empty not just bugging out - if (groupSeparatorEntry instanceof ListGroupSeparatorEntry listGroupSeparatorEntry) { - if (listGroupSeparatorEntry.listOption.options().isEmpty()) { - EmptyListLabel emptyListLabel = new EmptyListLabel(listGroupSeparatorEntry, category); - addEntry(emptyListLabel); - optionEntries.add(emptyListLabel); - } - } - - for (Option<?> option : group.options()) { - OptionEntry entry = new OptionEntry(option, category, group, groupSeparatorEntry, option.controller().provideWidget(yaclScreen, getDefaultEntryDimension())); - addEntry(entry); - optionEntries.add(entry); - } - - if (groupSeparatorEntry != null) { - groupSeparatorEntry.setChildEntries(optionEntries); - } - } - - recacheViewableChildren(); - setScrollAmount(0); - resetSmoothScrolling(); - } - - private void refreshListEntries(ListOption<?> listOption, ConfigCategory category) { - // find group separator for group - ListGroupSeparatorEntry groupSeparator = super.children().stream().filter(e -> e instanceof ListGroupSeparatorEntry gs && gs.group == listOption).map(ListGroupSeparatorEntry.class::cast).findAny().orElse(null); - - if (groupSeparator == null) { - YACLConstants.LOGGER.warn("Can't find group seperator to refresh list option entries for list option " + listOption.name()); - return; - } - - for (Entry entry : groupSeparator.childEntries) - super.removeEntry(entry); - groupSeparator.childEntries.clear(); - - // if no entries, below loop won't run where addEntryBelow() recaches viewable children - if (listOption.options().isEmpty()) { - EmptyListLabel emptyListLabel; - addEntryBelow(groupSeparator, emptyListLabel = new EmptyListLabel(groupSeparator, category)); - groupSeparator.childEntries.add(emptyListLabel); - return; - } - - Entry lastEntry = groupSeparator; - for (ListOptionEntry<?> listOptionEntry : listOption.options()) { - OptionEntry optionEntry = new OptionEntry(listOptionEntry, category, listOption, groupSeparator, listOptionEntry.controller().provideWidget(yaclScreen, getDefaultEntryDimension())); - addEntryBelow(lastEntry, optionEntry); - groupSeparator.childEntries.add(optionEntry); - lastEntry = optionEntry; - } - } - - public Dimension<Integer> getDefaultEntryDimension() { - return Dimension.ofInt(getRowLeft(), 0, getRowWidth(), 20); - } - - public void expandAllGroups() { - for (Entry entry : super.children()) { - if (entry instanceof GroupSeparatorEntry groupSeparatorEntry) { - groupSeparatorEntry.setExpanded(true); - } - } - } - - public void updateSearchQuery(String query) { - this.searchQuery = query; - expandAllGroups(); - recacheViewableChildren(); - } - - @Override - public int getRowLeft() { - return super.getRowLeft() - SCROLLBAR_WIDTH; - } - - @Override - public int getRowWidth() { - return getWidth() - SCROLLBAR_WIDTH - 20; - } - - @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 horizontal, double vertical) { - super.mouseScrolled(mouseX, mouseY, horizontal, vertical); - - for (Entry child : children()) { - if (child.mouseScrolled(mouseX, mouseY, horizontal, vertical)) - break; - } - - 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); - } - - 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<Entry> children() { - return viewableChildren; - } - - public void addEntry(int index, Entry entry) { - super.children().add(index, entry); - recacheViewableChildren(); - } - - public void addEntryBelow(Entry below, Entry entry) { - int idx = super.children().indexOf(below) + 1; - - if (idx == 0) - throw new IllegalStateException("The entry to insert below does not exist!"); - - addEntry(idx, entry); - } - - public void addEntryBelowWithoutScroll(Entry below, Entry entry) { - double d = (double)this.getMaxScroll() - this.getScrollAmount(); - addEntryBelow(below, entry); - setScrollAmount(getMaxScroll() - d); - } - - @Override - public boolean removeEntryFromTop(Entry entry) { - boolean ret = super.removeEntryFromTop(entry); - recacheViewableChildren(); - return ret; - } - - @Override - public boolean removeEntry(Entry entry) { - boolean ret = super.removeEntry(entry); - recacheViewableChildren(); - return ret; - } - - private void setHoverDescription(DescriptionWithName description) { - if (description != lastHoveredOption) { - lastHoveredOption = description; - hoverEvent.accept(description); - } - } - - @Override - protected void renderListBackground(GuiGraphics guiGraphics) { - //super.renderListBackground(); - } - - public abstract class Entry extends ElementListWidgetExt.Entry<Entry> { - public boolean isViewable() { - return true; - } - - protected boolean isHovered() { - return Objects.equals(getHovered(), this); - } - } - - public class OptionEntry extends Entry { - public final Option<?> option; - public final ConfigCategory category; - public final OptionGroup group; - - public final @Nullable GroupSeparatorEntry groupSeparatorEntry; - - public final AbstractWidget widget; - - private final TextScaledButtonWidget resetButton; - - private final String categoryName; - private final String groupName; - - public OptionEntry(Option<?> option, ConfigCategory category, OptionGroup group, @Nullable GroupSeparatorEntry groupSeparatorEntry, AbstractWidget widget) { - this.option = option; - this.category = category; - this.group = group; - this.groupSeparatorEntry = groupSeparatorEntry; - this.widget = widget; - this.categoryName = category.name().getString().toLowerCase(); - this.groupName = group.name().getString().toLowerCase(); - if (option.canResetToDefault() && this.widget.canReset()) { - this.widget.setDimension(this.widget.getDimension().expanded(-20, 0)); - this.resetButton = new TextScaledButtonWidget(yaclScreen, widget.getDimension().xLimit(), -50, 20, 20, 2f, Component.literal("\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(GuiGraphics graphics, 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(graphics, mouseX, mouseY, tickDelta); - - if (resetButton != null) { - resetButton.setY(y); - resetButton.render(graphics, mouseX, mouseY, tickDelta); - } - - if (isHovered()) { - setHoverDescription(DescriptionWithName.of(option.name(), option.description())); - } - } - - @Override - public boolean mouseScrolled(double mouseX, double mouseY, double horizontal, double vertical) { - return widget.mouseScrolled(mouseX, mouseY, horizontal, vertical); - } - - @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() { - return (groupSeparatorEntry == null || groupSeparatorEntry.isExpanded()) - && (searchQuery.isEmpty() - || groupName.contains(searchQuery) - || widget.matchesSearch(searchQuery)); - } - - @Override - public int getItemHeight() { - return Math.max(widget.getDimension().height(), resetButton != null ? resetButton.getHeight() : 0) + 2; - } - - @Override - public void setFocused(boolean focused) { - super.setFocused(focused); - if (focused) - setHoverDescription(DescriptionWithName.of(option.name(), option.description())); - } - - @Override - public List<? extends NarratableEntry> narratables() { - if (resetButton == null) - return ImmutableList.of(widget); - - return ImmutableList.of(widget, resetButton); - } - - @Override - public List<? extends GuiEventListener> children() { - if (resetButton == null) - return ImmutableList.of(widget); - - return ImmutableList.of(widget, resetButton); - } - } - - public class GroupSeparatorEntry extends Entry { - protected final OptionGroup group; - protected final MultiLineLabel wrappedName; - protected final MultiLineLabel wrappedTooltip; - - protected final LowProfileButtonWidget expandMinimizeButton; - - protected final Screen screen; - protected final Font font = Minecraft.getInstance().font; - - protected boolean groupExpanded; - - protected List<Entry> childEntries = new ArrayList<>(); - - private int y; - - private GroupSeparatorEntry(OptionGroup group, Screen screen) { - this.group = group; - this.screen = screen; - this.wrappedName = MultiLineLabel.create(font, group.name(), getRowWidth() - 45); - this.wrappedTooltip = MultiLineLabel.create(font, group.tooltip(), screen.width / 3 * 2 - 10); - this.groupExpanded = !group.collapsed(); - this.expandMinimizeButton = new LowProfileButtonWidget(0, 0, 20, 20, Component.empty(), btn -> onExpandButtonPress()); - updateExpandMinimizeText(); - } - - @Override - public void render(GuiGraphics graphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { - this.y = y; - - int buttonY = y + entryHeight / 2 - expandMinimizeButton.getHeight() / 2 + 1; - - expandMinimizeButton.setY(buttonY); - expandMinimizeButton.setX(x); - expandMinimizeButton.render(graphics, mouseX, mouseY, tickDelta); - - wrappedName.renderCentered(graphics, x + entryWidth / 2, y + getYPadding()); - - if (isHovered()) { - setHoverDescription(DescriptionWithName.of(group.name(), group.description())); - } - } - - public boolean isExpanded() { - return groupExpanded; - } - - public void setExpanded(boolean expanded) { - if (this.groupExpanded == expanded) - return; - - this.groupExpanded = expanded; - updateExpandMinimizeText(); - recacheViewableChildren(); - } - - protected void onExpandButtonPress() { - setExpanded(!isExpanded()); - } - - protected void updateExpandMinimizeText() { - expandMinimizeButton.setMessage(Component.literal(isExpanded() ? "â–¼" : "â–¶")); - } - - public void setChildEntries(List<? extends Entry> childEntries) { - this.childEntries.clear(); - this.childEntries.addAll(childEntries); - } - - @Override - public boolean isViewable() { - return searchQuery.isEmpty() || childEntries.stream().anyMatch(Entry::isViewable); - } - - @Override - public int getItemHeight() { - return Math.max(wrappedName.getLineCount(), 1) * font.lineHeight + getYPadding() * 2; - } - - private int getYPadding() { - return 6; - } - - @Override - public void setFocused(boolean focused) { - super.setFocused(focused); - if (focused) - setHoverDescription(DescriptionWithName.of(group.name(), group.description())); - } - - @Override - public List<? extends NarratableEntry> narratables() { - return ImmutableList.of(new NarratableEntry() { - @Override - public NarrationPriority narrationPriority() { - return NarrationPriority.HOVERED; - } - - @Override - public void updateNarration(NarrationElementOutput builder) { - builder.add(NarratedElementType.TITLE, group.name()); - builder.add(NarratedElementType.HINT, group.tooltip()); - } - }); - } - - @Override - public List<? extends GuiEventListener> children() { - return ImmutableList.of(expandMinimizeButton); - } - } - - public class ListGroupSeparatorEntry extends GroupSeparatorEntry { - private final ListOption<?> listOption; - private final TextScaledButtonWidget resetListButton; - private final TooltipButtonWidget addListButton; - - private ListGroupSeparatorEntry(ListOption<?> group, Screen screen) { - super(group, screen); - this.listOption = group; - - this.resetListButton = new TextScaledButtonWidget(screen, getRowRight() - 20, -50, 20, 20, 2f, Component.literal("\u21BB"), button -> { - group.requestSetDefault(); - }); - group.addListener((opt, val) -> this.resetListButton.active = !opt.isPendingValueDefault() && opt.available()); - this.resetListButton.active = !group.isPendingValueDefault() && group.available(); - - - this.addListButton = new TooltipButtonWidget(yaclScreen, resetListButton.getX() - 20, -50, 20, 20, Component.literal("+"), Component.translatable("yacl.list.add_top"), btn -> { - group.insertNewEntry(); - setExpanded(true); - }); - - updateExpandMinimizeText(); - minimizeIfUnavailable(); - } - - @Override - public void render(GuiGraphics graphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { - updateExpandMinimizeText(); // update every render because option could become available/unavailable at any time - - super.render(graphics, index, y, x, entryWidth, entryHeight, mouseX, mouseY, hovered, tickDelta); - - int buttonY = expandMinimizeButton.getY(); - - resetListButton.setY(buttonY); - addListButton.setY(buttonY); - - resetListButton.render(graphics, mouseX, mouseY, tickDelta); - addListButton.render(graphics, mouseX, mouseY, tickDelta); - } - - private void minimizeIfUnavailable() { - if (!listOption.available() && isExpanded()) { - setExpanded(false); - } - } - - @Override - protected void updateExpandMinimizeText() { - super.updateExpandMinimizeText(); - expandMinimizeButton.active = listOption == null || listOption.available(); - if (addListButton != null) - addListButton.active = expandMinimizeButton.active && listOption.numberOfEntries() < listOption.maximumNumberOfEntries(); - } - - @Override - public void setExpanded(boolean expanded) { - super.setExpanded(listOption.available() && expanded); - } - - @Override - public List<? extends GuiEventListener> children() { - return ImmutableList.of(expandMinimizeButton, addListButton, resetListButton); - } - } - - public class EmptyListLabel extends Entry { - private final ListGroupSeparatorEntry parent; - private final String groupName; - private final String categoryName; - - public EmptyListLabel(ListGroupSeparatorEntry parent, ConfigCategory category) { - this.parent = parent; - this.groupName = parent.group.name().getString().toLowerCase(); - this.categoryName = category.name().getString().toLowerCase(); - } - - @Override - public void render(GuiGraphics graphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { - graphics.drawCenteredString(Minecraft.getInstance().font, Component.translatable("yacl.list.empty").withStyle(ChatFormatting.DARK_GRAY, ChatFormatting.ITALIC), x + entryWidth / 2, y, -1); - } - - @Override - public boolean isViewable() { - return parent.isExpanded() && (searchQuery.isEmpty() || groupName.contains(searchQuery)); - } - - @Override - public int getItemHeight() { - return 11; - } - - @Override - public List<? extends GuiEventListener> children() { - return ImmutableList.of(); - } - - @Override - public List<? extends NarratableEntry> narratables() { - return ImmutableList.of(); - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/RequireRestartScreen.java b/common/src/main/java/dev/isxander/yacl3/gui/RequireRestartScreen.java deleted file mode 100644 index 5ba4b03..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/RequireRestartScreen.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.isxander.yacl3.gui; - -import net.minecraft.ChatFormatting; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.ConfirmScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -public class RequireRestartScreen extends ConfirmScreen { - public RequireRestartScreen(Screen parent) { - super(option -> { - if (option) Minecraft.getInstance().stop(); - else Minecraft.getInstance().setScreen(parent); - }, - Component.translatable("yacl.restart.title").withStyle(ChatFormatting.RED, ChatFormatting.BOLD), - Component.translatable("yacl.restart.message"), - Component.translatable("yacl.restart.yes"), - Component.translatable("yacl.restart.no") - ); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/SearchFieldWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/SearchFieldWidget.java deleted file mode 100644 index a666886..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/SearchFieldWidget.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.isxander.yacl3.gui; - -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.EditBox; -import net.minecraft.network.chat.Component; - -import java.util.function.Consumer; - -public class SearchFieldWidget extends EditBox { - private Component emptyText; - private final YACLScreen yaclScreen; - private final Font font; - private final Consumer<String> updateConsumer; - - private boolean isEmpty = true; - - public SearchFieldWidget(YACLScreen yaclScreen, Font font, int x, int y, int width, int height, Component text, Component emptyText, Consumer<String> updateConsumer) { - super(font, x, y, width, height, text); - setResponder(this::update); - setFilter(string -> !string.endsWith(" ") && !string.startsWith(" ")); - this.yaclScreen = yaclScreen; - this.font = font; - this.emptyText = emptyText; - this.updateConsumer = updateConsumer; - } - - @Override - public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - super.renderWidget(graphics, mouseX, mouseY, delta); - if (isVisible() && isEmpty()) { - graphics.drawString(font, emptyText, getX() + 4, this.getY() + (this.height - 8) / 2, 0x707070, true); - } - } - - private void update(String query) { - boolean wasEmpty = isEmpty; - isEmpty = query.isEmpty(); - - if (isEmpty && wasEmpty) - return; - - updateConsumer.accept(query); - } - - public String getQuery() { - return getValue().toLowerCase(); - } - - public boolean isEmpty() { - return isEmpty; - } - - public Component getEmptyText() { - return emptyText; - } - - public void setEmptyText(Component emptyText) { - this.emptyText = emptyText; - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/TextScaledButtonWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/TextScaledButtonWidget.java deleted file mode 100644 index 6ad0d1c..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/TextScaledButtonWidget.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.isxander.yacl3.gui; - -import com.mojang.blaze3d.vertex.PoseStack; -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.network.chat.Component; -import net.minecraft.util.Mth; - -public class TextScaledButtonWidget extends TooltipButtonWidget { - public float textScale; - - public TextScaledButtonWidget(Screen screen, int x, int y, int width, int height, float textScale, Component message, Component tooltip, OnPress onPress) { - super(screen, x, y, width, height, message, tooltip, onPress); - this.textScale = textScale; - } - - public TextScaledButtonWidget(Screen screen, int x, int y, int width, int height, float textScale, Component message, OnPress onPress) { - this(screen, x, y, width, height, textScale, message, null, onPress); - } - - @Override - public void renderString(GuiGraphics graphics, Font textRenderer, int color) { - Font font = Minecraft.getInstance().font; - PoseStack pose = graphics.pose(); - - pose.pushPose(); - pose.translate(((this.getX() + this.width / 2f) - font.width(getMessage()) * textScale / 2), (float)this.getY() + (this.height - 8 * textScale) / 2f / textScale, 0); - pose.scale(textScale, textScale, 1); - graphics.drawString(font, getMessage(), 0, 0, color | Mth.ceil(this.alpha * 255.0F) << 24, true); - pose.popPose(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/TooltipButtonWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/TooltipButtonWidget.java deleted file mode 100644 index f88bdc3..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/TooltipButtonWidget.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.isxander.yacl3.gui; - -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.Tooltip; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class TooltipButtonWidget extends Button { - - protected final Screen screen; - - public TooltipButtonWidget(Screen screen, int x, int y, int width, int height, Component message, Component tooltip, OnPress onPress) { - super(x, y, width, height, message, onPress, DEFAULT_NARRATION); - this.screen = screen; - // TODO - if (tooltip != null); - //setTooltip(new YACLTooltip(tooltip, this)); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/ValueFormatters.java b/common/src/main/java/dev/isxander/yacl3/gui/ValueFormatters.java deleted file mode 100644 index 3771fc3..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/ValueFormatters.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.isxander.yacl3.gui; - -import dev.isxander.yacl3.api.controller.ValueFormatter; -import net.minecraft.network.chat.Component; - -public final class ValueFormatters { - public static final PercentFormatter PERCENT = new PercentFormatter(); - - public static final class PercentFormatter implements ValueFormatter<Float> { - @Override - public Component format(Float value) { - return Component.literal(String.format("%.0f%%", value * 100)); - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/YACLScreen.java b/common/src/main/java/dev/isxander/yacl3/gui/YACLScreen.java deleted file mode 100644 index 01c5d99..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/YACLScreen.java +++ /dev/null @@ -1,417 +0,0 @@ -package dev.isxander.yacl3.gui; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; -import com.mojang.math.Axis; -import dev.isxander.yacl3.api.*; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.api.utils.MutableDimension; -import dev.isxander.yacl3.api.utils.OptionUtils; -import dev.isxander.yacl3.gui.tab.ScrollableNavigationBar; -import dev.isxander.yacl3.gui.tab.ListHolderWidget; -import dev.isxander.yacl3.gui.tab.TabExt; -import dev.isxander.yacl3.gui.utils.GuiUtils; -import dev.isxander.yacl3.impl.utils.YACLConstants; -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.client.gui.components.Tooltip; -import net.minecraft.client.gui.components.tabs.TabManager; -import net.minecraft.client.gui.components.tabs.TabNavigationBar; -import net.minecraft.client.gui.navigation.ScreenRectangle; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.tooltip.TooltipRenderUtil; -import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; - -import java.util.HashSet; -import java.util.Set; -import java.util.function.Consumer; - -public class YACLScreen extends Screen { - private static final ResourceLocation DARKER_BG = new ResourceLocation("textures/gui/menu_list_background.png"); - - public final YetAnotherConfigLib config; - - private final Screen parent; - - public final TabManager tabManager = new TabManager(this::addRenderableWidget, this::removeWidget); - public TabNavigationBar tabNavigationBar; - public ScreenRectangle tabArea; - - public Component saveButtonMessage; - public Tooltip saveButtonTooltipMessage; - private int saveButtonMessageTime; - - private boolean pendingChanges; - - public YACLScreen(YetAnotherConfigLib config, Screen parent) { - super(config.title()); - this.config = config; - this.parent = parent; - - OptionUtils.forEachOptions(config, option -> { - option.addListener((opt, val) -> onOptionChanged(opt)); - }); - } - - @Override - protected void init() { - tabArea = new ScreenRectangle(0, 24 - 1, this.width, this.height - 24 + 1); - - int currentTab = tabNavigationBar != null - ? tabNavigationBar.tabs.indexOf(tabManager.getCurrentTab()) - : 0; - if (currentTab == -1) - currentTab = 0; - - tabNavigationBar = new ScrollableNavigationBar(this.width, tabManager, config.categories() - .stream() - .map(category -> { - if (category instanceof PlaceholderCategory placeholder) - return new PlaceholderTab(placeholder); - return new CategoryTab(category); - }).toList()); - tabNavigationBar.selectTab(currentTab, false); - tabNavigationBar.arrangeElements(); - tabManager.setTabArea(tabArea); - addRenderableWidget(tabNavigationBar); - - config.initConsumer().accept(this); - } - - @Override - public void renderBackground(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) { - super.renderBackground(guiGraphics, mouseX, mouseY, partialTick); - - if (tabManager.getCurrentTab() instanceof TabExt tab) { - tab.renderBackground(guiGraphics); - } - } - - protected void finishOrSave() { - saveButtonMessage = null; - - if (pendingChanges()) { - Set<OptionFlag> flags = new HashSet<>(); - OptionUtils.forEachOptions(config, option -> { - if (option.applyValue()) { - flags.addAll(option.flags()); - } - }); - OptionUtils.forEachOptions(config, option -> { - if (option.changed()) { - // if still changed after applying, reset to the current value from binding - // as something has gone wrong. - option.forgetPendingValue(); - YACLConstants.LOGGER.error("Option '{}' value mismatch after applying! Reset to binding's getter.", option.name().getString()); - } - }); - config.saveFunction().run(); - - flags.forEach(flag -> flag.accept(minecraft)); - - pendingChanges = false; - if (tabManager.getCurrentTab() instanceof CategoryTab categoryTab) { - categoryTab.updateButtons(); - } - } else onClose(); - } - - protected void cancelOrReset() { - if (pendingChanges()) { // if pending changes, button acts as a cancel button - OptionUtils.forEachOptions(config, Option::forgetPendingValue); - onClose(); - } else { // if not, button acts as a reset button - OptionUtils.forEachOptions(config, Option::requestSetDefault); - } - } - - protected void undo() { - OptionUtils.forEachOptions(config, Option::forgetPendingValue); - } - - @Override - public void tick() { - if (tabManager.getCurrentTab() instanceof TabExt tabExt) { - tabExt.tick(); - } - - if (tabManager.getCurrentTab() instanceof CategoryTab categoryTab) { - if (saveButtonMessage != null) { - if (saveButtonMessageTime > 140) { - saveButtonMessage = null; - saveButtonTooltipMessage = null; - saveButtonMessageTime = 0; - } else { - saveButtonMessageTime++; - categoryTab.saveFinishedButton.setMessage(saveButtonMessage); - if (saveButtonTooltipMessage != null) { - categoryTab.saveFinishedButton.setTooltip(saveButtonTooltipMessage); - } - } - } - } - } - - private void setSaveButtonMessage(Component message, Component tooltip) { - saveButtonMessage = message; - saveButtonTooltipMessage = Tooltip.create(tooltip); - saveButtonMessageTime = 0; - } - - private boolean pendingChanges() { - return pendingChanges; - } - - private void onOptionChanged(Option<?> option) { - pendingChanges = false; - - OptionUtils.consumeOptions(config, opt -> { - pendingChanges |= opt.changed(); - return pendingChanges; - }); - - if (tabManager.getCurrentTab() instanceof CategoryTab categoryTab) { - categoryTab.updateButtons(); - } - } - - @Override - protected void renderMenuBackground(GuiGraphics guiGraphics) { - this.renderMenuBackground(guiGraphics, 0, this.tabArea.top() + 1, this.width, this.tabArea.height()); - } - - @Override - public boolean shouldCloseOnEsc() { - if (pendingChanges()) { - setSaveButtonMessage(Component.translatable("yacl.gui.save_before_exit").withStyle(ChatFormatting.RED), Component.translatable("yacl.gui.save_before_exit.tooltip")); - return false; - } - return true; - } - - @Override - public void onClose() { - minecraft.setScreen(parent); - } - - public static void renderMultilineTooltip(GuiGraphics graphics, Font font, MultiLineLabel text, int centerX, int yAbove, int yBelow, int screenWidth, int screenHeight) { - if (text.getLineCount() > 0) { - int maxWidth = text.getWidth(); - int lineHeight = font.lineHeight + 1; - int height = text.getLineCount() * lineHeight - 1; - - int belowY = yBelow + 12; - int aboveY = yAbove - height + 12; - int maxBelow = screenHeight - (belowY + height); - int minAbove = aboveY - height; - int y = aboveY; - if (minAbove < 8) - y = maxBelow > minAbove ? belowY : aboveY; - - int x = Math.max(centerX - text.getWidth() / 2 - 12, -6); - - int drawX = x + 12; - int drawY = y - 12; - - graphics.pose().pushPose(); - Tesselator tesselator = Tesselator.getInstance(); - BufferBuilder bufferBuilder = tesselator.getBuilder(); - RenderSystem.setShader(GameRenderer::getPositionColorShader); - bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - TooltipRenderUtil.renderTooltipBackground( - graphics, - drawX, - drawY, - maxWidth, - height, - 400 - ); - RenderSystem.enableDepthTest(); - RenderSystem.enableBlend(); - RenderSystem.defaultBlendFunc(); - BufferUploader.drawWithShader(bufferBuilder.end()); - RenderSystem.disableBlend(); - graphics.pose().translate(0.0, 0.0, 400.0); - - text.renderLeftAligned(graphics, drawX, drawY, lineHeight, -1); - - graphics.pose().popPose(); - } - } - - public class CategoryTab implements TabExt { - private final ConfigCategory category; - private final Tooltip tooltip; - - private ListHolderWidget<OptionListWidget> optionList; - public final Button saveFinishedButton; - private final Button cancelResetButton; - private final Button undoButton; - private final SearchFieldWidget searchField; - private OptionDescriptionWidget descriptionWidget; - - private final ScreenRectangle rightPaneDim; - - public CategoryTab(ConfigCategory category) { - this.category = category; - this.tooltip = Tooltip.create(category.tooltip()); - - int columnWidth = width / 3; - int padding = columnWidth / 20; - columnWidth = Math.min(columnWidth, 400); - int paddedWidth = columnWidth - padding * 2; - rightPaneDim = new ScreenRectangle(width / 3 * 2, tabArea.top() + 1, width / 3, tabArea.height()); - MutableDimension<Integer> actionDim = Dimension.ofInt(width / 3 * 2 + width / 6, height - padding - 20, paddedWidth, 20); - - saveFinishedButton = Button.builder(Component.literal("Done"), btn -> finishOrSave()) - .pos(actionDim.x() - actionDim.width() / 2, actionDim.y()) - .size(actionDim.width(), actionDim.height()) - .build(); - - actionDim.expand(-actionDim.width() / 2 - 2, 0).move(-actionDim.width() / 2 - 2, -22); - cancelResetButton = Button.builder(Component.literal("Cancel"), btn -> cancelOrReset()) - .pos(actionDim.x() - actionDim.width() / 2, actionDim.y()) - .size(actionDim.width(), actionDim.height()) - .build(); - - actionDim.move(actionDim.width() + 4, 0); - undoButton = Button.builder(Component.translatable("yacl.gui.undo"), btn -> undo()) - .pos(actionDim.x() - actionDim.width() / 2, actionDim.y()) - .size(actionDim.width(), actionDim.height()) - .tooltip(Tooltip.create(Component.translatable("yacl.gui.undo.tooltip"))) - .build(); - - searchField = new SearchFieldWidget( - YACLScreen.this, - font, - width / 3 * 2 + width / 6 - paddedWidth / 2 + 1, - undoButton.getY() - 22, - paddedWidth - 2, 18, - Component.translatable("gui.recipebook.search_hint"), - Component.translatable("gui.recipebook.search_hint"), - searchQuery -> optionList.getList().updateSearchQuery(searchQuery) - ); - - this.optionList = new ListHolderWidget<>( - () -> new ScreenRectangle(tabArea.position(), tabArea.width() / 3 * 2, tabArea.height()), - new OptionListWidget(YACLScreen.this, category, minecraft, 0, 0, width / 3 * 2 + 1, height, desc -> { - descriptionWidget.setOptionDescription(desc); - }) - ); - - descriptionWidget = new OptionDescriptionWidget( - () -> new ScreenRectangle( - width / 3 * 2 + padding, - tabArea.top() + padding, - paddedWidth, - searchField.getY() - 1 - tabArea.top() - padding * 2 - ), - null - ); - - updateButtons(); - } - - @Override - public Component getTabTitle() { - return category.name(); - } - - @Override - public void visitChildren(Consumer<AbstractWidget> consumer) { - consumer.accept(optionList); - consumer.accept(saveFinishedButton); - consumer.accept(cancelResetButton); - consumer.accept(undoButton); - consumer.accept(searchField); - consumer.accept(descriptionWidget); - } - - @Override - public void renderBackground(GuiGraphics graphics) { - RenderSystem.enableBlend(); - // right pane darker db - graphics.blit(DARKER_BG, rightPaneDim.left(), rightPaneDim.top(), rightPaneDim.right() + 2, rightPaneDim.bottom() + 2, rightPaneDim.width() + 2, rightPaneDim.height() + 2, 32, 32); - - // top separator for right pane - graphics.pose().pushPose(); - graphics.pose().translate(0, 0, 10); - graphics.blit(CreateWorldScreen.HEADER_SEPARATOR, rightPaneDim.left() - 1, rightPaneDim.top() - 2, 0.0F, 0.0F, rightPaneDim.width() + 1, 2, 32, 2); - graphics.pose().popPose(); - - // left separator for right pane - graphics.pose().pushPose(); - graphics.pose().translate(rightPaneDim.left(), rightPaneDim.top() - 1, 0); - graphics.pose().rotateAround(Axis.ZP.rotationDegrees(90), 0, 0, 1); - graphics.blit(CreateWorldScreen.FOOTER_SEPARATOR, 0, 0, 0f, 0f, rightPaneDim.height() + 1, 2, 32, 2); - graphics.pose().popPose(); - - RenderSystem.disableBlend(); - } - - @Override - public void doLayout(ScreenRectangle screenRectangle) { - - } - - @Override - public void tick() { - descriptionWidget.tick(); - } - - @Nullable - @Override - public Tooltip getTooltip() { - return tooltip; - } - - public void updateButtons() { - boolean pendingChanges = pendingChanges(); - - // TODO - undoButton.active = pendingChanges; saveFinishedButton.setMessage(pendingChanges ? Component.translatable("yacl.gui.save") : GuiUtils.translatableFallback("yacl.gui.done", CommonComponents.GUI_DONE)); - //saveFinishedButton.setTooltip(new YACLTooltip(pendingChanges ? Component.translatable("yacl.gui.save.tooltip") : Component.translatable("yacl.gui.finished.tooltip"), saveFinishedButton)); - cancelResetButton.setMessage(pendingChanges ? GuiUtils.translatableFallback("yacl.gui.cancel", CommonComponents.GUI_CANCEL) : Component.translatable("controls.reset")); - //cancelResetButton.setTooltip(new YACLTooltip(pendingChanges ? Component.translatable("yacl.gui.cancel.tooltip") : Component.translatable("yacl.gui.reset.tooltip"), cancelResetButton)); - } - } - - public class PlaceholderTab implements TabExt { - private final PlaceholderCategory category; - private final Tooltip tooltip; - - public PlaceholderTab(PlaceholderCategory category) { - this.category = category; - this.tooltip = Tooltip.create(category.tooltip()); - } - - @Override - public Component getTabTitle() { - return category.name(); - } - - @Override - public void visitChildren(Consumer<AbstractWidget> consumer) { - - } - - @Override - public void doLayout(ScreenRectangle screenRectangle) { - minecraft.setScreen(category.screen().apply(minecraft, YACLScreen.this)); - } - - @Override - public @Nullable Tooltip getTooltip() { - return this.tooltip; - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/YACLTooltipPositioner.java b/common/src/main/java/dev/isxander/yacl3/gui/YACLTooltipPositioner.java deleted file mode 100644 index bb87170..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/YACLTooltipPositioner.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.isxander.yacl3.gui; - -import net.minecraft.client.gui.navigation.ScreenRectangle; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner; -import net.minecraft.util.Mth; -import org.joml.Vector2i; -import org.joml.Vector2ic; - -import java.util.function.Supplier; - -public class YACLTooltipPositioner implements ClientTooltipPositioner { - private final Supplier<ScreenRectangle> buttonDimensions; - - public YACLTooltipPositioner(net.minecraft.client.gui.components.AbstractWidget widget) { - this.buttonDimensions = widget::getRectangle; - } - - public YACLTooltipPositioner(dev.isxander.yacl3.gui.AbstractWidget widget) { - this.buttonDimensions = () -> { - var dim = widget.getDimension(); - return new ScreenRectangle(dim.x(), dim.y(), dim.width(), dim.height()); - }; - } - - public YACLTooltipPositioner(Supplier<ScreenRectangle> buttonDimensions) { - this.buttonDimensions = buttonDimensions; - } - - @Override - public Vector2ic positionTooltip(int guiWidth, int guiHeight, int x, int y, int width, int height) { - ScreenRectangle buttonDimensions = this.buttonDimensions.get(); - - int centerX = buttonDimensions.left() + buttonDimensions.width() / 2; - int aboveY = buttonDimensions.top() - height - 4; - int belowY = buttonDimensions.top() + buttonDimensions.height() + 4; - - int maxBelow = guiHeight - (belowY + height); - int minAbove = aboveY - height; - - int yResult = aboveY; - if (minAbove < 8) - yResult = maxBelow > minAbove ? belowY : aboveY; - - int xResult = Mth.clamp(centerX - width / 2, -4, guiWidth - width - 4); - - return new Vector2i(xResult, yResult); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/ActionController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/ActionController.java deleted file mode 100644 index 77938f6..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/ActionController.java +++ /dev/null @@ -1,120 +0,0 @@ -package dev.isxander.yacl3.gui.controllers; - -import com.mojang.blaze3d.platform.InputConstants; -import dev.isxander.yacl3.api.ButtonOption; -import dev.isxander.yacl3.api.Controller; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import net.minecraft.network.chat.Component; - -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<BiConsumer<YACLScreen, ButtonOption>> { - public static final Component DEFAULT_TEXT = Component.translatable("yacl.control.action.execute"); - - private final ButtonOption option; - private final Component 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, Component text) { - this.option = option; - this.text = text; - - } - - /** - * {@inheritDoc} - */ - @Override - public ButtonOption option() { - return option; - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return text; - } - - /** - * {@inheritDoc} - */ - @Override - public AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new ActionControllerElement(this, screen, widgetDimension); - } - - public static class ActionControllerElement extends ControllerWidget<ActionController> { - private final String buttonString; - - public ActionControllerElement(ActionController control, YACLScreen screen, Dimension<Integer> 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 == InputConstants.KEY_RETURN || keyCode == InputConstants.KEY_SPACE || keyCode == InputConstants.KEY_NUMPADENTER) { - 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/common/src/main/java/dev/isxander/yacl3/gui/controllers/BooleanController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/BooleanController.java deleted file mode 100644 index cbd6ba5..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/BooleanController.java +++ /dev/null @@ -1,164 +0,0 @@ -package dev.isxander.yacl3.gui.controllers; - -import com.mojang.blaze3d.platform.InputConstants; -import dev.isxander.yacl3.api.Controller; -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.ApiStatus; - -import java.util.function.Function; - -/** - * This controller renders a simple formatted {@link Component} - */ -public class BooleanController implements Controller<Boolean> { - - public static final Function<Boolean, Component> ON_OFF_FORMATTER = (state) -> - state - ? CommonComponents.OPTION_ON - : CommonComponents.OPTION_OFF; - - public static final Function<Boolean, Component> TRUE_FALSE_FORMATTER = (state) -> - state - ? Component.translatable("yacl.control.boolean.true") - : Component.translatable("yacl.control.boolean.false"); - - public static final Function<Boolean, Component> YES_NO_FORMATTER = (state) -> - state - ? CommonComponents.GUI_YES - : CommonComponents.GUI_NO; - - private final Option<Boolean> option; - private final ValueFormatter<Boolean> 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<Boolean> 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<Boolean> option, boolean coloured) { - this(option, ON_OFF_FORMATTER, coloured); - } - - /** - * Constructs a tickbox controller - * - * @param option bound option - * @param valueFormatter format value into any {@link Component} - * @param coloured value format is green or red depending on the state - */ - public BooleanController(Option<Boolean> option, Function<Boolean, Component> valueFormatter, boolean coloured) { - this.option = option; - this.valueFormatter = valueFormatter::apply; - this.coloured = coloured; - } - - @ApiStatus.Internal - public static BooleanController createInternal(Option<Boolean> option, ValueFormatter<Boolean> formatter, boolean coloured) { - return new BooleanController(option, formatter::format, coloured); - } - - /** - * {@inheritDoc} - */ - @Override - public Option<Boolean> option() { - return option; - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return valueFormatter.format(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<Integer> widgetDimension) { - return new BooleanControllerElement(this, screen, widgetDimension); - } - - public static class BooleanControllerElement extends ControllerWidget<BooleanController> { - public BooleanControllerElement(BooleanController control, YACLScreen screen, Dimension<Integer> dim) { - super(control, screen, dim); - } - - @Override - protected void drawHoveredControl(GuiGraphics graphics, 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 Component getValueText() { - if (control.coloured()) { - return super.getValueText().copy().withStyle(control.option().pendingValue() ? ChatFormatting.GREEN : ChatFormatting.RED); - } - - return super.getValueText(); - } - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if (!isFocused()) { - return false; - } - - if (keyCode == InputConstants.KEY_RETURN || keyCode == InputConstants.KEY_SPACE || keyCode == InputConstants.KEY_NUMPADENTER) { - toggleSetting(); - return true; - } - - return false; - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/ColorController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/ColorController.java deleted file mode 100644 index 56e6d30..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/ColorController.java +++ /dev/null @@ -1,220 +0,0 @@ -package dev.isxander.yacl3.gui.controllers; - -import com.google.common.collect.ImmutableList; -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.api.utils.MutableDimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.controllers.string.IStringController; -import dev.isxander.yacl3.gui.controllers.string.StringControllerElement; -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; - -import java.awt.*; -import java.util.List; - -/** - * A color controller that uses a hex color field as input. - */ -public class ColorController implements IStringController<Color> { - private final Option<Color> option; - private final boolean allowAlpha; - - /** - * Constructs a color controller with {@link ColorController#allowAlpha()} defaulting to false - * - * @param option bound option - */ - public ColorController(Option<Color> 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<Color> option, boolean allowAlpha) { - this.option = option; - this.allowAlpha = allowAlpha; - } - - /** - * {@inheritDoc} - */ - @Override - public Option<Color> option() { - return option; - } - - public boolean allowAlpha() { - return allowAlpha; - } - - @Override - public String getString() { - return formatValue().getString(); - } - - @Override - public Component formatValue() { - MutableComponent text = Component.literal("#"); - text.append(Component.literal(toHex(option().pendingValue().getRed())).withStyle(ChatFormatting.RED)); - text.append(Component.literal(toHex(option().pendingValue().getGreen())).withStyle(ChatFormatting.GREEN)); - text.append(Component.literal(toHex(option().pendingValue().getBlue())).withStyle(ChatFormatting.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<Integer> widgetDimension) { - return new ColorControllerElement(this, screen, widgetDimension); - } - - public static class ColorControllerElement extends StringControllerElement { - private final ColorController colorController; - - protected MutableDimension<Integer> colorPreviewDim; - - private final List<Character> allowedChars; - - public ColorControllerElement(ColorController control, YACLScreen screen, Dimension<Integer> dim) { - super(control, screen, dim, true); - this.colorController = control; - this.allowedChars = ImmutableList.of('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); - } - - @Override - protected void drawValueText(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - if (isHovered()) { - colorPreviewDim.move(-inputFieldBounds.width() - 5, 0); - super.drawValueText(graphics, mouseX, mouseY, delta); - } - - graphics.fill(colorPreviewDim.x(), colorPreviewDim.y(), colorPreviewDim.xLimit(), colorPreviewDim.yLimit(), colorController.option().pendingValue().getRGB()); - drawOutline(graphics, colorPreviewDim.x(), colorPreviewDim.y(), colorPreviewDim.xLimit(), colorPreviewDim.yLimit(), 1, 0xFF000000); - } - - @Override - public void write(String string) { - if (string.startsWith("0x")) string = string.substring(2); - for (char chr : string.toCharArray()) { - if (!allowedChars.contains(Character.toLowerCase(chr))) { - return; - } - } - - if (caretPos == 0) - return; - - String trimmed = string.substring(0, Math.min(inputField.length() - caretPos, string.length())); - - if (modifyInput(builder -> builder.replace(caretPos, caretPos + trimmed.length(), trimmed))) { - caretPos += trimmed.length(); - setSelectionLength(); - updateControl(); - } - } - - @Override - protected void doBackspace() { - if (caretPos > 1) { - if (modifyInput(builder -> builder.setCharAt(caretPos - 1, '0'))) { - caretPos--; - updateControl(); - } - } - } - - @Override - protected void doDelete() { - if (caretPos >= 1) { - if (modifyInput(builder -> builder.setCharAt(caretPos, '0'))) { - updateControl(); - } - } - } - - @Override - protected boolean doCut() { - return false; - } - - @Override - protected boolean doCopy() { - return false; - } - - @Override - protected boolean doSelectAll() { - return false; - } - - protected void setSelectionLength() { - selectionLength = caretPos < inputField.length() && caretPos > 0 ? 1 : 0; - } - - @Override - protected int getDefaultCaretPos() { - return colorController.allowAlpha() ? 3 : 1; - } - - @Override - public void setDimension(Dimension<Integer> dim) { - super.setDimension(dim); - - int previewSize = (dim.height() - getYPadding() * 2) / 2; - colorPreviewDim = Dimension.ofInt(dim.xLimit() - getXPadding() - previewSize, dim.centerY() - previewSize / 2, previewSize, previewSize); - } - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - int prevSelectionLength = selectionLength; - selectionLength = 0; - if (super.keyPressed(keyCode, scanCode, modifiers)) { - caretPos = Math.max(1, caretPos); - setSelectionLength(); - return true; - } else selectionLength = prevSelectionLength; - return false; - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (super.mouseClicked(mouseX, mouseY, button)) { - caretPos = Math.max(1, caretPos); - setSelectionLength(); - return true; - } - return false; - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/ControllerWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/ControllerWidget.java deleted file mode 100644 index 19fe2f6..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/ControllerWidget.java +++ /dev/null @@ -1,148 +0,0 @@ -package dev.isxander.yacl3.gui.controllers; - -import dev.isxander.yacl3.api.Controller; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.utils.GuiUtils; -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.ComponentPath; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.client.gui.narration.NarratedElementType; -import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.gui.navigation.FocusNavigationEvent; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.Nullable; - -public abstract class ControllerWidget<T extends Controller<?>> extends AbstractWidget { - protected final T control; - protected MultiLineLabel wrappedTooltip; - protected final YACLScreen screen; - - protected boolean focused = false; - protected boolean hovered = false; - - protected final Component modifiedOptionName; - protected final String optionNameString; - - public ControllerWidget(T control, YACLScreen screen, Dimension<Integer> dim) { - super(dim); - this.control = control; - this.screen = screen; - control.option().addListener((opt, pending) -> updateTooltip()); - updateTooltip(); - this.modifiedOptionName = control.option().name().copy().withStyle(ChatFormatting.ITALIC); - this.optionNameString = control.option().name().getString().toLowerCase(); - } - - @Override - public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - hovered = isMouseOver(mouseX, mouseY); - - Component name = control.option().changed() ? modifiedOptionName : control.option().name(); - Component shortenedName = Component.literal(GuiUtils.shortenString(name.getString(), textRenderer, getDimension().width() - getControlWidth() - getXPadding() - 7, "...")).setStyle(name.getStyle()); - - drawButtonRect(graphics, getDimension().x(), getDimension().y(), getDimension().xLimit(), getDimension().yLimit(), hovered || focused, isAvailable()); - graphics.drawString(textRenderer, shortenedName, getDimension().x() + getXPadding(), getTextY(), getValueColor(), true); - - - drawValueText(graphics, mouseX, mouseY, delta); - if (isHovered()) { - drawHoveredControl(graphics, mouseX, mouseY, delta); - } - } - - protected void drawHoveredControl(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - - } - - protected void drawValueText(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - Component valueText = getValueText(); - graphics.drawString(textRenderer, valueText, getDimension().xLimit() - textRenderer.width(valueText) - getXPadding(), getTextY(), getValueColor(), true); - } - - private void updateTooltip() { - this.wrappedTooltip = MultiLineLabel.create(textRenderer, control.option().tooltip(), screen.width / 3 * 2 - 10); - } - - protected int getControlWidth() { - return isHovered() ? getHoveredControlWidth() : getUnhoveredControlWidth(); - } - - public boolean isHovered() { - return isAvailable() && (hovered || focused); - } - - protected abstract int getHoveredControlWidth(); - - protected int getUnhoveredControlWidth() { - return textRenderer.width(getValueText()); - } - - protected int getXPadding() { - return 5; - } - - protected int getYPadding() { - return 2; - } - - protected Component getValueText() { - return control.formatValue(); - } - - protected boolean isAvailable() { - return control.option().available(); - } - - protected int getValueColor() { - return isAvailable() ? -1 : inactiveColor; - } - - @Override - public boolean canReset() { - return true; - } - - protected int getTextY() { - return (int)(getDimension().y() + getDimension().height() / 2f - textRenderer.lineHeight / 2f); - } - - @Nullable - @Override - public ComponentPath nextFocusPath(FocusNavigationEvent focusNavigationEvent) { - return !this.isFocused() ? ComponentPath.leaf(this) : null; - } - - @Override - public boolean isFocused() { - return focused; - } - - @Override - public void setFocused(boolean focused) { - this.focused = focused; - } - - @Override - public void unfocus() { - this.focused = false; - } - - @Override - public boolean matchesSearch(String query) { - return optionNameString.contains(query.toLowerCase()); - } - - @Override - public NarrationPriority narrationPriority() { - return focused ? NarrationPriority.FOCUSED : isHovered() ? NarrationPriority.HOVERED : NarrationPriority.NONE; - } - - @Override - public void updateNarration(NarrationElementOutput builder) { - builder.add(NarratedElementType.TITLE, control.option().name()); - builder.add(NarratedElementType.HINT, control.option().tooltip()); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/LabelController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/LabelController.java deleted file mode 100644 index fee6c19..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/LabelController.java +++ /dev/null @@ -1,193 +0,0 @@ -package dev.isxander.yacl3.gui.controllers; - -import dev.isxander.yacl3.api.Controller; -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import net.minecraft.client.gui.ComponentPath; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.client.gui.narration.NarratedElementType; -import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.gui.navigation.FocusNavigationEvent; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.HoverEvent; -import net.minecraft.network.chat.Style; -import net.minecraft.util.FormattedCharSequence; -import net.minecraft.world.item.ItemStack; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -/** - * Simply renders some text as a label. - */ -public class LabelController implements Controller<Component> { - private final Option<Component> option; - /** - * Constructs a label controller - * - * @param option bound option - */ - public LabelController(Option<Component> option) { - this.option = option; - } - - /** - * {@inheritDoc} - */ - @Override - public Option<Component> option() { - return option; - } - - @Override - public Component formatValue() { - return option().pendingValue(); - } - - @Override - public AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new LabelControllerElement(screen, widgetDimension); - } - - public class LabelControllerElement extends AbstractWidget { - private List<FormattedCharSequence> wrappedText; - protected MultiLineLabel wrappedTooltip; - protected boolean focused; - - protected final YACLScreen screen; - - public LabelControllerElement(YACLScreen screen, Dimension<Integer> dim) { - super(dim); - this.screen = screen; - option().addListener((opt, pending) -> updateTooltip()); - updateTooltip(); - updateText(); - } - - @Override - public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - updateText(); - - int y = getDimension().y(); - for (FormattedCharSequence text : wrappedText) { - graphics.drawString(textRenderer, text, getDimension().x() + getXPadding(), y + getYPadding(), option().available() ? -1 : 0xFFA0A0A0, true); - y += textRenderer.lineHeight; - } - - if (isFocused()) { - graphics.fill(getDimension().x() - 1, getDimension().y() - 1, getDimension().xLimit() + 1, getDimension().y(), -1); - graphics.fill(getDimension().x() - 1, getDimension().y() - 1, getDimension().x(), getDimension().yLimit() + 1, -1); - graphics.fill(getDimension().x() - 1, getDimension().yLimit(), getDimension().xLimit() + 1, getDimension().yLimit() + 1, -1); - graphics.fill(getDimension().xLimit(), getDimension().y() - 1, getDimension().xLimit() + 1, getDimension().yLimit() + 1, -1); - } - - graphics.pose().pushPose(); - graphics.pose().translate(0, 0, 100); - if (isMouseOver(mouseX, mouseY)) { - YACLScreen.renderMultilineTooltip(graphics, textRenderer, wrappedTooltip, getDimension().centerX(), getDimension().y() - 5, getDimension().yLimit() + 5, screen.width, screen.height); - - Style style = getStyle(mouseX, mouseY); - if (style != null && style.getHoverEvent() != null) { - HoverEvent hoverEvent = style.getHoverEvent(); - HoverEvent.ItemStackInfo itemStackContent = hoverEvent.getValue(HoverEvent.Action.SHOW_ITEM); - if (itemStackContent != null) { - ItemStack stack = itemStackContent.getItemStack(); - graphics.renderTooltip(textRenderer, Screen.getTooltipFromItem(client, stack), stack.getTooltipImage(), mouseX, mouseY); - } else { - HoverEvent.EntityTooltipInfo entityContent = hoverEvent.getValue(HoverEvent.Action.SHOW_ENTITY); - if (entityContent != null) { - if (this.client.options.advancedItemTooltips) { - graphics.renderComponentTooltip(textRenderer, entityContent.getTooltipLines(), mouseX, mouseY); - } - } else { - Component text = hoverEvent.getValue(HoverEvent.Action.SHOW_TEXT); - if (text != null) { - MultiLineLabel multilineText = MultiLineLabel.create(textRenderer, text, getDimension().width()); - YACLScreen.renderMultilineTooltip(graphics, textRenderer, multilineText, getDimension().centerX(), getDimension().y(), getDimension().yLimit(), screen.width, screen.height); - } - } - } - } - } - graphics.pose().popPose(); - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (!isMouseOver(mouseX, mouseY)) - return false; - - Style style = getStyle((int) mouseX, (int) mouseY); - return screen.handleComponentClicked(style); - } - - protected Style getStyle(int mouseX, int mouseY) { - if (!getDimension().isPointInside(mouseX, mouseY)) - return null; - - int x = mouseX - getDimension().x(); - int y = mouseY - getDimension().y() - getYPadding(); - int line = y / textRenderer.lineHeight; - - if (x < 0 || x > getDimension().xLimit()) return null; - if (y < 0 || y > getDimension().yLimit()) return null; - if (line < 0 || line >= wrappedText.size()) return null; - - return textRenderer.getSplitter().componentStyleAtWidth(wrappedText.get(line), x); - } - - private int getXPadding() { - return 4; - } - - private int getYPadding() { - return 3; - } - - private void updateText() { - wrappedText = textRenderer.split(formatValue(), getDimension().width() - getXPadding() * 2); - setDimension(getDimension().withHeight(wrappedText.size() * textRenderer.lineHeight + getYPadding() * 2)); - } - - private void updateTooltip() { - this.wrappedTooltip = MultiLineLabel.create(textRenderer, option().tooltip(), screen.width / 3 * 2 - 10); - } - - @Override - public boolean matchesSearch(String query) { - return formatValue().getString().toLowerCase().contains(query.toLowerCase()); - } - - @Nullable - @Override - public ComponentPath nextFocusPath(FocusNavigationEvent focusNavigationEvent) { - if (!option().available()) - return null; - return !this.isFocused() ? ComponentPath.leaf(this) : null; - } - - @Override - public boolean isFocused() { - return focused; - } - - @Override - public void setFocused(boolean focused) { - this.focused = focused; - } - - @Override - public void updateNarration(NarrationElementOutput builder) { - builder.add(NarratedElementType.TITLE, formatValue()); - } - - @Override - public NarrationPriority narrationPriority() { - return NarrationPriority.FOCUSED; - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/ListEntryWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/ListEntryWidget.java deleted file mode 100644 index 7e71cc7..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/ListEntryWidget.java +++ /dev/null @@ -1,128 +0,0 @@ -package dev.isxander.yacl3.gui.controllers; - -import com.google.common.collect.ImmutableList; -import dev.isxander.yacl3.api.ListOption; -import dev.isxander.yacl3.api.ListOptionEntry; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.TooltipButtonWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.events.ContainerEventHandler; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -public class ListEntryWidget extends AbstractWidget implements ContainerEventHandler { - private final TooltipButtonWidget removeButton, moveUpButton, moveDownButton; - private final AbstractWidget entryWidget; - - private final ListOption<?> listOption; - private final ListOptionEntry<?> listOptionEntry; - - private final String optionNameString; - - private GuiEventListener focused; - private boolean dragging; - - public ListEntryWidget(YACLScreen screen, ListOptionEntry<?> listOptionEntry, AbstractWidget entryWidget) { - super(entryWidget.getDimension().withHeight(Math.max(entryWidget.getDimension().height(), 20) - ((listOptionEntry.parentGroup().indexOf(listOptionEntry) == listOptionEntry.parentGroup().options().size() - 1) ? 0 : 2))); // -2 to remove the padding - this.listOptionEntry = listOptionEntry; - this.listOption = listOptionEntry.parentGroup(); - this.optionNameString = listOptionEntry.name().getString().toLowerCase(); - this.entryWidget = entryWidget; - - Dimension<Integer> dim = entryWidget.getDimension(); - entryWidget.setDimension(dim.clone().move(20 * 2, 0).expand(-20 * 3, 0)); - - removeButton = new TooltipButtonWidget(screen, dim.xLimit() - 20, dim.y(), 20, 20, Component.literal("\u274c"), Component.translatable("yacl.list.remove"), btn -> { - listOption.removeEntry(listOptionEntry); - updateButtonStates(); - }); - - moveUpButton = new TooltipButtonWidget(screen, dim.x(), dim.y(), 20, 20, Component.literal("\u2191"), Component.translatable("yacl.list.move_up"), btn -> { - int index = listOption.indexOf(listOptionEntry) - 1; - if (index >= 0) { - listOption.removeEntry(listOptionEntry); - listOption.insertEntry(index, listOptionEntry); - updateButtonStates(); - } - }); - - moveDownButton = new TooltipButtonWidget(screen, dim.x() + 20, dim.y(), 20, 20, Component.literal("\u2193"), Component.translatable("yacl.list.move_down"), btn -> { - int index = listOption.indexOf(listOptionEntry) + 1; - if (index < listOption.options().size()) { - listOption.removeEntry(listOptionEntry); - listOption.insertEntry(index, listOptionEntry); - updateButtonStates(); - } - }); - - updateButtonStates(); - } - - @Override - public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - updateButtonStates(); // update every render in case option becomes available/unavailable - - removeButton.setY(getDimension().y()); - moveUpButton.setY(getDimension().y()); - moveDownButton.setY(getDimension().y()); - entryWidget.setDimension(entryWidget.getDimension().withY(getDimension().y())); - - removeButton.render(graphics, mouseX, mouseY, delta); - moveUpButton.render(graphics, mouseX, mouseY, delta); - moveDownButton.render(graphics, mouseX, mouseY, delta); - entryWidget.render(graphics, mouseX, mouseY, delta); - } - - protected void updateButtonStates() { - removeButton.active = listOption.available() && listOption.numberOfEntries() > listOption.minimumNumberOfEntries(); - moveUpButton.active = listOption.indexOf(listOptionEntry) > 0 && listOption.available(); - moveDownButton.active = listOption.indexOf(listOptionEntry) < listOption.options().size() - 1 && listOption.available(); - } - - @Override - public void unfocus() { - entryWidget.unfocus(); - } - - @Override - public void updateNarration(NarrationElementOutput builder) { - entryWidget.updateNarration(builder); - } - - @Override - public boolean matchesSearch(String query) { - return optionNameString.contains(query.toLowerCase()); - } - - @Override - public List<? extends GuiEventListener> children() { - return ImmutableList.of(moveUpButton, moveDownButton, entryWidget, removeButton); - } - - @Override - public boolean isDragging() { - return dragging; - } - - @Override - public void setDragging(boolean dragging) { - this.dragging = dragging; - } - - @Nullable - @Override - public GuiEventListener getFocused() { - return focused; - } - - @Override - public void setFocused(@Nullable GuiEventListener focused) { - this.focused = focused; - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/TickBoxController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/TickBoxController.java deleted file mode 100644 index de19c14..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/TickBoxController.java +++ /dev/null @@ -1,119 +0,0 @@ -package dev.isxander.yacl3.gui.controllers; - -import com.mojang.blaze3d.platform.InputConstants; -import dev.isxander.yacl3.api.Controller; -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.network.chat.Component; - -/** - * This controller renders a tickbox - */ -public class TickBoxController implements Controller<Boolean> { - private final Option<Boolean> option; - - /** - * Constructs a tickbox controller - * - * @param option bound option - */ - public TickBoxController(Option<Boolean> option) { - this.option = option; - } - - /** - * {@inheritDoc} - */ - @Override - public Option<Boolean> option() { - return option; - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return Component.empty(); - } - - /** - * {@inheritDoc} - */ - @Override - public AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new TickBoxControllerElement(this, screen, widgetDimension); - } - - public static class TickBoxControllerElement extends ControllerWidget<TickBoxController> { - public TickBoxControllerElement(TickBoxController control, YACLScreen screen, Dimension<Integer> dim) { - super(control, screen, dim); - } - - @Override - protected void drawHoveredControl(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - int outlineSize = 10; - int outlineX1 = getDimension().xLimit() - getXPadding() - outlineSize; - int outlineY1 = getDimension().centerY() - outlineSize / 2; - int outlineX2 = getDimension().xLimit() - getXPadding(); - int outlineY2 = getDimension().centerY() + outlineSize / 2; - - int color = getValueColor(); - int shadowColor = multiplyColor(color, 0.25f); - - drawOutline(graphics, outlineX1 + 1, outlineY1 + 1, outlineX2 + 1, outlineY2 + 1, 1, shadowColor); - drawOutline(graphics, outlineX1, outlineY1, outlineX2, outlineY2, 1, color); - if (control.option().pendingValue()) { - graphics.fill(outlineX1 + 3, outlineY1 + 3, outlineX2 - 1, outlineY2 - 1, shadowColor); - graphics.fill(outlineX1 + 2, outlineY1 + 2, outlineX2 - 2, outlineY2 - 2, color); - } - } - - @Override - protected void drawValueText(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - if (!isHovered()) - drawHoveredControl(graphics, mouseX, mouseY, 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 10; - } - - @Override - protected int getUnhoveredControlWidth() { - return 10; - } - - public void toggleSetting() { - control.option().requestSet(!control.option().pendingValue()); - playDownSound(); - } - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if (!focused) { - return false; - } - - if (keyCode == InputConstants.KEY_RETURN || keyCode == InputConstants.KEY_SPACE || keyCode == InputConstants.KEY_NUMPADENTER) { - toggleSetting(); - return true; - } - - return false; - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/CyclingControllerElement.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/CyclingControllerElement.java deleted file mode 100644 index 3d85afe..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/CyclingControllerElement.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.cycling; - -import com.mojang.blaze3d.platform.InputConstants; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.controllers.ControllerWidget; -import net.minecraft.client.gui.screens.Screen; - -public class CyclingControllerElement extends ControllerWidget<ICyclingController<?>> { - - public CyclingControllerElement(ICyclingController<?> control, YACLScreen screen, Dimension<Integer> dim) { - super(control, screen, dim); - } - - public void cycleValue(int increment) { - int targetIdx = control.getPendingValue() + increment; - if (targetIdx >= control.getCycleLength()) { - targetIdx -= control.getCycleLength(); - } else if (targetIdx < 0) { - targetIdx += control.getCycleLength(); - } - control.setPendingValue(targetIdx); - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (!isMouseOver(mouseX, mouseY) || (button != 0 && button != 1) || !isAvailable()) - return false; - - playDownSound(); - cycleValue(button == 1 || Screen.hasShiftDown() || Screen.hasControlDown() ? -1 : 1); - - return true; - } - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if (!focused) - return false; - - switch (keyCode) { - case InputConstants.KEY_LEFT -> - cycleValue(-1); - case InputConstants.KEY_RIGHT -> - cycleValue(1); - case InputConstants.KEY_RETURN, InputConstants.KEY_SPACE, InputConstants.KEY_NUMPADENTER -> - cycleValue(Screen.hasControlDown() || Screen.hasShiftDown() ? -1 : 1); - default -> { - return false; - } - } - - return true; - } - - @Override - protected int getHoveredControlWidth() { - return getUnhoveredControlWidth(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/CyclingListController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/CyclingListController.java deleted file mode 100644 index 3fce3cf..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/CyclingListController.java +++ /dev/null @@ -1,86 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.cycling; - -import com.google.common.collect.ImmutableList; -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.ApiStatus; - -import java.util.function.Function; - -/** - * A controller where once clicked, cycles through elements - * in the provided list. - */ -public class CyclingListController<T> implements ICyclingController<T> { - private final Option<T> option; - private final ValueFormatter<T> valueFormatter; - private final ImmutableList<T> values; - - /** - * Constructs a {@link CyclingListController}, with a default - * value formatter of {@link Object#toString()}. - * @param option option of which to bind the controller to - * @param values the values to cycle through - */ - public CyclingListController(Option<T> option, Iterable<? extends T> values) { - this(option, values, value -> Component.literal(value.toString())); - } - - /** - * Constructs a {@link CyclingListController} - * @param option option of which to bind the controller to - * @param values the values to cycle through - * @param valueFormatter function of how to convert each value to a string to display - */ - public CyclingListController(Option<T> option, Iterable<? extends T> values, Function<T, Component> valueFormatter) { - this.option = option; - this.valueFormatter = valueFormatter::apply; - this.values = ImmutableList.copyOf(values); - } - - @ApiStatus.Internal - public static <T> CyclingListController<T> createInternal(Option<T> option, Iterable<? extends T> values, ValueFormatter<T> formatter) { - return new CyclingListController<>(option, values, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public Option<T> option() { - return option; - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return valueFormatter.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(int ordinal) { - option().requestSet(values.get(ordinal)); - } - - /** - * {@inheritDoc} - */ - @Override - public int getPendingValue() { - return values.indexOf(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public int getCycleLength() { - return values.size(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/EnumController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/EnumController.java deleted file mode 100644 index 5a6a912..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/EnumController.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.cycling; - -import dev.isxander.yacl3.api.NameableEnum; -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import net.minecraft.network.chat.Component; -import net.minecraft.util.OptionEnum; - -import java.util.Arrays; -import java.util.function.Function; - -/** - * Simple controller type that displays the enum on the right. - * <p> - * Cycles forward with left click, cycles backward with right click or when shift is held - * - * @param <T> enum type - */ -public class EnumController<T extends Enum<T>> extends CyclingListController<T> { - public static <T extends Enum<T>> Function<T, Component> getDefaultFormatter() { - return value -> { - if (value instanceof NameableEnum nameableEnum) - return nameableEnum.getDisplayName(); - if (value instanceof OptionEnum translatableOption) - return translatableOption.getCaption(); - return Component.literal(value.toString()); - }; - } - - public EnumController(Option<T> option, Class<T> enumClass) { - this(option, getDefaultFormatter(), enumClass.getEnumConstants()); - } - - /** - * Constructs a cycling enum controller. - * - * @param option bound option - * @param valueFormatter format the enum into any {@link Component} - * @param availableValues all enum constants that can be cycled through - */ - public EnumController(Option<T> option, Function<T, Component> valueFormatter, T[] availableValues) { - super(option, Arrays.asList(availableValues), valueFormatter); - } - - public static <T extends Enum<T>> EnumController<T> createInternal(Option<T> option, ValueFormatter<T> formatter, T[] values) { - return new EnumController<>(option, formatter::format, values); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/ICyclingController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/ICyclingController.java deleted file mode 100644 index cfddefa..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/cycling/ICyclingController.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.cycling; - -import dev.isxander.yacl3.api.Controller; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; - -/** - * This interface simply generifies setting and getting of - * the pending value, using an ordinal so elements can cycle through - * without knowing the content. - */ -public interface ICyclingController<T> extends Controller<T> { - /** - * Sets the pending value to whatever corresponds to the ordinal - * @param ordinal index of element to set - */ - void setPendingValue(int ordinal); - - /** - * Gets the pending ordinal that corresponds to the actual value - * @return ordinal - */ - int getPendingValue(); - - /** - * Allows the element when it should wrap-around back to zeroth ordinal - */ - int getCycleLength(); - - /** - * {@inheritDoc} - */ - @Override - default AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new CyclingControllerElement(this, screen, widgetDimension); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/AbstractDropdownController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/AbstractDropdownController.java deleted file mode 100644 index b913d15..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/AbstractDropdownController.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.dropdown; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.gui.controllers.string.IStringController; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public abstract class AbstractDropdownController<T> implements IStringController<T> { - protected final Option<T> option; - private final List<String> allowedValues; - public final boolean allowEmptyValue; - public final boolean allowAnyValue; - - /** - * Constructs a dropdown controller - * - * @param option bound option - * @param allowedValues possible values - */ - protected AbstractDropdownController(Option<T> option, List<String> allowedValues, boolean allowEmptyValue, boolean allowAnyValue) { - this.option = option; - this.allowedValues = allowedValues; - this.allowEmptyValue = allowEmptyValue; - this.allowAnyValue = allowAnyValue; - } - - protected AbstractDropdownController(Option<T> option, List<String> allowedValues) { - this(option, allowedValues, false, false); - } - - protected AbstractDropdownController(Option<T> option) { - this(option, Collections.emptyList()); - } - - /** - * {@inheritDoc} - */ - @Override - public Option<T> option() { - return option; - } - - public List<String> getAllowedValues() { - return getAllowedValues(""); - } - public List<String> getAllowedValues(String inputField) { - List<String> values = new ArrayList<>(allowedValues); - if (allowEmptyValue && !values.contains("")) values.add(""); - if (allowAnyValue && !inputField.isBlank() && !allowedValues.contains(inputField)) { - values.add(inputField); - } - String currentValue = getString(); - if (allowAnyValue && !allowedValues.contains(currentValue)) { - values.add(currentValue); - } - return values; - } - - public boolean isValueValid(String value) { - if (value.isBlank()) return allowEmptyValue; - return allowAnyValue || getAllowedValues().contains(value); - } - - protected String getValidValue(String value) { - return getValidValue(value, 0); - } - protected String getValidValue(String value, int offset) { - if (offset == -1) return getString(); - - String valueLowerCase = value.toLowerCase(); - return getAllowedValues(value).stream() - .filter(val -> val.toLowerCase().contains(valueLowerCase)) - .sorted((s1, s2) -> { - String s1LowerCase = s1.toLowerCase(); - String s2LowerCase = s2.toLowerCase(); - if (s1LowerCase.startsWith(valueLowerCase) && !s2LowerCase.startsWith(valueLowerCase)) return -1; - if (!s1LowerCase.startsWith(valueLowerCase) && s2LowerCase.startsWith(valueLowerCase)) return 1; - return s1.compareTo(s2); - }) - .skip(offset) - .findFirst() - .orElseGet(this::getString); - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/AbstractDropdownControllerElement.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/AbstractDropdownControllerElement.java deleted file mode 100644 index 31d4d51..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/AbstractDropdownControllerElement.java +++ /dev/null @@ -1,238 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.dropdown; - -import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.vertex.PoseStack; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.controllers.string.StringControllerElement; -import dev.isxander.yacl3.gui.utils.GuiUtils; -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -import java.awt.Color; -import java.util.List; -import java.util.function.Consumer; - -public abstract class AbstractDropdownControllerElement<T, U> extends StringControllerElement { - public static final int MAX_SHOWN_NUMBER_OF_ITEMS = 7; - - private final AbstractDropdownController<T> dropdownController; - protected boolean dropdownVisible = false; - // Stores the current selection position. The item at this position in the dropdown list will be chosen as the - // accepted value when the element is closed. - protected int selectedIndex = 0; - // Stores a cached list of matching values - protected List<U> matchingValues = null; - - public AbstractDropdownControllerElement(AbstractDropdownController<T> control, YACLScreen screen, Dimension<Integer> dim) { - super(control, screen, dim, false); - this.dropdownController = control; - this.dropdownController.option.addListener((opt, val) -> this.matchingValues = this.computeMatchingValues()); - } - - public void showDropdown() { - dropdownVisible = true; - selectedIndex = 0; - } - - public void closeDropdown() { - dropdownVisible = false; - ensureValidValue(); - } - - public void ensureValidValue() { - inputField = dropdownController.getValidValue(inputField, selectedIndex); - this.matchingValues = this.computeMatchingValues(); - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (super.mouseClicked(mouseX, mouseY, button)) { - if (!dropdownVisible) { - showDropdown(); - doSelectAll(); - } - return true; - } - return false; - } - - @Override - public void setFocused(boolean focused) { - if (focused) { - doSelectAll(); - super.setFocused(true); - } else unfocus(); - } - - @Override - public void unfocus() { - closeDropdown(); - super.unfocus(); - } - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if (!inputFieldFocused) - return false; - if (dropdownVisible) { - switch (keyCode) { - case InputConstants.KEY_DOWN -> { - selectNextEntry(); - return true; - } - case InputConstants.KEY_UP -> { - selectPreviousEntry(); - return true; - } - case InputConstants.KEY_TAB -> { - if (Screen.hasShiftDown()) { - selectPreviousEntry(); - } else { - selectNextEntry(); - } - return true; - } - } - } else { - if (keyCode == InputConstants.KEY_RETURN || keyCode == InputConstants.KEY_NUMPADENTER) { - showDropdown(); - return true; - } - } - return super.keyPressed(keyCode, scanCode, modifiers); - } - - @Override - public boolean charTyped(char chr, int modifiers) { - if (!dropdownVisible) { - showDropdown(); - } - return super.charTyped(chr, modifiers); - } - - @Override - protected int getValueColor() { - if (inputFieldFocused) { - if (!dropdownController.isValueValid(inputField)) { - return 0xFFF06080; - } - } - return super.getValueColor(); - } - - public void selectNextEntry() { - if (selectedIndex == getDropdownLength() - 1) { - selectedIndex = 0; - } else { - selectedIndex++; - } - } - - public void selectPreviousEntry() { - if (selectedIndex == 0) { - selectedIndex = getDropdownLength() - 1; - } else { - selectedIndex--; - } - } - - public int getDropdownLength() { - return matchingValues.size(); - } - - @Override - public boolean modifyInput(Consumer<StringBuilder> builder) { - boolean success = super.modifyInput(builder); - if (success) { - this.matchingValues = this.computeMatchingValues(); - } - return success; - } - - public abstract List<U> computeMatchingValues(); - - public boolean matchingValue(String value) { - return value.toLowerCase().contains(inputField.toLowerCase()); - } - - @Override - public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - if (matchingValues == null) matchingValues = computeMatchingValues(); - - super.render(graphics, mouseX, mouseY, delta); - - if (inputFieldFocused && dropdownVisible) { - PoseStack matrices = graphics.pose(); - matrices.pushPose(); - matrices.translate(0, 0, 200); - renderDropdown(graphics); - matrices.popPose(); - } - } - - public void renderDropdown(GuiGraphics graphics) { - if (matchingValues.isEmpty()) return; - // Limit the visible options to allow scrolling through the suggestion list - int begin = Math.max(0, selectedIndex - MAX_SHOWN_NUMBER_OF_ITEMS / 2); - int end = begin + MAX_SHOWN_NUMBER_OF_ITEMS; - if (end >= matchingValues.size()) { - end = matchingValues.size(); - begin = Math.max(0, end - MAX_SHOWN_NUMBER_OF_ITEMS); - } - - renderDropdownBackground(graphics, end - begin); - if (!matchingValues.isEmpty()) { - // Highlight the currently selected element - graphics.setColor(0.0f, 0.0f, 0.0f, 0.5f); - int x = getDimension().x(); - int y = getDimension().yLimit() + 2 + getDimension().height() * (selectedIndex - begin); - graphics.fill(x, y, x + getDimension().width(), y + getDimension().height(), -1); - graphics.setColor(1.0f, 1.0f, 1.0f, 1.0f); - graphics.renderOutline(x, y, getDimension().width(), getDimension().height(), -1); - - } - - int n = 1; - for (int i = begin; i < end; ++i) { - renderDropdownEntry(graphics, matchingValues.get(i), n); - ++n; - } - } - - protected int getDropdownEntryPadding() { - return 0; - } - - protected void renderDropdownEntry(GuiGraphics graphics, U value, int n) { - String entry = getString(value); - int color = -1; - Component text; - if (entry.isBlank()) { - text = Component.translatable("yacl.control.text.blank").withStyle(ChatFormatting.GRAY); - } else { - text = shortenString(entry); - } - graphics.drawString(textRenderer, text, getDimension().xLimit() - textRenderer.width(text) - getDecorationPadding() - getDropdownEntryPadding(), getTextY() + n * getDimension().height() + 2, color, true); - } - - public abstract String getString(U object); - - public Component shortenString(String value) { - return Component.literal(GuiUtils.shortenString(value, textRenderer, getDimension().width() - 20, "...")); - } - - public void renderDropdownBackground(GuiGraphics graphics, int numberOfItems) { - graphics.setColor(0.25f, 0.25f, 0.25f, 1.0f); - graphics.blit(Screen.MENU_BACKGROUND, getDimension().x(), getDimension().yLimit() + 2, 0, 0.0f, 0.0f, getDimension().width(), getDimension().height() * numberOfItems + 2, 32, 32); - graphics.setColor(1.0f, 1.0f, 1.0f, 1.0f); - graphics.renderOutline(getDimension().x(), getDimension().yLimit() + 2, getDimension().width(), getDimension().height() * numberOfItems, -1); - } - - protected int getDecorationPadding() { - return super.getXPadding(); - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/DropdownStringController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/DropdownStringController.java deleted file mode 100644 index fafc759..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/DropdownStringController.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.dropdown; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; - -import java.util.List; - -public class DropdownStringController extends AbstractDropdownController<String> { - - public DropdownStringController(Option<String> option, List<String> allowedValues, boolean allowEmptyValue, boolean allowAnyValue) { - super(option, allowedValues, allowEmptyValue, allowAnyValue); - } - - @Override - public String getString() { - return option().pendingValue(); - } - - @Override - public void setFromString(String value) { - option().requestSet(getValidValue(value)); - } - - /** - * {@inheritDoc} - */ - @Override - public AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new DropdownStringControllerElement(this, screen, widgetDimension); - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/DropdownStringControllerElement.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/DropdownStringControllerElement.java deleted file mode 100644 index 615aada..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/DropdownStringControllerElement.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.dropdown; - -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.YACLScreen; - -import java.util.List; - -public class DropdownStringControllerElement extends AbstractDropdownControllerElement<String, String> { - private final DropdownStringController controller; - - public DropdownStringControllerElement(DropdownStringController control, YACLScreen screen, Dimension<Integer> dim) { - super(control, screen, dim); - this.controller = control; - } - - @Override - public List<String> computeMatchingValues() { - return controller.getAllowedValues(inputField).stream() - .filter(this::matchingValue) - .sorted((s1, s2) -> { - if (s1.startsWith(inputField) && !s2.startsWith(inputField)) return -1; - if (!s1.startsWith(inputField) && s2.startsWith(inputField)) return 1; - return s1.compareTo(s2); - }) - .toList(); - } - - public String getString(String object) { - return object; - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/EnumDropdownController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/EnumDropdownController.java deleted file mode 100644 index 8e6e0e6..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/EnumDropdownController.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.dropdown; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; - -import java.util.Arrays; -import java.util.stream.Stream; - -public class EnumDropdownController<E extends Enum<E>> extends AbstractDropdownController<E> { - /** - * The function used to convert enum constants to strings used for display, suggestion, and validation. Defaults to {@link Enum#toString}. - */ - protected final ValueFormatter<E> formatter; - - public EnumDropdownController(Option<E> option, ValueFormatter<E> formatter) { - super(option, Arrays.stream(option.pendingValue().getDeclaringClass().getEnumConstants()).map(formatter::format).map(Component::getString).toList()); - this.formatter = formatter; - } - - @Override - public String getString() { - return formatter.format(option().pendingValue()).getString(); - } - - @Override - public void setFromString(String value) { - option().requestSet(getEnumFromString(value)); - } - - /** - * Searches through enum constants for one whose {@link #formatter} result equals {@code value} - * - * @return The enum constant associated with the {@code value} or the pending value if none are found - * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy - */ - private E getEnumFromString(String value) { - value = value.toLowerCase(); - for (E constant : option().pendingValue().getDeclaringClass().getEnumConstants()) { - if (formatter.format(constant).getString().toLowerCase().equals(value)) return constant; - } - - return option().pendingValue(); - } - - @Override - public boolean isValueValid(String value) { - value = value.toLowerCase(); - for (String constant : getAllowedValues()) { - if (constant.equals(value)) return true; - } - - return false; - } - - @Override - protected String getValidValue(String value, int offset) { - return getValidEnumConstants(value) - .skip(offset) - .findFirst() - .orElseGet(this::getString); - } - - /** - * Filters and sorts through enum constants for those whose {@link #formatter} result equals {@code value} - * - * @return a sorted stream containing enum constants associated with the {@code value} - * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy - */ - @NotNull - protected Stream<String> getValidEnumConstants(String value) { - String valueLowerCase = value.toLowerCase(); - return getAllowedValues().stream() - .filter(constant -> constant.toLowerCase().contains(valueLowerCase)) - .sorted((s1, s2) -> { - String s1LowerCase = s1.toLowerCase(); - String s2LowerCase = s2.toLowerCase(); - if (s1LowerCase.startsWith(valueLowerCase) && !s2LowerCase.startsWith(valueLowerCase)) return -1; - if (!s1LowerCase.startsWith(valueLowerCase) && s2LowerCase.startsWith(valueLowerCase)) return 1; - return s1.compareTo(s2); - }); - } - - @Override - public AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new EnumDropdownControllerElement<>(this, screen, widgetDimension); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/EnumDropdownControllerElement.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/EnumDropdownControllerElement.java deleted file mode 100644 index 2df6f6b..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/EnumDropdownControllerElement.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.dropdown; - -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.YACLScreen; - -import java.util.List; - -public class EnumDropdownControllerElement<E extends Enum<E>> extends AbstractDropdownControllerElement<E, String> { - private final EnumDropdownController<E> controller; - - public EnumDropdownControllerElement(EnumDropdownController<E> control, YACLScreen screen, Dimension<Integer> dim) { - super(control, screen, dim); - this.controller = control; - } - - @Override - public List<String> computeMatchingValues() { - return controller.getValidEnumConstants(inputField).toList(); - } - - @Override - public String getString(String object) { - return object; - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/ItemController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/ItemController.java deleted file mode 100644 index ac903c7..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/ItemController.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.dropdown; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.utils.ItemRegistryHelper; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; - -/** - * Simple controller that simply runs the button action on press - * and renders a {@link} Text on the right. - */ -public class ItemController extends AbstractDropdownController<Item> { - - /** - * Constructs an item controller - * - * @param option bound option - */ - public ItemController(Option<Item> option) { - super(option); - } - - @Override - public String getString() { - return BuiltInRegistries.ITEM.getKey(option.pendingValue()).toString(); - } - - @Override - public void setFromString(String value) { - option.requestSet(ItemRegistryHelper.getItemFromName(value, option.pendingValue())); - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return Component.literal(getString()); - } - - - @Override - public boolean isValueValid(String value) { - return ItemRegistryHelper.isRegisteredItem(value); - } - - @Override - protected String getValidValue(String value, int offset) { - return ItemRegistryHelper.getMatchingItemIdentifiers(value) - .skip(offset) - .findFirst() - .map(ResourceLocation::toString) - .orElseGet(this::getString); - } - - /** - * {@inheritDoc} - */ - @Override - public AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new ItemControllerElement(this, screen, widgetDimension); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/ItemControllerElement.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/ItemControllerElement.java deleted file mode 100644 index 1617c41..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/dropdown/ItemControllerElement.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.dropdown; - -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.utils.ItemRegistryHelper; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -public class ItemControllerElement extends AbstractDropdownControllerElement<Item, ResourceLocation> { - private final ItemController itemController; - protected Item currentItem = null; - protected Map<ResourceLocation, Item> matchingItems = new HashMap<>(); - - - public ItemControllerElement(ItemController control, YACLScreen screen, Dimension<Integer> dim) { - super(control, screen, dim); - this.itemController = control; - } - - @Override - protected void drawValueText(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - var oldDimension = getDimension(); - setDimension(getDimension().withWidth(getDimension().width() - getDecorationPadding())); - super.drawValueText(graphics, mouseX, mouseY, delta); - setDimension(oldDimension); - if (currentItem != null) { - graphics.renderFakeItem(new ItemStack(currentItem), getDimension().xLimit() - getXPadding() - getDecorationPadding() + 2, getDimension().y() + 2); - } - } - - @Override - public List<ResourceLocation> computeMatchingValues() { - List<ResourceLocation> identifiers = ItemRegistryHelper.getMatchingItemIdentifiers(inputField).toList(); - currentItem = ItemRegistryHelper.getItemFromName(inputField, null); - for (ResourceLocation identifier : identifiers) { - matchingItems.put(identifier, BuiltInRegistries.ITEM.get(identifier)); - } - return identifiers; - } - - @Override - protected void renderDropdownEntry(GuiGraphics graphics, ResourceLocation identifier, int n) { - super.renderDropdownEntry(graphics, identifier, n); - graphics.renderFakeItem(new ItemStack(matchingItems.get(identifier)), getDimension().xLimit() - getDecorationPadding() - 2, getDimension().y() + n * getDimension().height() + 4); - } - - @Override - public String getString(ResourceLocation identifier) { - return identifier.toString(); - } - - @Override - protected int getDecorationPadding() { - return 16; - } - - @Override - protected int getDropdownEntryPadding() { - return 4; - } - - @Override - protected int getControlWidth() { - return super.getControlWidth() + getDecorationPadding(); - } - - @Override - protected Component getValueText() { - if (inputField.isEmpty() || itemController == null) - return super.getValueText(); - - if (inputFieldFocused) - return Component.literal(inputField); - - return itemController.option().pendingValue().getDescription(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/package-info.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/package-info.java deleted file mode 100644 index 1819a64..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * This package contains all {@link dev.isxander.yacl3.api.Controller} implementations - * - * <ul> - * <li>For numbers: {@link dev.isxander.yacl3.gui.controllers.slider}</li> - * <li>For booleans: {@link dev.isxander.yacl3.gui.controllers.TickBoxController}</li> - * <li>For lists/enums: {@link dev.isxander.yacl3.gui.controllers.cycling}</li> - * <li>For strings: {@link dev.isxander.yacl3.gui.controllers.string.StringController}</li> - * <li>For {@link dev.isxander.yacl3.api.ButtonOption}: {@link dev.isxander.yacl3.gui.controllers.ActionController}</li> - * </ul> - */ -package dev.isxander.yacl3.gui.controllers; diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/DoubleSliderController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/DoubleSliderController.java deleted file mode 100644 index 89308a8..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/DoubleSliderController.java +++ /dev/null @@ -1,119 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.slider; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import net.minecraft.network.chat.Component; -import org.apache.commons.lang3.Validate; - -import java.util.function.Function; - -/** - * {@link ISliderController} for doubles. - */ -public class DoubleSliderController implements ISliderController<Double> { - /** - * Formats doubles to two decimal places - */ - public static final Function<Double, Component> DEFAULT_FORMATTER = value -> Component.literal(String.format("%,.2f", value).replaceAll("[\u00a0\u202F]", " ")); - - private final Option<Double> option; - - private final double min, max, interval; - - private final ValueFormatter<Double> valueFormatter; - - /** - * Constructs a {@link ISliderController} for doubles - * using the default value formatter {@link DoubleSliderController#DEFAULT_FORMATTER}. - * - * @param option bound option - * @param min minimum slider value - * @param max maximum slider value - * @param interval step size (or increments) for the slider - */ - public DoubleSliderController(Option<Double> option, double min, double max, double interval) { - this(option, min, max, interval, DEFAULT_FORMATTER); - } - - /** - * Constructs a {@link ISliderController} for doubles. - * - * @param option bound option - * @param min minimum slider value - * @param max maximum slider value - * @param interval step size (or increments) for the slider - * @param valueFormatter format the value into any {@link Component} - */ - public DoubleSliderController(Option<Double> option, double min, double max, double interval, Function<Double, Component> valueFormatter) { - Validate.isTrue(max > min, "`max` cannot be smaller than `min`"); - Validate.isTrue(interval > 0, "`interval` must be more than 0"); - Validate.notNull(valueFormatter, "`valueFormatter` must not be null"); - - this.option = option; - this.min = min; - this.max = max; - this.interval = interval; - this.valueFormatter = valueFormatter::apply; - } - - public static DoubleSliderController createInternal(Option<Double> option, double min, double max, double interval, ValueFormatter<Double> formatter) { - return new DoubleSliderController(option, min, max, interval, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public Option<Double> option() { - return option; - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return valueFormatter.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public double min() { - return min; - } - - /** - * {@inheritDoc} - */ - @Override - public double max() { - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public double interval() { - return interval; - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(double value) { - option().requestSet(value); - } - - /** - * {@inheritDoc} - */ - @Override - public double pendingValue() { - return option().pendingValue(); - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/FloatSliderController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/FloatSliderController.java deleted file mode 100644 index 79246dd..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/FloatSliderController.java +++ /dev/null @@ -1,119 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.slider; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import net.minecraft.network.chat.Component; -import org.apache.commons.lang3.Validate; - -import java.util.function.Function; - -/** - * {@link ISliderController} for floats. - */ -public class FloatSliderController implements ISliderController<Float> { - /** - * Formats floats to one decimal place - */ - public static final Function<Float, Component> DEFAULT_FORMATTER = value -> Component.literal(String.format("%,.1f", value).replaceAll("[\u00a0\u202F]", " ")); - - private final Option<Float> option; - - private final float min, max, interval; - - private final ValueFormatter<Float> valueFormatter; - - /** - * Constructs a {@link ISliderController} for floats - * using the default value formatter {@link FloatSliderController#DEFAULT_FORMATTER}. - * - * @param option bound option - * @param min minimum slider value - * @param max maximum slider value - * @param interval step size (or increments) for the slider - */ - public FloatSliderController(Option<Float> option, float min, float max, float interval) { - this(option, min, max, interval, DEFAULT_FORMATTER); - } - - /** - * Constructs a {@link ISliderController} for floats. - * - * @param option bound option - * @param min minimum slider value - * @param max maximum slider value - * @param interval step size (or increments) for the slider - * @param valueFormatter format the value into any {@link Component} - */ - public FloatSliderController(Option<Float> option, float min, float max, float interval, Function<Float, Component> valueFormatter) { - Validate.isTrue(max > min, "`max` cannot be smaller than `min`"); - Validate.isTrue(interval > 0, "`interval` must be more than 0"); - Validate.notNull(valueFormatter, "`valueFormatter` must not be null"); - - this.option = option; - this.min = min; - this.max = max; - this.interval = interval; - this.valueFormatter = valueFormatter::apply; - } - - public static FloatSliderController createInternal(Option<Float> option, float min, float max, float interval, ValueFormatter<Float> formatter) { - return new FloatSliderController(option, min, max, interval, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public Option<Float> option() { - return option; - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return valueFormatter.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public double min() { - return min; - } - - /** - * {@inheritDoc} - */ - @Override - public double max() { - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public double interval() { - return interval; - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(double value) { - option().requestSet((float) value); - } - - /** - * {@inheritDoc} - */ - @Override - public double pendingValue() { - return option().pendingValue(); - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/ISliderController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/ISliderController.java deleted file mode 100644 index 4a3f36b..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/ISliderController.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.slider; - -import dev.isxander.yacl3.api.Controller; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; - -/** - * Simple custom slider implementation that shifts the current value across when shown. - * <p> - * For simplicity, {@link SliderControllerElement} works in doubles so each - * {@link ISliderController} must cast to double. This is to get around re-writing the element for every type. - */ -public interface ISliderController<T extends Number> extends Controller<T> { - /** - * Gets the minimum value for the slider - */ - double min(); - - /** - * Gets the maximum value for the slider - */ - double max(); - - /** - * Gets the interval (or step size) for the slider. - */ - double interval(); - - /** - * Gets the range of the slider. - */ - default double range() { - return max() - min(); - } - - /** - * Sets the {@link dev.isxander.yacl3.api.Option}'s pending value - */ - void setPendingValue(double value); - - /** - * Gets the {@link dev.isxander.yacl3.api.Option}'s pending value - */ - double pendingValue(); - - /** - * {@inheritDoc} - */ - @Override - default AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new SliderControllerElement(this, screen, widgetDimension, min(), max(), interval()); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/IntegerSliderController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/IntegerSliderController.java deleted file mode 100644 index bcb551d..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/IntegerSliderController.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.slider; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import net.minecraft.network.chat.Component; -import org.apache.commons.lang3.Validate; - -import java.util.function.Function; - -/** - * {@link ISliderController} for integers. - */ -public class IntegerSliderController implements ISliderController<Integer> { - public static final Function<Integer, Component> DEFAULT_FORMATTER = value -> Component.literal(String.format("%,d", value).replaceAll("[\u00a0\u202F]", " ")); - - private final Option<Integer> option; - - private final int min, max, interval; - - private final ValueFormatter<Integer> valueFormatter; - - /** - * Constructs a {@link ISliderController} for integers - * using the default value formatter {@link IntegerSliderController#DEFAULT_FORMATTER}. - * - * @param option bound option - * @param min minimum slider value - * @param max maximum slider value - * @param interval step size (or increments) for the slider - */ - public IntegerSliderController(Option<Integer> option, int min, int max, int interval) { - this(option, min, max, interval, DEFAULT_FORMATTER); - } - - /** - * Constructs a {@link ISliderController} for integers. - * - * @param option bound option - * @param min minimum slider value - * @param max maximum slider value - * @param interval step size (or increments) for the slider - * @param valueFormatter format the value into any {@link Component} - */ - public IntegerSliderController(Option<Integer> option, int min, int max, int interval, Function<Integer, Component> valueFormatter) { - Validate.isTrue(max > min, "`max` cannot be smaller than `min`"); - Validate.isTrue(interval > 0, "`interval` must be more than 0"); - Validate.notNull(valueFormatter, "`valueFormatter` must not be null"); - - this.option = option; - this.min = min; - this.max = max; - this.interval = interval; - this.valueFormatter = valueFormatter::apply; - } - - public static IntegerSliderController createInternal(Option<Integer> option, int min, int max, int interval, ValueFormatter<Integer> formatter) { - return new IntegerSliderController(option, min, max, interval, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public Option<Integer> option() { - return option; - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return valueFormatter.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public double min() { - return min; - } - - /** - * {@inheritDoc} - */ - @Override - public double max() { - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public double interval() { - return interval; - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(double value) { - option().requestSet((int) value); - } - - /** - * {@inheritDoc} - */ - @Override - public double pendingValue() { - return option().pendingValue(); - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/LongSliderController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/LongSliderController.java deleted file mode 100644 index 105bd46..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/LongSliderController.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.slider; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import net.minecraft.network.chat.Component; -import org.apache.commons.lang3.Validate; - -import java.util.function.Function; - -/** - * {@link ISliderController} for longs. - */ -public class LongSliderController implements ISliderController<Long> { - public static final Function<Long, Component> DEFAULT_FORMATTER = value -> Component.literal(String.format("%,d", value).replaceAll("[\u00a0\u202F]", " ")); - - private final Option<Long> option; - - private final long min, max, interval; - - private final ValueFormatter<Long> valueFormatter; - - /** - * Constructs a {@link ISliderController} for longs - * using the default value formatter {@link LongSliderController#DEFAULT_FORMATTER}. - * - * @param option bound option - * @param min minimum slider value - * @param max maximum slider value - * @param interval step size (or increments) for the slider - */ - public LongSliderController(Option<Long> option, long min, long max, long interval) { - this(option, min, max, interval, DEFAULT_FORMATTER); - } - - /** - * Constructs a {@link ISliderController} for longs. - * - * @param option bound option - * @param min minimum slider value - * @param max maximum slider value - * @param interval step size (or increments) for the slider - * @param valueFormatter format the value into any {@link Component} - */ - public LongSliderController(Option<Long> option, long min, long max, long interval, Function<Long, Component> valueFormatter) { - Validate.isTrue(max > min, "`max` cannot be smaller than `min`"); - Validate.isTrue(interval > 0, "`interval` must be more than 0"); - Validate.notNull(valueFormatter, "`valueFormatter` must not be null"); - - this.option = option; - this.min = min; - this.max = max; - this.interval = interval; - this.valueFormatter = valueFormatter::apply; - } - - public static LongSliderController createInternal(Option<Long> option, long min, long max, long interval, ValueFormatter<Long> formatter) { - return new LongSliderController(option, min, max, interval, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public Option<Long> option() { - return option; - } - - /** - * {@inheritDoc} - */ - @Override - public Component formatValue() { - return valueFormatter.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public double min() { - return min; - } - - /** - * {@inheritDoc} - */ - @Override - public double max() { - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public double interval() { - return interval; - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(double value) { - option().requestSet((long) value); - } - - /** - * {@inheritDoc} - */ - @Override - public double pendingValue() { - return option().pendingValue(); - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/SliderControllerElement.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/SliderControllerElement.java deleted file mode 100644 index 32d7561..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/SliderControllerElement.java +++ /dev/null @@ -1,157 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.slider; - -import com.mojang.blaze3d.platform.InputConstants; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.controllers.ControllerWidget; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.util.Mth; - -public class SliderControllerElement extends ControllerWidget<ISliderController<?>> { - private final double min, max, interval; - - private float interpolation; - - private Dimension<Integer> sliderBounds; - - private boolean mouseDown = false; - - public SliderControllerElement(ISliderController<?> option, YACLScreen screen, Dimension<Integer> dim, double min, double max, double interval) { - super(option, screen, dim); - this.min = min; - this.max = max; - this.interval = interval; - setDimension(dim); - } - - @Override - public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - super.render(graphics, mouseX, mouseY, delta); - - calculateInterpolation(); - } - - @Override - protected void drawHoveredControl(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - // track - graphics.fill(sliderBounds.x(), sliderBounds.centerY() - 1, sliderBounds.xLimit(), sliderBounds.centerY(), -1); - // track shadow - graphics.fill(sliderBounds.x() + 1, sliderBounds.centerY(), sliderBounds.xLimit() + 1, sliderBounds.centerY() + 1, 0xFF404040); - - // thumb shadow - graphics.fill(getThumbX() - getThumbWidth() / 2 + 1, sliderBounds.y() + 1, getThumbX() + getThumbWidth() / 2 + 1, sliderBounds.yLimit() + 1, 0xFF404040); - // thumb - graphics.fill(getThumbX() - getThumbWidth() / 2, sliderBounds.y(), getThumbX() + getThumbWidth() / 2, sliderBounds.yLimit(), -1); - } - - @Override - protected void drawValueText(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - graphics.pose().pushPose(); - if (isHovered()) - graphics.pose().translate(-(sliderBounds.width() + 6 + getThumbWidth() / 2f), 0, 0); - super.drawValueText(graphics, mouseX, mouseY, delta); - graphics.pose().popPose(); - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (!isAvailable() || button != 0 || !sliderBounds.isPointInside((int) mouseX, (int) mouseY)) - return false; - - mouseDown = true; - - setValueFromMouse(mouseX); - return true; - } - - @Override - public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { - if (!isAvailable() || button != 0 || !mouseDown) - return false; - - setValueFromMouse(mouseX); - return true; - } - - public void incrementValue(double amount) { - control.setPendingValue(Mth.clamp(control.pendingValue() + interval * amount, min, max)); - calculateInterpolation(); - } - - @Override - public boolean mouseScrolled(double mouseX, double mouseY, double horizontal, double vertical) { - if (!isAvailable() || (!isMouseOver(mouseX, mouseY)) || (!Screen.hasShiftDown() && !Screen.hasControlDown())) - return false; - - incrementValue(vertical); - return true; - } - - @Override - public boolean mouseReleased(double mouseX, double mouseY, int button) { - if (isAvailable() && mouseDown) - playDownSound(); - mouseDown = false; - - return super.mouseReleased(mouseX, mouseY, button); - } - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if (!focused) - return false; - - switch (keyCode) { - case InputConstants.KEY_LEFT -> incrementValue(-1); - case InputConstants.KEY_RIGHT -> incrementValue(1); - default -> { - return false; - } - } - - return true; - } - - @Override - public boolean isMouseOver(double mouseX, double mouseY) { - return super.isMouseOver(mouseX, mouseY) || mouseDown; - } - - protected void setValueFromMouse(double mouseX) { - double value = (mouseX - sliderBounds.x()) / sliderBounds.width() * control.range(); - control.setPendingValue(roundToInterval(value)); - calculateInterpolation(); - } - - protected double roundToInterval(double value) { - return Mth.clamp(min + (interval * Math.round(value / interval)), min, max); // extremely imprecise, requires clamping - } - - @Override - protected int getHoveredControlWidth() { - return sliderBounds.width() + getUnhoveredControlWidth() + 6 + getThumbWidth() / 2; - } - - protected void calculateInterpolation() { - interpolation = Mth.clamp((float) ((control.pendingValue() - control.min()) * 1 / control.range()), 0f, 1f); - } - - @Override - public void setDimension(Dimension<Integer> dim) { - super.setDimension(dim); - int trackWidth = dim.width() / 3; - if (optionNameString.isEmpty()) - trackWidth = dim.width() / 2; - - sliderBounds = Dimension.ofInt(dim.xLimit() - getXPadding() - getThumbWidth() / 2 - trackWidth, dim.centerY() - 5, trackWidth, 10); - } - - protected int getThumbX() { - return (int) (sliderBounds.x() + sliderBounds.width() * interpolation); - } - - protected int getThumbWidth() { - return 4; - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/package-info.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/package-info.java deleted file mode 100644 index e2cb0e3..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/slider/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * This package contains implementations of sliders for different number types - * <ul> - * <li>For doubles: {@link dev.isxander.yacl3.gui.controllers.slider.DoubleSliderController}</li> - * <li>For floats: {@link dev.isxander.yacl3.gui.controllers.slider.FloatSliderController}</li> - * <li>For integers: {@link dev.isxander.yacl3.gui.controllers.slider.IntegerSliderController}</li> - * <li>For longs: {@link dev.isxander.yacl3.gui.controllers.slider.LongSliderController}</li> - * </ul> - */ -package dev.isxander.yacl3.gui.controllers.slider; diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/IStringController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/IStringController.java deleted file mode 100644 index 14d10dd..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/IStringController.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.string; - -import dev.isxander.yacl3.api.Controller; -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import net.minecraft.network.chat.Component; - -/** - * A controller that can be any type but can input and output a string. - */ -public interface IStringController<T> extends Controller<T> { - /** - * Gets the option's pending value as a string. - * - * @see Option#pendingValue() - */ - String getString(); - - /** - * Sets the option's pending value from a string. - * - * @see Option#requestSet(Object) - */ - void setFromString(String value); - - /** - * {@inheritDoc} - */ - @Override - default Component formatValue() { - return Component.literal(getString()); - } - - default boolean isInputValid(String input) { - return true; - } - - @Override - default AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new StringControllerElement(this, screen, widgetDimension, true); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/StringController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/StringController.java deleted file mode 100644 index 4bafc0f..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/StringController.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.string; - -import dev.isxander.yacl3.api.Option; - -/** - * A custom text field implementation for strings. - */ -public class StringController implements IStringController<String> { - private final Option<String> option; - - /** - * Constructs a string controller - * - * @param option bound option - */ - public StringController(Option<String> option) { - this.option = option; - } - - /** - * {@inheritDoc} - */ - @Override - public Option<String> option() { - return option; - } - - @Override - public String getString() { - return option().pendingValue(); - } - - @Override - public void setFromString(String value) { - option().requestSet(value); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/StringControllerElement.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/StringControllerElement.java deleted file mode 100644 index 689d8e2..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/StringControllerElement.java +++ /dev/null @@ -1,466 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.string; - -import com.mojang.blaze3d.platform.InputConstants; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.controllers.ControllerWidget; -import dev.isxander.yacl3.gui.utils.GuiUtils; -import dev.isxander.yacl3.gui.utils.UndoRedoHelper; -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -import java.util.function.Consumer; - -public class StringControllerElement extends ControllerWidget<IStringController<?>> { - protected final boolean instantApply; - - protected String inputField; - protected Dimension<Integer> inputFieldBounds; - protected boolean inputFieldFocused; - - protected int caretPos; - protected int previousCaretPos; - protected int selectionLength; - protected int renderOffset; - - protected UndoRedoHelper undoRedoHelper; - - protected float ticks; - protected float caretTicks; - - private final Component emptyText; - - public StringControllerElement(IStringController<?> control, YACLScreen screen, Dimension<Integer> dim, boolean instantApply) { - super(control, screen, dim); - this.instantApply = instantApply; - inputField = control.getString(); - inputFieldFocused = false; - selectionLength = 0; - emptyText = Component.literal("Click to type...").withStyle(ChatFormatting.GRAY); - control.option().addListener((opt, val) -> { - inputField = control.getString(); - }); - setDimension(dim); - } - - @Override - protected void drawHoveredControl(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - - } - - @Override - protected void drawValueText(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - Component valueText = getValueText(); - if (!isHovered()) valueText = Component.literal(GuiUtils.shortenString(valueText.getString(), textRenderer, getMaxUnwrapLength(), "...")).setStyle(valueText.getStyle()); - - int textX = getDimension().xLimit() - textRenderer.width(valueText) + renderOffset - getXPadding(); - graphics.enableScissor(inputFieldBounds.x(), inputFieldBounds.y() - 2, inputFieldBounds.xLimit() + 1, inputFieldBounds.yLimit() + 4); - graphics.drawString(textRenderer, valueText, textX, getTextY(), getValueColor(), true); - - if (isHovered()) { - ticks += delta; - - String text = getValueText().getString(); - - graphics.fill(inputFieldBounds.x(), inputFieldBounds.yLimit(), inputFieldBounds.xLimit(), inputFieldBounds.yLimit() + 1, -1); - graphics.fill(inputFieldBounds.x() + 1, inputFieldBounds.yLimit() + 1, inputFieldBounds.xLimit() + 1, inputFieldBounds.yLimit() + 2, 0xFF404040); - - if (inputFieldFocused || focused) { - if (caretPos > text.length()) - caretPos = text.length(); - - int caretX = textX + textRenderer.width(text.substring(0, caretPos)); - if (text.isEmpty()) - caretX = inputFieldBounds.x() + inputFieldBounds.width() / 2; - - if (selectionLength != 0) { - int selectionX = textX + textRenderer.width(text.substring(0, caretPos + selectionLength)); - graphics.fill(caretX, inputFieldBounds.y() - 2, selectionX, inputFieldBounds.yLimit() - 1, 0x803030FF); - } - - if(caretPos != previousCaretPos) { - previousCaretPos = caretPos; - caretTicks = 0; - } - - if ((caretTicks += delta) % 20 <= 10) - graphics.fill(caretX, inputFieldBounds.y() - 2, caretX + 1, inputFieldBounds.yLimit() - 1, -1); - } - } - graphics.disableScissor(); - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (isAvailable() && getDimension().isPointInside((int) mouseX, (int) mouseY)) { - inputFieldFocused = true; - - if (!inputFieldBounds.isPointInside((int) mouseX, (int) mouseY)) { - caretPos = getDefaultCaretPos(); - } else { - // gets the appropriate caret position for where you click - int textX = (int) mouseX - (inputFieldBounds.xLimit() - textRenderer.width(getValueText())); - int pos = -1; - int currentWidth = 0; - for (char ch : inputField.toCharArray()) { - pos++; - int charLength = textRenderer.width(String.valueOf(ch)); - if (currentWidth + charLength / 2 > textX) { // if more than halfway past the characters select in front of that char - caretPos = pos; - break; - } else if (pos == inputField.length() - 1) { - // if we have reached the end and no matches, it must be the second half of the char so the last position - caretPos = pos + 1; - } - currentWidth += charLength; - } - - selectionLength = 0; - } -// if (undoRedoHelper == null) { -// undoRedoHelper = new UndoRedoHelper(inputField, caretPos, selectionLength); -// } - - return true; - } else { - unfocus(); - } - - return false; - } - - protected int getDefaultCaretPos() { - return inputField.length(); - } - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if (!inputFieldFocused) - return false; - - switch (keyCode) { - case InputConstants.KEY_ESCAPE, InputConstants.KEY_RETURN -> { - unfocus(); - return true; - } - case InputConstants.KEY_LEFT -> { - if (Screen.hasShiftDown()) { - if (Screen.hasControlDown()) { - int spaceChar = findSpaceIndex(true); - selectionLength += caretPos - spaceChar; - caretPos = spaceChar; - } else if (caretPos > 0) { - caretPos--; - selectionLength += 1; - } - checkRenderOffset(); - } else { - if (caretPos > 0) { - if (Screen.hasControlDown()) { - caretPos = findSpaceIndex(true); - } else { - if (selectionLength != 0) { - caretPos += Math.min(selectionLength, 0); - } else caretPos--; - } - } - checkRenderOffset(); - selectionLength = 0; - } - - return true; - } - case InputConstants.KEY_RIGHT -> { - if (Screen.hasShiftDown()) { - if (Screen.hasControlDown()) { - int spaceChar = findSpaceIndex(false); - selectionLength -= spaceChar - caretPos; - caretPos = spaceChar; - } else if (caretPos < inputField.length()) { - caretPos++; - selectionLength -= 1; - } - checkRenderOffset(); - } else { - if (caretPos < inputField.length()) { - if (Screen.hasControlDown()) { - caretPos = findSpaceIndex(false); - } else { - if (selectionLength != 0) { - caretPos += Math.max(selectionLength, 0); - } else caretPos++; - } - checkRenderOffset(); - } - selectionLength = 0; - } - - return true; - } - case InputConstants.KEY_BACKSPACE -> { - doBackspace(); - return true; - } - case InputConstants.KEY_DELETE -> { - doDelete(); - return true; - } - case InputConstants.KEY_END -> { - if (Screen.hasShiftDown()) { - selectionLength -= inputField.length() - caretPos; - } else selectionLength = 0; - caretPos = inputField.length(); - checkRenderOffset(); - return true; - } - case InputConstants.KEY_HOME -> { - if (Screen.hasShiftDown()) { - selectionLength += caretPos; - caretPos = 0; - } else { - caretPos = 0; - selectionLength = 0; - } - checkRenderOffset(); - return true; - } -// case InputConstants.KEY_Z -> { -// if (Screen.hasControlDown()) { -// UndoRedoHelper.FieldState updated = Screen.hasShiftDown() ? undoRedoHelper.redo() : undoRedoHelper.undo(); -// if (updated != null) { -// System.out.println("Updated: " + updated); -// if (modifyInput(builder -> builder.replace(0, inputField.length(), updated.text()))) { -// caretPos = updated.cursorPos(); -// selectionLength = updated.selectionLength(); -// checkRenderOffset(); -// } -// } -// return true; -// } -// } - } - - if (Screen.isPaste(keyCode)) { - return doPaste(); - } else if (Screen.isCopy(keyCode)) { - return doCopy(); - } else if (Screen.isCut(keyCode)) { - return doCut(); - } else if (Screen.isSelectAll(keyCode)) { - return doSelectAll(); - } - - return false; - } - - protected boolean doPaste() { - this.write(client.keyboardHandler.getClipboard()); - updateUndoHistory(); - return true; - } - - protected boolean doCopy() { - if (selectionLength != 0) { - client.keyboardHandler.setClipboard(getSelection()); - return true; - } - return false; - } - - protected boolean doCut() { - if (selectionLength != 0) { - client.keyboardHandler.setClipboard(getSelection()); - this.write(""); - updateUndoHistory(); - return true; - } - return false; - } - - protected boolean doSelectAll() { - caretPos = inputField.length(); - checkRenderOffset(); - selectionLength = -caretPos; - return true; - } - - protected void checkRenderOffset() { - if (textRenderer.width(inputField) < getUnshiftedLength()) { - renderOffset = 0; - return; - } - - int textX = getDimension().xLimit() - textRenderer.width(inputField) - getXPadding(); - int caretX = textX + textRenderer.width(inputField.substring(0, caretPos)); - - int minX = getDimension().xLimit() - getXPadding() - getUnshiftedLength(); - int maxX = minX + getUnshiftedLength(); - - if (caretX + renderOffset < minX) { - renderOffset = minX - caretX; - } else if (caretX + renderOffset > maxX) { - renderOffset = maxX - caretX; - } - } - - @Override - public boolean charTyped(char chr, int modifiers) { - if (!inputFieldFocused) - return false; - - if (!Screen.hasControlDown()) { - write(Character.toString(chr)); - updateUndoHistory(); - return true; - } - - return false; - } - - protected void doBackspace() { - if (selectionLength != 0) { - write(""); - } else if (caretPos > 0) { - if (modifyInput(builder -> builder.deleteCharAt(caretPos - 1))) { - caretPos--; - checkRenderOffset(); - } - } - updateUndoHistory(); - } - - protected void doDelete() { - if (selectionLength != 0) { - write(""); - } else if (caretPos < inputField.length()) { - modifyInput(builder -> builder.deleteCharAt(caretPos)); - } - updateUndoHistory(); - } - - public void write(String string) { - if (selectionLength == 0) { - if (modifyInput(builder -> builder.insert(caretPos, string))) { - caretPos += string.length(); - checkRenderOffset(); - } - } else { - int start = getSelectionStart(); - int end = getSelectionEnd(); - - if (modifyInput(builder -> builder.replace(start, end, string))) { - caretPos = start + string.length(); - selectionLength = 0; - checkRenderOffset(); - } - } - } - - public boolean modifyInput(Consumer<StringBuilder> consumer) { - StringBuilder temp = new StringBuilder(inputField); - consumer.accept(temp); - if (!control.isInputValid(temp.toString())) - return false; - inputField = temp.toString(); - if (instantApply) - updateControl(); - return true; - } - - protected void updateUndoHistory() { -// undoRedoHelper.save(inputField, caretPos, selectionLength); - } - - public int getUnshiftedLength() { - if (optionNameString.isEmpty()) - return getDimension().width() - getXPadding() * 2; - return getDimension().width() / 8 * 5; - } - - public int getMaxUnwrapLength() { - if (optionNameString.isEmpty()) - return getDimension().width() - getXPadding() * 2; - return getDimension().width() / 2; - } - - public int getSelectionStart() { - return Math.min(caretPos, caretPos + selectionLength); - } - - public int getSelectionEnd() { - return Math.max(caretPos, caretPos + selectionLength); - } - - protected String getSelection() { - return inputField.substring(getSelectionStart(), getSelectionEnd()); - } - - protected int findSpaceIndex(boolean reverse) { - int i; - int fromIndex = caretPos; - if (reverse) { - if (caretPos > 0) - fromIndex -= 2; - i = this.inputField.lastIndexOf(" ", fromIndex) + 1; - } else { - if (caretPos < inputField.length()) - fromIndex += 1; - i = this.inputField.indexOf(" ", fromIndex) + 1; - - if (i == 0) i = inputField.length(); - } - - return i; - } - - @Override - public void setFocused(boolean focused) { - super.setFocused(focused); - inputFieldFocused = focused; - } - - @Override - public void unfocus() { - super.unfocus(); - inputFieldFocused = false; - renderOffset = 0; - if (!instantApply) updateControl(); - } - - @Override - public void setDimension(Dimension<Integer> dim) { - super.setDimension(dim); - - int width = Math.max(6, Math.min(textRenderer.width(getValueText()), getUnshiftedLength())); - inputFieldBounds = Dimension.ofInt(dim.xLimit() - getXPadding() - width, dim.centerY() - textRenderer.lineHeight / 2, width, textRenderer.lineHeight); - } - - @Override - public boolean isHovered() { - return super.isHovered() || inputFieldFocused; - } - - protected void updateControl() { - control.setFromString(inputField); - } - - @Override - protected int getUnhoveredControlWidth() { - return !isHovered() ? Math.min(getHoveredControlWidth(), getMaxUnwrapLength()) : getHoveredControlWidth(); - } - - @Override - protected int getHoveredControlWidth() { - return Math.min(textRenderer.width(getValueText()), getUnshiftedLength()); - } - - @Override - protected Component getValueText() { - if (!inputFieldFocused && inputField.isEmpty()) - return emptyText; - - return instantApply || !inputFieldFocused ? control.formatValue() : Component.literal(inputField); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/DoubleFieldController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/DoubleFieldController.java deleted file mode 100644 index 1fe3e41..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/DoubleFieldController.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.string.number; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import dev.isxander.yacl3.gui.controllers.slider.DoubleSliderController; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.ApiStatus; - -import java.util.function.Function; - -/** - * {@inheritDoc} - */ -public class DoubleFieldController extends NumberFieldController<Double> { - private final double min, max; - - /** - * Constructs a double field controller - * - * @param option option to bind controller to - * @param min minimum allowed value (clamped on apply) - * @param max maximum allowed value (clamped on apply) - * @param formatter display text, not used whilst editing - */ - public DoubleFieldController(Option<Double> option, double min, double max, Function<Double, Component> formatter) { - super(option, formatter); - this.min = min; - this.max = max; - } - - /** - * Constructs a double field controller. - * Uses {@link DoubleSliderController#DEFAULT_FORMATTER} as display text, - * not used whilst editing. - * - * @param option option to bind controller to - * @param min minimum allowed value (clamped on apply) - * @param max maximum allowed value (clamped on apply) - */ - public DoubleFieldController(Option<Double> option, double min, double max) { - this(option, min, max, DoubleSliderController.DEFAULT_FORMATTER); - } - - /** - * Constructs a double field controller. - * Does not have a minimum or a maximum range. - * - * @param option option to bind controller to - * @param formatter display text, not used whilst editing - */ - public DoubleFieldController(Option<Double> option, Function<Double, Component> formatter) { - this(option, -Double.MAX_VALUE, Double.MAX_VALUE, formatter); - } - - /** - * Constructs a double field controller. - * Uses {@link DoubleSliderController#DEFAULT_FORMATTER} as display text, - * not used whilst editing. - * Does not have a minimum or a maximum range. - * - * @param option option to bind controller to - */ - public DoubleFieldController(Option<Double> option) { - this(option, -Double.MAX_VALUE, Double.MAX_VALUE, DoubleSliderController.DEFAULT_FORMATTER); - } - - @ApiStatus.Internal - public static DoubleFieldController createInternal(Option<Double> option, double min, double max, ValueFormatter<Double> formatter) { - return new DoubleFieldController(option, min, max, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public double min() { - return this.min; - } - - /** - * {@inheritDoc} - */ - @Override - public double max() { - return this.max; - } - - /** - * {@inheritDoc} - */ - @Override - public String getString() { - return NUMBER_FORMAT.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(double value) { - option().requestSet(value); - } - - /** - * {@inheritDoc} - */ - @Override - public double pendingValue() { - return option().pendingValue(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/FloatFieldController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/FloatFieldController.java deleted file mode 100644 index 8c81b49..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/FloatFieldController.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.string.number; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import dev.isxander.yacl3.gui.controllers.slider.FloatSliderController; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.ApiStatus; - -import java.util.function.Function; - -/** - * {@inheritDoc} - */ -public class FloatFieldController extends NumberFieldController<Float> { - private final float min, max; - - /** - * Constructs a float field controller - * - * @param option option to bind controller to - * @param min minimum allowed value (clamped on apply) - * @param max maximum allowed value (clamped on apply) - * @param formatter display text, not used whilst editing - */ - public FloatFieldController(Option<Float> option, float min, float max, Function<Float, Component> formatter) { - super(option, formatter); - this.min = min; - this.max = max; - } - - /** - * Constructs a float field controller. - * Uses {@link FloatSliderController#DEFAULT_FORMATTER} as display text, - * not used whilst editing. - * - * @param option option to bind controller to - * @param min minimum allowed value (clamped on apply) - * @param max maximum allowed value (clamped on apply) - */ - public FloatFieldController(Option<Float> option, float min, float max) { - this(option, min, max, FloatSliderController.DEFAULT_FORMATTER); - } - - /** - * Constructs a float field controller. - * Does not have a minimum or a maximum range. - * - * @param option option to bind controller to - * @param formatter display text, not used whilst editing - */ - public FloatFieldController(Option<Float> option, Function<Float, Component> formatter) { - this(option, -Float.MAX_VALUE, Float.MAX_VALUE, formatter); - } - - /** - * Constructs a float field controller. - * Uses {@link FloatSliderController#DEFAULT_FORMATTER} as display text, - * not used whilst editing. - * Does not have a minimum or a maximum range. - * - * @param option option to bind controller to - */ - public FloatFieldController(Option<Float> option) { - this(option, -Float.MAX_VALUE, Float.MAX_VALUE, FloatSliderController.DEFAULT_FORMATTER); - } - - @ApiStatus.Internal - public static FloatFieldController createInternal(Option<Float> option, float min, float max, ValueFormatter<Float> formatter) { - return new FloatFieldController(option, min, max, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public double min() { - return this.min; - } - - /** - * {@inheritDoc} - */ - @Override - public double max() { - return this.max; - } - - /** - * {@inheritDoc} - */ - @Override - public String getString() { - return NUMBER_FORMAT.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(double value) { - option().requestSet((float) value); - } - - /** - * {@inheritDoc} - */ - @Override - public double pendingValue() { - return option().pendingValue(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/IntegerFieldController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/IntegerFieldController.java deleted file mode 100644 index 6286978..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/IntegerFieldController.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.string.number; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import dev.isxander.yacl3.gui.controllers.slider.IntegerSliderController; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.ApiStatus; - -import java.util.function.Function; - -/** - * {@inheritDoc} - */ -public class IntegerFieldController extends NumberFieldController<Integer> { - private final int min, max; - - /** - * Constructs a integer field controller - * - * @param option option to bind controller to - * @param min minimum allowed value (clamped on apply) - * @param max maximum allowed value (clamped on apply) - * @param formatter display text, not used whilst editing - */ - public IntegerFieldController(Option<Integer> option, int min, int max, Function<Integer, Component> formatter) { - super(option, formatter); - this.min = min; - this.max = max; - } - - /** - * Constructs a integer field controller. - * Uses {@link IntegerSliderController#DEFAULT_FORMATTER} as display text, - * not used whilst editing. - * - * @param option option to bind controller to - * @param min minimum allowed value (clamped on apply) - * @param max maximum allowed value (clamped on apply) - */ - public IntegerFieldController(Option<Integer> option, int min, int max) { - this(option, min, max, IntegerSliderController.DEFAULT_FORMATTER); - } - - /** - * Constructs a integer field controller. - * Does not have a minimum or a maximum range. - * - * @param option option to bind controller to - * @param formatter display text, not used whilst editing - */ - public IntegerFieldController(Option<Integer> option, Function<Integer, Component> formatter) { - this(option, -Integer.MAX_VALUE, Integer.MAX_VALUE, formatter); - } - - /** - * Constructs a integer field controller. - * Uses {@link IntegerSliderController#DEFAULT_FORMATTER} as display text, - * not used whilst editing. - * Does not have a minimum or a maximum range. - * - * @param option option to bind controller to - */ - public IntegerFieldController(Option<Integer> option) { - this(option, -Integer.MAX_VALUE, Integer.MAX_VALUE, IntegerSliderController.DEFAULT_FORMATTER); - } - - @ApiStatus.Internal - public static IntegerFieldController createInternal(Option<Integer> option, int min, int max, ValueFormatter<Integer> formatter) { - return new IntegerFieldController(option, min, max, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public double min() { - return this.min; - } - - /** - * {@inheritDoc} - */ - @Override - public double max() { - return this.max; - } - - /** - * {@inheritDoc} - */ - @Override - public String getString() { - return NUMBER_FORMAT.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(double value) { - option().requestSet((int) value); - } - - /** - * {@inheritDoc} - */ - @Override - public double pendingValue() { - return option().pendingValue(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/LongFieldController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/LongFieldController.java deleted file mode 100644 index 906a2b5..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/LongFieldController.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.string.number; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import dev.isxander.yacl3.gui.controllers.slider.LongSliderController; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.ApiStatus; - -import java.util.function.Function; - -/** - * {@inheritDoc} - */ -public class LongFieldController extends NumberFieldController<Long> { - private final long min, max; - - /** - * Constructs a long field controller - * - * @param option option to bind controller to - * @param min minimum allowed value (clamped on apply) - * @param max maximum allowed value (clamped on apply) - * @param formatter display text, not used whilst editing - */ - public LongFieldController(Option<Long> option, long min, long max, Function<Long, Component> formatter) { - super(option, formatter); - this.min = min; - this.max = max; - } - - /** - * Constructs a long field controller. - * Uses {@link LongSliderController#DEFAULT_FORMATTER} as display text, - * not used whilst editing. - * - * @param option option to bind controller to - * @param min minimum allowed value (clamped on apply) - * @param max maximum allowed value (clamped on apply) - */ - public LongFieldController(Option<Long> option, long min, long max) { - this(option, min, max, LongSliderController.DEFAULT_FORMATTER); - } - - /** - * Constructs a long field controller. - * Does not have a minimum or a maximum range. - * - * @param option option to bind controller to - * @param formatter display text, not used whilst editing - */ - public LongFieldController(Option<Long> option, Function<Long, Component> formatter) { - this(option, -Long.MAX_VALUE, Long.MAX_VALUE, formatter); - } - - /** - * Constructs a long field controller. - * Uses {@link LongSliderController#DEFAULT_FORMATTER} as display text, - * not used whilst editing. - * Does not have a minimum or a maximum range. - * - * @param option option to bind controller to - */ - public LongFieldController(Option<Long> option) { - this(option, -Long.MAX_VALUE, Long.MAX_VALUE, LongSliderController.DEFAULT_FORMATTER); - } - - @ApiStatus.Internal - public static LongFieldController createInternal(Option<Long> option, long min, long max, ValueFormatter<Long> formatter) { - return new LongFieldController(option, min, max, formatter::format); - } - - /** - * {@inheritDoc} - */ - @Override - public double min() { - return this.min; - } - - /** - * {@inheritDoc} - */ - @Override - public double max() { - return this.max; - } - - /** - * {@inheritDoc} - */ - @Override - public String getString() { - return NUMBER_FORMAT.format(option().pendingValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public void setPendingValue(double value) { - option().requestSet((long) value); - } - - /** - * {@inheritDoc} - */ - @Override - public double pendingValue() { - return option().pendingValue(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/NumberFieldController.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/NumberFieldController.java deleted file mode 100644 index 3c06876..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/NumberFieldController.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.isxander.yacl3.gui.controllers.string.number; - -import dev.isxander.yacl3.api.Option; -import dev.isxander.yacl3.api.controller.ValueFormatter; -import dev.isxander.yacl3.api.utils.Dimension; -import dev.isxander.yacl3.gui.AbstractWidget; -import dev.isxander.yacl3.gui.YACLScreen; -import dev.isxander.yacl3.gui.controllers.slider.ISliderController; -import dev.isxander.yacl3.gui.controllers.string.IStringController; -import dev.isxander.yacl3.gui.controllers.string.StringControllerElement; -import dev.isxander.yacl3.impl.utils.YACLConstants; -import net.minecraft.network.chat.Component; -import net.minecraft.util.Mth; - -import java.text.DecimalFormatSymbols; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.function.Function; - -/** - * Controller that allows you to enter in numbers using a text field. - * - * @param <T> number type - */ -public abstract class NumberFieldController<T extends Number> implements ISliderController<T>, IStringController<T> { - - protected static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(); - private static final DecimalFormatSymbols DECIMAL_FORMAT_SYMBOLS = DecimalFormatSymbols.getInstance(); - - private final Option<T> option; - private final ValueFormatter<T> displayFormatter; - - public NumberFieldController(Option<T> option, Function<T, Component> displayFormatter) { - this.option = option; - this.displayFormatter = displayFormatter::apply; - } - - @Override - public Option<T> option() { - return this.option; - } - - @Override - public void setFromString(String value) { - try { - setPendingValue(Mth.clamp(NUMBER_FORMAT.parse(value).doubleValue(), min(), max())); - } catch (ParseException ignore) { - YACLConstants.LOGGER.warn("Failed to parse number: {}", value); - } - } - - @Override - public double pendingValue() { - return option().pendingValue().doubleValue(); - } - - @Override - public boolean isInputValid(String input) { - input = input.replace(DECIMAL_FORMAT_SYMBOLS.getGroupingSeparator() + "", ""); - ParsePosition parsePosition = new ParsePosition(0); - NUMBER_FORMAT.parse(input, parsePosition); - return parsePosition.getIndex() == input.length(); - } - - @Override - public Component formatValue() { - return displayFormatter.format(option().pendingValue()); - } - - @Override - public AbstractWidget provideWidget(YACLScreen screen, Dimension<Integer> widgetDimension) { - return new StringControllerElement(this, screen, widgetDimension, false); - } - - @Override - public double interval() { - return -1; - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/package-info.java b/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/package-info.java deleted file mode 100644 index 4d8bbc2..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/controllers/string/number/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * This package contains implementations of input fields for different number types - * <ul> - * <li>For doubles: {@link dev.isxander.yacl3.gui.controllers.string.number.DoubleFieldController}</li> - * <li>For floats: {@link dev.isxander.yacl3.gui.controllers.string.number.FloatFieldController}</li> - * <li>For integers: {@link dev.isxander.yacl3.gui.controllers.string.number.IntegerFieldController}</li> - * <li>For longs: {@link dev.isxander.yacl3.gui.controllers.string.number.LongFieldController}</li> - * </ul> - */ -package dev.isxander.yacl3.gui.controllers.string.number; diff --git a/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRenderer.java b/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRenderer.java deleted file mode 100644 index d3fb4bf..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRenderer.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.isxander.yacl3.gui.image; - -import net.minecraft.client.gui.GuiGraphics; - -public interface ImageRenderer { - int render(GuiGraphics graphics, int x, int y, int renderWidth, float tickDelta); - - void close(); - - default void tick() {} -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRendererFactory.java b/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRendererFactory.java deleted file mode 100644 index d9d2e2d..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRendererFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.isxander.yacl3.gui.image; - -public interface ImageRendererFactory { - /** - * Prepares the image. This can be run off-thread, - * and should NOT contain any GL calls whatsoever. - */ - ImageSupplier prepareImage() throws Exception; - - default boolean requiresOffThreadPreparation() { - return true; - } - - interface ImageSupplier { - ImageRenderer completeImage() throws Exception; - } - - interface OnThread extends ImageRendererFactory { - @Override - default boolean requiresOffThreadPreparation() { - return false; - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRendererManager.java b/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRendererManager.java deleted file mode 100644 index 2f7ef50..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/image/ImageRendererManager.java +++ /dev/null @@ -1,127 +0,0 @@ -package dev.isxander.yacl3.gui.image; - -import com.mojang.blaze3d.systems.RenderSystem; -import dev.isxander.yacl3.gui.image.impl.AnimatedDynamicTextureImage; -import dev.isxander.yacl3.impl.utils.YACLConstants; -import dev.isxander.yacl3.platform.YACLPlatform; -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.*; -import java.util.function.BiFunction; -import java.util.function.Predicate; -import java.util.function.Supplier; - -public class ImageRendererManager { - private static final ExecutorService SINGLE_THREAD_EXECUTOR = Executors.newSingleThreadExecutor(task -> new Thread(task, "YACL Image Prep")); - - private static final Map<ResourceLocation, CompletableFuture<ImageRenderer>> IMAGE_CACHE = new ConcurrentHashMap<>(); - static final Map<ResourceLocation, ImageRenderer> PRELOADED_IMAGE_CACHE = new ConcurrentHashMap<>(); - - static final List<PreloadedImageFactory> PRELOADED_IMAGE_FACTORIES = List.of( - new PreloadedImageFactory( - location -> location.getPath().endsWith(".webp"), - AnimatedDynamicTextureImage::createWEBPFromResource - ), - new PreloadedImageFactory( - location -> location.getPath().endsWith(".gif"), - AnimatedDynamicTextureImage::createGIFFromResource - ) - ); - - public static <T extends ImageRenderer> Optional<T> getImage(ResourceLocation id) { - if (PRELOADED_IMAGE_CACHE.containsKey(id)) { - return Optional.of((T) PRELOADED_IMAGE_CACHE.get(id)); - } - - if (IMAGE_CACHE.containsKey(id)) { - // warn developers if they don't put their webp/gif images `/textures` folder - if (YACLPlatform.isDevelopmentEnv()) { - if (PRELOADED_IMAGE_FACTORIES.stream().anyMatch(factory -> factory.predicate().test(id))) { - YACLConstants.LOGGER.error("Image '{}' not preloaded. MAKE SURE THAT ALL YACL WEBP/GIF IMAGES ARE INSIDE YOUR ASSETS `/textures` FOLDER, ELSE THEY WILL NOT BE PRELOADED!!! THIS ERROR WILL NOT APPEAR IN PROD", id); - } - } - - return Optional.ofNullable((T) IMAGE_CACHE.get(id).getNow(null)); - } - - return Optional.empty(); - } - - @SuppressWarnings("unchecked") - public static <T extends ImageRenderer> CompletableFuture<T> registerImage(ResourceLocation id, ImageRendererFactory factory) { - if (IMAGE_CACHE.containsKey(id)) { - return (CompletableFuture<T>) IMAGE_CACHE.get(id); - } - - var future = new CompletableFuture<ImageRenderer>(); - IMAGE_CACHE.put(id, future); - - SINGLE_THREAD_EXECUTOR.submit(() -> { - Supplier<Optional<ImageRendererFactory.ImageSupplier>> supplier = - factory.requiresOffThreadPreparation() - ? new CompletedSupplier<>(safelyPrepareFactory(id, factory)) - : () -> safelyPrepareFactory(id, factory); - - Minecraft.getInstance().execute(() -> completeImageFactory(id, supplier, future)); - }); - - return (CompletableFuture<T>) future; - } - - private static void completeImageFactory(ResourceLocation id, Supplier<Optional<ImageRendererFactory.ImageSupplier>> supplier, CompletableFuture<ImageRenderer> future) { - RenderSystem.assertOnRenderThread(); - - ImageRendererFactory.ImageSupplier completableImage = supplier.get().orElse(null); - if (completableImage == null) { - return; - } - - // sanity check - this should never happen - if (future.isDone()) { - YACLConstants.LOGGER.error("Image '{}' was already completed", id); - return; - } - - ImageRenderer image; - try { - image = completableImage.completeImage(); - } catch (Exception e) { - YACLConstants.LOGGER.error("Failed to create image '{}'", id, e); - return; - } - - future.complete(image); - } - - public static void closeAll() { - SINGLE_THREAD_EXECUTOR.shutdownNow(); - IMAGE_CACHE.values().removeIf(future -> { - if (future.isDone()) { - future.join().close(); - } - return true; - }); - } - - static Optional<ImageRendererFactory.ImageSupplier> safelyPrepareFactory(ResourceLocation id, ImageRendererFactory factory) { - try { - return Optional.of(factory.prepareImage()); - } catch (Exception e) { - YACLConstants.LOGGER.error("Failed to prepare image '{}'", id, e); - IMAGE_CACHE.remove(id); - return Optional.empty(); - } - } - - public record PreloadedImageFactory(Predicate<ResourceLocation> predicate, BiFunction<Resource, ResourceLocation, ImageRendererFactory> factory) { - } - - private record CompletedSupplier<T>(T get) implements Supplier<T> { - } - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/image/YACLImageReloadListener.java b/common/src/main/java/dev/isxander/yacl3/gui/image/YACLImageReloadListener.java deleted file mode 100644 index bac8c56..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/image/YACLImageReloadListener.java +++ /dev/null @@ -1,102 +0,0 @@ -package dev.isxander.yacl3.gui.image; - -import dev.isxander.yacl3.impl.utils.YACLConstants; -import net.minecraft.CrashReport; -import net.minecraft.CrashReportCategory; -import net.minecraft.ReportedException; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.PreparableReloadListener; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.profiling.ProfilerFiller; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; -import java.util.function.Function; - -public class YACLImageReloadListener implements PreparableReloadListener { - @Override - public CompletableFuture<Void> reload( - PreparationBarrier preparationBarrier, - ResourceManager resourceManager, - ProfilerFiller preparationsProfiler, - ProfilerFiller reloadProfiler, - Executor backgroundExecutor, - Executor gameExecutor - ) { - YACLConstants.LOGGER.info("YACL is reloading images"); - Map<ResourceLocation, Resource> imageResources = resourceManager.listResources( - "textures", - location -> ImageRendererManager.PRELOADED_IMAGE_FACTORIES - .stream() - .anyMatch(factory -> factory.predicate().test(location)) - ); - - // extreme mojang hackery. - // for some reason this wait method needs to be called for the reload - // instance to be marked as complete - if (imageResources.isEmpty()) { - preparationBarrier.wait(null); - } - - List<CompletableFuture<?>> futures = new ArrayList<>(imageResources.size()); - - for (Map.Entry<ResourceLocation, Resource> entry : imageResources.entrySet()) { - ResourceLocation location = entry.getKey(); - Resource resource = entry.getValue(); - - ImageRendererFactory imageFactory = ImageRendererManager.PRELOADED_IMAGE_FACTORIES - .stream() - .filter(factory -> factory.predicate().test(location)) - .map(factory -> factory.factory().apply(resource, location)) - .findAny() - .orElseThrow(); - - CompletableFuture<Optional<ImageRenderer>> imageFuture = - CompletableFuture.supplyAsync( - () -> ImageRendererManager.safelyPrepareFactory( - location, imageFactory - ), - backgroundExecutor - ) - .thenCompose(preparationBarrier::wait) - .thenApplyAsync(imageSupplierOpt -> { - if (imageSupplierOpt.isEmpty()) { - return Optional.empty(); - } - ImageRendererFactory.ImageSupplier supplier = imageSupplierOpt.get(); - - ImageRenderer imageRenderer; - try { - imageRenderer = supplier.completeImage(); - } catch (Exception e) { - YACLConstants.LOGGER.error("Failed to create image '{}'", location, e); - return Optional.empty(); - } - - ImageRendererManager.PRELOADED_IMAGE_CACHE.put(location, imageRenderer); - - return Optional.of(imageRenderer); - }, gameExecutor); - - futures.add(imageFuture); - - imageFuture.whenComplete((result, throwable) -> { - if (throwable != null) { - CrashReport crashReport = CrashReport.forThrowable(throwable, "Failed to load image"); - CrashReportCategory category = crashReport.addCategory("YACL Gui"); - category.setDetail("Image identifier", location.toString()); - throw new ReportedException(crashReport); - } - }); - } - - YACLConstants.LOGGER.info("YACL has found {} images", imageResources.size()); - - return CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/image/impl/AnimatedDynamicTextureImage.java b/common/src/main/java/dev/isxander/yacl3/gui/image/impl/AnimatedDynamicTextureImage.java deleted file mode 100644 index 2136f56..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/image/impl/AnimatedDynamicTextureImage.java +++ /dev/null @@ -1,294 +0,0 @@ -package dev.isxander.yacl3.gui.image.impl; - -import com.mojang.blaze3d.Blaze3D; -import com.mojang.blaze3d.platform.GlConst; -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.platform.NativeImage; -import com.twelvemonkeys.imageio.plugins.webp.WebPImageReaderSpi; -import dev.isxander.yacl3.debug.DebugProperties; -import dev.isxander.yacl3.gui.image.ImageRendererFactory; -import dev.isxander.yacl3.impl.utils.YACLConstants; -import net.minecraft.CrashReport; -import net.minecraft.CrashReportCategory; -import net.minecraft.ReportedException; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.FastColor; - -import javax.imageio.ImageIO; -import javax.imageio.ImageReader; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.metadata.IIOMetadataNode; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.nio.file.Path; -import java.util.List; -import java.util.stream.IntStream; - -public class AnimatedDynamicTextureImage extends DynamicTextureImage { - private int currentFrame; - private double lastFrameTime; - - private final double[] frameDelays; - private final int frameCount; - - private final int packCols, packRows; - private final int frameWidth, frameHeight; - - public AnimatedDynamicTextureImage(NativeImage image, int frameWidth, int frameHeight, int frameCount, double[] frameDelayMS, int packCols, int packRows, ResourceLocation uniqueLocation) { - super(image, uniqueLocation); - this.frameWidth = frameWidth; - this.frameHeight = frameHeight; - this.frameCount = frameCount; - this.frameDelays = frameDelayMS; - this.packCols = packCols; - this.packRows = packRows; - } - - @Override - public int render(GuiGraphics graphics, int x, int y, int renderWidth, float tickDelta) { - if (image == null) return 0; - - float ratio = renderWidth / (float)frameWidth; - int targetHeight = (int) (frameHeight * ratio); - - int currentCol = currentFrame % packCols; - int currentRow = (int) Math.floor(currentFrame / (double)packCols); - - graphics.pose().pushPose(); - graphics.pose().translate(x, y, 0); - graphics.pose().scale(ratio, ratio, 1); - - if (DebugProperties.IMAGE_FILTERING) { - GlStateManager._texParameter(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MAG_FILTER, GlConst.GL_LINEAR); - GlStateManager._texParameter(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MIN_FILTER, GlConst.GL_LINEAR); - } - - graphics.blit( - uniqueLocation, - 0, 0, - frameWidth * currentCol, frameHeight * currentRow, - frameWidth, frameHeight, - this.width, this.height - ); - graphics.pose().popPose(); - - if (frameCount > 1) { - double timeMS = Blaze3D.getTime() * 1000; - if (lastFrameTime == 0) lastFrameTime = timeMS; - if (timeMS - lastFrameTime >= frameDelays[currentFrame]) { - currentFrame++; - lastFrameTime = timeMS; - } - if (currentFrame >= frameCount - 1) - currentFrame = 0; - } - - return targetHeight; - } - - public static ImageRendererFactory createGIFFromTexture(ResourceLocation textureLocation) { - return () -> { - ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); - Resource resource = resourceManager.getResource(textureLocation).orElseThrow(); - - return createGIFSupplier(resource.open(), textureLocation); - }; - } - - public static ImageRendererFactory createGIFFromResource(Resource resource, ResourceLocation resourceLocation) { - return () -> createGIFSupplier(resource.open(), resourceLocation); - } - - public static ImageRendererFactory createGIFFromPath(Path path, ResourceLocation uniqueLocation) { - return () -> createGIFSupplier(new FileInputStream(path.toFile()), uniqueLocation); - } - - public static ImageRendererFactory createWEBPFromTexture(ResourceLocation textureLocation) { - return () -> { - ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); - Resource resource = resourceManager.getResource(textureLocation).orElseThrow(); - - return createWEBPSupplier(resource.open(), textureLocation); - }; - } - - public static ImageRendererFactory createWEBPFromResource(Resource resource, ResourceLocation resourceLocation) { - return () -> createWEBPSupplier(resource.open(), resourceLocation); - } - - public static ImageRendererFactory createWEBPFromPath(Path path, ResourceLocation uniqueLocation) { - return () -> createWEBPSupplier(new FileInputStream(path.toFile()), uniqueLocation); - } - - private static ImageRendererFactory.ImageSupplier createGIFSupplier(InputStream is, ResourceLocation uniqueLocation) { - try (is) { - ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next(); - reader.setInput(ImageIO.createImageInputStream(is)); - - AnimFrameProvider animFrameFunction = i -> { - IIOMetadata metadata = reader.getImageMetadata(i); - String metaFormatName = metadata.getNativeMetadataFormatName(); - IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(metaFormatName); - IIOMetadataNode graphicsControlExtensionNode = (IIOMetadataNode) root.getElementsByTagName("GraphicControlExtension").item(0); - int delay = Integer.parseInt(graphicsControlExtensionNode.getAttribute("delayTime")) * 10; - - return new AnimFrame(delay, 0, 0); - }; - - return createFromImageReader(reader, animFrameFunction, uniqueLocation); - } catch (Exception e) { - CrashReport crashReport = CrashReport.forThrowable(e, "Failed to load GIF image"); - CrashReportCategory category = crashReport.addCategory("YACL Gui"); - category.setDetail("Image identifier", uniqueLocation.toString()); - throw new ReportedException(crashReport); - } - } - - private static ImageRendererFactory.ImageSupplier createWEBPSupplier(InputStream is, ResourceLocation uniqueLocation) { - try (is) { - ImageReader reader = new WebPImageReaderSpi().createReaderInstance(); - reader.setInput(ImageIO.createImageInputStream(is)); - - int numImages = reader.getNumImages(true); // Force reading of all frames - AnimFrameProvider animFrameFunction = i -> null; - if (numImages > 1) { - // WebP reader does not expose frame delay, prepare for reflection hell - Class<?> webpReaderClass = Class.forName("com.twelvemonkeys.imageio.plugins.webp.WebPImageReader"); - Field framesField = webpReaderClass.getDeclaredField("frames"); - framesField.setAccessible(true); - java.util.List<?> frames = (List<?>) framesField.get(reader); - - Class<?> animationFrameClass = Class.forName("com.twelvemonkeys.imageio.plugins.webp.AnimationFrame"); - Field durationField = animationFrameClass.getDeclaredField("duration"); - durationField.setAccessible(true); - Field boundsField = animationFrameClass.getDeclaredField("bounds"); - boundsField.setAccessible(true); - - animFrameFunction = i -> { - Rectangle bounds = (Rectangle) boundsField.get(frames.get(i)); - return new AnimFrame((int) durationField.get(frames.get(i)), bounds.x, bounds.y); - }; - // that was fun - } - - return createFromImageReader(reader, animFrameFunction, uniqueLocation); - } catch (Throwable e) { - CrashReport crashReport = CrashReport.forThrowable(e, "Failed to load WEBP image"); - CrashReportCategory category = crashReport.addCategory("YACL Gui"); - category.setDetail("Image identifier", uniqueLocation.toString()); - throw new ReportedException(crashReport); - } - } - - private static ImageRendererFactory.ImageSupplier createFromImageReader(ImageReader reader, AnimFrameProvider animationProvider, ResourceLocation uniqueLocation) throws Exception { - if (reader.isSeekForwardOnly()) { - throw new RuntimeException("Image reader is not seekable"); - } - - int frameCount = reader.getNumImages(true); - - // Because this is being backed into a texture atlas, we need a maximum dimension - // so you can get the texture atlas size. - // Smaller frames are given black borders - int frameWidth = IntStream.range(0, frameCount).map(i -> { - try { - return reader.getWidth(i); - } catch (IOException e) { - throw new RuntimeException(e); - } - }).max().orElseThrow(); - int frameHeight = IntStream.range(0, frameCount).map(i -> { - try { - return reader.getHeight(i); - } catch (IOException e) { - throw new RuntimeException(e); - } - }).max().orElseThrow(); - - // Packs the frames into an optimal 1:1 texture. - // OpenGL can only have texture axis with a max of 32768 pixels, - // and packing them to that length is not efficient, apparently. - double ratio = frameWidth / (double)frameHeight; - int cols = (int)Math.ceil(Math.sqrt(frameCount) / Math.sqrt(ratio)); - int rows = (int)Math.ceil(frameCount / (double)cols); - - NativeImage image = new NativeImage(NativeImage.Format.RGBA, frameWidth * cols, frameHeight * rows, false); - -// // Fill whole atlas with black, as each frame may have different dimensions -// // that would cause borders of transparent pixels to appear around the frames -// for (int x = 0; x < frameWidth * cols; x++) { -// for (int y = 0; y < frameHeight * rows; y++) { -// image.setPixelRGBA(x, y, 0xFF000000); -// } -// } - - BufferedImage bi = null; - Graphics2D graphics = null; - - // each frame may have a different delay - double[] frameDelays = new double[frameCount]; - - for (int i = 0; i < frameCount; i++) { - AnimFrame frame = animationProvider.get(i); - if (frameCount > 1) // frame will be null if not animation - frameDelays[i] = frame.durationMS; - - if (bi == null) { - // first frame... - bi = reader.read(i); - graphics = bi.createGraphics(); - } else { - // WebP reader sometimes provides delta frames, (only the pixels that changed since the last frame) - // so instead of overwriting the image every frame, we draw delta frames on top of the previous frame - // to keep a complete image. - BufferedImage deltaFrame = reader.read(i); - graphics.drawImage(deltaFrame, frame.xOffset, frame.yOffset, null); - } - - // Each frame may have different dimensions, so we need to center them. - int xOffset = (frameWidth - bi.getWidth()) / 2; - int yOffset = (frameHeight - bi.getHeight()) / 2; - - for (int w = 0; w < bi.getWidth(); w++) { - for (int h = 0; h < bi.getHeight(); h++) { - int rgb = bi.getRGB(w, h); - int r = FastColor.ARGB32.red(rgb); - int g = FastColor.ARGB32.green(rgb); - int b = FastColor.ARGB32.blue(rgb); - int a = FastColor.ARGB32.alpha(rgb); - - int col = i % cols; - int row = (int) Math.floor(i / (double)cols); - - image.setPixelRGBA( - frameWidth * col + w + xOffset, - frameHeight * row + h + yOffset, - FastColor.ABGR32.color(a, b, g, r) // NativeImage uses ABGR for some reason - ); - } - } - } - - if (graphics != null) - graphics.dispose(); - reader.dispose(); - - return () -> new AnimatedDynamicTextureImage(image, frameWidth, frameHeight, frameCount, frameDelays, cols, rows, uniqueLocation); - } - - @FunctionalInterface - private interface AnimFrameProvider { - AnimFrame get(int frame) throws Exception; - } - - private record AnimFrame(int durationMS, int xOffset, int yOffset) {} - -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/image/impl/DynamicTextureImage.java b/common/src/main/java/dev/isxander/yacl3/gui/image/impl/DynamicTextureImage.java deleted file mode 100644 index 2d2abb9..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/image/impl/DynamicTextureImage.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.isxander.yacl3.gui.image.impl; - -import com.mojang.blaze3d.platform.GlConst; -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.systems.RenderSystem; -import dev.isxander.yacl3.debug.DebugProperties; -import dev.isxander.yacl3.gui.image.ImageRenderer; -import dev.isxander.yacl3.gui.image.ImageRendererFactory; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.renderer.texture.DynamicTexture; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.resources.ResourceLocation; - -import java.io.FileInputStream; -import java.nio.file.Path; - -public class DynamicTextureImage implements ImageRenderer { - protected static final TextureManager textureManager = Minecraft.getInstance().getTextureManager(); - - protected NativeImage image; - protected DynamicTexture texture; - protected final ResourceLocation uniqueLocation; - protected final int width, height; - - public DynamicTextureImage(NativeImage image, ResourceLocation location) { - RenderSystem.assertOnRenderThread(); - - this.image = image; - this.texture = new DynamicTexture(image); - this.uniqueLocation = location; - textureManager.register(this.uniqueLocation, this.texture); - this.width = image.getWidth(); - this.height = image.getHeight(); - } - - @Override - public int render(GuiGraphics graphics, int x, int y, int renderWidth, float tickDelta) { - if (image == null) return 0; - - float ratio = renderWidth / (float)this.width; - int targetHeight = (int) (this.height * ratio); - - graphics.pose().pushPose(); - graphics.pose().translate(x, y, 0); - graphics.pose().scale(ratio, ratio, 1); - - if (DebugProperties.IMAGE_FILTERING) { - GlStateManager._texParameter(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MAG_FILTER, GlConst.GL_LINEAR); - GlStateManager._texParameter(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MIN_FILTER, GlConst.GL_LINEAR); - } - - graphics.blit(uniqueLocation, 0, 0, 0, 0, this.width, this.height, this.width, this.height); - - graphics.pose().popPose(); - - return targetHeight; - } - - @Override - public void close() { - image.close(); - image = null; - texture = null; - textureManager.release(uniqueLocation); - } - - public static ImageRendererFactory fromPath(Path imagePath, ResourceLocation location) { - return (ImageRendererFactory.OnThread) () -> () -> new DynamicTextureImage(NativeImage.read(new FileInputStream(imagePath.toFile())), location); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/image/impl/ResourceTextureImage.java b/common/src/main/java/dev/isxander/yacl3/gui/image/impl/ResourceTextureImage.java deleted file mode 100644 index abbeec7..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/image/impl/ResourceTextureImage.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.isxander.yacl3.gui.image.impl; - -import com.mojang.blaze3d.platform.GlConst; -import com.mojang.blaze3d.platform.GlStateManager; -import dev.isxander.yacl3.debug.DebugProperties; -import dev.isxander.yacl3.gui.image.ImageRenderer; -import dev.isxander.yacl3.gui.image.ImageRendererFactory; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.resources.ResourceLocation; - -public class ResourceTextureImage implements ImageRenderer { - private final ResourceLocation location; - private final int width, height; - private final int textureWidth, textureHeight; - private final float u, v; - - public ResourceTextureImage(ResourceLocation location, float u, float v, int width, int height, int textureWidth, int textureHeight) { - this.location = location; - this.width = width; - this.height = height; - this.textureWidth = textureWidth; - this.textureHeight = textureHeight; - this.u = u; - this.v = v; - } - - @Override - public int render(GuiGraphics graphics, int x, int y, int renderWidth, float tickDelta) { - float ratio = renderWidth / (float)this.width; - int targetHeight = (int) (this.height * ratio); - - graphics.pose().pushPose(); - graphics.pose().translate(x, y, 0); - graphics.pose().scale(ratio, ratio, 1); - - if (DebugProperties.IMAGE_FILTERING) { - GlStateManager._texParameter(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MAG_FILTER, GlConst.GL_LINEAR); - GlStateManager._texParameter(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MIN_FILTER, GlConst.GL_LINEAR); - } - - graphics.blit(location, 0, 0, this.u, this.v, this.width, this.height, this.textureWidth, this.textureHeight); - - graphics.pose().popPose(); - - return targetHeight; - } - - @Override - public void close() { - - } - - public static ImageRendererFactory createFactory(ResourceLocation location, float u, float v, int width, int height, int textureWidth, int textureHeight) { - return (ImageRendererFactory.OnThread) () -> () -> new ResourceTextureImage(location, u, v, width, height, textureWidth, textureHeight); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/tab/ListHolderWidget.java b/common/src/main/java/dev/isxander/yacl3/gui/tab/ListHolderWidget.java deleted file mode 100644 index df28d27..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/tab/ListHolderWidget.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.isxander.yacl3.gui.tab; - -import com.google.common.collect.ImmutableList; -import dev.isxander.yacl3.gui.ElementListWidgetExt; -import net.minecraft.client.gui.ComponentPath; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.components.events.ContainerEventHandler; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.gui.navigation.FocusNavigationEvent; -import net.minecraft.client.gui.navigation.ScreenRectangle; -import net.minecraft.network.chat.CommonComponents; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.function.Supplier; - -public class ListHolderWidget<T extends ElementListWidgetExt<?>> extends AbstractWidget implements ContainerEventHandler { - private final Supplier<ScreenRectangle> dimensions; - private final T list; - - public ListHolderWidget(Supplier<ScreenRectangle> dimensions, T list) { - super(0, 0, 100, 0, CommonComponents.EMPTY); - this.dimensions = dimensions; - this.list = list; - } - - @Override - public void renderWidget(GuiGraphics guiGraphics, int mouseX, int mouseY, float deltaTick) { - ScreenRectangle dimensions = this.dimensions.get(); - this.setX(dimensions.left()); - this.setY(dimensions.top()); - this.width = dimensions.width(); - this.height = dimensions.height(); - this.list.updateDimensions(dimensions); - this.list.render(guiGraphics, mouseX, mouseY, deltaTick); - } - - @Override - protected void updateWidgetNarration(NarrationElementOutput output) { - this.list.updateNarration(output); - } - - @Override - public List<? extends GuiEventListener> children() { - return ImmutableList.of(this.list); - } - - public T getList() { - return list; - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - return this.list.mouseClicked(mouseX, mouseY, button); - } - - @Override - public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { - return this.list.mouseDragged(mouseX, mouseY, button, deltaX, deltaY); - } - - @Override - public boolean mouseReleased(double mouseX, double mouseY, int button) { - return this.list.mouseReleased(mouseX, mouseY, button); - } - - @Override - public boolean mouseScrolled(double mouseX, double mouseY, double horizontal, double vertical) { - return this.list.mouseScrolled(mouseX, mouseY, horizontal, vertical); - } - - @Override - public boolean keyPressed(int i, int j, int k) { - return this.list.keyPressed(i, j, k); - } - - @Override - public boolean charTyped(char c, int i) { - return this.list.charTyped(c, i); - } - - @Override - public boolean isDragging() { - return this.list.isDragging(); - } - - @Override - public void setDragging(boolean dragging) { - this.list.setDragging(dragging); - } - - @Nullable - @Override - public GuiEventListener getFocused() { - return this.list.getFocused(); - } - - @Override - public void setFocused(@Nullable GuiEventListener listener) { - this.list.setFocused(listener); - } - - @Nullable - @Override - public ComponentPath nextFocusPath(FocusNavigationEvent event) { - return this.list.nextFocusPath(event); - } - - @Nullable - @Override - public ComponentPath getCurrentFocusPath() { - return this.list.getCurrentFocusPath(); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/tab/ScrollableNavigationBar.java b/common/src/main/java/dev/isxander/yacl3/gui/tab/ScrollableNavigationBar.java deleted file mode 100644 index 66ba6a3..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/tab/ScrollableNavigationBar.java +++ /dev/null @@ -1,115 +0,0 @@ -package dev.isxander.yacl3.gui.tab; - -import com.google.common.collect.ImmutableList; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.components.TabButton; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.gui.components.tabs.Tab; -import net.minecraft.client.gui.components.tabs.TabManager; -import net.minecraft.client.gui.components.tabs.TabNavigationBar; -import net.minecraft.util.Mth; -import org.jetbrains.annotations.Nullable; - -public class ScrollableNavigationBar extends TabNavigationBar { - private static final int NAVBAR_MARGIN = 28; - - private static final Font font = Minecraft.getInstance().font; - - private int scrollOffset; - private int maxScrollOffset; - - public ScrollableNavigationBar(int width, TabManager tabManager, Iterable<? extends Tab> tabs) { - super(width, tabManager, ImmutableList.copyOf(tabs)); - - // add tab tooltips to the tab buttons - for (TabButton tabButton : this.tabButtons) { - if (tabButton.tab() instanceof TabExt tab) { - tabButton.setTooltip(tab.getTooltip()); - } - } - } - - @Override - public void arrangeElements() { - int noScrollWidth = this.width - NAVBAR_MARGIN*2; - - int allTabsWidth = 0; - // first pass: set the width of each tab button - for (TabButton tabButton : this.tabButtons) { - int buttonWidth = font.width(tabButton.getMessage()) + 20; - allTabsWidth += buttonWidth; - tabButton.setWidth(buttonWidth); - } - - if (allTabsWidth < noScrollWidth) { - int equalWidth = noScrollWidth / this.tabButtons.size(); - var smallTabs = this.tabButtons.stream().filter(btn -> btn.getWidth() < equalWidth).toList(); - var bigTabs = this.tabButtons.stream().filter(btn -> btn.getWidth() >= equalWidth).toList(); - int leftoverWidth = noScrollWidth - bigTabs.stream().mapToInt(AbstractWidget::getWidth).sum(); - int equalWidthForSmallTabs = leftoverWidth / smallTabs.size(); - for (TabButton tabButton : smallTabs) { - tabButton.setWidth(equalWidthForSmallTabs); - } - - allTabsWidth = noScrollWidth; - } - - this.layout.arrangeElements(); - this.layout.setY(0); - this.scrollOffset = 0; - - this.layout.setX(Math.max((this.width - allTabsWidth) / 2, NAVBAR_MARGIN)); - this.maxScrollOffset = Math.max(0, allTabsWidth - noScrollWidth); - } - - @Override - public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - graphics.pose().pushPose(); - // render option list BELOW the navbar without need to scissor - graphics.pose().translate(0, 0, 10); - - super.render(graphics, mouseX, mouseY, delta); - - graphics.pose().popPose(); - } - - @Override - public boolean mouseScrolled(double mouseX, double mouseY, double horizontal, double vertical) { - this.setScrollOffset(this.scrollOffset - (int)(vertical*15)); - return true; - } - - @Override - public boolean isMouseOver(double mouseX, double mouseY) { - return mouseY <= 24; - } - - public void setScrollOffset(int scrollOffset) { - layout.setX(layout.getX() + this.scrollOffset); - this.scrollOffset = Mth.clamp(scrollOffset, 0, maxScrollOffset); - layout.setX(layout.getX() - this.scrollOffset); - } - - public int getScrollOffset() { - return scrollOffset; - } - - @Override - public void setFocused(@Nullable GuiEventListener child) { - super.setFocused(child); - if (child instanceof TabButton tabButton) { - this.ensureVisible(tabButton); - } - } - - protected void ensureVisible(TabButton tabButton) { - if (tabButton.getX() < NAVBAR_MARGIN) { - this.setScrollOffset(this.scrollOffset - (NAVBAR_MARGIN - tabButton.getX())); - } else if (tabButton.getX() + tabButton.getWidth() > this.width - NAVBAR_MARGIN) { - this.setScrollOffset(this.scrollOffset + (tabButton.getX() + tabButton.getWidth() - (this.width - NAVBAR_MARGIN))); - } - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/tab/TabExt.java b/common/src/main/java/dev/isxander/yacl3/gui/tab/TabExt.java deleted file mode 100644 index 1b4b3e5..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/tab/TabExt.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.isxander.yacl3.gui.tab; - -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.Tooltip; -import net.minecraft.client.gui.components.tabs.Tab; -import org.jetbrains.annotations.Nullable; - -public interface TabExt extends Tab { - @Nullable Tooltip getTooltip(); - - default void tick() {} - - default void renderBackground(GuiGraphics graphics) {} -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/utils/GuiUtils.java b/common/src/main/java/dev/isxander/yacl3/gui/utils/GuiUtils.java deleted file mode 100644 index 2910d0f..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/utils/GuiUtils.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.isxander.yacl3.gui.utils; - -import net.minecraft.client.gui.Font; -import net.minecraft.locale.Language; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; - -public class GuiUtils { - public static MutableComponent translatableFallback(String key, Component fallback) { - if (Language.getInstance().has(key)) - return Component.translatable(key); - return fallback.copy(); - } - - public static String shortenString(String string, Font font, int maxWidth, String suffix) { - if (string.isEmpty()) - return string; - - boolean firstIter = true; - while (font.width(string) > maxWidth) { - string = string.substring(0, Math.max(string.length() - 1 - (firstIter ? 1 : suffix.length() + 1), 0)).trim(); - string += suffix; - - if (string.equals(suffix)) - break; - - firstIter = false; - } - - return string; - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/utils/ItemRegistryHelper.java b/common/src/main/java/dev/isxander/yacl3/gui/utils/ItemRegistryHelper.java deleted file mode 100644 index 3c4f03a..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/utils/ItemRegistryHelper.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.isxander.yacl3.gui.utils; - - -import net.minecraft.ResourceLocationException; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.NotNull; - -import java.util.Comparator; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Stream; - -public final class ItemRegistryHelper { - - /** - * Checks whether the given string is an identifier referring to a known item - * - * @param identifier Item identifier, either of the format "namespace:path" or "path". If no namespace is included, - * the default vanilla namespace "minecraft" is used. - * @return true if the identifier refers to a registered item, false otherwise - */ - public static boolean isRegisteredItem(String identifier) { - try { - ResourceLocation itemIdentifier = new ResourceLocation(identifier.toLowerCase()); - return BuiltInRegistries.ITEM.containsKey(itemIdentifier); - } catch (ResourceLocationException e) { - return false; - } - } - - /** - * Looks up the item of the given identifier string. - * - * @param identifier Item identifier, either of the format "namespace:path" or "path". If no namespace is included, - * the default vanilla namespace "minecraft" is used. - * @param defaultItem Fallback item that gets returned if the identifier does not name a registered item. - * @return The item identified by the given string, or the fallback if the identifier is not known. - */ - public static Item getItemFromName(String identifier, Item defaultItem) { - try { - ResourceLocation itemIdentifier = new ResourceLocation(identifier.toLowerCase()); - if (BuiltInRegistries.ITEM.containsKey(itemIdentifier)) { - return BuiltInRegistries.ITEM.get(itemIdentifier); - } - } catch (ResourceLocationException ignored) { - } - return defaultItem; - } - - /** - * Looks up the item of the given identifier string. - * - * @param identifier Item identifier, either of the format "namespace:path" or "path". If no namespace is included, - * the default vanilla namespace "minecraft" is used. - * @return The item identified by the given string, or `Items.AIR` if the identifier is not known. - */ - public static Item getItemFromName(String identifier) { - return getItemFromName(identifier, Items.AIR); - } - - /** - * Returns a list of item identifiers matching the given string. The value matches an identifier if: - * <li>No namespace is provided in the value and the value is a substring of the path segment of any identifier, - * regardless of namespace.</li> - * <li>A namespace is provided, equals the identifier's namespace, and the value is the begin of the identifier's - * path segment.</li> - * - * @param value (partial) identifier, either of the format "namespace:path" or "path". - * @return list of matching item identifiers; empty if the given string does not correspond to any known identifiers - */ - public static Stream<ResourceLocation> getMatchingItemIdentifiers(String value) { - int sep = value.indexOf(ResourceLocation.NAMESPACE_SEPARATOR); - Predicate<ResourceLocation> filterPredicate; - if (sep == -1) { - filterPredicate = identifier -> - identifier.getPath().contains(value) - || BuiltInRegistries.ITEM.get(identifier).getDescription().getString().toLowerCase().contains(value.toLowerCase()); - } else { - String namespace = value.substring(0, sep); - String path = value.substring(sep + 1); - filterPredicate = identifier -> identifier.getNamespace().equals(namespace) && identifier.getPath().startsWith(path); - } - return BuiltInRegistries.ITEM.holders() - .map(holder -> holder.key().location()) - .filter(filterPredicate) - /* - Sort items as follows based on the given "value" string's path: - - if both items' paths begin with the entered string, sort the identifiers (including namespace) - - otherwise, if either of the items' path begins with the entered string, sort it to the left - - else neither path matches: sort by identifiers again - - This allows the user to enter "diamond_ore" and match "minecraft:diamond_ore" before - "minecraft:deepslate_diamond_ore", even though the second is lexicographically smaller - */ - .sorted((id1, id2) -> { - String path = (sep == -1 ? value : value.substring(sep + 1)).toLowerCase(); - boolean id1StartsWith = id1.getPath().toLowerCase().startsWith(path); - boolean id2StartsWith = id2.getPath().toLowerCase().startsWith(path); - if (id1StartsWith) { - if (id2StartsWith) { - return id1.compareTo(id2); - } - return -1; - } - if (id2StartsWith) { - return 1; - } - return id1.compareTo(id2); - }); - } -} diff --git a/common/src/main/java/dev/isxander/yacl3/gui/utils/UndoRedoHelper.java b/common/src/main/java/dev/isxander/yacl3/gui/utils/UndoRedoHelper.java deleted file mode 100644 index 3328c16..0000000 --- a/common/src/main/java/dev/isxander/yacl3/gui/utils/UndoRedoHelper.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.isxander.yacl3.gui.utils; - -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; - -public class UndoRedoHelper { - private final List<FieldState> history = new ArrayList<>(); - private int index = 0; - - public UndoRedoHelper(String text, int cursorPos, int selectionLength) { - history.add(new FieldState(text, cursorPos, selectionLength)); - } - - public void save(String text, int cursorPos, int selectionLength) { - int max = history.size(); - history.subList(index, max).clear(); - history.add(new FieldState(text, cursorPos, selectionLength)); - index++; - } - - public @Nullable FieldState undo() { - index--; - index = Math.max(index, 0); - - if (history.isEmpty()) - return null; - return history.get(index); - } - - public @Nullable FieldState redo() { - if (index < history.size() - 1) { - index++; - return history.get(index); - } else { - return null; - } - } - - public record FieldState(String text, int cursorPos, int selectionLength) {} -} |