diff --git a/.github/workflows/format-java.yml b/.github/workflows/format-java.yml new file mode 100644 index 00000000..3b15c202 --- /dev/null +++ b/.github/workflows/format-java.yml @@ -0,0 +1,47 @@ +# Runs formatting requirements +name: Java Formatting + +on: + push: + branches: ['1.20.1', '1.21.1'] + paths: ['src/main/java/**', 'src/test/**'] + pull_request: + paths: ['**'] + +concurrency: + group: formatting-${{ github.ref }} + cancel-in-progress: true + +jobs: + formatting: + name: Formatting + runs-on: ubuntu-latest + permissions: + pull-requests: read + steps: + - name: Checkout Repository + uses: actions/checkout@v6 + with: + fetch-depth: 0 # do a full checkout instead of a shallow clone of HEAD so spotless's ratchetFrom works + - name: Check Path Filter + uses: dorny/paths-filter@v3 + id: filter + with: + filters: | + code: + - 'src/main/java/**' + - 'src/test/**' + - name: Setup Java + if: steps.filter.outputs.code == 'true' + uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: '21' + - name: Setup Gradle + if: steps.filter.outputs.code == 'true' + uses: gradle/actions/setup-gradle@v4 + with: + cache-read-only: true + - name: Run Spotless Formatting Check with Gradle + if: steps.filter.outputs.code == 'true' + run: chmod +x ./gradlew && ./gradlew spotlessCheck --warning-mode all diff --git a/build.gradle b/build.gradle index a7075c0f..c1106045 100755 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,7 @@ plugins { id 'maven-publish' alias libs.plugins.modDevGradle //alias libs.plugins.shadow - alias libs.plugins.editorconfig + alias libs.plugins.spotless alias libs.plugins.lombok } @@ -73,7 +73,7 @@ apply from: "$rootDir/gradle/scripts/repositories.gradle" apply from: "$rootDir/dependencies.gradle" apply from: "$rootDir/gradle/scripts/resources.gradle" apply from: "$rootDir/gradle/scripts/publishing.gradle" -apply from: "$rootDir/gradle/scripts/formatting.gradle" +apply from: "$rootDir/gradle/scripts/spotless.gradle" apply from: "$rootDir/gradle/scripts/docs.gradle" diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 3063e6a7..ba184193 100755 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -4,7 +4,7 @@ minecraft = "1.20.1" forge = "47.4.28" parchment = "2023.09.03" # https://parchmentmc.org/docs/getting-started shadow = "8.3.5" -editorconfig = "0.1.0" +spotless = "8.1.0" modDevGradle = "2.0.86" lombok = "8.14" @@ -25,5 +25,5 @@ mcdevAnnotations = { module = "com.demonwav.mcdev:annotations", version.ref = "m [plugins] modDevGradle = { id = "net.neoforged.moddev.legacyforge", version.ref = "modDevGradle" } shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } -editorconfig = { id = "org.ec4j.editorconfig", version.ref = "editorconfig" } +spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } lombok = { id = "io.freefair.lombok", version.ref = "lombok" } diff --git a/gradle/scripts/formatting.gradle b/gradle/scripts/formatting.gradle deleted file mode 100644 index 677adf1c..00000000 --- a/gradle/scripts/formatting.gradle +++ /dev/null @@ -1,6 +0,0 @@ -// EditorConfig auto-formatter -// See https://github.com/ec4j/editorconfig-gradle-plugin -// Can be locally toggled via @formatter:off/@formatter:on comments -editorconfig { - includes = ['*'] -} diff --git a/gradle/scripts/spotless.gradle b/gradle/scripts/spotless.gradle new file mode 100644 index 00000000..b082a949 --- /dev/null +++ b/gradle/scripts/spotless.gradle @@ -0,0 +1,27 @@ +// Spotless auto-formatter +// See https://github.com/diffplug/spotless/tree/main/plugin-gradle +// Can be locally toggled via spotless:off/spotless:on comments +spotless { + encoding 'UTF-8' + ratchetFrom 'origin/1.20.1' + + format 'misc', { + target '.gitignore' + + trimTrailingWhitespace() + leadingTabsToSpaces() + endWithNewline() + } + java { + target 'src/main/java/**/*.java', 'src/test/java/**/*.java' + + def orderFile = file("$rootDir/spotless/spotless.importorder") + def formatFile = file("$rootDir/spotless/spotless.eclipseformat.xml") + + toggleOffOn() + importOrderFile(orderFile) + removeUnusedImports('cleanthat-javaparser-unnecessaryimport') + endWithNewline() + eclipse('4.36').configFile(formatFile) + } +} diff --git a/spotless/spotless.eclipseformat.xml b/spotless/spotless.eclipseformat.xml new file mode 100644 index 00000000..8db01de4 --- /dev/null +++ b/spotless/spotless.eclipseformat.xml @@ -0,0 +1,400 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spotless/spotless.importorder b/spotless/spotless.importorder new file mode 100644 index 00000000..5c05beb3 --- /dev/null +++ b/spotless/spotless.importorder @@ -0,0 +1,7 @@ +#Organize Import Order +0=brachy +1=net +2= +3=java +4=javax +5=\# diff --git a/src/main/java/brachy/modularui/ClientProxy.java b/src/main/java/brachy/modularui/ClientProxy.java index 6d436a98..6198a558 100644 --- a/src/main/java/brachy/modularui/ClientProxy.java +++ b/src/main/java/brachy/modularui/ClientProxy.java @@ -22,7 +22,6 @@ import net.minecraft.client.Timer; import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; import net.minecraftforge.client.event.RegisterClientTooltipComponentFactoriesEvent; import net.minecraftforge.common.MinecraftForge; @@ -33,6 +32,7 @@ import net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import java.util.function.Function; @@ -73,7 +73,7 @@ protected void onInit(FMLCommonSetupEvent event) { } private void onClientStartup(FMLClientSetupEvent event) { - //noinspection deprecation,RedundantCast + // noinspection deprecation,RedundantCast event.enqueueWork(() -> MenuScreens.register(ModularUIMenuTypes.MODULAR_CONTAINER.get(), (MenuScreens.ScreenConstructor) ContainerScreenWrapper::new)); } diff --git a/src/main/java/brachy/modularui/CommonProxy.java b/src/main/java/brachy/modularui/CommonProxy.java index 5161e2bc..8f73a4b7 100644 --- a/src/main/java/brachy/modularui/CommonProxy.java +++ b/src/main/java/brachy/modularui/CommonProxy.java @@ -11,7 +11,6 @@ import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; -import com.mojang.brigadier.Command; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.AddReloadListenerEvent; import net.minecraftforge.event.RegisterCommandsEvent; @@ -23,6 +22,8 @@ import net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import com.mojang.brigadier.Command; + public class CommonProxy { CommonProxy(FMLJavaModLoadingContext ctx) { @@ -74,7 +75,8 @@ private void onRegisterCommand(RegisterCommandsEvent event) { .executes(ctx -> { ThemeManager.reload(); // TODO translations for this - ctx.getSource().sendSuccess(() -> Component.literal("ModularUI Themes reloaded").withStyle(Text.GREEN), true); + ctx.getSource().sendSuccess( + () -> Component.literal("ModularUI Themes reloaded").withStyle(Text.GREEN), true); return Command.SINGLE_SUCCESS; })); event.getDispatcher().register(command); diff --git a/src/main/java/brachy/modularui/ModularUI.java b/src/main/java/brachy/modularui/ModularUI.java index 1a0caaf1..e961bb04 100644 --- a/src/main/java/brachy/modularui/ModularUI.java +++ b/src/main/java/brachy/modularui/ModularUI.java @@ -112,7 +112,7 @@ public static boolean isClientThread() { /** * @return if the game is the PHYSICAL client, e.g. not a dedicated server. * @apiNote Do not use this to check if you're currently on the server thread for side-specific actions! - * It does NOT work for that. Use {@link #isClientThread()} instead. + * It does NOT work for that. Use {@link #isClientThread()} instead. * @see #isClientThread() */ public static boolean isClientSide() { @@ -123,7 +123,7 @@ public static boolean isClientSide() { * This check isn't the same for client and server! * * @return if it's safe to access the current instance {@link net.minecraft.world.level.Level Level} on client or if - * it's safe to access any level on server. + * it's safe to access any level on server. */ public static boolean canGetServerLevel() { if (isClientSide()) { @@ -174,15 +174,15 @@ private static RegistryAccess getClientRegistries() { public enum Mods { - //BLUR(ModIds.BLUR), - //BOGOSORTER(ModIds.BOGOSORTER), + // BLUR(ModIds.BLUR), + // BOGOSORTER(ModIds.BOGOSORTER), CURIOS(ModIds.CURIOS), EMI(ModIds.EMI), JEI(ModIds.JEI), REI(ModIds.REI), KUBEJS(ModIds.KUBEJS), - //MODNAMETOOLTIP(ModIds.MODNAMETOOLTIP) - //NEA(ModIds.NEA), + // MODNAMETOOLTIP(ModIds.MODNAMETOOLTIP) + // NEA(ModIds.NEA), EMBEDDIUM(ModIds.EMBEDDIUM), SODIUM(ModIds.SODIUM), IRIS(ModIds.IRIS), diff --git a/src/main/java/brachy/modularui/ModularUIConfig.java b/src/main/java/brachy/modularui/ModularUIConfig.java index 8a8926f4..29e75365 100644 --- a/src/main/java/brachy/modularui/ModularUIConfig.java +++ b/src/main/java/brachy/modularui/ModularUIConfig.java @@ -26,7 +26,8 @@ public class ModularUIConfig { .translation("config.modularui.defaultScrollSpeed") .defineInRange("defaultScrollSpeed", 30, 1, 100); public static final BooleanValue SMOOTH_PROGRESS_BARS = BUILDER - .comment("If progress bars should step in texture pixels or screen pixels. (Screen pixels are way smaller and therefore smoother)") + .comment( + "If progress bars should step in texture pixels or screen pixels. (Screen pixels are way smaller and therefore smoother)") .translation("config.modularui.smoothProgressBars") .define("smoothProgressBars", false); public static final IntValue ANIMATION_TIME = BUILDER @@ -39,7 +40,8 @@ public class ModularUIConfig { .translation("config.modularui.tooltipPos") .defineEnum("tooltipPos", RichTooltip.Pos.NEXT_TO_MOUSE); public static final BooleanValue ESC_RESTORES_LAST_TEXT = BUILDER - .comment("If true, pressing ESC key in the text field will restore the last text instead of confirming current one.") + .comment( + "If true, pressing ESC key in the text field will restore the last text instead of confirming current one.") .translation("config.modularui.escRestoresLastText") .define("escRestoresLastText", false); public static final BooleanValue USE_DARK_THEME_BY_DEFAULT = BUILDER @@ -49,12 +51,12 @@ public class ModularUIConfig { public static final BooleanValue ENABLE_TEST_GUIS = BUILDER .comment("Enables a test block, test item with a test gui and opening a gui by right clicking a diamond.") .translation("config.modularui.enableTestGuis") - .worldRestart() //.gameRestart() + .worldRestart() // .gameRestart() .define("enableTestGuis", ModularUI.isDev()); public static final BooleanValue ENABLE_TEST_OVERLAYS = BUILDER .comment("Enables a test overlay shown on title screen and watermark shown on every GuiContainer.") .translation("config.modularui.enableTestOverlays") - .worldRestart() //.gameRestart() + .worldRestart() // .gameRestart() .define("enableTestOverlays", false); public static final BooleanValue REPLACE_VANILLA_TOOLTIPS = BUILDER .comment("If true, vanilla tooltip will be replaced with MUI's RichTooltip") diff --git a/src/main/java/brachy/modularui/ModularUIMenuTypes.java b/src/main/java/brachy/modularui/ModularUIMenuTypes.java index 7064700d..ee441676 100644 --- a/src/main/java/brachy/modularui/ModularUIMenuTypes.java +++ b/src/main/java/brachy/modularui/ModularUIMenuTypes.java @@ -11,9 +11,11 @@ public class ModularUIMenuTypes { - private static final DeferredRegister> MENU_TYPES = DeferredRegister.create(Registries.MENU, ModularUI.MOD_ID); + private static final DeferredRegister> MENU_TYPES = DeferredRegister.create(Registries.MENU, + ModularUI.MOD_ID); - public static final RegistryObject> MODULAR_CONTAINER = MENU_TYPES.register("modular", + public static final RegistryObject> MODULAR_CONTAINER = MENU_TYPES.register( + "modular", () -> IForgeMenuType.create(ModularContainerMenu::new)); public static void register(IEventBus modBus) { diff --git a/src/main/java/brachy/modularui/api/ITheme.java b/src/main/java/brachy/modularui/api/ITheme.java index 60059cbf..4d38ad15 100644 --- a/src/main/java/brachy/modularui/api/ITheme.java +++ b/src/main/java/brachy/modularui/api/ITheme.java @@ -11,12 +11,8 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.Encoder; - import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; - -import net.minecraft.util.ExtraCodecs; - import org.jetbrains.annotations.UnmodifiableView; import java.util.Collection; @@ -39,6 +35,7 @@ public interface ITheme { ITheme::getId); Encoder ENCODER = new Encoder<>() { + @Override public DataResult encode(ITheme input, DynamicOps ops, T prefix) { var mapBuilder = ops.mapBuilder(); @@ -49,7 +46,8 @@ public DataResult encode(ITheme input, DynamicOps ops, T prefix) { for (WidgetThemeEntry entry : input.getWidgetThemeEntries()) { if (entry.key() == IThemeApi.FALLBACK) continue; var set = encodedThemes.computeIfAbsent(entry.key().getName(), k -> new ObjectOpenHashSet<>()); - if (entry.key().isSubWidgetTheme() && set.contains(entry.theme()) && set.contains(entry.hoverTheme())) continue; + if (entry.key().isSubWidgetTheme() && set.contains(entry.theme()) && set.contains(entry.hoverTheme())) + continue; entry.encode(ops, mapBuilder, false); set.add(entry.theme()); set.add(entry.hoverTheme()); diff --git a/src/main/java/brachy/modularui/api/IThemeApi.java b/src/main/java/brachy/modularui/api/IThemeApi.java index 924725bc..115590c4 100644 --- a/src/main/java/brachy/modularui/api/IThemeApi.java +++ b/src/main/java/brachy/modularui/api/IThemeApi.java @@ -19,7 +19,6 @@ import brachy.modularui.utils.serialization.json.JsonBuilder; import com.mojang.serialization.Codec; - import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -105,7 +104,8 @@ public interface IThemeApi { .register(); WidgetThemeKey TOGGLE_BUTTON = get().widgetThemeKeyBuilder("toggleButton", SelectableTheme.class) - .defaultTheme(SelectableTheme.whiteTextShadow(18, 18, GuiTextures.MC_BUTTON, GuiTextures.MC_BUTTON_DISABLED)) + .defaultTheme( + SelectableTheme.whiteTextShadow(18, 18, GuiTextures.MC_BUTTON, GuiTextures.MC_BUTTON_DISABLED)) .defaultHoverTheme(SelectableTheme.whiteTextShadow(18, 18, GuiTextures.MC_BUTTON_HOVERED, IDrawable.NONE)) .fieldsOf(FALLBACK) .field(SELECTED_BACKGROUND, IDrawable.class, IDrawable.CODEC, SelectableTheme::getSelectedBackground) @@ -124,7 +124,6 @@ public interface IThemeApi { String HOVER_SUFFIX = ":hover"; - /** * @return the default api implementation */ @@ -188,7 +187,8 @@ default void registerTheme(ThemeBuilder themeBuilder) { * @param defaultTheme default theme if no theme was found * @return the registered theme for the given screen or the given default theme or {@link #getDefaultTheme()} */ - default ITheme getThemeForScreen(String owner, String name, @Nullable String defaultTheme, @Nullable String fallbackTheme) { + default ITheme getThemeForScreen(String owner, String name, @Nullable String defaultTheme, + @Nullable String fallbackTheme) { return getThemeForScreen(owner, name, null, defaultTheme, fallbackTheme); } @@ -201,7 +201,8 @@ default ITheme getThemeForScreen(String owner, String name, @Nullable String def * @param defaultTheme default theme if no theme was found * @return the registered theme for the given screen or the given default theme or {@link #getDefaultTheme()} */ - ITheme getThemeForScreen(String owner, String name, @Nullable String panel, @Nullable String defaultTheme, @Nullable String fallbackTheme); + ITheme getThemeForScreen(String owner, String name, @Nullable String panel, @Nullable String defaultTheme, + @Nullable String fallbackTheme); /** * Gets the appropriate theme for a specific panel. @@ -212,7 +213,8 @@ default ITheme getThemeForScreen(String owner, String name, @Nullable String def */ default ITheme getThemeForScreen(ModularPanel panel, @Nullable String defaultTheme) { ModularScreen screen = panel.getScreen(); - return getThemeForScreen(screen.getOwner(), screen.getName(), panel.getName(), defaultTheme, screen.getThemeOverride()); + return getThemeForScreen(screen.getOwner(), screen.getName(), panel.getName(), defaultTheme, + screen.getThemeOverride()); } /** @@ -247,7 +249,8 @@ default void registerThemeForScreen(String owner, String name, String theme) { @Deprecated WidgetThemeKey registerWidgetTheme(String id, T defaultTheme, T defaultHoverTheme, - WidgetThemeMerger merger, WidgetThemeCodec codec); + WidgetThemeMerger merger, + WidgetThemeCodec codec); default WidgetThemeKeyBuilder widgetThemeKeyBuilder(String id, Class type) { return new WidgetThemeKeyBuilder<>(id, type); diff --git a/src/main/java/brachy/modularui/api/drawable/IDrawable.java b/src/main/java/brachy/modularui/api/drawable/IDrawable.java index eba02dd1..2406237b 100644 --- a/src/main/java/brachy/modularui/api/drawable/IDrawable.java +++ b/src/main/java/brachy/modularui/api/drawable/IDrawable.java @@ -14,14 +14,14 @@ import brachy.modularui.widget.Widget; import brachy.modularui.widget.sizer.Area; -import com.mojang.serialization.Codec; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.JsonOps; -import com.mojang.serialization.MapCodec; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import com.google.gson.JsonElement; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; import org.jetbrains.annotations.Nullable; /** @@ -45,6 +45,7 @@ static IDrawable of(IDrawable... drawables) { * An empty drawable. Does nothing. */ IDrawable EMPTY = new IDrawable() { + @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) {} @@ -58,6 +59,7 @@ public String toString() { * An empty drawable used to mark hover textures as "should not be used"! */ IDrawable NONE = new IDrawable() { + @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) {} @@ -68,7 +70,8 @@ public String toString() { }; CodecRegistry CODECS = new CodecRegistry<>(); - MapCodec CODEC_DISPATCH = CodecUtil.dispatchNullable(Codec.STRING, IDrawable::getTypeName, CODECS::getNullableCodec); + MapCodec CODEC_DISPATCH = CodecUtil.dispatchNullable(Codec.STRING, IDrawable::getTypeName, + CODECS::getNullableCodec); Codec CODEC_EMPTY_NONE = Codec.STRING.flatXmap(s -> { if (s == null || s.equals("empty") || s.equals("null")) return DataResult.success(EMPTY); if (s.equals("none")) return DataResult.success(NONE); @@ -168,7 +171,8 @@ default void drawAtZero(GuiContext context, Area area, WidgetTheme widgetTheme) */ @OnlyIn(Dist.CLIENT) default void drawAtZeroPadded(GuiContext context, Area area, WidgetTheme widgetTheme) { - draw(context, area.getPadding().left(), area.getPadding().top(), area.paddedWidth(), area.paddedHeight(), widgetTheme); + draw(context, area.getPadding().left(), area.getPadding().top(), area.paddedWidth(), area.paddedHeight(), + widgetTheme); } /** diff --git a/src/main/java/brachy/modularui/api/drawable/IRichTextBuilder.java b/src/main/java/brachy/modularui/api/drawable/IRichTextBuilder.java index a1f39740..d8ac7303 100644 --- a/src/main/java/brachy/modularui/api/drawable/IRichTextBuilder.java +++ b/src/main/java/brachy/modularui/api/drawable/IRichTextBuilder.java @@ -94,12 +94,14 @@ default T addDrawableLine(IDrawable line) { * @param lang lang key of the multilang to add. * @return this */ - /*TODO default T addMultiLine(String lang) { - for (MutableComponent text : LangHandler.getMultiLang(lang)) { - getRichText().addLine(text); - } - return getThis(); - }*/ + /* + * TODO default T addMultiLine(String lang) { + * for (MutableComponent text : LangHandler.getMultiLang(lang)) { + * getRichText().addLine(text); + * } + * return getThis(); + * } + */ /** * Starts a new line. This is always preferred over {@code "\n"} or {@code IKey.str("\n")}, it reduces computation a diff --git a/src/main/java/brachy/modularui/api/drawable/ITextLine.java b/src/main/java/brachy/modularui/api/drawable/ITextLine.java index b5621525..e0601e66 100644 --- a/src/main/java/brachy/modularui/api/drawable/ITextLine.java +++ b/src/main/java/brachy/modularui/api/drawable/ITextLine.java @@ -10,7 +10,8 @@ public interface ITextLine { int getHeight(Font font); - void draw(GuiContext context, Font font, float x, float y, int color, boolean shadow, int availableWidth, int availableHeight); + void draw(GuiContext context, Font font, float x, float y, int color, boolean shadow, int availableWidth, + int availableHeight); Object getHoveringElement(Font font, int x, int y); } diff --git a/src/main/java/brachy/modularui/api/drawable/Text.java b/src/main/java/brachy/modularui/api/drawable/Text.java index 7c532ea9..8e79e7f9 100644 --- a/src/main/java/brachy/modularui/api/drawable/Text.java +++ b/src/main/java/brachy/modularui/api/drawable/Text.java @@ -10,8 +10,6 @@ import brachy.modularui.utils.Alignment; import brachy.modularui.utils.serialization.codec.MutableObjectCodec; -import com.demonwav.mcdev.annotations.Translatable; - import net.minecraft.ChatFormatting; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; @@ -19,6 +17,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.demonwav.mcdev.annotations.Translatable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -157,7 +156,8 @@ default void draw(GuiContext context, int x, int y, int width, int height, Widge } @OnlyIn(Dist.CLIENT) - default void drawAligned(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme, Alignment alignment) { + default void drawAligned(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme, + Alignment alignment) { renderer.setColor(widgetTheme.getTextColor()); renderer.setShadow(widgetTheme.isTextShadow()); renderer.setAlignment(alignment, width, height); @@ -201,9 +201,11 @@ default float getScale() { ModularComponent withStyle(); - /*default AnimatedText withAnimation() { - return new AnimatedText(this); - }*/ + /* + * default AnimatedText withAnimation() { + * return new AnimatedText(this); + * } + */ /** * Set text formatting to this key. If {@link Text#RESET} is used, then that's applied first and then all other diff --git a/src/main/java/brachy/modularui/api/layout/IViewportStack.java b/src/main/java/brachy/modularui/api/layout/IViewportStack.java index cb7e6856..7662b632 100755 --- a/src/main/java/brachy/modularui/api/layout/IViewportStack.java +++ b/src/main/java/brachy/modularui/api/layout/IViewportStack.java @@ -4,7 +4,6 @@ import brachy.modularui.widget.sizer.Area; import com.mojang.blaze3d.vertex.PoseStack; - import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; diff --git a/src/main/java/brachy/modularui/api/value/IValue.java b/src/main/java/brachy/modularui/api/value/IValue.java index 7e2d7a36..bdf9456d 100644 --- a/src/main/java/brachy/modularui/api/value/IValue.java +++ b/src/main/java/brachy/modularui/api/value/IValue.java @@ -1,6 +1,5 @@ package brachy.modularui.api.value; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.UnknownNullability; /** diff --git a/src/main/java/brachy/modularui/api/widget/IDraggable.java b/src/main/java/brachy/modularui/api/widget/IDraggable.java index 252f36e0..2fd7500e 100644 --- a/src/main/java/brachy/modularui/api/widget/IDraggable.java +++ b/src/main/java/brachy/modularui/api/widget/IDraggable.java @@ -21,7 +21,8 @@ public interface IDraggable { /** * Gets called every frame after everything else is rendered. * Is only called when {@link #isMoving()} is true. - * Translate to the mouse pos and draw with {@link WidgetTree#drawTree(IWidget, ModularGuiContext, boolean, boolean)}. + * Translate to the mouse pos and draw with + * {@link WidgetTree#drawTree(IWidget, ModularGuiContext, boolean, boolean)}. * * @param graphics * @param partialTicks difference from last from diff --git a/src/main/java/brachy/modularui/api/widget/IPositioned.java b/src/main/java/brachy/modularui/api/widget/IPositioned.java index 9f65c924..b37ea882 100644 --- a/src/main/java/brachy/modularui/api/widget/IPositioned.java +++ b/src/main/java/brachy/modularui/api/widget/IPositioned.java @@ -15,7 +15,7 @@ * * @param widget type */ -@SuppressWarnings({"unused", "UnusedReturnValue"}) +@SuppressWarnings({ "unused", "UnusedReturnValue" }) public interface IPositioned> { /** @@ -62,8 +62,10 @@ default W coverChildrenHeight() { } /** - * Calculate the width by covering all children of this widget. For this calculation the widget children are used NOT the resizer - * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this widgets size + * Calculate the width by covering all children of this widget. For this calculation the widget children are used + * NOT the resizer + * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this + * widgets size * is calculated. If all children depend on this widgets size, the min size is used. * * @param minWidth minimum width this widget can have, negative values disables cover children @@ -75,8 +77,10 @@ default W coverChildrenWidth(int minWidth) { } /** - * Calculate the height by covering all children of this widget. For this calculation the widget children are used NOT the resizer - * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this widgets size + * Calculate the height by covering all children of this widget. For this calculation the widget children are used + * NOT the resizer + * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this + * widgets size * is calculated. If all children depend on this widgets size, the min size is used. * * @param minHeight minimum height this widget can have, negative values disables cover children @@ -97,8 +101,10 @@ default W coverChildren() { } /** - * Calculate the width and height by covering all children of this widget. For this calculation the widget children are used NOT the resizer - * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this widgets size + * Calculate the width and height by covering all children of this widget. For this calculation the widget children + * are used NOT the resizer + * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this + * widgets size * is calculated. If all children depend on this widgets size, the min size is used. * * @param minSize minimum width and height this widget can have, negative values disables cover children @@ -109,8 +115,10 @@ default W coverChildren(int minSize) { } /** - * Calculate the width and height by covering all children of this widget. For this calculation the widget children are used NOT the resizer - * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this widgets size + * Calculate the width and height by covering all children of this widget. For this calculation the widget children + * are used NOT the resizer + * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this + * widgets size * is calculated. If all children depend on this widgets size, the min size is used. * * @param minWidth minimum width this widget can have, negative values disables cover children @@ -149,7 +157,8 @@ default W disableCoverChildren() { } /** - * Sets if this resizer is decoration. Decoration will be ignored during coverChildren and margin/padding calculations. + * Sets if this resizer is decoration. Decoration will be ignored during coverChildren and margin/padding + * calculations. * * @param decoration true if this resizer is decoration * @return this @@ -167,7 +176,8 @@ default W decoration() { } /** - * Sets whether this widget should expand inside a {@link brachy.modularui.widgets.layout.Flow Flow} widget. Expanded means it takes + * Sets whether this widget should expand inside a {@link brachy.modularui.widgets.layout.Flow Flow} widget. + * Expanded means it takes * as much space as possible on the main axis without overlapping with other children in the flow. * * @return this @@ -190,8 +200,10 @@ default W relative(Area area) { } /** - * Sets the resizer this widget should be relative to. That means all left, top, right, bottom, width and height properties will be - * calculated based of the new resizer. By default, this is the widgets parent. Every resize node tree configuration is allowed as long + * Sets the resizer this widget should be relative to. That means all left, top, right, bottom, width and height + * properties will be + * calculated based of the new resizer. By default, this is the widgets parent. Every resize node tree configuration + * is allowed as long * as there are no circular dependencies. * * @param resizeNode resizer parent override @@ -239,7 +251,8 @@ default W left(int val) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0). + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0). * 0.0 means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. * * @param val relative left edge to parent left edge distance @@ -251,9 +264,12 @@ default W leftRel(float val) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative left edge to parent left edge distance * @param offset additional distance offset in pixel @@ -265,14 +281,18 @@ default W leftRelOffset(float val, int offset) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an anchor. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative left edge to parent left edge distance - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W leftRelAnchor(float val, float anchor) { @@ -281,17 +301,22 @@ default W leftRelAnchor(float val, float anchor) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative left edge to parent left edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W leftRel(float val, int offset, float anchor) { @@ -300,18 +325,24 @@ default W leftRel(float val, int offset, float anchor) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val left edge to parent left edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value - * @param measure determines if the val param should be a relative value or in pixel, the anchor does nothing in pixel + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value + * @param measure determines if the val param should be a relative value or in pixel, the anchor does + * nothing in pixel * @return this */ default W left(float val, int offset, float anchor, Unit.Measure measure) { @@ -332,9 +363,12 @@ default W left(DoubleSupplier val, Unit.Measure measure) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative left edge to parent left edge distance function which is called on every resize * @param offset additional distance offset in pixel @@ -346,14 +380,18 @@ default W leftRelOffset(DoubleSupplier val, int offset) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an anchor. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative left edge to parent left edge distance function which is called on every resize - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W leftRelAnchor(DoubleSupplier val, float anchor) { @@ -362,17 +400,22 @@ default W leftRelAnchor(DoubleSupplier val, float anchor) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative left edge to parent left edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W leftRel(DoubleSupplier val, int offset, float anchor) { @@ -392,7 +435,8 @@ default W right(int val) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0). + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0). * 0.0 means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. * * @param val relative right edge to parent right edge distance @@ -404,9 +448,12 @@ default W rightRel(float val) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset. + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative right edge to parent right edge distance * @param offset additional distance offset in pixel @@ -418,14 +465,18 @@ default W rightRelOffset(float val, int offset) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an anchor. + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative right edge to parent right edge distance - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W rightRelAnchor(float val, float anchor) { @@ -434,17 +485,22 @@ default W rightRelAnchor(float val, float anchor) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative right edge to parent right edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W rightRel(float val, int offset, float anchor) { @@ -453,18 +509,24 @@ default W rightRel(float val, int offset, float anchor) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val right edge to parent right edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value - * @param measure determines if the val param should be a relative value or in pixel, the anchor does nothing in pixel + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value + * @param measure determines if the val param should be a relative value or in pixel, the anchor does + * nothing in pixel * @return this */ default W right(float val, int offset, float anchor, Unit.Measure measure) { @@ -485,9 +547,12 @@ default W right(DoubleSupplier val, Unit.Measure measure) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset. + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative right edge to parent right edge distance function which is called on every resize * @param offset additional distance offset in pixel @@ -499,14 +564,18 @@ default W rightRelOffset(DoubleSupplier val, int offset) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an anchor. + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative right edge to parent right edge distance function which is called on every resize - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W rightRelAnchor(DoubleSupplier val, float anchor) { @@ -515,17 +584,22 @@ default W rightRelAnchor(DoubleSupplier val, float anchor) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative right edge to parent right edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W rightRel(DoubleSupplier val, int offset, float anchor) { @@ -545,7 +619,8 @@ default W top(int val) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0). + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0). * 0.0 means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. * * @param val relative top edge to parent top edge distance @@ -557,9 +632,12 @@ default W topRel(float val) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset. + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative top edge to parent top edge distance * @param offset additional distance offset in pixel @@ -571,14 +649,18 @@ default W topRelOffset(float val, int offset) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an anchor. + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative top edge to parent top edge distance - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W topRelAnchor(float val, float anchor) { @@ -587,17 +669,22 @@ default W topRelAnchor(float val, float anchor) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative top edge to parent top edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W topRel(float val, int offset, float anchor) { @@ -606,18 +693,24 @@ default W topRel(float val, int offset, float anchor) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val top edge to parent top edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value - * @param measure determines if the val param should be a relative value or in pixel, the anchor does nothing in pixel + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value + * @param measure determines if the val param should be a relative value or in pixel, the anchor does + * nothing in pixel * @return this */ default W top(float val, int offset, float anchor, Unit.Measure measure) { @@ -638,9 +731,12 @@ default W top(DoubleSupplier val, Unit.Measure measure) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset. + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative top edge to parent top edge distance function which is called on every resize * @param offset additional distance offset in pixel @@ -652,14 +748,18 @@ default W topRelOffset(DoubleSupplier val, int offset) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an anchor. + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative top edge to parent top edge distance function which is called on every resize - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W topRelAnchor(DoubleSupplier val, float anchor) { @@ -668,17 +768,22 @@ default W topRelAnchor(DoubleSupplier val, float anchor) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative top edge to parent top edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W topRel(DoubleSupplier val, int offset, float anchor) { @@ -698,7 +803,8 @@ default W bottom(int val) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0). + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0). * 0.0 means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. * * @param val relative bottom edge to parent bottom edge distance @@ -710,9 +816,12 @@ default W bottomRel(float val) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset. + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative bottom edge to parent bottom edge distance * @param offset additional distance offset in pixel @@ -724,14 +833,18 @@ default W bottomRelOffset(float val, int offset) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an anchor. + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative bottom edge to parent bottom edge distance - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W bottomRelAnchor(float val, float anchor) { @@ -740,17 +853,22 @@ default W bottomRelAnchor(float val, float anchor) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative bottom edge to parent bottom edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W bottomRel(float val, int offset, float anchor) { @@ -759,18 +877,24 @@ default W bottomRel(float val, int offset, float anchor) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val bottom edge to parent bottom edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value - * @param measure determines if the val param should be a relative value or in pixel, the anchor does nothing in pixel + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value + * @param measure determines if the val param should be a relative value or in pixel, the anchor does + * nothing in pixel * @return this */ default W bottom(float val, int offset, float anchor, Unit.Measure measure) { @@ -779,7 +903,8 @@ default W bottom(float val, int offset, float anchor, Unit.Measure measure) { } /** - * Sets the distance from this widgets bottom edge to the resizers widget bottom edge in pixel or as a relative value. + * Sets the distance from this widgets bottom edge to the resizers widget bottom edge in pixel or as a relative + * value. * * @param val bottom edge to parent bottom edge distance function which is called on every resize * @param measure determines if the val param should be a relative value or in pixel @@ -791,9 +916,12 @@ default W bottom(DoubleSupplier val, Unit.Measure measure) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the top edge touches the + * parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative bottom edge to parent bottom edge distance function which is called on every resize * @param offset additional distance offset in pixel @@ -805,14 +933,18 @@ default W bottomRelOffset(DoubleSupplier val, int offset) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the bottom edge touches the parent left bottom. 1.0 means the top edge touches the parent top edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an anchor. + * 0.0 for the relative value means the bottom edge touches the parent left bottom. 1.0 means the top edge touches + * the parent top edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative bottom edge to parent bottom edge distance function which is called on every resize - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W bottomRelAnchor(DoubleSupplier val, float anchor) { @@ -821,17 +953,22 @@ default W bottomRelAnchor(DoubleSupplier val, float anchor) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative bottom edge to parent bottom edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W bottomRel(DoubleSupplier val, int offset, float anchor) { @@ -863,7 +1000,8 @@ default W widthRel(float val) { /** * Sets the relative width of this widget with an offset. 1.0 is the same size as the resizer parent. - * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be negative. + * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be + * negative. * * @param val relative width * @param offset additional size offset in pixel @@ -888,7 +1026,8 @@ default W width(float val, Unit.Measure measure) { /** * Sets the width of this widget in pixel or as a relative value with an offset. - * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be negative. + * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be + * negative. * * @param val relative width function which is called on every resize * @param offset additional size offset in pixel @@ -947,7 +1086,8 @@ default W height(float val, Unit.Measure measure) { /** * Sets the relative height of this widget with an offset. 1.0 is the same size as the resizer parent. - * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be negative. + * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be + * negative. * * @param val relative height * @param offset additional size offset in pixel @@ -960,7 +1100,8 @@ default W heightRelOffset(float val, int offset) { /** * Sets the width of this widget in pixel or as a relative value with an offset. - * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be negative. + * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be + * negative. * * @param val relative width function which is called on every resize * @param offset additional size offset in pixel @@ -1008,7 +1149,8 @@ default W posRel(float x, float y) { } /** - * Sets the relative position with an {@link Alignment}. Combines {@link #leftRel(float)} and {@link #topRel(float)}. + * Sets the relative position with an {@link Alignment}. Combines {@link #leftRel(float)} and + * {@link #topRel(float)}. * * @param alignment relative position * @return this @@ -1031,7 +1173,8 @@ default W size(int w, int h) { } /** - * Sets the relative width and height of this widget. Combines {@link #widthRel(float)} and {@link #heightRel(float)}. + * Sets the relative width and height of this widget. Combines {@link #widthRel(float)} and + * {@link #heightRel(float)}. * * @param w relative width * @param h relative height @@ -1053,7 +1196,8 @@ default W size(int val) { } /** - * Sets the relative width and height of this widget. Combines {@link #widthRel(float)} and {@link #heightRel(float)}. + * Sets the relative width and height of this widget. Combines {@link #widthRel(float)} and + * {@link #heightRel(float)}. * * @param val relative width and height * @return this @@ -1091,7 +1235,8 @@ default W full() { /** * Sets the anchor on the left side of the widget. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. * * @param val anchor on the left side * @return this @@ -1103,7 +1248,8 @@ default W anchorLeft(float val) { /** * Sets the anchor on the right side of the widget. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. * * @param val anchor on the right side * @return this @@ -1115,7 +1261,8 @@ default W anchorRight(float val) { /** * Sets the anchor on the top side of the widget. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. * * @param val anchor on the top side * @return this @@ -1127,7 +1274,8 @@ default W anchorTop(float val) { /** * Sets the anchor on the bottom side of the widget. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. * * @param val anchor on the bottom side * @return this diff --git a/src/main/java/brachy/modularui/api/widget/IWidget.java b/src/main/java/brachy/modularui/api/widget/IWidget.java index a5e9a204..dd0690a7 100644 --- a/src/main/java/brachy/modularui/api/widget/IWidget.java +++ b/src/main/java/brachy/modularui/api/widget/IWidget.java @@ -14,9 +14,8 @@ import brachy.modularui.widget.sizer.Area; import brachy.modularui.widget.sizer.StandardResizer; -import com.mojang.serialization.Codec; - import com.google.common.base.CharMatcher; +import com.mojang.serialization.Codec; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -74,7 +73,8 @@ default boolean hasParent() { /** * @return the panel this widget is in */ - @NotNull ModularPanel getPanel(); + @NotNull + ModularPanel getPanel(); /** * @return the area this widget occupies @@ -297,6 +297,7 @@ default WidgetThemeEntry getWidgetThemeEntry(ITheme theme) { /** * Gets the theme that is currently in use for this widget. + * * @return The gui theme. */ ITheme getTheme(); diff --git a/src/main/java/brachy/modularui/api/widget/Interactable.java b/src/main/java/brachy/modularui/api/widget/Interactable.java index 5618137c..39a89df0 100755 --- a/src/main/java/brachy/modularui/api/widget/Interactable.java +++ b/src/main/java/brachy/modularui/api/widget/Interactable.java @@ -4,10 +4,10 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.sounds.SoundEvents; -import com.mojang.blaze3d.platform.InputConstants; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.blaze3d.platform.InputConstants; import org.jetbrains.annotations.NotNull; import org.lwjgl.glfw.GLFW; @@ -22,8 +22,8 @@ public interface Interactable { * * @param button mouse button that was pressed. * @return result that determines what happens to other widgets - * {@link #onMouseTapped(int)} is only called if this returns {@link Result#ACCEPT} or - * {@link Result#SUCCESS} + * {@link #onMouseTapped(int)} is only called if this returns {@link Result#ACCEPT} or + * {@link Result#SUCCESS} */ @NotNull default Result onMousePressed(int button) { @@ -35,7 +35,7 @@ default Result onMousePressed(int button) { * * @param button mouse button that was released. * @return whether other widgets should get called to. If this returns false, - * {@link #onMouseTapped(int)} will NOT be called. + * {@link #onMouseTapped(int)} will NOT be called. */ default boolean onMouseReleased(int button) { return false; @@ -46,9 +46,9 @@ default boolean onMouseReleased(int button) { * * @param button mouse button that was pressed. * @return result that determines if other widgets should get tapped to - * {@link Result#IGNORE IGNORE} and {@link Result#ACCEPT ACCEPT} will both "ignore" the result and - * {@link Result#STOP STOP} and {@link Result#SUCCESS SUCCESS} will both stop other widgets - * from getting tapped. + * {@link Result#IGNORE IGNORE} and {@link Result#ACCEPT ACCEPT} will both "ignore" the result and + * {@link Result#STOP STOP} and {@link Result#SUCCESS SUCCESS} will both stop other widgets + * from getting tapped. */ @NotNull default Result onMouseTapped(int button) { @@ -62,8 +62,8 @@ default Result onMouseTapped(int button) { * @param scanCode character that was pressed. * @param modifiers any modifiers that were used. * @return result that determines what happens to other widgets - * {@link #onKeyTapped(int, int, int)} is only called if this returns {@link Result#ACCEPT} or - * {@link Result#SUCCESS} + * {@link #onKeyTapped(int, int, int)} is only called if this returns {@link Result#ACCEPT} or + * {@link Result#SUCCESS} */ @NotNull default Result onKeyPressed(int keyCode, int scanCode, int modifiers) { @@ -77,7 +77,7 @@ default Result onKeyPressed(int keyCode, int scanCode, int modifiers) { * @param scanCode character that was pressed. * @param modifiers any modifiers that were used. * @return whether other widgets should get called too. If this returns false, {@link #onKeyTapped(int, int, int)} - * will NOT be called. + * will NOT be called. */ default boolean onKeyReleased(int keyCode, int scanCode, int modifiers) { return false; @@ -90,8 +90,8 @@ default boolean onKeyReleased(int keyCode, int scanCode, int modifiers) { * @param scanCode character that was pressed. * @param modifiers any modifiers that were used. * @return result that determines if other widgets should get tapped to - * {@link Result#IGNORE} and {@link Result#ACCEPT} will both "ignore" the result and {@link Result#STOP} and - * {@link Result#SUCCESS} will both stop other widgets from getting tapped. + * {@link Result#IGNORE} and {@link Result#ACCEPT} will both "ignore" the result and {@link Result#STOP} and + * {@link Result#SUCCESS} will both stop other widgets from getting tapped. */ @NotNull default Result onKeyTapped(int keyCode, int scanCode, int modifiers) { @@ -104,8 +104,8 @@ default Result onKeyTapped(int keyCode, int scanCode, int modifiers) { * @param codePoint character that was typed * @param modifiers any modifiers that were used. * @return result that determines what happens to other widgets - * {@link #onKeyTapped(int, int, int)} is only called if this returns {@link Result#ACCEPT} or - * {@link Result#SUCCESS} + * {@link #onKeyTapped(int, int, int)} is only called if this returns {@link Result#ACCEPT} or + * {@link Result#SUCCESS} */ @NotNull default Result onCharTyped(char codePoint, int modifiers) { diff --git a/src/main/java/brachy/modularui/core/mixins/client/MinecraftMixin.java b/src/main/java/brachy/modularui/core/mixins/client/MinecraftMixin.java index 99eeb5f2..0eb0ea30 100755 --- a/src/main/java/brachy/modularui/core/mixins/client/MinecraftMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/client/MinecraftMixin.java @@ -30,7 +30,8 @@ public class MinecraftMixin { } } - @Inject(method = "setScreen", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/Screen;removed()V")) + @Inject(method = "setScreen", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/Screen;removed()V")) public void modularui$trackRealScreenClose(Screen guiScreen, CallbackInfo ci) { if (guiScreen == null) { // the ScreenEvent.Closing is also closed when the screen is transitioning to another screen, diff --git a/src/main/java/brachy/modularui/core/mixins/common/ComponentSerializerMixin.java b/src/main/java/brachy/modularui/core/mixins/common/ComponentSerializerMixin.java index 7e7fc859..cc73421f 100644 --- a/src/main/java/brachy/modularui/core/mixins/common/ComponentSerializerMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/common/ComponentSerializerMixin.java @@ -25,10 +25,11 @@ public class ComponentSerializerMixin { @WrapOperation( - method = "serialize(Lnet/minecraft/network/chat/Component;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/network/chat/Component$Serializer;serialize(Lnet/minecraft/network/chat/Component;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;")) - public JsonElement serialize(Component.Serializer instance, Component src, Type typeOfSrc, JsonSerializationContext context, Operation original) { + method = "serialize(Lnet/minecraft/network/chat/Component;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/network/chat/Component$Serializer;serialize(Lnet/minecraft/network/chat/Component;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;")) + public JsonElement serialize(Component.Serializer instance, Component src, Type typeOfSrc, + JsonSerializationContext context, Operation original) { if (src instanceof ModularComponent mc) { var d = ModularComponent.CODEC.mutableCodec().encodeJson(mc); var res = d.result(); @@ -38,10 +39,14 @@ public JsonElement serialize(Component.Serializer instance, Component src, Type return original.call(instance, src, typeOfSrc, context); } - @WrapOperation(method = "deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/minecraft/network/chat/MutableComponent;", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/chat/Component$Serializer;deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/minecraft/network/chat/MutableComponent;")) - public MutableComponent deserialize(Component.Serializer instance, JsonElement json, Type typeOfT, JsonDeserializationContext context, Operation original) { + @WrapOperation(method = "deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/minecraft/network/chat/MutableComponent;", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/network/chat/Component$Serializer;deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/minecraft/network/chat/MutableComponent;")) + public MutableComponent deserialize(Component.Serializer instance, JsonElement json, Type typeOfT, + JsonDeserializationContext context, Operation original) { MutableComponent comp = original.call(instance, json, typeOfT, context); - if (comp.getClass() == MutableComponent.class && json instanceof JsonObject jsonObj && ModularComponent.CODEC.hasAnyField(jsonObj)) { + if (comp.getClass() == MutableComponent.class && json instanceof JsonObject jsonObj && + ModularComponent.CODEC.hasAnyField(jsonObj)) { ModularComponent mc = comp.asModular(); var d = ModularComponent.CODEC.mutableCodec().parseJson(jsonObj, mc); var res = d.result(); diff --git a/src/main/java/brachy/modularui/core/mixins/common/TextColorMixin.java b/src/main/java/brachy/modularui/core/mixins/common/TextColorMixin.java index bf5109b5..be8c2a5d 100644 --- a/src/main/java/brachy/modularui/core/mixins/common/TextColorMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/common/TextColorMixin.java @@ -12,7 +12,8 @@ public class TextColorMixin { /** * @reason Minecraft uses Integer.parseInt which fails when alpha is specified because of signed vs. unsigned */ - @Redirect(method = "parseColor", at = @At(value = "INVOKE", target = "Ljava/lang/Integer;parseInt(Ljava/lang/String;I)I")) + @Redirect(method = "parseColor", + at = @At(value = "INVOKE", target = "Ljava/lang/Integer;parseInt(Ljava/lang/String;I)I")) private static int fixDecode(String s, int radix) { return (int) Long.parseLong(s, radix); } diff --git a/src/main/java/brachy/modularui/core/mixins/emi/EmiRenderHelperMixin.java b/src/main/java/brachy/modularui/core/mixins/emi/EmiRenderHelperMixin.java index d0cf4827..9b440e04 100644 --- a/src/main/java/brachy/modularui/core/mixins/emi/EmiRenderHelperMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/emi/EmiRenderHelperMixin.java @@ -14,7 +14,8 @@ public class EmiRenderHelperMixin { @Inject(method = "renderRecipe", - at = @At(value = "INVOKE", target = "Ldev/emi/emi/api/recipe/EmiRecipe;addWidgets(Ldev/emi/emi/api/widget/WidgetHolder;)V")) + at = @At(value = "INVOKE", + target = "Ldev/emi/emi/api/recipe/EmiRecipe;addWidgets(Ldev/emi/emi/api/widget/WidgetHolder;)V")) private static void modularui$tellTheRecipeItsInATooltip(EmiRecipe recipe, EmiDrawContext context, int x, int y, boolean showMissing, int overlayColor, CallbackInfo ci) { diff --git a/src/main/java/brachy/modularui/core/mixins/emi/RecipeScreenMixin.java b/src/main/java/brachy/modularui/core/mixins/emi/RecipeScreenMixin.java index 6380a572..c232eb4a 100644 --- a/src/main/java/brachy/modularui/core/mixins/emi/RecipeScreenMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/emi/RecipeScreenMixin.java @@ -16,7 +16,8 @@ @Mixin(value = RecipeScreen.class, remap = false) public class RecipeScreenMixin { - @Shadow private List currentPage; + @Shadow + private List currentPage; @Inject(method = "mouseScrolled", at = @At("HEAD"), remap = true, cancellable = true) private void mui$mouseScrolled(double mouseX, double mouseY, double amount, CallbackInfoReturnable cir) { @@ -45,7 +46,8 @@ public class RecipeScreenMixin { } @Inject(method = "mouseDragged", at = @At("HEAD"), remap = true, cancellable = true) - private void mui$mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY, CallbackInfoReturnable cir) { + private void mui$mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY, + CallbackInfoReturnable cir) { for (WidgetGroup group : currentPage) { for (Widget widget : group.widgets) { if (widget instanceof ModularUIEmiRecipe.UIWrapperWidget wrapperWidget) { @@ -56,5 +58,4 @@ public class RecipeScreenMixin { } } } - } diff --git a/src/main/java/brachy/modularui/core/mixins/jei/RecipeGuiLogicMixin.java b/src/main/java/brachy/modularui/core/mixins/jei/RecipeGuiLogicMixin.java index f1fe8357..3f72b280 100644 --- a/src/main/java/brachy/modularui/core/mixins/jei/RecipeGuiLogicMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/jei/RecipeGuiLogicMixin.java @@ -2,13 +2,12 @@ import brachy.modularui.integration.jei.recipe.ModularUIJeiCategory; +import net.minecraft.client.renderer.Rect2i; + import mezz.jei.api.gui.IRecipeLayoutDrawable; import mezz.jei.common.util.ImmutableSize2i; import mezz.jei.gui.recipes.IRecipeLayoutWithButtons; import mezz.jei.gui.recipes.RecipeGuiLogic; - -import net.minecraft.client.renderer.Rect2i; - import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; @@ -19,7 +18,8 @@ public class RecipeGuiLogicMixin { @ModifyArg(method = "getVisibleRecipeLayoutsWithButtons", - at = @At(value = "INVOKE", target = "Ljava/util/Optional;map(Ljava/util/function/Function;)Ljava/util/Optional;")) + at = @At(value = "INVOKE", + target = "Ljava/util/Optional;map(Ljava/util/function/Function;)Ljava/util/Optional;")) private Function, ImmutableSize2i> modularui$useCategoryMaxHeightForLayout(Function, ImmutableSize2i> original) { return layoutWithButtons -> { ImmutableSize2i size = original.apply(layoutWithButtons); @@ -30,7 +30,8 @@ public class RecipeGuiLogicMixin { int borderWidth = size.width() - area.getWidth(); // size.height() contains the layout's areaWithBorder.height int borderHeight = size.height() - area.getHeight(); - return new ImmutableSize2i(muiCategory.getMaxWidth() + borderWidth, muiCategory.getMaxHeight() + borderHeight); + return new ImmutableSize2i(muiCategory.getMaxWidth() + borderWidth, + muiCategory.getMaxHeight() + borderHeight); } return size; }; diff --git a/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutBuilderMixin.java b/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutBuilderMixin.java index 8d33fc53..f28803c1 100644 --- a/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutBuilderMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutBuilderMixin.java @@ -28,9 +28,9 @@ public abstract class RecipeLayoutBuilderMixin implements IRecipeLayoutBuilde @Shadow private @Final T recipe; - + private static final @Unique ThreadLocal modularui$currentRecipe = new ThreadLocal<>(); - + @Inject(method = "buildRecipeLayout", at = @At("HEAD")) private void modularui$setCurrentRecipe(IFocusGroup focuses, Collection> decorators, IScalableDrawable recipeBackground, int recipeBorderPadding, @@ -40,14 +40,16 @@ public abstract class RecipeLayoutBuilderMixin implements IRecipeLayoutBuilde @Inject(method = "buildRecipeLayout", at = @At("RETURN")) private void modularui$clearCurrentRecipe(IFocusGroup focuses, Collection> decorators, - IScalableDrawable recipeBackground, int recipeBorderPadding, - CallbackInfoReturnable>> cir) { + IScalableDrawable recipeBackground, int recipeBorderPadding, + CallbackInfoReturnable>> cir) { modularui$currentRecipe.remove(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @ModifyExpressionValue(method = { "createShapelessIcon", "getRecipeTransferButtonPosition" }, - at = @At(value = "INVOKE", target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getWidth()I"), require = 0) + at = @At(value = "INVOKE", + target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getWidth()I"), + require = 0) private static int modularui$makeWidthRecipeDependent(int original, @Local(argsOnly = true) IRecipeCategory recipeCategory) { if (recipeCategory instanceof ModularUIJeiCategory muiCategory) { @@ -58,7 +60,9 @@ public abstract class RecipeLayoutBuilderMixin implements IRecipeLayoutBuilde @SuppressWarnings({ "rawtypes", "unchecked" }) @ModifyExpressionValue(method = { "createShapelessIcon", "getRecipeTransferButtonPosition" }, - at = @At(value = "INVOKE", target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getHeight()I"), require = 0) + at = @At(value = "INVOKE", + target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getHeight()I"), + require = 0) private static int modularui$makeHeightRecipeDependent(int original, @Local(argsOnly = true) IRecipeCategory recipeCategory) { if (recipeCategory instanceof ModularUIJeiCategory muiCategory) { diff --git a/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutMixin.java b/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutMixin.java index 08e32cce..1cdd2ab4 100644 --- a/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutMixin.java @@ -10,7 +10,6 @@ import mezz.jei.api.gui.inputs.RecipeSlotUnderMouse; import mezz.jei.api.recipe.category.IRecipeCategory; import mezz.jei.library.gui.recipes.RecipeLayout; - import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -26,8 +25,10 @@ public abstract class RecipeLayoutMixin implements IRecipeLayoutDrawable { private @Final IRecipeCategory recipeCategory; @WrapOperation(method = "drawOverlays", - at = @At(value = "INVOKE", target = "Lmezz/jei/library/gui/recipes/RecipeLayout;getSlotUnderMouse(DD)Ljava/util/Optional;")) - private Optional modularui$disableIngredientTooltipRender(RecipeLayout self, double mouseX, double mouseY, + at = @At(value = "INVOKE", + target = "Lmezz/jei/library/gui/recipes/RecipeLayout;getSlotUnderMouse(DD)Ljava/util/Optional;")) + private Optional modularui$disableIngredientTooltipRender(RecipeLayout self, double mouseX, + double mouseY, Operation> original) { if (self.getRecipeCategory() instanceof ModularUIJeiCategory) { return Optional.empty(); @@ -36,7 +37,8 @@ public abstract class RecipeLayoutMixin implements IRecipeLayoutDrawable { } @ModifyExpressionValue(method = "", - at = @At(value = "INVOKE", target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getWidth()I"), + at = @At(value = "INVOKE", + target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getWidth()I"), require = 0) private int modularui$makeWidthRecipeDependent(int original, @Local(argsOnly = true) R recipe) { if (this.recipeCategory instanceof ModularUIJeiCategory muiCategory) { @@ -46,7 +48,8 @@ public abstract class RecipeLayoutMixin implements IRecipeLayoutDrawable { } @ModifyExpressionValue(method = "", - at = @At(value = "INVOKE", target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getHeight()I"), + at = @At(value = "INVOKE", + target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getHeight()I"), require = 0) private int modularui$makeHeightRecipeDependent(int original, @Local(argsOnly = true) R recipe) { if (this.recipeCategory instanceof ModularUIJeiCategory muiCategory) { diff --git a/src/main/java/brachy/modularui/core/mixins/rei/DefaultDisplayViewingScreenMixin.java b/src/main/java/brachy/modularui/core/mixins/rei/DefaultDisplayViewingScreenMixin.java index b684d8a7..3d8174dc 100644 --- a/src/main/java/brachy/modularui/core/mixins/rei/DefaultDisplayViewingScreenMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/rei/DefaultDisplayViewingScreenMixin.java @@ -1,7 +1,7 @@ package brachy.modularui.core.mixins.rei; -import brachy.modularui.integration.rei.recipe.ModularUIReiDisplay; import brachy.modularui.integration.rei.recipe.ModularUIReiCategory; +import brachy.modularui.integration.rei.recipe.ModularUIReiDisplay; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; @@ -34,7 +34,9 @@ protected DefaultDisplayViewingScreenMixin(Map, List category, Operation original, @Local(name = "display") Display display) { @@ -42,7 +44,8 @@ protected DefaultDisplayViewingScreenMixin(Map, List displaySupplier) { @@ -53,7 +56,8 @@ protected DefaultDisplayViewingScreenMixin(Map, List category, Display display, @Nullable ToIntFunction> originalValue) { - if (category instanceof ModularUIReiCategory muiCategory && display instanceof ModularUIReiDisplay muiDisplay) { + if (category instanceof ModularUIReiCategory muiCategory && + display instanceof ModularUIReiDisplay muiDisplay) { return ((ModularUIReiCategory) muiCategory).getDisplayHeight(muiDisplay); } else { // if this isn't a MUI display, set it back to the original value diff --git a/src/main/java/brachy/modularui/core/mixins/rei/EntryWidgetAccessor.java b/src/main/java/brachy/modularui/core/mixins/rei/EntryWidgetAccessor.java index 495f1187..20f5ec81 100644 --- a/src/main/java/brachy/modularui/core/mixins/rei/EntryWidgetAccessor.java +++ b/src/main/java/brachy/modularui/core/mixins/rei/EntryWidgetAccessor.java @@ -1,9 +1,8 @@ package brachy.modularui.core.mixins.rei; -import me.shedaniel.rei.impl.client.gui.widget.EntryWidget; - import net.minecraft.client.gui.GuiGraphics; +import me.shedaniel.rei.impl.client.gui.widget.EntryWidget; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; diff --git a/src/main/java/brachy/modularui/drawable/AdaptableUITexture.java b/src/main/java/brachy/modularui/drawable/AdaptableUITexture.java index 153670fd..ecc61f17 100644 --- a/src/main/java/brachy/modularui/drawable/AdaptableUITexture.java +++ b/src/main/java/brachy/modularui/drawable/AdaptableUITexture.java @@ -4,8 +4,8 @@ import net.minecraft.client.renderer.GameRenderer; import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import lombok.experimental.Accessors; import org.joml.Matrix4f; @@ -19,14 +19,18 @@ @Accessors(fluent = true) public class AdaptableUITexture extends UITexture { - @Getter private final int imageWidth, imageHeight, bl, bt, br, bb; - @Getter private final boolean tiled; + @Getter + private final int imageWidth, imageHeight, bl, bt, br, bb; + @Getter + private final boolean tiled; /** * Use {@link UITexture#builder()} with {@link Builder#adaptable(int, int)} */ - AdaptableUITexture(ResourceLocation location, float u0, float v0, float u1, float v1, ColorType colorType, boolean nonOpaque, - int colorOverride, int imageWidth, int imageHeight, int bl, int bt, int br, int bb, boolean tiled) { + AdaptableUITexture(ResourceLocation location, float u0, float v0, float u1, float v1, ColorType colorType, + boolean nonOpaque, + int colorOverride, int imageWidth, int imageHeight, int bl, int bt, int br, int bb, + boolean tiled) { super(location, u0, v0, u1, v1, colorType, nonOpaque, colorOverride); this.imageWidth = imageWidth; this.imageHeight = imageHeight; @@ -45,7 +49,8 @@ public AdaptableUITexture register(String name) { @Override public AdaptableUITexture getSubArea(float uStart, float vStart, float uEnd, float vEnd) { return new AdaptableUITexture(this.location, lerpU(uStart), lerpV(vStart), lerpU(uEnd), lerpV(vEnd), - this.colorType, this.nonOpaque, this.colorOverride, this.imageWidth, this.imageHeight, this.bl, this.bt, this.br, this.bb, + this.colorType, this.nonOpaque, this.colorOverride, this.imageWidth, this.imageHeight, this.bl, this.bt, + this.br, this.bb, this.tiled); } @@ -154,9 +159,11 @@ public void drawTiled(GuiContext context, float x, float y, float width, float h if ((this.bl > 0 || this.br > 0) && this.bt <= 0 && this.bb <= 0) { // left border - GuiDraw.drawTiledTexture(pose, x, y, this.bl, height, this.u0, this.v0, uInnerStart, this.v1, this.bl, th, 0); + GuiDraw.drawTiledTexture(pose, x, y, this.bl, height, this.u0, this.v0, uInnerStart, this.v1, this.bl, th, + 0); // right border - GuiDraw.drawTiledTexture(pose, x1 - this.br, y, this.br, height, uInnerEnd, this.v0, this.u1, this.v1, this.br, th, 0); + GuiDraw.drawTiledTexture(pose, x1 - this.br, y, this.br, height, uInnerEnd, this.v0, this.u1, this.v1, + this.br, th, 0); // center GuiDraw.drawTiledTexture(pose, x + this.bl, y, width - this.bl - this.br, height, uInnerStart, this.v0, uInnerEnd, this.v1, tw - this.bl - this.br, th, 0); diff --git a/src/main/java/brachy/modularui/drawable/Circle.java b/src/main/java/brachy/modularui/drawable/Circle.java index fd8efdbb..56054588 100644 --- a/src/main/java/brachy/modularui/drawable/Circle.java +++ b/src/main/java/brachy/modularui/drawable/Circle.java @@ -8,10 +8,10 @@ import brachy.modularui.utils.Interpolations; import brachy.modularui.utils.serialization.codec.MutableObjectCodec; -import com.mojang.serialization.Codec; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.ToString; diff --git a/src/main/java/brachy/modularui/drawable/ColorType.java b/src/main/java/brachy/modularui/drawable/ColorType.java index d850dfa9..da9afcfe 100755 --- a/src/main/java/brachy/modularui/drawable/ColorType.java +++ b/src/main/java/brachy/modularui/drawable/ColorType.java @@ -3,8 +3,8 @@ import brachy.modularui.theme.WidgetTheme; import net.minecraft.util.ExtraCodecs; -import com.mojang.serialization.Codec; +import com.mojang.serialization.Codec; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.Getter; diff --git a/src/main/java/brachy/modularui/drawable/CycleDrawable.java b/src/main/java/brachy/modularui/drawable/CycleDrawable.java index 2df9576e..8355996b 100644 --- a/src/main/java/brachy/modularui/drawable/CycleDrawable.java +++ b/src/main/java/brachy/modularui/drawable/CycleDrawable.java @@ -5,9 +5,8 @@ import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.serialization.codec.MutableObjectCodec; -import com.mojang.serialization.Codec; - import com.google.common.collect.Iterables; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -22,7 +21,8 @@ public class CycleDrawable implements IDrawable { public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(CycleDrawable::new) - .addOpt("drawables", CycleDrawable::drawables, CycleDrawable::getListDrawables, IDrawable.CODEC.listOf(), Collections.emptyList()) + .addOpt("drawables", CycleDrawable::drawables, CycleDrawable::getListDrawables, IDrawable.CODEC.listOf(), + Collections.emptyList()) .addOpt("cycleTime", CycleDrawable::cycleTime, CycleDrawable::cycleTime, Codec.INT, 1000) .build(); diff --git a/src/main/java/brachy/modularui/drawable/DrawableStack.java b/src/main/java/brachy/modularui/drawable/DrawableStack.java index a2cad6eb..2cc24488 100644 --- a/src/main/java/brachy/modularui/drawable/DrawableStack.java +++ b/src/main/java/brachy/modularui/drawable/DrawableStack.java @@ -6,10 +6,11 @@ import brachy.modularui.utils.serialization.codec.CodecUtil; import net.minecraft.util.ExtraCodecs; -import com.mojang.serialization.Codec; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; + import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -19,9 +20,9 @@ */ public record DrawableStack(IDrawable... drawables) implements IDrawable { - public static final Codec CODEC = ExtraCodecs.lazyInitializedCodec(() -> - CodecUtil.checkedEncoder(IDrawable.CODEC.listOf().xmap(DrawableStack::fromList, DrawableStack::toList), - d -> d instanceof DrawableStack)); + public static final Codec CODEC = ExtraCodecs.lazyInitializedCodec(() -> CodecUtil.checkedEncoder( + IDrawable.CODEC.listOf().xmap(DrawableStack::fromList, DrawableStack::toList), + d -> d instanceof DrawableStack)); public static final IDrawable[] EMPTY_BACKGROUND = {}; public static final DrawableStack EMPTY = new DrawableStack(EMPTY_BACKGROUND); diff --git a/src/main/java/brachy/modularui/drawable/FluidDrawable.java b/src/main/java/brachy/modularui/drawable/FluidDrawable.java index 20bbc03a..603c9c54 100644 --- a/src/main/java/brachy/modularui/drawable/FluidDrawable.java +++ b/src/main/java/brachy/modularui/drawable/FluidDrawable.java @@ -10,9 +10,9 @@ import net.minecraft.Util; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.material.Fluid; -import com.mojang.serialization.Codec; import net.minecraftforge.fluids.FluidStack; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -29,7 +29,8 @@ public class FluidDrawable implements IDrawable { public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(FluidDrawable::new) - .add("fluids", FluidDrawable::fluids, FluidDrawable::getFluidList, CodecUtil.listLike(FluidStack.CODEC)).alias("fluid") + .add("fluids", FluidDrawable::fluids, FluidDrawable::getFluidList, CodecUtil.listLike(FluidStack.CODEC)) + .alias("fluid") .addOpt("cycleTime", FluidDrawable::cycleTime, FluidDrawable::cycleTime, Codec.INT, 1000) .build(); diff --git a/src/main/java/brachy/modularui/drawable/GuiDraw.java b/src/main/java/brachy/modularui/drawable/GuiDraw.java index ccd9edf6..f2af00cb 100644 --- a/src/main/java/brachy/modularui/drawable/GuiDraw.java +++ b/src/main/java/brachy/modularui/drawable/GuiDraw.java @@ -30,6 +30,13 @@ import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.event.RenderTooltipEvent; +import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fluids.FluidStack; + import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; @@ -38,13 +45,6 @@ import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.RenderTooltipEvent; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fluids.FluidStack; - import org.jetbrains.annotations.Nullable; import org.joml.Matrix4d; import org.joml.Matrix4f; @@ -243,7 +243,8 @@ public static void drawRoundedRect(GuiGraphics graphics, float x0, float y0, flo /** * Set up the texture as a sampler differently depending on if it's part of the GUI atlas or not. *

- * If the texture is part of the GUI atlas, the atlas will be used for drawing and the UV coordinates will be scaled to the atlas texture.
+ * If the texture is part of the GUI atlas, the atlas will be used for drawing and the UV coordinates will be scaled + * to the atlas texture.
* If it's not part of the GUI atlas, nothing special is done. * * @param location the texture file's location, e.g. {@code "modularui:textures/gui/slot/item.png"} @@ -252,7 +253,7 @@ public static void drawRoundedRect(GuiGraphics graphics, float x0, float y0, flo * @param u1 u1 UV coordinate * @param v1 v1 UV coordinate * @return If texture is in the GUI atlas, rescaled UV coordinates {@code u0, v0, u1, v1}.
- * If not, the same coordinates that were passed in. + * If not, the same coordinates that were passed in. */ public static RectangleF setupTexture(ResourceLocation location, float u0, float v0, float u1, float v1) { TextureAtlasSprite sprite = GuiSpriteManager.getInstance() @@ -264,7 +265,8 @@ public static RectangleF setupTexture(ResourceLocation location, float u0, float // have to multiply by 16 here because of MC weirdness // REMOVE THE MULTIPLICATION IN 1.21!!! - return new RectangleF(sprite.getU(u0 * 16), sprite.getV(v0 * 16), sprite.getU(u1 * 16), sprite.getV(v1 * 16)); + return new RectangleF(sprite.getU(u0 * 16), sprite.getV(v0 * 16), sprite.getU(u1 * 16), + sprite.getV(v1 * 16)); } else { RenderSystem.setShaderTexture(0, location); return new RectangleF(u0, v0, u1, v1); @@ -273,7 +275,8 @@ public static RectangleF setupTexture(ResourceLocation location, float u0, float public static boolean isGuiAtlasSprite(ResourceLocation location) { location = GUI_TEXTURE_ID_CONVERTER.fileToId(location); - return GuiSpriteManager.getInstance().getSprite(location).atlasLocation() != MissingTextureAtlasSprite.getLocation(); + return GuiSpriteManager.getInstance().getSprite(location).atlasLocation() != + MissingTextureAtlasSprite.getLocation(); } public static void drawTexture(Matrix4f pose, ResourceLocation location, float x, float y, float w, float h, @@ -391,7 +394,8 @@ public static void drawTexture(Matrix4f pose, VertexConsumer buffer, float x0, f } public static void drawTiledTexture(Matrix4f pose, ResourceLocation location, float x, float y, float w, float h, - int u, int v, int tileWidth, int tileHeight, int textureWidth, int textureHeight, float z) { + int u, int v, int tileWidth, int tileHeight, int textureWidth, + int textureHeight, float z) { if (!isGuiAtlasSprite(location)) { RenderSystem.setShaderTexture(0, location); drawTiledTexture(pose, x, y, w, h, u, v, tileWidth, tileHeight, textureWidth, textureHeight, z); @@ -438,7 +442,8 @@ public static void drawTiledTexture(Matrix4f pose, ResourceLocation location, fl RectangleF newUvs = setupTexture(location, u0, v0, u1, v1); - drawTiledTexture(pose, x, y, w, h, newUvs.u0(), newUvs.v0(), newUvs.u1(), newUvs.v1(), textureWidth, textureHeight, z); + drawTiledTexture(pose, x, y, w, h, newUvs.u0(), newUvs.v0(), newUvs.u1(), newUvs.v1(), textureWidth, + textureHeight, z); RenderSystem.disableBlend(); } @@ -1043,7 +1048,8 @@ public static void drawText(GuiGraphics graphics, FormattedCharSequence text, fl @SuppressWarnings("UnstableApiUsage") public static void drawTooltipBackground(GuiContext context, ItemStack stack, List lines, - int x, int y, int textWidth, int height, @Nullable IRichTextBuilder tooltip) { + int x, int y, int textWidth, int height, + @Nullable IRichTextBuilder tooltip) { GuiGraphics graphics = context.getGraphics(); // TODO theme color diff --git a/src/main/java/brachy/modularui/drawable/GuiSpriteManager.java b/src/main/java/brachy/modularui/drawable/GuiSpriteManager.java index 5be6ba16..41827b48 100644 --- a/src/main/java/brachy/modularui/drawable/GuiSpriteManager.java +++ b/src/main/java/brachy/modularui/drawable/GuiSpriteManager.java @@ -13,7 +13,8 @@ * 1.21 has this class in vanilla, it can be used via {@code Minecraft.getGuiSprites()}.
* Here in 1.20 land, though, we have to implement it ourselves. *

- * Note that the atlas JSON should be kept, as MC 1.21 only adds textures in gui/sprites to the atlas. We want all of them. + * Note that the atlas JSON should be kept, as MC 1.21 only adds textures in gui/sprites to the atlas. We want + * all of them. */ public class GuiSpriteManager extends TextureAtlasHolder { @@ -45,5 +46,4 @@ public static GuiSpriteManager getInstance() { public @NotNull TextureAtlasSprite getSprite(@NotNull ResourceLocation location) { return super.getSprite(location); } - } diff --git a/src/main/java/brachy/modularui/drawable/GuiTextures.java b/src/main/java/brachy/modularui/drawable/GuiTextures.java index fde66650..a31ab1d4 100644 --- a/src/main/java/brachy/modularui/drawable/GuiTextures.java +++ b/src/main/java/brachy/modularui/drawable/GuiTextures.java @@ -205,8 +205,12 @@ public interface GuiTextures { UITexture ANIMATED_TEXTURE_TEST = UITexture.fullImage(ModularUI.id("gui/icons/animated_gradient")); - TabTexture TAB_TOP = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_top"), ColorType.DEFAULT), GuiAxis.Y, false, 28, 32, 4); - TabTexture TAB_BOTTOM = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_bottom"), ColorType.DEFAULT), GuiAxis.Y, true, 28, 32, 4); - TabTexture TAB_LEFT = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_left"), ColorType.DEFAULT), GuiAxis.X, false, 32, 28, 4); - TabTexture TAB_RIGHT = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_right"), ColorType.DEFAULT), GuiAxis.X, true, 32, 28, 4); + TabTexture TAB_TOP = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_top"), ColorType.DEFAULT), + GuiAxis.Y, false, 28, 32, 4); + TabTexture TAB_BOTTOM = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_bottom"), ColorType.DEFAULT), + GuiAxis.Y, true, 28, 32, 4); + TabTexture TAB_LEFT = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_left"), ColorType.DEFAULT), + GuiAxis.X, false, 32, 28, 4); + TabTexture TAB_RIGHT = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_right"), ColorType.DEFAULT), + GuiAxis.X, true, 32, 28, 4); } diff --git a/src/main/java/brachy/modularui/drawable/Icon.java b/src/main/java/brachy/modularui/drawable/Icon.java index b2d649ff..1bbb4cf1 100644 --- a/src/main/java/brachy/modularui/drawable/Icon.java +++ b/src/main/java/brachy/modularui/drawable/Icon.java @@ -9,10 +9,10 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import brachy.modularui.widget.sizer.Box; -import com.mojang.serialization.Codec; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; import lombok.Getter; /** @@ -29,11 +29,16 @@ public class Icon implements IIcon { .addOpt("margin", Icon::margin, Icon::getMargin, Box.CODEC, Box.ZERO) .build(); - @Getter private IDrawable drawable; - @Getter private int width = 0, height = 0; - @Getter private float aspectRatio = 0; - @Getter private Alignment alignment = Alignment.Center; - @Getter private final Box margin = new Box(); + @Getter + private IDrawable drawable; + @Getter + private int width = 0, height = 0; + @Getter + private float aspectRatio = 0; + @Getter + private Alignment alignment = Alignment.Center; + @Getter + private final Box margin = new Box(); private Icon() { this.drawable = IDrawable.EMPTY; diff --git a/src/main/java/brachy/modularui/drawable/InteractableIcon.java b/src/main/java/brachy/modularui/drawable/InteractableIcon.java index bd8e7578..6d0098bc 100644 --- a/src/main/java/brachy/modularui/drawable/InteractableIcon.java +++ b/src/main/java/brachy/modularui/drawable/InteractableIcon.java @@ -3,7 +3,6 @@ import brachy.modularui.api.drawable.IIcon; import brachy.modularui.api.widget.IGuiAction; import brachy.modularui.api.widget.Interactable; - import brachy.modularui.screen.viewport.GuiContext; import lombok.Getter; diff --git a/src/main/java/brachy/modularui/drawable/ItemDrawable.java b/src/main/java/brachy/modularui/drawable/ItemDrawable.java index f9789c4c..f5b02d0a 100755 --- a/src/main/java/brachy/modularui/drawable/ItemDrawable.java +++ b/src/main/java/brachy/modularui/drawable/ItemDrawable.java @@ -11,10 +11,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.ItemLike; -import com.mojang.serialization.Codec; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -31,7 +31,8 @@ public class ItemDrawable implements IDrawable { public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(ItemDrawable::new) - .add("items", ItemDrawable::items, ItemDrawable::getItemList, CodecUtil.listLike(ItemStack.CODEC)).alias("item") + .add("items", ItemDrawable::items, ItemDrawable::getItemList, CodecUtil.listLike(ItemStack.CODEC)) + .alias("item") .addOpt("cycleTime", ItemDrawable::cycleTime, ItemDrawable::cycleTime, Codec.INT, 1000) .build(); diff --git a/src/main/java/brachy/modularui/drawable/Rectangle.java b/src/main/java/brachy/modularui/drawable/Rectangle.java index d2a469b9..167ca9b7 100644 --- a/src/main/java/brachy/modularui/drawable/Rectangle.java +++ b/src/main/java/brachy/modularui/drawable/Rectangle.java @@ -1,6 +1,5 @@ package brachy.modularui.drawable; -import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.ModularUI; import brachy.modularui.animation.IAnimatable; import brachy.modularui.api.drawable.IDrawable; @@ -8,13 +7,14 @@ import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.Color; import brachy.modularui.utils.Interpolations; +import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.utils.serialization.codec.MutableObjectCodec; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.serialization.Codec; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -178,8 +178,10 @@ public final boolean equals(Object o) { if (!(o instanceof Rectangle rectangle)) return false; return cornerRadius == rectangle.cornerRadius && colorTL == rectangle.colorTL && colorTR == rectangle.colorTR && - colorBL == rectangle.colorBL && colorBR == rectangle.colorBR && cornerSegments == rectangle.cornerSegments && - Float.compare(borderThickness, rectangle.borderThickness) == 0 && canApplyTheme == rectangle.canApplyTheme; + colorBL == rectangle.colorBL && colorBR == rectangle.colorBR && + cornerSegments == rectangle.cornerSegments && + Float.compare(borderThickness, rectangle.borderThickness) == 0 && + canApplyTheme == rectangle.canApplyTheme; } @Override diff --git a/src/main/java/brachy/modularui/drawable/SchemaRenderer.java b/src/main/java/brachy/modularui/drawable/SchemaRenderer.java index 0afa5477..6e8a67e7 100755 --- a/src/main/java/brachy/modularui/drawable/SchemaRenderer.java +++ b/src/main/java/brachy/modularui/drawable/SchemaRenderer.java @@ -6,8 +6,8 @@ import brachy.modularui.drawable.schema.ISchema; import net.minecraft.world.phys.BlockHitResult; -import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.PoseStack; import lombok.Setter; import lombok.experimental.Accessors; import lombok.experimental.Tolerate; diff --git a/src/main/java/brachy/modularui/drawable/SubAreaDrawable.java b/src/main/java/brachy/modularui/drawable/SubAreaDrawable.java index b3c2592e..f9f058d8 100644 --- a/src/main/java/brachy/modularui/drawable/SubAreaDrawable.java +++ b/src/main/java/brachy/modularui/drawable/SubAreaDrawable.java @@ -8,13 +8,13 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import com.mojang.serialization.Codec; - import lombok.Getter; import org.jetbrains.annotations.Nullable; public class SubAreaDrawable extends DelegateDrawable { - public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(SubAreaDrawable::new) + public static final MutableObjectCodec CODEC = MutableObjectCodec + .drawableBuilder(SubAreaDrawable::new) .add("drawable", SubAreaDrawable::drawable, SubAreaDrawable::getWrappedDrawable, IDrawable.CODEC) .addOpt("u0", SubAreaDrawable::u0, SubAreaDrawable::getU0, Codec.FLOAT, 0f).alias("uStart") .addOpt("v0", SubAreaDrawable::v0, SubAreaDrawable::getV0, Codec.FLOAT, 0f).alias("vStart") @@ -35,7 +35,8 @@ public SubAreaDrawable(@Nullable IDrawable drawable) { @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { - context.getStencil().push(x + this.u0 * width, y + this.v0 * height, (this.u1 - this.u0) * width, (this.v1 - this.v0) * height); + context.getStencil().push(x + this.u0 * width, y + this.v0 * height, (this.u1 - this.u0) * width, + (this.v1 - this.v0) * height); super.draw(context, x, y, width, height, widgetTheme); context.getStencil().pop(); } diff --git a/src/main/java/brachy/modularui/drawable/TextureRegistry.java b/src/main/java/brachy/modularui/drawable/TextureRegistry.java index 1944fc85..fc7141e2 100644 --- a/src/main/java/brachy/modularui/drawable/TextureRegistry.java +++ b/src/main/java/brachy/modularui/drawable/TextureRegistry.java @@ -18,7 +18,9 @@ private static synchronized void registerTextureInternal(String name, UITexture UITexture current = TEXTURES.put(name, texture); REVERSE_TEXTURES.put(texture, name); if (current != null && (ModularUI.isDev() || ModularUIConfig.DEBUG_UI.get())) { - ModularUI.LOGGER.warn("[DEBUG] Replacing texture with name '{}' and location '{}' with texture with location '{}'", name, current.location, texture.location); + ModularUI.LOGGER.warn( + "[DEBUG] Replacing texture with name '{}' and location '{}' with texture with location '{}'", name, + current.location, texture.location); } } @@ -52,9 +54,12 @@ public static void registerTextureAutoName(UITexture texture) { number++; name = baseName + "_" + number; if (number == 20 && (ModularUI.isDev() || ModularUIConfig.DEBUG_UI.get())) { - ModularUI.LOGGER.warn("[DEBUG] Trying to register a UITexture with location '{}' for at least 20 times. This is likely a bug and should be fixed.", texture.location); + ModularUI.LOGGER.warn( + "[DEBUG] Trying to register a UITexture with location '{}' for at least 20 times. This is likely a bug and should be fixed.", + texture.location); } else if (number == 10000) { - throw new IllegalStateException("Trying to register a UITexture with location '" + texture.location + "' 10000 times."); + throw new IllegalStateException( + "Trying to register a UITexture with location '" + texture.location + "' 10000 times."); } } registerTexture(name, texture); diff --git a/src/main/java/brachy/modularui/drawable/TiledUITexture.java b/src/main/java/brachy/modularui/drawable/TiledUITexture.java index 55a0ae7a..db04aab6 100644 --- a/src/main/java/brachy/modularui/drawable/TiledUITexture.java +++ b/src/main/java/brachy/modularui/drawable/TiledUITexture.java @@ -4,8 +4,8 @@ import net.minecraft.client.renderer.GameRenderer; import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import lombok.experimental.Accessors; @@ -14,7 +14,8 @@ @Accessors(fluent = true) public class TiledUITexture extends UITexture { - @Getter private final int imageWidth, imageHeight; + @Getter + private final int imageWidth, imageHeight; /** * Use {@link UITexture#builder()} with {@link Builder#tiled()} @@ -45,7 +46,8 @@ public void draw(GuiContext context, float x, float y, float width, float height @Override protected TiledUITexture copy() { - return new TiledUITexture(location, u0, v0, u1, v1, colorType, nonOpaque, colorOverride, imageWidth, imageHeight); + return new TiledUITexture(location, u0, v0, u1, v1, colorType, nonOpaque, colorOverride, imageWidth, + imageHeight); } @Override diff --git a/src/main/java/brachy/modularui/drawable/UITexture.java b/src/main/java/brachy/modularui/drawable/UITexture.java index cb54aa6c..3b3cb724 100644 --- a/src/main/java/brachy/modularui/drawable/UITexture.java +++ b/src/main/java/brachy/modularui/drawable/UITexture.java @@ -12,12 +12,12 @@ import net.minecraft.resources.FileToIdConverter; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.ExtraCodecs; -import com.mojang.serialization.Codec; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.MapCodec; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.MapCodec; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -30,12 +30,15 @@ @Accessors(fluent = true, chain = true) public class UITexture implements IDrawable { - public static final MapCodec CODEC_FROM_BUILDER = Builder.CODEC.flatXmap(Builder::buildForCodec, t -> DataResult.success(t.toBuilder())); - public static final Codec CODEC_FROM_NAME = ExtraCodecs.stringResolverCodec(TextureRegistry::getTextureId, TextureRegistry::getTexture); + public static final MapCodec CODEC_FROM_BUILDER = Builder.CODEC.flatXmap(Builder::buildForCodec, + t -> DataResult.success(t.toBuilder())); + public static final Codec CODEC_FROM_NAME = ExtraCodecs + .stringResolverCodec(TextureRegistry::getTextureId, TextureRegistry::getTexture); public static final MapCodec CODEC = IDrawable.CODECS.register("texture", CodecUtil.chainedMapCodec(CODEC_FROM_NAME.fieldOf("name"), CODEC_FROM_BUILDER)); - public static final UITexture DEFAULT = fullImage(ResourceLocation.withDefaultNamespace("gui/options_background"), ColorType.DEFAULT); + public static final UITexture DEFAULT = fullImage(ResourceLocation.withDefaultNamespace("gui/options_background"), + ColorType.DEFAULT); public static final FileToIdConverter GUI_TEXTURE_ID_CONVERTER = new FileToIdConverter("textures/gui", ".png"); private static final ResourceLocation ICONS_LOCATION = ModularUI.id("textures/gui/icons.png"); @@ -61,13 +64,16 @@ static UITexture icon(String name, int x, int y) { @ToString.Include @Getter public final ResourceLocation location; - @Getter public final float u0, v0, u1, v1; + @Getter + public final float u0, v0, u1, v1; @Getter @Nullable public final ColorType colorType; - @Getter public final boolean nonOpaque; + @Getter + public final boolean nonOpaque; - @Getter protected int colorOverride = 0; + @Getter + protected int colorOverride = 0; /** * Creates a drawable texture @@ -94,7 +100,8 @@ public UITexture(ResourceLocation location, float u0, float v0, float u1, float * @param colorType a function to get which color from a widget theme should be used to color this texture. * @param nonOpaque whether the texture should draw with blend (if true) or not (if false) */ - public UITexture(ResourceLocation location, float u0, float v0, float u1, float v1, @Nullable ColorType colorType, boolean nonOpaque) { + public UITexture(ResourceLocation location, float u0, float v0, float u1, float v1, @Nullable ColorType colorType, + boolean nonOpaque) { this(location, u0, v0, u1, v1, colorType, nonOpaque, 0); } @@ -106,11 +113,13 @@ public UITexture(ResourceLocation location, float u0, float v0, float u1, float * @param v0 y offset of the image (0-1) * @param u1 x end offset of the image (0-1) * @param v1 y end offset of the image (0-1) - * @param colorType a function to get which color from a widget theme should be used to color this texture. Can be null. + * @param colorType a function to get which color from a widget theme should be used to color this texture. Can + * be null. * @param nonOpaque whether the texture should draw with blend (if true) or not (if false). * @param colorOverride color override for the texture in ARGB format. 0 means no override */ - public UITexture(ResourceLocation location, float u0, float v0, float u1, float v1, @Nullable ColorType colorType, boolean nonOpaque, int colorOverride) { + public UITexture(ResourceLocation location, float u0, float v0, float u1, float v1, @Nullable ColorType colorType, + boolean nonOpaque, int colorOverride) { this.colorType = colorType; boolean png = !location.getPath().endsWith(".png"); boolean textures = !location.getPath().startsWith("textures/"); @@ -268,7 +277,8 @@ public int hashCode() { } protected UITexture copy() { - return new UITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, this.nonOpaque, this.colorOverride); + return new UITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, this.nonOpaque, + this.colorOverride); } public UITexture withColorOverride(int color) { @@ -306,19 +316,29 @@ public static class Builder { .addOpt("colorOverride", Builder::colorOverride, Builder::getColorOverride, Codec.INT, 0) .build(); - @Getter private ResourceLocation location; + @Getter + private ResourceLocation location; @Getter @Setter private int iw = -1, ih = -1; - @Getter private int x, y, w, h; - @Getter private float u0 = 0, v0 = 0, u1 = 1, v1 = 1; - @Getter private Mode mode = Mode.FULL; - @Getter private int bl = 0, bt = 0, br = 0, bb = 0; - @Getter private String name; - @Getter private boolean tiled = false; - @Getter private ColorType colorType = null; - @Getter private boolean nonOpaque = false; - @Getter private int colorOverride = 0; + @Getter + private int x, y, w, h; + @Getter + private float u0 = 0, v0 = 0, u1 = 1, v1 = 1; + @Getter + private Mode mode = Mode.FULL; + @Getter + private int bl = 0, bt = 0, br = 0, bb = 0; + @Getter + private String name; + @Getter + private boolean tiled = false; + @Getter + private ColorType colorType = null; + @Getter + private boolean nonOpaque = false; + @Getter + private int colorOverride = 0; /** * @param loc location of the image to draw @@ -588,7 +608,8 @@ public UITexture build() { private DataResult buildForCodec() { // no error throwing and no drawable registration - return create().map(texture -> this.colorOverride != 0 ? texture.withColorOverride(this.colorOverride) : texture); + return create() + .map(texture -> this.colorOverride != 0 ? texture.withColorOverride(this.colorOverride) : texture); } private DataResult create() { @@ -602,9 +623,11 @@ private DataResult create() { this.v1 = 1; this.mode = Mode.RELATIVE; } else if (this.mode == Mode.PIXEL) { - if (this.iw <= 0 || this.ih <= 0) return DataResult.error(() -> "Image size must be > 0 for sub area via xywh or ltrb"); + if (this.iw <= 0 || this.ih <= 0) + return DataResult.error(() -> "Image size must be > 0 for sub area via xywh or ltrb"); if (this.x < 0 || this.y < 0 || this.w > this.iw || this.h > this.ih) { - return DataResult.error(() -> "X and Y must be > 0 and W and H must by smaller than the specified image size"); + return DataResult.error( + () -> "X and Y must be > 0 and W and H must by smaller than the specified image size"); } float tw = 1f / this.iw, th = 1f / this.ih; this.u0 = this.x * tw; @@ -620,15 +643,18 @@ private DataResult create() { if (this.bl > 0 || this.bt > 0 || this.br > 0 || this.bb > 0) { if (this.iw <= 0 || this.ih <= 0) return DataResult.error(() -> "Image size must be > 0 for adaptable textures (border > 0)"); - return DataResult.success(new AdaptableUITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, + return DataResult.success(new AdaptableUITexture(this.location, this.u0, this.v0, this.u1, this.v1, + this.colorType, this.nonOpaque, 0, this.iw, this.ih, this.bl, this.bt, this.br, this.bb, this.tiled)); } if (this.tiled) { - if (this.iw <= 0 || this.ih <= 0) return DataResult.error(() -> "Image size must be > 0 for tiled textures"); + if (this.iw <= 0 || this.ih <= 0) + return DataResult.error(() -> "Image size must be > 0 for tiled textures"); return DataResult.success(new TiledUITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, this.nonOpaque, 0, this.iw, this.ih)); } - return DataResult.success(new UITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, this.nonOpaque)); + return DataResult.success(new UITexture(this.location, this.u0, this.v0, this.u1, this.v1, + this.colorType, this.nonOpaque)); } return DataResult.error(() -> "Unknown error"); } diff --git a/src/main/java/brachy/modularui/drawable/graph/GraphAxis.java b/src/main/java/brachy/modularui/drawable/graph/GraphAxis.java index 31c4c758..882edb58 100644 --- a/src/main/java/brachy/modularui/drawable/graph/GraphAxis.java +++ b/src/main/java/brachy/modularui/drawable/graph/GraphAxis.java @@ -8,8 +8,8 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; -import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.blaze3d.vertex.VertexConsumer; import lombok.Getter; import org.jetbrains.annotations.ApiStatus; import org.joml.Matrix4f; diff --git a/src/main/java/brachy/modularui/drawable/graph/GraphDrawable.java b/src/main/java/brachy/modularui/drawable/graph/GraphDrawable.java index 9547dc8c..cf0a09ec 100644 --- a/src/main/java/brachy/modularui/drawable/graph/GraphDrawable.java +++ b/src/main/java/brachy/modularui/drawable/graph/GraphDrawable.java @@ -10,9 +10,9 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.RenderType; + import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexConsumer; - import lombok.Getter; import java.util.ArrayList; @@ -285,12 +285,16 @@ public GraphDrawable graphAspectRatio(float aspectRatio) { public final boolean equals(Object o) { if (!(o instanceof GraphDrawable that)) return false; - return backgroundColor == that.backgroundColor && Float.compare(majorTickThickness, that.majorTickThickness) == 0 && + return backgroundColor == that.backgroundColor && + Float.compare(majorTickThickness, that.majorTickThickness) == 0 && Float.compare(majorTickLength, that.majorTickLength) == 0 && Float.compare(minorTickThickness, that.minorTickThickness) == 0 && - Float.compare(minorTickLength, that.minorTickLength) == 0 && Float.compare(gridLineWidth, that.gridLineWidth) == 0 && - gridLineColor == that.gridLineColor && Float.compare(minorGridLineWidth, that.minorGridLineWidth) == 0 && - minorGridLineColor == that.minorGridLineColor && view.equals(that.view) && x.equals(that.x) && y.equals(that.y) && + Float.compare(minorTickLength, that.minorTickLength) == 0 && + Float.compare(gridLineWidth, that.gridLineWidth) == 0 && + gridLineColor == that.gridLineColor && + Float.compare(minorGridLineWidth, that.minorGridLineWidth) == 0 && + minorGridLineColor == that.minorGridLineColor && view.equals(that.view) && x.equals(that.x) && + y.equals(that.y) && plots.equals(that.plots); } diff --git a/src/main/java/brachy/modularui/drawable/graph/Plot.java b/src/main/java/brachy/modularui/drawable/graph/Plot.java index 7bf7fa19..b7182d05 100644 --- a/src/main/java/brachy/modularui/drawable/graph/Plot.java +++ b/src/main/java/brachy/modularui/drawable/graph/Plot.java @@ -1,17 +1,17 @@ package brachy.modularui.drawable.graph; -import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.api.GuiAxis; import brachy.modularui.drawable.GuiDraw; import brachy.modularui.utils.Color; import brachy.modularui.utils.Interpolations; +import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.utils.math.DAM; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.util.Mth; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; public class Plot { diff --git a/src/main/java/brachy/modularui/drawable/progress/AbstractProgressDrawable.java b/src/main/java/brachy/modularui/drawable/progress/AbstractProgressDrawable.java index 2a8257cd..754733bc 100644 --- a/src/main/java/brachy/modularui/drawable/progress/AbstractProgressDrawable.java +++ b/src/main/java/brachy/modularui/drawable/progress/AbstractProgressDrawable.java @@ -10,7 +10,8 @@ public abstract class AbstractProgressDrawable> extends BaseProgressDrawable { - @Getter private IDrawable filledTexture; + @Getter + private IDrawable filledTexture; @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { @@ -23,7 +24,8 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget if (p < 1f) context.getStencil().pop(); } - protected abstract void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme); + protected abstract void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme); /** * Sets the filled texture which is partially drawn based on the current progress. diff --git a/src/main/java/brachy/modularui/drawable/progress/BaseProgressDrawable.java b/src/main/java/brachy/modularui/drawable/progress/BaseProgressDrawable.java index 0594b1c8..5cd78bd1 100644 --- a/src/main/java/brachy/modularui/drawable/progress/BaseProgressDrawable.java +++ b/src/main/java/brachy/modularui/drawable/progress/BaseProgressDrawable.java @@ -16,9 +16,12 @@ public abstract class BaseProgressDrawable> implements IDrawable { - @Getter private IDrawable emptyBackground; - @Getter private DoubleSupplier progress; - @Getter protected float progressStepSize = 0; + @Getter + private IDrawable emptyBackground; + @Getter + private DoubleSupplier progress; + @Getter + protected float progressStepSize = 0; @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { @@ -84,7 +87,8 @@ public D progressDuration(long duration, TimeUnit unit) { /** * Sets a progress step size. The displayed progress will be clamped to the closest multiple of this value. - * Small values are smooth and high values are choppy. Values higher than 1 means the displayed progress is always 0. + * Small values are smooth and high values are choppy. Values higher than 1 means the displayed progress is always + * 0. * * @param progressStepSize progress step size * @return this. @@ -109,7 +113,6 @@ public D emptyTexture(IDrawable drawable) { return self(); } - @SuppressWarnings("unchecked") protected D self() { return (D) this; diff --git a/src/main/java/brachy/modularui/drawable/progress/CircularProgressDrawable.java b/src/main/java/brachy/modularui/drawable/progress/CircularProgressDrawable.java index 34e83105..1d8b56b3 100644 --- a/src/main/java/brachy/modularui/drawable/progress/CircularProgressDrawable.java +++ b/src/main/java/brachy/modularui/drawable/progress/CircularProgressDrawable.java @@ -2,29 +2,31 @@ import brachy.modularui.screen.viewport.GuiContext; import brachy.modularui.theme.WidgetTheme; - import brachy.modularui.utils.math.MathUtils; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.ShaderInstance; + import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; - import lombok.Getter; import org.joml.Matrix4f; /** - * A progress texture which translates the progress into a circular angle. This works with any {@link brachy.modularui.api.drawable.IDrawable}. + * A progress texture which translates the progress into a circular angle. This works with any + * {@link brachy.modularui.api.drawable.IDrawable}. */ public class CircularProgressDrawable extends AbstractProgressDrawable { - @Getter private Direction direction = Direction.CW; + @Getter + private Direction direction = Direction.CW; @Override - protected void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + protected void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme) { float p = progress; float angle = p * MathUtils.PI2; context.getStencil().push(() -> { @@ -139,6 +141,7 @@ public int hashCode() { } public enum Direction { - CW, CCW + CW, + CCW } } diff --git a/src/main/java/brachy/modularui/drawable/progress/CompositeProgress.java b/src/main/java/brachy/modularui/drawable/progress/CompositeProgress.java index ddefca73..c38f258f 100644 --- a/src/main/java/brachy/modularui/drawable/progress/CompositeProgress.java +++ b/src/main/java/brachy/modularui/drawable/progress/CompositeProgress.java @@ -4,7 +4,6 @@ import brachy.modularui.screen.viewport.GuiContext; import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.Rectangle; - import brachy.modularui.utils.math.MathUtils; import lombok.Getter; @@ -22,7 +21,8 @@ public class CompositeProgress extends BaseProgressDrawable { /** - * Creates a circle like, 4-slice progress bar. The texture is split into four quadrants which are drawn in either left, right, up + * Creates a circle like, 4-slice progress bar. The texture is split into four quadrants which are drawn in either + * left, right, up * or down direction. * * @param emptyTexture empty texture which is always displayed fully @@ -30,7 +30,8 @@ public class CompositeProgress extends BaseProgressDrawable { * @param direction clockwise or counterclockwise direction * @return progress drawable */ - public static CompositeProgress circularLike4Slice(IDrawable emptyTexture, IDrawable fullTexture, CircularProgressDrawable.Direction direction) { + public static CompositeProgress circularLike4Slice(IDrawable emptyTexture, IDrawable fullTexture, + CircularProgressDrawable.Direction direction) { CompositeProgress prog = new CompositeProgress().emptyTexture(emptyTexture); if (direction == CircularProgressDrawable.Direction.CCW) { prog.add(fullTexture, 0, 0, 0.5f, 0.5f, ProgressDrawable.Direction.DOWN, 0.25f) @@ -45,10 +46,10 @@ public static CompositeProgress circularLike4Slice(IDrawable emptyTexture, IDraw .add(fullTexture, 0, 0.5f, 0.5f, 1, ProgressDrawable.Direction.UP, 1f); } return prog; - } - @Getter private final List parts = new ArrayList<>(); + @Getter + private final List parts = new ArrayList<>(); private boolean dirty = true; @Override @@ -89,15 +90,17 @@ public CompositeProgress add(BaseProgressDrawable progress, float until, Unar return add(new Part(progress, until, area)); } - public CompositeProgress add(IDrawable filledTexture, float u0, float v0, float u1, float v1, ProgressDrawable.Direction direction, float untilProgress) { + public CompositeProgress add(IDrawable filledTexture, float u0, float v0, float u1, float v1, + ProgressDrawable.Direction direction, float untilProgress) { return add(filledTexture, u0, v0, u1, v1, direction, untilProgress, 0); } - public CompositeProgress add(IDrawable filledTexture, float u0, float v0, float u1, float v1, ProgressDrawable.Direction direction, float untilProgress, int progressPixelStep) { + public CompositeProgress add(IDrawable filledTexture, float u0, float v0, float u1, float v1, + ProgressDrawable.Direction direction, float untilProgress, int progressPixelStep) { return add(new ProgressDrawable() - .direction(direction) - .filledTexture(filledTexture.getSubArea(u0, v0, u1, v1)) - .progressPixelStepSize(progressPixelStep), + .direction(direction) + .filledTexture(filledTexture.getSubArea(u0, v0, u1, v1)) + .progressPixelStepSize(progressPixelStep), untilProgress, r -> { r.subArea(u0, v0, u1, v1); diff --git a/src/main/java/brachy/modularui/drawable/progress/ProgressDrawable.java b/src/main/java/brachy/modularui/drawable/progress/ProgressDrawable.java index 2ce74cbb..4428a4bc 100644 --- a/src/main/java/brachy/modularui/drawable/progress/ProgressDrawable.java +++ b/src/main/java/brachy/modularui/drawable/progress/ProgressDrawable.java @@ -8,16 +8,20 @@ import lombok.Getter; /** - * A standard progress drawable which can display a progress bar with any {@link brachy.modularui.api.drawable.IDrawable} + * A standard progress drawable which can display a progress bar with any + * {@link brachy.modularui.api.drawable.IDrawable} * in the directions left, right, up and down. */ public class ProgressDrawable extends AbstractProgressDrawable { - @Getter private Direction direction = Direction.RIGHT; - @Getter private float progressPixelStepSize = 0; + @Getter + private Direction direction = Direction.RIGHT; + @Getter + private float progressPixelStepSize = 0; @Override - public void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + public void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme) { float u0 = 0, u1 = 1, v0 = 0, v1 = 1; switch (this.direction) { case LEFT -> u0 = 1 - progress; @@ -32,7 +36,8 @@ public void pushProgressStencil(float progress, GuiContext context, int x, int y protected float getCurrentProgressStepSize(int width, int height) { float stepSize = this.progressStepSize; float pixelStepSize = this.progressPixelStepSize; - if (stepSize == 0 && pixelStepSize == 0 && !ModularUIConfig.smoothProgressBars() && getFilledTexture() instanceof UITexture) { + if (stepSize == 0 && pixelStepSize == 0 && !ModularUIConfig.smoothProgressBars() && + getFilledTexture() instanceof UITexture) { pixelStepSize = 1; } if (pixelStepSize > 0) { @@ -94,7 +99,8 @@ public ProgressDrawable down() { /** * Sets a progress step size. The displayed progress will be clamped to the closest multiple of this value. - * Small values are smooth and high values are choppy. Values higher than 1 means the displayed progress is always 0. + * Small values are smooth and high values are choppy. Values higher than 1 means the displayed progress is always + * 0. * * @param progressStepSize progress step size * @return this. diff --git a/src/main/java/brachy/modularui/drawable/schema/ArraySchema.java b/src/main/java/brachy/modularui/drawable/schema/ArraySchema.java index f79c3079..4f9f4161 100755 --- a/src/main/java/brachy/modularui/drawable/schema/ArraySchema.java +++ b/src/main/java/brachy/modularui/drawable/schema/ArraySchema.java @@ -252,7 +252,7 @@ public ArraySchema build() { validate(); BlockState[][][] blocks = new BlockState[this.tensor .size()][this.tensor.get(0).length][this.tensor.get(0)[0] - .length()]; + .length()]; for (int x = 0; x < this.tensor.size(); x++) { String[] xLayer = this.tensor.get(x); for (int y = 0; y < xLayer.length; y++) { diff --git a/src/main/java/brachy/modularui/drawable/schema/BaseSchemaRenderer.java b/src/main/java/brachy/modularui/drawable/schema/BaseSchemaRenderer.java index 327acbf3..5a8b11f5 100755 --- a/src/main/java/brachy/modularui/drawable/schema/BaseSchemaRenderer.java +++ b/src/main/java/brachy/modularui/drawable/schema/BaseSchemaRenderer.java @@ -44,6 +44,10 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; +import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; +import net.minecraftforge.client.model.data.ModelData; + +import com.google.common.collect.Lists; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.platform.Window; @@ -56,10 +60,6 @@ import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexSorting; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.client.model.data.ModelData; - -import com.google.common.collect.Lists; import it.unimi.dsi.fastutil.objects.ObjectArraySet; import it.unimi.dsi.fastutil.objects.Reference2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; @@ -97,12 +97,16 @@ public class BaseSchemaRenderer implements IDrawable { protected static final DummyLightTexture lightTexture = new DummyLightTexture(); - @Getter private final ISchema schema; + @Getter + private final ISchema schema; protected final RenderLevel renderLevel; protected final Viewport viewport = new Viewport(); - @Getter private final Camera camera = new Camera(); - @Getter private BlockHitResult lastRayTrace = null; - @Getter private RenderFilter renderFilter = RenderFilter.ALL; + @Getter + private final Camera camera = new Camera(); + @Getter + private BlockHitResult lastRayTrace = null; + @Getter + private RenderFilter renderFilter = RenderFilter.ALL; protected RenderCompileTask lastRenderCompileTask = null; protected final ChunkBufferBuilderPack chunkBufferBuilders; @@ -111,11 +115,13 @@ public class BaseSchemaRenderer implements IDrawable { protected boolean dirty = true; // projection * model view matrix - @Getter private final Matrix4f projection = new Matrix4f(); + @Getter + private final Matrix4f projection = new Matrix4f(); @Getter @Setter private boolean captureDebugInfo; - @Getter private final Vector3f openGLMousePos = new Vector3f(); + @Getter + private final Vector3f openGLMousePos = new Vector3f(); protected final List pos = new ArrayList<>(); public BaseSchemaRenderer(ISchema schema) { @@ -160,8 +166,9 @@ protected void recompile() { RenderCompileResults compileResults = new RenderCompileResults(); CompletableFuture.supplyAsync( - Util.wrapThreadWithTaskName("scm_chk_rebuild", () -> this.lastRenderCompileTask.compileBlockBuffers(compileResults)), - Util.backgroundExecutor()) + Util.wrapThreadWithTaskName("scm_chk_rebuild", + () -> this.lastRenderCompileTask.compileBlockBuffers(compileResults)), + Util.backgroundExecutor()) .thenCompose(Function.identity()) .whenComplete((result, error) -> { if (error != null) { @@ -269,8 +276,7 @@ public void drawBlockOutlines(MultiBufferSource.BufferSource bufferSource) { vc, p.getX(), p.getY(), p.getZ(), p.getX() + 1, p.getY() + 1, p.getZ() + 1, - 1f, 0f, 0f, 1f - ); + 1f, 0f, 0f, 1f); } } bufferSource.endBatch(RenderType.lines()); @@ -298,7 +304,6 @@ private RenderCompileResults checkRecompile() { // if we're still compiling, send previous result return res; - } @SuppressWarnings("deprecation") @@ -468,7 +473,8 @@ protected void renderBlocks(RenderCompileResults renderResult, RenderType render renderType.clearRenderState(); } - protected void renderBlockEntities(RenderCompileResults renderResult, MultiBufferSource bufferSource, float partialTick) { + protected void renderBlockEntities(RenderCompileResults renderResult, MultiBufferSource bufferSource, + float partialTick) { PoseStack poseStack = new PoseStack(); for (BlockEntity blockEntity : renderResult.blockEntities) { @@ -498,7 +504,8 @@ protected void handleBlockEntity(PoseStack poseStack, Mu protected void setupCamera(int width, int height) { // setup viewport and clear GL buffers int clearColor = getClearColor(); - RenderSystem.clearColor(Color.getRedF(clearColor), Color.getGreenF(clearColor), Color.getBlueF(clearColor), Color.getAlphaF(clearColor)); + RenderSystem.clearColor(Color.getRedF(clearColor), Color.getGreenF(clearColor), Color.getBlueF(clearColor), + Color.getAlphaF(clearColor)); RenderSystem.backupProjectionMatrix(); float near = 0.05f; @@ -565,7 +572,8 @@ protected BlockHitResult rayTrace(int mouseX, int mouseY, int width, int height) var p = e.getKey(); boolean reuseVec = this.pos.size() > i; var vec = reuseVec ? this.pos.get(i) : new Vector3f(); - vec = m.project(p.getX() + 0.5f, p.getY() + 0.5f, p.getZ() + 0.5f, this.viewport.getViewport(), vec); + vec = m.project(p.getX() + 0.5f, p.getY() + 0.5f, p.getZ() + 0.5f, this.viewport.getViewport(), + vec); if (reuseVec) this.pos.set(i, vec); else this.pos.add(vec); i++; @@ -613,7 +621,8 @@ public Vector3f screenToOpenGLPos(int x, int y, int width, int height, float dep return screenToOpenGLPos(x, y, width, height, depth, false, dest); } - private Vector3f screenToOpenGLPos(int x, int y, int width, int height, float depth, boolean readDepth, Vector3f dest) { + private Vector3f screenToOpenGLPos(int x, int y, int width, int height, float depth, boolean readDepth, + Vector3f dest) { this.viewport.rescaleToViewport(x, y, width, height, dest); if (readDepth) depth = MatrixUtils.readDepth((int) dest.x, (int) dest.y); dest.z = depth; @@ -621,7 +630,8 @@ private Vector3f screenToOpenGLPos(int x, int y, int width, int height, float de } public Vector3f screenToWorldPos(int x, int y, int screenWidth, int screenHeight) { - return screenToWorldPos(projection(), screenToOpenGLPos(x, y, screenWidth, screenHeight, new Vector3f()), new Vector3f()); + return screenToWorldPos(projection(), screenToOpenGLPos(x, y, screenWidth, screenHeight, new Vector3f()), + new Vector3f()); } private Vector3f screenToWorldPos(Matrix4f projection, Vector3f openGLPos) { @@ -679,7 +689,8 @@ public void updateRenderFilter(RenderFilter renderFilter) { public boolean equals(Object o) { if (!(o instanceof BaseSchemaRenderer that)) return false; - return this.schema.equals(that.schema) && this.renderLevel.equals(that.renderLevel) && this.camera.equals(that.camera) && + return this.schema.equals(that.schema) && this.renderLevel.equals(that.renderLevel) && + this.camera.equals(that.camera) && Objects.equals(this.viewport, that.viewport) && Objects.equals(this.renderFilter, that.renderFilter); } @@ -834,7 +845,8 @@ protected CompletableFuture compileBlockBuffers(RenderComp }); } - protected CompletableFuture uploadChunkLayer(RenderCompileResults results, BufferBuilder.RenderedBuffer builder, + protected CompletableFuture uploadChunkLayer(RenderCompileResults results, + BufferBuilder.RenderedBuffer builder, RenderType renderType) { return CompletableFuture.runAsync(() -> { VertexBuffer buffer = results.getOrCreateChunkBuffers().get(renderType); diff --git a/src/main/java/brachy/modularui/drawable/schema/BlockHighlight.java b/src/main/java/brachy/modularui/drawable/schema/BlockHighlight.java index fd686a39..a7f81b0b 100755 --- a/src/main/java/brachy/modularui/drawable/schema/BlockHighlight.java +++ b/src/main/java/brachy/modularui/drawable/schema/BlockHighlight.java @@ -7,6 +7,7 @@ import net.minecraft.core.Direction; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; + import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; @@ -14,7 +15,6 @@ import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; - import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -32,12 +32,12 @@ public class BlockHighlight { static { int[][] intVertices = { - {1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0}, - {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0}, - {0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0}, - {0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1}, - {0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0}, - {1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0} + { 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0 }, + { 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0 }, + { 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1 }, + { 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0 }, + { 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0 } }; for (int i = 0; i < 6; i++) { for (int j = 0; j < 12; j++) { diff --git a/src/main/java/brachy/modularui/drawable/schema/BoxSchema.java b/src/main/java/brachy/modularui/drawable/schema/BoxSchema.java index 328b877c..5fedd335 100755 --- a/src/main/java/brachy/modularui/drawable/schema/BoxSchema.java +++ b/src/main/java/brachy/modularui/drawable/schema/BoxSchema.java @@ -43,7 +43,8 @@ public BlockPos getOrigin() { public boolean equals(Object o) { if (!(o instanceof BoxSchema entries)) return false; - return level.equals(entries.level) && min.equals(entries.min) && max.equals(entries.max) && center.equals(entries.center); + return level.equals(entries.level) && min.equals(entries.min) && max.equals(entries.max) && + center.equals(entries.center); } @Override diff --git a/src/main/java/brachy/modularui/drawable/schema/DummyLightTexture.java b/src/main/java/brachy/modularui/drawable/schema/DummyLightTexture.java index e83dd799..b94aeb08 100755 --- a/src/main/java/brachy/modularui/drawable/schema/DummyLightTexture.java +++ b/src/main/java/brachy/modularui/drawable/schema/DummyLightTexture.java @@ -6,9 +6,9 @@ import net.minecraft.util.Mth; import net.minecraft.world.level.LevelTimeAccess; import net.minecraft.world.level.lighting.LightEngine; + import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; - import org.joml.Vector3f; import org.joml.Vector3fc; import org.lwjgl.opengl.GL11; diff --git a/src/main/java/brachy/modularui/drawable/schema/LiquidVertexConsumer.java b/src/main/java/brachy/modularui/drawable/schema/LiquidVertexConsumer.java index 42c83bba..a214910a 100755 --- a/src/main/java/brachy/modularui/drawable/schema/LiquidVertexConsumer.java +++ b/src/main/java/brachy/modularui/drawable/schema/LiquidVertexConsumer.java @@ -3,9 +3,9 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.SectionPos; + import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; - import org.joml.Matrix3f; import org.joml.Matrix4f; diff --git a/src/main/java/brachy/modularui/drawable/schema/MapSchema.java b/src/main/java/brachy/modularui/drawable/schema/MapSchema.java index 28579fa7..c3671544 100755 --- a/src/main/java/brachy/modularui/drawable/schema/MapSchema.java +++ b/src/main/java/brachy/modularui/drawable/schema/MapSchema.java @@ -83,7 +83,8 @@ public Vector3fc getFocus() { public Iterator> iterator() { return new AbstractIterator<>() { - private final ObjectIterator> it = blocks.long2ReferenceEntrySet().fastIterator(); + private final ObjectIterator> it = blocks.long2ReferenceEntrySet() + .fastIterator(); @Override protected Map.Entry computeNext() { diff --git a/src/main/java/brachy/modularui/drawable/schema/PosListSchema.java b/src/main/java/brachy/modularui/drawable/schema/PosListSchema.java index 1bb80609..94db9d6c 100755 --- a/src/main/java/brachy/modularui/drawable/schema/PosListSchema.java +++ b/src/main/java/brachy/modularui/drawable/schema/PosListSchema.java @@ -2,19 +2,15 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import lombok.Getter; -import lombok.Setter; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import java.util.Iterator; import java.util.Map; -import java.util.Objects; -import java.util.function.BiPredicate; public abstract class PosListSchema implements ISchema { diff --git a/src/main/java/brachy/modularui/drawable/schema/RenderLevel.java b/src/main/java/brachy/modularui/drawable/schema/RenderLevel.java index 94eb5491..a0aed1d9 100644 --- a/src/main/java/brachy/modularui/drawable/schema/RenderLevel.java +++ b/src/main/java/brachy/modularui/drawable/schema/RenderLevel.java @@ -30,13 +30,15 @@ import org.jetbrains.annotations.Nullable; import java.util.List; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class RenderLevel implements LevelTimeAccess { - @Getter private final ISchema schema; + @Getter + private final ISchema schema; private final Level level; private final RenderFilter renderFilter; private final Thread thread; diff --git a/src/main/java/brachy/modularui/drawable/schema/SchemaLevel.java b/src/main/java/brachy/modularui/drawable/schema/SchemaLevel.java index cc34a844..7d4d2668 100755 --- a/src/main/java/brachy/modularui/drawable/schema/SchemaLevel.java +++ b/src/main/java/brachy/modularui/drawable/schema/SchemaLevel.java @@ -32,7 +32,6 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkSource; import net.minecraft.world.level.chunk.DataLayer; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.dimension.BuiltinDimensionTypes; @@ -62,6 +61,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Stream; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault diff --git a/src/main/java/brachy/modularui/drawable/schema/Viewport.java b/src/main/java/brachy/modularui/drawable/schema/Viewport.java index 4d03251a..1433081d 100644 --- a/src/main/java/brachy/modularui/drawable/schema/Viewport.java +++ b/src/main/java/brachy/modularui/drawable/schema/Viewport.java @@ -2,9 +2,9 @@ import net.minecraft.client.Minecraft; import net.minecraft.util.Mth; + import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.systems.RenderSystem; - import lombok.Getter; import org.joml.Vector3f; @@ -12,7 +12,8 @@ public class Viewport { - @Getter private final int[] viewport = new int[4]; + @Getter + private final int[] viewport = new int[4]; public void setX(int x) { this.viewport[0] = x; @@ -81,7 +82,8 @@ public float unscaleYFromViewport(float viewportY, float nonViewportHeight) { return (1f - ((viewportY - getY()) / (float) getH())) * nonViewportHeight; } - public Vector3f unscaleFromViewport(float viewportX, float viewportY, float nonViewportWidth, float nonViewportHeight, Vector3f dest) { + public Vector3f unscaleFromViewport(float viewportX, float viewportY, float nonViewportWidth, + float nonViewportHeight, Vector3f dest) { dest.x = unscaleXFromViewport(viewportX, nonViewportWidth); dest.y = unscaleYFromViewport(viewportY, nonViewportHeight); return dest; diff --git a/src/main/java/brachy/modularui/drawable/text/AnimatedText.java b/src/main/java/brachy/modularui/drawable/text/AnimatedText.java index d909a391..9531b6d7 100644 --- a/src/main/java/brachy/modularui/drawable/text/AnimatedText.java +++ b/src/main/java/brachy/modularui/drawable/text/AnimatedText.java @@ -2,127 +2,130 @@ // TODO turn into ComponentsContents /* -@Accessors(fluent = true, chain = true) -public class AnimatedText extends StyledText { - - private MutableComponent full; - private String fullString; - private String currentString = ""; - private int currentIndex; - /** - * How fast the characters appear - *//* - @Setter - private int speed = 40; // ms per char - private long timeLastDraw; - @Setter - private boolean forward = true; - - private boolean isAnimating = false; - - public AnimatedText(IKey key) { - super(key); - } - - @Override - public MutableComponent get() { - return Component.literal(this.currentString); - } - - public void reset() { - this.full = null; - } - - private void advance() { - if (!this.isAnimating || (this.forward && this.currentIndex >= this.fullString.length()) || - (!this.forward && this.currentIndex < 0)) - return; - long time = Util.getMillis(); - int amount = (int) ((time - this.timeLastDraw) / this.speed); - if (amount == 0) return; - if (this.forward) { - int max = Math.min(this.fullString.length() - 1, this.currentIndex + amount); - this.currentIndex = Math.max(this.currentIndex, 0); - for (int i = this.currentIndex; i < max; i++) { - char c = this.fullString.charAt(i); - if (c == ' ') { - max = Math.min(this.fullString.length() - 1, max + 1); - } - // noinspection StringConcatenationInLoop - this.currentString += c; - } - this.currentIndex = max; - } else { - int min = Math.max(0, this.currentIndex - amount); - this.currentIndex = Math.min(this.currentIndex, this.currentString.length() - 1); - for (int i = this.currentIndex; i >= min; i--) { - char c = this.fullString.charAt(i); - if (c == ' ') { - min = Math.max(0, min - 1); - } - this.currentString = this.currentString.substring(0, i); - } - this.currentIndex = min; - } - this.timeLastDraw += (long) amount * this.speed; - } - - @OnlyIn(Dist.CLIENT) - @Override - public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { - if (this.full == null || !this.full.equals(super.get())) { - if (this.isAnimating) { - this.full = super.get(); - this.fullString = this.full.getString(); - this.currentString = this.forward ? "" : this.fullString; - this.currentIndex = this.forward ? 0 : this.fullString.length() - 1; - this.timeLastDraw = Util.getMillis(); - } else { - this.currentString = this.forward ? "" : this.fullString; - } - } - advance(); - if (this.currentString.isEmpty()) return; - super.draw(context, x, y, width, height, widgetTheme); - } - - public AnimatedText startAnimation() { - this.isAnimating = true; - return this; - } - - public AnimatedText stopAnimation() { - this.isAnimating = false; - return this; - } - - @Override - public @NotNull AnimatedText style(ChatFormatting formatting) { - return (AnimatedText) super.style(formatting); - } - - @Override - public @NotNull AnimatedText alignment(Alignment alignment) { - return (AnimatedText) super.alignment(alignment); - } - - @Override - public @NotNull AnimatedText color(int color) { - return color(() -> color); - } - - @Override - public @NotNull AnimatedText color(@Nullable IntSupplier color) { - return (AnimatedText) super.color(color); - } - - @Override - public @NotNull AnimatedText scale(float scale) { - return (AnimatedText) super.scale(scale); - } - - @Override - public @NotNull AnimatedText shadow(@Nullable Boolean shadow) { - return (AnimatedText) super.shadow(shadow); - } -}*/ + * @Accessors(fluent = true, chain = true) + * public class AnimatedText extends StyledText { + * + * private MutableComponent full; + * private String fullString; + * private String currentString = ""; + * private int currentIndex; + * /** + * How fast the characters appear + *//* + * @Setter + * private int speed = 40; // ms per char + * private long timeLastDraw; + * + * @Setter + * private boolean forward = true; + * + * private boolean isAnimating = false; + * + * public AnimatedText(IKey key) { + * super(key); + * } + * + * @Override + * public MutableComponent get() { + * return Component.literal(this.currentString); + * } + * + * public void reset() { + * this.full = null; + * } + * + * private void advance() { + * if (!this.isAnimating || (this.forward && this.currentIndex >= this.fullString.length()) || + * (!this.forward && this.currentIndex < 0)) + * return; + * long time = Util.getMillis(); + * int amount = (int) ((time - this.timeLastDraw) / this.speed); + * if (amount == 0) return; + * if (this.forward) { + * int max = Math.min(this.fullString.length() - 1, this.currentIndex + amount); + * this.currentIndex = Math.max(this.currentIndex, 0); + * for (int i = this.currentIndex; i < max; i++) { + * char c = this.fullString.charAt(i); + * if (c == ' ') { + * max = Math.min(this.fullString.length() - 1, max + 1); + * } + * // noinspection StringConcatenationInLoop + * this.currentString += c; + * } + * this.currentIndex = max; + * } else { + * int min = Math.max(0, this.currentIndex - amount); + * this.currentIndex = Math.min(this.currentIndex, this.currentString.length() - 1); + * for (int i = this.currentIndex; i >= min; i--) { + * char c = this.fullString.charAt(i); + * if (c == ' ') { + * min = Math.max(0, min - 1); + * } + * this.currentString = this.currentString.substring(0, i); + * } + * this.currentIndex = min; + * } + * this.timeLastDraw += (long) amount * this.speed; + * } + * + * @OnlyIn(Dist.CLIENT) + * + * @Override + * public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + * if (this.full == null || !this.full.equals(super.get())) { + * if (this.isAnimating) { + * this.full = super.get(); + * this.fullString = this.full.getString(); + * this.currentString = this.forward ? "" : this.fullString; + * this.currentIndex = this.forward ? 0 : this.fullString.length() - 1; + * this.timeLastDraw = Util.getMillis(); + * } else { + * this.currentString = this.forward ? "" : this.fullString; + * } + * } + * advance(); + * if (this.currentString.isEmpty()) return; + * super.draw(context, x, y, width, height, widgetTheme); + * } + * + * public AnimatedText startAnimation() { + * this.isAnimating = true; + * return this; + * } + * + * public AnimatedText stopAnimation() { + * this.isAnimating = false; + * return this; + * } + * + * @Override + * public @NotNull AnimatedText style(ChatFormatting formatting) { + * return (AnimatedText) super.style(formatting); + * } + * + * @Override + * public @NotNull AnimatedText alignment(Alignment alignment) { + * return (AnimatedText) super.alignment(alignment); + * } + * + * @Override + * public @NotNull AnimatedText color(int color) { + * return color(() -> color); + * } + * + * @Override + * public @NotNull AnimatedText color(@Nullable IntSupplier color) { + * return (AnimatedText) super.color(color); + * } + * + * @Override + * public @NotNull AnimatedText scale(float scale) { + * return (AnimatedText) super.scale(scale); + * } + * + * @Override + * public @NotNull AnimatedText shadow(@Nullable Boolean shadow) { + * return (AnimatedText) super.shadow(shadow); + * } + * } + */ diff --git a/src/main/java/brachy/modularui/drawable/text/ComposedLine.java b/src/main/java/brachy/modularui/drawable/text/ComposedLine.java index 16619549..ba57ff23 100755 --- a/src/main/java/brachy/modularui/drawable/text/ComposedLine.java +++ b/src/main/java/brachy/modularui/drawable/text/ComposedLine.java @@ -53,7 +53,9 @@ public void draw(GuiContext context, Font font, float x, float y, int color, boo } x += w; } else if (o != null) { - throw new IllegalArgumentException("ComposedLine objects must either be a FormattedCharSequence or an IIcon, but found a " + o.getClass().getSimpleName() + "!"); + throw new IllegalArgumentException( + "ComposedLine objects must either be a FormattedCharSequence or an IIcon, but found a " + + o.getClass().getSimpleName() + "!"); } } } diff --git a/src/main/java/brachy/modularui/drawable/text/DynamicComponent.java b/src/main/java/brachy/modularui/drawable/text/DynamicComponent.java index e83af5fc..317cd47a 100644 --- a/src/main/java/brachy/modularui/drawable/text/DynamicComponent.java +++ b/src/main/java/brachy/modularui/drawable/text/DynamicComponent.java @@ -26,7 +26,8 @@ public class DynamicComponent implements Component, IDrawable { private long time = -1; private final Supplier supplier; private Style style = Style.EMPTY; - @Getter private float scale = 1f; + @Getter + private float scale = 1f; private Component lastComp; public DynamicComponent(Supplier supplier) { diff --git a/src/main/java/brachy/modularui/drawable/text/FontRenderHelper.java b/src/main/java/brachy/modularui/drawable/text/FontRenderHelper.java index 5a20e009..e6f36b23 100755 --- a/src/main/java/brachy/modularui/drawable/text/FontRenderHelper.java +++ b/src/main/java/brachy/modularui/drawable/text/FontRenderHelper.java @@ -65,12 +65,14 @@ public static int getDefaultTextHeight() { } @OnlyIn(Dist.CLIENT) - public static void drawComponent(Component comp, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + public static void drawComponent(Component comp, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme) { drawComponent(comp, context, x, y, width, height, widgetTheme, 1f); } @OnlyIn(Dist.CLIENT) - public static void drawComponent(Component comp, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme, float scale) { + public static void drawComponent(Component comp, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme, float scale) { Text.renderer.setAlignment(Alignment.CENTER, width, height); Text.renderer.setColor(widgetTheme.getTextColor()); Text.renderer.setScale(scale); @@ -249,11 +251,13 @@ public interface StyleSink { } private static boolean feedChar(Style style, FormattedCharSink sink, int position, char character) { - return Character.isSurrogate(character) ? sink.accept(position, style, 65533) : sink.accept(position, style, character); + return Character.isSurrogate(character) ? sink.accept(position, style, 65533) : + sink.accept(position, style, character); } /** - * Copied and edited from {@link net.minecraft.util.StringDecomposer#iterateFormatted(String, int, Style, Style, FormattedCharSink)}. + * Copied and edited from + * {@link net.minecraft.util.StringDecomposer#iterateFormatted(String, int, Style, Style, FormattedCharSink)}. */ public static boolean iterateFormatted(String text, int skip, Style currentStyle, Style defaultStyle, FormattedCharSink sink, StyleSink styleSink) { @@ -272,7 +276,8 @@ public static boolean iterateFormatted(String text, int skip, Style currentStyle char c1 = text.charAt(j + 1); ChatFormatting chatformatting = ChatFormatting.getByCode(c1); if (chatformatting != null) { - style = chatformatting == ChatFormatting.RESET ? defaultStyle : style.applyLegacyFormat(chatformatting); + style = chatformatting == ChatFormatting.RESET ? defaultStyle : + style.applyLegacyFormat(chatformatting); styleChanged = true; } diff --git a/src/main/java/brachy/modularui/drawable/text/ModularComponent.java b/src/main/java/brachy/modularui/drawable/text/ModularComponent.java index b18d92f9..e9cae410 100644 --- a/src/main/java/brachy/modularui/drawable/text/ModularComponent.java +++ b/src/main/java/brachy/modularui/drawable/text/ModularComponent.java @@ -7,8 +7,6 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import brachy.modularui.widgets.TextWidget; -import com.demonwav.mcdev.annotations.Translatable; - import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.ComponentContents; @@ -23,8 +21,9 @@ import net.minecraft.network.chat.contents.SelectorContents; import net.minecraft.network.chat.contents.TranslatableContents; import net.minecraft.util.ExtraCodecs; -import com.mojang.serialization.Codec; +import com.demonwav.mcdev.annotations.Translatable; +import com.mojang.serialization.Codec; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -38,9 +37,11 @@ public class ModularComponent extends MutableComponent implements Text { - public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(ModularComponent.class, "Text") + public static final MutableObjectCodec CODEC = MutableObjectCodec + .drawableBuilder(ModularComponent.class, "Text") .wrapped(ExtraCodecs.COMPONENT.xmap(ModularComponent::of, mc -> mc)) - .addOpt("alignment", ModularComponent::alignment, ModularComponent::getAlignment, Alignment.CODEC, Alignment.Center) + .addOpt("alignment", ModularComponent::alignment, ModularComponent::getAlignment, Alignment.CODEC, + Alignment.Center) .addOpt("scale", ModularComponent::scale, ModularComponent::getScale, Codec.FLOAT, 1f) .addOpt("shadow", ModularComponent::shadow, ModularComponent::getShadow, Codec.BOOL, null) .addUnencodable("dynamicColor", ModularComponent::color, ModularComponent::getDynamicColor) @@ -62,7 +63,8 @@ public static ModularComponent translatableWithFallback(@Translatable String key return ModularComponent.create(new TranslatableContents(key, fallback, TranslatableContents.NO_ARGS)); } - public static ModularComponent translatableWithFallback(@Translatable String key, @Nullable String fallback, Object... args) { + public static ModularComponent translatableWithFallback(@Translatable String key, @Nullable String fallback, + Object... args) { return ModularComponent.create(new TranslatableContents(key, fallback, args)); } @@ -74,7 +76,8 @@ public static ModularComponent keybind(String name) { return ModularComponent.create(new KeybindContents(name)); } - public static ModularComponent nbt(String nbtPathPattern, boolean interpreting, Optional separator, DataSource dataSource) { + public static ModularComponent nbt(String nbtPathPattern, boolean interpreting, Optional separator, + DataSource dataSource) { return ModularComponent.create(new NbtContents(nbtPathPattern, interpreting, separator, dataSource)); } @@ -95,10 +98,14 @@ public static ModularComponent of(Component component) { return new ModularComponent(component.getContents(), component.getSiblings(), component.getStyle()); } - @Getter private Alignment alignment = Alignment.CENTER; - @Getter private float scale = 1f; - @Getter private Boolean shadow; - @Getter private IntSupplier dynamicColor; + @Getter + private Alignment alignment = Alignment.CENTER; + @Getter + private float scale = 1f; + @Getter + private Boolean shadow; + @Getter + private IntSupplier dynamicColor; protected ModularComponent(ComponentContents contents, List siblings, Style style) { super(contents, siblings, style); @@ -208,7 +215,7 @@ public ModularComponent asModular() { } @Override - public @NotNull ModularComponent withStyle(ChatFormatting @NotNull ... formats) { + public @NotNull ModularComponent withStyle(ChatFormatting @NotNull... formats) { return (ModularComponent) super.withStyle(formats); } @@ -231,7 +238,8 @@ public ModularComponent asModular() { public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof ModularComponent other)) return false; - return super.equals(other) && this.alignment.equals(other.alignment) && Float.compare(this.scale, other.scale) == 0 && + return super.equals(other) && this.alignment.equals(other.alignment) && + Float.compare(this.scale, other.scale) == 0 && Objects.equals(this.shadow, other.shadow) && Objects.equals(this.dynamicColor, other.dynamicColor); } diff --git a/src/main/java/brachy/modularui/drawable/text/RichText.java b/src/main/java/brachy/modularui/drawable/text/RichText.java index 9f5fd118..c3792705 100644 --- a/src/main/java/brachy/modularui/drawable/text/RichText.java +++ b/src/main/java/brachy/modularui/drawable/text/RichText.java @@ -19,12 +19,12 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.chat.FormattedText; import net.minecraft.util.ExtraCodecs; + import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.Decoder; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.Encoder; - import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import lombok.Getter; @@ -44,6 +44,7 @@ public class RichText implements IDrawable, IRichTextBuilder { ModularComponent.CODEC.codec(), ExtraCodecs.COMPONENT, Spacer.CODEC_MAP.codec(), Codec.STRING, IDrawable.CODEC); private static final Encoder RICH_ELEMENT_ENCODER = new Encoder<>() { + @Override public DataResult encode(Object input, DynamicOps ops, T prefix) { if (input == null) return DataResult.success(ops.empty()); @@ -56,7 +57,8 @@ public DataResult encode(Object input, DynamicOps ops, T prefix) { if (input instanceof Component v) return ExtraCodecs.COMPONENT.encode(v, ops, prefix); if (input instanceof IDrawable v) return IDrawable.CODEC.encode(v, ops, prefix); if (input instanceof Spacer v) return Spacer.CODEC_MAP.codec().encode(v, ops, prefix); - return DataResult.error(() -> "RichText is currently unable to encode objects of type " + input.getClass().getSimpleName()); + return DataResult.error( + () -> "RichText is currently unable to encode objects of type " + input.getClass().getSimpleName()); } }; public static final Codec RICH_ELEMENT_CODEC = Codec.of(RICH_ELEMENT_ENCODER, RICH_ELEMENT_DECODER); @@ -71,10 +73,14 @@ public DataResult encode(Object input, DynamicOps ops, T prefix) { private final List elements = new ArrayList<>(); private TooltipLines componentList; - @Getter private Alignment alignment = Alignment.CenterLeft; - @Getter private float scale = 1f; - @Getter private Integer color = null; - @Getter private Boolean shadow = null; + @Getter + private Alignment alignment = Alignment.CenterLeft; + @Getter + private float scale = 1f; + @Getter + private Integer color = null; + @Getter + private Boolean shadow = null; private int cursor = 0; private boolean cursorLocked = false; @@ -370,7 +376,8 @@ public void draw(GuiContext context, int x, int y, int width, int height, int co draw(renderer, context, x, y, width, height, color, shadow); } - public void draw(TextRenderer renderer, GuiContext context, int x, int y, int width, int height, int color, boolean shadow) { + public void draw(TextRenderer renderer, GuiContext context, int x, int y, int width, int height, int color, + boolean shadow) { if (ModularUI.isDev() && !this.verified) { verifyListElements(this.elements); this.verified = true; @@ -388,7 +395,8 @@ public int getLastHeight() { return (int) renderer.getLastHeight(); } - public void setupRenderer(TextRenderer renderer, int x, int y, float width, float height, int color, boolean shadow) { + public void setupRenderer(TextRenderer renderer, int x, int y, float width, float height, int color, + boolean shadow) { renderer.setPos(x, y); renderer.setScale(this.scale); renderer.setColor(this.color != null ? this.color : color); @@ -479,7 +487,8 @@ public static void verifyListElements(List elements) { continue; } if (!errored.contains(o.getClass())) { - errors.add("Element of type '" + o.getClass() + "' is not valid for RichText. Elements must implement one of these interfaces: [FormattedText, IIcon, ITextLine]"); + errors.add("Element of type '" + o.getClass() + + "' is not valid for RichText. Elements must implement one of these interfaces: [FormattedText, IIcon, ITextLine]"); errored.add(o.getClass()); } } diff --git a/src/main/java/brachy/modularui/drawable/text/RichTextCompiler.java b/src/main/java/brachy/modularui/drawable/text/RichTextCompiler.java index c647a2eb..1a52b6ba 100755 --- a/src/main/java/brachy/modularui/drawable/text/RichTextCompiler.java +++ b/src/main/java/brachy/modularui/drawable/text/RichTextCompiler.java @@ -108,7 +108,8 @@ private void compile(List raw) { } private boolean iterateFormatted(String content, int skip, Style style) { - return FontRenderHelper.iterateFormatted(content, skip, style, Style.EMPTY, this.lineBreakFinder, this.lineBreakFinder); + return FontRenderHelper.iterateFormatted(content, skip, style, Style.EMPTY, this.lineBreakFinder, + this.lineBreakFinder); } private void compileText(Component component) { @@ -195,7 +196,7 @@ private void addLineElement(String s, Style style, float width) { if (s.isEmpty()) return; this.h = Math.max(this.h, this.fr.lineHeight); this.x += width; - //if (s.length() > 1) s = this.fr.bidirectionalShaping(s); // TODO: this turns ", " into " ," for some reason + // if (s.length() > 1) s = this.fr.bidirectionalShaping(s); // TODO: this turns ", " into " ," for some reason this.currentLine.add(FormattedCharSequence.forward(s, style)); } diff --git a/src/main/java/brachy/modularui/drawable/text/Spacer.java b/src/main/java/brachy/modularui/drawable/text/Spacer.java index 3eb45d38..26b9dea1 100755 --- a/src/main/java/brachy/modularui/drawable/text/Spacer.java +++ b/src/main/java/brachy/modularui/drawable/text/Spacer.java @@ -4,9 +4,9 @@ import brachy.modularui.screen.viewport.GuiContext; import net.minecraft.client.gui.Font; + import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; - import lombok.Getter; public class Spacer implements ITextLine { diff --git a/src/main/java/brachy/modularui/drawable/text/TextRenderer.java b/src/main/java/brachy/modularui/drawable/text/TextRenderer.java index a2ad5c55..107a960a 100644 --- a/src/main/java/brachy/modularui/drawable/text/TextRenderer.java +++ b/src/main/java/brachy/modularui/drawable/text/TextRenderer.java @@ -260,7 +260,8 @@ protected int getStartX(float maxWidth, float lineWidth) { maxWidth = this.maxWidth; } if (this.alignment.x > 0 && maxWidth > 0) { - return Math.max(this.x, this.x + Math.round(maxWidth * this.alignment.x) - Math.round(lineWidth * this.alignment.x)); + return Math.max(this.x, + this.x + Math.round(maxWidth * this.alignment.x) - Math.round(lineWidth * this.alignment.x)); } return this.x; } diff --git a/src/main/java/brachy/modularui/factory/GuiManager.java b/src/main/java/brachy/modularui/factory/GuiManager.java index 8c105c7b..922b35bc 100644 --- a/src/main/java/brachy/modularui/factory/GuiManager.java +++ b/src/main/java/brachy/modularui/factory/GuiManager.java @@ -72,7 +72,8 @@ public static boolean hasFactory(ResourceLocation name) { return FACTORIES.containsKey(name); } - public static void open(@NotNull UIFactory factory, @NotNull T guiData, ServerPlayer player) { + public static void open(@NotNull UIFactory factory, @NotNull T guiData, + ServerPlayer player) { if (player instanceof FakePlayer || openedContainers.contains(player)) return; openedContainers.add(player); // create panel, collect sync handlers and create menu @@ -90,7 +91,8 @@ public static void open(@NotNull UIFactory factory, @NotN player.closeContainer(); } int windowId = player.containerCounter; - ModularContainerMenu menu = settings.hasCustomContainer() ? settings.createContainer(windowId) : factory.createContainer(windowId); + ModularContainerMenu menu = settings.hasCustomContainer() ? settings.createContainer(windowId) : + factory.createContainer(windowId); menu.construct(player, msm, settings, panel.getName(), guiData); // sync to client @@ -121,9 +123,11 @@ public static void openFromClient(int windowId, int networkI guiData.addSyncHandlers(syncManager); ModularScreen screen = factory.createScreen(guiData, panel); screen.getContext().setSettings(settings); - ModularContainerMenu container = settings.hasCustomContainer() ? settings.createContainer(windowId) : factory.createContainer(windowId); + ModularContainerMenu container = settings.hasCustomContainer() ? settings.createContainer(windowId) : + factory.createContainer(windowId); container.construct(player, msm, settings, panel.getName(), guiData); - IMuiScreen wrapper = settings.hasCustomGui() ? settings.createGui(container, screen) : factory.createScreenWrapper(container, screen); + IMuiScreen wrapper = settings.hasCustomGui() ? settings.createGui(container, screen) : + factory.createScreenWrapper(container, screen); if (!(wrapper.wrappedScreen() instanceof AbstractContainerScreen guiContainer)) { throw new IllegalStateException("The wrapping screen must be a GuiContainer for synced GUIs!"); } @@ -146,7 +150,8 @@ public static void openFromClient(@NotNull UIFactory fact @OnlyIn(Dist.CLIENT) static void openScreen(ModularScreen screen, UISettings settings) { - if (screen.getScreenWrapper() != null && MCHelper.getCurrentScreen() == screen.getScreenWrapper().wrappedScreen()) { + if (screen.getScreenWrapper() != null && + MCHelper.getCurrentScreen() == screen.getScreenWrapper().wrappedScreen()) { // already open return; } diff --git a/src/main/java/brachy/modularui/factory/PlayerInventoryGuiData.java b/src/main/java/brachy/modularui/factory/PlayerInventoryGuiData.java index 11fb2d5a..b31ae042 100644 --- a/src/main/java/brachy/modularui/factory/PlayerInventoryGuiData.java +++ b/src/main/java/brachy/modularui/factory/PlayerInventoryGuiData.java @@ -21,7 +21,8 @@ @Getter public class PlayerInventoryGuiData extends GuiData { - public static PlayerInventoryGuiData of(Player player, InventoryType inventoryType, T context, int slotIndex) { + public static PlayerInventoryGuiData of(Player player, InventoryType inventoryType, T context, + int slotIndex) { return new PlayerInventoryGuiData<>(player, inventoryType, context, slotIndex); } diff --git a/src/main/java/brachy/modularui/factory/PlayerInventoryUIFactory.java b/src/main/java/brachy/modularui/factory/PlayerInventoryUIFactory.java index 0f91b294..7174ead4 100755 --- a/src/main/java/brachy/modularui/factory/PlayerInventoryUIFactory.java +++ b/src/main/java/brachy/modularui/factory/PlayerInventoryUIFactory.java @@ -35,7 +35,8 @@ public void openFromCurios(Player player, String type, int index) { if (!ModularUI.Mods.CURIOS.isLoaded()) { throw new IllegalArgumentException("Can't open UI for curio item when curios is not loaded!"); } - GuiManager.open(this, PlayerInventoryGuiData.of(player, InventoryTypes.CURIOS, type, index), verifyServerSide(player)); + GuiManager.open(this, PlayerInventoryGuiData.of(player, InventoryTypes.CURIOS, type, index), + verifyServerSide(player)); } public void open(Player player, InventoryType type, T context, int index) { diff --git a/src/main/java/brachy/modularui/factory/inventory/InventoryType.java b/src/main/java/brachy/modularui/factory/inventory/InventoryType.java index a7a53cfa..a9b2ba06 100755 --- a/src/main/java/brachy/modularui/factory/inventory/InventoryType.java +++ b/src/main/java/brachy/modularui/factory/inventory/InventoryType.java @@ -67,7 +67,7 @@ public boolean isActive() { * @return index of slot with stackable item or -1 if none found */ public int findFirstStackable(Player player, ItemStack stack, boolean ignoreEmpty) { - int[] holder = {-1}; + int[] holder = { -1 }; visitAllStackable(player, stack, (type, context, index, stackInSlot) -> { if (stackInSlot.isEmpty() && ignoreEmpty) return false; holder[0] = index; diff --git a/src/main/java/brachy/modularui/factory/inventory/InventoryTypes.java b/src/main/java/brachy/modularui/factory/inventory/InventoryTypes.java index 2114f921..5fd0ef8c 100755 --- a/src/main/java/brachy/modularui/factory/inventory/InventoryTypes.java +++ b/src/main/java/brachy/modularui/factory/inventory/InventoryTypes.java @@ -6,11 +6,11 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.InputConstants; import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.SubscribeEvent; +import com.mojang.blaze3d.platform.InputConstants; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; @@ -73,7 +73,7 @@ public static Collection> getAll() { * @param stack item stack to check stackability for * @param visitor visitor function */ - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public static void visitAllStackable(Player player, ItemStack stack, InventoryVisitor visitor) { for (InventoryType type : getAll()) { if (type.visitAllStackable(player, stack, visitor)) { @@ -90,7 +90,7 @@ public static void visitAllStackable(Player player, ItemStack stack, InventoryVi * @param player the player to visit inventory in * @param visitor visitor function */ - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public static void visitAll(Player player, InventoryVisitor visitor) { for (InventoryType type : getAll()) { if (type.visitAll(player, visitor)) { diff --git a/src/main/java/brachy/modularui/integration/emi/EmiRecipeViewerSlot.java b/src/main/java/brachy/modularui/integration/emi/EmiRecipeViewerSlot.java index 60361bed..dcc643cf 100644 --- a/src/main/java/brachy/modularui/integration/emi/EmiRecipeViewerSlot.java +++ b/src/main/java/brachy/modularui/integration/emi/EmiRecipeViewerSlot.java @@ -4,13 +4,12 @@ import brachy.modularui.integration.recipeviewer.RecipeSlotRole; import brachy.modularui.integration.recipeviewer.RecipeViewerSlotWidget; import brachy.modularui.screen.viewport.ModularGuiContext; +import brachy.modularui.theme.WidgetThemeEntry; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.world.item.crafting.Ingredient; import net.minecraftforge.fluids.FluidStack; -import brachy.modularui.theme.WidgetThemeEntry; - import dev.emi.emi.api.stack.EmiIngredient; import dev.emi.emi.api.widget.SlotWidget; import dev.emi.emi.api.widget.TankWidget; @@ -20,7 +19,8 @@ @ApiStatus.Internal public class EmiRecipeViewerSlot extends RecipeViewerSlotWidget> { - @Getter private SlotWidget slotWidget; + @Getter + private SlotWidget slotWidget; public EmiRecipeViewerSlot(Class ingredientClass) { super(ingredientClass); @@ -30,7 +30,8 @@ public EmiRecipeViewerSlot(Class ingredientClass) { tooltipAutoUpdate(true); tooltipDynamic(tooltip -> { - for (ClientTooltipComponent ctc : this.slotWidget.getTooltip(getContext().getAbsMouseX(), getContext().getAbsMouseY())) { + for (ClientTooltipComponent ctc : this.slotWidget.getTooltip(getContext().getAbsMouseX(), + getContext().getAbsMouseY())) { tooltip.addDrawableLine(new TooltipComponentIcon(ctc, false)); } }); @@ -38,7 +39,8 @@ public EmiRecipeViewerSlot(Class ingredientClass) { @Override protected void rebuildRealSlot() { - EmiIngredient ingredient = EmiStackConverter.convertToEmiEntry(this.entries, this.chance, this.renderMappingFunction); + EmiIngredient ingredient = EmiStackConverter.convertToEmiEntry(this.entries, this.chance, + this.renderMappingFunction); if (this.ingredientClass == FluidStack.class) { // special case fluid slots slotWidget = new TankWidget(ingredient, 0, 0, 18, 18, 1); @@ -51,12 +53,14 @@ protected void rebuildRealSlot() { @Override public void draw(ModularGuiContext context, WidgetThemeEntry widgetTheme) { - this.slotWidget.render(context.getGraphics(), context.getMouseX(), context.getMouseY(), context.getRenderPartialTicks()); + this.slotWidget.render(context.getGraphics(), context.getMouseX(), context.getMouseY(), + context.getRenderPartialTicks()); } @Override public Result onMousePressed(int button) { - return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? Result.SUCCESS : Result.ACCEPT; + return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? + Result.SUCCESS : Result.ACCEPT; } @Override diff --git a/src/main/java/brachy/modularui/integration/emi/EmiStackConverter.java b/src/main/java/brachy/modularui/integration/emi/EmiStackConverter.java index 37f9ad5c..055cca16 100644 --- a/src/main/java/brachy/modularui/integration/emi/EmiStackConverter.java +++ b/src/main/java/brachy/modularui/integration/emi/EmiStackConverter.java @@ -60,17 +60,17 @@ public EmiIngredient convertTo(EntryList stack, float chance, UnaryOp return toEMIIngredient(stackList.stream().map(mapper)).setChance(chance); } else if (stack instanceof ItemTagList tagList) { return EmiIngredient.of(tagList.getEntries().stream() - .map(ItemTagList.ItemTagEntry::stacks) - .map(stream -> toEMIIngredient(stream.map(mapper))) - .collect(Collectors.toList()), - tagList.getEntries().get(0).amount()) + .map(ItemTagList.ItemTagEntry::stacks) + .map(stream -> toEMIIngredient(stream.map(mapper))) + .collect(Collectors.toList()), + tagList.getEntries().get(0).amount()) .setChance(chance); } else if (stack instanceof ItemHolderSetList holderSetList) { return EmiIngredient.of(holderSetList.getEntries().stream() - .map(ItemHolderSetList.ItemHolderSetEntry::stacks) - .map(stream -> toEMIIngredient(stream.map(mapper))) - .collect(Collectors.toList()), - holderSetList.getEntries().get(0).amount()) + .map(ItemHolderSetList.ItemHolderSetEntry::stacks) + .map(stream -> toEMIIngredient(stream.map(mapper))) + .collect(Collectors.toList()), + holderSetList.getEntries().get(0).amount()) .setChance(chance); } return EmiStack.EMPTY; @@ -106,17 +106,17 @@ public EmiIngredient convertTo(EntryList stack, float chance, UnaryO return toEMIIngredient(stackList.stream().map(mapper)).setChance(chance); } else if (stack instanceof FluidTagList tagList) { return EmiIngredient.of(tagList.getEntries().stream() - .map(FluidTagList.FluidTagEntry::stacks) - .map(stream -> toEMIIngredient(stream.map(mapper))) - .collect(Collectors.toList()), - tagList.getEntries().get(0).amount()) + .map(FluidTagList.FluidTagEntry::stacks) + .map(stream -> toEMIIngredient(stream.map(mapper))) + .collect(Collectors.toList()), + tagList.getEntries().get(0).amount()) .setChance(chance); } else if (stack instanceof FluidHolderSetList holderSetList) { return EmiIngredient.of(holderSetList.getEntries().stream() - .map(FluidHolderSetList.FluidHolderSetEntry::stacks) - .map(stream -> toEMIIngredient(stream.map(mapper))) - .collect(Collectors.toList()), - holderSetList.getEntries().get(0).amount()) + .map(FluidHolderSetList.FluidHolderSetEntry::stacks) + .map(stream -> toEMIIngredient(stream.map(mapper))) + .collect(Collectors.toList()), + holderSetList.getEntries().get(0).amount()) .setChance(chance); } return EmiStack.EMPTY; @@ -138,7 +138,8 @@ public static Optional> getFor(Class clazz) { return Optional.ofNullable(getForNullable(clazz)); } - public static EmiIngredient convertToEmiEntry(EntryList entries, float chance, UnaryOperator renderMappingFunction) { + public static EmiIngredient convertToEmiEntry(EntryList entries, float chance, + UnaryOperator renderMappingFunction) { Converter converter = getForNullable(entries.getType()); if (converter != null) { return converter.convertTo(entries, chance, renderMappingFunction); diff --git a/src/main/java/brachy/modularui/integration/emi/ModularUIEmiPlugin.java b/src/main/java/brachy/modularui/integration/emi/ModularUIEmiPlugin.java index 5df34a5c..2694258e 100644 --- a/src/main/java/brachy/modularui/integration/emi/ModularUIEmiPlugin.java +++ b/src/main/java/brachy/modularui/integration/emi/ModularUIEmiPlugin.java @@ -4,7 +4,6 @@ import brachy.modularui.integration.emi.handler.EmiScreenHandler; import brachy.modularui.screen.ContainerScreenWrapper; import brachy.modularui.screen.ScreenWrapper; - import brachy.modularui.test.TestRecipeViewerGuis; import dev.emi.emi.api.EmiEntrypoint; diff --git a/src/main/java/brachy/modularui/integration/emi/handler/EmiScreenHandler.java b/src/main/java/brachy/modularui/integration/emi/handler/EmiScreenHandler.java index c2461406..2bb66324 100755 --- a/src/main/java/brachy/modularui/integration/emi/handler/EmiScreenHandler.java +++ b/src/main/java/brachy/modularui/integration/emi/handler/EmiScreenHandler.java @@ -29,7 +29,7 @@ import java.util.function.Consumer; public class EmiScreenHandler extends RecipeViewerHandler - implements EmiExclusionArea, EmiDragDropHandler, EmiStackProvider { + implements EmiExclusionArea, EmiDragDropHandler, EmiStackProvider { private static final Map, EmiScreenHandler> CACHE = new Reference2ReferenceOpenHashMap<>(); @@ -102,7 +102,7 @@ public EmiStackInteraction getStackAt(T screen, int x, int y) { if (converter == null) { return EmiStackInteraction.EMPTY; } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) var converted = ((EmiStackConverter.Converter) converter).convertTo(provider); return new EmiStackInteraction(converted, null, false); } diff --git a/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiCategory.java b/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiCategory.java index f04e9c18..4886f811 100644 --- a/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiCategory.java +++ b/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiCategory.java @@ -1,10 +1,10 @@ package brachy.modularui.integration.emi.recipe; +import brachy.modularui.integration.recipeviewer.RecipeViewerUtils; + import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; -import brachy.modularui.integration.recipeviewer.RecipeViewerUtils; - import dev.emi.emi.api.recipe.EmiRecipe; import dev.emi.emi.api.recipe.EmiRecipeCategory; import dev.emi.emi.api.render.EmiRenderable; @@ -21,7 +21,8 @@ public ModularUIEmiCategory(ResourceLocation id, EmiRenderable icon, EmiRenderab super(id, icon, simplified); } - public ModularUIEmiCategory(ResourceLocation id, EmiRenderable icon, EmiRenderable simplified, Comparator sorter) { + public ModularUIEmiCategory(ResourceLocation id, EmiRenderable icon, EmiRenderable simplified, + Comparator sorter) { super(id, icon, simplified, sorter); } diff --git a/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiRecipe.java b/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiRecipe.java index 64e05125..eb91ea21 100644 --- a/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiRecipe.java +++ b/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiRecipe.java @@ -36,12 +36,14 @@ public abstract class ModularUIEmiRecipe implements EmiRecipe { private static final String SCREEN_NAME_PREFIX = "emi_recipe_"; - private static final LoadingCache PREVIEW_SCREEN_CACHE = CacheBuilder.newBuilder() + private static final LoadingCache PREVIEW_SCREEN_CACHE = CacheBuilder + .newBuilder() .expireAfterAccess(Duration.ofSeconds(60)) .initialCapacity(8) .maximumSize(32) .softValues() .build(new CacheLoader<>() { + @Override public ModularScreen load(ModularUIEmiRecipe key) { return key.createScreen(); @@ -58,7 +60,8 @@ private static ModularScreen getCachedModularScreen(ModularUIEmiRecipe recipe) { return PREVIEW_SCREEN_CACHE.getUnchecked(recipe); } - @Getter private final ResourceLocation id; + @Getter + private final ResourceLocation id; private final Supplier recipeUI; private boolean sizeCalculated = false; @@ -81,7 +84,8 @@ public ModularUIEmiRecipe(ResourceLocation recipeId, int width, int height, Supp /** * Calculates the size of the recipe if not already done.
- * This should be called in subclasses' constructors. Otherwise, the size of ALL the recipes in the same category are calculated + * This should be called in subclasses' constructors. Otherwise, the size of ALL the recipes in the same category + * are calculated * at once, which can make the game lag for a few seconds. */ protected void calculateSize() { @@ -159,7 +163,8 @@ public IWidget transformWidget(IWidget widget) { private boolean useScreenCacheForNextWidgetQuery = false; /** - * This is used to make EMI's recipe tooltip components use the screen cache because those normally recreate the widgets every frame + * This is used to make EMI's recipe tooltip components use the screen cache because those normally recreate the + * widgets every frame */ @ApiStatus.Internal public final void useScreenCacheForNextWidgetQuery() { diff --git a/src/main/java/brachy/modularui/integration/jei/JeiRecipeViewerSlot.java b/src/main/java/brachy/modularui/integration/jei/JeiRecipeViewerSlot.java index 5c1b4ce7..e6d42af3 100644 --- a/src/main/java/brachy/modularui/integration/jei/JeiRecipeViewerSlot.java +++ b/src/main/java/brachy/modularui/integration/jei/JeiRecipeViewerSlot.java @@ -3,15 +3,13 @@ import brachy.modularui.drawable.TooltipComponentIcon; import brachy.modularui.integration.recipeviewer.RecipeViewerSlotWidget; import brachy.modularui.integration.recipeviewer.entry.EntryList; +import brachy.modularui.screen.viewport.ModularGuiContext; +import brachy.modularui.theme.WidgetThemeEntry; import brachy.modularui.utils.TooltipLines; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.navigation.ScreenPosition; -import brachy.modularui.screen.viewport.ModularGuiContext; - -import brachy.modularui.theme.WidgetThemeEntry; - import lombok.Getter; import mezz.jei.api.gui.builder.IRecipeSlotBuilder; import mezz.jei.api.gui.ingredient.IRecipeSlotDrawable; @@ -28,9 +26,11 @@ * Ingredient changes after building will only change the displayed ingredients. */ @ApiStatus.Internal -public class JeiRecipeViewerSlot extends RecipeViewerSlotWidget> implements ISlottedRecipeWidget { +public class JeiRecipeViewerSlot extends RecipeViewerSlotWidget> + implements ISlottedRecipeWidget { - @Getter private @Nullable IRecipeSlotDrawable slotWidget; + @Getter + private @Nullable IRecipeSlotDrawable slotWidget; private boolean configured; private boolean overrideDisplay; @@ -98,17 +98,18 @@ public void draw(ModularGuiContext context, WidgetThemeEntry widgetTheme) { this.slotWidget.draw(context.getGraphics(), isHovering()); } -/* - @Override - public Result onMousePressed(int button) { - return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? Result.SUCCESS : Result.ACCEPT; - } - - @Override - public Result onKeyPressed(int keyCode, int scanCode, int modifiers) { - return this.slotWidget.keyPressed(keyCode, scanCode, modifiers) ? Result.SUCCESS : Result.ACCEPT; - } -*/ + /* + * @Override + * public Result onMousePressed(int button) { + * return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? Result.SUCCESS + * : Result.ACCEPT; + * } + * + * @Override + * public Result onKeyPressed(int keyCode, int scanCode, int modifiers) { + * return this.slotWidget.keyPressed(keyCode, scanCode, modifiers) ? Result.SUCCESS : Result.ACCEPT; + * } + */ @Override public Optional getSlotUnderMouse(double mouseX, double mouseY) { diff --git a/src/main/java/brachy/modularui/integration/jei/ModularUIJeiPlugin.java b/src/main/java/brachy/modularui/integration/jei/ModularUIJeiPlugin.java index 69b78917..a7dd2ff1 100644 --- a/src/main/java/brachy/modularui/integration/jei/ModularUIJeiPlugin.java +++ b/src/main/java/brachy/modularui/integration/jei/ModularUIJeiPlugin.java @@ -5,12 +5,11 @@ import brachy.modularui.integration.recipeviewer.RecipeSlotRole; import brachy.modularui.screen.ContainerScreenWrapper; import brachy.modularui.screen.ScreenWrapper; +import brachy.modularui.test.TestRecipeViewerGuis; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.resources.ResourceLocation; -import brachy.modularui.test.TestRecipeViewerGuis; - import lombok.Getter; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; @@ -30,8 +29,10 @@ @JeiPlugin public class ModularUIJeiPlugin implements IModPlugin { - @Getter private static IJeiRuntime runtime = null; - @Getter private static IJeiHelpers jeiHelpers; + @Getter + private static IJeiRuntime runtime = null; + @Getter + private static IJeiHelpers jeiHelpers; public static boolean hasRuntime() { return runtime != null; @@ -87,7 +88,7 @@ public void registerGuiHandlers(IGuiHandlerRegistration registration) { public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) { if (ModularUI.Mods.REI.isLoaded() || ModularUI.Mods.EMI.isLoaded()) return; - //JeiContainerHandler.register(ModularContainerMenu.class, registration); + // JeiContainerHandler.register(ModularContainerMenu.class, registration); } @Override diff --git a/src/main/java/brachy/modularui/integration/jei/ModularUIJeiProperties.java b/src/main/java/brachy/modularui/integration/jei/ModularUIJeiProperties.java index 423680f0..d206800a 100644 --- a/src/main/java/brachy/modularui/integration/jei/ModularUIJeiProperties.java +++ b/src/main/java/brachy/modularui/integration/jei/ModularUIJeiProperties.java @@ -7,7 +7,6 @@ import net.minecraft.client.gui.screens.Screen; import com.mojang.blaze3d.platform.Window; - import lombok.Getter; import mezz.jei.api.gui.handlers.IGuiProperties; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -40,7 +39,7 @@ public ModularUIJeiProperties(IMuiScreen screen) { this.screenClass = screen.wrappedScreen().getClass(); // we have to assign default values to gui size if the size is 0 (e.g. during the instant it's created) - // because MUI initializes the screen/panel sizing data after JEI wants to use them + // because MUI initializes the screen/panel sizing data after JEI wants to use them Window window = Minecraft.getInstance().getWindow(); Area screenArea = screen.screen().getScreenArea(); this.screenWidth = screenArea.width == 0 ? window.getGuiScaledWidth() : screenArea.width; diff --git a/src/main/java/brachy/modularui/integration/jei/handler/JeiContainerHandler.java b/src/main/java/brachy/modularui/integration/jei/handler/JeiContainerHandler.java index f5fa1089..73f40a17 100755 --- a/src/main/java/brachy/modularui/integration/jei/handler/JeiContainerHandler.java +++ b/src/main/java/brachy/modularui/integration/jei/handler/JeiContainerHandler.java @@ -23,7 +23,8 @@ public class JeiContainerHandler implements IUniversalRecipeTransferHandler { - public static void register(Class clz, IRecipeTransferRegistration registration) { + public static void register(Class clz, + IRecipeTransferRegistration registration) { new JeiContainerHandler<>(clz, registration.getTransferHelper()).register(registration); } @@ -74,7 +75,9 @@ public Type getType() { } else if (muiError instanceof RecipeTransferError.Cosmetic) { return Type.COSMETIC; } else { - throw new IllegalStateException("Recipe transfer error %s is not an internal, user facing or cosmetic error".formatted(muiError)); + throw new IllegalStateException( + "Recipe transfer error %s is not an internal, user facing or cosmetic error" + .formatted(muiError)); } } diff --git a/src/main/java/brachy/modularui/integration/jei/handler/JeiScreenHandler.java b/src/main/java/brachy/modularui/integration/jei/handler/JeiScreenHandler.java index 15d77c3b..64447d8f 100755 --- a/src/main/java/brachy/modularui/integration/jei/handler/JeiScreenHandler.java +++ b/src/main/java/brachy/modularui/integration/jei/handler/JeiScreenHandler.java @@ -27,7 +27,6 @@ import mezz.jei.api.registration.IGuiHandlerRegistration; import mezz.jei.api.runtime.IClickableIngredient; import mezz.jei.gui.overlay.IngredientListOverlay; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -36,7 +35,7 @@ import java.util.Optional; public class JeiScreenHandler extends RecipeViewerHandler - implements IGhostIngredientHandler, IScreenHandler { + implements IGhostIngredientHandler, IScreenHandler { private static final Map, JeiScreenHandler> CACHE = new Reference2ReferenceOpenHashMap<>(); @@ -97,7 +96,8 @@ public boolean shouldHighlightTargets() { } @Override - public Optional> getClickableIngredientUnderMouse(IClickableIngredientFactory factory, T screen, + public Optional> getClickableIngredientUnderMouse(IClickableIngredientFactory factory, + T screen, double mouseX, double mouseY) { IWidget hovered = screen.screen().getContext().getTopHovered(); if (hovered instanceof IngredientProvider provider) { @@ -116,7 +116,8 @@ private I mapFirstIngredient(IngredientProvider provider) { return provider.renderMappingFunction().apply(provider.getIngredients().getStacks().get(0)); } - private Optional> createClickableIngredient(IClickableIngredientFactory factory, I ingredient, + private Optional> createClickableIngredient(IClickableIngredientFactory factory, + I ingredient, Rectangle area) { Optional> type = ModularUIJeiPlugin.getJeiHelpers().getIngredientManager() .getIngredientTypeChecked(ingredient); @@ -162,10 +163,13 @@ public boolean isSearchFocused() { return new JeiRecipeViewerSlot<>(ingredientClass); } - public static class ContainerScreen & IMuiScreen> extends JeiScreenHandler implements IGuiContainerHandler { + public static class ContainerScreen & IMuiScreen> extends JeiScreenHandler + implements IGuiContainerHandler { @SuppressWarnings("unchecked") - public static & IMuiScreen> ContainerScreen ofContainer(Class clazz) { + public static & IMuiScreen> ContainerScreen ofContainer(Class clazz) { return (ContainerScreen) CACHE.computeIfAbsent(clazz, clz -> new ContainerScreen<>((Class) clz)); } diff --git a/src/main/java/brachy/modularui/integration/jei/recipe/ModularUIJeiCategory.java b/src/main/java/brachy/modularui/integration/jei/recipe/ModularUIJeiCategory.java index 32718645..9a3de6e2 100644 --- a/src/main/java/brachy/modularui/integration/jei/recipe/ModularUIJeiCategory.java +++ b/src/main/java/brachy/modularui/integration/jei/recipe/ModularUIJeiCategory.java @@ -61,6 +61,7 @@ protected ModularUIJeiCategory(Function recipeUI, Function() { + @Override public Dimensions load(T recipe) { return ModularUIJeiCategory.this.calculateSize(recipe); @@ -86,8 +87,10 @@ protected Dimensions calculateSize(T recipe) { /** * Calculates and caches the size of the recipe if not already done.
- * This should be called in subclasses' {@link #setupRecipeIngredients(IRecipeLayoutBuilder, Object, IFocusGroup) setupRecipeIngredients} methods. - * Otherwise, the size of ALL the recipes in the same category are calculated at once, which can make the game lag for a few seconds. + * This should be called in subclasses' {@link #setupRecipeIngredients(IRecipeLayoutBuilder, Object, IFocusGroup) + * setupRecipeIngredients} methods. + * Otherwise, the size of ALL the recipes in the same category are calculated at once, which can make the game lag + * for a few seconds. */ protected final void calculateAndCacheSize(T recipe) { this.displaySizeCache.getUnchecked(recipe); @@ -95,7 +98,8 @@ protected final void calculateAndCacheSize(T recipe) { /** * Return the maximum expected display width here.
- * You should also return a per-category display width that's at most this value in {@link #getWidth(Object)} if the default value + * You should also return a per-category display width that's at most this value in {@link #getWidth(Object)} if the + * default value * doesn't suit your needs. * * @return The maximum expected display width @@ -104,7 +108,8 @@ protected final void calculateAndCacheSize(T recipe) { /** * Return the maximum expected display height here.
- * You should also return a per-category display height that's at most this value in {@link #getHeight(Object)} if the default value + * You should also return a per-category display height that's at most this value in {@link #getHeight(Object)} if + * the default value * doesn't suit your needs. * * @return The maximum expected display height @@ -116,7 +121,8 @@ protected final void calculateAndCacheSize(T recipe) { * This is used by JEI for lookups, to figure out what ingredients are inputs and outputs for a recipe. * *

- * Note that you can only add inputs and outputs for JEI's recipe lookup/search here, as the layout builder that's + * Note that you can only add inputs and outputs for JEI's recipe lookup/search here, as the layout builder + * that's * passed into this method only handles those and not the displayed recipe previews. */ @ApiStatus.OverrideOnly @@ -161,14 +167,16 @@ public IWidget transformWidget(IRecipeExtrasBuilder builder, IWidget widget) { @ApiStatus.OverrideOnly @MustBeInvokedByOverriders - public IWidget createRecipeSlotForWidget(IRecipeLayoutBuilder builder, IWidget widget, T recipe, IFocusGroup focuses, MutableInt index) { + public IWidget createRecipeSlotForWidget(IRecipeLayoutBuilder builder, IWidget widget, T recipe, + IFocusGroup focuses, MutableInt index) { if (!(widget instanceof JeiRecipeViewerSlot recipeViewerSlot)) return widget; if (recipeViewerSlot.getName() == null) { recipeViewerSlot.name("jei_slot_" + index.getAndIncrement()); } - IRecipeSlotBuilder slotBuilder = builder.addSlot(ModularUIJeiPlugin.mapToJeiRole(recipeViewerSlot.recipeSlotRole())) + IRecipeSlotBuilder slotBuilder = builder + .addSlot(ModularUIJeiPlugin.mapToJeiRole(recipeViewerSlot.recipeSlotRole())) .setSlotName(recipeViewerSlot.getName()); recipeViewerSlot.configureJeiSlotBuilder(slotBuilder); @@ -190,12 +198,14 @@ public Component getTitle() { @Override public void setRecipe(IRecipeLayoutBuilder builder, T recipe, IFocusGroup focuses) { // guard against JEMI issues by explicitly checking for JEI's implementation - // this is also done to skip having to create the whole widget tree when JEI is only looking up the recipe's ingredients + // this is also done to skip having to create the whole widget tree when JEI is only looking up the recipe's + // ingredients // Check the mod first so compatibility runtimes without JEI do not load its builder class. if (ModularUI.Mods.JEI.isLoaded() && builder instanceof RecipeLayoutBuilder) { ModularScreen screen = createScreen(recipe); MutableInt index = new MutableInt(0); - screen.getMainPanel().visitTransformAllChildren(widget -> createRecipeSlotForWidget(builder, widget, recipe, focuses, index)); + screen.getMainPanel().visitTransformAllChildren( + widget -> createRecipeSlotForWidget(builder, widget, recipe, focuses, index)); veryTemporaryScreenCache.put(recipe, screen); } else { // don't bother with creating the full widget tree if setRecipe was called to get the recipe's ingredients @@ -220,7 +230,8 @@ public void createRecipeExtras(IRecipeExtrasBuilder builder, T recipe, IFocusGro } @Override - public void getTooltip(ITooltipBuilder tooltipBuilder, T recipe, IRecipeSlotsView recipeSlotsView, double mouseX, double mouseY) {} + public void getTooltip(ITooltipBuilder tooltipBuilder, T recipe, IRecipeSlotsView recipeSlotsView, double mouseX, + double mouseY) {} @Override public @Nullable IDrawable getIcon() { @@ -247,7 +258,7 @@ public int getWidth(T recipe) { return display.width; } - protected record Dimensions(int width, int height) { } + protected record Dimensions(int width, int height) {} public static class UIWrapperWidget implements IJeiGuiEventListener, IRecipeWidget { @@ -268,7 +279,8 @@ public ScreenPosition getPosition() { @Override public void drawWidget(GuiGraphics graphics, double mouseX, double mouseY) { - EmbedHandler.drawEmbed(this.screen, graphics, (int) mouseX, (int) mouseY, Minecraft.getInstance().getPartialTick()); + EmbedHandler.drawEmbed(this.screen, graphics, (int) mouseX, (int) mouseY, + Minecraft.getInstance().getPartialTick()); } @Override @@ -296,7 +308,7 @@ public void getTooltip(ITooltipBuilder tooltipBuilder, double mouseX, double mou @Override public void mouseMoved(double mouseX, double mouseY) { - //this.screen.mouseMoved(mouseX, mouseY); + // this.screen.mouseMoved(mouseX, mouseY); } @Override @@ -324,5 +336,4 @@ public boolean keyPressed(double mouseX, double mouseY, int keyCode, int scanCod return this.screen.keyPressed(keyCode, scanCode, modifiers); } } - } diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerSlotWidget.java b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerSlotWidget.java index ae56d31e..6d565e6f 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerSlotWidget.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerSlotWidget.java @@ -7,8 +7,6 @@ import brachy.modularui.integration.recipeviewer.entry.item.ItemStackList; import brachy.modularui.integration.recipeviewer.handlers.IngredientProvider; import brachy.modularui.integration.recipeviewer.handlers.RecipeViewerHandler; -import brachy.modularui.screen.viewport.ModularGuiContext; -import brachy.modularui.theme.WidgetThemeEntry; import brachy.modularui.widget.Widget; import net.minecraft.world.item.ItemStack; @@ -17,22 +15,27 @@ import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; -import org.jetbrains.annotations.ApiStatus; import java.util.function.UnaryOperator; @Accessors(fluent = true) -public abstract class RecipeViewerSlotWidget> extends Widget implements Interactable { +public abstract class RecipeViewerSlotWidget> extends Widget + implements Interactable { - @Getter protected RecipeSlotRole recipeSlotRole = RecipeSlotRole.RENDER_ONLY; + @Getter + protected RecipeSlotRole recipeSlotRole = RecipeSlotRole.RENDER_ONLY; protected EntryList entries; - @Getter @Setter protected float chance = 1f; - @Getter @Setter protected UnaryOperator renderMappingFunction = UnaryOperator.identity(); + @Getter + @Setter + protected float chance = 1f; + @Getter + @Setter + protected UnaryOperator renderMappingFunction = UnaryOperator.identity(); protected final Class ingredientClass; public RecipeViewerSlotWidget(Class ingredientClass) { - this.ingredientClass = ingredientClass; + this.ingredientClass = ingredientClass; } public W recipeSlotRole(RecipeSlotRole recipeSlotRole) { @@ -59,7 +62,8 @@ public W value(I stack) { } else if (stack.getClass() == FluidStack.class) { return value((EntryList) FluidStackList.of((FluidStack) stack)); } else { - throw new IllegalArgumentException("Cannot use value(stack) with non-standard stack types! Use value(entryList) instead."); + throw new IllegalArgumentException( + "Cannot use value(stack) with non-standard stack types! Use value(entryList) instead."); } } diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerState.java b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerState.java index c4ec300e..5cdad0b9 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerState.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerState.java @@ -7,18 +7,21 @@ public enum RecipeViewerState implements Predicate { ENABLED { + @Override public boolean test(ModularScreen screen) { return true; } }, DISABLED { + @Override public boolean test(ModularScreen screen) { return false; } }, DEFAULT { + @Override public boolean test(ModularScreen screen) { return !screen.isClientOnly(); diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerUtils.java b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerUtils.java index 21ffe030..fd6c28fc 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerUtils.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerUtils.java @@ -12,5 +12,4 @@ private RecipeViewerUtils() {} public static Component getCategoryTitle(ResourceLocation categoryId) { return Component.translatable(categoryId.toLanguageKey(CATEGORY_LANGUAGE_KEY_PREFIX)); } - } diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidEntryList.java b/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidEntryList.java index 0e216fd0..450c6f81 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidEntryList.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidEntryList.java @@ -6,7 +6,8 @@ import java.util.List; -public sealed interface FluidEntryList extends EntryList permits FluidStackList, FluidTagList, FluidHolderSetList { +public sealed interface FluidEntryList extends EntryList + permits FluidStackList, FluidTagList, FluidHolderSetList { List getStacks(); diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemEntryList.java b/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemEntryList.java index 381e27aa..f400115f 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemEntryList.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemEntryList.java @@ -6,7 +6,8 @@ import java.util.List; -public sealed interface ItemEntryList extends EntryList permits ItemStackList, ItemTagList, ItemHolderSetList { +public sealed interface ItemEntryList extends EntryList + permits ItemStackList, ItemTagList, ItemHolderSetList { List getStacks(); diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/handlers/RecipeTransferError.java b/src/main/java/brachy/modularui/integration/recipeviewer/handlers/RecipeTransferError.java index b5e4094f..ad8fa58e 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/handlers/RecipeTransferError.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/handlers/RecipeTransferError.java @@ -15,7 +15,7 @@ *

*/ public abstract sealed class RecipeTransferError permits RecipeTransferError.Internal, RecipeTransferError.UserFacing, - RecipeTransferError.Cosmetic { + RecipeTransferError.Cosmetic { public abstract boolean allowsTransfer(); @@ -41,7 +41,7 @@ public List getTooltip() { * has many (or all) of the items required for a recipe in their inventory, it is shown first. * * @return the number of input recipes slots are missing ingredient's in the player's inventory. - * Return -1 by default to avoid sorting + * Return -1 by default to avoid sorting * @since 19.2.0 */ public int getMissingCountHint() { diff --git a/src/main/java/brachy/modularui/integration/rei/ModularUIReiPlugin.java b/src/main/java/brachy/modularui/integration/rei/ModularUIReiPlugin.java index 5d6a1bf7..da33fdf0 100644 --- a/src/main/java/brachy/modularui/integration/rei/ModularUIReiPlugin.java +++ b/src/main/java/brachy/modularui/integration/rei/ModularUIReiPlugin.java @@ -4,7 +4,6 @@ import brachy.modularui.integration.rei.handler.REIScreenHandler; import brachy.modularui.screen.ContainerScreenWrapper; import brachy.modularui.screen.ScreenWrapper; - import brachy.modularui.test.TestRecipeViewerGuis; import me.shedaniel.rei.api.client.plugins.REIClientPlugin; diff --git a/src/main/java/brachy/modularui/integration/rei/REIStackConverter.java b/src/main/java/brachy/modularui/integration/rei/REIStackConverter.java index 470b2491..a0f29125 100644 --- a/src/main/java/brachy/modularui/integration/rei/REIStackConverter.java +++ b/src/main/java/brachy/modularui/integration/rei/REIStackConverter.java @@ -123,12 +123,12 @@ public static Converter getForNullable(Class clazz) { return (Converter) CONVERTERS.get(clazz); } - public static Optional> getFor(Class clazz) { return Optional.ofNullable(getForNullable(clazz)); } - public static EntryIngredient convertToReiEntry(EntryList entries, float chance, UnaryOperator renderMappingFunction) { + public static EntryIngredient convertToReiEntry(EntryList entries, float chance, + UnaryOperator renderMappingFunction) { REIStackConverter.Converter converter = REIStackConverter.getForNullable(entries.getType()); if (converter != null) { return converter.convertTo(entries, chance, renderMappingFunction); diff --git a/src/main/java/brachy/modularui/integration/rei/ReiRecipeViewerSlot.java b/src/main/java/brachy/modularui/integration/rei/ReiRecipeViewerSlot.java index 8b0c1886..0a079bd4 100644 --- a/src/main/java/brachy/modularui/integration/rei/ReiRecipeViewerSlot.java +++ b/src/main/java/brachy/modularui/integration/rei/ReiRecipeViewerSlot.java @@ -20,7 +20,8 @@ public class ReiRecipeViewerSlot extends RecipeViewerSlotWidget ingredientClass) { super(ingredientClass); @@ -59,15 +60,18 @@ protected void rebuildRealSlot() { @Override public void draw(ModularGuiContext context, WidgetThemeEntry widgetTheme) { - this.slotWidget.render(context.getGraphics(), context.getMouseX(), context.getMouseY(), context.getRenderPartialTicks()); + this.slotWidget.render(context.getGraphics(), context.getMouseX(), context.getMouseY(), + context.getRenderPartialTicks()); if (this.isHovering() && slotWidget instanceof EntryWidgetAccessor accessor) { - accessor.modularui$invokeDrawHighlighted(context.getGraphics(), context.getMouseX(), context.getMouseY(), context.getRenderPartialTicks()); + accessor.modularui$invokeDrawHighlighted(context.getGraphics(), context.getMouseX(), context.getMouseY(), + context.getRenderPartialTicks()); } } @Override public Result onMousePressed(int button) { - return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? Result.SUCCESS : Result.ACCEPT; + return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? + Result.SUCCESS : Result.ACCEPT; } @Override diff --git a/src/main/java/brachy/modularui/integration/rei/handler/MUIDraggableStackVisitor.java b/src/main/java/brachy/modularui/integration/rei/handler/MUIDraggableStackVisitor.java index 5187dee3..5c6fc82d 100644 --- a/src/main/java/brachy/modularui/integration/rei/handler/MUIDraggableStackVisitor.java +++ b/src/main/java/brachy/modularui/integration/rei/handler/MUIDraggableStackVisitor.java @@ -25,7 +25,6 @@ public MUIDraggableStackVisitor(Class clazz) { this.clazz = clazz; } - @Override public boolean isHandingScreen(R screen) { return clazz.isAssignableFrom(screen.getClass()); diff --git a/src/main/java/brachy/modularui/integration/rei/handler/MUIOverlayDecider.java b/src/main/java/brachy/modularui/integration/rei/handler/MUIOverlayDecider.java index ca7577e6..a6a1984f 100755 --- a/src/main/java/brachy/modularui/integration/rei/handler/MUIOverlayDecider.java +++ b/src/main/java/brachy/modularui/integration/rei/handler/MUIOverlayDecider.java @@ -39,8 +39,8 @@ public InteractionResult shouldScreenBeOverlaid(R screen) { return InteractionResult.PASS; } ModularScreen modularScreen = muiScreen.screen(); - return modularScreen.getContext().getRecipeViewerSettings().isEnabled(modularScreen) ? InteractionResult.SUCCESS : InteractionResult.FAIL; - + return modularScreen.getContext().getRecipeViewerSettings().isEnabled(modularScreen) ? + InteractionResult.SUCCESS : InteractionResult.FAIL; } @Override diff --git a/src/main/java/brachy/modularui/integration/rei/handler/REIScreenHandler.java b/src/main/java/brachy/modularui/integration/rei/handler/REIScreenHandler.java index 9fd54548..77dd5268 100755 --- a/src/main/java/brachy/modularui/integration/rei/handler/REIScreenHandler.java +++ b/src/main/java/brachy/modularui/integration/rei/handler/REIScreenHandler.java @@ -29,7 +29,7 @@ import java.util.Map; public class REIScreenHandler extends RecipeViewerHandler - implements DraggableStackProvider, ExclusionZonesProvider { + implements DraggableStackProvider, ExclusionZonesProvider { private static final Map, REIScreenHandler> CACHE = new Reference2ReferenceOpenHashMap<>(); @@ -76,7 +76,7 @@ public static void register(Class clazz, Scre if (converter == null) { return null; } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) var converted = ((REIStackConverter.Converter) converter).convertTo(provider); return new DraggableStack() { diff --git a/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiCategory.java b/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiCategory.java index f4c4e837..345d28ab 100644 --- a/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiCategory.java +++ b/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiCategory.java @@ -1,9 +1,9 @@ package brachy.modularui.integration.rei.recipe; -import net.minecraft.network.chat.Component; - import brachy.modularui.integration.recipeviewer.RecipeViewerUtils; +import net.minecraft.network.chat.Component; + import me.shedaniel.math.Rectangle; import me.shedaniel.rei.api.client.gui.widgets.Widget; import me.shedaniel.rei.api.client.registry.display.DisplayCategory; @@ -42,7 +42,9 @@ public int getDisplayHeight(D display) { /** * Return the maximum expected display height here.
- * You should also return a per-category display height that's at most this value in {@link #getDisplayHeight(ModularUIReiDisplay)}. + * You should also return a per-category display height that's at most this value in + * {@link #getDisplayHeight(ModularUIReiDisplay)}. + * * @return The maximum expected display height */ public abstract int getMaxDisplayHeight(); diff --git a/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiDisplay.java b/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiDisplay.java index bc9fe944..3f7a237e 100644 --- a/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiDisplay.java +++ b/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiDisplay.java @@ -40,12 +40,14 @@ public abstract class ModularUIReiDisplay implements Display { private final ResourceLocation recipeId; private final Supplier recipeUI; - @Getter protected final CategoryIdentifier categoryIdentifier; + @Getter + protected final CategoryIdentifier categoryIdentifier; private boolean sizeCalculated = false; private int displayWidth, displayHeight; - public ModularUIReiDisplay(ResourceLocation recipeId, Supplier recipeUI, CategoryIdentifier categoryId) { + public ModularUIReiDisplay(ResourceLocation recipeId, Supplier recipeUI, + CategoryIdentifier categoryId) { this.recipeId = recipeId; this.recipeUI = recipeUI; this.categoryIdentifier = categoryId; @@ -53,7 +55,8 @@ public ModularUIReiDisplay(ResourceLocation recipeId, Supplier recipeUI /** * Calculates the size of the recipe if not already done.
- * This should be called in subclasses' constructors. Otherwise, the size of ALL the recipes in the same category are calculated + * This should be called in subclasses' constructors. Otherwise, the size of ALL the recipes in the same category + * are calculated * at once, which can make the game lag for a few seconds. */ protected void calculateSize() { @@ -63,7 +66,8 @@ protected void calculateSize() { IWidget ui = this.recipeUI.get(); int w = ui.resizer().getFixedPixelWidth(), h = ui.resizer().getFixedPixelHeight(); if (w < 0 || h < 0) { - ModularScreen screen = createScreen(ui, this.recipeId.getNamespace(), SCREEN_NAME_PREFIX + this.recipeId.getPath()); + ModularScreen screen = createScreen(ui, this.recipeId.getNamespace(), + SCREEN_NAME_PREFIX + this.recipeId.getPath()); w = EmbedHandler.getEmbedWidth(screen); h = EmbedHandler.getEmbedHeight(screen); } @@ -82,7 +86,8 @@ public int getDisplayHeight() { } private ModularScreen createScreen() { - return createScreen(this.recipeUI.get(), this.recipeId.getNamespace(), SCREEN_NAME_PREFIX + this.recipeId.getPath()); + return createScreen(this.recipeUI.get(), this.recipeId.getNamespace(), + SCREEN_NAME_PREFIX + this.recipeId.getPath()); } @ApiStatus.OverrideOnly @@ -191,7 +196,7 @@ public List children() { @Override public void mouseMoved(double mouseX, double mouseY) { - //this.screen.mouseMoved(mouseX, mouseY); + // this.screen.mouseMoved(mouseX, mouseY); } @Override diff --git a/src/main/java/brachy/modularui/network/ModularNetwork.java b/src/main/java/brachy/modularui/network/ModularNetwork.java index 4bb47173..e13e17c1 100644 --- a/src/main/java/brachy/modularui/network/ModularNetwork.java +++ b/src/main/java/brachy/modularui/network/ModularNetwork.java @@ -24,7 +24,8 @@ @ApiStatus.Internal public abstract class ModularNetwork { - // You have to make sure you are choosing the logical side you are currently on otherwise you can mess things up badly, + // You have to make sure you are choosing the logical side you are currently on otherwise you can mess things up + // badly, // since there is no validation. public static final Client CLIENT = new Client(); public static final ServerManager SERVER = new ServerManager(); @@ -118,12 +119,14 @@ public void receivePacket(Player player, SyncHandlerPacket packet) { } @Override - public void sendSyncHandlerPacket(String panel, SyncHandler syncHandler, FriendlyByteBuf buffer, Player player) { + public void sendSyncHandlerPacket(String panel, SyncHandler syncHandler, FriendlyByteBuf buffer, + Player player) { get(player).sendSyncHandlerPacket(panel, syncHandler, buffer, player); } @Override - public void sendActionPacket(ModularSyncManager msm, String panel, String key, FriendlyByteBuf buffer, Player player) { + public void sendActionPacket(ModularSyncManager msm, String panel, String key, FriendlyByteBuf buffer, + Player player) { get(player).sendActionPacket(msm, panel, key, buffer, player); } diff --git a/src/main/java/brachy/modularui/network/ModularNetworkSide.java b/src/main/java/brachy/modularui/network/ModularNetworkSide.java index 92647ace..9693e4b9 100644 --- a/src/main/java/brachy/modularui/network/ModularNetworkSide.java +++ b/src/main/java/brachy/modularui/network/ModularNetworkSide.java @@ -29,7 +29,8 @@ public abstract class ModularNetworkSide { abstract void sendPacket(NetworkHandler.INetPacket packet, Player player); void activateInternal(int networkId, ModularSyncManager manager) { - if (activeScreens.containsKey(networkId)) throw new IllegalStateException("Network ID " + networkId + " is already active."); + if (activeScreens.containsKey(networkId)) + throw new IllegalStateException("Network ID " + networkId + " is already active."); activeScreens.put(networkId, manager); inverseActiveScreens.put(manager, networkId); } diff --git a/src/main/java/brachy/modularui/overlay/DebugOverlay.java b/src/main/java/brachy/modularui/overlay/DebugOverlay.java index 6493c381..cea50ac2 100644 --- a/src/main/java/brachy/modularui/overlay/DebugOverlay.java +++ b/src/main/java/brachy/modularui/overlay/DebugOverlay.java @@ -117,13 +117,15 @@ public DebugOverlay(IMuiScreen screen) { .child(toggleOption(10, "Any", "showParent")) .child(toggleOption(11, "Pos", "showParentPos")) .child(toggleOption(12, "Size", "showParentSize")) - .child(toggleOption(13, "Widget Theme", "showParentWidgetTheme")) + .child(toggleOption(13, "Widget Theme", + "showParentWidgetTheme")) .child(toggleOption(14, "Outline", "showParentOutline"))))))); } public static IWidget toggleOption(int i, String name, String field) { Object config = ModularUIConfig.CONFIG.getValues().get(List.of("dev", field)); - if (!(config instanceof ForgeConfigSpec.ConfigValue configValue) || !(configValue.get() instanceof Boolean)) { + if (!(config instanceof ForgeConfigSpec.ConfigValue configValue) || + !(configValue.get() instanceof Boolean)) { throw new IllegalArgumentException("Config field 'dev.%s' is not a boolean value!".formatted(field)); } @SuppressWarnings("unchecked") diff --git a/src/main/java/brachy/modularui/overlay/OverlayStack.java b/src/main/java/brachy/modularui/overlay/OverlayStack.java index d81b426b..3b4d60db 100644 --- a/src/main/java/brachy/modularui/overlay/OverlayStack.java +++ b/src/main/java/brachy/modularui/overlay/OverlayStack.java @@ -9,10 +9,10 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraftforge.common.MinecraftForge; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/brachy/modularui/screen/BuildPanelEvent.java b/src/main/java/brachy/modularui/screen/BuildPanelEvent.java index 5d916f92..82560731 100644 --- a/src/main/java/brachy/modularui/screen/BuildPanelEvent.java +++ b/src/main/java/brachy/modularui/screen/BuildPanelEvent.java @@ -11,14 +11,18 @@ * An event that is invoked after a panel has been build. * Sub panels can be completely replaced using the {@link SubPanel sub panel event}. * Main panels can not be replaced, but it's children can be by using - * {@link brachy.modularui.api.widget.IWidget#visitTransformAllChildren(UnaryOperator) IWidget.visitTransformAllChildren(UnaryOperator)}. + * {@link brachy.modularui.api.widget.IWidget#visitTransformAllChildren(UnaryOperator) + * IWidget.visitTransformAllChildren(UnaryOperator)}. */ @ApiStatus.NonExtendable public class BuildPanelEvent extends Event { - @Getter private final ModularScreen screen; - @Getter private final ModularPanel mainPanel; - @Getter protected ModularPanel openingPanel; + @Getter + private final ModularScreen screen; + @Getter + private final ModularPanel mainPanel; + @Getter + protected ModularPanel openingPanel; protected BuildPanelEvent(ModularScreen screen, ModularPanel openingPanel) { this.screen = screen; @@ -47,7 +51,8 @@ public boolean matches(String screenOwner, String mainPanel) { } public boolean matches(String screenOwner, String mainPanel, String openingPanel) { - return getScreenName().equals(screenOwner) && getMainPanelName().equals(mainPanel) && getOpeningPanelName().equals(openingPanel); + return getScreenName().equals(screenOwner) && getMainPanelName().equals(mainPanel) && + getOpeningPanelName().equals(openingPanel); } public static final class MainPanel extends BuildPanelEvent { diff --git a/src/main/java/brachy/modularui/screen/ClientScreenHandler.java b/src/main/java/brachy/modularui/screen/ClientScreenHandler.java index 00d448f7..8972982d 100644 --- a/src/main/java/brachy/modularui/screen/ClientScreenHandler.java +++ b/src/main/java/brachy/modularui/screen/ClientScreenHandler.java @@ -45,9 +45,6 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.HitResult; -import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ContainerScreenEvent; import net.minecraftforge.client.event.ScreenEvent; @@ -58,6 +55,9 @@ import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.Getter; import org.jetbrains.annotations.ApiStatus; @@ -110,8 +110,9 @@ public static void onInitScreenPost(ScreenEvent.Init.Post event) { OverlayStack.foreach(ms -> ms.onResize(event.getScreen().width, event.getScreen().height), false); } - // TODO: Figure out when exactly early inputs (before recipe viewer) for mouse press, mouse release, key press, key release, - // mouse scroll and mouse drag are needed. One case would may be draggable widgets. + // TODO: Figure out when exactly early inputs (before recipe viewer) for mouse press, mouse release, key press, key + // release, + // mouse scroll and mouse drag are needed. One case would may be draggable widgets. @SubscribeEvent public static void onScreenKeyPressedHigh(ScreenEvent.KeyPressed.Pre event) { defaultContext.updateKey(event.getKeyCode(), event.getScanCode(), event.getModifiers(), true); @@ -371,7 +372,8 @@ private static boolean keyTyped(Screen screen, int keyCode, int scanCode, int mo } if (!hasLevel) return false; // E only closes in world if (Minecraft.getInstance().options.keyInventory - .isActiveAndMatches(InputConstants.getKey(keyCode, scanCode)) && !RecipeViewerHandler.getCurrent().isSearchFocused()) { + .isActiveAndMatches(InputConstants.getKey(keyCode, scanCode)) && + !RecipeViewerHandler.getCurrent().isSearchFocused()) { dropOrClosePanel(); return true; } @@ -446,7 +448,8 @@ public static void drawScreen(GuiGraphics graphics, ModularScreen muiScreen, Scr } } - public static void drawScreenInternal(GuiGraphics graphics, ModularScreen muiScreen, Screen mcScreen, int mouseX, int mouseY, float partialTicks) { + public static void drawScreenInternal(GuiGraphics graphics, ModularScreen muiScreen, Screen mcScreen, int mouseX, + int mouseY, float partialTicks) { Stencil.reset(); muiScreen.getContext().reset(); muiScreen.getContext().getStencil().push(muiScreen.getScreenArea()); @@ -550,12 +553,14 @@ private static void drawFloatingItemStack(AbstractContainerScreen mcScreen, G } @ApiStatus.Internal - public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, int mouseX, int mouseY, float partialTicks) { + public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, int mouseX, int mouseY, + float partialTicks) { drawVanillaElements(graphics, mcScreen, mouseX, mouseY, partialTicks, r -> true); } @ApiStatus.Internal - public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, int mouseX, int mouseY, float partialTicks, Predicate filter) { + public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, int mouseX, int mouseY, + float partialTicks, Predicate filter) { for (Renderable renderable : mcScreen.renderables) { if (filter.test(renderable)) { renderable.render(graphics, mouseX, mouseY, partialTicks); @@ -563,7 +568,8 @@ public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, in } } - public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen muiScreen, @Nullable ModularScreen fallback) { + public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen muiScreen, + @Nullable ModularScreen fallback) { fpsCounter.onDraw(); if (!ModularUIConfig.Dev.debugUI()) return; if (muiScreen == null) { @@ -582,8 +588,10 @@ public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen int mouseX = context.getAbsMouseX(), mouseY = context.getAbsMouseY(); int screenH = muiScreen.getScreenArea().height; - int outlineColor = Color.parseString(ModularUIConfig.DEBUG_OUTLINE_COLOR.get(), DEFAULT_DEBUG_OUTLINE_COLOR).resultOrPartial(s -> {}).orElseThrow(); - int textColor = Color.parseString(ModularUIConfig.DEBUG_TEXT_COLOR.get(), DEFAULT_DEBUG_TEXT_COLOR).resultOrPartial(s -> {}).orElseThrow(); + int outlineColor = Color.parseString(ModularUIConfig.DEBUG_OUTLINE_COLOR.get(), DEFAULT_DEBUG_OUTLINE_COLOR) + .resultOrPartial(s -> {}).orElseThrow(); + int textColor = Color.parseString(ModularUIConfig.DEBUG_TEXT_COLOR.get(), DEFAULT_DEBUG_TEXT_COLOR) + .resultOrPartial(s -> {}).orElseThrow(); float scale = ModularUIConfig.Dev.scale(); int shift = (int) (11 * scale + 0.5f); int lineY = screenH - shift - 2; @@ -635,7 +643,8 @@ public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen locatedHovered.unapplyMatrix(context); if (showHovered) { if (ModularUIConfig.Dev.showWidgetTheme()) { - s = I18n.get("modularui.debug.widget_theme_key", hovered.getWidgetThemeEntry(hovered.getTheme()).key().getFullName()); + s = I18n.get("modularui.debug.widget_theme_key", + hovered.getWidgetThemeEntry(hovered.getTheme()).key().getFullName()); GuiDraw.drawText(graphics, s, 5, lineY, scale, textColor, true); lineY -= shift; } @@ -658,7 +667,8 @@ public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen lineY -= 10; } if (ModularUIConfig.Dev.showParentWidgetTheme()) { - s = I18n.get("modularui.debug.widget_theme_key", parent.getWidgetThemeEntry(parent.getTheme()).key().getFullName()); + s = I18n.get("modularui.debug.widget_theme_key", + parent.getWidgetThemeEntry(parent.getTheme()).key().getFullName()); GuiDraw.drawText(graphics, s, 5, lineY, scale, textColor, true); lineY -= shift; } @@ -690,7 +700,8 @@ public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen if (slotWidget.isSynced()) { SlotGroup slotGroup = slot.getSlotGroup(); boolean allowShiftTransfer = slotGroup != null && slotGroup.isAllowShiftTransfer(); - s = I18n.get("modularui.debug.shift_click_priority", allowShiftTransfer ? slotGroup.getShiftClickPriority() : "DISABLED"); + s = I18n.get("modularui.debug.shift_click_priority", + allowShiftTransfer ? slotGroup.getShiftClickPriority() : "DISABLED"); GuiDraw.drawText(graphics, s, 5, lineY, scale, textColor, true); } } else if (hovered instanceof RichTextWidget richTextWidget) { diff --git a/src/main/java/brachy/modularui/screen/ContainerScreenWrapper.java b/src/main/java/brachy/modularui/screen/ContainerScreenWrapper.java index bc83da69..e17a8593 100755 --- a/src/main/java/brachy/modularui/screen/ContainerScreenWrapper.java +++ b/src/main/java/brachy/modularui/screen/ContainerScreenWrapper.java @@ -31,7 +31,7 @@ public ContainerScreenWrapper(ModularContainerMenu container, @NotNull ModularSc * * @deprecated Internal use only. */ - @SuppressWarnings({"DataFlowIssue", "DeprecatedIsStillUsed"}) + @SuppressWarnings({ "DataFlowIssue", "DeprecatedIsStillUsed" }) @Deprecated @ApiStatus.Internal public ContainerScreenWrapper(ModularContainerMenu container, Inventory playerInventory, Component title) { diff --git a/src/main/java/brachy/modularui/screen/EmbedHandler.java b/src/main/java/brachy/modularui/screen/EmbedHandler.java index 7c229a23..73b9ea43 100644 --- a/src/main/java/brachy/modularui/screen/EmbedHandler.java +++ b/src/main/java/brachy/modularui/screen/EmbedHandler.java @@ -5,15 +5,12 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.Renderable; import net.minecraft.client.gui.screens.Screen; + import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; - import org.jetbrains.annotations.Nullable; -import java.util.function.Predicate; - public class EmbedHandler { public static int getEmbedWidth(ModularScreen screen) { @@ -24,7 +21,8 @@ public static int getEmbedHeight(ModularScreen screen) { return screen.getMainPanel().getArea().height; } - public static void drawEmbed(ModularScreen screen, GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + public static void drawEmbed(ModularScreen screen, GuiGraphics graphics, int mouseX, int mouseY, + float partialTicks) { drawEmbed(screen, graphics, mouseX, mouseY, partialTicks, null, null); } diff --git a/src/main/java/brachy/modularui/screen/ModularContainerMenu.java b/src/main/java/brachy/modularui/screen/ModularContainerMenu.java index dbd79d33..9cb55c01 100644 --- a/src/main/java/brachy/modularui/screen/ModularContainerMenu.java +++ b/src/main/java/brachy/modularui/screen/ModularContainerMenu.java @@ -19,11 +19,11 @@ import net.minecraft.world.inventory.ClickType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.InputConstants; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.items.ItemHandlerHelper; +import com.mojang.blaze3d.platform.InputConstants; import lombok.Getter; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; @@ -64,14 +64,16 @@ public ModularContainerMenu(int containerId) { super(ModularUIMenuTypes.MODULAR_CONTAINER.get(), containerId); } - public ModularContainerMenu(int containerId, Inventory playerInv, @Nullable FriendlyByteBuf data) { + public ModularContainerMenu(int containerId, Inventory playerInv, + @Nullable FriendlyByteBuf data) { this(containerId); // TODO: Better integration with menu types for custom containers and screens. throw new IllegalArgumentException("Do not open the modular container the forge way. Use an UIFactory!"); } @ApiStatus.Internal - public void construct(Player player, ModularSyncManager msm, UISettings settings, String mainPanelName, GuiData guiData) { + public void construct(Player player, ModularSyncManager msm, UISettings settings, String mainPanelName, + GuiData guiData) { this.player = player; this.syncManager = msm; this.syncManager.construct(this, mainPanelName); @@ -171,7 +173,8 @@ public void registerSlot(String panelName, ModularSlot slot) { if (slot.getSlotGroupName() != null) { SlotGroup slotGroup = getSyncManager().getSlotGroup(panelName, slot.getSlotGroupName()); if (slotGroup == null) { - ModularUI.LOGGER.throwing(new IllegalArgumentException("SlotGroup '" + slot.getSlotGroupName() + "' is not registered!")); + ModularUI.LOGGER.throwing( + new IllegalArgumentException("SlotGroup '" + slot.getSlotGroupName() + "' is not registered!")); return; } slot.slotGroup(slotGroup); @@ -190,7 +193,8 @@ public void registerSlot(String panelName, ModularSlot slot) { @Contract("_, null, null -> fail") @NotNull @ApiStatus.Internal - public SlotGroup validateSlotGroup(String panelName, @Nullable String slotGroupName, @Nullable SlotGroup slotGroup) { + public SlotGroup validateSlotGroup(String panelName, @Nullable String slotGroupName, + @Nullable SlotGroup slotGroup) { if (slotGroup != null) { if (getSyncManager().getSlotGroup(panelName, slotGroup.getName()) == null) { throw new IllegalArgumentException("Slot group is not registered in the GUI."); @@ -325,19 +329,19 @@ public void clicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, } } else if (heldStack.getMaxStackSize() > 1 && ItemStack.isSameItemSameTags(slotStack, heldStack) && !slotStack.isEmpty()) { - int stackCount = slotStack.getCount(); + int stackCount = slotStack.getCount(); - if (stackCount + heldStack.getCount() <= heldStack.getMaxStackSize()) { - heldStack.grow(stackCount); - slotStack = clickedSlot.remove(stackCount); + if (stackCount + heldStack.getCount() <= heldStack.getMaxStackSize()) { + heldStack.grow(stackCount); + slotStack = clickedSlot.remove(stackCount); - if (slotStack.isEmpty()) { - clickedSlot.setByPlayer(ItemStack.EMPTY); - } + if (slotStack.isEmpty()) { + clickedSlot.setByPlayer(ItemStack.EMPTY); + } - clickedSlot.onTake(player, this.getCarried()); - } - } + clickedSlot.onTake(player, this.getCarried()); + } + } } clickedSlot.setChanged(); } @@ -353,7 +357,8 @@ public void clicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, int step = mouseButton == InputConstants.MOUSE_BUTTON_LEFT ? 1 : -1; for (int i = 0; i < 2; ++i) { - for (int s = start; s >= 0 && s < slots.size() && carried.getCount() < carried.getMaxStackSize(); s += step) { + for (int s = start; s >= 0 && s < slots.size() && + carried.getCount() < carried.getMaxStackSize(); s += step) { Slot current = slots.get(s); if (current instanceof ModularSlot modularSlot && modularSlot.isPhantom()) continue; @@ -382,80 +387,85 @@ public void clicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, broadcastChanges(); } else if (clickTypeIn == ClickType.SWAP && ((mouseButton >= 0 && mouseButton < 9) || mouseButton == Inventory.SLOT_OFFHAND)) { - // minecraft does not check if the hotbar slot can actually take and put items - Slot hotbarSlot = findPlayerSlot(player, mouseButton); // mouseButton is the slot index here - if (hotbarSlot == null && mouseButton == Inventory.SLOT_OFFHAND) { - // the offhand is usually not bound as a slot, but it still needs to respect stack size limits - hotbarSlot = new Slot(inventory, Inventory.SLOT_OFFHAND, 0, 0); - } - if (hotbarSlot != null && slotId >= 0) { - Slot fromSlot = getSlot(slotId); - ItemStack fromStack = fromSlot.getItem().copy(); - ItemStack hotbarStack = hotbarSlot.getItem().copy(); - - if (!fromStack.isEmpty() && !hotbarSlot.mayPlace(fromStack)) return; - if (!hotbarStack.isEmpty() && !fromSlot.mayPlace(hotbarStack)) return; - if (!fromStack.isEmpty() && !fromSlot.mayPickup(player)) return; - if (!hotbarStack.isEmpty() && !hotbarSlot.mayPickup(player)) return; - - if (!fromStack.isEmpty() && !hotbarStack.isEmpty() && ItemStack.isSameItemSameTags(fromStack, hotbarStack)) { - int hotbarLimit = hotbarSlot.getMaxStackSize(fromStack); - if (hotbarStack.getCount() < hotbarLimit) { - int toMove = Math.min(fromStack.getCount(), hotbarLimit - hotbarStack.getCount()); - hotbarStack.grow(toMove); - fromStack.shrink(toMove); - hotbarSlot.set(hotbarStack); - fromSlot.set(fromStack); + // minecraft does not check if the hotbar slot can actually take and put items + Slot hotbarSlot = findPlayerSlot(player, mouseButton); // mouseButton is the slot index here + if (hotbarSlot == null && mouseButton == Inventory.SLOT_OFFHAND) { + // the offhand is usually not bound as a slot, but it still needs to respect stack size limits + hotbarSlot = new Slot(inventory, Inventory.SLOT_OFFHAND, 0, 0); + } + if (hotbarSlot != null && slotId >= 0) { + Slot fromSlot = getSlot(slotId); + ItemStack fromStack = fromSlot.getItem().copy(); + ItemStack hotbarStack = hotbarSlot.getItem().copy(); + + if (!fromStack.isEmpty() && !hotbarSlot.mayPlace(fromStack)) return; + if (!hotbarStack.isEmpty() && !fromSlot.mayPlace(hotbarStack)) return; + if (!fromStack.isEmpty() && !fromSlot.mayPickup(player)) return; + if (!hotbarStack.isEmpty() && !hotbarSlot.mayPickup(player)) return; + + if (!fromStack.isEmpty() && !hotbarStack.isEmpty() && + ItemStack.isSameItemSameTags(fromStack, hotbarStack)) { + int hotbarLimit = hotbarSlot.getMaxStackSize(fromStack); + if (hotbarStack.getCount() < hotbarLimit) { + int toMove = Math.min(fromStack.getCount(), hotbarLimit - hotbarStack.getCount()); + hotbarStack.grow(toMove); + fromStack.shrink(toMove); + hotbarSlot.set(hotbarStack); + fromSlot.set(fromStack); + } + return; + } + boolean canFitInHotbar = fromStack.isEmpty() || + fromStack.getCount() <= hotbarSlot.getMaxStackSize(fromStack); + boolean canFitInFromSlot = hotbarStack.isEmpty() || + hotbarStack.getCount() <= fromSlot.getMaxStackSize(hotbarStack); + + if (canFitInHotbar && canFitInFromSlot) { + fromSlot.setByPlayer(hotbarStack); + hotbarSlot.setByPlayer(fromStack); + fromSlot.onTake(player, fromStack); + return; + } + if (hotbarStack.isEmpty() && !fromStack.isEmpty()) { + int moveAmt = hotbarSlot.getMaxStackSize(fromStack); + hotbarStack = fromStack.copyWithCount(moveAmt); + fromStack.shrink(moveAmt); + fromSlot.set(fromStack); + hotbarSlot.setByPlayer(hotbarStack); + } else if (fromStack.isEmpty() && !hotbarStack.isEmpty()) { + int moveAmt = fromSlot.getMaxStackSize(hotbarStack); + fromStack = hotbarStack.copyWithCount(moveAmt); + hotbarStack.shrink(moveAmt); + fromSlot.setByPlayer(fromStack); + hotbarSlot.set(hotbarStack); + } + } + } else + if (clickTypeIn == ClickType.THROW && getCarried().isEmpty() && slotId >= 0) { + Slot slot = getSlot(slotId); + + if (slot.hasItem() && slot.mayPickup(player)) { + ItemStack stackInSlot = slot.getItem().copy(); + int amountToDrop = 1; + // mouseButton 1 is CTRL+Q + if (mouseButton == 1) { + amountToDrop = Math.min(stackInSlot.getCount(), stackInSlot.getMaxStackSize()); } - return; - } - boolean canFitInHotbar = fromStack.isEmpty() || fromStack.getCount() <= hotbarSlot.getMaxStackSize(fromStack); - boolean canFitInFromSlot = hotbarStack.isEmpty() || hotbarStack.getCount() <= fromSlot.getMaxStackSize(hotbarStack); - - if (canFitInHotbar && canFitInFromSlot) { - fromSlot.setByPlayer(hotbarStack); - hotbarSlot.setByPlayer(fromStack); - fromSlot.onTake(player, fromStack); - return; - } - if (hotbarStack.isEmpty() && !fromStack.isEmpty()) { - int moveAmt = hotbarSlot.getMaxStackSize(fromStack); - hotbarStack = fromStack.copyWithCount(moveAmt); - fromStack.shrink(moveAmt); - fromSlot.set(fromStack); - hotbarSlot.setByPlayer(hotbarStack); - } else if (fromStack.isEmpty() && !hotbarStack.isEmpty()) { - int moveAmt = fromSlot.getMaxStackSize(hotbarStack); - fromStack = hotbarStack.copyWithCount(moveAmt); - hotbarStack.shrink(moveAmt); - fromSlot.setByPlayer(fromStack); - hotbarSlot.set(hotbarStack); - } - } - } else if (clickTypeIn == ClickType.THROW && getCarried().isEmpty() && slotId >= 0) { - Slot slot = getSlot(slotId); - - if (slot.hasItem() && slot.mayPickup(player)) { - ItemStack stackInSlot = slot.getItem().copy(); - int amountToDrop = 1; - // mouseButton 1 is CTRL+Q - if (mouseButton == 1) { - amountToDrop = Math.min(stackInSlot.getCount(), stackInSlot.getMaxStackSize()); - } - if (amountToDrop > 0) { - ItemStack droppedStack = stackInSlot.copyWithCount(amountToDrop); - stackInSlot.shrink(amountToDrop); - slot.set(stackInSlot); - player.drop(droppedStack, true); + if (amountToDrop > 0) { + ItemStack droppedStack = stackInSlot.copyWithCount(amountToDrop); + stackInSlot.shrink(amountToDrop); + slot.set(stackInSlot); + player.drop(droppedStack, true); + } } + } else { + superClicked(slotId, mouseButton, clickTypeIn, player); } - } else { - superClicked(slotId, mouseButton, clickTypeIn, player); - } } - protected final void superClicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, @NotNull Player player) { + protected final void superClicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, + @NotNull Player player) { super.clicked(slotId, mouseButton, clickTypeIn, player); } @@ -507,7 +517,8 @@ protected Slot findExternalPlayerSlot(Player player, int index) { slot.onQuickCraft(remainder, copy); slot.onTake(playerIn, remainder); slot.onCraftShiftClick(playerIn, remainder); - return copy; // return a non-empty stack if insertion was successful, this causes this function to be called again, important for crafting + return copy; // return a non-empty stack if insertion was successful, this causes this function to be + // called again, important for crafting } } return ItemStack.EMPTY; @@ -521,7 +532,8 @@ protected ItemStack transferItem(ModularSlot fromSlot, ItemStack fromStack) { SlotGroup slotGroup = Objects.requireNonNull(toSlot.getSlotGroup()); if (slotGroup != fromSlotGroup && toSlot.isActive() && toSlot.mayPlace(fromStack)) { ItemStack toStack = toSlot.getItem().copy(); - if (!toSlot.isPhantom() && !fromSlot.isPhantom() && ItemHandlerHelper.canItemStacksStack(fromStack, toStack)) { + if (!toSlot.isPhantom() && !fromSlot.isPhantom() && + ItemHandlerHelper.canItemStacksStack(fromStack, toStack)) { int j = toStack.getCount() + fromStack.getCount(); // Math.min(toSlot.getMaxStackSize(), fromStack.getMaxStackSize()); int maxSize = toSlot.getMaxStackSize(fromStack); diff --git a/src/main/java/brachy/modularui/screen/ModularPanel.java b/src/main/java/brachy/modularui/screen/ModularPanel.java index b16c6d3d..009bc95b 100644 --- a/src/main/java/brachy/modularui/screen/ModularPanel.java +++ b/src/main/java/brachy/modularui/screen/ModularPanel.java @@ -52,7 +52,8 @@ * This class is like a window in windows. It can hold any amount of widgets. It may also be draggable. * To open another panel on top of the main panel you must use * {@link IPanelHandler#simple(ModularPanel, SecondaryPanel.IPanelBuilder, boolean)} - * or {@link PanelSyncManager#syncedPanel(String, boolean, PanelSyncHandler.IPanelBuilder)} if the panel should be synced. + * or {@link PanelSyncManager#syncedPanel(String, boolean, PanelSyncHandler.IPanelBuilder)} if the panel should be + * synced. */ public class ModularPanel> extends ParentWidget implements IViewport, IDragResizeable { @@ -99,7 +100,8 @@ public static ModularPanel defaultPanel(@NotNull String name, int width, int /** * True if this panel can be dragged. Never works on the main panel. */ - @Getter private boolean draggable = true; + @Getter + private boolean draggable = true; private boolean disablePanelsBelow = false; private boolean closeOnOutOfBoundsClick = false; @@ -177,7 +179,8 @@ public void closeIfOpen() { } getAnimator().onFinish(() -> { if (this.screen != null) { - // can happen when multiple panels close at once and animation is enabled, but NEA is currently not ported so screen + // can happen when multiple panels close at once and animation is enabled, but NEA is currently not + // ported so screen // before sub panels can finish animating this.screen.getPanelManager().closePanel(this); } @@ -287,7 +290,8 @@ public void onClose() { @Override public boolean isExcludeAreaInRecipeViewer() { - return super.isExcludeAreaInRecipeViewer() || (!getScreen().isOverlay() && !this.invisible && !resizer().isFullSize()); + return super.isExcludeAreaInRecipeViewer() || + (!getScreen().isOverlay() && !this.invisible && !resizer().isFullSize()); } @MustBeInvokedByOverriders diff --git a/src/main/java/brachy/modularui/screen/ModularScreen.java b/src/main/java/brachy/modularui/screen/ModularScreen.java index 23974886..4fbb6d1c 100644 --- a/src/main/java/brachy/modularui/screen/ModularScreen.java +++ b/src/main/java/brachy/modularui/screen/ModularScreen.java @@ -29,14 +29,14 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.MinecraftForge; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -101,29 +101,38 @@ public static ModularScreen createEmbed(String owner, ModularPanel panel, int /** * The full id of this screen as a {@link ResourceLocation}. Consists of the owner and name. + * * @return The full id of this screen * @see #getOwner() * @see #getName() */ @SuppressWarnings("JavadocDeclaration") - @Getter private final ResourceLocation id; - @Getter private final PanelManager panelManager; - @Getter private final ModularGuiContext context; + @Getter + private final ResourceLocation id; + @Getter + private final PanelManager panelManager; + @Getter + private final ModularGuiContext context; private final Map, List> guiActionListeners = new Object2ObjectOpenHashMap<>(); private final Object2ObjectArrayMap frameUpdates = new Object2ObjectArrayMap<>(); - @Getter private final ScreenResizeNode resizeNode = new ScreenResizeNode(this); - @Getter private boolean pauseScreen = false; - @Getter private boolean openParentOnClose = false; + @Getter + private final ScreenResizeNode resizeNode = new ScreenResizeNode(this); + @Getter + private boolean pauseScreen = false; + @Getter + private boolean openParentOnClose = false; @Getter @Nullable private String themeOverride; private ITheme currentTheme; - @Getter private IMuiScreen screenWrapper; + @Getter + private IMuiScreen screenWrapper; /** * true if this is an overlay for another screen */ - @Getter private boolean overlay = false; + @Getter + private boolean overlay = false; private double lastUpdate = -1, lastFrameUpdate = -1; @@ -144,13 +153,16 @@ public ModularScreen(@NotNull String owner, @NotNull ModularPanel mainPanel) * @param mainPanelCreator function which creates the main panel of this screen */ public ModularScreen(String owner, @NotNull Function> mainPanelCreator) { - this(UIType.MODULAR_SCREEN, owner, Objects.requireNonNull(mainPanelCreator, "The main panel function must not be null!"), false); + this(UIType.MODULAR_SCREEN, owner, + Objects.requireNonNull(mainPanelCreator, "The main panel function must not be null!"), false); } - private ModularScreen(UIType uiType, String owner, @Nullable Function> mainPanelCreator, boolean __) { + private ModularScreen(UIType uiType, String owner, + @Nullable Function> mainPanelCreator, boolean __) { this.context = new ModularGuiContext(Objects.requireNonNull(uiType, "UIType must not be null"), this); Objects.requireNonNull(owner, "The owner must not be null!"); - ModularPanel mainPanel = mainPanelCreator != null ? mainPanelCreator.apply(this.context) : buildUI(this.context); + ModularPanel mainPanel = mainPanelCreator != null ? mainPanelCreator.apply(this.context) : + buildUI(this.context); Objects.requireNonNull(mainPanel, "The main panel must not be null!"); this.id = ResourceLocation.fromNamespaceAndPath(owner, mainPanel.getName()); this.panelManager = new PanelManager(this, mainPanel); @@ -309,7 +321,7 @@ public void onUpdate() { public void onFrameUpdate() { this.panelManager.checkDirty(); for (ObjectIterator> iterator = this.frameUpdates - .object2ObjectEntrySet().fastIterator(); iterator.hasNext(); ) { + .object2ObjectEntrySet().fastIterator(); iterator.hasNext();) { Object2ObjectMap.Entry entry = iterator.next(); if (!entry.getKey().isValid()) { iterator.remove(); @@ -583,7 +595,8 @@ public boolean mouseScrolled(double delta) { * Interactable#onMouseDrag(double, double, int, double, double)} on every widget * under the mouse after gui action listeners have been called. * - * @param button mouse button that is held down (0 = left button, 1 = right button, 2 = scroll button, 4 and 5 = side buttons) + * @param button mouse button that is held down (0 = left button, 1 = right button, 2 = scroll button, 4 and 5 = + * side buttons) * @param dragX the X distance of the drag * @param dragY the Y distance of the drag * @return true if the action was consumed and further processing should be canceled @@ -677,8 +690,8 @@ public Area getScreenArea() { } public boolean isClientOnly() { - return isOverlay() || getContext().getUIType() != UIType.MODULAR_SCREEN - || !this.screenWrapper.isContainerScreen() || getContainer().isClientOnly(); + return isOverlay() || getContext().getUIType() != UIType.MODULAR_SCREEN || + !this.screenWrapper.isContainerScreen() || getContainer().isClientOnly(); } public ModularContainerMenu getContainer() { diff --git a/src/main/java/brachy/modularui/screen/OpenScreenEvent.java b/src/main/java/brachy/modularui/screen/OpenScreenEvent.java index 881e8079..5b059c1e 100644 --- a/src/main/java/brachy/modularui/screen/OpenScreenEvent.java +++ b/src/main/java/brachy/modularui/screen/OpenScreenEvent.java @@ -13,8 +13,10 @@ public class OpenScreenEvent extends Event { - @Getter private final Screen screen; - @Getter private final List overlays = new ArrayList<>(); + @Getter + private final Screen screen; + @Getter + private final List overlays = new ArrayList<>(); public OpenScreenEvent(Screen screen) { this.screen = screen; diff --git a/src/main/java/brachy/modularui/screen/PanelManager.java b/src/main/java/brachy/modularui/screen/PanelManager.java index a07fa3fc..dabf0831 100644 --- a/src/main/java/brachy/modularui/screen/PanelManager.java +++ b/src/main/java/brachy/modularui/screen/PanelManager.java @@ -221,7 +221,8 @@ public void closeTopPanel() { } /** - * Closes all panels. Note that this won't close the screen and can put the screen and main panel into an invalid state if used + * Closes all panels. Note that this won't close the screen and can put the screen and main panel into an invalid + * state if used * incorrectly. Use {@link #closePanelsAndScreen()} to actually close all panels and the screen properly. * * @return if the screen was open diff --git a/src/main/java/brachy/modularui/screen/RecipeViewerSettingsImpl.java b/src/main/java/brachy/modularui/screen/RecipeViewerSettingsImpl.java index 3e6d0b9d..15a83fa0 100644 --- a/src/main/java/brachy/modularui/screen/RecipeViewerSettingsImpl.java +++ b/src/main/java/brachy/modularui/screen/RecipeViewerSettingsImpl.java @@ -155,7 +155,7 @@ public List> getGhostIngredientSlots() { public List getAllExclusionAreas() { this.exclusionWidgets.removeIf(widget -> !widget.isValid()); List areas = new ArrayList<>(this.exclusionAreas); - for (Iterator iterator = this.exclusionWidgets.iterator(); iterator.hasNext(); ) { + for (Iterator iterator = this.exclusionWidgets.iterator(); iterator.hasNext();) { IWidget widget = iterator.next(); if (!widget.isValid()) { iterator.remove(); diff --git a/src/main/java/brachy/modularui/screen/RichTooltip.java b/src/main/java/brachy/modularui/screen/RichTooltip.java index 3b6cbadb..c8773977 100644 --- a/src/main/java/brachy/modularui/screen/RichTooltip.java +++ b/src/main/java/brachy/modularui/screen/RichTooltip.java @@ -27,14 +27,14 @@ import net.minecraft.util.StringRepresentable; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.serialization.Codec; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.RenderTooltipEvent; import net.minecraftforge.common.MinecraftForge; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -72,11 +72,13 @@ public class RichTooltip implements IRichTextBuilder { @Getter @Setter private boolean autoUpdate = false; - @Getter private int titleMargin = 0; + @Getter + private int titleMargin = 0; private boolean appliedMargin = true; private int x = 0, y = 0; - @Getter private int maxWidth = Integer.MAX_VALUE; + @Getter + private int maxWidth = Integer.MAX_VALUE; private boolean dirty; @@ -156,22 +158,26 @@ public void draw(GuiContext context, ItemStack stack) { RichText copy = this.text.copy(); // rich event to gather additional tooltip // this does not trigger vanilla event listeners - var richGatherEventPre = new RichTooltipEvent.Gather.Pre(copy, stack, context, mouseX, mouseY, screen.width, screen.height, this.maxWidth); + var richGatherEventPre = new RichTooltipEvent.Gather.Pre(copy, stack, context, mouseX, mouseY, screen.width, + screen.height, this.maxWidth); if (MinecraftForge.EVENT_BUS.post(richGatherEventPre)) return; this.maxWidth = richGatherEventPre.getMaxWidth(); // vanilla event to gather additional tooltip TooltipLines textLines = copy.getAsText(); - // wrap the List> in the type vanilla wants. Listeners may add any FormattedText, - // which the wrapper converts into Components. + // wrap the List> in the type vanilla wants. Listeners may add any + // FormattedText, + // which the wrapper converts into Components. // noinspection UnstableApiUsage - var vanillaGatherEvent = new RenderTooltipEvent.GatherComponents(stack, screen.width, screen.height, textLines.vanillaElementHandler(), this.maxWidth); + var vanillaGatherEvent = new RenderTooltipEvent.GatherComponents(stack, screen.width, screen.height, + textLines.vanillaElementHandler(), this.maxWidth); if (MinecraftForge.EVENT_BUS.post(vanillaGatherEvent)) return; this.maxWidth = vanillaGatherEvent.getMaxWidth(); // rich event to gather additional tooltip // this does not trigger vanilla event listeners - var richGatherEventPost = new RichTooltipEvent.Gather.Post(copy, stack, context, mouseX, mouseY, screen.width, screen.height, this.maxWidth); + var richGatherEventPost = new RichTooltipEvent.Gather.Post(copy, stack, context, mouseX, mouseY, screen.width, + screen.height, this.maxWidth); if (MinecraftForge.EVENT_BUS.post(richGatherEventPost)) return; this.maxWidth = richGatherEventPost.getMaxWidth(); @@ -461,8 +467,8 @@ public final boolean equals(Object o) { if (!(o instanceof RichTooltip that)) return false; return showUpTimer == that.showUpTimer && autoUpdate == that.autoUpdate && - titleMargin == that.titleMargin && appliedMargin == that.appliedMargin - && x == that.x && y == that.y && maxWidth == that.maxWidth && + titleMargin == that.titleMargin && appliedMargin == that.appliedMargin && x == that.x && y == that.y && + maxWidth == that.maxWidth && text.equals(that.text) && Objects.equals(parent, that.parent) && pos == that.pos && Objects.equals(tooltipBuilder, that.tooltipBuilder); } diff --git a/src/main/java/brachy/modularui/screen/UISettings.java b/src/main/java/brachy/modularui/screen/UISettings.java index 6ae5621e..34902759 100644 --- a/src/main/java/brachy/modularui/screen/UISettings.java +++ b/src/main/java/brachy/modularui/screen/UISettings.java @@ -33,8 +33,10 @@ public class UISettings { @OnlyIn(Dist.CLIENT) private GuiCreator guiSupplier; private Predicate canInteractWith; - @Getter private String theme; - @Getter private final RecipeViewerSettings recipeViewerSettings; + @Getter + private String theme; + @Getter + private final RecipeViewerSettings recipeViewerSettings; @Getter @Setter @Accessors(fluent = true) diff --git a/src/main/java/brachy/modularui/screen/event/RichTooltipEvent.java b/src/main/java/brachy/modularui/screen/event/RichTooltipEvent.java index 0c62d883..25b99c3f 100755 --- a/src/main/java/brachy/modularui/screen/event/RichTooltipEvent.java +++ b/src/main/java/brachy/modularui/screen/event/RichTooltipEvent.java @@ -32,13 +32,20 @@ private RichTooltipEvent() {} @Cancelable public static class Gather extends Event { - @Getter private final IRichTextBuilder tooltip; - @Getter protected final ItemStack itemStack; - @Getter protected final GuiContext guiContext; - @Getter protected int x; - @Getter protected int y; - @Getter protected int screenWidth; - @Getter protected int screenHeight; + @Getter + private final IRichTextBuilder tooltip; + @Getter + protected final ItemStack itemStack; + @Getter + protected final GuiContext guiContext; + @Getter + protected int x; + @Getter + protected int y; + @Getter + protected int screenWidth; + @Getter + protected int screenHeight; @Getter @Setter protected int maxWidth; diff --git a/src/main/java/brachy/modularui/screen/viewport/GuiContext.java b/src/main/java/brachy/modularui/screen/viewport/GuiContext.java index dbfe84c9..a8c1854c 100644 --- a/src/main/java/brachy/modularui/screen/viewport/GuiContext.java +++ b/src/main/java/brachy/modularui/screen/viewport/GuiContext.java @@ -12,10 +12,10 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; -import com.mojang.blaze3d.vertex.PoseStack; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.blaze3d.vertex.PoseStack; import lombok.Getter; import lombok.Setter; import org.jetbrains.annotations.ApiStatus; @@ -49,21 +49,32 @@ public static GuiContext getDefault() { /* Mouse states */ private int mouseX; private int mouseY; - @Getter private int lastMouseButton; - @Getter private boolean lastButtonPress; // button pressed = true, button released = false - @Getter private double lastMouseScrollDelta; + @Getter + private int lastMouseButton; + @Getter + private boolean lastButtonPress; // button pressed = true, button released = false + @Getter + private double lastMouseScrollDelta; /* Keyboard states */ - @Getter private int lastKeyCode; - @Getter private int lastScanCode; - @Getter private int lastKeyModifiers; - @Getter private char lastCodePoint; - @Getter private boolean lastKeyPress; // key pressed = true, key released = false + @Getter + private int lastKeyCode; + @Getter + private int lastScanCode; + @Getter + private int lastKeyModifiers; + @Getter + private char lastCodePoint; + @Getter + private boolean lastKeyPress; // key pressed = true, key released = false /* Render states */ - @Getter private float renderPartialTicks; - @Getter private long tick = 0; - @Getter private int currentDrawingZ = 0; + @Getter + private float renderPartialTicks; + @Getter + private long tick = 0; + @Getter + private int currentDrawingZ = 0; public GuiContext(UIType uiType) { this.uiType = uiType; diff --git a/src/main/java/brachy/modularui/screen/viewport/GuiViewportStack.java b/src/main/java/brachy/modularui/screen/viewport/GuiViewportStack.java index 491c630c..4452c310 100755 --- a/src/main/java/brachy/modularui/screen/viewport/GuiViewportStack.java +++ b/src/main/java/brachy/modularui/screen/viewport/GuiViewportStack.java @@ -5,7 +5,6 @@ import brachy.modularui.widget.sizer.Area; import com.mojang.blaze3d.vertex.PoseStack; - import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; @@ -92,7 +91,9 @@ public void popViewport(IViewport viewport) { } else { name = this.top.isViewportMatrix() ? asString(this.top.getViewport()) : "not a viewport"; } - throw new IllegalStateException("Viewports must be popped in reverse order they were pushed. Tried to pop '" + asString(viewport) + "', but last pushed is '" + name + "'."); + throw new IllegalStateException( + "Viewports must be popped in reverse order they were pushed. Tried to pop '" + asString(viewport) + + "', but last pushed is '" + name + "'."); } pop(); updateViewport(true); @@ -112,7 +113,8 @@ public void popMatrix() { } public void push(TransformationMatrix transformationMatrix) { - this.viewportStack.push(newMatrix().construct(transformationMatrix, this.top == null ? null : this.top.getMatrix())); + this.viewportStack + .push(newMatrix().construct(transformationMatrix, this.top == null ? null : this.top.getMatrix())); updateViewport(false); if (this.top.isViewportMatrix()) { this.topViewport = this.top; diff --git a/src/main/java/brachy/modularui/screen/viewport/LocatedWidget.java b/src/main/java/brachy/modularui/screen/viewport/LocatedWidget.java index af88fdce..20a7cdd6 100755 --- a/src/main/java/brachy/modularui/screen/viewport/LocatedWidget.java +++ b/src/main/java/brachy/modularui/screen/viewport/LocatedWidget.java @@ -73,6 +73,5 @@ public boolean equals(LocatedWidget a, LocatedWidget b) { if (a == null || b == null) return false; return Objects.equals(a.getElement(), b.getElement()); } - } } diff --git a/src/main/java/brachy/modularui/screen/viewport/ModularGuiContext.java b/src/main/java/brachy/modularui/screen/viewport/ModularGuiContext.java index 8e0e5021..8841cd9a 100644 --- a/src/main/java/brachy/modularui/screen/viewport/ModularGuiContext.java +++ b/src/main/java/brachy/modularui/screen/viewport/ModularGuiContext.java @@ -9,11 +9,11 @@ import brachy.modularui.api.widget.IVanillaSlot; import brachy.modularui.api.widget.IWidget; import brachy.modularui.api.widget.ResizeDragArea; -import brachy.modularui.utils.CursorHandler; import brachy.modularui.screen.DraggablePanelWrapper; import brachy.modularui.screen.ModularPanel; import brachy.modularui.screen.ModularScreen; import brachy.modularui.screen.UISettings; +import brachy.modularui.utils.CursorHandler; import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; diff --git a/src/main/java/brachy/modularui/screen/viewport/TransformationMatrix.java b/src/main/java/brachy/modularui/screen/viewport/TransformationMatrix.java index f3d2a4a0..10b004f2 100755 --- a/src/main/java/brachy/modularui/screen/viewport/TransformationMatrix.java +++ b/src/main/java/brachy/modularui/screen/viewport/TransformationMatrix.java @@ -65,7 +65,8 @@ TransformationMatrix construct(IViewport viewport, Area area, @Nullable Matrix4f return construct(viewport, area, parent, true); } - private TransformationMatrix construct(IViewport viewport, Area area, @Nullable Matrix4f parent, boolean isViewport) { + private TransformationMatrix construct(IViewport viewport, Area area, @Nullable Matrix4f parent, + boolean isViewport) { checkInUse(); this.wrapped = null; this.viewport = viewport; diff --git a/src/main/java/brachy/modularui/test/TestBlock.java b/src/main/java/brachy/modularui/test/TestBlock.java index c725f5df..6c9708a7 100644 --- a/src/main/java/brachy/modularui/test/TestBlock.java +++ b/src/main/java/brachy/modularui/test/TestBlock.java @@ -34,7 +34,9 @@ public TestBlock(BiFunction blockEntityCreato } @Override - public @NotNull InteractionResult use(@NotNull BlockState state, Level level, @NotNull BlockPos pos, @NotNull Player player, @NotNull InteractionHand hand, @NotNull BlockHitResult hit) { + public @NotNull InteractionResult use(@NotNull BlockState state, Level level, @NotNull BlockPos pos, + @NotNull Player player, @NotNull InteractionHand hand, + @NotNull BlockHitResult hit) { if (!level.isClientSide) { UIFactories.blockEntity().open(player, pos); } @@ -42,7 +44,9 @@ public TestBlock(BiFunction blockEntityCreato } @Override - public @Nullable BlockEntityTicker getTicker(@NotNull Level level, @NotNull BlockState state, @NotNull BlockEntityType blockEntityType) { + public @Nullable < + T extends BlockEntity> BlockEntityTicker getTicker(@NotNull Level level, @NotNull BlockState state, + @NotNull BlockEntityType blockEntityType) { return (level1, pos, state1, blockEntity) -> ((AbstractBlockEntity) blockEntity).update(); } } diff --git a/src/main/java/brachy/modularui/test/TestBlockEntity.java b/src/main/java/brachy/modularui/test/TestBlockEntity.java index 346bed21..2738168b 100644 --- a/src/main/java/brachy/modularui/test/TestBlockEntity.java +++ b/src/main/java/brachy/modularui/test/TestBlockEntity.java @@ -70,19 +70,23 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * Various test and demos for synced widgets, slots and JEI interactions. Anything that doesn't fall into any of those categories goes into + * Various test and demos for synced widgets, slots and JEI interactions. Anything that doesn't fall into any of those + * categories goes into * {@link TestGuis}. */ public class TestBlockEntity extends AbstractBlockEntity implements IUIHolder { - private static final Object2IntMap handlerSizeMap = new Object2IntOpenHashMap<>() {{ - put(Items.DIAMOND, 9); - put(Items.EMERALD, 9); - put(Items.GOLD_INGOT, 7); - put(Items.IRON_INGOT, 6); - put(Items.CLAY_BALL, 2); - defaultReturnValue(3); - }}; + private static final Object2IntMap handlerSizeMap = new Object2IntOpenHashMap<>() { + + { + put(Items.DIAMOND, 9); + put(Items.EMERALD, 9); + put(Items.GOLD_INGOT, 7); + put(Items.IRON_INGOT, 6); + put(Items.CLAY_BALL, 2); + defaultReturnValue(3); + } + }; private long time = 0; private final int duration = 80; @@ -93,6 +97,7 @@ public class TestBlockEntity extends AbstractBlockEntity implements IUIHolder mainPanel) { @Override public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, UISettings settings) { - //settings.customContainer(() -> new CraftingModularContainer(3, 3, this.craftingInventory)); - //settings.customGui(() -> TestGuiContainer::new); + // settings.customContainer(() -> new CraftingModularContainer(3, 3, this.craftingInventory)); + // settings.customGui(() -> TestGuiContainer::new); syncManager.registerSlotGroup("item_inv", 3); - syncManager.registerSlotGroup(new SlotGroup("crafting", 3, SlotGroup.STORAGE_SLOT_PRIO * 2).setAllowSorting(false)); + syncManager.registerSlotGroup( + new SlotGroup("crafting", 3, SlotGroup.STORAGE_SLOT_PRIO * 2).setAllowSorting(false)); IntSyncValue cycleStateValue = new IntSyncValue(() -> this.cycleState, val -> this.cycleState = val).allowC2S(); syncManager.getHyperVisor().syncValue("cycle_state", cycleStateValue); syncManager.syncValue("progress", new DoubleSyncValue(() -> (double) this.progress / this.duration)); @@ -141,18 +146,21 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, ItemStack itemStack = packet.readItem(); if (itemStack.isEmpty()) return new EmptyWidget(); Item item = itemStack.getItem(); - ItemStackHandler handler = stackHandlerMap.computeIfAbsent(item, k -> new ItemStackHandler(handlerSizeMap.getInt(k))); + ItemStackHandler handler = stackHandlerMap.computeIfAbsent(item, + k -> new ItemStackHandler(handlerSizeMap.getInt(k))); String name = ForgeRegistries.ITEMS.getKey(item).toString(); Flow flow = Flow.row(); for (int i = 0; i < handler.getSlots(); i++) { int finalI = i; flow.child(new ItemSlot() - .syncHandler(syncManager1.getOrCreateSyncHandler(name, i, ItemSlotSyncHandler.class, () -> new ItemSlotSyncHandler(new ModularSlot(handler, finalI))))); + .syncHandler(syncManager1.getOrCreateSyncHandler(name, i, ItemSlotSyncHandler.class, + () -> new ItemSlotSyncHandler(new ModularSlot(handler, finalI))))); } return flow; }); - DynamicLinkedSyncHandler> dynamicLinkedSyncHandler = new DynamicLinkedSyncHandler<>(numberListSyncHandler) + DynamicLinkedSyncHandler> dynamicLinkedSyncHandler = new DynamicLinkedSyncHandler<>( + numberListSyncHandler) .widgetProvider((syncManager1, value1) -> { List vals = value1.getValue(); return Flow.row() @@ -205,7 +213,8 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, .key('O', new ItemSlot().slot(new ModularCraftingSlot(this.craftingInventory, 9) .inputInventory(this.craftingInventory) .gridSize(3, 3))) - .key('D', new ItemDisplayWidget().syncHandler("display_item").displayAmount(true)) + .key('D', + new ItemDisplayWidget().syncHandler("display_item").displayAmount(true)) .slotGroup("crafting") .build() .margin(5, 5, 20, 5) @@ -229,10 +238,13 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, .name("buttons_and_values_col") .widthRel(0.5f) .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) - .child(Text.str("Storage slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Storage slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("III", "III") - .key('I', i -> new ItemSlot().slot(new ModularSlot(this.storage, i))) + .key('I', + i -> new ItemSlot() + .slot(new ModularSlot(this.storage, i))) .slotGroup("item_inv") .build() .placeSortButtonsTopRightVertical()) @@ -242,14 +254,20 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, .tooltip(tooltip -> { tooltip.showUpTimer(10); tooltip.addLine(Text.str("Test Line g")); - tooltip.addLine(Text.str("An image inside of a tooltip:")); - tooltip.addDrawableLine(GuiTextures.MUI_LOGO.asIcon().size(50).alignment(Alignment.TopCenter)); + tooltip.addLine( + Text.str("An image inside of a tooltip:")); + tooltip.addDrawableLine( + GuiTextures.MUI_LOGO.asIcon().size(50) + .alignment(Alignment.TopCenter)); tooltip.addLine(Text.str("And here a circle:")); tooltip.addDrawableLine(new Circle() - .color(Color.RED.darker(2), Color.RED.brighter(2)) - .asIcon() - .size(20)) - .addDrawableLine(new ItemDrawable(new ItemStack(Items.DIAMOND)).asIcon()) + .color(Color.RED.darker(2), + Color.RED.brighter(2)) + .asIcon() + .size(20)) + .addDrawableLine(new ItemDrawable( + new ItemStack(Items.DIAMOND)) + .asIcon()) .pos(RichTooltip.Pos.LEFT); }) .onMousePressed((context, mouseButton) -> { @@ -263,77 +281,99 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, .reverseLayout(false) .child(new ToggleButton() .valueWrapped(cycleStateValue, 0) - .overlay(GuiTextures.CYCLE_BUTTON_DEMO.getSubArea(0, 0, 1, 1 / 3f))) + .overlay(GuiTextures.CYCLE_BUTTON_DEMO + .getSubArea(0, 0, 1, 1 / 3f))) .child(new ToggleButton() .valueWrapped(cycleStateValue, 1) - .overlay(GuiTextures.CYCLE_BUTTON_DEMO.getSubArea(0, 1 / 3f, 1, 2 / 3f))) + .overlay(GuiTextures.CYCLE_BUTTON_DEMO + .getSubArea(0, 1 / 3f, 1, 2 / 3f))) .child(new ToggleButton() .valueWrapped(cycleStateValue, 2) - .overlay(GuiTextures.CYCLE_BUTTON_DEMO.getSubArea(0, 2 / 3f, 1, 1)))) + .overlay(GuiTextures.CYCLE_BUTTON_DEMO + .getSubArea(0, 2 / 3f, 1, 1)))) .child(Flow.row() .name("progress_row") .coverChildrenHeight() .mainAxisAlignment(Alignment.MainAxis.SPACE_AROUND) .child(new ProgressWidget() .syncHandler("progress") - .texture(GuiTextures.PROGRESS_ARROW, ProgressDrawable.Direction.RIGHT) + .texture(GuiTextures.PROGRESS_ARROW, + ProgressDrawable.Direction.RIGHT) .size(20)) .child(CompositeProgress.circularLike4Slice( - GuiTextures.PROGRESS_CYCLE.getSubArea(0, 0f, 1, 0.5f), - GuiTextures.PROGRESS_CYCLE.getSubArea(0, 0.5f, 1, 1f), - CircularProgressDrawable.Direction.CW) + GuiTextures.PROGRESS_CYCLE.getSubArea(0, 0f, 1, + 0.5f), + GuiTextures.PROGRESS_CYCLE.getSubArea(0, 0.5f, + 1, 1f), + CircularProgressDrawable.Direction.CW) .asWidget() .syncHandler("progress") - .size(20))) - ) + .size(20)))) .child(Flow.col() .name("slots_col") .widthRel(0.5f) .heightRelOffset(1f, -6) // space for player sort buttons .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) - .child(Text.str("Oversized slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Oversized slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("III") - .key('I', i -> new ItemSlot().slot(new ModularSlot(this.oversizedStorage, i).ignoreMaxStackSize(true))) + .key('I', i -> new ItemSlot() + .slot(new ModularSlot(this.oversizedStorage, i) + .ignoreMaxStackSize(true))) .build()) - .child(Text.str("Phantom slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Phantom slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("III") - .key('I', i -> new PhantomItemSlot().slot(new ModularSlot(this.phantomStorage, i).ignoreMaxStackSize(true))) + .key('I', + i -> new PhantomItemSlot().slot( + new ModularSlot(this.phantomStorage, i) + .ignoreMaxStackSize(true))) .build()) - .child(Text.str("Fluid slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Fluid slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("FFF") - .key('F', i -> new FluidSlot().syncHandler(new FluidSlotSyncHandler(this.fluidStorage, i))) + .key('F', i -> new FluidSlot().syncHandler( + new FluidSlotSyncHandler(this.fluidStorage, i))) .build()) - .child(Text.str("Phantom Fluid slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Phantom Fluid slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("FFF") - .key('F', i -> new FluidSlot().syncHandler(new FluidSlotSyncHandler(this.phantomFluidStorage, i).phantom(true))) - .build()) - ))) + .key('F', + i -> new FluidSlot() + .syncHandler(new FluidSlotSyncHandler( + this.phantomFluidStorage, i) + .phantom(true))) + .build())))) .addPage(new ParentWidget<>() .name("dynamic_sync_page") .sizeRel(1f) .child(Flow.col() .name("dynamic widgets") - .child(Text.str("Dynamic synced widget demo. Items act as keys to a unique storage with different amount of slots.").asWidget().scale(0.7f)) + .child(Text.str( + "Dynamic synced widget demo. Items act as keys to a unique storage with different amount of slots.") + .asWidget().scale(0.7f)) .child(new ItemSlot() .slot(new ModularSlot(this.storageInventory0, 0) .changeListener(((oldItem, newItem, client, init) -> { - if (client && !ItemStack.isSameItemSameTags(oldItem, newItem)) { - dynamicSyncHandler.notifyUpdate(packet -> packet.writeItemStack(newItem, false)); + if (client && !ItemStack.isSameItemSameTags(oldItem, + newItem)) { + dynamicSyncHandler.notifyUpdate(packet -> packet + .writeItemStack(newItem, false)); } })))) .child(new DynamicWidget<>() .widthRel(1f) .syncHandler(dynamicSyncHandler)) - .child(Text.str("Dynamic linked sync handler demo.").asWidget().scale(0.7f).marginTop(6)) + .child(Text.str("Dynamic linked sync handler demo.").asWidget() + .scale(0.7f).marginTop(6)) .child(new DynamicWidget<>() .widthRel(1f) .coverChildrenHeight() - .syncHandler(dynamicLinkedSyncHandler)) - ))) + .syncHandler(dynamicLinkedSyncHandler))))) .child(SlotGroupWidget.playerInventory(false))); return panel; } @@ -350,8 +390,8 @@ public ModularPanel openSecondWindow(PanelSyncManager syncManager, IPanelHand syncManager.registerSlotGroup(slotGroup); AtomicInteger number = new AtomicInteger(0); syncManager.syncValue("int_value", new IntSyncValue(number::get, number::set)); - IPanelHandler panelSyncHandler = syncManager.syncedPanel("other_panel_2", true, (syncManager1, syncHandler1) -> - openThirdWindow(syncManager1, syncHandler1, number)); + IPanelHandler panelSyncHandler = syncManager.syncedPanel("other_panel_2", true, + (syncManager1, syncHandler1) -> openThirdWindow(syncManager1, syncHandler1, number)); IntSyncValue num = syncManager.getHyperVisor().findSyncHandler("cycle_state", IntSyncValue.class); panel.child(ButtonWidget.panelCloseButton()) .child(new ButtonWidget<>() @@ -381,7 +421,8 @@ public ModularPanel openSecondWindow(PanelSyncManager syncManager, IPanelHand return panel; } - public ModularPanel openThirdWindow(PanelSyncManager syncManager, IPanelHandler syncHandler, AtomicInteger integer) { + public ModularPanel openThirdWindow(PanelSyncManager syncManager, IPanelHandler syncHandler, + AtomicInteger integer) { ModularPanel panel = new ModularPanel<>("third_window") .disablePanelsBelow(false) .closeOnOutOfBoundsClick(false) @@ -414,7 +455,6 @@ public void update() { } } - @Override public CompoundTag serializeNBT() { CompoundTag t = super.serializeNBT(); diff --git a/src/main/java/brachy/modularui/test/TestGuis.java b/src/main/java/brachy/modularui/test/TestGuis.java index a1a8e0cd..766f097f 100644 --- a/src/main/java/brachy/modularui/test/TestGuis.java +++ b/src/main/java/brachy/modularui/test/TestGuis.java @@ -1,6 +1,5 @@ package brachy.modularui.test; -import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.ModularUI; import brachy.modularui.animation.Animator; import brachy.modularui.animation.IAnimator; @@ -11,7 +10,6 @@ import brachy.modularui.api.drawable.Text; import brachy.modularui.api.layout.IViewportStack; import brachy.modularui.api.widget.IWidget; -import brachy.modularui.drawable.schema.BlockHighlight; import brachy.modularui.drawable.FluidDrawable; import brachy.modularui.drawable.GuiDraw; import brachy.modularui.drawable.GuiTextures; @@ -21,9 +19,10 @@ import brachy.modularui.drawable.graph.GraphDrawable; import brachy.modularui.drawable.progress.CircularProgressDrawable; import brachy.modularui.drawable.progress.ProgressDrawable; -import brachy.modularui.factory.ClientGUI; import brachy.modularui.drawable.schema.ArraySchema; +import brachy.modularui.drawable.schema.BlockHighlight; import brachy.modularui.drawable.schema.ISchema; +import brachy.modularui.factory.ClientGUI; import brachy.modularui.screen.CustomModularScreen; import brachy.modularui.screen.ModularPanel; import brachy.modularui.screen.ModularScreen; @@ -33,6 +32,7 @@ import brachy.modularui.utils.ColorShade; import brachy.modularui.utils.Interpolation; import brachy.modularui.utils.Interpolations; +import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.utils.math.DAM; import brachy.modularui.value.BoolValue; import brachy.modularui.value.DoubleValue; @@ -64,11 +64,11 @@ import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.material.Fluids; -import com.mojang.blaze3d.vertex.VertexConsumer; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.registries.ForgeRegistries; import com.google.common.base.CaseFormat; +import com.mojang.blaze3d.vertex.VertexConsumer; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import org.apache.commons.lang3.tuple.Pair; @@ -109,8 +109,10 @@ public TestGuis() { } /** - * This method finds all 'build___UI' methods in this class via reflection and adds a button that opens that UI to a list widget. - * This makes it very convenient to add and test test-screens without having to swap out the screen that the diamond item opens. + * This method finds all 'build___UI' methods in this class via reflection and adds a button that opens that UI to a + * list widget. + * This makes it very convenient to add and test test-screens without having to swap out the screen that the diamond + * item opens. */ @Override public @NotNull ModularPanel buildUI(ModularGuiContext context) { @@ -136,14 +138,16 @@ public TestGuis() { String name = m.getName(); if (name.startsWith("build")) name = name.substring(5); if (name.endsWith("UI")) name = name.substring(0, name.length() - 2); - String codeTextureName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name); + String codeTextureName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, + name); name = name.replaceAll("([a-z])([A-Z])", "$1 $2"); return button(name) .onMousePressed((context1, button) -> { try { ModularPanel panel = (ModularPanel) m.invoke(null); if (TestGuis.withCode) { - // WIP: this is meant to put an image of the code next to ui for showcase purpose + // WIP: this is meant to put an image of the code next to ui for + // showcase purpose panel.child(UITexture.builder() .location(ModularUI.id("gui/code/" + codeTextureName)) .build() @@ -151,23 +155,26 @@ public TestGuis() { .leftRel(1f) .heightRel(1f)); } - ClientGUI.open(new ModularScreen(ModularUI.MOD_ID, panel).openParentOnClose(true)); + ClientGUI.open(new ModularScreen(ModularUI.MOD_ID, panel) + .openParentOnClose(true)); } catch (IllegalAccessException | InvocationTargetException e) { ModularUI.LOGGER.throwing(e); } return true; }); }) - /*.child(button("OpenGL test") - .onMousePressed(button -> { - ClientGUI.open(new GLTestGui().openParentOnClose(true)); - return true; - })) - .child(button("Sortable List") - .onMousePressed(button -> { - ClientGUI.open(new TestGui().openParentOnClose(true)); - return true; - }))*/ + /* + * .child(button("OpenGL test") + * .onMousePressed(button -> { + * ClientGUI.open(new GLTestGui().openParentOnClose(true)); + * return true; + * })) + * .child(button("Sortable List") + * .onMousePressed(button -> { + * ClientGUI.open(new TestGui().openParentOnClose(true)); + * return true; + * })) + */ .child(button("Test self") .onMousePressed((context1, button) -> { ClientGUI.open(this); @@ -204,7 +211,6 @@ private static ButtonWidget button(String text) { .margin(1) .name("G:" + i + ",W:" + j); }))); - } public static @NotNull ModularPanel buildPendulumAnimationUI() { @@ -266,53 +272,63 @@ private static ButtonWidget button(String text) { stack.translate(x0, y0); stack.scale(scale, scale); stack.translate(-x0, -y0); - widget.color(Color.lerp(0xFF040404, Color.RED.main, Math.min(1f, 1.2f * logGrowVal))); + widget.color( + Color.lerp(0xFF040404, Color.RED.main, Math.min(1f, 1.2f * logGrowVal))); }))); } - /*public static @NotNull ModularPanel buildSpriteAndEntityUI() { - TextureAtlasSprite sprite = SpriteHelper.getSpriteOfBlockState(GameObjectHelper.getBlockState("minecraft", "command_block"), EnumFacing.UP); - // SpriteHelper.getSpriteOfItem(new ItemStack(Items.DIAMOND)); - Entity entity = FakeEntity.create(EntityDragon.class); - float period = 3000f; - return ModularPanel.defaultPanel("main") - .size(150) - .overlay(new Rectangle() - .color(Color.GREEN.main) - .hollow(2) - .asIcon().margin(5)) - .child(new TextWidget<>(IKey.str("Test String")).scale(0.6f).horizontalCenter().top(7)) - .child(new DraggableWidget<>() - .background(new SpriteDrawable(sprite)) - .size(20) - .alignX(0.5f) - .top(20) - .tooltipBuilder(tooltip -> { - tooltip.addLine( - "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " - + "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. " - + "Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. " - + "Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem"); - tooltip.addLine("Longer Line 2"); - tooltip.addLine("Line 3"); - tooltip.alignment(Alignment.Center); - tooltip.scale(0.5f); - tooltip.pos(RichTooltip.Pos.NEXT_TO_MOUSE); - })) - .child(new IDrawable() { - @Override - public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { - GuiDraw.drawEntity(context.getGraphics(), entity, 0, 0, width, height, context.getCurrentDrawingZ(), (graphics, e) -> { - // TODO the drawable doesnt seem to update the rotation - float scale = 0.9f; - graphics.pose().scale(scale, scale, scale); - graphics.pose().translate(0, 7, 0); - //graphics.pose().rotate(35, 1, 0, 0); - //graphics.pose().rotate(360 * (Util.getMillis() % period) / period, 0, 1, 0); - }, null); - } - }.asWidget().alignX(0.5f).bottom(10).size(100, 75)); - }*/ + /* + * public static @NotNull ModularPanel buildSpriteAndEntityUI() { + * TextureAtlasSprite sprite = SpriteHelper.getSpriteOfBlockState(GameObjectHelper.getBlockState("minecraft", + * "command_block"), EnumFacing.UP); + * // SpriteHelper.getSpriteOfItem(new ItemStack(Items.DIAMOND)); + * Entity entity = FakeEntity.create(EntityDragon.class); + * float period = 3000f; + * return ModularPanel.defaultPanel("main") + * .size(150) + * .overlay(new Rectangle() + * .color(Color.GREEN.main) + * .hollow(2) + * .asIcon().margin(5)) + * .child(new TextWidget<>(IKey.str("Test String")).scale(0.6f).horizontalCenter().top(7)) + * .child(new DraggableWidget<>() + * .background(new SpriteDrawable(sprite)) + * .size(20) + * .alignX(0.5f) + * .top(20) + * .tooltipBuilder(tooltip -> { + * tooltip.addLine( + * "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " + * + + * "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. " + * + + * "Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. " + * + + * "Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem" + * ); + * tooltip.addLine("Longer Line 2"); + * tooltip.addLine("Line 3"); + * tooltip.alignment(Alignment.Center); + * tooltip.scale(0.5f); + * tooltip.pos(RichTooltip.Pos.NEXT_TO_MOUSE); + * })) + * .child(new IDrawable() { + * + * @Override + * public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + * GuiDraw.drawEntity(context.getGraphics(), entity, 0, 0, width, height, context.getCurrentDrawingZ(), (graphics, + * e) -> { + * // TODO the drawable doesnt seem to update the rotation + * float scale = 0.9f; + * graphics.pose().scale(scale, scale, scale); + * graphics.pose().translate(0, 7, 0); + * //graphics.pose().rotate(35, 1, 0, 0); + * //graphics.pose().rotate(360 * (Util.getMillis() % period) / period, 0, 1, 0); + * }, null); + * } + * }.asWidget().alignX(0.5f).bottom(10).size(100, 75)); + * } + */ public static @NotNull ModularPanel buildRichTextUI() { IntValue integer = new IntValue(0); @@ -326,7 +342,8 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget .asIcon() .asHoverable() .tooltip(richTooltip -> richTooltip.addFromItem(new ItemStack(Blocks.GRASS)) - .add(Text.GRAY + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."))) + .add(Text.GRAY + + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."))) .add(", nice to ") .addDrawable(new ItemDrawable(new ItemStack(Items.PORKCHOP)) .asIcon() @@ -346,19 +363,18 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget .newLine() .newLine() .add(Text.comp(Text.comp( - Text.str("Underline all: "), - Text.comp( - Text.str("Green Text, "), - Text.str("this is red").style(Text.RED), - Text.str(" and this should be green again")) - .style(Text.GREEN), - Text.str(". Still underlined, ")) + Text.str("Underline all: "), + Text.comp( + Text.str("Green Text, "), + Text.str("this is red").style(Text.RED), + Text.str(" and this should be green again")) + .style(Text.GREEN), + Text.str(". Still underlined, ")) .style(Text.UNDERLINE), Text.str("but not anymore."))) .newLine() .addDrawable(Text.str("Green, %s, %s and green again", Text.str("red").style(Text.RED), - Text.str("underline").style(null, Text.UNDERLINE) - ).style(Text.GREEN)) + Text.str("underline").style(null, Text.UNDERLINE)).style(Text.GREEN)) .newLine() .add(Text.RESET + "" + Text.UNDERLINE + "Underlined" + Text.RESET) .newLine() @@ -368,37 +384,43 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget int i = integer.getIntValue() + 1; integer.setIntValue(i); return Text.str("key [%s]", Text.str("arg") - .style(Text.UNDERLINE, Text.BLACK)) + .style(Text.UNDERLINE, Text.BLACK)) .style(i % 30 > 5 ? Text.RED : Text.DARK_BLUE); }).fallbackStyle(Text.BOLD), Text.str(" Test"))) - .textShadow(false) - )); + .textShadow(false))); } public static @NotNull ModularPanel buildWorldSchemaUI() { - /*TrackedDummyWorld world = new TrackedDummyWorld(); - world.addBlock(new BlockPos(0, 0, 0), new BlockInfo(Blocks.DIAMOND_BLOCK.getDefaultState())); - world.addBlock(new BlockPos(0, 1, 0), new BlockInfo(Blocks.BEDROCK.getDefaultState())); - world.addBlock(new BlockPos(1, 0, 1), new BlockInfo(Blocks.GOLD_BLOCK.getDefaultState()));*/ -/* return ModularPanel.defaultPanel("main") - .size(150) - .overlay(new SchemaRenderer(BoxSchema.of(Minecraft.getMinecraft().world, new BlockPos(Platform.getClientPlayer()), 5)) - .cameraFunc((camera, schema) -> { - double pitch = Math.PI / 4; - double T = 4000D; - double yaw = Minecraft.getSystemTime() % T / T * Math.PI * 2; - camera.setLookAt(new BlockPos(Platform.getClientPlayer()), 20, yaw, pitch); - }) - .isometric(true) - .asIcon().size(140));*/ - - /*MapSchema world = new MapSchema.Builder() - .add(new BlockPos(0, 0, 0), Blocks.DIAMOND_BLOCK.getDefaultState()) - .add(new BlockPos(0, 1, 0), Blocks.BEDROCK.getDefaultState()) - .add(new BlockPos(0, 2, 0), Blocks.WOOL.getDefaultState()) - .add(new BlockPos(1, 0, 1), Blocks.GOLD_BLOCK.getDefaultState()) - .add(new BlockPos(0, 3, 0), Blocks.BEACON.getDefaultState()) - .build();*/ + /* + * TrackedDummyWorld world = new TrackedDummyWorld(); + * world.addBlock(new BlockPos(0, 0, 0), new BlockInfo(Blocks.DIAMOND_BLOCK.getDefaultState())); + * world.addBlock(new BlockPos(0, 1, 0), new BlockInfo(Blocks.BEDROCK.getDefaultState())); + * world.addBlock(new BlockPos(1, 0, 1), new BlockInfo(Blocks.GOLD_BLOCK.getDefaultState())); + */ + /* + * return ModularPanel.defaultPanel("main") + * .size(150) + * .overlay(new SchemaRenderer(BoxSchema.of(Minecraft.getMinecraft().world, new + * BlockPos(Platform.getClientPlayer()), 5)) + * .cameraFunc((camera, schema) -> { + * double pitch = Math.PI / 4; + * double T = 4000D; + * double yaw = Minecraft.getSystemTime() % T / T * Math.PI * 2; + * camera.setLookAt(new BlockPos(Platform.getClientPlayer()), 20, yaw, pitch); + * }) + * .isometric(true) + * .asIcon().size(140)); + */ + + /* + * MapSchema world = new MapSchema.Builder() + * .add(new BlockPos(0, 0, 0), Blocks.DIAMOND_BLOCK.getDefaultState()) + * .add(new BlockPos(0, 1, 0), Blocks.BEDROCK.getDefaultState()) + * .add(new BlockPos(0, 2, 0), Blocks.WOOL.getDefaultState()) + * .add(new BlockPos(1, 0, 1), Blocks.GOLD_BLOCK.getDefaultState()) + * .add(new BlockPos(0, 3, 0), Blocks.BEACON.getDefaultState()) + * .build(); + */ ISchema schema = ArraySchema.builder() .layer("D D", " ", " ", " ") @@ -419,7 +441,7 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget var panel = ModularPanel.defaultPanel("main").size(170); panel.child(new SchemaWidget(renderer) - .full()) + .full()) .child(new SchemaWidget.LayerButton(renderer, 0, 3) .bottom(1) .left(1) @@ -469,7 +491,8 @@ public static ModularPanel buildCollapseDisabledChildrenUI() { .marginBottom(-1) .widgetThemeKey(IThemeApi.BUTTON) .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) - .setEnabledIf(w -> text.toLowerCase().contains(searchValue.getStringValue())) + .setEnabledIf( + w -> text.toLowerCase().contains(searchValue.getStringValue())) .child(new ItemDrawable(stack).asWidget()) .child(new ScrollingTextWidget(Text.str(text)) .widgetThemeKey(IThemeApi.BUTTON) @@ -501,7 +524,8 @@ public static ModularPanel buildCollapseDisabledChildrenUI() { Rectangle color1 = new Rectangle().color(Color.BLACK.main); Rectangle color2 = new Rectangle().color(Color.WHITE.main); - IDrawable gradient = (context1, x, y, width, height, widgetTheme) -> GuiDraw.drawHorizontalGradientRect(context1.getGraphics(), x, y, width, height, color1.getColor(), color2.getColor()); + IDrawable gradient = (context1, x, y, width, height, widgetTheme) -> GuiDraw.drawHorizontalGradientRect( + context1.getGraphics(), x, y, width, height, color1.getColor(), color2.getColor()); IDrawable correctedGradient = (context1, x, y, width, height, widgetTheme) -> { int points = 500; Matrix4f pose = context1.graphicsPose().last().pose(); @@ -520,18 +544,22 @@ public static ModularPanel buildCollapseDisabledChildrenUI() { ModularPanel panel = new ModularPanel<>("colors").width(300).coverChildrenHeight().padding(7); - IPanelHandler colorPicker1 = IPanelHandler.simple(panel, (mainPanel, player) -> new ColorPickerDialog("color_picker1", color1.getColor(), true) - .resultConsumer(color1::color) - .draggable(true) - .relative(panel) - .top(0) - .rightRel(1f), true); - IPanelHandler colorPicker2 = IPanelHandler.simple(panel, (mainPanel, player) -> new ColorPickerDialog("color_picker2", color2.getColor(), true) - .resultConsumer(color2::color) - .draggable(true) - .relative(panel) - .top(0) - .leftRel(1f), true); + IPanelHandler colorPicker1 = IPanelHandler.simple(panel, + (mainPanel, player) -> new ColorPickerDialog("color_picker1", color1.getColor(), true) + .resultConsumer(color1::color) + .draggable(true) + .relative(panel) + .top(0) + .rightRel(1f), + true); + IPanelHandler colorPicker2 = IPanelHandler.simple(panel, + (mainPanel, player) -> new ColorPickerDialog("color_picker2", color2.getColor(), true) + .resultConsumer(color2::color) + .draggable(true) + .relative(panel) + .top(0) + .leftRel(1f), + true); return panel .child(Flow.column() @@ -576,7 +604,8 @@ public static ModularPanel buildCollapseDisabledChildrenUI() { public static ModularPanel buildContextMenu() { List options1 = IntStream.range(0, 5).mapToObj(i -> "Option " + (i + 1)).collect(Collectors.toList()); - List options2 = IntStream.range(0, 5).mapToObj(i -> "Sub Option " + (i + 1)).collect(Collectors.toList()); + List options2 = IntStream.range(0, 5).mapToObj(i -> "Sub Option " + (i + 1)) + .collect(Collectors.toList()); ObjectValue itemValue = new ObjectValue<>(ItemStack.class, new ItemStack(Items.ACACIA_DOOR)); return new ModularPanel<>("context_menu_test") .size(150) @@ -595,7 +624,7 @@ public static ModularPanel buildContextMenu() { .overlay(Text.str("Sub Menu")) .openRightDown() .menuList(l1 -> l1 - //.width(90) + // .width(90) .maxSize(80) .children(options2, s -> Text.str(s).asWidget()))))) .child(new DropdownWidget<>("test_dropdown", ItemStack.class) @@ -617,8 +646,7 @@ public static ModularPanel buildContextMenu() { .child(new ItemDrawable(item).asWidget()) .child(Text.str(item.getDisplayName().getString()).asWidget() .widgetThemeKey(IThemeApi.BUTTON) - .invisible())) - ); + .invisible()))); } public static @NotNull ModularPanel buildGraphUI() { @@ -806,15 +834,14 @@ private static Rectangle rndRect(IntList colors, Random random) { .filledTexture(new FluidDrawable(new FluidStack(Fluids.WATER, 1))) .counterClockwise() .asWidget())) - .coverChildren() - ); + .coverChildren()); } private static class TestPanel extends ModularPanel { public TestPanel(String name) { super(name); - //background(GuiTextures.BACKGROUND); + // background(GuiTextures.BACKGROUND); size(100, 100); } diff --git a/src/main/java/brachy/modularui/test/TestHandler.java b/src/main/java/brachy/modularui/test/TestHandler.java index 8d4f5519..9088f96c 100644 --- a/src/main/java/brachy/modularui/test/TestHandler.java +++ b/src/main/java/brachy/modularui/test/TestHandler.java @@ -17,7 +17,6 @@ import brachy.modularui.screen.event.RichTooltipEvent; import brachy.modularui.screen.viewport.GuiContext; import brachy.modularui.screen.viewport.ModularGuiContext; -import brachy.modularui.theme.ReloadThemeEvent; import brachy.modularui.theme.SelectableTheme; import brachy.modularui.theme.ThemeBuilder; import brachy.modularui.theme.WidgetTheme; @@ -29,7 +28,6 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import com.mojang.datafixers.util.Either; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.RenderTooltipEvent; @@ -38,6 +36,7 @@ import net.minecraftforge.fml.common.Mod; import net.minecraftforge.registries.ForgeRegistries; +import com.mojang.datafixers.util.Either; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -58,11 +57,11 @@ public class TestHandler { .widgetThemeHover(IThemeApi.TOGGLE_BUTTON, new SelectableTheme.Builder<>() .selectedIconColor(Color.DEEP_PURPLE.brighter(0)) .selectedBackground("slot_fluid") - .background("slot_item") - ) + .background("slot_item")) .textColor(IThemeApi.TEXT_FIELD, Color.DEEP_PURPLE.main); private static final IIcon tooltipLine = new IDrawable() { + @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { int high = Color.PURPLE.main; @@ -134,9 +133,11 @@ public static void onPreInit() { @SubscribeEvent public static void onOpenScreen(OpenScreenEvent event) { if (ModularUIConfig.enableTestOverlays()) { - /*if (event.getScreen() instanceof gui) { - event.addOverlay(getMainMenuOverlayTest(gui)); - } else */ + /* + * if (event.getScreen() instanceof gui) { + * event.addOverlay(getMainMenuOverlayTest(gui)); + * } else + */ if (event.getScreen() instanceof AbstractContainerScreen gui) { event.addOverlay(getContainerOverlayTest(gui)); } @@ -147,33 +148,37 @@ public static void onOpenScreen(OpenScreenEvent event) { @SubscribeEvent public static void onBuildPanel(BuildPanelEvent.MainPanel event) { if (event.matches(ModularUI.MOD_ID, "test_tile")) { - Flow flow = WidgetTree.findChildAt(event.getOpeningPanel(), Flow.class, "main_col", "paged", "dynamic_sync_page", "dynamic widgets"); + Flow flow = WidgetTree.findChildAt(event.getOpeningPanel(), Flow.class, "main_col", "paged", + "dynamic_sync_page", "dynamic widgets"); flow.addChild(Text.str("Added from Event").asWidget(), 0); } } - /*private ModularScreen getMainMenuOverlayTest(GuiMainMenu gui) { - TextWidget title = new TextWidget<>(IKey.str("ModularUI")); - int[] colors = {Color.WHITE.main, Color.AMBER.main, Color.BLUE.main, Color.GREEN.main, Color.DEEP_PURPLE.main, Color.RED.main}; - AtomicInteger k = new AtomicInteger(); - return new ModularScreen(ModularUI.ID, - ModularPanel.defaultPanel("overlay") - .fullScreenInvisible() - .child(title.scale(5f) - .shadow(true) - .color(colors[k.get()]) - .leftRel(0.5f).topRel(0.07f)) - .child(new ButtonWidget<>() // test button overlapping - .topRel(0.25f, 59, 0f) - .leftRelOffset(0.5f, 91) - .size(44) - .overlay(IKey.str("Fun Button")) - .onMousePressed(mouseButton -> { - k.set((k.get() + 1) % colors.length); - title.color(colors[k.get()]); - return true; - }))); - }*/ + /* + * private ModularScreen getMainMenuOverlayTest(GuiMainMenu gui) { + * TextWidget title = new TextWidget<>(IKey.str("ModularUI")); + * int[] colors = {Color.WHITE.main, Color.AMBER.main, Color.BLUE.main, Color.GREEN.main, Color.DEEP_PURPLE.main, + * Color.RED.main}; + * AtomicInteger k = new AtomicInteger(); + * return new ModularScreen(ModularUI.ID, + * ModularPanel.defaultPanel("overlay") + * .fullScreenInvisible() + * .child(title.scale(5f) + * .shadow(true) + * .color(colors[k.get()]) + * .leftRel(0.5f).topRel(0.07f)) + * .child(new ButtonWidget<>() // test button overlapping + * .topRel(0.25f, 59, 0f) + * .leftRelOffset(0.5f, 91) + * .size(44) + * .overlay(IKey.str("Fun Button")) + * .onMousePressed(mouseButton -> { + * k.set((k.get() + 1) % colors.length); + * title.color(colors[k.get()]); + * return true; + * }))); + * } + */ @OnlyIn(Dist.CLIENT) private static ModularScreen getContainerOverlayTest(AbstractContainerScreen gui) { diff --git a/src/main/java/brachy/modularui/test/TestItem.java b/src/main/java/brachy/modularui/test/TestItem.java index 7ba247df..acac46dc 100644 --- a/src/main/java/brachy/modularui/test/TestItem.java +++ b/src/main/java/brachy/modularui/test/TestItem.java @@ -51,20 +51,20 @@ public ModularPanel buildUI(PlayerInventoryGuiData data, PanelSyncManager ModularPanel panel = ModularPanel.defaultPanel("knapping_gui").resizeableOnDrag(true); panel.child(Flow.col().margin(7) - .child(new ParentWidget<>().widthRel(1f).expanded() - .child(SlotGroupWidget.builder() - .row("I I") - .row(" I") - .row(" ") - .row(" I ") - .key('I', index -> new ItemSlot().slot(SyncHandlers.itemSlot(ihm, index) - .ignoreMaxStackSize(true) - .slotGroup("mixer_items") - // do not allow putting items which can hold other items into the item - // some mods don't do this on their backpacks, so it won't catch those cases - .filter(stack -> !stack.getCapability(ITEM_HANDLER).isPresent()))) - .build())) - .child(SlotGroupWidget.playerInventory(false))) + .child(new ParentWidget<>().widthRel(1f).expanded() + .child(SlotGroupWidget.builder() + .row("I I") + .row(" I") + .row(" ") + .row(" I ") + .key('I', index -> new ItemSlot().slot(SyncHandlers.itemSlot(ihm, index) + .ignoreMaxStackSize(true) + .slotGroup("mixer_items") + // do not allow putting items which can hold other items into the item + // some mods don't do this on their backpacks, so it won't catch those cases + .filter(stack -> !stack.getCapability(ITEM_HANDLER).isPresent()))) + .build())) + .child(SlotGroupWidget.playerInventory(false))) .child(GuiTextures.ANIMATED_TEXTURE_TEST.asWidget().size(32).leftRel(1f).topRel(0f).margin(7)); return panel; diff --git a/src/main/java/brachy/modularui/test/TestMachine.java b/src/main/java/brachy/modularui/test/TestMachine.java index dc4a52e7..ffb9e4a0 100644 --- a/src/main/java/brachy/modularui/test/TestMachine.java +++ b/src/main/java/brachy/modularui/test/TestMachine.java @@ -78,13 +78,16 @@ public static class BE extends AbstractBlockEntity implements IUIHolder items = LazyOptional.of(() -> new CombinedInvWrapper(inputItems, outputItems)); - private final LazyOptional fluids = LazyOptional.of(() -> new CombinedFluidHandlerWrapper(inputFluids, outputFluids)); + private final LazyOptional items = LazyOptional + .of(() -> new CombinedInvWrapper(inputItems, outputItems)); + private final LazyOptional fluids = LazyOptional + .of(() -> new CombinedFluidHandlerWrapper(inputFluids, outputFluids)); private int ticks = 0; private boolean running = false, paused = false; private int recipeProgress = 0; - @Nullable private Recipe lastRecipe = null; + @Nullable + private Recipe lastRecipe = null; public BE(BlockPos pos, BlockState blockState) { super(TestRegistration.MACHINE_BE_TYPE.get(), pos, blockState); @@ -118,7 +121,9 @@ public ModularPanel buildUI(PosGuiData data, PanelSyncManager syncManager, UI .coverChildren(176, 30) .padding(7) .widgetThemeKey(IThemeApi.PANEL) - .child(Recipes.buildMachineUI(panel, this.inputItems, this.outputItems, this.inputFluids, this.outputFluids, new DoubleSyncValue(this::getProgress), false)) + .child(Recipes.buildMachineUI(panel, this.inputItems, this.outputItems, + this.inputFluids, this.outputFluids, new DoubleSyncValue(this::getProgress), + false)) .child(new ParentWidget<>() .coverChildren() .decoration() @@ -137,11 +142,11 @@ public ModularPanel buildUI(PosGuiData data, PanelSyncManager syncManager, UI .bottom(7) .rightRelAnchor(0, 1f) .child(new ToggleButton() - .value(new BooleanSyncValue(() -> this.paused, v -> this.paused = v).allowC2S()) + .value(new BooleanSyncValue(() -> this.paused, v -> this.paused = v) + .allowC2S()) .overlay(true, GuiTextures.PLAY) .overlay(false, GuiTextures.PAUSE)) - .name("side_options")) - ) + .name("side_options"))) .child(new SingleChildWidget<>() .coverChildren() .padding(7) @@ -282,7 +287,8 @@ public static class Recipes { .itemIn(Items.GOLD_INGOT, 4) .itemOut(Items.NETHER_STAR)); - // add (many) more recipes with (consistent) random inputs and outputs to try to overflow the cache for testing + // add (many) more recipes with (consistent) random inputs and outputs to try to overflow the cache for + // testing final int VERY_MANY_RECIPES = 256; RandomSource rng = RandomSource.create(""" // chosen by fair dice roll. @@ -299,20 +305,23 @@ public static class Recipes { while (recipe.inItems.size() < inItems) { BuiltInRegistries.ITEM.getRandom(rng).ifPresent(item -> { ItemStack stack = item.value().getDefaultInstance(); - stack.setCount(Mth.clamp((int) (rng.nextGaussian() * stack.getMaxStackSize()), 0, stack.getMaxStackSize())); + stack.setCount(Mth.clamp((int) (rng.nextGaussian() * stack.getMaxStackSize()), 0, + stack.getMaxStackSize())); recipe.itemIn(stack); }); } while (recipe.outItems.size() < outItems) { BuiltInRegistries.ITEM.getRandom(rng).ifPresent(item -> { ItemStack stack = item.value().getDefaultInstance(); - stack.setCount(Mth.clamp((int) (rng.nextGaussian() * stack.getMaxStackSize()), 0, stack.getMaxStackSize())); + stack.setCount(Mth.clamp((int) (rng.nextGaussian() * stack.getMaxStackSize()), 0, + stack.getMaxStackSize())); recipe.itemOut(stack); }); } while (recipe.inFluids.size() < inFluids) { BuiltInRegistries.FLUID.getRandom(rng).ifPresent(fluid -> { - int amount = Mth.clamp((int) (rng.nextGaussian() * FLUID_SLOT_CAPACITY), 0, FLUID_SLOT_CAPACITY); + int amount = Mth.clamp((int) (rng.nextGaussian() * FLUID_SLOT_CAPACITY), 0, + FLUID_SLOT_CAPACITY); if (amount == 0) return; recipe.fluidIn(fluid.value(), amount); @@ -320,7 +329,8 @@ public static class Recipes { } while (recipe.outFluids.size() < outFluids) { BuiltInRegistries.FLUID.getRandom(rng).ifPresent(fluid -> { - int amount = Mth.clamp((int) (rng.nextGaussian() * FLUID_SLOT_CAPACITY), 0, FLUID_SLOT_CAPACITY); + int amount = Mth.clamp((int) (rng.nextGaussian() * FLUID_SLOT_CAPACITY), 0, + FLUID_SLOT_CAPACITY); if (amount == 0) return; recipe.fluidOut(fluid.value(), amount); @@ -331,7 +341,8 @@ public static class Recipes { } }); - public static Recipe findRecipe(IItemHandler inputItems, IFluidHandler inputFluids, @Nullable Recipe lastRecipe) { + public static Recipe findRecipe(IItemHandler inputItems, IFluidHandler inputFluids, + @Nullable Recipe lastRecipe) { if (lastRecipe != null && lastRecipe.startRecipe(inputItems, inputFluids, true)) return lastRecipe; for (Recipe recipe : list) { if (recipe.startRecipe(inputItems, inputFluids, true)) { @@ -372,8 +383,10 @@ private static boolean extract(FluidStack stack, IFluidHandler handler, boolean return false; } - public static IWidget buildMachineUI(ModularPanel panel, IItemHandlerModifiable inItems, IItemHandlerModifiable outItems, - IMultiTankFluidHandler inFluids, IMultiTankFluidHandler outFluids, IDoubleValue progress, + public static IWidget buildMachineUI(ModularPanel panel, IItemHandlerModifiable inItems, + IItemHandlerModifiable outItems, + IMultiTankFluidHandler inFluids, IMultiTankFluidHandler outFluids, + IDoubleValue progress, final boolean isRecipeViewerUI) { var val = new StringValue("Option 1"); IPanelHandler panelHandler = IPanelHandler.simple(panel, (parent, player) -> { @@ -389,7 +402,8 @@ public static IWidget buildMachineUI(ModularPanel panel, IItemHandlerModifiab .option("Option 1") .option("Option 2") .option("Option 3") - .optionToWidget((s, b) -> Text.str(s).asWidget().center().color(Color.WHITE.main).shadow(true).padding(2))) + .optionToWidget((s, b) -> Text.str(s).asWidget().center().color(Color.WHITE.main) + .shadow(true).padding(2))) .child(new ButtonWidget<>() .size(70, 14) .overlay(Text.str("Sub panel")) diff --git a/src/main/java/brachy/modularui/test/TestRecipeViewerGuis.java b/src/main/java/brachy/modularui/test/TestRecipeViewerGuis.java index 49f5dfdd..92fb283b 100644 --- a/src/main/java/brachy/modularui/test/TestRecipeViewerGuis.java +++ b/src/main/java/brachy/modularui/test/TestRecipeViewerGuis.java @@ -1,18 +1,5 @@ package brachy.modularui.test; -import brachy.modularui.utils.handlers.fluid.EmptyFluidTank; -import brachy.modularui.utils.handlers.fluid.IMultiTankFluidHandler; -import brachy.modularui.utils.handlers.fluid.MultiTankFluidHandler; - -import mezz.jei.api.forge.ForgeTypes; - -import net.minecraft.ChatFormatting; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.Tags; -import net.minecraftforge.fluids.FluidStack; - import brachy.modularui.ModularUI; import brachy.modularui.api.widget.IWidget; import brachy.modularui.integration.emi.recipe.ModularUIEmiRecipe; @@ -20,13 +7,26 @@ import brachy.modularui.integration.jei.recipe.ModularUIJeiCategory; import brachy.modularui.integration.recipeviewer.RecipeSlotRole; import brachy.modularui.integration.recipeviewer.handlers.IngredientProvider; -import brachy.modularui.integration.rei.recipe.ModularUIReiDisplay; import brachy.modularui.integration.rei.recipe.ModularUIReiCategory; +import brachy.modularui.integration.rei.recipe.ModularUIReiDisplay; import brachy.modularui.screen.ModularPanel; +import brachy.modularui.utils.handlers.fluid.EmptyFluidTank; +import brachy.modularui.utils.handlers.fluid.IMultiTankFluidHandler; +import brachy.modularui.utils.handlers.fluid.MultiTankFluidHandler; import brachy.modularui.value.DoubleValue; import brachy.modularui.widgets.slot.FluidSlot; import brachy.modularui.widgets.slot.ItemSlot; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.common.Tags; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidTank; +import net.minecraftforge.items.IItemHandlerModifiable; +import net.minecraftforge.items.wrapper.EmptyHandler; + import dev.emi.emi.api.EmiApi; import dev.emi.emi.api.EmiRegistry; import dev.emi.emi.api.recipe.EmiRecipeCategory; @@ -41,6 +41,7 @@ import me.shedaniel.rei.api.common.entry.EntryIngredient; import me.shedaniel.rei.api.common.util.EntryIngredients; import me.shedaniel.rei.api.common.util.EntryStacks; +import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; @@ -48,11 +49,6 @@ import mezz.jei.api.registration.IRecipeCatalystRegistration; import mezz.jei.api.registration.IRecipeCategoryRegistration; import mezz.jei.api.registration.IRecipeRegistration; - -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.wrapper.EmptyHandler; - import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; @@ -65,12 +61,14 @@ public class TestRecipeViewerGuis { private static final IItemHandlerModifiable EMPTY_INFINITE_ITEM_HANDLER = new EmptyHandler() { + @Override public int getSlots() { return Integer.MAX_VALUE; // pls don't iterate UwU } }; private static final IMultiTankFluidHandler EMPTY_MULTI_TANK_FLUID_HANDLER = new MultiTankFluidHandler() { + @Override public int getTanks() { return Integer.MAX_VALUE; // pls don't iterate UwU @@ -108,8 +106,11 @@ public static IWidget buildViewerUI(TestMachine.Recipe recipe) { return slot.toRecipeViewerSlot() .value(fluid) .tooltipBuilder(tooltip -> { - tooltip.addLine(Component.literal("Amount: " + fluid.getAmount() + " L").withStyle(ChatFormatting.BLUE)); - tooltip.addLine(Component.literal("Temperature: " + fluid.getFluid().getFluidType().getTemperature() + " K").withStyle(ChatFormatting.RED)); + tooltip.addLine(Component.literal("Amount: " + fluid.getAmount() + " L") + .withStyle(ChatFormatting.BLUE)); + tooltip.addLine(Component + .literal("Temperature: " + fluid.getFluid().getFluidType().getTemperature() + " K") + .withStyle(ChatFormatting.RED)); String liquid = !fluid.getFluid().is(Tags.Fluids.GASEOUS) ? "liquid" : "gas"; tooltip.addLine(Component.literal("State: " + liquid).withStyle(ChatFormatting.GREEN)); }); @@ -133,7 +134,8 @@ public static void openTestRecipeViewerCategory() { public static class EMI { - public static final EmiRecipeCategory CATEGORY = new EmiRecipeCategory(ModularUI.id("machine"), EmiStack.of(TestRegistration.TEST_MACHINE_BLOCK_ITEM.get())); + public static final EmiRecipeCategory CATEGORY = new EmiRecipeCategory(ModularUI.id("machine"), + EmiStack.of(TestRegistration.TEST_MACHINE_BLOCK_ITEM.get())); public static void openRecipeCategory() { EmiApi.displayRecipeCategory(CATEGORY); @@ -149,8 +151,10 @@ public static void register(EmiRegistry registry) { public static class RecipeDisplay extends ModularUIEmiRecipe { private final TestMachine.Recipe recipe; - @Getter private final List inputs = new ArrayList<>(); - @Getter private final List outputs = new ArrayList<>(); + @Getter + private final List inputs = new ArrayList<>(); + @Getter + private final List outputs = new ArrayList<>(); public RecipeDisplay(Supplier widgetSupplier, TestMachine.Recipe recipe) { super(recipe.id, widgetSupplier); @@ -170,7 +174,8 @@ public EmiRecipeCategory getCategory() { public static class JEI { - public static final RecipeType RECIPE_TYPE = new RecipeType<>(ModularUI.id("machine"), TestMachine.Recipe.class); + public static final RecipeType RECIPE_TYPE = new RecipeType<>(ModularUI.id("machine"), + TestMachine.Recipe.class); public static void openRecipeCategory() { ModularUIJeiPlugin.getRuntime().getRecipesGui().showTypes(List.of(RECIPE_TYPE)); @@ -211,7 +216,8 @@ public int getMaxHeight() { } @Override - public void setupRecipeIngredients(IRecipeLayoutBuilder builder, TestMachine.Recipe recipe, IFocusGroup focuses) { + public void setupRecipeIngredients(IRecipeLayoutBuilder builder, TestMachine.Recipe recipe, + IFocusGroup focuses) { builder.addSlot(RecipeIngredientRole.INPUT) .addItemStacks(recipe.inItems) .addIngredients(ForgeTypes.FLUID_STACK, recipe.inFluids); @@ -249,8 +255,10 @@ public static void registerDisplay(DisplayRegistry registry) { public static class RecipeDisplay extends ModularUIReiDisplay { private final TestMachine.Recipe recipe; - @Getter private final List inputEntries = new ArrayList<>(); - @Getter private final List outputEntries = new ArrayList<>(); + @Getter + private final List inputEntries = new ArrayList<>(); + @Getter + private final List outputEntries = new ArrayList<>(); public RecipeDisplay(Supplier recipeUI, TestMachine.Recipe recipe) { super(recipe.id, recipeUI, CATEGORY); diff --git a/src/main/java/brachy/modularui/test/TestRegistration.java b/src/main/java/brachy/modularui/test/TestRegistration.java index c14440a5..a9514ec3 100644 --- a/src/main/java/brachy/modularui/test/TestRegistration.java +++ b/src/main/java/brachy/modularui/test/TestRegistration.java @@ -2,31 +2,30 @@ import brachy.modularui.ModularUI; -import net.minecraft.core.Direction; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; -import org.jetbrains.annotations.Nullable; - -import java.util.function.Function; import java.util.function.Supplier; public class TestRegistration { - private static final DeferredRegister BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, ModularUI.MOD_ID); - private static final DeferredRegister ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModularUI.MOD_ID); - private static final DeferredRegister> BE_TYPES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, ModularUI.MOD_ID); + private static final DeferredRegister BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, + ModularUI.MOD_ID); + private static final DeferredRegister ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, + ModularUI.MOD_ID); + private static final DeferredRegister> BE_TYPES = DeferredRegister + .create(ForgeRegistries.BLOCK_ENTITY_TYPES, ModularUI.MOD_ID); - public static final RegistryObject TEST_BLOCK = BLOCKS.register("test_block", () -> new TestBlock(TestBlockEntity::new)); - public static final RegistryObject TEST_BLOCK_ITEM = ITEMS.register("test_block", () -> new BlockItem(TEST_BLOCK.get(), new Item.Properties())); + public static final RegistryObject TEST_BLOCK = BLOCKS.register("test_block", + () -> new TestBlock(TestBlockEntity::new)); + public static final RegistryObject TEST_BLOCK_ITEM = ITEMS.register("test_block", + () -> new BlockItem(TEST_BLOCK.get(), new Item.Properties())); private static Supplier testItemFactory() { if (ModularUI.Mods.CURIOS.isLoaded()) { @@ -36,11 +35,15 @@ private static Supplier testItemFactory() { } public static final RegistryObject TEST_ITEM = ITEMS.register("test_item", testItemFactory()); - public static final RegistryObject> BE_TYPE = BE_TYPES.register("test_block", () -> BlockEntityType.Builder.of(TestBlockEntity::new, TEST_BLOCK.get()).build(null)); - - public static final RegistryObject TEST_MACHINE_BLOCK = BLOCKS.register("machine_block", () -> new TestBlock(TestMachine.BE::new)); - public static final RegistryObject TEST_MACHINE_BLOCK_ITEM = ITEMS.register("machine_block", () -> new BlockItem(TEST_MACHINE_BLOCK.get(), new Item.Properties())); - public static final RegistryObject> MACHINE_BE_TYPE = BE_TYPES.register("machine_block", () -> BlockEntityType.Builder.of(TestMachine.BE::new, TEST_MACHINE_BLOCK.get()).build(null)); + public static final RegistryObject> BE_TYPE = BE_TYPES.register("test_block", + () -> BlockEntityType.Builder.of(TestBlockEntity::new, TEST_BLOCK.get()).build(null)); + + public static final RegistryObject TEST_MACHINE_BLOCK = BLOCKS.register("machine_block", + () -> new TestBlock(TestMachine.BE::new)); + public static final RegistryObject TEST_MACHINE_BLOCK_ITEM = ITEMS.register("machine_block", + () -> new BlockItem(TEST_MACHINE_BLOCK.get(), new Item.Properties())); + public static final RegistryObject> MACHINE_BE_TYPE = BE_TYPES.register("machine_block", + () -> BlockEntityType.Builder.of(TestMachine.BE::new, TEST_MACHINE_BLOCK.get()).build(null)); public static void register(IEventBus bus) { BLOCKS.register(bus); diff --git a/src/main/java/brachy/modularui/theme/ReloadThemeEvent.java b/src/main/java/brachy/modularui/theme/ReloadThemeEvent.java index 2dec0005..ea533710 100755 --- a/src/main/java/brachy/modularui/theme/ReloadThemeEvent.java +++ b/src/main/java/brachy/modularui/theme/ReloadThemeEvent.java @@ -4,6 +4,7 @@ /** * This event is invoked when themes are reloaded, but not on startup. - * Do not use this to register themes. Use {@link net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent FMLConstructModEvent} instead. + * Do not use this to register themes. Use {@link net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent + * FMLConstructModEvent} instead. */ public class ReloadThemeEvent extends Event {} diff --git a/src/main/java/brachy/modularui/theme/SelectableTheme.java b/src/main/java/brachy/modularui/theme/SelectableTheme.java index b67841bc..8e0a88e3 100755 --- a/src/main/java/brachy/modularui/theme/SelectableTheme.java +++ b/src/main/java/brachy/modularui/theme/SelectableTheme.java @@ -71,7 +71,7 @@ public int getSelectedIconColor() { } public static class Builder> - extends WidgetThemeBuilder { + extends WidgetThemeBuilder { public B selectedColor(int color) { add(IThemeApi.SELECTED_COLOR, ThemeBuilder.colorJson(color)); diff --git a/src/main/java/brachy/modularui/theme/TextFieldTheme.java b/src/main/java/brachy/modularui/theme/TextFieldTheme.java index 17db0a73..7e556b05 100755 --- a/src/main/java/brachy/modularui/theme/TextFieldTheme.java +++ b/src/main/java/brachy/modularui/theme/TextFieldTheme.java @@ -34,7 +34,7 @@ public WidgetTheme withNoHoverBackground() { } public static class Builder> - extends WidgetThemeBuilder { + extends WidgetThemeBuilder { public B markedColor(int markedColor) { add(IThemeApi.MARKED_COLOR, ThemeBuilder.colorJson(markedColor)); diff --git a/src/main/java/brachy/modularui/theme/ThemeAPI.java b/src/main/java/brachy/modularui/theme/ThemeAPI.java index c42ed12d..4de8d3e3 100644 --- a/src/main/java/brachy/modularui/theme/ThemeAPI.java +++ b/src/main/java/brachy/modularui/theme/ThemeAPI.java @@ -61,7 +61,8 @@ public List getJavaDefaultThemes(String id) { } @Override - public ITheme getThemeForScreen(String owner, String name, @Nullable String panel, @Nullable String defaultTheme, @Nullable String fallbackTheme) { + public ITheme getThemeForScreen(String owner, String name, @Nullable String panel, @Nullable String defaultTheme, + @Nullable String fallbackTheme) { String theme = getThemeIdForScreen(owner, name, panel); if (theme != null) return getTheme(theme); if (defaultTheme != null) return getTheme(defaultTheme); @@ -99,7 +100,9 @@ public void registerThemeForScreen(String screen, String theme) { @SuppressWarnings("unchecked") @Override - public WidgetThemeKey registerWidgetTheme(String id, T defaultTheme, T defaultHoverTheme, WidgetThemeMerger merger, WidgetThemeCodec codec) { + public WidgetThemeKey registerWidgetTheme(String id, T defaultTheme, T defaultHoverTheme, + WidgetThemeMerger merger, + WidgetThemeCodec codec) { Objects.requireNonNull(id, "Id for widget theme must not be null"); Objects.requireNonNull(defaultTheme, "Default widget theme must not be null, but is null for id '" + id + "'."); Objects.requireNonNull(merger, "Merger for widget theme must not be null, but is null for id '" + id + "'."); diff --git a/src/main/java/brachy/modularui/theme/ThemeBuilder.java b/src/main/java/brachy/modularui/theme/ThemeBuilder.java index f64a0e13..deec4410 100755 --- a/src/main/java/brachy/modularui/theme/ThemeBuilder.java +++ b/src/main/java/brachy/modularui/theme/ThemeBuilder.java @@ -115,7 +115,7 @@ public B background(WidgetThemeKey widgetTheme, String textureId) { } public B background(WidgetThemeKey widgetTheme, JsonBuilder builder) { - if (builder instanceof WidgetThemeBuilder) { + if (builder instanceof WidgetThemeBuilder) { throw new IllegalArgumentException("Did you mean to call .widgetTheme() instead of .background()?"); } mergeAdd(widgetTheme.getFullName(), @@ -134,7 +134,7 @@ public B hoverBackground(WidgetThemeKey widgetTheme, String textureId) { } public B hoverBackground(WidgetThemeKey widgetTheme, JsonBuilder builder) { - if (builder instanceof WidgetThemeBuilder) { + if (builder instanceof WidgetThemeBuilder) { throw new IllegalArgumentException("Did you mean to call .widgetTheme() instead of .hoverBackground()?"); } mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, @@ -148,7 +148,8 @@ public B color(WidgetThemeKey widgetTheme, int v) { } public B hoverColor(WidgetThemeKey widgetTheme, int v) { - mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, new JsonBuilder().add(IThemeApi.COLOR, colorJson(v))); + mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, + new JsonBuilder().add(IThemeApi.COLOR, colorJson(v))); return getThis(); } @@ -158,7 +159,8 @@ public B textColor(WidgetThemeKey widgetTheme, int v) { } public B textHoverColor(WidgetThemeKey widgetTheme, int v) { - mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, new JsonBuilder().add(IThemeApi.TEXT_COLOR, colorJson(v))); + mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, + new JsonBuilder().add(IThemeApi.TEXT_COLOR, colorJson(v))); return getThis(); } @@ -178,7 +180,8 @@ public B iconColor(WidgetThemeKey widgetTheme, int v) { } public B iconHoverColor(WidgetThemeKey widgetTheme, int v) { - mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, new JsonBuilder().add(IThemeApi.ICON_COLOR, colorJson(v))); + mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, + new JsonBuilder().add(IThemeApi.ICON_COLOR, colorJson(v))); return getThis(); } diff --git a/src/main/java/brachy/modularui/theme/ThemeManager.java b/src/main/java/brachy/modularui/theme/ThemeManager.java index 76732303..5235b8c4 100755 --- a/src/main/java/brachy/modularui/theme/ThemeManager.java +++ b/src/main/java/brachy/modularui/theme/ThemeManager.java @@ -13,7 +13,6 @@ import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.SimplePreparableReloadListener; import net.minecraft.util.profiling.ProfilerFiller; -import com.mojang.serialization.JsonOps; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.MinecraftForge; @@ -21,6 +20,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import com.mojang.serialization.JsonOps; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -75,7 +75,8 @@ public static void reload() { for (String namespace : resourceManager.getNamespaces()) { profiler.push(namespace); - for (Resource resource : resourceManager.getResourceStack(ResourceLocation.fromNamespaceAndPath(namespace, THEMES_PATH))) { + for (Resource resource : resourceManager + .getResourceStack(ResourceLocation.fromNamespaceAndPath(namespace, THEMES_PATH))) { profiler.push(resource.sourcePackId()); themeJsonSources.add(resource.sourcePackId()); @@ -266,7 +267,7 @@ private static void loadScreenThemes(JsonObject json) { private static void validateJsonScreenThemes() { for (ObjectIterator> iterator = ThemeAPI.INSTANCE.jsonScreenThemes - .object2ObjectEntrySet().fastIterator(); iterator.hasNext(); ) { + .object2ObjectEntrySet().fastIterator(); iterator.hasNext();) { Map.Entry entry = iterator.next(); if (!ThemeAPI.INSTANCE.hasTheme(entry.getValue())) { ModularUI.LOGGER.error("Tried to register theme '{}' for screen '{}', but theme does not exist", @@ -287,7 +288,7 @@ private ThemeJson(String id, List jsons, boolean override) { this.id = id; this.override = override; String p = null; - for (ListIterator iterator = jsons.listIterator(jsons.size()); iterator.hasPrevious(); ) { + for (ListIterator iterator = jsons.listIterator(jsons.size()); iterator.hasPrevious();) { JsonObject json = iterator.previous(); if (json.has(IThemeApi.PARENT)) { p = json.get(IThemeApi.PARENT).getAsString(); @@ -319,7 +320,8 @@ private Theme deserialize() { WidgetThemeMap widgetThemes = new WidgetThemeMap(); WidgetThemeEntry parentWidgetTheme = parent.getFallbackEntry(); // fallback theme of parent // fallback theme of new theme - var incompleteFallbackJson = ImmutableJson.of(jsonBuilder.getJson()); // themes should only inherit values which are declared here + var incompleteFallbackJson = ImmutableJson.of(jsonBuilder.getJson()); // themes should only inherit values + // which are declared here var fallbackJson = IThemeApi.FALLBACK.getMerger().merge( jsonBuilder.getJson(), ThemeManager.jsons.get(IThemeApi.FALLBACK, parentWidgetTheme.theme()), @@ -373,9 +375,11 @@ private void parse(WidgetThemeMap map, ITheme parent, Wi if (key.isSubWidgetTheme()) fallback = ImmutableJson.EMPTY; ImmutableJson widgetThemeJson; if (rawWidgetThemeJson != null) { - T parentWidgetTheme = key.isSubWidgetTheme() ? map.getTheme(key.getParent()).theme() : parent.getWidgetThemeEntry(key).theme(); + T parentWidgetTheme = key.isSubWidgetTheme() ? map.getTheme(key.getParent()).theme() : + parent.getWidgetThemeEntry(key).theme(); // sub widget themes strictly only inherit from their parent widget theme and not the parent theme - widgetThemeJson = ImmutableJson.of(merger.merge(rawWidgetThemeJson, ThemeManager.jsons.get(key, parentWidgetTheme), fallback)); + widgetThemeJson = ImmutableJson + .of(merger.merge(rawWidgetThemeJson, ThemeManager.jsons.get(key, parentWidgetTheme), fallback)); } else { widgetThemeJson = ThemeManager.jsons.get(key, parent.getWidgetThemeEntry(key).theme()); } @@ -387,12 +391,15 @@ private void parse(WidgetThemeMap map, ITheme parent, Wi } // only inherit from the widget theme if it was actually defined, otherwise use parent - ImmutableJson parentWidgetHoverTheme = definedStandard ? widgetThemeJson : ThemeManager.jsons.get(key, parent.getWidgetThemeEntry(key).hoverTheme()); + ImmutableJson parentWidgetHoverTheme = definedStandard ? widgetThemeJson : + ThemeManager.jsons.get(key, parent.getWidgetThemeEntry(key).hoverTheme()); JsonObject widgetThemeHover = merger.merge(widgetThemeHoverJson, parentWidgetHoverTheme, fallback); var immutableHoverWidgetTheme = ImmutableJson.of(widgetThemeHover); - T widgetThemeInstance = key.getCodec().codec().parse(JsonOps.INSTANCE, widgetThemeJson.toJson()).getOrThrow(false, s -> {}); - T widgetThemeHoverInstance = key.getCodec().codec().parse(JsonOps.INSTANCE, immutableHoverWidgetTheme.toJson()).getOrThrow(false, s -> {}); + T widgetThemeInstance = key.getCodec().codec().parse(JsonOps.INSTANCE, widgetThemeJson.toJson()) + .getOrThrow(false, s -> {}); + T widgetThemeHoverInstance = key.getCodec().codec() + .parse(JsonOps.INSTANCE, immutableHoverWidgetTheme.toJson()).getOrThrow(false, s -> {}); map.register(key, widgetThemeInstance, widgetThemeHoverInstance); } diff --git a/src/main/java/brachy/modularui/theme/WidgetTheme.java b/src/main/java/brachy/modularui/theme/WidgetTheme.java index 322040d3..b0f8ca66 100755 --- a/src/main/java/brachy/modularui/theme/WidgetTheme.java +++ b/src/main/java/brachy/modularui/theme/WidgetTheme.java @@ -14,15 +14,21 @@ public static WidgetThemeEntry getDefault() { return ThemeAPI.DEFAULT_THEME.getFallbackEntry(); } - @Getter private final int defaultWidth; - @Getter private final int defaultHeight; + @Getter + private final int defaultWidth; + @Getter + private final int defaultHeight; @Getter @Nullable private final IDrawable background; - @Getter private final int color; - @Getter private final int textColor; - @Getter private final boolean textShadow; - @Getter private final int iconColor; + @Getter + private final int color; + @Getter + private final int textColor; + @Getter + private final boolean textShadow; + @Getter + private final int iconColor; public static WidgetTheme whiteTextShadow(int defaultWidth, int defaultHeight, @Nullable IDrawable background) { return new WidgetTheme(defaultWidth, defaultHeight, background, Color.WHITE.main, diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeCodec.java b/src/main/java/brachy/modularui/theme/WidgetThemeCodec.java index a7375aa0..276592c0 100644 --- a/src/main/java/brachy/modularui/theme/WidgetThemeCodec.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeCodec.java @@ -5,7 +5,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; - import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.AccessLevel; import lombok.Getter; @@ -43,12 +42,12 @@ public DataResult decode(DynamicOps ops, MapLike input) { List args = new ArrayList<>(); this.fields.forEach(f -> args.add(f.decode(ops, map, errors))); if (!errors.isEmpty()) { - return DataResult.error(() -> - String.format("Errors while decoding widget theme: %s", errors)); + return DataResult.error(() -> String.format("Errors while decoding widget theme: %s", errors)); } try { return DataResult.success(this.ctor.newInstance(args.toArray(Object[]::new))); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | + IllegalArgumentException e) { return DataResult.error(e::getMessage); } } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeEntry.java b/src/main/java/brachy/modularui/theme/WidgetThemeEntry.java index 6f3e0689..3d260a09 100755 --- a/src/main/java/brachy/modularui/theme/WidgetThemeEntry.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeEntry.java @@ -12,10 +12,10 @@ * @see WidgetThemeKey * @see ITheme * - * @param key The {@link WidgetThemeKey} which this theme data is for. - * @param theme The theme data. + * @param key The {@link WidgetThemeKey} which this theme data is for. + * @param theme The theme data. * @param hoverTheme Theme data to be used when this widget is being hovered over. - * @param The class of the theme data. + * @param The class of the theme data. */ public record WidgetThemeEntry(WidgetThemeKey key, T theme, T hoverTheme) { @@ -44,6 +44,7 @@ public void encode(DynamicOps ops, RecordBuilder mapBuilder, boolean f mapBuilder.add(this.key.getFullName(), this.key.getCodec().codec().encodeStart(ops, this.theme)); } if (this.theme == this.hoverTheme) return; - mapBuilder.add(this.key.getFullName() + IThemeApi.HOVER_SUFFIX, this.key.getCodec().codec().encodeStart(ops, this.hoverTheme)); + mapBuilder.add(this.key.getFullName() + IThemeApi.HOVER_SUFFIX, + this.key.getCodec().codec().encodeStart(ops, this.hoverTheme)); } } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeField.java b/src/main/java/brachy/modularui/theme/WidgetThemeField.java index 264ae95f..70eab730 100644 --- a/src/main/java/brachy/modularui/theme/WidgetThemeField.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeField.java @@ -9,7 +9,8 @@ import java.util.List; import java.util.Map; -public record WidgetThemeField(String name, Class type, Codec codec, FieldReader fieldReader, +public record WidgetThemeField(String name, Class type, Codec codec, + FieldReader fieldReader, boolean canFallback) { void encode(T widgetTheme, DynamicOps ops, RecordBuilder mapBuilder) { @@ -27,7 +28,8 @@ V decode(DynamicOps ops, Map map, List errors) { J element = map.get(name()); if (element == null) { if (!map.containsKey(name())) { - errors.add(String.format("Field '%s' in widget theme of type %s was not found", name(), type().getSimpleName())); + errors.add(String.format("Field '%s' in widget theme of type %s was not found", name(), + type().getSimpleName())); } return null; } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeKey.java b/src/main/java/brachy/modularui/theme/WidgetThemeKey.java index edae54e0..f89165da 100755 --- a/src/main/java/brachy/modularui/theme/WidgetThemeKey.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeKey.java @@ -4,10 +4,10 @@ import brachy.modularui.utils.serialization.codec.CodecUtil; import net.minecraft.util.ExtraCodecs; -import com.mojang.serialization.Codec; -import com.mojang.serialization.JsonOps; import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.JsonOps; import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import lombok.Getter; import org.jetbrains.annotations.NotNull; @@ -17,7 +17,8 @@ import java.util.Objects; /** - * A widget theme key represents a specific type of data (e.g. item slot theme, fluid slot theme, button theme, etc), which a theme may contain.
+ * A widget theme key represents a specific type of data (e.g. item slot theme, fluid slot theme, button theme, etc), + * which a theme may contain.
* The theme key contains a codec for serialising this data, as well as the default.
* * @see WidgetThemeEntry @@ -28,7 +29,8 @@ public class WidgetThemeKey implements Comparable> { private static final Map> KEYS = new Object2ReferenceOpenHashMap<>(); - public static final Codec> CODEC = CodecUtil.chainedCodec(CodecUtil.nullCodec(), ExtraCodecs.stringResolverCodec(WidgetThemeKey::getFullName, KEYS::get)); + public static final Codec> CODEC = CodecUtil.chainedCodec(CodecUtil.nullCodec(), + ExtraCodecs.stringResolverCodec(WidgetThemeKey::getFullName, KEYS::get)); @Nullable public static WidgetThemeKey getFromFullName(String key) { @@ -38,21 +40,28 @@ public static WidgetThemeKey getFromFullName(String key) { @Nullable @Getter private final WidgetThemeKey parent; - @Getter private final Class type; - @Getter private final String name; + @Getter + private final Class type; + @Getter + private final String name; @Nullable @Getter private final String subName; - @Getter private final T defaultValue; - @Getter private final T defaultHoverValue; - @Getter private final WidgetThemeMerger merger; - @Getter private final WidgetThemeCodec codec; + @Getter + private final T defaultValue; + @Getter + private final T defaultHoverValue; + @Getter + private final WidgetThemeMerger merger; + @Getter + private final WidgetThemeCodec codec; WidgetThemeKey(Class type, String name, T defaultValue, WidgetThemeMerger merger, WidgetThemeCodec codec) { this(type, name, defaultValue, defaultValue, merger, codec); } - WidgetThemeKey(Class type, String name, T defaultValue, T defaultHoverValue, WidgetThemeMerger merger, WidgetThemeCodec codec) { + WidgetThemeKey(Class type, String name, T defaultValue, T defaultHoverValue, WidgetThemeMerger merger, + WidgetThemeCodec codec) { this(null, type, name, null, defaultValue, defaultHoverValue, merger, codec); } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeKeyBuilder.java b/src/main/java/brachy/modularui/theme/WidgetThemeKeyBuilder.java index 75b22ff0..071e6eb3 100755 --- a/src/main/java/brachy/modularui/theme/WidgetThemeKeyBuilder.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeKeyBuilder.java @@ -45,26 +45,31 @@ public WidgetThemeKeyBuilder fieldsOf(WidgetThemeKey key) { return this; } - public WidgetThemeKeyBuilder field(String name, Class type, Codec codec, FieldReader fieldReader) { + public WidgetThemeKeyBuilder field(String name, Class type, Codec codec, + FieldReader fieldReader) { return field(name, type, codec, fieldReader, false); } - public WidgetThemeKeyBuilder fallbackField(String name, Class type, Codec codec, FieldReader fieldReader) { + public WidgetThemeKeyBuilder fallbackField(String name, Class type, Codec codec, + FieldReader fieldReader) { return field(name, type, codec, fieldReader, true); } /** - * Adds a field to the codec. The widget theme must have a public constructor with all the fields in the same order they were added. + * Adds a field to the codec. The widget theme must have a public constructor with all the fields in the same order + * they were added. * The constructor is found and used via reflection. * * @param name name of the field, used to read and write in JSON * @param type type of the field in the constructor, must be exact * @param codec codec for this field * @param fieldReader reads the field from a widget theme - * @param canFallback determines if values are inherited from parent or fallback first, if this is true fallback is used first, + * @param canFallback determines if values are inherited from parent or fallback first, if this is true fallback is + * used first, * but can be disabled individually via the "inherited" property in JSON */ - public WidgetThemeKeyBuilder field(String name, Class type, Codec codec, FieldReader fieldReader, boolean canFallback) { + public WidgetThemeKeyBuilder field(String name, Class type, Codec codec, FieldReader fieldReader, + boolean canFallback) { this.fields.add(new WidgetThemeField<>(name, type, codec, fieldReader, canFallback)); return this; } @@ -89,16 +94,19 @@ public WidgetThemeKey register() { merger = (WidgetThemeMerger) this.parser.getMerger(); } } - if (this.fields.isEmpty() && (merger == null || codec == null)) throw new IllegalArgumentException("No fields for codec provided!"); + if (this.fields.isEmpty() && (merger == null || codec == null)) + throw new IllegalArgumentException("No fields for codec provided!"); if (merger == null) merger = new WidgetThemeMerger<>(this.fields); if (codec == null) { Constructor ctor; Class[] types = this.fields.stream().map(WidgetThemeField::type).toArray(Class[]::new); try { - ctor = this.type.getDeclaredConstructor(this.fields.stream().map(WidgetThemeField::type).toArray(Class[]::new)); + ctor = this.type + .getDeclaredConstructor(this.fields.stream().map(WidgetThemeField::type).toArray(Class[]::new)); } catch (NoSuchMethodException e) { String sTypes = Arrays.stream(types).map(Class::getSimpleName).reduce("", (a, b) -> a + b + ", "); - throw new IllegalArgumentException("No constructor found for the fields with the given types in that order. Types: " + sTypes); + throw new IllegalArgumentException( + "No constructor found for the fields with the given types in that order. Types: " + sTypes); } codec = new WidgetThemeCodec<>(this.type, this.fields, ctor); } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeMerger.java b/src/main/java/brachy/modularui/theme/WidgetThemeMerger.java index 802f56f4..e0bed769 100644 --- a/src/main/java/brachy/modularui/theme/WidgetThemeMerger.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeMerger.java @@ -27,7 +27,8 @@ public JsonObject merge(JsonObject input, ImmutableJson parent, ImmutableJson fa return input; } - private void mergeField(WidgetThemeField field, JsonObject input, ImmutableJson parent, ImmutableJson fallback, JsonElement inheritsList) { + private void mergeField(WidgetThemeField field, JsonObject input, ImmutableJson parent, + ImmutableJson fallback, JsonElement inheritsList) { var key = field.name(); if (input.has(key)) return; if (field.canFallback() && !inherits(inheritsList, key) && fallback.has(key)) { diff --git a/src/main/java/brachy/modularui/utils/Alignment.java b/src/main/java/brachy/modularui/utils/Alignment.java index baa477c8..f5ab0aaf 100644 --- a/src/main/java/brachy/modularui/utils/Alignment.java +++ b/src/main/java/brachy/modularui/utils/Alignment.java @@ -4,10 +4,10 @@ import net.minecraft.util.ExtraCodecs; import net.minecraft.util.StringRepresentable; -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; import com.google.common.base.CaseFormat; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.AccessLevel; import lombok.Getter; @@ -23,14 +23,16 @@ public class Alignment { private static final Codec CODEC_OF_INSTANCE = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("x").forGetter(Alignment::getX), - Codec.FLOAT.fieldOf("y").forGetter(Alignment::getY) - ).apply(instance, Alignment::new)); - private static final Codec CODEC_OF_NAME = ExtraCodecs.stringResolverCodec(Alignment::getName, ALIGNMENT_MAP::get); + Codec.FLOAT.fieldOf("y").forGetter(Alignment::getY)).apply(instance, Alignment::new)); + private static final Codec CODEC_OF_NAME = ExtraCodecs.stringResolverCodec(Alignment::getName, + ALIGNMENT_MAP::get); public static final Codec CODEC = CodecUtil.chainedCodec(CODEC_OF_NAME, CODEC_OF_INSTANCE); - @Getter public final float x, y; - @Getter(AccessLevel.PRIVATE) private final String name; + @Getter + public final float x, y; + @Getter(AccessLevel.PRIVATE) + private final String name; public static final Alignment TopLeft = new Alignment(0, 0, "TopLeft"); public static final Alignment TopCenter = new Alignment(0.5f, 0, "TopCenter"); diff --git a/src/main/java/brachy/modularui/utils/Color.java b/src/main/java/brachy/modularui/utils/Color.java index 1954e036..aa4f7c89 100644 --- a/src/main/java/brachy/modularui/utils/Color.java +++ b/src/main/java/brachy/modularui/utils/Color.java @@ -5,14 +5,14 @@ import brachy.modularui.utils.serialization.codec.CodecUtil; import net.minecraft.util.Mth; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.serialization.Codec; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import com.google.gson.JsonObject; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.codecs.RecordCodecBuilder; import java.util.Locale; import java.util.Random; @@ -610,7 +610,7 @@ public static int withBlack(int argb, float black) { * @return rgba as an array [red, green, blue] */ public static int[] getRGBValues(int argb) { - return new int[]{getRed(argb), getGreen(argb), getBlue(argb)}; + return new int[] { getRed(argb), getGreen(argb), getBlue(argb) }; } /** @@ -619,7 +619,7 @@ public static int[] getRGBValues(int argb) { * @return rgba as an array [red, green, blue, alpha] */ public static int[] getARGBValues(int argb) { - return new int[]{getRed(argb), getGreen(argb), getBlue(argb), getAlpha(argb)}; + return new int[] { getRed(argb), getGreen(argb), getBlue(argb), getAlpha(argb) }; } /** @@ -629,7 +629,7 @@ public static int[] getARGBValues(int argb) { * @return HSV values array */ public static float[] getHSVValues(int argb) { - return new float[]{getHue(argb), getHSVSaturation(argb), getValue(argb)}; + return new float[] { getHue(argb), getHSVSaturation(argb), getValue(argb) }; } /** @@ -639,7 +639,7 @@ public static float[] getHSVValues(int argb) { * @return HSL values array */ public static float[] getHSLValues(int argb) { - return new float[]{getHue(argb), getHSLSaturation(argb), getLightness(argb)}; + return new float[] { getHue(argb), getHSLSaturation(argb), getLightness(argb) }; } /** @@ -649,7 +649,7 @@ public static float[] getHSLValues(int argb) { * @return CMYK values array */ public static float[] getCMYKValues(int argb) { - return new float[]{getCyan(argb), getMagenta(argb), getYellow(argb), getBlack(argb)}; + return new float[] { getCyan(argb), getMagenta(argb), getYellow(argb), getBlack(argb) }; } /** @@ -836,11 +836,13 @@ public static void resetGlColor() { } public static int getLargestDiff(int argb1, int argb2) { - return Math.max(Math.abs(getRed(argb1) - getRed(argb2)), Math.max(Math.abs(getGreen(argb1) - getGreen(argb2)), Math.abs(getBlue(argb1) - getBlue(argb2)))); + return Math.max(Math.abs(getRed(argb1) - getRed(argb2)), + Math.max(Math.abs(getGreen(argb1) - getGreen(argb2)), Math.abs(getBlue(argb1) - getBlue(argb2)))); } public static float getLargestDiffFloat(int argb1, int argb2) { - return Math.max(Math.abs(getRedF(argb1) - getRedF(argb2)), Math.max(Math.abs(getGreenF(argb1) - getGreenF(argb2)), Math.abs(getBlueF(argb1) - getBlueF(argb2)))); + return Math.max(Math.abs(getRedF(argb1) - getRedF(argb2)), + Math.max(Math.abs(getGreenF(argb1) - getGreenF(argb2)), Math.abs(getBlueF(argb1) - getBlueF(argb2)))); } public static boolean areSameColor(int argb1, int argb2) { @@ -932,41 +934,39 @@ public static String componentToFullHexString(int component) { return s; } - public static final Codec CODEC_STRING = Codec.STRING.comapFlatMap(Color::parseString, c -> "#" + argbToFullHexString(c)); + public static final Codec CODEC_STRING = Codec.STRING.comapFlatMap(Color::parseString, + c -> "#" + argbToFullHexString(c)); public static final Codec CODEC_ARGB = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("r").forGetter(Color::getRedF), Codec.FLOAT.fieldOf("g").forGetter(Color::getGreenF), Codec.FLOAT.fieldOf("b").forGetter(Color::getBlueF), - Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF) - ).apply(instance, Color::argb)); + Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF)).apply(instance, Color::argb)); public static final Codec CODEC_HSV = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("h").forGetter(Color::getHue), Codec.FLOAT.fieldOf("s").forGetter(Color::getHSVSaturation), Codec.FLOAT.fieldOf("v").forGetter(Color::getValue), - Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF) - ).apply(instance, Color::ofHSV)); + Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF)).apply(instance, Color::ofHSV)); public static final Codec CODEC_HSL = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("h").forGetter(Color::getHue), Codec.FLOAT.fieldOf("s").forGetter(Color::getHSLSaturation), Codec.FLOAT.fieldOf("l").forGetter(Color::getLightness), - Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF) - ).apply(instance, Color::ofHSL)); + Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF)).apply(instance, Color::ofHSL)); public static final Codec CODEC_CMYK = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("c").forGetter(Color::getCyan), Codec.FLOAT.fieldOf("m").forGetter(Color::getMagenta), Codec.FLOAT.fieldOf("y").forGetter(Color::getYellow), Codec.FLOAT.fieldOf("k").forGetter(Color::getBlack), - Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF) - ).apply(instance, Color::ofCMYK)); + Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF)).apply(instance, Color::ofCMYK)); /** * Encodes into hex string and decodes, hex string, arg obj, hsv obj, hsl obj, cmyk obj and then raw argb integer. */ - public static final Codec CODEC = CodecUtil.codecOf(CODEC_STRING, CODEC_STRING, CODEC_ARGB, CODEC_HSV, CODEC_HSL, CODEC_CMYK, Codec.INT); + public static final Codec CODEC = CodecUtil.codecOf(CODEC_STRING, CODEC_STRING, CODEC_ARGB, CODEC_HSV, + CODEC_HSL, CODEC_CMYK, Codec.INT); public static DataResult parseString(String colorString) { return parseString(colorString, WHITE.main); @@ -976,8 +976,10 @@ public static DataResult parseString(String colorString) { * Parses a color ARGB int from a string. * The string can be a number in decimal (no prefix), hexadecimal (0x, 0X or # prefix) or octal (0 prefix). * Otherwise, it can be a name from a {@link ColorShade} instance. The default instances can be found at the bottom - * of this class. These names can be suffixed with colon and a negative number for darker colors or positive number for brighter colors. - * The number is an index to an array with predefined shades. 0 is the main color. If no color for a name is found, the fallback value + * of this class. These names can be suffixed with colon and a negative number for darker colors or positive number + * for brighter colors. + * The number is an index to an array with predefined shades. 0 is the main color. If no color for a name is found, + * the fallback value * is returned. The shade index is clamped to valid values. *

* Example: "deep_purple:-3" returns 0xFF4527A0 @@ -1001,7 +1003,8 @@ public static DataResult parseString(String colorString, int fallback) return DataResult.success(color); } catch (NumberFormatException e) { String finalColorString = colorString; - return DataResult.error(() -> String.format("Failed to decode color of string '%s'.", finalColorString), fallback); + return DataResult.error(() -> String.format("Failed to decode color of string '%s'.", finalColorString), + fallback); } } @@ -1025,14 +1028,17 @@ public static DataResult parseString(String colorString, int fallback) if (colorShade != null) { if (fail != null) { String finalFail = fail; - return DataResult.error(() -> String.format("If the color is a word then after teh : must come a negative or positive integer, but got '%s'.", finalFail), colorShade.main); + return DataResult.error(() -> String.format( + "If the color is a word then after teh : must come a negative or positive integer, but got '%s'.", + finalFail), colorShade.main); } if (index == 0) return DataResult.success(colorShade.main); if (index > 0) return DataResult.success(colorShade.brighterSafe(index - 1)); return DataResult.success(colorShade.darkerSafe(-index - 1)); } String finalColorString1 = colorString; - return DataResult.error(() -> String.format("No color shade for name '%s' was found", finalColorString1), fallback); + return DataResult.error(() -> String.format("No color shade for name '%s' was found", finalColorString1), + fallback); } private static boolean hasRGB(JsonObject json) { diff --git a/src/main/java/brachy/modularui/utils/CursorHandler.java b/src/main/java/brachy/modularui/utils/CursorHandler.java index b3eb9f76..3447011d 100644 --- a/src/main/java/brachy/modularui/utils/CursorHandler.java +++ b/src/main/java/brachy/modularui/utils/CursorHandler.java @@ -65,7 +65,8 @@ public static long createSafeCursor(int shape) { try (GLFWErrorCallback ignored = org.lwjgl.glfw.GLFW.glfwSetErrorCallback(null)) { long cursor = GLFW.glfwCreateStandardCursor(shape); if (cursor == 0L) { // If can't load platform-specific default cursors - ModularUI.LOGGER.warn("GLFW: Failed to create standard cursor shape {}. Falling back to default pointer.", + ModularUI.LOGGER.warn( + "GLFW: Failed to create standard cursor shape {}. Falling back to default pointer.", shape); // TODO: Load custom textures return 0L; diff --git a/src/main/java/brachy/modularui/utils/FormattingUtil.java b/src/main/java/brachy/modularui/utils/FormattingUtil.java index 6bc35b44..b93eb59d 100755 --- a/src/main/java/brachy/modularui/utils/FormattingUtil.java +++ b/src/main/java/brachy/modularui/utils/FormattingUtil.java @@ -73,7 +73,7 @@ private static String checkNumbers(String string, int startIndex) { * @param string Any string with ASCII characters. * @return A string that is all lowercase, with underscores inserted before word/number boundaries: * - *

+     *         
      *         
{@code "maragingSteel300" -> "maraging_steel_300"} *
{@code "gtceu:maraging_steel_300" -> "gtceu:maraging_steel_300"} *
{@code "maragingSteel_300" -> "maraging_steel_300"} @@ -146,7 +146,7 @@ public static String toRomanNumeral(int number) { * * @param string Any string with ASCII characters. * @return A string that is all lowercase, with underscores inserted before word/number boundaries: - * "maraging_steel_300" -> "maragingSteel300" + * "maraging_steel_300" -> "maragingSteel300" */ public static String lowerUnderscoreToUpperCamel(String string) { StringBuilder result = new StringBuilder(); diff --git a/src/main/java/brachy/modularui/utils/GradientUtil.java b/src/main/java/brachy/modularui/utils/GradientUtil.java index 7d1662b1..465941d8 100755 --- a/src/main/java/brachy/modularui/utils/GradientUtil.java +++ b/src/main/java/brachy/modularui/utils/GradientUtil.java @@ -23,7 +23,7 @@ public static float[] getRGB(int color) { float g = ((color >> 8) & 0xFF) / 255f; // noinspection PointlessBitwiseExpression float b = ((color >> 0) & 0xFF) / 255f; - return new float[]{r, g, b}; + return new float[] { r, g, b }; } public static int multiplyBlendWithAlpha(int c1, int c2) { @@ -123,7 +123,7 @@ public static float[] RGBtoHSL(int rgbColor) { s = (max - min) / (2 - max - min); } - return new float[]{h, s * 100, l * 100}; + return new float[] { h, s * 100, l * 100 }; } public static int toRGB(float[] hsv) { diff --git a/src/main/java/brachy/modularui/utils/ImageUtil.java b/src/main/java/brachy/modularui/utils/ImageUtil.java index fb20cfb5..bb84a7ad 100644 --- a/src/main/java/brachy/modularui/utils/ImageUtil.java +++ b/src/main/java/brachy/modularui/utils/ImageUtil.java @@ -114,7 +114,8 @@ public static boolean testImageSize(ResourceLocation resLoc, int width, int heig int w = ImageUtil.getWidth(size); int h = ImageUtil.getHeight(size); if (w != width || h != height) { - ModularUI.LOGGER.error("Image size is incorrect of image '{}'. Expected {}|{}, but actually is {}|{}", resLoc, + ModularUI.LOGGER.error("Image size is incorrect of image '{}'. Expected {}|{}, but actually is {}|{}", + resLoc, width, height, w, h); } else { ModularUI.LOGGER.info("Image '{}' has correct size", resLoc); @@ -200,6 +201,7 @@ private interface SizeParser { private enum ImageType implements SizeParser { PNG(8, 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) { + @Override public long parse(InputStream inputStream) throws IOException { DataInput dataInput = getDataInput(inputStream); @@ -209,6 +211,7 @@ public long parse(InputStream inputStream) throws IOException { } }, JPEG(2, 0xFF, 0xD8) { + @Override public long parse(InputStream inputStream) throws IOException { DataInput dis = getDataInput(inputStream); @@ -247,6 +250,7 @@ public long parse(InputStream inputStream) throws IOException { }, // 5th byte is variable -> only use the first 4 GIF(6, 0x47, 0x49, 0x46, 0x38) { + @Override public long parse(InputStream inputStream) throws IOException { return packSize(readLittleEndianShort(inputStream), readLittleEndianShort(inputStream)); diff --git a/src/main/java/brachy/modularui/utils/Interpolation.java b/src/main/java/brachy/modularui/utils/Interpolation.java index 75fe110c..259dc17a 100755 --- a/src/main/java/brachy/modularui/utils/Interpolation.java +++ b/src/main/java/brachy/modularui/utils/Interpolation.java @@ -13,24 +13,28 @@ public enum Interpolation implements IInterpolation, StringRepresentable { LINEAR("linear") { + @Override public float interpolate(float a, float b, float x) { return Interpolations.lerp(a, b, x); } }, QUAD_IN("quad_in") { + @Override public float interpolate(float a, float b, float x) { return a + (b - a) * x * x; } }, QUAD_OUT("quad_out") { + @Override public float interpolate(float a, float b, float x) { return a - (b - a) * x * (x - 2); } }, QUAD_INOUT("quad_inout") { + @Override public float interpolate(float a, float b, float x) { x *= 2; @@ -43,12 +47,14 @@ public float interpolate(float a, float b, float x) { } }, CUBIC_IN("cubic_in") { + @Override public float interpolate(float a, float b, float x) { return a + (b - a) * x * x * x; } }, CUBIC_OUT("cubic_out") { + @Override public float interpolate(float a, float b, float x) { x -= 1; @@ -56,6 +62,7 @@ public float interpolate(float a, float b, float x) { } }, CUBIC_INOUT("cubic_inout") { + @Override public float interpolate(float a, float b, float x) { x *= 2; @@ -68,18 +75,21 @@ public float interpolate(float a, float b, float x) { } }, EXP_IN("exp_in") { + @Override public float interpolate(float a, float b, float x) { return a + (b - a) * (float) Math.pow(2, 10 * (x - 1)); } }, EXP_OUT("exp_out") { + @Override public float interpolate(float a, float b, float x) { return a + (b - a) * (float) (-Math.pow(2, -10 * x) + 1); } }, EXP_INOUT("exp_inout") { + @Override public float interpolate(float a, float b, float x) { if (x == 0) return a; @@ -96,6 +106,7 @@ public float interpolate(float a, float b, float x) { }, /* Following interpolations below were copied from: https://easings.net/ */ BACK_IN("back_in") { + @Override public float interpolate(float a, float b, float x) { final float c1 = 1.70158F; @@ -105,6 +116,7 @@ public float interpolate(float a, float b, float x) { } }, BACK_OUT("back_out") { + @Override public float interpolate(float a, float b, float x) { final float c1 = 1.70158F; @@ -114,6 +126,7 @@ public float interpolate(float a, float b, float x) { } }, BACK_INOUT("back_inout") { + @Override public float interpolate(float a, float b, float x) { final float c1 = 1.70158F; @@ -126,6 +139,7 @@ public float interpolate(float a, float b, float x) { } }, ELASTIC_IN("elastic_in") { + @Override public float interpolate(float a, float b, float x) { final float c4 = (2 * (float) Math.PI) / 3; @@ -137,6 +151,7 @@ public float interpolate(float a, float b, float x) { } }, ELASTIC_OUT("elastic_out") { + @Override public float interpolate(float a, float b, float x) { final float c4 = (2 * (float) Math.PI) / 3; @@ -148,25 +163,28 @@ public float interpolate(float a, float b, float x) { } }, ELASTIC_INOUT("elastic_inout") { + @Override public float interpolate(float a, float b, float x) { final float c5 = (2 * (float) Math.PI) / 4.5F; float v = (float) Math.sin((20 * x - 11.125) * c5); float factor = x == 0 ? 0 : (x == 1 ? 1 : - (x < 0.5 ? -((float) Math.pow(2, 20 * x - 10) * v) / 2 : - ((float) Math.pow(2, -20 * x + 10) * v) / 2 + 1)); + (x < 0.5 ? -((float) Math.pow(2, 20 * x - 10) * v) / 2 : + ((float) Math.pow(2, -20 * x + 10) * v) / 2 + 1)); return Interpolations.lerp(a, b, factor); } }, BOUNCE_IN("bounce_in") { + @Override public float interpolate(float a, float b, float x) { return Interpolations.lerp(a, b, 1 - BOUNCE_OUT.interpolate(0, 1, 1 - x)); } }, BOUNCE_OUT("bounce_out") { + @Override public float interpolate(float a, float b, float x) { final float n1 = 7.5625F; @@ -187,6 +205,7 @@ public float interpolate(float a, float b, float x) { } }, BOUNCE_INOUT("bounce_inout") { + @Override public float interpolate(float a, float b, float x) { float factor = x < 0.5 ? (1 - BOUNCE_OUT.interpolate(0, 1, 1 - 2 * x)) / 2 : @@ -196,6 +215,7 @@ public float interpolate(float a, float b, float x) { } }, SINE_IN("sine_in") { + @Override public float interpolate(float a, float b, float x) { float factor = 1 - (float) Math.cos((x * Math.PI) / 2); @@ -204,6 +224,7 @@ public float interpolate(float a, float b, float x) { } }, SINE_OUT("sine_out") { + @Override public float interpolate(float a, float b, float x) { float factor = (float) Math.sin((x * Math.PI) / 2); @@ -212,6 +233,7 @@ public float interpolate(float a, float b, float x) { } }, SINE_INOUT("sine_inout") { + @Override public float interpolate(float a, float b, float x) { float factor = (float) (-(Math.cos(Math.PI * x) - 1) / 2); @@ -220,6 +242,7 @@ public float interpolate(float a, float b, float x) { } }, QUART_IN("quart_in") { + @Override public float interpolate(float a, float b, float x) { float factor = x * x * x * x; @@ -228,6 +251,7 @@ public float interpolate(float a, float b, float x) { } }, QUART_OUT("quart_out") { + @Override public float interpolate(float a, float b, float x) { float factor = 1 - (float) Math.pow(1 - x, 4); @@ -236,6 +260,7 @@ public float interpolate(float a, float b, float x) { } }, QUART_INOUT("quart_inout") { + @Override public float interpolate(float a, float b, float x) { float factor = x < 0.5 ? 8 * x * x * x * x : 1 - (float) Math.pow(-2 * x + 2, 4) / 2; @@ -244,6 +269,7 @@ public float interpolate(float a, float b, float x) { } }, QUINT_IN("quint_in") { + @Override public float interpolate(float a, float b, float x) { float factor = x * x * x * x * x; @@ -252,6 +278,7 @@ public float interpolate(float a, float b, float x) { } }, QUINT_OUT("quint_out") { + @Override public float interpolate(float a, float b, float x) { float factor = 1 - (float) Math.pow(1 - x, 5); @@ -260,6 +287,7 @@ public float interpolate(float a, float b, float x) { } }, QUINT_INOUT("quint_inout") { + @Override public float interpolate(float a, float b, float x) { float factor = x < 0.5 ? 16 * x * x * x * x * x : 1 - (float) Math.pow(-2 * x + 2, 5) / 2; @@ -268,6 +296,7 @@ public float interpolate(float a, float b, float x) { } }, CIRCLE_IN("circle_in") { + @Override public float interpolate(float a, float b, float x) { x = Mth.clamp(x, 0, 1); @@ -278,6 +307,7 @@ public float interpolate(float a, float b, float x) { } }, CIRCLE_OUT("circle_out") { + @Override public float interpolate(float a, float b, float x) { x = Mth.clamp(x, 0, 1); @@ -288,6 +318,7 @@ public float interpolate(float a, float b, float x) { } }, CIRCLE_INOUT("circle_inout") { + @Override public float interpolate(float a, float b, float x) { x = Mth.clamp(x, 0, 1); diff --git a/src/main/java/brachy/modularui/utils/MUIRenderTypes.java b/src/main/java/brachy/modularui/utils/MUIRenderTypes.java index 1f98dfd3..89f9646a 100644 --- a/src/main/java/brachy/modularui/utils/MUIRenderTypes.java +++ b/src/main/java/brachy/modularui/utils/MUIRenderTypes.java @@ -4,11 +4,12 @@ import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; + import java.util.function.Function; @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/brachy/modularui/utils/MatrixUtils.java b/src/main/java/brachy/modularui/utils/MatrixUtils.java index eea8d940..cdca8353 100755 --- a/src/main/java/brachy/modularui/utils/MatrixUtils.java +++ b/src/main/java/brachy/modularui/utils/MatrixUtils.java @@ -7,15 +7,15 @@ import net.minecraft.client.Minecraft; import net.minecraft.core.Direction; import net.minecraft.util.Mth; -import com.mojang.blaze3d.platform.GlUtil; -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Table; import com.google.common.collect.Tables; +import com.mojang.blaze3d.platform.GlUtil; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; import org.jetbrains.annotations.Contract; import org.joml.Matrix4f; import org.joml.Matrix4fc; @@ -27,6 +27,7 @@ import java.nio.ByteBuffer; import java.security.InvalidParameterException; import java.util.Objects; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault @@ -45,7 +46,7 @@ public class MatrixUtils { .synchronizedTable(HashBasedTable.create()); private static final ByteBuffer PIXEL_DEPTH_BUFFER = GlUtil.allocateMemory(4); - private static final int[] VIEWPORT_COORDS = {0, 0, 0, 0}; + private static final int[] VIEWPORT_COORDS = { 0, 0, 0, 0 }; /** * @param from the original vector @@ -275,13 +276,13 @@ public static Vector3f projectScreenToWorld(int x, int y, int viewWidth, int vie * This is in essence the same code as in gluProject, but it returns the resulting transformation matrixinstead of * applying it to the deprecated OpenGL transformation stack. * - * @param x X-coordinate in pixels - * @param y Y-coordinate in pixels - * @param viewport the viewport described by {@code [x, y, width, height]} + * @param x X-coordinate in pixels + * @param y Y-coordinate in pixels + * @param viewport the viewport described by {@code [x, y, width, height]} * @return world pos */ public static Vector3f projectScreenToWorld(int x, int y, int[] viewport) { - return projectScreenToWorld(x, y, viewport, 0, true); + return projectScreenToWorld(x, y, viewport, 0, true); } public static Vector3f projectScreenToWorld(int x, int y, int[] viewport, float depth) { diff --git a/src/main/java/brachy/modularui/utils/MouseData.java b/src/main/java/brachy/modularui/utils/MouseData.java index 316d5b07..d4c41047 100755 --- a/src/main/java/brachy/modularui/utils/MouseData.java +++ b/src/main/java/brachy/modularui/utils/MouseData.java @@ -3,10 +3,11 @@ import brachy.modularui.api.widget.Interactable; import net.minecraft.network.FriendlyByteBuf; -import com.mojang.blaze3d.platform.InputConstants; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.blaze3d.platform.InputConstants; + public record MouseData(Dist side, int mouseButton, boolean shift, boolean ctrl, boolean alt) { public boolean isClient() { diff --git a/src/main/java/brachy/modularui/utils/Rectangle.java b/src/main/java/brachy/modularui/utils/Rectangle.java index 72cba84e..8845bab0 100755 --- a/src/main/java/brachy/modularui/utils/Rectangle.java +++ b/src/main/java/brachy/modularui/utils/Rectangle.java @@ -325,7 +325,8 @@ public void set(int x, int y, int w, int h) { } public void subArea(float u0, float v0, float u1, float v1) { - set((int) (this.x + u0 * this.width), (int) (this.y + v0 * this.height), (int) ((u1 - u0) * this.width), (int) ((v1 - v0) * this.height)); + set((int) (this.x + u0 * this.width), (int) (this.y + v0 * this.height), (int) ((u1 - u0) * this.width), + (int) ((v1 - v0) * this.height)); } public PointF getCenter() { diff --git a/src/main/java/brachy/modularui/utils/Stencil.java b/src/main/java/brachy/modularui/utils/Stencil.java index cb29c84e..2a252555 100755 --- a/src/main/java/brachy/modularui/utils/Stencil.java +++ b/src/main/java/brachy/modularui/utils/Stencil.java @@ -8,12 +8,12 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.ShaderInstance; + import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; - import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/brachy/modularui/utils/TooltipLines.java b/src/main/java/brachy/modularui/utils/TooltipLines.java index deff7938..6f59998b 100755 --- a/src/main/java/brachy/modularui/utils/TooltipLines.java +++ b/src/main/java/brachy/modularui/utils/TooltipLines.java @@ -12,6 +12,7 @@ import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; import net.minecraft.world.inventory.tooltip.TooltipComponent; + import com.mojang.datafixers.util.Either; import java.util.AbstractList; diff --git a/src/main/java/brachy/modularui/utils/TreeUtil.java b/src/main/java/brachy/modularui/utils/TreeUtil.java index 13d9e3c8..841f2d11 100644 --- a/src/main/java/brachy/modularui/utils/TreeUtil.java +++ b/src/main/java/brachy/modularui/utils/TreeUtil.java @@ -86,7 +86,8 @@ public static > boolean foreachChildBFS(T parent, Predica * @param includeSelf true if the consumer should also consume the parent * @return true if the iteration was not terminated by the consumer */ - public static > boolean foreachChildBFS(T parent, Predicate consumer, boolean includeSelf) { + public static > boolean foreachChildBFS(T parent, Predicate consumer, + boolean includeSelf) { if (includeSelf && !consumer.test(parent)) return false; return parent.visitAllChildrenBFS(consumer); } @@ -126,7 +127,8 @@ public static > boolean foreachChild(T parent, Predicate< * @param includeSelf true if the consumer should also consume the parent * @return the first resulting value of the consumer or null of it always returned null */ - public static , V> @Nullable V foreachChildWithResult(T parent, Function consumer, boolean includeSelf) { + public static , V> @Nullable V foreachChildWithResult(T parent, Function consumer, + boolean includeSelf) { if (includeSelf) { V t = consumer.apply(parent); if (t != null) return t; @@ -332,7 +334,8 @@ public static , R extends ITreeNode> R findParent(T pa @Nullable @SuppressWarnings("unchecked") - public static , R extends ITreeNode> R findParent(T parent, Class type, @Nullable Predicate test) { + public static , R extends ITreeNode> R findParent(T parent, Class type, + @Nullable Predicate test) { while (parent != null) { if (type.isAssignableFrom(parent.getClass()) && (test == null || test.test((R) parent))) { return (R) parent; diff --git a/src/main/java/brachy/modularui/utils/handlers/fluid/CycleFluidEntryHandler.java b/src/main/java/brachy/modularui/utils/handlers/fluid/CycleFluidEntryHandler.java index bf44e684..01abe5a5 100644 --- a/src/main/java/brachy/modularui/utils/handlers/fluid/CycleFluidEntryHandler.java +++ b/src/main/java/brachy/modularui/utils/handlers/fluid/CycleFluidEntryHandler.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault diff --git a/src/main/java/brachy/modularui/utils/handlers/item/CycleItemEntryHandler.java b/src/main/java/brachy/modularui/utils/handlers/item/CycleItemEntryHandler.java index 126febbd..55a6b7ad 100644 --- a/src/main/java/brachy/modularui/utils/handlers/item/CycleItemEntryHandler.java +++ b/src/main/java/brachy/modularui/utils/handlers/item/CycleItemEntryHandler.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault diff --git a/src/main/java/brachy/modularui/utils/math/DAM.java b/src/main/java/brachy/modularui/utils/math/DAM.java index a31beb97..3ece585e 100644 --- a/src/main/java/brachy/modularui/utils/math/DAM.java +++ b/src/main/java/brachy/modularui/utils/math/DAM.java @@ -272,7 +272,7 @@ public static double[] pow(double[] src, double op, double @Nullable [] res) { public static double[] diff(double[] src) { if (src.length < 2) return EMPTY; - if (src.length == 2) return new double[]{src[1] - src[0]}; + if (src.length == 2) return new double[] { src[1] - src[0] }; double[] res = new double[src.length - 1]; for (int i = 0; i < res.length; i++) { res[i] = src[i + 1] - src[i]; diff --git a/src/main/java/brachy/modularui/utils/math/FAM.java b/src/main/java/brachy/modularui/utils/math/FAM.java index 8169a7f7..543899bd 100644 --- a/src/main/java/brachy/modularui/utils/math/FAM.java +++ b/src/main/java/brachy/modularui/utils/math/FAM.java @@ -213,7 +213,7 @@ public static float[] div(float[] src, float[] op, float @Nullable [] res) { public static float[] diff(float[] src) { if (src.length < 2) return EMPTY; - if (src.length == 2) return new float[]{src[1] - src[0]}; + if (src.length == 2) return new float[] { src[1] - src[0] }; float[] res = new float[src.length - 1]; for (int i = 0; i < res.length; i++) { res[i] = src[i + 1] - src[i]; diff --git a/src/main/java/brachy/modularui/utils/math/MathUtils.java b/src/main/java/brachy/modularui/utils/math/MathUtils.java index 760460c3..7ef9c7e9 100644 --- a/src/main/java/brachy/modularui/utils/math/MathUtils.java +++ b/src/main/java/brachy/modularui/utils/math/MathUtils.java @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; + import javax.annotation.ParametersAreNonnullByDefault; @MethodsReturnNonnullByDefault @@ -174,7 +175,7 @@ public static int gridRows(int count, int size, int width) { return count <= 0 ? 1 : (int) Math.ceil(x); } - public static int min(int @Nullable ... values) { + public static int min(int @Nullable... values) { if (values == null || values.length == 0) throw new IllegalArgumentException(); if (values.length == 1) return values[0]; if (values.length == 2) return Math.min(values[0], values[1]); @@ -187,7 +188,7 @@ public static int min(int @Nullable ... values) { return min; } - public static int max(int @Nullable ... values) { + public static int max(int @Nullable... values) { if (values == null || values.length == 0) throw new IllegalArgumentException(); if (values.length == 1) return values[0]; if (values.length == 2) return Math.max(values[0], values[1]); diff --git a/src/main/java/brachy/modularui/utils/math/NumberFormat.java b/src/main/java/brachy/modularui/utils/math/NumberFormat.java index 3b46cfe3..106a83c2 100644 --- a/src/main/java/brachy/modularui/utils/math/NumberFormat.java +++ b/src/main/java/brachy/modularui/utils/math/NumberFormat.java @@ -35,9 +35,11 @@ public class NumberFormat { .build(); public static Params params(DecimalFormat format, int maxLength, boolean considerOnlyDecimalsForLength, - boolean considerDecimalSeparatorForLength, boolean considerMinusForLength, boolean considerSuffixForLength, + boolean considerDecimalSeparatorForLength, boolean considerMinusForLength, + boolean considerSuffixForLength, boolean spaceAfterNumber) { - return new Params(format, maxLength, considerOnlyDecimalsForLength, considerDecimalSeparatorForLength, considerMinusForLength, considerSuffixForLength, spaceAfterNumber); + return new Params(format, maxLength, considerOnlyDecimalsForLength, considerDecimalSeparatorForLength, + considerMinusForLength, considerSuffixForLength, spaceAfterNumber); } public static ParamsBuilder paramsBuilder() { @@ -45,50 +47,52 @@ public static ParamsBuilder paramsBuilder() { } public record Params(DecimalFormat format, int maxLength, boolean considerOnlyDecimalsForLength, - boolean considerDecimalSeparatorForLength, boolean considerMinusForLength, boolean considerSuffixForLength, + boolean considerDecimalSeparatorForLength, boolean considerMinusForLength, + boolean considerSuffixForLength, boolean spaceAfterNumber) { - public Params(DecimalFormat format, int maxLength, boolean considerOnlyDecimalsForLength, boolean considerDecimalSeparatorForLength, - boolean considerMinusForLength, boolean considerSuffixForLength, boolean spaceAfterNumber) { - this.format = format; - this.maxLength = maxLength; - this.considerOnlyDecimalsForLength = considerOnlyDecimalsForLength; - this.considerDecimalSeparatorForLength = considerDecimalSeparatorForLength; - this.considerMinusForLength = considerMinusForLength; - this.considerSuffixForLength = considerSuffixForLength; - this.spaceAfterNumber = spaceAfterNumber; - if (!this.considerOnlyDecimalsForLength && this.maxLength < 1) { - throw new IllegalArgumentException("Max length must be at least 1 character"); - } + public Params(DecimalFormat format, int maxLength, boolean considerOnlyDecimalsForLength, + boolean considerDecimalSeparatorForLength, + boolean considerMinusForLength, boolean considerSuffixForLength, boolean spaceAfterNumber) { + this.format = format; + this.maxLength = maxLength; + this.considerOnlyDecimalsForLength = considerOnlyDecimalsForLength; + this.considerDecimalSeparatorForLength = considerDecimalSeparatorForLength; + this.considerMinusForLength = considerMinusForLength; + this.considerSuffixForLength = considerSuffixForLength; + this.spaceAfterNumber = spaceAfterNumber; + if (!this.considerOnlyDecimalsForLength && this.maxLength < 1) { + throw new IllegalArgumentException("Max length must be at least 1 character"); } + } - public ParamsBuilder copyToBuilder() { - DecimalFormat format = (DecimalFormat) this.format.clone(); - format.setMinimumFractionDigits(this.format.getMinimumFractionDigits()); - format.setMaximumFractionDigits(this.format.getMaximumFractionDigits()); - format.setMinimumIntegerDigits(this.format.getMinimumIntegerDigits()); - format.setMaximumIntegerDigits(this.format.getMaximumIntegerDigits()); - format.setRoundingMode(this.format.getRoundingMode()); - format.setGroupingSize(this.format.getGroupingSize()); - format.setGroupingUsed(this.format.isGroupingUsed()); - return new ParamsBuilder() - .format(format) - .maxLength(this.maxLength) - .considerOnlyDecimalsForLength(this.considerOnlyDecimalsForLength) - .considerDecimalSeparatorForLength(this.considerDecimalSeparatorForLength) - .considerMinusForLength(this.considerMinusForLength) - .considerSuffixForLength(this.considerSuffixForLength) - .spaceAfterNumber(this.spaceAfterNumber); - } + public ParamsBuilder copyToBuilder() { + DecimalFormat format = (DecimalFormat) this.format.clone(); + format.setMinimumFractionDigits(this.format.getMinimumFractionDigits()); + format.setMaximumFractionDigits(this.format.getMaximumFractionDigits()); + format.setMinimumIntegerDigits(this.format.getMinimumIntegerDigits()); + format.setMaximumIntegerDigits(this.format.getMaximumIntegerDigits()); + format.setRoundingMode(this.format.getRoundingMode()); + format.setGroupingSize(this.format.getGroupingSize()); + format.setGroupingUsed(this.format.isGroupingUsed()); + return new ParamsBuilder() + .format(format) + .maxLength(this.maxLength) + .considerOnlyDecimalsForLength(this.considerOnlyDecimalsForLength) + .considerDecimalSeparatorForLength(this.considerDecimalSeparatorForLength) + .considerMinusForLength(this.considerMinusForLength) + .considerSuffixForLength(this.considerSuffixForLength) + .spaceAfterNumber(this.spaceAfterNumber); + } - public String format(double number) { - return NumberFormat.format(number, this); - } + public String format(double number) { + return NumberFormat.format(number, this); + } - public String format(BigDecimal number) { - return NumberFormat.format(number, this); - } + public String format(BigDecimal number) { + return NumberFormat.format(number, this); } + } public static class ParamsBuilder { @@ -160,7 +164,8 @@ public ParamsBuilder spaceAfterNumber(boolean spaceAfterNumber) { } public Params build() { - return new Params(checkFormat(), this.maxLength, this.considerOnlyDecimalsForLength, this.considerDecimalSeparatorForLength, + return new Params(checkFormat(), this.maxLength, this.considerOnlyDecimalsForLength, + this.considerDecimalSeparatorForLength, this.considerMinusForLength, this.considerSuffixForLength, spaceAfterNumber); } } @@ -224,7 +229,8 @@ public static SIPrefix findBestPrefix(double number) { public static SIPrefix findBestPrefix(BigDecimal number) { number = number.abs(); - if ((number.compareTo(BigDecimal.ONE) >= 0 && number.compareTo(TEN_THOUSAND) < 0) || number.equals(BigDecimal.ZERO)) { + if ((number.compareTo(BigDecimal.ONE) >= 0 && number.compareTo(TEN_THOUSAND) < 0) || + number.equals(BigDecimal.ZERO)) { return SIPrefix.One; } SIPrefix[] high = SIPrefix.HIGH; diff --git a/src/main/java/brachy/modularui/utils/math/ParseResult.java b/src/main/java/brachy/modularui/utils/math/ParseResult.java index e72c5c32..c32b530a 100644 --- a/src/main/java/brachy/modularui/utils/math/ParseResult.java +++ b/src/main/java/brachy/modularui/utils/math/ParseResult.java @@ -50,6 +50,7 @@ public String getErrorMessage() { return isFailure() ? String.format("%s for Token %s at %d:%d", this.error.getMessage(), this.error.getTokenString(), - this.error.getStartPosition(), this.error.getEndPosition()) : null; + this.error.getStartPosition(), this.error.getEndPosition()) : + null; } } diff --git a/src/main/java/brachy/modularui/utils/math/PostfixPercentOperator.java b/src/main/java/brachy/modularui/utils/math/PostfixPercentOperator.java index db3cd4be..9d111e64 100644 --- a/src/main/java/brachy/modularui/utils/math/PostfixPercentOperator.java +++ b/src/main/java/brachy/modularui/utils/math/PostfixPercentOperator.java @@ -16,7 +16,8 @@ public class PostfixPercentOperator extends AbstractOperator { public static final BigDecimal HUNDRED = new BigDecimal(100); @Override - public EvaluationValue evaluate(Expression expression, Token operatorToken, EvaluationValue... operands) throws EvaluationException { + public EvaluationValue evaluate(Expression expression, Token operatorToken, + EvaluationValue... operands) throws EvaluationException { EvaluationValue operand = operands[0]; if (operand.isNumberValue()) { diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/CodecRegistry.java b/src/main/java/brachy/modularui/utils/serialization/codec/CodecRegistry.java index be0b938c..3a51d597 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/CodecRegistry.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/CodecRegistry.java @@ -2,7 +2,6 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; - import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/CodecUtil.java b/src/main/java/brachy/modularui/utils/serialization/codec/CodecUtil.java index a183ceff..4939604c 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/CodecUtil.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/CodecUtil.java @@ -10,7 +10,6 @@ import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; import com.mojang.serialization.codecs.KeyDispatchCodec; - import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import java.util.ArrayList; @@ -51,6 +50,7 @@ public static Codec nullCodec(Supplier decoder) { public static Codec nullCodec(Supplier decoder, Predicate nullTester) { return new Codec<>() { + @Override public DataResult> decode(DynamicOps ops, T input) { if (input == null || Objects.equals(ops.empty(), input)) { @@ -87,6 +87,7 @@ public static Decoder chainedDecoder(Decoder... decoder) { if (decoder == null || decoder.length == 0) throw new NullPointerException(); if (decoder.length == 1) return decoder[0]; return new Decoder<>() { + @Override public DataResult> decode(DynamicOps ops, T input) { StringBuilder message = new StringBuilder(); @@ -106,6 +107,7 @@ public static Encoder chainedEncoder(Encoder... encoder) { if (encoder == null || encoder.length == 0) throw new NullPointerException(); if (encoder.length == 1) return encoder[0]; return new Encoder<>() { + @Override public DataResult encode(A input, DynamicOps ops, T prefix) { StringBuilder message = new StringBuilder(); @@ -126,6 +128,7 @@ public static MapCodec chainedMapCodec(MapCodec... codecs) { if (codecs.length == 1) return codecs[0]; // I hate this return new MapCodec<>() { + @Override public Stream keys(DynamicOps ops) { Stream s = Stream.empty(); @@ -169,13 +172,15 @@ public static Decoder optionsDecoder(Decoder... codecs) { if (codecs == null || codecs.length == 0) throw new NullPointerException(); if (codecs.length == 1) return (Codec) codecs[0]; return new Decoder<>() { + @Override public DataResult> decode(DynamicOps ops, T input) { StringBuilder message = new StringBuilder(); for (var codec : codecs) { var d = codec.decode(ops, input); var res = d.result(); - if (res.isPresent()) return DataResult.success(new Pair<>(res.get().getFirst(), res.get().getSecond())); + if (res.isPresent()) + return DataResult.success(new Pair<>(res.get().getFirst(), res.get().getSecond())); message.append(d.error().orElseThrow().message()).append("; "); } return DataResult.error(() -> message.substring(0, message.length() - 2)); @@ -195,8 +200,8 @@ public static Codec codecOf(Encoder encoder, Decoder... decoder) { return Codec.of(encoder, chainedDecoder(decoder)); } - public static MapCodec dispatchNullable(Codec keyCodec, Function type, Function> codec) { + public static MapCodec dispatchNullable(Codec keyCodec, Function type, + Function> codec) { return dispatchNullable("type", keyCodec, type, codec); } @@ -220,20 +225,22 @@ public static MapCodec partialDispatchMap(String key, Codec keyCode Function> type, Function>> codec) { return new KeyDispatchCodec<>(key, keyCodec, type, codec); - } public static Encoder checked(Encoder codec, Predicate test) { return new Encoder<>() { + @Override public DataResult encode(A input, DynamicOps ops, T prefix) { - return test.test(input) ? codec.encode(input, ops, prefix) : DataResult.error(() -> "Codec " + codec + " can't handle value " + input); + return test.test(input) ? codec.encode(input, ops, prefix) : + DataResult.error(() -> "Codec " + codec + " can't handle value " + input); } }; } public static Codec checkedEncoder(Codec codec, Predicate test) { return new Codec<>() { + @Override public DataResult> decode(DynamicOps ops, T input) { return codec.decode(ops, input); @@ -241,7 +248,8 @@ public DataResult> decode(DynamicOps ops, T input) { @Override public DataResult encode(A input, DynamicOps ops, T prefix) { - return test.test(input) ? codec.encode(input, ops, prefix) : DataResult.error(() -> "Codec " + codec + " can't handle value " + input); + return test.test(input) ? codec.encode(input, ops, prefix) : + DataResult.error(() -> "Codec " + codec + " can't handle value " + input); } @Override diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/Field.java b/src/main/java/brachy/modularui/utils/serialization/codec/Field.java index 4a761a0b..1717f206 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/Field.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/Field.java @@ -6,7 +6,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; - import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -19,12 +18,18 @@ @Accessors(fluent = true, chain = true) public final class Field { - @Getter private final String name; - @Getter private final FieldWriter fieldWriter; - @Getter private final FieldReader fieldReader; - @Getter private final Codec codec; - @Getter private final Supplier defaultSupplier; - @Getter private final boolean dynamicSupplier; + @Getter + private final String name; + @Getter + private final FieldWriter fieldWriter; + @Getter + private final FieldReader fieldReader; + @Getter + private final Codec codec; + @Getter + private final Supplier defaultSupplier; + @Getter + private final boolean dynamicSupplier; @Getter @Setter private String[] altNames; @@ -35,7 +40,8 @@ public final class Field { @Setter private boolean writeDefault = true; - Field(String name, FieldWriter fieldWriter, FieldReader fieldReader, Codec codec, Supplier defaultSupplier, boolean dynamicSupplier) { + Field(String name, FieldWriter fieldWriter, FieldReader fieldReader, Codec codec, + Supplier defaultSupplier, boolean dynamicSupplier) { this.name = name; this.fieldWriter = fieldWriter; this.fieldReader = fieldReader; @@ -70,13 +76,15 @@ public void encode(T holder, DynamicOps ops, RecordBuilder map) { V value = this.fieldReader.readField(holder); if (isUnencodable()) { if (!isEmpty(value)) { - map.withErrorsFrom(DataResult.error(() -> String.format("Field '%s' is unencodeable, but the value is not empty", this.name))); + map.withErrorsFrom(DataResult.error( + () -> String.format("Field '%s' is unencodeable, but the value is not empty", this.name))); } return; } if (value == null) { if (!hasDefault()) { - map.withErrorsFrom(DataResult.error(() -> String.format("Field '%s' is not optional, but is trying to encode a null value", this.name))); + map.withErrorsFrom(DataResult.error(() -> String + .format("Field '%s' is not optional, but is trying to encode a null value", this.name))); return; } if (this.encodeWhen == EncodeWhen.ALWAYS) { @@ -108,7 +116,8 @@ public boolean shouldEncode(V value) { if (element == null) { if (this.encodeWhen == EncodeWhen.NEVER || !this.writeDefault) return null; if (!hasDefault()) { - return null;//isUnencodable() ? null : String.format("Field '%s' has no value and is not optional", this.name); + return null;// isUnencodable() ? null : String.format("Field '%s' has no value and is not optional", + // this.name); } this.fieldWriter.writeField(holder, getModifiableDefault()); return null; @@ -153,7 +162,9 @@ private DataResult decode(T holder, DynamicOps ops, J element, Mutable value = res.get(); } if (value == null) { - return DataResult.error(() -> String.format("Field '%s' is unable to decode instance and the holder has no default value and this property has no default value", this.name)); + return DataResult.error(() -> String.format( + "Field '%s' is unable to decode instance and the holder has no default value and this property has no default value", + this.name)); } } return decoder.decode(ops, dRes.get(), value); @@ -172,7 +183,9 @@ private DataResult decode(T holder, DynamicOps ops, J element, Mutable value = res.get(); } if (value == null) { - return DataResult.error(() -> String.format("Field '%s' is unable to decode instance and the holder has no default value and this property has no default value", this.name)); + return DataResult.error(() -> String.format( + "Field '%s' is unable to decode instance and the holder has no default value and this property has no default value", + this.name)); } } return decoder.parse(ops, element, value); @@ -202,7 +215,8 @@ public Field copyToType(Function converter) { public Field copyToType(String newName, Function converter) { var field = new Field(newName, (o, v) -> this.fieldWriter.writeField(converter.apply(o), v), - (o) -> this.fieldReader.readField(converter.apply(o)), this.codec, this.defaultSupplier, this.dynamicSupplier); + (o) -> this.fieldReader.readField(converter.apply(o)), this.codec, this.defaultSupplier, + this.dynamicSupplier); field.altNames(this.altNames); field.encodeWhen(this.encodeWhen); field.writeDefault(this.writeDefault); @@ -211,7 +225,8 @@ public Field copyToType(String newName, Function converter) { public Field copy(String newName) { if (this.name.equals(newName)) return this; - var field = new Field<>(newName, this.fieldWriter, this.fieldReader, this.codec, this.defaultSupplier, this.dynamicSupplier); + var field = new Field<>(newName, this.fieldWriter, this.fieldReader, this.codec, this.defaultSupplier, + this.dynamicSupplier); field.altNames(this.altNames); field.encodeWhen(this.encodeWhen); field.writeDefault(this.writeDefault); diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/MutableCodec.java b/src/main/java/brachy/modularui/utils/serialization/codec/MutableCodec.java index 94c04a1b..e31a2264 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/MutableCodec.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/MutableCodec.java @@ -1,13 +1,12 @@ package brachy.modularui.utils.serialization.codec; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - /** * A {@link Codec} that can decode mutable field to an existing instance. * diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/MutableObjectCodec.java b/src/main/java/brachy/modularui/utils/serialization/codec/MutableObjectCodec.java index ca55d10e..53b77430 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/MutableObjectCodec.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/MutableObjectCodec.java @@ -3,6 +3,8 @@ import brachy.modularui.api.drawable.IDrawable; import brachy.modularui.api.widget.IWidget; +import com.google.common.base.CaseFormat; +import com.google.gson.JsonObject; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; @@ -10,9 +12,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; - -import com.google.common.base.CaseFormat; -import com.google.gson.JsonObject; import it.unimi.dsi.fastutil.objects.Object2ReferenceLinkedOpenHashMap; import lombok.Getter; import lombok.experimental.Accessors; @@ -31,7 +30,8 @@ import java.util.stream.Stream; /** - * This can handle (de)serialization and conversion to various data types, editing properties, copying properties and applying default + * This can handle (de)serialization and conversion to various data types, editing properties, copying properties and + * applying default * properties to (partially) mutable objects. * * @param type of property @@ -43,7 +43,8 @@ public class MutableObjectCodec extends MapCodec implements MutableMapDeco private final InstanceMapDecoder instanceDecoder; private final UnaryOperator baseCopy; private final Codec wrapped; - @Getter private final MutableCodecCodec mutableCodec = new MutableCodecCodec<>(this); + @Getter + private final MutableCodecCodec mutableCodec = new MutableCodecCodec<>(this); private MutableObjectCodec(List> fields, InstanceMapDecoder instanceDecoder, UnaryOperator baseCopy, Codec wrapped) { @@ -135,7 +136,8 @@ public static Builder drawableBuilder(Class type, St return new DrawableBuilder<>(typeName); } - public static Builder drawableBuilder(String typeName, InstanceMapDecoder instanceDecoder) { + public static Builder drawableBuilder(String typeName, + InstanceMapDecoder instanceDecoder) { return new DrawableBuilder(typeName).instanceDecoder(instanceDecoder); } @@ -143,7 +145,8 @@ public static Builder drawableBuilder(String typeName, return new DrawableBuilder(typeName).instance(instance); } - public static Builder drawableBuilder(Class type, InstanceMapDecoder instanceDecoder) { + public static Builder drawableBuilder(Class type, + InstanceMapDecoder instanceDecoder) { return new DrawableBuilder(type.getSimpleName()).instanceDecoder(instanceDecoder); } @@ -203,7 +206,8 @@ public DataResult decode(DynamicOps ops, MapLike input, T instance) if (error != null) errors.add(error); }); if (!errors.isEmpty()) { - return DataResult.error(() -> String.format("Errors while decoding object of type '%s': %s", instance.getClass().getSimpleName(), errors)); + return DataResult.error(() -> String.format("Errors while decoding object of type '%s': %s", + instance.getClass().getSimpleName(), errors)); } return DataResult.success(instance); } @@ -248,7 +252,8 @@ public DataResult decodeInstance(DynamicOps ops, MapLike input) { return this.wrapped.parse(ops, ops.createMap(input.entries())); } if (this.instanceDecoder != null) return this.instanceDecoder.decodeInstance(ops, input); - return DataResult.error(() -> "Instance can not be created since no instance decoder or wrapped codec was provided."); + return DataResult + .error(() -> "Instance can not be created since no instance decoder or wrapped codec was provided."); } public String convertToString(T instance, boolean pretty) { @@ -281,12 +286,14 @@ public record MutableCodecCodec(MutableObjectCodec codec) implements Mutab @Override public DataResult> decode(DynamicOps ops, T input, A instance) { - return CodecUtil.ifMap(ops, input, map -> this.codec.decode(ops, map, instance)).map(t -> new Pair<>(t, input)); + return CodecUtil.ifMap(ops, input, map -> this.codec.decode(ops, map, instance)) + .map(t -> new Pair<>(t, input)); } @Override public DataResult> decodeInstance(DynamicOps ops, T input) { - return CodecUtil.ifMap(ops, input, map -> this.codec.decodeInstance(ops, map)).map(t -> new Pair<>(t, input)); + return CodecUtil.ifMap(ops, input, map -> this.codec.decodeInstance(ops, map)) + .map(t -> new Pair<>(t, input)); } @Override @@ -308,7 +315,8 @@ public static class Builder { /** * Sets the instance decoder. This is needed when parsing from JSON. The decoder should create a new instance - * and decode any necessary data for that. If the object has a no-arg constructor, then {@link #instance(Supplier)} should be used. + * and decode any necessary data for that. If the object has a no-arg constructor, then + * {@link #instance(Supplier)} should be used. * If this setter is used, then {@link #baseCopy(UnaryOperator)} must also be used. */ public Builder instanceDecoder(InstanceMapDecoder instanceDecoder) { @@ -317,10 +325,12 @@ public Builder instanceDecoder(InstanceMapDecoder instanceDecoder) { } /** - * Sets the instance supplier. This is needed when parsing from JSON and for copying. This MUST always return a new instance. + * Sets the instance supplier. This is needed when parsing from JSON and for copying. This MUST always return a + * new instance. */ public Builder instance(Supplier instance) { return instanceDecoder(new InstanceMapDecoder() { + @Override public DataResult decodeInstance(DynamicOps ops, MapLike input) { return DataResult.success(instance.get()); @@ -329,7 +339,8 @@ public DataResult decodeInstance(DynamicOps ops, MapLike input) { } /** - * Sets the base copy function. This creates a new instance, but without setting any mutable properties. This MUST always return + * Sets the base copy function. This creates a new instance, but without setting any mutable properties. This + * MUST always return * a new instance. If the object has a no-arg constructor, then {@link #instance(Supplier)} should be used. */ public Builder baseCopy(UnaryOperator baseCopy) { @@ -342,8 +353,10 @@ public Builder baseCopy(UnaryOperator baseCopy) { } /** - * When this object is encoded and decoded this codec will be called first. This is useful when this object is based on another - * object which already has a codec. Example: {@link brachy.modularui.drawable.text.ModularComponent#CODEC ModularComponent.CODEC} + * When this object is encoded and decoded this codec will be called first. This is useful when this object is + * based on another + * object which already has a codec. Example: {@link brachy.modularui.drawable.text.ModularComponent#CODEC + * ModularComponent.CODEC} */ public Builder wrapped(Codec codec) { this.wrapped = codec; @@ -395,14 +408,16 @@ public

Builder addFieldOf(MutableObjectCodec

parent, Function co return addFieldOf(parent, converter, fieldName, fieldName); } - public

Builder addFieldOf(MutableObjectCodec

parent, Function converter, String fieldName, String newName) { + public

Builder addFieldOf(MutableObjectCodec

parent, Function converter, String fieldName, + String newName) { parent.findField(fieldName).ifPresentOrElse(f -> addField(f.copyToType(newName, converter)), () -> { throw new IllegalArgumentException("MutableObjectCodec does not have field '" + fieldName + "'."); }); return this; } - public Builder add(String name, FieldWriter fieldWriter, FieldReader fieldReader, MapCodec codec) { + public Builder add(String name, FieldWriter fieldWriter, FieldReader fieldReader, + MapCodec codec) { return addDynOpt(name, fieldWriter, fieldReader, codec.codec(), null); } @@ -411,7 +426,8 @@ public Builder add(String name, FieldWriter fieldWriter, FieldReade * * @see #addDynOpt(String, FieldWriter, FieldReader, Codec, Supplier) */ - public Builder add(String name, FieldWriter fieldWriter, FieldReader fieldReader, Codec codec) { + public Builder add(String name, FieldWriter fieldWriter, FieldReader fieldReader, + Codec codec) { return addDynOpt(name, fieldWriter, fieldReader, codec, null); } @@ -423,7 +439,8 @@ public Builder addOpt(String name, FieldWriter fieldWriter, FieldRe /** * Adds a new optional, mutable property with a const default value. * - * @param defValue default value, if this is null, the default value is null and this property is still considered optional + * @param defValue default value, if this is null, the default value is null and this property is still + * considered optional * @see #addDynOpt(String, FieldWriter, FieldReader, Codec, Supplier) */ public Builder addOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, @@ -434,7 +451,8 @@ public Builder addOpt(String name, FieldWriter fieldWriter, FieldRe return addField(new Field<>(name, fieldWriter, fieldReader, codec, () -> defValue, false)); } - public Builder addDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, MapCodec codec, + public Builder addDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, + MapCodec codec, @Nullable Supplier defaultSupplier) { return addDynOpt(name, fieldWriter, fieldReader, codec.codec(), defaultSupplier); } @@ -451,7 +469,8 @@ public Builder addDynOpt(String name, FieldWriter fieldWriter, Fiel * @return this * @throws NullPointerException if name, fieldEncoder or fieldDecoder is null */ - public Builder addDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, Codec codec, + public Builder addDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, + Codec codec, @Nullable Supplier defaultSupplier) { Objects.requireNonNull(name, "Name of field must not be null!"); Objects.requireNonNull(fieldWriter, "Field encoder must not be null!"); @@ -460,11 +479,13 @@ public Builder addDynOpt(String name, FieldWriter fieldWriter, Fiel .encodeWhen(Field.EncodeWhen.ALWAYS)); } - public Builder addUnencodable(String name, FieldWriter fieldWriter, FieldReader fieldReader) { + public Builder addUnencodable(String name, FieldWriter fieldWriter, + FieldReader fieldReader) { return add(name, fieldWriter, fieldReader, (Codec) null); } - public Builder addUnencodableOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, + public Builder addUnencodableOpt(String name, FieldWriter fieldWriter, + FieldReader fieldReader, @Nullable V defaultValue) { return addOpt(name, fieldWriter, fieldReader, (Codec) null, defaultValue); } @@ -476,7 +497,8 @@ public Builder addUnencodableOpt(String name, FieldWriter fieldWrit * * @see #addDynOpt(String, FieldWriter, FieldReader, Codec, Supplier) */ - public Builder addUnencodableDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, + public Builder addUnencodableDynOpt(String name, FieldWriter fieldWriter, + FieldReader fieldReader, @Nullable Supplier defaultSupplier) { return addDynOpt(name, fieldWriter, fieldReader, (Codec) null, defaultSupplier); } @@ -517,7 +539,8 @@ private Builder doOnField(Consumer> consumer) { } public MutableObjectCodec build() { - var c = new MutableObjectCodec<>(new ArrayList<>(this.fields.values()), this.instanceDecoder, this.baseCopy, this.wrapped); + var c = new MutableObjectCodec<>(new ArrayList<>(this.fields.values()), this.instanceDecoder, this.baseCopy, + this.wrapped); if (this.registry != null) { this.registry.register(c, this.names); } diff --git a/src/main/java/brachy/modularui/utils/serialization/json/JsonHelper.java b/src/main/java/brachy/modularui/utils/serialization/json/JsonHelper.java index 95da9a07..c41bc035 100755 --- a/src/main/java/brachy/modularui/utils/serialization/json/JsonHelper.java +++ b/src/main/java/brachy/modularui/utils/serialization/json/JsonHelper.java @@ -3,16 +3,15 @@ import brachy.modularui.ModularUI; import brachy.modularui.utils.serialization.codec.MutableCodec; -import com.mojang.serialization.Decoder; -import com.mojang.serialization.Encoder; -import com.mojang.serialization.JsonOps; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.mojang.serialization.Decoder; +import com.mojang.serialization.Encoder; +import com.mojang.serialization.JsonOps; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -53,7 +52,7 @@ public static T deserializeWithFallback(JsonObject json, JsonObject fallback return t != null ? t : deserialize(fallback, clazz, defaultValue, keys); } - public static float getFloat(JsonObject json, float defaultValue, String @NotNull ... keys) { + public static float getFloat(JsonObject json, float defaultValue, String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -67,7 +66,7 @@ public static float getFloat(JsonObject json, float defaultValue, String @NotNul return defaultValue; } - public static int getInt(JsonObject json, int defaultValue, String @NotNull ... keys) { + public static int getInt(JsonObject json, int defaultValue, String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -82,12 +81,12 @@ public static int getInt(JsonObject json, int defaultValue, String @NotNull ... } public static int getIntWithFallback(JsonObject json, JsonObject fallback, int defaultValue, - String @NotNull ... keys) { + String @NotNull... keys) { Integer i = getBoxedInt(json, null, keys); return i != null ? i : getInt(fallback, defaultValue, keys); } - public static boolean getBoolean(JsonObject json, boolean defaultValue, String @NotNull ... keys) { + public static boolean getBoolean(JsonObject json, boolean defaultValue, String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -102,12 +101,12 @@ public static boolean getBoolean(JsonObject json, boolean defaultValue, String @ } public static boolean getBoolWithFallback(JsonObject json, JsonObject fallback, boolean defaultValue, - String @NotNull ... keys) { + String @NotNull... keys) { Boolean i = getBoxedBool(json, null, keys); return i != null ? i : getBoolean(fallback, defaultValue, keys); } - public static String getString(JsonObject json, String defaultValue, String @NotNull ... keys) { + public static String getString(JsonObject json, String defaultValue, String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -119,7 +118,7 @@ public static String getString(JsonObject json, String defaultValue, String @Not } public static T getObject(JsonObject json, T defaultValue, Function factory, - String @NotNull ... keys) { + String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -134,7 +133,7 @@ public static T getObject(JsonObject json, T defaultValue, Function T getElement(JsonObject json, T defaultValue, Function factory, - String @NotNull ... keys) { + String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -145,7 +144,7 @@ public static T getElement(JsonObject json, T defaultValue, Function T getElement(JsonObject json, T defaultValue, Function T getElement(JsonObject json, T defaultValue, Function ITEM_STACK = makeAdapter(FriendlyByteBuf::readItem, FriendlyByteBuf::writeItem, ItemStack::matches); - public static final IByteBufAdapter FLUID_STACK = makeMemberAdapter(FluidStack::readFromPacket, FluidStack::writeToPacket, FluidStack::isFluidStackIdentical); - public static final IByteBufAdapter NBT = makeAdapter(FriendlyByteBuf::readNbt, FriendlyByteBuf::writeNbt, null); - public static final IByteBufAdapter STRING = makeAdapter(NetworkUtils::readStringSafe, NetworkUtils::writeStringSafe, null); - public static final IByteBufAdapter BYTE_BUF = makeAdapter(NetworkUtils::readByteBuf, NetworkUtils::writeByteBuf, null); - public static final IByteBufAdapter FRIENDLY_BYTE_BUF = makeAdapter(NetworkUtils::readFriendlyByteBuf, NetworkUtils::writeByteBuf, null); - - public static final IByteBufAdapter INT = makeAdapter(FriendlyByteBuf::readInt, FriendlyByteBuf::writeInt, null); - public static final IByteBufAdapter LONG = makeAdapter(FriendlyByteBuf::readLong, FriendlyByteBuf::writeLong, null); - public static final IByteBufAdapter FLOAT = makeAdapter(FriendlyByteBuf::readFloat, FriendlyByteBuf::writeFloat, null); - public static final IByteBufAdapter DOUBLE = makeAdapter(FriendlyByteBuf::readDouble, FriendlyByteBuf::writeDouble, null); - public static final IByteBufAdapter BOOL = makeAdapter(FriendlyByteBuf::readBoolean, FriendlyByteBuf::writeBoolean, null); - public static final IByteBufAdapter BYTE = makeAdapter(FriendlyByteBuf::readByte, (buffer, b) -> buffer.writeByte(b), null); - public static final IByteBufAdapter SHORT = makeAdapter(FriendlyByteBuf::readShort, (buffer, b) -> buffer.writeShort(b), null); - public static final IByteBufAdapter CHAR = makeAdapter(FriendlyByteBuf::readChar, (buffer, b) -> buffer.writeChar(b), null); - - public static final IByteBufAdapter BLOCKSTATE = makeAdapterFromCodec(BlockState.CODEC, BlockState::equals); + public static final IByteBufAdapter ITEM_STACK = makeAdapter(FriendlyByteBuf::readItem, + FriendlyByteBuf::writeItem, ItemStack::matches); + public static final IByteBufAdapter FLUID_STACK = makeMemberAdapter(FluidStack::readFromPacket, + FluidStack::writeToPacket, FluidStack::isFluidStackIdentical); + public static final IByteBufAdapter NBT = makeAdapter(FriendlyByteBuf::readNbt, + FriendlyByteBuf::writeNbt, null); + public static final IByteBufAdapter STRING = makeAdapter(NetworkUtils::readStringSafe, + NetworkUtils::writeStringSafe, null); + public static final IByteBufAdapter BYTE_BUF = makeAdapter(NetworkUtils::readByteBuf, + NetworkUtils::writeByteBuf, null); + public static final IByteBufAdapter FRIENDLY_BYTE_BUF = makeAdapter( + NetworkUtils::readFriendlyByteBuf, NetworkUtils::writeByteBuf, null); + + public static final IByteBufAdapter INT = makeAdapter(FriendlyByteBuf::readInt, FriendlyByteBuf::writeInt, + null); + public static final IByteBufAdapter LONG = makeAdapter(FriendlyByteBuf::readLong, FriendlyByteBuf::writeLong, + null); + public static final IByteBufAdapter FLOAT = makeAdapter(FriendlyByteBuf::readFloat, + FriendlyByteBuf::writeFloat, null); + public static final IByteBufAdapter DOUBLE = makeAdapter(FriendlyByteBuf::readDouble, + FriendlyByteBuf::writeDouble, null); + public static final IByteBufAdapter BOOL = makeAdapter(FriendlyByteBuf::readBoolean, + FriendlyByteBuf::writeBoolean, null); + public static final IByteBufAdapter BYTE = makeAdapter(FriendlyByteBuf::readByte, + (buffer, b) -> buffer.writeByte(b), null); + public static final IByteBufAdapter SHORT = makeAdapter(FriendlyByteBuf::readShort, + (buffer, b) -> buffer.writeShort(b), null); + public static final IByteBufAdapter CHAR = makeAdapter(FriendlyByteBuf::readChar, + (buffer, b) -> buffer.writeChar(b), null); + + public static final IByteBufAdapter BLOCKSTATE = makeAdapterFromCodec(BlockState.CODEC, + BlockState::equals); public static final IByteBufAdapter BLOCKPOS = makeAdapterFromCodec(BlockPos.CODEC, BlockPos::equals); - public static final IByteBufAdapter GLOBAL_POS = makeAdapterFromCodec(GlobalPos.CODEC, GlobalPos::equals); - public static final IByteBufAdapter RESOURCE_LOCATION = makeAdapterFromCodec(ResourceLocation.CODEC, ResourceLocation::equals); - public static final IByteBufAdapter UUID = makeAdapter(FriendlyByteBuf::readUUID, FriendlyByteBuf::writeUUID, java.util.UUID::equals); - public static final IByteBufAdapter COMPONENT = makeAdapter(FriendlyByteBuf::readComponent, FriendlyByteBuf::writeComponent, Component::equals); + public static final IByteBufAdapter GLOBAL_POS = makeAdapterFromCodec(GlobalPos.CODEC, + GlobalPos::equals); + public static final IByteBufAdapter RESOURCE_LOCATION = makeAdapterFromCodec( + ResourceLocation.CODEC, ResourceLocation::equals); + public static final IByteBufAdapter UUID = makeAdapter(FriendlyByteBuf::readUUID, FriendlyByteBuf::writeUUID, + java.util.UUID::equals); + public static final IByteBufAdapter COMPONENT = makeAdapter(FriendlyByteBuf::readComponent, + FriendlyByteBuf::writeComponent, Component::equals); public static final IByteBufAdapter BYTE_ARR = new IByteBufAdapter<>() { @@ -157,7 +176,8 @@ public static IByteBufAdapter makeMemberAdapter(@NotNull IByteBufDeserial return makeAdapter(deserializer, memberSerializer.asBasic(), comparator); } - public static IByteBufAdapter makeAdapterFromCodec(@NotNull Codec codec, @NotNull EqualityTest equals) { + public static IByteBufAdapter makeAdapterFromCodec(@NotNull Codec codec, + @NotNull EqualityTest equals) { return new IByteBufAdapter<>() { @Override diff --git a/src/main/java/brachy/modularui/value/ProgressValue.java b/src/main/java/brachy/modularui/value/ProgressValue.java index cb9cdca3..27fee8d8 100644 --- a/src/main/java/brachy/modularui/value/ProgressValue.java +++ b/src/main/java/brachy/modularui/value/ProgressValue.java @@ -8,7 +8,8 @@ public class ProgressValue extends DoubleValue { - @Getter private final int duration; + @Getter + private final int duration; public ProgressValue(int duration) { super(0); diff --git a/src/main/java/brachy/modularui/value/sync/AbstractGenericSyncValue.java b/src/main/java/brachy/modularui/value/sync/AbstractGenericSyncValue.java index d6e200d1..1666be3a 100644 --- a/src/main/java/brachy/modularui/value/sync/AbstractGenericSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/AbstractGenericSyncValue.java @@ -11,7 +11,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public abstract class AbstractGenericSyncValue> extends ValueSyncHandler { +public abstract class AbstractGenericSyncValue> + extends ValueSyncHandler { private final Class type; private final Supplier getter; @@ -24,7 +25,8 @@ protected AbstractGenericSyncValue(Class type, Supplier getter, Consumer) this.cache.getClass(); } @@ -48,7 +50,8 @@ protected AbstractGenericSyncValue(Class type, @Nullable Supplier clientGe this.cache = this.getter.get(); if (type == null) { if (this.cache == null) { - throw new IllegalArgumentException("If the value class is not give, then the getter must return a non null value!"); + throw new IllegalArgumentException( + "If the value class is not give, then the getter must return a non null value!"); } type = (Class) this.cache.getClass(); } @@ -129,7 +132,8 @@ public boolean isValueOfType(Class expectedType) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. * This method forces a sync after the modification. * * @param consumer function that operates on the current cached value @@ -139,8 +143,10 @@ public void modifyValue(Consumer consumer) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. - * This method can automatically sync the cache after the modification. Be careful with potential issues when the sync arg is false. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. + * This method can automatically sync the cache after the modification. Be careful with potential issues when the + * sync arg is false. * * @param consumer function that operates on the current cached value */ diff --git a/src/main/java/brachy/modularui/value/sync/BooleanSyncValue.java b/src/main/java/brachy/modularui/value/sync/BooleanSyncValue.java index 1fc04eea..b110c0cf 100644 --- a/src/main/java/brachy/modularui/value/sync/BooleanSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/BooleanSyncValue.java @@ -14,7 +14,8 @@ import java.util.Objects; import java.util.function.BooleanSupplier; -public class BooleanSyncValue extends ValueSyncHandler implements IBoolSyncValue, IStringSyncValue { +public class BooleanSyncValue extends ValueSyncHandler + implements IBoolSyncValue, IStringSyncValue { private final BooleanSupplier getter; private final BooleanConsumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/DoubleSyncValue.java b/src/main/java/brachy/modularui/value/sync/DoubleSyncValue.java index 0f629868..4a433792 100644 --- a/src/main/java/brachy/modularui/value/sync/DoubleSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/DoubleSyncValue.java @@ -15,7 +15,8 @@ import java.util.function.DoubleConsumer; import java.util.function.DoubleSupplier; -public class DoubleSyncValue extends ValueSyncHandler implements IDoubleSyncValue, IFloatSyncValue, IStringSyncValue { +public class DoubleSyncValue extends ValueSyncHandler + implements IDoubleSyncValue, IFloatSyncValue, IStringSyncValue { private final DoubleSupplier getter; private final DoubleConsumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/DynamicLinkedSyncHandler.java b/src/main/java/brachy/modularui/value/sync/DynamicLinkedSyncHandler.java index 1b6a5c92..46f8cc82 100644 --- a/src/main/java/brachy/modularui/value/sync/DynamicLinkedSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/DynamicLinkedSyncHandler.java @@ -2,7 +2,6 @@ import brachy.modularui.api.widget.IWidget; import brachy.modularui.widget.WidgetTree; - import brachy.modularui.widgets.dynamic.IDynamicHandler; import net.minecraft.network.FriendlyByteBuf; @@ -14,13 +13,16 @@ import java.util.function.Supplier; /** - * This is a variation of {@link DynamicSyncHandler} with the difference that this is linked to a {@link ValueSyncHandler}. - * This sync handler is automatically notified, when the linked value is updated. The widget provider here has the linked sync handler as an + * This is a variation of {@link DynamicSyncHandler} with the difference that this is linked to a + * {@link ValueSyncHandler}. + * This sync handler is automatically notified, when the linked value is updated. The widget provider here has the + * linked sync handler as an * argument instead of a packet. * To use it simply pass in a registered value sync handler into the constructor and link it to a * {@link brachy.modularui.widgets.dynamic.DynamicWidget DynamicWidget}. */ -public class DynamicLinkedSyncHandler> extends SyncHandler> implements IDynamicHandler { +public class DynamicLinkedSyncHandler> extends SyncHandler> + implements IDynamicHandler { private IWidgetProvider widgetProvider; private Consumer onWidgetUpdate; @@ -103,7 +105,8 @@ private void notifyUpdate(boolean sync) { * Sets a widget creator which is called on client and server. {@link SyncHandler}s can be created here using * {@link PanelSyncManager#getOrCreateSyncHandler(String, int, Class, Supplier)}. Returning null in the function * will not update the widget. - * On client side the result is handed over to a linked {@link brachy.modularui.widgets.dynamic.DynamicWidget DynamicWidget}. + * On client side the result is handed over to a linked {@link brachy.modularui.widgets.dynamic.DynamicWidget + * DynamicWidget}. * * @param widgetProvider the widget creator function * @return this @@ -115,7 +118,8 @@ public DynamicLinkedSyncHandler widgetProvider(IWidgetProvider widgetProvi } /** - * An internal function which is used to link the {@link brachy.modularui.widgets.dynamic.DynamicWidget DynamicWidget}. + * An internal function which is used to link the {@link brachy.modularui.widgets.dynamic.DynamicWidget + * DynamicWidget}. */ @ApiStatus.Internal @Override diff --git a/src/main/java/brachy/modularui/value/sync/DynamicSyncHandler.java b/src/main/java/brachy/modularui/value/sync/DynamicSyncHandler.java index a6777461..68c8fd2a 100644 --- a/src/main/java/brachy/modularui/value/sync/DynamicSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/DynamicSyncHandler.java @@ -128,7 +128,8 @@ public DynamicSyncHandler widgetProvider(IWidgetProvider widgetProvider) { } /** - * An internal function which is used to link the {@link brachy.modularui.widgets.dynamic.DynamicWidget DynamicWidget}. + * An internal function which is used to link the {@link brachy.modularui.widgets.dynamic.DynamicWidget + * DynamicWidget}. */ @ApiStatus.Internal @Override diff --git a/src/main/java/brachy/modularui/value/sync/EnumSyncValue.java b/src/main/java/brachy/modularui/value/sync/EnumSyncValue.java index 8f74213e..0f4d4aae 100644 --- a/src/main/java/brachy/modularui/value/sync/EnumSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/EnumSyncValue.java @@ -15,7 +15,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public class EnumSyncValue> extends ValueSyncHandler> implements IEnumValue, IIntSyncValue { +public class EnumSyncValue> extends ValueSyncHandler> + implements IEnumValue, IIntSyncValue { @Getter protected final Class enumClass; diff --git a/src/main/java/brachy/modularui/value/sync/FloatSyncValue.java b/src/main/java/brachy/modularui/value/sync/FloatSyncValue.java index 3ae97ba5..87c5d6e9 100644 --- a/src/main/java/brachy/modularui/value/sync/FloatSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/FloatSyncValue.java @@ -15,7 +15,8 @@ import java.util.Objects; -public class FloatSyncValue extends ValueSyncHandler implements IFloatSyncValue, IDoubleSyncValue, IStringSyncValue { +public class FloatSyncValue extends ValueSyncHandler + implements IFloatSyncValue, IDoubleSyncValue, IStringSyncValue { private final FloatSupplier getter; private final FloatConsumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/FluidSlotSyncHandler.java b/src/main/java/brachy/modularui/value/sync/FluidSlotSyncHandler.java index 602f7d05..885cb9db 100644 --- a/src/main/java/brachy/modularui/value/sync/FluidSlotSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/FluidSlotSyncHandler.java @@ -1,8 +1,8 @@ package brachy.modularui.value.sync; +import brachy.modularui.utils.MouseData; import brachy.modularui.utils.handlers.fluid.FluidTankHandler; import brachy.modularui.utils.handlers.fluid.IMultiTankFluidHandler; -import brachy.modularui.utils.MouseData; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.sounds.SoundEvent; @@ -41,11 +41,13 @@ public class FluidSlotSyncHandler extends ValueSyncHandler - * Note that if this FluidSlotSyncHandler was constructed with only a fluid tank and no fluid handler, this field's value will be + * Note that if this FluidSlotSyncHandler was constructed with only a fluid tank and no fluid handler, this field's + * value will be * {@link #UNKNOWN_TANK_INDEX} so you should check that instead of assuming it's nonnegative (>=0). */ @Accessors(fluent = false) - @Getter private final int tankIndex; + @Getter + private final int tankIndex; @Getter @Setter private boolean canFillSlot = true, canDrainSlot = true, phantom = false; @@ -173,10 +175,12 @@ private boolean fillSlot(Player player, ItemStack currentStack, int maxAttempts, if (maxAmount <= 0) return false; boolean performedTransfer = false; for (int i = 0; i < maxAttempts; i++) { - FluidActionResult result = FluidUtil.tryEmptyContainer(currentStack, this.fluidHandler, maxAmount, null, false); + FluidActionResult result = FluidUtil.tryEmptyContainer(currentStack, this.fluidHandler, maxAmount, null, + false); ItemStack remainingStack = result.getResult(); if (!result.isSuccess() || - (currentStack.getCount() > 1 && !remainingStack.isEmpty() && !player.getInventory().add(remainingStack))) { + (currentStack.getCount() > 1 && !remainingStack.isEmpty() && + !player.getInventory().add(remainingStack))) { player.drop(remainingStack, true); break; // do not continue if we can't add resulting container into inventory } @@ -200,19 +204,23 @@ private boolean fillSlot(Player player, ItemStack currentStack, int maxAttempts, return performedTransfer; } - private boolean drainSlot(Player player, ItemStack currentStack, int maxAttempts, int maxAmount, boolean playSound) { + private boolean drainSlot(Player player, ItemStack currentStack, int maxAttempts, int maxAmount, + boolean playSound) { FluidStack currentFluid = this.fluidTank.getFluid(); if (currentFluid.isEmpty() || maxAmount <= 0) return false; boolean performedTransfer = false; for (int i = 0; i < maxAttempts; i++) { - FluidActionResult result = FluidUtil.tryFillContainer(currentStack, this.fluidHandler, maxAmount, null, false); + FluidActionResult result = FluidUtil.tryFillContainer(currentStack, this.fluidHandler, maxAmount, null, + false); ItemStack remainingStack = result.getResult(); if (!result.isSuccess() || - (currentStack.getCount() > 1 && !remainingStack.isEmpty() && !player.getInventory().add(remainingStack))) { + (currentStack.getCount() > 1 && !remainingStack.isEmpty() && + !player.getInventory().add(remainingStack))) { break; // do not continue if we can't add resulting container into inventory } - remainingStack = FluidUtil.tryFillContainer(currentStack, this.fluidHandler, maxAmount, playSound ? player : null, true).result; + remainingStack = FluidUtil.tryFillContainer(currentStack, this.fluidHandler, maxAmount, + playSound ? player : null, true).result; if (currentStack.getCount() == 1) { currentStack = remainingStack; } else { @@ -234,13 +242,15 @@ public void tryClickPhantom(MouseData mouseData) { Player player = getSyncManager().getPlayer(); ItemStack currentStack = player.containerMenu.getCarried(); FluidStack currentFluid = this.fluidTank.getFluid(); - IFluidHandlerItem fluidHandlerItem = currentStack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM, null).resolve().orElse(null); + IFluidHandlerItem fluidHandlerItem = currentStack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM, null) + .resolve().orElse(null); if (mouseData.isLeftMouseButton()) { if (this.canFillSlot) { // set slot to fluid of tank item if (fluidHandlerItem != null) { - FluidStack cellFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE); + FluidStack cellFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, + IFluidHandler.FluidAction.SIMULATE); if (!cellFluid.isEmpty()) { if (cellFluid.isFluidEqual(currentFluid)) { // if it already contains the same fluid increase the amount by the cells amount @@ -287,7 +297,8 @@ public void tryClickPhantom(MouseData mouseData) { } } - private void drainSlotPhantom(boolean shift, Player player, FluidStack currentFluid, IFluidHandlerItem fluidHandlerItem) { + private void drainSlotPhantom(boolean shift, Player player, FluidStack currentFluid, + IFluidHandlerItem fluidHandlerItem) { currentFluid = currentFluid.copy(); if (this.controlsAmount && !shift) { if (fluidHandlerItem != null) { @@ -361,7 +372,8 @@ public void playSound(Player player, FluidStack fluid, SoundAction action) { if (sound == null) return; // on client, it needs the player to play the sound // on server the player is an exception - player.level().playSound(getSyncManager().isClient() ? player : null, player.getX(), player.getY() + 0.5, player.getZ(), sound, + player.level().playSound(getSyncManager().isClient() ? player : null, player.getX(), player.getY() + 0.5, + player.getZ(), sound, SoundSource.BLOCKS, 1.0F, 1.0F); } diff --git a/src/main/java/brachy/modularui/value/sync/GenericCollectionSyncHandler.java b/src/main/java/brachy/modularui/value/sync/GenericCollectionSyncHandler.java index fb8efce2..27334ce0 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericCollectionSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/GenericCollectionSyncHandler.java @@ -16,7 +16,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public abstract class GenericCollectionSyncHandler, S extends GenericCollectionSyncHandler> extends ValueSyncHandler { +public abstract class GenericCollectionSyncHandler, + S extends GenericCollectionSyncHandler> extends ValueSyncHandler { private final Supplier getter; private final Consumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/GenericListSyncHandler.java b/src/main/java/brachy/modularui/value/sync/GenericListSyncHandler.java index 6a75e7fc..41ee91b3 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericListSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/GenericListSyncHandler.java @@ -67,7 +67,8 @@ public Class> getValueType() { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. * This method forces a sync after the modification. * * @param consumer function that operates on the current cached value @@ -77,8 +78,10 @@ public void modifyValue(Consumer> consumer) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. - * This method can automatically sync the cache after the modification. Be careful with potential issues when the sync arg is false. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. + * This method can automatically sync the cache after the modification. Be careful with potential issues when the + * sync arg is false. * * @param consumer function that operates on the current cached value */ diff --git a/src/main/java/brachy/modularui/value/sync/GenericMapSyncHandler.java b/src/main/java/brachy/modularui/value/sync/GenericMapSyncHandler.java index 3f45e05a..19a9376a 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericMapSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/GenericMapSyncHandler.java @@ -127,7 +127,8 @@ public Class> getValueType() { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. * This method forces a sync after the modification. * * @param consumer function that operates on the current cached value @@ -137,8 +138,10 @@ public void modifyValue(Consumer> consumer) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. - * This method can automatically sync the cache after the modification. Be careful with potential issues when the sync arg is false. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. + * This method can automatically sync the cache after the modification. Be careful with potential issues when the + * sync arg is false. * * @param consumer function that operates on the current cached value */ diff --git a/src/main/java/brachy/modularui/value/sync/GenericSetSyncHandler.java b/src/main/java/brachy/modularui/value/sync/GenericSetSyncHandler.java index f65ae769..06e0f7c1 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericSetSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/GenericSetSyncHandler.java @@ -62,7 +62,8 @@ public Class> getValueType() { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. * This method forces a sync after the modification. * * @param consumer function that operates on the current cached value @@ -72,8 +73,10 @@ public void modifyValue(Consumer> consumer) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. - * This method can automatically sync the cache after the modification. Be careful with potential issues when the sync arg is false. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. + * This method can automatically sync the cache after the modification. Be careful with potential issues when the + * sync arg is false. * * @param consumer function that operates on the current cached value */ diff --git a/src/main/java/brachy/modularui/value/sync/GenericSyncValue.java b/src/main/java/brachy/modularui/value/sync/GenericSyncValue.java index 6be7e564..41078693 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/GenericSyncValue.java @@ -28,14 +28,20 @@ * Example: * GenericSyncValue.builder(ItemStack.class) *

- * When you work with types which themselves have generic types, then your IDE will likely yell at you. In this case you can use - * {@link #rawTypeBuilder(Class)}. Only use this if you have to, since you can technically put any class inside there without ModularUI be - * able to verify it. Since you can't specify the type {@link T} with the type here you need to use the diamond operator. + * When you work with types which themselves have generic types, then your IDE will likely yell at you. In this case you + * can use + * {@link #rawTypeBuilder(Class)}. Only use this if you have to, since you can technically put any class inside there + * without ModularUI be + * able to verify it. Since you can't specify the type {@link T} with the type here you need to use the diamond + * operator. *

* Example: GenericSyncValue.<List<ItemStack>>rawTypeBuilder(List.class) - *
Note that you wouldn't actually use {@link java.util.List List} here. It's just an example for a type with a generic parameter. + *
+ * Note that you wouldn't actually use {@link java.util.List List} here. It's just an example for a type with a generic + * parameter. *

- * If the value is never null you can also use {@link #notNullBuilder()}. This will infer the type with the value supplier. + * If the value is never null you can also use {@link #notNullBuilder()}. This will infer the type with the value + * supplier. *

* Example: GenericSyncValue.<ItemStack>notNullBuilder() *

@@ -139,7 +145,8 @@ public static Builder builder(Class type) { /** * Creates a builder for a generic sync value. This method should only be used if the type has generic parameters. - * The downside of this method is that the compiler can't verify the passed in class. Technically any class can be passed on, + * The downside of this method is that the compiler can't verify the passed in class. Technically any class can be + * passed on, * but issues will arise later down the line. * * @param type Class of the value to sync. This is used to verify synced value types. @@ -179,10 +186,14 @@ private Builder(Class type) { } /** - * Sets the getter for the sync value. Usually this returns a field in a {@link net.minecraft.world.level.block.entity.BlockEntity BlockEntity} or - * similar. On server side this is called every tick and compared to the sync values cache. If the values are different + * Sets the getter for the sync value. Usually this returns a field in a + * {@link net.minecraft.world.level.block.entity.BlockEntity BlockEntity} or + * similar. On server side this is called every tick and compared to the sync values cache. If the values are + * different * (determined by {@link #equals(EqualityTest)}), it is synced to the client. - *

This setter is required!

+ *

+ * This setter is required! + *

* * @param getter function that returns the current value that may be synced * @return this builder @@ -193,10 +204,14 @@ public Builder getter(Supplier<@UnknownNullability T> getter) { } /** - * Sets the setter for the sync value. Usually this sets a field in a {@link net.minecraft.world.level.block.entity.BlockEntity BlockEntity} or - * similar. This is called when a value is synced in client or server. In many cases this can be null since the synced value is + * Sets the setter for the sync value. Usually this sets a field in a + * {@link net.minecraft.world.level.block.entity.BlockEntity BlockEntity} or + * similar. This is called when a value is synced in client or server. In many cases this can be null since the + * synced value is * cached inside the sync handler. - *

This setter is optional!

+ *

+ * This setter is optional! + *

* * @param setter function that updates the source of the value * @return this builder @@ -207,9 +222,12 @@ public Builder setter(Consumer<@UnknownNullability T> setter) { } /** - * Sets a function which writes the value to a {@link FriendlyByteBuf}. The function is called every time the value is synced to the + * Sets a function which writes the value to a {@link FriendlyByteBuf}. The function is called every time the + * value is synced to the * other side. - *

This setter is required!

+ *

+ * This setter is required! + *

* * @param deserializer function that writes the value to a packet buffer * @return this builder @@ -220,9 +238,12 @@ public Builder deserializer(IByteBufDeserializer<@UnknownNullability T> deser } /** - * Sets a function which reads the value from a {@link FriendlyByteBuf}. The function is called every time the value is synced to the + * Sets a function which reads the value from a {@link FriendlyByteBuf}. The function is called every time the + * value is synced to the * other side. - *

This setter is required!

+ *

+ * This setter is required! + *

* * @param serializer function that reads the value from a packet buffer * @return this builder @@ -233,12 +254,18 @@ public Builder serializer(IByteBufSerializer<@UnknownNullability T> serialize } /** - * Sets a function which tests two instances of the value for differences. This function is called every tick on server to determine - * if the value from {@link #getter(Supplier)} needs to be synced. By default, this uses {@link Objects#equals(Object, Object)}. - * If your value does not implement {@link Object#equals(Object)}, then this setter must be called in order for it to function - * properly. Otherwise {@link Objects#equals(Object, Object)} always returns false since the instances will always be different, + * Sets a function which tests two instances of the value for differences. This function is called every tick on + * server to determine + * if the value from {@link #getter(Supplier)} needs to be synced. By default, this uses + * {@link Objects#equals(Object, Object)}. + * If your value does not implement {@link Object#equals(Object)}, then this setter must be called in order for + * it to function + * properly. Otherwise {@link Objects#equals(Object, Object)} always returns false since the instances will + * always be different, * which causes the value to be synced every tick. - *

This setter is optional!

+ *

+ * This setter is optional! + *

* * @param equals function that determines if two instances of the value are equal * @return this builder @@ -259,20 +286,30 @@ public Builder equalsDefault() { } /** - * Sets a function which creates a copy of the value. This is called every time the value cache is updated. This is to prevent - * accidental mutations of the cache value. For example if you called {@link #setValue(Object)}, but keep a reference to the new - * value and then modify your reference, then the cached value is also updated since it's the same object. If now the - * {@link #getter(Supplier)} function happens to return exactly that reference, then the {@link #equals(EqualityTest)} function always - * compares its cache to itself (since it compare the cache to the getter value, which are the same in this case). This causes + * Sets a function which creates a copy of the value. This is called every time the value cache is updated. This + * is to prevent + * accidental mutations of the cache value. For example if you called {@link #setValue(Object)}, but keep a + * reference to the new + * value and then modify your reference, then the cached value is also updated since it's the same object. If + * now the + * {@link #getter(Supplier)} function happens to return exactly that reference, then the + * {@link #equals(EqualityTest)} function always + * compares its cache to itself (since it compare the cache to the getter value, which are the same in this + * case). This causes * the value to be never synced from server to client. *

- * By default, the {@link #serializer(IByteBufSerializer)} and {@link #deserializer(IByteBufDeserializer)} function are called to - * create a new instance. If these functions are implemented properly, it is always guaranteed to create a new instance of the + * By default, the {@link #serializer(IByteBufSerializer)} and {@link #deserializer(IByteBufDeserializer)} + * function are called to + * create a new instance. If these functions are implemented properly, it is always guaranteed to create a new + * instance of the * value. However, it is still recommended to provide your own proper copy method. *

- * If you know, that your values is immutable (can't be modified once created), then you can use {@link #copyImmutable()}. + * If you know, that your values is immutable (can't be modified once created), then you can use + * {@link #copyImmutable()}. * That function won't copy the value, but just return the value. - *

This setter is optional!

+ *

+ * This setter is optional! + *

* * @param copy function that creates a new exact copy of the value * @return this builder @@ -283,7 +320,8 @@ public Builder copy(ICopy<@UnknownNullability T> copy) { } /** - * Sets a {@link #copy(ICopy)} function which assumes the values are always immutable. This should only be used if the value is + * Sets a {@link #copy(ICopy)} function which assumes the values are always immutable. This should only be used + * if the value is * always immutable (can't be modified once created). See {@link #copy(ICopy)} for more info. * * @return this builder @@ -294,7 +332,8 @@ public Builder copyImmutable() { } /** - * Sets an adapter. This combines {@link #deserializer(IByteBufDeserializer)}, {@link #serializer(IByteBufSerializer)} and + * Sets an adapter. This combines {@link #deserializer(IByteBufDeserializer)}, + * {@link #serializer(IByteBufSerializer)} and * {@link #equals(EqualityTest)} into one method. * * @param adapter byte buf adapter @@ -310,10 +349,13 @@ public Builder adapter(IByteBufAdapter<@UnknownNullability T> adapter) { } /** - * Sets the value to be nullable. This wraps all the used functions into null safe variants. This only for convenience. + * Sets the value to be nullable. This wraps all the used functions into null safe variants. This only for + * convenience. * Manually having to consider nullability inside all the functions is cumbersome. This setter is a shortcut. * It is opt-in since, it creates a very minor overhead in the serializer and deserializer. - *

This setter is optional!

+ *

+ * This setter is optional! + *

* * @return this builder */ @@ -335,7 +377,8 @@ public Builder allowC2S() { * @throws IllegalArgumentException if the value type is null and the getter returns null */ public GenericSyncValue build() { - return new GenericSyncValue<>(type, getter, setter, deserializer, serializer, equals, copy, nullable).allowC2S(this.allowC2S); + return new GenericSyncValue<>(type, getter, setter, deserializer, serializer, equals, copy, nullable) + .allowC2S(this.allowC2S); } } } diff --git a/src/main/java/brachy/modularui/value/sync/ISyncRegistrar.java b/src/main/java/brachy/modularui/value/sync/ISyncRegistrar.java index ee8e8a7f..01f70ff2 100644 --- a/src/main/java/brachy/modularui/value/sync/ISyncRegistrar.java +++ b/src/main/java/brachy/modularui/value/sync/ISyncRegistrar.java @@ -47,7 +47,8 @@ default DynamicSyncHandler dynamicSyncHandler(String key, DynamicSyncHandler.IWi return dynamicSyncHandler(key, 0, widgetProvider); } - default DynamicSyncHandler dynamicSyncHandler(String key, int id, DynamicSyncHandler.IWidgetProvider widgetProvider) { + default DynamicSyncHandler dynamicSyncHandler(String key, int id, + DynamicSyncHandler.IWidgetProvider widgetProvider) { DynamicSyncHandler syncHandler = new DynamicSyncHandler().widgetProvider(widgetProvider); syncValue(key, id, syncHandler); return syncHandler; @@ -55,12 +56,14 @@ default DynamicSyncHandler dynamicSyncHandler(String key, int id, DynamicSyncHan IPanelHandler syncedPanel(String key, boolean subPanel, PanelSyncHandler.IPanelBuilder panelBuilder); - @Nullable IPanelHandler findPanelHandlerNullable(String key); + @Nullable + IPanelHandler findPanelHandlerNullable(String key); default @NotNull IPanelHandler findPanelHandler(String key) { IPanelHandler panelHandler = findPanelHandlerNullable(key); if (panelHandler == null) { - throw new NoSuchElementException("Expected to find panel sync handler with key '" + key + "', but none was found."); + throw new NoSuchElementException( + "Expected to find panel sync handler with key '" + key + "', but none was found."); } return panelHandler; } @@ -134,10 +137,12 @@ default ItemSlotSyncHandler getOrCreateSlot(String name, Supplier s } default ItemSlotSyncHandler getOrCreateSlot(String name, int id, Supplier slotSupplier) { - return getOrCreateSyncHandler(name, id, ItemSlotSyncHandler.class, () -> new ItemSlotSyncHandler(slotSupplier.get())); + return getOrCreateSyncHandler(name, id, ItemSlotSyncHandler.class, + () -> new ItemSlotSyncHandler(slotSupplier.get())); } - @Nullable SyncHandler findSyncHandlerNullable(String name, int id); + @Nullable + SyncHandler findSyncHandlerNullable(String name, int id); default @Nullable SyncHandler findSyncHandlerNullable(String name) { return findSyncHandlerNullable(name, 0); @@ -146,7 +151,8 @@ default ItemSlotSyncHandler getOrCreateSlot(String name, int id, Supplier findSyncHandler(String name, int id) { SyncHandler syncHandler = findSyncHandlerNullable(name, id); if (syncHandler == null) { - throw new NoSuchElementException("Expected to find sync handler with key '" + makeSyncKey(name, id) + "', but none was found."); + throw new NoSuchElementException( + "Expected to find sync handler with key '" + makeSyncKey(name, id) + "', but none was found."); } return syncHandler; } @@ -170,11 +176,12 @@ default ItemSlotSyncHandler getOrCreateSlot(String name, int id, Supplier> @NotNull T findSyncHandler(String name, int id, Class type) { SyncHandler syncHandler = findSyncHandlerNullable(name, id); if (syncHandler == null) { - throw new NoSuchElementException("Expected to find sync handler with key '" + makeSyncKey(name, id) + "', but none was found."); + throw new NoSuchElementException( + "Expected to find sync handler with key '" + makeSyncKey(name, id) + "', but none was found."); } if (!type.isAssignableFrom(syncHandler.getClass())) { - throw new ClassCastException("Expected to find sync handler with key '" + makeSyncKey(name, id) + "' of type '" + type.getName() - + "', but found type '" + syncHandler.getClass().getName() + "'."); + throw new ClassCastException("Expected to find sync handler with key '" + makeSyncKey(name, id) + + "' of type '" + type.getName() + "', but found type '" + syncHandler.getClass().getName() + "'."); } return type.cast(syncHandler); } @@ -195,7 +202,8 @@ default ItemSlotSyncHandler getOrCreateSlot(String name, int id, Supplier> @NotNull Optional findSyncHandlerOptional(String name, int id, Class type) { + default > @NotNull Optional findSyncHandlerOptional(String name, int id, + Class type) { return Optional.ofNullable(findSyncHandlerNullable(name, id, type)); } diff --git a/src/main/java/brachy/modularui/value/sync/IntSyncValue.java b/src/main/java/brachy/modularui/value/sync/IntSyncValue.java index f21434be..3dfca81c 100644 --- a/src/main/java/brachy/modularui/value/sync/IntSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/IntSyncValue.java @@ -15,7 +15,8 @@ import java.util.function.IntConsumer; import java.util.function.IntSupplier; -public class IntSyncValue extends ValueSyncHandler implements IIntSyncValue, IDoubleSyncValue, IStringSyncValue { +public class IntSyncValue extends ValueSyncHandler + implements IIntSyncValue, IDoubleSyncValue, IStringSyncValue { private int cache; private final IntSupplier getter; diff --git a/src/main/java/brachy/modularui/value/sync/LongSyncValue.java b/src/main/java/brachy/modularui/value/sync/LongSyncValue.java index 44cac7c5..0a527ef2 100644 --- a/src/main/java/brachy/modularui/value/sync/LongSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/LongSyncValue.java @@ -15,7 +15,8 @@ import java.util.function.LongConsumer; import java.util.function.LongSupplier; -public class LongSyncValue extends ValueSyncHandler implements ILongSyncValue, IIntSyncValue, IStringSyncValue { +public class LongSyncValue extends ValueSyncHandler + implements ILongSyncValue, IIntSyncValue, IStringSyncValue { private final LongSupplier getter; private final LongConsumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/ModularSyncManager.java b/src/main/java/brachy/modularui/value/sync/ModularSyncManager.java index 3e65bd84..deac1de0 100644 --- a/src/main/java/brachy/modularui/value/sync/ModularSyncManager.java +++ b/src/main/java/brachy/modularui/value/sync/ModularSyncManager.java @@ -80,7 +80,8 @@ public void onOpen() { if (isOpen()) return; if (isDisposed()) throw new IllegalStateException("Can't open sync manager after it has been disposed!"); if (this.menu == null) { - throw new IllegalStateException("Sync Manager can't be opened when its not yet constructed. ModularContainer is null."); + throw new IllegalStateException( + "Sync Manager can't be opened when its not yet constructed. ModularContainer is null."); } setState(State.OPEN); this.panelSyncManagerMap.values().forEach(PanelSyncManager::onOpen); @@ -143,7 +144,8 @@ public void receiveWidgetUpdate(String panelName, String mapKey, boolean action, if (psm != null) { psm.receiveWidgetUpdate(mapKey, action, id, buf); } else if (!this.panelHistory.contains(panelName)) { - ModularUI.LOGGER.throwing(new IllegalStateException("A packet was send to panel '" + panelName + "' which was not opened yet!.")); + ModularUI.LOGGER.throwing(new IllegalStateException( + "A packet was send to panel '" + panelName + "' which was not opened yet!.")); } // else the panel was open at some point // we simply discard the packet silently and assume the packet was correctly send, but the panel closed earlier @@ -195,13 +197,15 @@ public ModularSyncManager registerSlotGroup(SlotGroup slotGroup) { } @Override - public ModularSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, ISyncedAction action) { + public ModularSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, + ISyncedAction action) { this.mainPSM.registerSyncedAction(mapKey, executeClient, executeServer, action); return this; } @Override - public > T getOrCreateSyncHandler(String name, int id, Class clazz, Supplier supplier) { + public > T getOrCreateSyncHandler(String name, int id, Class clazz, + Supplier supplier) { return this.mainPSM.getOrCreateSyncHandler(name, id, clazz, supplier); } @@ -237,6 +241,9 @@ private void setState(State state) { } enum State { - INIT, OPEN, CLOSED, DISPOSED + INIT, + OPEN, + CLOSED, + DISPOSED } } diff --git a/src/main/java/brachy/modularui/value/sync/PanelSyncManager.java b/src/main/java/brachy/modularui/value/sync/PanelSyncManager.java index 758be0b8..4f39369f 100644 --- a/src/main/java/brachy/modularui/value/sync/PanelSyncManager.java +++ b/src/main/java/brachy/modularui/value/sync/PanelSyncManager.java @@ -67,7 +67,8 @@ public void initialize(String panelName) { this.locked = true; this.syncHandlers.forEach((mapKey, syncHandler) -> syncHandler.init(mapKey, this)); this.init = true; - this.subPanels.forEach((s, syncHandler) -> this.modularSyncManager.getMainPSM().registerPanelSyncHandler(s, syncHandler)); + this.subPanels.forEach( + (s, syncHandler) -> this.modularSyncManager.getMainPSM().registerPanelSyncHandler(s, syncHandler)); } private void registerPanelSyncHandler(String name, SyncHandler syncHandler) { @@ -79,8 +80,9 @@ private void registerPanelSyncHandler(String name, SyncHandler syncHandler) { } String currentName = this.reverseSyncHandlers.get(syncHandler); if (currentName != null && !name.equals(currentName)) { - throw new IllegalStateException("Failed to register panel sync handler for name '" + name + "' during initialization. " + - "The panel sync handler is already registered under the name '" + currentName + "'."); + throw new IllegalStateException( + "Failed to register panel sync handler for name '" + name + "' during initialization. " + + "The panel sync handler is already registered under the name '" + currentName + "'."); } this.syncHandlers.put(name, syncHandler); this.reverseSyncHandlers.put(syncHandler, name); @@ -104,7 +106,8 @@ public void onOpen() { public void onClose() { this.closeListener.forEach(listener -> listener.accept(getPlayer())); this.syncHandlers.values().forEach(SyncHandler::dispose); - // Previously panel sync handlers were removed from the main psm, however this problematic if the screen will be reopened at some + // Previously panel sync handlers were removed from the main psm, however this problematic if the screen will be + // reopened at some // point. We can just not remove the sync handlers since mui has proper checks for re-registering panels. } @@ -141,7 +144,8 @@ public void receiveWidgetUpdate(String mapKey, boolean action, int id, FriendlyB } else if (syncHandler.isAllowC2S()) { syncHandler.readOnServer(id, buf); } else { - ModularUI.LOGGER.throwing(Level.WARN, new SecurityException("Tried to send a packet to server, but the sync handler does not accept client packets.")); + ModularUI.LOGGER.throwing(Level.WARN, new SecurityException( + "Tried to send a packet to server, but the sync handler does not accept client packets.")); } } @@ -151,7 +155,8 @@ private boolean invokeSyncedAction(String mapKey, FriendlyByteBuf buf) { ModularUI.LOGGER.warn("SyncAction '{}' does not exist for panel '{}'!.", mapKey, panelName); return false; } - if (!isLocked() || this.allowSyncHandlerRegistration || !syncedAction.isExecuteClient() || !syncedAction.isExecuteServer()) { + if (!isLocked() || this.allowSyncHandlerRegistration || !syncedAction.isExecuteClient() || + !syncedAction.isExecuteServer()) { syncedAction.invoke(this.client, buf); } else { // only allow sync handler registration if it is executed on client and server @@ -182,9 +187,11 @@ private void putSyncValue(String name, int id, SyncHandler syncHandler) { // registration of sync handlers forbidden if (this.allowSyncHandlerRegistration) { // lock can be bypassed currently, but it wasn't used - throw new IllegalStateException("SyncHandlers must be registered during panel building. Please use getOrCreateSyncHandler() inside DynamicSyncHandler!"); + throw new IllegalStateException( + "SyncHandlers must be registered during panel building. Please use getOrCreateSyncHandler() inside DynamicSyncHandler!"); } else { - throw new IllegalStateException("SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); + throw new IllegalStateException( + "SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); } } String key = makeSyncKey(name, id); @@ -223,13 +230,17 @@ public PanelSyncManager syncValue(String name, int id, SyncHandler syncHandle * NOTE *

* A panel sync handler is only created once. If one was already registered, that one will be returned. - * (This is only relevant for nested sub panels.) Furthermore, the panel handler has to be created on client and server with the same - * key. Like any other sync handler, the panel sync handler has to be created before the panel opened. The only exception is inside + * (This is only relevant for nested sub panels.) Furthermore, the panel handler has to be created on client and + * server with the same + * key. Like any other sync handler, the panel sync handler has to be created before the panel opened. The only + * exception is inside * dynamic sync handlers. * * @param key the key used for syncing - * @param subPanel true if this panel should close when its parent closes (the parent is defined by this {@link PanelSyncManager}) - * @param panelBuilder the panel builder, that will create the new panel. It must not return null or any existing panels. + * @param subPanel true if this panel should close when its parent closes (the parent is defined by this + * {@link PanelSyncManager}) + * @param panelBuilder the panel builder, that will create the new panel. It must not return null or any existing + * panels. * @return a synced panel handler. * @throws NullPointerException if the build panel of the builder is null * @throws IllegalArgumentException if the build panel of the builder is the main panel @@ -241,12 +252,14 @@ public IPanelHandler syncedPanel(String key, boolean subPanel, PanelSyncHandler. if (ph != null) return ph; if (isLocked() && !this.allowSyncHandlerRegistration) { // registration of sync handlers forbidden - throw new IllegalStateException("Synced panels must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); + throw new IllegalStateException( + "Synced panels must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); } PanelSyncHandler syncHandler = new PanelSyncHandler(panelBuilder, subPanel); this.subPanels.put(key, syncHandler); if (isInitialised() && (this == this.modularSyncManager.getMainPSM() || - this.modularSyncManager.getMainPSM().findSyncHandlerNullable(this.panelName, PanelSyncHandler.class) == null)) { + this.modularSyncManager.getMainPSM().findSyncHandlerNullable(this.panelName, PanelSyncHandler.class) == + null)) { // current panel is open this.modularSyncManager.getMainPSM().registerPanelSyncHandler(key, syncHandler); } @@ -302,7 +315,8 @@ public PanelSyncManager onCommonTick(Runnable runnable) { } @Override - public PanelSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, ISyncedAction action) { + public PanelSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, + ISyncedAction action) { if (executeClient || executeServer) { this.syncedActions.put(mapKey, new SyncedAction(action, executeClient, executeServer)); } @@ -311,7 +325,8 @@ public PanelSyncManager registerSyncedAction(String mapKey, boolean executeClien public void callSyncedAction(String mapKey, FriendlyByteBuf packet) { if (invokeSyncedAction(mapKey, packet)) { - ModularNetwork.get(isClient()).sendActionPacket(getModularSyncManager(), this.panelName, mapKey, packet, getPlayer()); + ModularNetwork.get(isClient()).sendActionPacket(getModularSyncManager(), this.panelName, mapKey, packet, + getPlayer()); } } @@ -326,12 +341,14 @@ public void callSyncedAction(String mapKey) { } @Override - public > T getOrCreateSyncHandler(String name, int id, Class clazz, Supplier supplier) { + public > T getOrCreateSyncHandler(String name, int id, Class clazz, + Supplier supplier) { SyncHandler syncHandler = findSyncHandlerNullable(name, id); if (syncHandler == null) { if (isLocked() && !this.allowSyncHandlerRegistration) { // registration is locked, and we don't have permission to temporarily bypass lock - throw new IllegalStateException("SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); + throw new IllegalStateException( + "SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); } T t = supplier.get(); boolean l = this.locked; @@ -343,7 +360,8 @@ public > T getOrCreateSyncHandler(String name, int id, if (clazz.isAssignableFrom(syncHandler.getClass())) { return clazz.cast(syncHandler); } - throw new IllegalStateException("SyncHandler for key " + makeSyncKey(name, id) + " is of type " + syncHandler.getClass() + ", but type " + clazz + " was expected!"); + throw new IllegalStateException("SyncHandler for key " + makeSyncKey(name, id) + " is of type " + + syncHandler.getClass() + ", but type " + clazz + " was expected!"); } @Override @@ -352,7 +370,8 @@ public > T getOrCreateSyncHandler(String name, int id, if (syncHandler == null) { if (isLocked() && !this.allowSyncHandlerRegistration) { // registration is locked, and we don't have permission to temporarily bypass lock - throw new IllegalStateException("SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); + throw new IllegalStateException( + "SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); } T t = supplier.get(); boolean l = this.locked; @@ -362,7 +381,7 @@ public > T getOrCreateSyncHandler(String name, int id, return t; } try { - //noinspection unchecked + // noinspection unchecked return (T) syncHandler; } catch (ClassCastException e) { throw new IllegalStateException("SyncHandler for key " + makeSyncKey(name, id) + diff --git a/src/main/java/brachy/modularui/value/sync/ShortSyncValue.java b/src/main/java/brachy/modularui/value/sync/ShortSyncValue.java index f6a991ba..d8d045cd 100644 --- a/src/main/java/brachy/modularui/value/sync/ShortSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/ShortSyncValue.java @@ -14,7 +14,8 @@ import java.util.Objects; -public class ShortSyncValue extends ValueSyncHandler implements IShortSyncValue, IIntSyncValue, IStringSyncValue { +public class ShortSyncValue extends ValueSyncHandler + implements IShortSyncValue, IIntSyncValue, IStringSyncValue { private short cache; private final ShortValue.Supplier getter; diff --git a/src/main/java/brachy/modularui/value/sync/StringSyncValue.java b/src/main/java/brachy/modularui/value/sync/StringSyncValue.java index 429ece08..8eaf928f 100644 --- a/src/main/java/brachy/modularui/value/sync/StringSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/StringSyncValue.java @@ -13,7 +13,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public class StringSyncValue extends AbstractGenericSyncValue implements IStringSyncValue { +public class StringSyncValue extends AbstractGenericSyncValue + implements IStringSyncValue { public StringSyncValue(Supplier getter, Consumer setter) { super(String.class, getter, setter); diff --git a/src/main/java/brachy/modularui/value/sync/SyncHandler.java b/src/main/java/brachy/modularui/value/sync/SyncHandler.java index 730d01f4..27b1dc43 100644 --- a/src/main/java/brachy/modularui/value/sync/SyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/SyncHandler.java @@ -32,8 +32,10 @@ public abstract class SyncHandler> implements ISyncOrVa /** * the key that belongs to this sync handler */ - @Getter private String key; - @Getter private boolean allowC2S; + @Getter + private String key; + @Getter + private boolean allowC2S; @ApiStatus.OverrideOnly @MustBeInvokedByOverriders @@ -71,7 +73,8 @@ public final void syncToClient(int id, @NotNull IPacketWriter bufferConsumer) { @OnlyIn(Dist.CLIENT) public final void syncToServer(int id, @NotNull IPacketWriter bufferConsumer) { if (!isAllowC2S()) { - ModularUI.LOGGER.throwing(Level.WARN, new SecurityException("Sync handler is unable to send packets to server!")); + ModularUI.LOGGER.throwing(Level.WARN, + new SecurityException("Sync handler is unable to send packets to server!")); return; } FriendlyByteBuf buffer = new FriendlyByteBuf(Unpooled.buffer()); @@ -88,7 +91,8 @@ public final void syncToServer(int id, @NotNull IPacketWriter bufferConsumer) { */ public final void sync(int id, @NotNull IPacketWriter bufferConsumer) { if (getSyncManager().isClient() && !isAllowC2S()) { - ModularUI.LOGGER.throwing(Level.WARN, new SecurityException("Sync handler is unable to send packets to server!")); + ModularUI.LOGGER.throwing(Level.WARN, + new SecurityException("Sync handler is unable to send packets to server!")); return; } FriendlyByteBuf buffer = new FriendlyByteBuf(Unpooled.buffer()); @@ -181,8 +185,10 @@ public boolean isSyncHandler() { } /** - * Sets this sync handler to accept C2S (client to server) packets. This value MUST be the same on client and server. - * By default, this is false to prevent clients from force updating values. Values which the player can control through a button for + * Sets this sync handler to accept C2S (client to server) packets. This value MUST be the same on client and + * server. + * By default, this is false to prevent clients from force updating values. Values which the player can control + * through a button for * example are completely fine to allow C2S updates. * * @param allowC2S whether this sync handler should allow client to server updates @@ -194,8 +200,10 @@ public S allowC2S(boolean allowC2S) { } /** - * Sets this sync handler whether to accept C2S (client to server) packets or not. This value MUST be the same on client and server. - * By default, this is false to prevent clients from force updating values. Values which the player can control through a button for + * Sets this sync handler whether to accept C2S (client to server) packets or not. This value MUST be the same on + * client and server. + * By default, this is false to prevent clients from force updating values. Values which the player can control + * through a button for * example are completely fine to allow C2S updates. * * @return this @@ -209,7 +217,8 @@ public S self() { return (S) this; } - private static void send(ModularNetworkSide network, String panel, FriendlyByteBuf buffer, SyncHandler syncHandler) { + private static void send(ModularNetworkSide network, String panel, FriendlyByteBuf buffer, + SyncHandler syncHandler) { Objects.requireNonNull(buffer); Objects.requireNonNull(syncHandler); if (!syncHandler.isValid()) { diff --git a/src/main/java/brachy/modularui/value/sync/ValueSyncHandler.java b/src/main/java/brachy/modularui/value/sync/ValueSyncHandler.java index ec09f688..d26ada1e 100644 --- a/src/main/java/brachy/modularui/value/sync/ValueSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/ValueSyncHandler.java @@ -7,7 +7,8 @@ import lombok.Getter; import lombok.Setter; -public abstract class ValueSyncHandler> extends SyncHandler implements IValueSyncHandler { +public abstract class ValueSyncHandler> extends SyncHandler + implements IValueSyncHandler { public static final int SYNC_VALUE = 0; diff --git a/src/main/java/brachy/modularui/widget/AbstractScrollWidget.java b/src/main/java/brachy/modularui/widget/AbstractScrollWidget.java index c0e42dfe..9cb712d8 100644 --- a/src/main/java/brachy/modularui/widget/AbstractScrollWidget.java +++ b/src/main/java/brachy/modularui/widget/AbstractScrollWidget.java @@ -26,12 +26,13 @@ * @param type of this widget */ public abstract class AbstractScrollWidget> - extends AbstractParentWidget implements IViewport, Interactable { + extends AbstractParentWidget implements IViewport, Interactable { private final ScrollArea scroll = new ScrollArea(); private boolean scrollXActive, scrollYActive; - @Getter private boolean showScrollShadows = true; + @Getter + private boolean showScrollShadows = true; public AbstractScrollWidget(@Nullable HorizontalScrollData x, @Nullable VerticalScrollData y) { super(); @@ -76,8 +77,10 @@ public void beforeResize(boolean onOpen) { } protected void checkScrollbarActive(boolean resizeOnChange) { - boolean scrollYActive = this.scroll.getScrollY() != null && this.scroll.getScrollY().isScrollBarActive(getScrollArea()); - boolean scrollXActive = this.scroll.getScrollX() != null && this.scroll.getScrollX().isScrollBarActive(getScrollArea(), scrollYActive); + boolean scrollYActive = this.scroll.getScrollY() != null && + this.scroll.getScrollY().isScrollBarActive(getScrollArea()); + boolean scrollXActive = this.scroll.getScrollX() != null && + this.scroll.getScrollX().isScrollBarActive(getScrollArea(), scrollYActive); if (resizeOnChange && (scrollYActive != this.scrollYActive || scrollXActive != this.scrollXActive)) { scheduleResize(); } @@ -142,7 +145,8 @@ public void postDraw(ModularGuiContext context, boolean transformed) { if (!transformed) { context.getStencil().pop(); WidgetThemeEntry scrollbarTheme = getTheme().getScrollbarThemeEntry(); - this.scroll.drawScrollbar(context, scrollbarTheme.getTheme(isHovering()), scrollbarTheme.theme().getBackground()); + this.scroll.drawScrollbar(context, scrollbarTheme.getTheme(isHovering()), + scrollbarTheme.theme().getBackground()); if (this.showScrollShadows) this.scroll.drawScrollShadow(context); } } diff --git a/src/main/java/brachy/modularui/widget/InternalWidgetTree.java b/src/main/java/brachy/modularui/widget/InternalWidgetTree.java index 628aa8da..86f2a14b 100644 --- a/src/main/java/brachy/modularui/widget/InternalWidgetTree.java +++ b/src/main/java/brachy/modularui/widget/InternalWidgetTree.java @@ -9,9 +9,9 @@ import brachy.modularui.widgets.layout.IExpander; import net.minecraft.client.gui.GuiGraphics; -import com.mojang.blaze3d.systems.RenderSystem; import com.google.common.base.Joiner; +import com.mojang.blaze3d.systems.RenderSystem; import org.jetbrains.annotations.Contract; import java.util.ArrayList; diff --git a/src/main/java/brachy/modularui/widget/ParentWidget.java b/src/main/java/brachy/modularui/widget/ParentWidget.java index 53243ba6..08a91eb6 100755 --- a/src/main/java/brachy/modularui/widget/ParentWidget.java +++ b/src/main/java/brachy/modularui/widget/ParentWidget.java @@ -9,7 +9,7 @@ * @param type of this widget */ public class ParentWidget> extends AbstractParentWidget - implements IParentWidget { + implements IParentWidget { public boolean addChild(IWidget child, int index) { return super.addChild(child, index); diff --git a/src/main/java/brachy/modularui/widget/ScrollWidget.java b/src/main/java/brachy/modularui/widget/ScrollWidget.java index c1139d72..962aec24 100755 --- a/src/main/java/brachy/modularui/widget/ScrollWidget.java +++ b/src/main/java/brachy/modularui/widget/ScrollWidget.java @@ -6,7 +6,7 @@ import brachy.modularui.widget.scroll.VerticalScrollData; public class ScrollWidget> extends AbstractScrollWidget - implements IParentWidget { + implements IParentWidget { public ScrollWidget() { super(null, null); diff --git a/src/main/java/brachy/modularui/widget/Widget.java b/src/main/java/brachy/modularui/widget/Widget.java index 3097ed42..b82515c4 100644 --- a/src/main/java/brachy/modularui/widget/Widget.java +++ b/src/main/java/brachy/modularui/widget/Widget.java @@ -31,7 +31,6 @@ import brachy.modularui.widgets.slot.ItemSlot; import com.mojang.serialization.Codec; - import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -65,18 +64,23 @@ public class Widget> extends AbstractWidget implements IPosi .addOpt("name", Widget::name, Widget::getName, Codec.STRING, null) .addOpt("enabled", Widget::setEnabled, Widget::isEnabled, Codec.BOOL, true) .addOpt("syncKey", Widget::setSyncKey, Widget::getSyncKey, Codec.STRING, null) - .addOpt("disableThemeBackground", Widget::disableThemeBackground, Widget::isDisableThemeBackground, Codec.BOOL, false) - .addOpt("disableHoverThemeBackground", Widget::disableHoverThemeBackground, Widget::isDisableHoverThemeBackground, Codec.BOOL, false) + .addOpt("disableThemeBackground", Widget::disableThemeBackground, Widget::isDisableThemeBackground, + Codec.BOOL, false) + .addOpt("disableHoverThemeBackground", Widget::disableHoverThemeBackground, + Widget::isDisableHoverThemeBackground, Codec.BOOL, false) .addOpt("shadow", Widget::shadow, Widget::getShadow, IDrawable.CODEC, null) .addOpt("background", Widget::setBackground, Widget::getBackground, IDrawable.CODEC, null) .addOpt("backgroundOverlay", Widget::setBackground, Widget::getBackground, IDrawable.CODEC, null) .addOpt("overlay", Widget::overlay, Widget::getOverlay, IDrawable.CODEC, null) .addOpt("hoverBackground", Widget::setHoverBackground, Widget::getHoverBackground, IDrawable.CODEC, null) - .addOpt("hoverBackgroundOverlay", Widget::setHoverBackgroundOverlay, Widget::getHoverBackground, IDrawable.CODEC, null) + .addOpt("hoverBackgroundOverlay", Widget::setHoverBackgroundOverlay, Widget::getHoverBackground, + IDrawable.CODEC, null) .addOpt("hoverOverlay", Widget::hoverOverlay, Widget::getHoverOverlay, IDrawable.CODEC, null) - .addOpt("widgetThemeKey", Widget::widgetThemeKey, Widget::getWidgetThemeKeyOverride, WidgetThemeKey.CODEC, null) + .addOpt("widgetThemeKey", Widget::widgetThemeKey, Widget::getWidgetThemeKeyOverride, WidgetThemeKey.CODEC, + null) .addOpt("themeOverride", Widget::themeOverride, Widget::getThemeOverride, ITheme.REFERENCE_CODEC, null) - .addOpt("excludeAreaInRecipeViewer", Widget::excludeAreaInRecipeViewer, Widget::isExcludeAreaInRecipeViewer, Codec.BOOL, false) + .addOpt("excludeAreaInRecipeViewer", Widget::excludeAreaInRecipeViewer, Widget::isExcludeAreaInRecipeViewer, + Codec.BOOL, false) .addOpt("tooltip", Widget::setTooltip, Widget::getTooltip, RichTooltip.CODEC, null) .addFieldsOf(StandardResizer.COMPACT_CODEC, Widget::resizer) .addFieldOf(Area.CODEC, Widget::getArea, "margin") @@ -87,7 +91,8 @@ public class Widget> extends AbstractWidget implements IPosi .build(); // other - @Getter private boolean excludeAreaInRecipeViewer = false; + @Getter + private boolean excludeAreaInRecipeViewer = false; // sizing @Getter private BiConsumer transform; @@ -312,7 +317,8 @@ public void drawOverlay(ModularGuiContext context, WidgetThemeEntry widgetThe @Override public void drawForeground(ModularGuiContext context) { RichTooltip tooltip = getTooltip(); - if (tooltip != null && !context.getUISettings().drawTooltipExternally() && isHoveringFor(tooltip.showUpTimer())) { + if (tooltip != null && !context.getUISettings().drawTooltipExternally() && + isHoveringFor(tooltip.showUpTimer())) { tooltip.draw(context); } } @@ -424,7 +430,8 @@ protected WidgetTheme getActiveWidgetTheme(WidgetThemeEntry widgetTheme, bool } /** - * Returns the actual used widget theme entry. Uses {@link #widgetThemeKey(String)} if it has been set, otherwise calls + * Returns the actual used widget theme entry. Uses {@link #widgetThemeKey(String)} if it has been set, otherwise + * calls * {@link #getWidgetThemeEntryInternal(ITheme)} * * @param theme theme to get widget theme from @@ -439,7 +446,8 @@ public final WidgetThemeEntry getWidgetThemeEntry(ITheme theme) { } /** - * Returns the actual used widget theme entry. Uses {@link #widgetThemeKey(String)} if it has been set, otherwise calls + * Returns the actual used widget theme entry. Uses {@link #widgetThemeKey(String)} if it has been set, otherwise + * calls * {@link #getWidgetThemeEntryInternal(ITheme)} * * @param theme theme to get widget theme entry from @@ -489,6 +497,7 @@ public W widgetThemeKey(WidgetThemeKey s) { /** * Sets an override theme to use for this widget and its children. * This will change the appearance of this widget according to the theme. + * * @param theme The theme to use. * @return this */ @@ -500,6 +509,7 @@ public W themeOverride(ITheme theme) { /** * Sets an override theme to use for this widget and its children. * This will change the appearance of this widget according to the theme. + * * @param theme The theme to use. * @return this */ @@ -512,7 +522,8 @@ public W themeOverride(String theme) { } /** - * Sets a shadow. Shadows are drawn before the background and don't actually have to be shadows. This doesn't effect theme backgrounds + * Sets a shadow. Shadows are drawn before the background and don't actually have to be shadows. This doesn't effect + * theme backgrounds * and doesn't change when hovered. * * @param shadow background to use. @@ -526,10 +537,12 @@ public W shadow(IDrawable... shadow) { /** * Sets a background. The theme background will be drawn before this override. *

- * NOTE: This will NOT disable the theme background. Disable it separately with {@link #disableThemeBackground(boolean)}. + * NOTE: This will NOT disable the theme background. Disable it separately with + * {@link #disableThemeBackground(boolean)}. *

* This method is meant for unique textures. For generic backgrounds please use themes. Also consider using - * {@link #overlay(IDrawable...)} instead. Using {@link IDrawable#EMPTY} will make the background invisible while still overriding + * {@link #overlay(IDrawable...)} instead. Using {@link IDrawable#EMPTY} will make the background invisible while + * still overriding * the widget theme. Background are drawn before the widget and overlays are drawn. * * @param background background to use. @@ -541,7 +554,8 @@ public W backgroundOverlay(IDrawable... background) { } /** - * Sets a background and disables the theme background. See {@link #backgroundOverlay(IDrawable...)} for more information. + * Sets a background and disables the theme background. See {@link #backgroundOverlay(IDrawable...)} for more + * information. * * @param background background * @return this @@ -564,20 +578,24 @@ public W overlay(IDrawable... overlay) { /** * Sets a hover background. The hover theme background will be drawn before this override. *

- * NOTE: This will NOT disable the hover theme background. Disable it separately with {@link #disableHoverThemeBackground(boolean)}. + * NOTE: This will NOT disable the hover theme background. Disable it separately with + * {@link #disableHoverThemeBackground(boolean)}. *

*

* This method is meant for unique textures. For generic backgrounds please use themes. Also consider using - * {@link #hoverOverlay(IDrawable...)} instead. Using {@link IDrawable#EMPTY} will make the background invisible while still + * {@link #hoverOverlay(IDrawable...)} instead. Using {@link IDrawable#EMPTY} will make the background invisible + * while still * overriding the widget theme. Background are drawn before the widget and overlays are drawn. *

* Following argument special cases should be considered: *

    - *
  • {@code null} will fallback to {@link WidgetThemeEntry#hoverTheme()}
  • - *
  • {@link IDrawable#EMPTY} will make the hover background invisible
  • - *
  • {@link IDrawable#NONE} will use the normal background instead (which is also achieved using {@link #disableHoverBackground()}) - * (note that this won't disable the hover theme background)
  • - *
  • multiple drawables, will result in them being drawn on top of each other in the order they are passed to the method
  • + *
  • {@code null} will fallback to {@link WidgetThemeEntry#hoverTheme()}
  • + *
  • {@link IDrawable#EMPTY} will make the hover background invisible
  • + *
  • {@link IDrawable#NONE} will use the normal background instead (which is also achieved using + * {@link #disableHoverBackground()}) + * (note that this won't disable the hover theme background)
  • + *
  • multiple drawables, will result in them being drawn on top of each other in the order they are passed to the + * method
  • *
* * @param background hover background to use. @@ -589,7 +607,8 @@ public W hoverBackgroundOverlay(IDrawable... background) { } /** - * Sets a background and disables the theme background. See {@link #backgroundOverlay(IDrawable...)} for more information. + * Sets a background and disables the theme background. See {@link #backgroundOverlay(IDrawable...)} for more + * information. * * @param background background * @return this @@ -605,9 +624,11 @@ public W hoverBackground(IDrawable... background) { *

* Following argument special cases should be considered: *

    - *
  • {@link IDrawable#EMPTY} will make the hover overlay invisible
  • - *
  • {@code null} and {@link IDrawable#NONE} will use the normal overlay instead (which is also achieved using {@link #disableHoverOverlay()})
  • - *
  • multiple drawables, will result in them being drawn on top of each other in the order they are passed to the method
  • + *
  • {@link IDrawable#EMPTY} will make the hover overlay invisible
  • + *
  • {@code null} and {@link IDrawable#NONE} will use the normal overlay instead (which is also achieved using + * {@link #disableHoverOverlay()})
  • + *
  • multiple drawables, will result in them being drawn on top of each other in the order they are passed to the + * method
  • *
* * @param overlay hover overlay to use. @@ -629,13 +650,21 @@ public W disableHoverThemeBackground(boolean b) { } // background setter for codec - private void setBackground(IDrawable d) {setBackground(d, true, false);} + private void setBackground(IDrawable d) { + setBackground(d, true, false); + } - private void setHoverBackground(IDrawable d) {setBackground(d, true, true);} + private void setHoverBackground(IDrawable d) { + setBackground(d, true, true); + } - private void setBackgroundOverlay(IDrawable d) {setBackground(d, false, false);} + private void setBackgroundOverlay(IDrawable d) { + setBackground(d, false, false); + } - private void setHoverBackgroundOverlay(IDrawable d) {setBackground(d, false, true);} + private void setHoverBackgroundOverlay(IDrawable d) { + setBackground(d, false, true); + } private void setBackground(IDrawable drawable, boolean disableTheme, boolean hover) { if (drawable != null) { @@ -784,7 +813,7 @@ public W onUpdateListener(Consumer listener, boolean merge) { return getThis(); } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) private void setOnUpdateListener(Consumer listener) { onUpdateListener(listener); } @@ -848,7 +877,7 @@ public W transform(BiConsumer transform) { return getThis(); } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) private void setTransform(BiConsumer listener) { transform(listener); } @@ -998,7 +1027,7 @@ public W name(String name) { * This can be used to further configure widgets in ways not directly allowed by the builder functions. *

* For example, adding a click action to a progress widget changes from this: - * {@snippet lang="java": + * {@snippet lang = "java": * ProgressWidget progressWidget = new ProgressWidget() * .value() * .texture(); @@ -1012,19 +1041,19 @@ public W name(String name) { * //... * } * to this: - * {@snippet lang="java": - * parentWidget.child(new ProgressWidget() - * .value() - * .texture() - * .configure(w -> { - * w.listenGuiAction((IGuiAction.MousePressed) (ctx, button) -> { - * if (!ctx.isMouseAbove(w)) return false; - * //... - * return true; - * }); - * })) - * .child() - * //... + * {@snippet lang = "java": + * parentWidget.child(new ProgressWidget() + * .value() + * .texture() + * .configure(w -> { + * w.listenGuiAction((IGuiAction.MousePressed) (ctx, button) -> { + * if (!ctx.isMouseAbove(w)) return false; + * // ... + * return true; + * }); + * })) + * .child() + * // ... * } * * @param configurator the configuration function diff --git a/src/main/java/brachy/modularui/widget/WidgetTree.java b/src/main/java/brachy/modularui/widget/WidgetTree.java index 2576018c..0e8f6078 100644 --- a/src/main/java/brachy/modularui/widget/WidgetTree.java +++ b/src/main/java/brachy/modularui/widget/WidgetTree.java @@ -98,11 +98,13 @@ public static Optional findFirstWithNameOptional(IWidget parent, String * @return the first widget with matching name and class or null if none was found */ @SuppressWarnings("unchecked") - public static @Nullable T findFirstWithNameNullable(IWidget parent, String name, Class type) { + public static @Nullable T findFirstWithNameNullable(IWidget parent, String name, + Class type) { return foreachChildWithResult(parent, w -> w.isNameAndType(name, type) ? (T) w : null, true); } - public static Optional findFirstWithNameOptional(IWidget parent, String name, Class type) { + public static Optional findFirstWithNameOptional(IWidget parent, String name, + Class type) { return Optional.ofNullable(findFirstWithNameNullable(parent, name, type)); } @@ -217,7 +219,8 @@ public static void collectSyncValues(PanelSyncManager syncManager, ModularPanel< } @ApiStatus.Internal - public static void collectSyncValues(PanelSyncManager syncManager, String panelName, IWidget panel, boolean includePanel) { + public static void collectSyncValues(PanelSyncManager syncManager, String panelName, IWidget panel, + boolean includePanel) { MutableInt id = new MutableInt(0); String syncKey = ModularSyncManager.AUTO_SYNC_PREFIX + panelName; foreachChildBFS(panel, widget -> { @@ -233,7 +236,8 @@ public static void collectSyncValues(PanelSyncManager syncManager, String panelN public static int countUnregisteredSyncHandlers(PanelSyncManager syncManager, IWidget parent) { MutableInt count = new MutableInt(); foreachChildBFS(parent, widget -> { - if (widget instanceof ISynced synced && synced.isSynced() && !synced.getSyncHandler().isRegistered(syncManager)) { + if (widget instanceof ISynced synced && synced.isSynced() && + !synced.getSyncHandler().isRegistered(syncManager)) { count.increment(); } return true; diff --git a/src/main/java/brachy/modularui/widget/scroll/HorizontalScrollData.java b/src/main/java/brachy/modularui/widget/scroll/HorizontalScrollData.java index 4e0def6f..a87950db 100755 --- a/src/main/java/brachy/modularui/widget/scroll/HorizontalScrollData.java +++ b/src/main/java/brachy/modularui/widget/scroll/HorizontalScrollData.java @@ -108,13 +108,15 @@ public void drawScrollShadow(ScrollArea area, ModularGuiContext context) { float prog = MathUtils.clamp(s / maxOpacityScroll, 0, 1); int startColor = Color.withAlpha(startColorFull, prog * 0.8f); int size = Math.min((int) (prog * maxShadowSize), maxShadowSizeLimit); - GuiDraw.drawHorizontalGradientRect(context.getGraphics(), sp.getScrollPaddingLeft(), y, size, h, startColor, endColor); + GuiDraw.drawHorizontalGradientRect(context.getGraphics(), sp.getScrollPaddingLeft(), y, size, h, startColor, + endColor); } if (s < max) { float prog = MathUtils.clamp((max - s) / maxOpacityScroll, 0, 1); int startColor = Color.withAlpha(startColorFull, prog * 0.8f); int size = Math.min((int) (prog * maxShadowSize), maxShadowSizeLimit); - GuiDraw.drawHorizontalGradientRect(context.getGraphics(), area.w() - size - sp.getScrollPaddingRight(), y, size, h, endColor, startColor); + GuiDraw.drawHorizontalGradientRect(context.getGraphics(), area.w() - size - sp.getScrollPaddingRight(), y, + size, h, endColor, startColor); } } } diff --git a/src/main/java/brachy/modularui/widget/scroll/ScrollData.java b/src/main/java/brachy/modularui/widget/scroll/ScrollData.java index 48a25dd7..a364c642 100755 --- a/src/main/java/brachy/modularui/widget/scroll/ScrollData.java +++ b/src/main/java/brachy/modularui/widget/scroll/ScrollData.java @@ -253,7 +253,8 @@ public ScrollData texture(IDrawable drawable) { } @OnlyIn(Dist.CLIENT) - public abstract void drawScrollbar(ModularGuiContext context, ScrollArea area, WidgetTheme widgetTheme, IDrawable texture); + public abstract void drawScrollbar(ModularGuiContext context, ScrollArea area, WidgetTheme widgetTheme, + IDrawable texture); @OnlyIn(Dist.CLIENT) protected void drawScrollBar(ModularGuiContext context, int x, int y, int w, int h, WidgetTheme widgetTheme, diff --git a/src/main/java/brachy/modularui/widget/scroll/ScrollPadding.java b/src/main/java/brachy/modularui/widget/scroll/ScrollPadding.java index 1ef9f48b..03172993 100755 --- a/src/main/java/brachy/modularui/widget/scroll/ScrollPadding.java +++ b/src/main/java/brachy/modularui/widget/scroll/ScrollPadding.java @@ -13,10 +13,14 @@ public class ScrollPadding extends Box { public static final ScrollPadding SHARED = new ScrollPadding(); public static final ScrollPadding ZERO = new ScrollPadding(); - @Getter protected int scrollPaddingLeft; - @Getter protected int scrollPaddingTop; - @Getter protected int scrollPaddingRight; - @Getter protected int scrollPaddingBottom; + @Getter + protected int scrollPaddingLeft; + @Getter + protected int scrollPaddingTop; + @Getter + protected int scrollPaddingRight; + @Getter + protected int scrollPaddingBottom; public ScrollPadding scrollPaddingAll(int all) { return this.scrollPaddingAll(all, all); diff --git a/src/main/java/brachy/modularui/widget/scroll/VerticalScrollData.java b/src/main/java/brachy/modularui/widget/scroll/VerticalScrollData.java index c603ee8a..2dde07f4 100755 --- a/src/main/java/brachy/modularui/widget/scroll/VerticalScrollData.java +++ b/src/main/java/brachy/modularui/widget/scroll/VerticalScrollData.java @@ -107,13 +107,15 @@ public void drawScrollShadow(ScrollArea area, ModularGuiContext context) { float prog = MathUtils.clamp(s / maxOpacityScroll, 0, 1); int startColor = Color.withAlpha(startColorFull, prog * 0.8f); int size = Math.min((int) (prog * maxShadowSize), maxShadowSizeLimit); - GuiDraw.drawVerticalGradientRect(context.getGraphics(), x, sp.getScrollPaddingTop(), w, size, startColor, endColor); + GuiDraw.drawVerticalGradientRect(context.getGraphics(), x, sp.getScrollPaddingTop(), w, size, startColor, + endColor); } if (s < max) { float prog = MathUtils.clamp((max - s) / maxOpacityScroll, 0, 1); int startColor = Color.withAlpha(startColorFull, prog * 0.8f); int size = Math.min((int) (prog * maxShadowSize), maxShadowSizeLimit); - GuiDraw.drawVerticalGradientRect(context.getGraphics(), x, area.h() - size - sp.getScrollPaddingBottom(), w, size, endColor, startColor); + GuiDraw.drawVerticalGradientRect(context.getGraphics(), x, area.h() - size - sp.getScrollPaddingBottom(), w, + size, endColor, startColor); } } } diff --git a/src/main/java/brachy/modularui/widget/sizer/Area.java b/src/main/java/brachy/modularui/widget/sizer/Area.java index dfd4fb55..ad0e4454 100644 --- a/src/main/java/brachy/modularui/widget/sizer/Area.java +++ b/src/main/java/brachy/modularui/widget/sizer/Area.java @@ -12,8 +12,8 @@ import net.minecraft.client.gui.navigation.ScreenRectangle; import net.minecraft.util.Mth; -import com.mojang.serialization.Codec; +import com.mojang.serialization.Codec; import lombok.Getter; import java.util.Objects; diff --git a/src/main/java/brachy/modularui/widget/sizer/Box.java b/src/main/java/brachy/modularui/widget/sizer/Box.java index f9d229cf..3b74f00f 100644 --- a/src/main/java/brachy/modularui/widget/sizer/Box.java +++ b/src/main/java/brachy/modularui/widget/sizer/Box.java @@ -6,7 +6,6 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import com.mojang.serialization.Codec; - import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; diff --git a/src/main/java/brachy/modularui/widget/sizer/DimensionSizer.java b/src/main/java/brachy/modularui/widget/sizer/DimensionSizer.java index d9e67a1b..8be7d884 100644 --- a/src/main/java/brachy/modularui/widget/sizer/DimensionSizer.java +++ b/src/main/java/brachy/modularui/widget/sizer/DimensionSizer.java @@ -8,7 +8,6 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import com.mojang.serialization.Codec; - import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -25,8 +24,10 @@ public class DimensionSizer { public static final MutableObjectCodec CODEC = MutableObjectCodec.builder(DimensionSizer.class) .baseCopy(sizer -> new DimensionSizer(sizer.resizer, sizer.axis)) - .addOpt("coverChildrenMinSize", DimensionSizer::setCoverChildrenMinSize, DimensionSizer::getCoverChildrenMinSize, Codec.INT, -1) - .addOpt("start", DimensionSizer::setStart, DimensionSizer::getStart, Unit.CODEC, Unit.ZERO).neverWriteDefault() + .addOpt("coverChildrenMinSize", DimensionSizer::setCoverChildrenMinSize, + DimensionSizer::getCoverChildrenMinSize, Codec.INT, -1) + .addOpt("start", DimensionSizer::setStart, DimensionSizer::getStart, Unit.CODEC, Unit.ZERO) + .neverWriteDefault() .addOpt("end", DimensionSizer::setEnd, DimensionSizer::getEnd, Unit.CODEC, Unit.ZERO).neverWriteDefault() .addOpt("size", DimensionSizer::setSize, DimensionSizer::getSize, Unit.CODEC, Unit.ZERO).neverWriteDefault() .build(); @@ -35,7 +36,8 @@ public class DimensionSizer { private final GuiAxis axis; private final Unit p1 = new Unit(), p2 = new Unit(); - @Getter(AccessLevel.PRIVATE) private Unit start, end, size; + @Getter(AccessLevel.PRIVATE) + private Unit start, end, size; private Unit next = p1; @Getter @@ -292,7 +294,7 @@ public int postApply(ResizeNode resizer, ResizeNode relativeTo, int p0, int p1) } else if (this.end != null) { p = calcPoint(this.end, s, parentSize, parentCalculated) - s; } else { - p = area.getRelativePoint(this.axis) + p0/* + area.getMargin().getStart(this.axis)*/; + p = area.getRelativePoint(this.axis) + p0/* + area.getMargin().getStart(this.axis) */; moveAmount = -p0; } area.setRelativePoint(this.axis, p); @@ -400,7 +402,9 @@ protected Unit getPoint() { public void detectConflictingConfiguration() { if (this.expanded && this.coverChildrenMinSize >= 0) { - ModularUI.LOGGER.warn("Resizer '{}' has expanded() and coverChildren() on {} axis. This conflicts and may cause layout issues.", this.resizer, this.axis); + ModularUI.LOGGER.warn( + "Resizer '{}' has expanded() and coverChildren() on {} axis. This conflicts and may cause layout issues.", + this.resizer, this.axis); } // TODO detect when this depends and all siblings depend on parent and parent depends on all children } diff --git a/src/main/java/brachy/modularui/widget/sizer/ResizeNode.java b/src/main/java/brachy/modularui/widget/sizer/ResizeNode.java index c0f5e049..160e55b3 100644 --- a/src/main/java/brachy/modularui/widget/sizer/ResizeNode.java +++ b/src/main/java/brachy/modularui/widget/sizer/ResizeNode.java @@ -114,7 +114,8 @@ public void setDefaultParent(ResizeNode resizeNode) { } protected void setParentOverride(ResizeNode resizeNode) { - // ModularUI.LOGGER.info("Set override parent of {} to {}. Current: default: {}, override: {}", this, resizeNode, + // ModularUI.LOGGER.info("Set override parent of {} to {}. Current: default: {}, override: {}", this, + // resizeNode, // this.defaultParent, this.parentOverride); if (resizeNode == this) throw new IllegalArgumentException("Tried to set itself as parent override in " + this); if (removeFromParent(this.parentOverride, this.defaultParent, resizeNode)) return; diff --git a/src/main/java/brachy/modularui/widget/sizer/StandardResizer.java b/src/main/java/brachy/modularui/widget/sizer/StandardResizer.java index 87be52fa..d7d4562e 100644 --- a/src/main/java/brachy/modularui/widget/sizer/StandardResizer.java +++ b/src/main/java/brachy/modularui/widget/sizer/StandardResizer.java @@ -14,7 +14,6 @@ import brachy.modularui.widgets.layout.IExpander; import com.mojang.serialization.Codec; - import lombok.AccessLevel; import lombok.Getter; import org.jetbrains.annotations.ApiStatus; @@ -36,7 +35,8 @@ public class StandardResizer extends WidgetResizeNode implements IPositioned COMPACT_CODEC = MutableObjectCodec.builder(StandardResizer.class) + public static final MutableObjectCodec COMPACT_CODEC = MutableObjectCodec + .builder(StandardResizer.class) .baseCopy(resizer -> new StandardResizer(resizer.getWidget())) .addOpt("expanded", StandardResizer::expanded, StandardResizer::isExpanded, Codec.BOOL, false) .addOpt("decoration", StandardResizer::decoration, StandardResizer::isDecoration, Codec.BOOL, false) @@ -50,10 +50,14 @@ public class StandardResizer extends WidgetResizeNode implements IPositioned children, boolea // if all children sizes depend on their parent, just use the min size as default w = this.x.getCoverChildrenMinSize(); } else { - GuiError.throwNew(getWidget(), GuiError.Type.SIZING, "Can't cover children width when all children depend on their parent and min size is 0!"); + GuiError.throwNew(getWidget(), GuiError.Type.SIZING, + "Can't cover children width when all children depend on their parent and min size is 0!"); return false; } } @@ -293,7 +298,8 @@ protected boolean doCoverChildren(IWidget widget, List children, boolea // if all children sizes depend on their parent, just use the min size as default h = this.y.getCoverChildrenMinSize(); } else { - GuiError.throwNew(getWidget(), GuiError.Type.SIZING, "Can't cover children height when all children depend on their parent and min size is 0!"); + GuiError.throwNew(getWidget(), GuiError.Type.SIZING, + "Can't cover children height when all children depend on their parent and min size is 0!"); return false; } } @@ -372,7 +378,8 @@ protected void coverChildrenForLayout(ILayoutWidget layout, IWidget widget, List x1 = Math.max(x1, area.rx + area.width + padding.right() + margin.right()); } } else if (coverByDefaultSizeX) { - withDefaultW = Math.max(withDefaultW, child.getDefaultWidth() + margin.horizontal() + padding.horizontal()); + withDefaultW = Math.max(withDefaultW, + child.getDefaultWidth() + margin.horizontal() + padding.horizontal()); } } @@ -388,7 +395,8 @@ protected void coverChildrenForLayout(ILayoutWidget layout, IWidget widget, List y1 = Math.max(y1, area.ry + area.height + padding.bottom() + margin.bottom()); } } else if (coverByDefaultSizeY) { - withDefaultH = Math.max(withDefaultH, child.getDefaultHeight() + margin.vertical() + padding.vertical()); + withDefaultH = Math.max(withDefaultH, + child.getDefaultHeight() + margin.vertical() + padding.vertical()); } } } @@ -398,7 +406,8 @@ protected void coverChildrenForLayout(ILayoutWidget layout, IWidget widget, List // if all children sizes depend on their parent, just use the min size as default w = this.x.getCoverChildrenMinSize(); } else { - GuiError.throwNew(getWidget(), GuiError.Type.SIZING, "Can't cover children width when all children depend on their parent and min size is 0!"); + GuiError.throwNew(getWidget(), GuiError.Type.SIZING, + "Can't cover children width when all children depend on their parent and min size is 0!"); return; } } @@ -407,7 +416,8 @@ protected void coverChildrenForLayout(ILayoutWidget layout, IWidget widget, List // if all children sizes depend on their parent, just use the min size as default h = this.y.getCoverChildrenMinSize(); } else { - GuiError.throwNew(getWidget(), GuiError.Type.SIZING, "Can't cover children height when all children depend on their parent and min size is 0!"); + GuiError.throwNew(getWidget(), GuiError.Type.SIZING, + "Can't cover children height when all children depend on their parent and min size is 0!"); return; } } diff --git a/src/main/java/brachy/modularui/widget/sizer/Unit.java b/src/main/java/brachy/modularui/widget/sizer/Unit.java index 3fc937b1..c00a84e0 100644 --- a/src/main/java/brachy/modularui/widget/sizer/Unit.java +++ b/src/main/java/brachy/modularui/widget/sizer/Unit.java @@ -4,8 +4,8 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import net.minecraft.util.StringRepresentable; -import com.mojang.serialization.Codec; +import com.mojang.serialization.Codec; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -179,7 +179,6 @@ public String getText(GuiAxis axis) { return axis.isHorizontal() ? this.xText : this.yText; } - @Override public @NotNull String getSerializedName() { return this.name; diff --git a/src/main/java/brachy/modularui/widgets/AbstractCycleButtonWidget.java b/src/main/java/brachy/modularui/widgets/AbstractCycleButtonWidget.java index 28471c35..49e1115a 100644 --- a/src/main/java/brachy/modularui/widgets/AbstractCycleButtonWidget.java +++ b/src/main/java/brachy/modularui/widgets/AbstractCycleButtonWidget.java @@ -27,14 +27,17 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; -public class AbstractCycleButtonWidget> extends SingleChildWidget implements Interactable { +public class AbstractCycleButtonWidget> extends SingleChildWidget + implements Interactable { private static final State[] EMPTY = new State[0]; - @Getter private int stateCount = 0; + @Getter + private int stateCount = 0; private boolean explicitStateCount = false; private boolean hasCount = false; - @Getter private IIntValue intValue; + @Getter + private IIntValue intValue; private int lastValue = -1; private State[] states = EMPTY; protected IWidget fallbackChild = null; @@ -81,7 +84,9 @@ public State getOrCreateState(int index) { updateStateCount(index + 1, false); if (this.stateCount <= index) { if (this.explicitStateCount) { - throw new IllegalArgumentException("Could not get state %d of widget %s. The state count was explicitly set to %d.".formatted(index, this, this.stateCount)); + throw new IllegalArgumentException( + "Could not get state %d of widget %s. The state count was explicitly set to %d." + .formatted(index, this, this.stateCount)); } throw new IllegalStateException("For some reason less states are available then expected."); } diff --git a/src/main/java/brachy/modularui/widgets/AbstractFluidDisplayWidget.java b/src/main/java/brachy/modularui/widgets/AbstractFluidDisplayWidget.java index b781516e..7777aaac 100644 --- a/src/main/java/brachy/modularui/widgets/AbstractFluidDisplayWidget.java +++ b/src/main/java/brachy/modularui/widgets/AbstractFluidDisplayWidget.java @@ -20,17 +20,21 @@ import lombok.Getter; import org.jetbrains.annotations.NotNull; -public abstract class AbstractFluidDisplayWidget> extends Widget implements IngredientProvider { +public abstract class AbstractFluidDisplayWidget> extends Widget + implements IngredientProvider { public static final String UNIT_BUCKET = "B"; public static final String UNIT_LITER = "L"; - @Getter private final Box contentPadding = new Box().all(1); + @Getter + private final Box contentPadding = new Box().all(1); private String unit = UNIT_BUCKET; - @Getter private SIPrefix baseUnitPrefix = SIPrefix.Milli; - @Getter private boolean flipLighterThanAir = true; - @Getter private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; - + @Getter + private SIPrefix baseUnitPrefix = SIPrefix.Milli; + @Getter + private boolean flipLighterThanAir = true; + @Getter + private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; protected AbstractFluidDisplayWidget() { size(18); @@ -63,11 +67,13 @@ public void drawOverlay(ModularGuiContext context, WidgetThemeEntry widgetThe super.drawOverlay(context, widgetTheme); FluidStack fluid = getFluidStack(); if (!fluid.isEmpty() && displayAmountText()) { - String s = NumberFormat.format(getBaseUnitAmount(fluid.getAmount()), NumberFormat.AMOUNT_TEXT) + getBaseUnit(); + String s = NumberFormat.format(getBaseUnitAmount(fluid.getAmount()), NumberFormat.AMOUNT_TEXT) + + getBaseUnit(); // mc doesn't consider the 1px border in item slots for amount text, but it looks weird when it touches the // left border, so we only apply padding there GuiDraw.drawScaledAlignedTextInBox(context, s, this.contentPadding.left() - 1, -1, - getArea().width - this.contentPadding.left(), getArea().height - this.contentPadding.bottom(), Alignment.BottomRight, + getArea().width - this.contentPadding.left(), getArea().height - this.contentPadding.bottom(), + Alignment.BottomRight, ModularUIConfig.FLUID_SLOT_TEXT_SCALE.get().floatValue(), 1f, 0.0f); } } diff --git a/src/main/java/brachy/modularui/widgets/ButtonWidget.java b/src/main/java/brachy/modularui/widgets/ButtonWidget.java index 96729b69..259fa4a2 100644 --- a/src/main/java/brachy/modularui/widgets/ButtonWidget.java +++ b/src/main/java/brachy/modularui/widgets/ButtonWidget.java @@ -29,8 +29,10 @@ public static ButtonWidget panelCloseButton() { }); } - @Getter private boolean playClickSound = true; - @Getter private Runnable clickSound; + @Getter + private boolean playClickSound = true; + @Getter + private Runnable clickSound; private IGuiAction.MousePressed mousePressed; private IGuiAction.MouseReleased mouseReleased; private IGuiAction.MousePressed mouseTapped; diff --git a/src/main/java/brachy/modularui/widgets/CategoryList.java b/src/main/java/brachy/modularui/widgets/CategoryList.java index e1f4e8c2..2a1e3567 100644 --- a/src/main/java/brachy/modularui/widgets/CategoryList.java +++ b/src/main/java/brachy/modularui/widgets/CategoryList.java @@ -20,7 +20,8 @@ public class CategoryList extends AbstractParentWidget implements Interactable, ILayoutWidget { private final List subCategories = new ArrayList<>(); - @Getter private boolean expanded = false; + @Getter + private boolean expanded = false; private int totalHeight = 0; private IDrawable expandedOverlay; private IDrawable collapsedOverlay; diff --git a/src/main/java/brachy/modularui/widgets/ColorPickerDialog.java b/src/main/java/brachy/modularui/widgets/ColorPickerDialog.java index 3f103f31..ca06ffde 100644 --- a/src/main/java/brachy/modularui/widgets/ColorPickerDialog.java +++ b/src/main/java/brachy/modularui/widgets/ColorPickerDialog.java @@ -21,16 +21,23 @@ public class ColorPickerDialog extends Dialog { private static final IDrawable handleBackground = new Rectangle().color(Color.WHITE.main); - @Getter private int color; - @Getter private int red; - @Getter private int green; - @Getter private int blue; - @Getter private double hue; - @Getter private double saturation; + @Getter + private int color; + @Getter + private int red; + @Getter + private int green; + @Getter + private int blue; + @Getter + private double hue; + @Getter + private double saturation; private double value; private int alpha; - @Getter private final boolean controlAlpha; + @Getter + private final boolean controlAlpha; private final Rectangle preview = new Rectangle(); private final Rectangle sliderBackgroundR = new Rectangle(); diff --git a/src/main/java/brachy/modularui/widgets/CycleButtonWidget.java b/src/main/java/brachy/modularui/widgets/CycleButtonWidget.java index 7174f806..2fe561c6 100755 --- a/src/main/java/brachy/modularui/widgets/CycleButtonWidget.java +++ b/src/main/java/brachy/modularui/widgets/CycleButtonWidget.java @@ -9,10 +9,12 @@ import java.util.function.Consumer; /** - * A button which cycles between multiple states by clicking on it. Background, overlay and tooltip can be supplied perstate. + * A button which cycles between multiple states by clicking on it. Background, overlay and tooltip can be supplied + * perstate. *

* Note that you need to set the amount of states before setting any state backgrounds etc. The state count is - * automatically set, if the passed {@link IIntValue} is a {@link IEnumValue IEnumValue} or a {@link IBoolValue IBoolValue}. + * automatically set, if the passed {@link IIntValue} is a {@link IEnumValue IEnumValue} or a {@link IBoolValue + * IBoolValue}. *

* * @see ToggleButton diff --git a/src/main/java/brachy/modularui/widgets/Expandable.java b/src/main/java/brachy/modularui/widgets/Expandable.java index 96f1e101..2c35a23a 100644 --- a/src/main/java/brachy/modularui/widgets/Expandable.java +++ b/src/main/java/brachy/modularui/widgets/Expandable.java @@ -23,16 +23,23 @@ public class Expandable extends Widget implements Interactable, IViewport { - @Getter private IWidget normalView = new EmptyWidget(); - @Getter private IWidget expandedView = new EmptyWidget(); + @Getter + private IWidget normalView = new EmptyWidget(); + @Getter + private IWidget expandedView = new EmptyWidget(); private final List children = Arrays.asList(normalView, expandedView); private List currentChildren = children; - @Getter private boolean expanded = false; + @Getter + private boolean expanded = false; private Area areaSnapshot; - @Getter private Animator animator; - @Getter private BiConsumer stencilTransform; - @Getter private int animationDuration = 300; - @Getter private IInterpolation interpolation = Interpolation.SINE_OUT; + @Getter + private Animator animator; + @Getter + private BiConsumer stencilTransform; + @Getter + private int animationDuration = 300; + @Getter + private IInterpolation interpolation = Interpolation.SINE_OUT; public Expandable() { coverChildren(); diff --git a/src/main/java/brachy/modularui/widgets/FluidDisplayWidget.java b/src/main/java/brachy/modularui/widgets/FluidDisplayWidget.java index 1c15a44e..6badd3db 100644 --- a/src/main/java/brachy/modularui/widgets/FluidDisplayWidget.java +++ b/src/main/java/brachy/modularui/widgets/FluidDisplayWidget.java @@ -15,9 +15,12 @@ public class FluidDisplayWidget extends AbstractFluidDisplayWidget { - @Getter private IValue value; - @Getter private int capacity = 0; - @Getter private boolean displayAmount = true; + @Getter + private IValue value; + @Getter + private int capacity = 0; + @Getter + private boolean displayAmount = true; @Override public boolean isValidSyncOrValue(@NotNull ISyncOrValue syncOrValue) { diff --git a/src/main/java/brachy/modularui/widgets/ItemDisplayWidget.java b/src/main/java/brachy/modularui/widgets/ItemDisplayWidget.java index ad63f075..eb289611 100644 --- a/src/main/java/brachy/modularui/widgets/ItemDisplayWidget.java +++ b/src/main/java/brachy/modularui/widgets/ItemDisplayWidget.java @@ -20,9 +20,12 @@ public class ItemDisplayWidget extends Widget implements IngredientProvider { - @Getter private IValue value; - @Getter private boolean displayAmount = false; - @Getter private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; + @Getter + private IValue value; + @Getter + private boolean displayAmount = false; + @Getter + private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; public ItemDisplayWidget() { size(18); diff --git a/src/main/java/brachy/modularui/widgets/ListWidget.java b/src/main/java/brachy/modularui/widgets/ListWidget.java index 374de678..b0e884f6 100644 --- a/src/main/java/brachy/modularui/widgets/ListWidget.java +++ b/src/main/java/brachy/modularui/widgets/ListWidget.java @@ -33,14 +33,19 @@ * @param type of this widget */ public class ListWidget> extends AbstractScrollWidget - implements ILayoutWidget, IParentWidget { + implements ILayoutWidget, IParentWidget { - @Getter private ScrollData scrollData; - @Getter private IIcon childSeparator; + @Getter + private ScrollData scrollData; + @Getter + private IIcon childSeparator; private final IntList separatorPositions = new IntArrayList(); - @Getter private boolean collapseDisabledChildren = true; - @Getter private boolean wrapTight = false; - @Getter private Alignment.CrossAxis crossAxisAlignment = Alignment.CrossAxis.CENTER; + @Getter + private boolean collapseDisabledChildren = true; + @Getter + private boolean wrapTight = false; + @Getter + private Alignment.CrossAxis crossAxisAlignment = Alignment.CrossAxis.CENTER; private Unit mainAxisMaxSize; /** * Whether the children list should be laid out in reverse. @@ -302,8 +307,10 @@ public W collapseDisabledChildren() { } /** - * Sets if disabled children should be collapsed. This means that if a child changes enabled state, this widget gets notified and - * re-layouts its children. Children which are disabled will not be considered during layout, so that the list will not appear to have + * Sets if disabled children should be collapsed. This means that if a child changes enabled state, this widget gets + * notified and + * re-layouts its children. Children which are disabled will not be considered during layout, so that the list will + * not appear to have * empty spots. This is enabled by default on lists. * * @param doCollapse true if disabled children should be collapsed. diff --git a/src/main/java/brachy/modularui/widgets/PageButton.java b/src/main/java/brachy/modularui/widgets/PageButton.java index 0fee754d..a84d6096 100755 --- a/src/main/java/brachy/modularui/widgets/PageButton.java +++ b/src/main/java/brachy/modularui/widgets/PageButton.java @@ -15,10 +15,12 @@ public class PageButton extends Widget implements Interactable { - @Getter private final int index; + @Getter + private final int index; private final PagedWidget.Controller controller; private IDrawable inactiveTexture = null; - @Getter private boolean invert = false; + @Getter + private boolean invert = false; public PageButton(int index, PagedWidget.Controller controller) { this.index = index; diff --git a/src/main/java/brachy/modularui/widgets/PagedWidget.java b/src/main/java/brachy/modularui/widgets/PagedWidget.java index 41280263..e07fe4e9 100755 --- a/src/main/java/brachy/modularui/widgets/PagedWidget.java +++ b/src/main/java/brachy/modularui/widgets/PagedWidget.java @@ -14,11 +14,15 @@ public class PagedWidget> extends Widget { - @Getter private final List pages = new ArrayList<>(); - @Getter private IWidget currentPage; - @Getter private int currentPageIndex = 0; - - @Nullable private IntConsumer onPageChange; + @Getter + private final List pages = new ArrayList<>(); + @Getter + private IWidget currentPage; + @Getter + private int currentPageIndex = 0; + + @Nullable + private IntConsumer onPageChange; @Override public void afterInit() { diff --git a/src/main/java/brachy/modularui/widgets/RichTextWidget.java b/src/main/java/brachy/modularui/widgets/RichTextWidget.java index 60d79280..58ea2698 100755 --- a/src/main/java/brachy/modularui/widgets/RichTextWidget.java +++ b/src/main/java/brachy/modularui/widgets/RichTextWidget.java @@ -21,7 +21,8 @@ public class RichTextWidget extends Widget implements IRichTextB private final RichText text = new RichText(); private Consumer builder; private boolean dirty = false; - @Getter private boolean autoUpdate = false; + @Getter + private boolean autoUpdate = false; public void markDirty() { this.dirty = true; @@ -43,7 +44,8 @@ public void draw(ModularGuiContext context, WidgetThemeEntry widgetTheme) { @Override public void drawForeground(ModularGuiContext context) { super.drawForeground(context); - if (!context.getUISettings().drawTooltipExternally() && getHoveredElement(context) instanceof IHoverable hoverable) { + if (!context.getUISettings().drawTooltipExternally() && + getHoveredElement(context) instanceof IHoverable hoverable) { hoverable.onHover(); RichTooltip tooltip = hoverable.getTooltip(); if (tooltip != null) { diff --git a/src/main/java/brachy/modularui/widgets/SchemaWidget.java b/src/main/java/brachy/modularui/widgets/SchemaWidget.java index 24db37ad..862fbbf5 100755 --- a/src/main/java/brachy/modularui/widgets/SchemaWidget.java +++ b/src/main/java/brachy/modularui/widgets/SchemaWidget.java @@ -11,8 +11,8 @@ import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; -import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.InputConstants; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.joml.Vector3f; @@ -20,14 +20,22 @@ public class SchemaWidget extends Widget implements Interactable { - @Getter private final BaseSchemaRenderer schemaRenderer; - @Getter private boolean enableRotation = true; - @Getter private boolean enableTranslation = true; - @Getter private boolean enableScaling = true; - @Getter private float scale = 10f; - @Getter private float pitch = MathUtils.PI_QUART; - @Getter private float yaw = 0; - @Getter private final Vector3f offset = new Vector3f(); + @Getter + private final BaseSchemaRenderer schemaRenderer; + @Getter + private boolean enableRotation = true; + @Getter + private boolean enableTranslation = true; + @Getter + private boolean enableScaling = true; + @Getter + private float scale = 10f; + @Getter + private float pitch = MathUtils.PI_QUART; + @Getter + private float yaw = 0; + @Getter + private final Vector3f offset = new Vector3f(); public SchemaWidget(ISchema schema) { this(new BaseSchemaRenderer(schema)); diff --git a/src/main/java/brachy/modularui/widgets/ScrollingTextWidget.java b/src/main/java/brachy/modularui/widgets/ScrollingTextWidget.java index 3fd0a578..cccd70a0 100755 --- a/src/main/java/brachy/modularui/widgets/ScrollingTextWidget.java +++ b/src/main/java/brachy/modularui/widgets/ScrollingTextWidget.java @@ -17,10 +17,14 @@ public class ScrollingTextWidget extends TextWidget { private TextRenderer.Line line; - @Getter private float progress = 0; - @Getter private IAnimator animator; - @Getter private Animator forward; - @Getter private Animator backward; + @Getter + private float progress = 0; + @Getter + private IAnimator animator; + @Getter + private Animator forward; + @Getter + private Animator backward; private int speed = 15; diff --git a/src/main/java/brachy/modularui/widgets/SliderWidget.java b/src/main/java/brachy/modularui/widgets/SliderWidget.java index 75b2b46c..180a5e4b 100644 --- a/src/main/java/brachy/modularui/widgets/SliderWidget.java +++ b/src/main/java/brachy/modularui/widgets/SliderWidget.java @@ -28,17 +28,25 @@ @Accessors(chain = true) public class SliderWidget extends Widget implements Interactable { - @Getter private IDoubleValue doubleValue; + @Getter + private IDoubleValue doubleValue; private IDrawable stopperDrawable = new Rectangle().color(Color.withAlpha(Color.WHITE.main, 0.4f)); private IDrawable handleDrawable = GuiTextures.BUTTON_CLEAN; - @Getter private GuiAxis axis = GuiAxis.X; - @Getter private DoubleList stopper; - @Getter private int stopperWidth = 2, stopperHeight = 4; + @Getter + private GuiAxis axis = GuiAxis.X; + @Getter + private DoubleList stopper; + @Getter + private int stopperWidth = 2, stopperHeight = 4; private final Unit sliderWidth = new Unit(), sliderHeight = new Unit(); - @Getter private final Area sliderArea = new Area(); - @Getter private double min, max; - @Getter private double each = 0; - @Getter private boolean dragging = false; + @Getter + private final Area sliderArea = new Area(); + @Getter + private double min, max; + @Getter + private double each = 0; + @Getter + private boolean dragging = false; private double cache = Double.MIN_VALUE; diff --git a/src/main/java/brachy/modularui/widgets/SlotGroupWidget.java b/src/main/java/brachy/modularui/widgets/SlotGroupWidget.java index 80b06578..8797d9e2 100644 --- a/src/main/java/brachy/modularui/widgets/SlotGroupWidget.java +++ b/src/main/java/brachy/modularui/widgets/SlotGroupWidget.java @@ -76,8 +76,10 @@ public static SlotGroupWidget rect(int w, int h, IntFunction slotCreato return slots.size(w * 18, h * 18); } - @Getter private String slotGroupName; - @Getter private SlotGroup slotGroup; + @Getter + private String slotGroupName; + @Getter + private SlotGroup slotGroup; private boolean sortButtonsAdded = false; private Consumer sortButtonsEditor; diff --git a/src/main/java/brachy/modularui/widgets/SortButtons.java b/src/main/java/brachy/modularui/widgets/SortButtons.java index 89a1e250..e9aec603 100644 --- a/src/main/java/brachy/modularui/widgets/SortButtons.java +++ b/src/main/java/brachy/modularui/widgets/SortButtons.java @@ -32,10 +32,13 @@ public class SortButtons extends Widget { // } } - @Getter private String slotGroupName; - @Getter private SlotGroup slotGroup; + @Getter + private String slotGroupName; + @Getter + private SlotGroup slotGroup; - @Getter private boolean horizontal = true; + @Getter + private boolean horizontal = true; private final ButtonWidget sortButton = new ButtonWidget<>(); private final ButtonWidget settingsButton = new ButtonWidget<>(); @Getter diff --git a/src/main/java/brachy/modularui/widgets/TextWidget.java b/src/main/java/brachy/modularui/widgets/TextWidget.java index f5e71b0b..081030a0 100644 --- a/src/main/java/brachy/modularui/widgets/TextWidget.java +++ b/src/main/java/brachy/modularui/widgets/TextWidget.java @@ -23,12 +23,18 @@ public class TextWidget> extends Widget { - @Getter private Component key; - @Getter private Alignment alignment = Alignment.CenterLeft; - @Getter private IntSupplier color = null; - @Getter private Boolean textShadow = null; - @Getter private float scale = 1f; - @Getter private int maxWidth = -1; + @Getter + private Component key; + @Getter + private Alignment alignment = Alignment.CenterLeft; + @Getter + private IntSupplier color = null; + @Getter + private Boolean textShadow = null; + @Getter + private float scale = 1f; + @Getter + private int maxWidth = -1; private String lastText; private @Nullable Supplier keySupplier; @@ -102,7 +108,8 @@ private TextRenderer simulate(float maxWidth) { renderer.setPos(padding.left(), padding.top()); renderer.setScale(this.scale); renderer.setSimulate(true); - // Don't update the key here, otherwise an infinite loop of checkComponentUpdated -> simulate -> checkComponentUpdated occurs + // Don't update the key here, otherwise an infinite loop of checkComponentUpdated -> simulate -> + // checkComponentUpdated occurs renderer.draw(null, this.key); renderer.setSimulate(false); return renderer; @@ -184,7 +191,7 @@ public W shadow(@Nullable Boolean shadow) { public W style(ChatFormatting formatting) { // TODO - //this.key.style(formatting); + // this.key.style(formatting); return getThis(); } diff --git a/src/main/java/brachy/modularui/widgets/ToggleButton.java b/src/main/java/brachy/modularui/widgets/ToggleButton.java index 759d7ef8..7c8ab5f0 100644 --- a/src/main/java/brachy/modularui/widgets/ToggleButton.java +++ b/src/main/java/brachy/modularui/widgets/ToggleButton.java @@ -9,7 +9,6 @@ import brachy.modularui.theme.SelectableTheme; import brachy.modularui.theme.WidgetTheme; import brachy.modularui.theme.WidgetThemeEntry; - import brachy.modularui.value.BoolValue; import lombok.Getter; @@ -54,7 +53,8 @@ public ToggleButton value(IBoolValue boolValue) { } public ToggleButton valueWrapped(IIntValue intValue, int trueValue) { - return value(new BoolValue.Dynamic(() -> intValue.getIntValue() == trueValue, v -> intValue.setIntValue(trueValue))); + return value( + new BoolValue.Dynamic(() -> intValue.getIntValue() == trueValue, v -> intValue.setIntValue(trueValue))); } public ToggleButton background(boolean selected, IDrawable drawable) { diff --git a/src/main/java/brachy/modularui/widgets/dynamic/DynamicHandler.java b/src/main/java/brachy/modularui/widgets/dynamic/DynamicHandler.java index aaec6bac..04f340b6 100644 --- a/src/main/java/brachy/modularui/widgets/dynamic/DynamicHandler.java +++ b/src/main/java/brachy/modularui/widgets/dynamic/DynamicHandler.java @@ -43,4 +43,3 @@ public DynamicHandler widgetProvider(Supplier widgetProvider) { return this; } } - diff --git a/src/main/java/brachy/modularui/widgets/dynamic/DynamicWidget.java b/src/main/java/brachy/modularui/widgets/dynamic/DynamicWidget.java index 207ee4fe..ec65561f 100644 --- a/src/main/java/brachy/modularui/widgets/dynamic/DynamicWidget.java +++ b/src/main/java/brachy/modularui/widgets/dynamic/DynamicWidget.java @@ -16,8 +16,10 @@ /** * A widget which can update its child based on a function in {@link DynamicSyncHandler}. * Such a sync handler must be supplied or else this widget has no effect. - * The dynamic child can be a widget tree of any size which can also contain {@link SyncHandler}s. These sync handlers MUST be registered - * via a variant of {@link brachy.modularui.value.sync.PanelSyncManager#getOrCreateSyncHandler(String, Class, Supplier)}. + * The dynamic child can be a widget tree of any size which can also contain {@link SyncHandler}s. These sync handlers + * MUST be registered + * via a variant of + * {@link brachy.modularui.value.sync.PanelSyncManager#getOrCreateSyncHandler(String, Class, Supplier)}. * * @param type of this widget */ diff --git a/src/main/java/brachy/modularui/widgets/layout/Flow.java b/src/main/java/brachy/modularui/widgets/layout/Flow.java index 905f72a6..2401f3de 100644 --- a/src/main/java/brachy/modularui/widgets/layout/Flow.java +++ b/src/main/java/brachy/modularui/widgets/layout/Flow.java @@ -35,30 +35,38 @@ public static Flow col() { /** * The main axis on which to align children. */ - @Getter private final GuiAxis axis; + @Getter + private final GuiAxis axis; /** * How the children should be laid out on the main axis. */ - @Getter private Alignment.MainAxis mainAxisAlignment = Alignment.MainAxis.START; + @Getter + private Alignment.MainAxis mainAxisAlignment = Alignment.MainAxis.START; /** * How the children should be laid out on the cross axis. */ - @Getter private Alignment.CrossAxis crossAxisAlignment = Alignment.CrossAxis.CENTER; + @Getter + private Alignment.CrossAxis crossAxisAlignment = Alignment.CrossAxis.CENTER; /** * Additional space between each child on main axis. * Does not work with {@link Alignment.MainAxis#SPACE_BETWEEN} and {@link Alignment.MainAxis#SPACE_AROUND}. */ - @Getter private int childPadding = 0; - @Getter private int crossAxisChildPadding = 0; + @Getter + private int childPadding = 0; + @Getter + private int crossAxisChildPadding = 0; /** * Whether disabled child widgets should be collapsed for display. */ - @Getter private boolean collapseDisabledChildren = false; + @Getter + private boolean collapseDisabledChildren = false; /** * Whether the children list should be laid out in reverse order */ - @Getter private boolean reverseLayout = false; - @Getter private boolean wrap = false; + @Getter + private boolean reverseLayout = false; + @Getter + private boolean wrap = false; private final List ignoredWidgets = new ArrayList<>(); private final List layoutWidgets = new ArrayList<>(); diff --git a/src/main/java/brachy/modularui/widgets/layout/Grid.java b/src/main/java/brachy/modularui/widgets/layout/Grid.java index 84a2856c..8bf30622 100755 --- a/src/main/java/brachy/modularui/widgets/layout/Grid.java +++ b/src/main/java/brachy/modularui/widgets/layout/Grid.java @@ -28,11 +28,15 @@ public class Grid extends AbstractScrollWidget implements ILayoutWidget, IParentWidget { private final List> matrix = new ArrayList<>(); - @Getter private final Box minElementMargin = new Box(); - @Getter private int minRowHeight = 5, minColWidth = 5; - @Getter private Alignment alignment = Alignment.Center; + @Getter + private final Box minElementMargin = new Box(); + @Getter + private int minRowHeight = 5, minColWidth = 5; + @Getter + private Alignment alignment = Alignment.Center; private boolean dirty = false, unsanitized = false; - @Getter private boolean collapseDisabledChildren = false; + @Getter + private boolean collapseDisabledChildren = false; public Grid() { super(null, null); @@ -353,7 +357,8 @@ public Grid collapseDisabledChildren() { * * @param width number of elements in each row * @param height number of elements in each column - * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). Can return null. + * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). + * Can return null. * @return this */ public Grid gridOfWidthHeight(int width, int height, GridPosMapper widgetCreator) { @@ -365,7 +370,8 @@ public Grid gridOfWidthHeight(int width, int height, GridPos * * @param size total number of elements (width * height) * @param height number of elements in each column - * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). Can return null. + * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). + * Can return null. * @return this */ public Grid gridOfSizeHeight(int size, int height, GridPosMapper widgetCreator) { @@ -377,7 +383,8 @@ public Grid gridOfSizeHeight(int size, int height, GridPosMa * * @param size total number of elements (width * height) * @param width number of elements in each row - * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). Can return null. + * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). + * Can return null. * @return this */ public Grid gridOfSizeWidth(int size, int width, GridPosMapper widgetCreator) { @@ -388,12 +395,14 @@ public Grid gridOfSizeWidth(int size, int width, GridPosMapp * Creates a grid of widgets with a given grid of any type. * * @param matrix elements of any type - * @param widgetCreator A mapper to map each element to a widget. The arguments are (xIndex, yIndex, totalIndex, element). Can return null. + * @param widgetCreator A mapper to map each element to a widget. The arguments are (xIndex, yIndex, totalIndex, + * element). Can return null. * @param type of elements * @param widget type * @return this */ - public Grid gridOfElements(Iterable> matrix, GridPosElementMapper widgetCreator) { + public Grid gridOfElements(Iterable> matrix, + GridPosElementMapper widgetCreator) { return grid(createGridOfElements(matrix, widgetCreator)); } @@ -414,16 +423,19 @@ public Grid gridOf(int width, Iterable list) { * * @param width number of elements in each row * @param list elements of any type - * @param widgetCreator A mapper to map each element to a widget. The arguments are (xIndex, yIndex, listIndex, element). Can return null. + * @param widgetCreator A mapper to map each element to a widget. The arguments are (xIndex, yIndex, listIndex, + * element). Can return null. * @param type of elements * @param widget type * @return this */ - public Grid gridOfWidthElements(int width, Iterable list, GridPosElementMapper widgetCreator) { + public Grid gridOfWidthElements(int width, Iterable list, + GridPosElementMapper widgetCreator) { return grid(createGridOfWidthElements(width, list, widgetCreator)); } - public static List> createGridOfElements(Iterable> matrix, GridPosElementMapper widgetCreator) { + public static List> createGridOfElements(Iterable> matrix, + GridPosElementMapper widgetCreator) { List> widgetMatrix = new ArrayList<>(); Iterator> colIt = matrix.iterator(); int r = 0, i = 0; @@ -442,7 +454,9 @@ public static List> createGridOfElements(Iterable return widgetMatrix; } - public static List> createGridOfWidthElements(int width, Iterable list, GridPosElementMapper widgetCreator) { + public static List> createGridOfWidthElements(int width, Iterable list, + GridPosElementMapper widgetCreator) { width = Math.max(width, 1); List> widgetMatrix = new ArrayList<>(); Iterator it = list.iterator(); @@ -462,7 +476,8 @@ public static List> createGridOfWidthElements(int return widgetMatrix; } - public static List> createGridOfWidthHeight(int width, int height, GridPosMapper widgetCreator) { + public static List> createGridOfWidthHeight(int width, int height, + GridPosMapper widgetCreator) { height = Math.max(height, 1); width = Math.max(width, 1); List> matrix = new ArrayList<>(); @@ -476,11 +491,13 @@ public static List> createGridOfWidthHeight(int widt return matrix; } - public static List> createGridOfSizeHeight(int size, int height, GridPosMapper widgetCreator) { + public static List> createGridOfSizeHeight(int size, int height, + GridPosMapper widgetCreator) { return createGridOfWidthHeight(calcSize(size, height), height, widgetCreator); } - public static List> createGridOfSizeWidth(int size, int width, GridPosMapper widgetCreator) { + public static List> createGridOfSizeWidth(int size, int width, + GridPosMapper widgetCreator) { return createGridOfWidthHeight(width, calcSize(size, width), widgetCreator); } @@ -489,7 +506,8 @@ private static int calcSize(int totalSize, int otherSize) { } /** - * Ensures that every row in the matrix has the same size by appending null values to rows with fewer elements than the longest row. + * Ensures that every row in the matrix has the same size by appending null values to rows with fewer elements than + * the longest row. */ private void sanitizeMatrix() { if (!this.unsanitized) return; @@ -509,7 +527,8 @@ private static void foreachRow(Iterable row, Consumer consumer row.forEach(consumer); } - private static void foreachGrid(Iterable> grid, Consumer consumer) { + private static void foreachGrid(Iterable> grid, + Consumer consumer) { for (Iterable row : grid) { row.forEach(consumer); } diff --git a/src/main/java/brachy/modularui/widgets/menu/AbstractMenuButton.java b/src/main/java/brachy/modularui/widgets/menu/AbstractMenuButton.java index e585c880..82fbbce7 100644 --- a/src/main/java/brachy/modularui/widgets/menu/AbstractMenuButton.java +++ b/src/main/java/brachy/modularui/widgets/menu/AbstractMenuButton.java @@ -29,7 +29,8 @@ * * @param type of this widget */ -public abstract class AbstractMenuButton> extends Widget implements IMenuPart, Interactable { +public abstract class AbstractMenuButton> extends Widget + implements IMenuPart, Interactable { /** * The general direction where the menu will be opened. This is just a shortcut to standard resizer calls. @@ -53,11 +54,13 @@ public abstract class AbstractMenuButton> extend /** * true if the menu is currently open (soft or hard) */ - @Getter private boolean open; + @Getter + private boolean open; /** * true if the menu is currently soft open (opened by hovering) */ - @Getter private boolean softOpen; // state, soft means opened by hovering + @Getter + private boolean softOpen; // state, soft means opened by hovering private IPanelHandler panelHandler; private final String panelName; diff --git a/src/main/java/brachy/modularui/widgets/menu/MenuPanel.java b/src/main/java/brachy/modularui/widgets/menu/MenuPanel.java index cbe6cf52..902d2854 100644 --- a/src/main/java/brachy/modularui/widgets/menu/MenuPanel.java +++ b/src/main/java/brachy/modularui/widgets/menu/MenuPanel.java @@ -45,7 +45,7 @@ public boolean closeOnOutOfBoundsClick() { return true; } - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public void closeAllMenus(boolean soft, boolean requireNoHover) { // need to collect menus first instead of closing while iterating to avoid CME List menus = WidgetTree.flatListByType(this, Menu.class); diff --git a/src/main/java/brachy/modularui/widgets/slot/CraftingContainerWrapper.java b/src/main/java/brachy/modularui/widgets/slot/CraftingContainerWrapper.java index 20507800..44d6b9d4 100755 --- a/src/main/java/brachy/modularui/widgets/slot/CraftingContainerWrapper.java +++ b/src/main/java/brachy/modularui/widgets/slot/CraftingContainerWrapper.java @@ -14,7 +14,8 @@ /** * A crafting inventory that wraps a {@link IItemHandlerModifiable}. * This inventory creates a content list which is used here to detect changes from the item handler. - * This is required as interacting with a slot will update the content, but will not notify the container to check for new recipes. + * This is required as interacting with a slot will update the content, but will not notify the container to check for + * new recipes. */ public class CraftingContainerWrapper extends TransientCraftingContainer { diff --git a/src/main/java/brachy/modularui/widgets/slot/FluidSlot.java b/src/main/java/brachy/modularui/widgets/slot/FluidSlot.java index 62201c58..da52fa0b 100644 --- a/src/main/java/brachy/modularui/widgets/slot/FluidSlot.java +++ b/src/main/java/brachy/modularui/widgets/slot/FluidSlot.java @@ -12,9 +12,9 @@ import brachy.modularui.screen.viewport.ModularGuiContext; import brachy.modularui.theme.SlotTheme; import brachy.modularui.theme.WidgetThemeEntry; +import brachy.modularui.utils.MouseData; import brachy.modularui.utils.handlers.fluid.EmptyFluidTank; import brachy.modularui.utils.handlers.fluid.IMultiTankFluidHandler; -import brachy.modularui.utils.MouseData; import brachy.modularui.value.sync.FluidSlotSyncHandler; import brachy.modularui.widgets.AbstractFluidDisplayWidget; @@ -24,14 +24,14 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; -import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraftforge.common.SoundActions; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidTank; import net.minecraftforge.fml.ModList; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -39,7 +39,7 @@ import java.text.DecimalFormat; public class FluidSlot extends AbstractFluidDisplayWidget - implements Interactable, GhostIngredientSlot, IngredientProvider { + implements Interactable, GhostIngredientSlot, IngredientProvider { public static final int DEFAULT_SIZE = 18; public static final String UNIT_BUCKET = "B"; @@ -53,7 +53,8 @@ public class FluidSlot extends AbstractFluidDisplayWidget private FluidSlotSyncHandler syncHandler; - @Getter private boolean alwaysShowFull = true; + @Getter + private boolean alwaysShowFull = true; public FluidSlot() { tooltip().autoUpdate(true); @@ -188,7 +189,8 @@ public Result onMousePressed(int button) { } ItemStack cursorStack = MCHelper.getPlayer().containerMenu.getCarried(); if (this.syncHandler.phantom() || - (!cursorStack.isEmpty() && cursorStack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM, null).isPresent())) { + (!cursorStack.isEmpty() && + cursorStack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM, null).isPresent())) { MouseData mouseData = MouseData.create(button); this.syncHandler.syncToServer(FluidSlotSyncHandler.SYNC_CLICK, mouseData::writeToPacket); } diff --git a/src/main/java/brachy/modularui/widgets/slot/IOnSlotChanged.java b/src/main/java/brachy/modularui/widgets/slot/IOnSlotChanged.java index 67fff989..67e752e8 100755 --- a/src/main/java/brachy/modularui/widgets/slot/IOnSlotChanged.java +++ b/src/main/java/brachy/modularui/widgets/slot/IOnSlotChanged.java @@ -12,11 +12,11 @@ public interface IOnSlotChanged { /** * Called when an item stack in a {@link ModularSlot} changes. * - * @param oldStack the previous item in the slot - * @param newStack the item that is now in the slot - * @param client true if this function is currently called on client side - * @param init if this is the first sync call after opening the GUI. Doe not necessarily that this slot - * changed + * @param oldStack the previous item in the slot + * @param newStack the item that is now in the slot + * @param client true if this function is currently called on client side + * @param init if this is the first sync call after opening the GUI. Doe not necessarily that this slot + * changed */ void onChange(ItemStack oldStack, ItemStack newStack, boolean client, boolean init); } diff --git a/src/main/java/brachy/modularui/widgets/slot/ItemSlot.java b/src/main/java/brachy/modularui/widgets/slot/ItemSlot.java index d0b759f0..863303ff 100644 --- a/src/main/java/brachy/modularui/widgets/slot/ItemSlot.java +++ b/src/main/java/brachy/modularui/widgets/slot/ItemSlot.java @@ -25,12 +25,12 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.items.IItemHandlerModifiable; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import lombok.Setter; import org.jetbrains.annotations.NotNull; @@ -42,7 +42,8 @@ public class ItemSlot extends Widget implements IVanillaSlot, Interact public static final int SIZE = 18; - @Getter private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; + @Getter + private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; public static ItemSlot create(boolean phantom) { return phantom ? new PhantomItemSlot() : new ItemSlot(); @@ -113,7 +114,8 @@ protected void drawOverlay(ModularGuiContext context) { @Override public void drawForeground(ModularGuiContext context) { RichTooltip tooltip = getTooltip(); - if (tooltip != null && !context.getUISettings().drawTooltipExternally() && isHoveringFor(tooltip.showUpTimer())) { + if (tooltip != null && !context.getUISettings().drawTooltipExternally() && + isHoveringFor(tooltip.showUpTimer())) { tooltip.draw(context, getSlot().getItem()); } } @@ -238,7 +240,8 @@ private void drawSlot(ModularGuiContext context, ModularSlot slot) { String format = null; if (!getSyncHandler().isPhantom()) { - if (slot == acc.getClickedSlot() && !acc.getDraggingItem().isEmpty() && acc.getIsSplittingStack() && !slotStack.isEmpty()) { + if (slot == acc.getClickedSlot() && !acc.getDraggingItem().isEmpty() && acc.getIsSplittingStack() && + !slotStack.isEmpty()) { slotStack = slotStack.copy(); slotStack.setCount(slotStack.getCount() / 2); } else if (acc.getIsQuickCrafting() && acc.getQuickCraftSlots().contains(slot) && !carried.isEmpty()) { @@ -246,13 +249,15 @@ private void drawSlot(ModularGuiContext context, ModularSlot slot) { return; } - if (AbstractContainerMenu.canItemQuickReplace(slot, carried, true) && getScreen().getContainer().canDragTo(slot)) { + if (AbstractContainerMenu.canItemQuickReplace(slot, carried, true) && + getScreen().getContainer().canDragTo(slot)) { slotStack = carried.copy(); isDragPreview = true; int maxSize = Math.min(slotStack.getMaxStackSize(), slot.getMaxStackSize(slotStack)); amount = slot.getItem().getCount(); - amount += AbstractContainerMenu.getQuickCraftPlaceCount(acc.getQuickCraftSlots(), acc.getQuickCraftingType(), slotStack); + amount += AbstractContainerMenu.getQuickCraftPlaceCount(acc.getQuickCraftSlots(), + acc.getQuickCraftingType(), slotStack); if (amount > maxSize) { amount = maxSize; format = ChatFormatting.YELLOW.toString(); diff --git a/src/main/java/brachy/modularui/widgets/slot/ModularCraftingSlot.java b/src/main/java/brachy/modularui/widgets/slot/ModularCraftingSlot.java index e8d3f19f..23b3fb6f 100755 --- a/src/main/java/brachy/modularui/widgets/slot/ModularCraftingSlot.java +++ b/src/main/java/brachy/modularui/widgets/slot/ModularCraftingSlot.java @@ -24,9 +24,11 @@ /** * An output slot for crafting recipes for modular UIs. For input slots use regular {@link ModularSlot ModularSlots}. * The implementation is mostly copied from {@link net.minecraft.world.inventory.ResultSlot ResultSlot}. - * To use this, you must call {@link #inputInventory(IItemHandlerModifiable, int)} or {@link #inputInventory(IItemHandlerModifiable)}. + * To use this, you must call {@link #inputInventory(IItemHandlerModifiable, int)} or + * {@link #inputInventory(IItemHandlerModifiable)}. * If the grid has any other size than 3x3, you also need to call {@link #gridSize(int, int)}. - * It is required that all input slots use the same {@link IItemHandlerModifiable}. Additionally, all input slots and this output slot, MUST + * It is required that all input slots use the same {@link IItemHandlerModifiable}. Additionally, all input slots and + * this output slot, MUST * be in the same slot group. */ @SuppressWarnings("unused") @@ -61,7 +63,8 @@ public ModularCraftingSlot gridSize(int columns, int rows) { } /** - * Mandatory setter for the input inventory. The input inventory must contain the slot indices consecutively from left to right, + * Mandatory setter for the input inventory. The input inventory must contain the slot indices consecutively from + * left to right, * top to bottom. For a 3x3 grid it would look like this: *

* 0 1 2
@@ -78,7 +81,8 @@ public ModularCraftingSlot inputInventory(IItemHandlerModifiable inputInventory) } /** - * Mandatory setter for the input inventory. The input inventory must contain the slot indices consecutively from left to right, + * Mandatory setter for the input inventory. The input inventory must contain the slot indices consecutively from + * left to right, * top to bottom. For a 3x3 grid with starting index 0 it would look like this: *

* 0 1 2
@@ -101,10 +105,12 @@ public ModularCraftingSlot inputInventory(IItemHandlerModifiable inputInventory, public CraftingContainerWrapper getCraftSlots() { if (this.craftSlots == null) { if (this.inputInventory == null) { - throw new IllegalStateException("The crafting inventory of the crafting slot has not been initialised. " + - "Call inputInventory() with appropriate arguments and optionally gridSize()."); + throw new IllegalStateException( + "The crafting inventory of the crafting slot has not been initialised. " + + "Call inputInventory() with appropriate arguments and optionally gridSize()."); } - this.craftSlots = new CraftingContainerWrapper(this, this.cols, this.rows, this.inputInventory, this.inputStartIndex); + this.craftSlots = new CraftingContainerWrapper(this, this.cols, this.rows, this.inputInventory, + this.inputStartIndex); } return this.craftSlots; } diff --git a/src/main/java/brachy/modularui/widgets/slot/ModularSlot.java b/src/main/java/brachy/modularui/widgets/slot/ModularSlot.java index 016f106e..12e7ab82 100644 --- a/src/main/java/brachy/modularui/widgets/slot/ModularSlot.java +++ b/src/main/java/brachy/modularui/widgets/slot/ModularSlot.java @@ -1,7 +1,7 @@ package brachy.modularui.widgets.slot; -import brachy.modularui.core.mixins.common.SlotAccessor; import brachy.modularui.core.mixins.common.CombinedInvWrapperAccessor; +import brachy.modularui.core.mixins.common.SlotAccessor; import brachy.modularui.value.sync.ItemSlotSyncHandler; import net.minecraft.resources.ResourceLocation; @@ -9,7 +9,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.datafixers.util.Pair; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.SlotItemHandler; @@ -18,6 +17,7 @@ import net.minecraftforge.items.wrapper.PlayerMainInvWrapper; import net.minecraftforge.items.wrapper.PlayerOffhandInvWrapper; +import com.mojang.datafixers.util.Pair; import lombok.Getter; import lombok.Setter; import org.jetbrains.annotations.ApiStatus; @@ -39,10 +39,12 @@ public class ModularSlot extends SlotItemHandler { slot -> Objects.requireNonNull(slot.getSlotGroup()).getShiftClickPriority()); @Getter - @Setter(onMethod_ = {@ApiStatus.Internal}) + @Setter(onMethod_ = { @ApiStatus.Internal }) private boolean enabled = true; - @Getter private boolean canTake = true, canPut = true, canDragInto = true; - @Getter private Predicate filter = stack -> true; + @Getter + private boolean canTake = true, canPut = true, canDragInto = true; + @Getter + private Predicate filter = stack -> true; private IOnSlotChanged changeListener = IOnSlotChanged.DEFAULT; @Getter private boolean ignoreMaxStackSize = false; @@ -176,7 +178,8 @@ protected Player getPlayer() { @Override public boolean isSameInventory(@NotNull Slot other) { - return other instanceof SlotItemHandler slotItemHandler && slotItemHandler.getItemHandler() == this.getItemHandler(); + return other instanceof SlotItemHandler slotItemHandler && + slotItemHandler.getItemHandler() == this.getItemHandler(); } /** diff --git a/src/main/java/brachy/modularui/widgets/textfield/BaseTextFieldWidget.java b/src/main/java/brachy/modularui/widgets/textfield/BaseTextFieldWidget.java index 3aad273e..00b42eed 100644 --- a/src/main/java/brachy/modularui/widgets/textfield/BaseTextFieldWidget.java +++ b/src/main/java/brachy/modularui/widgets/textfield/BaseTextFieldWidget.java @@ -17,8 +17,8 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; -import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.InputConstants; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.lwjgl.glfw.GLFW; @@ -33,7 +33,7 @@ * The base of a text input widget. Handles mouse/InputConstants input and rendering. */ public class BaseTextFieldWidget> extends AbstractScrollWidget - implements IFocusedWidget { + implements IFocusedWidget { public static final DecimalFormat format = new DecimalFormat("###.###"); @@ -57,15 +57,21 @@ public class BaseTextFieldWidget> extends Abstr @Getter protected List lastText; protected int scrollOffset = 0; - @Getter protected float scale = 1f; - @Getter protected boolean focusOnGuiOpen; + @Getter + protected float scale = 1f; + @Getter + protected boolean focusOnGuiOpen; private int cursorTimer; protected long lastClickTime = 0; - @Getter protected Integer textColor; - @Getter protected Integer markedColor; - @Getter protected Component hintText = null; - @Getter protected Integer hintTextColor; + @Getter + protected Integer textColor; + @Getter + protected Integer markedColor; + @Getter + protected Component hintText = null; + @Getter + protected Integer hintTextColor; public BaseTextFieldWidget() { super(new HorizontalScrollData(false, 4), null); diff --git a/src/main/java/brachy/modularui/widgets/textfield/TextFieldRenderer.java b/src/main/java/brachy/modularui/widgets/textfield/TextFieldRenderer.java index a7a7473d..a09b4e02 100755 --- a/src/main/java/brachy/modularui/widgets/textfield/TextFieldRenderer.java +++ b/src/main/java/brachy/modularui/widgets/textfield/TextFieldRenderer.java @@ -9,10 +9,10 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.util.FormattedCharSequence; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Setter; import org.apache.commons.lang3.mutable.MutableFloat; import org.apache.commons.lang3.mutable.MutableInt; diff --git a/src/main/java/brachy/modularui/widgets/textfield/TextFieldWidget.java b/src/main/java/brachy/modularui/widgets/textfield/TextFieldWidget.java index 0ea4f9c3..9994454e 100644 --- a/src/main/java/brachy/modularui/widgets/textfield/TextFieldWidget.java +++ b/src/main/java/brachy/modularui/widgets/textfield/TextFieldWidget.java @@ -39,14 +39,21 @@ @Accessors(chain = true) public class TextFieldWidget extends BaseTextFieldWidget { - @Getter private IStringValue stringValue; + @Getter + private IStringValue stringValue; private Function validator = val -> val; - @Getter private boolean numbers = false; - @Getter private String mathFailMessage = null; - @Getter private double defaultNumber = 0; - @Getter private boolean tooltipOverride = false; - @Getter private boolean autoUpdateOnChange = false; - @Getter private boolean acceptsExpression = true; + @Getter + private boolean numbers = false; + @Getter + private String mathFailMessage = null; + @Getter + private double defaultNumber = 0; + @Getter + private boolean tooltipOverride = false; + @Getter + private boolean autoUpdateOnChange = false; + @Getter + private boolean acceptsExpression = true; public double parse(String num) { if (!this.acceptsExpression) { @@ -115,7 +122,8 @@ public void onUpdate() { @Override public void drawForeground(ModularGuiContext context) { if (hasTooltip() && !context.getUISettings().drawTooltipExternally() && - (tooltipOverride || getScrollData().isScrollBarActive(getScrollArea())) && isHoveringFor(getTooltip().showUpTimer())) { + (tooltipOverride || getScrollData().isScrollBarActive(getScrollArea())) && + isHoveringFor(getTooltip().showUpTimer())) { getTooltip().draw(getContext()); } } @@ -159,7 +167,8 @@ protected void onTextChanged() { super.onTextChanged(); if (this.autoUpdateOnChange) { String text = this.validator.apply(getText()); - this.stringValue.setStringValue(this.numbers ? format.parse(text, new ParsePosition(0)).toString() : getText()); + this.stringValue + .setStringValue(this.numbers ? format.parse(text, new ParsePosition(0)).toString() : getText()); } } diff --git a/src/test/java/brachy/modularui/CodecTest.java b/src/test/java/brachy/modularui/CodecTest.java index b96d9ef1..b01d18d1 100644 --- a/src/test/java/brachy/modularui/CodecTest.java +++ b/src/test/java/brachy/modularui/CodecTest.java @@ -17,12 +17,11 @@ import brachy.modularui.widget.Widget; import brachy.modularui.widget.sizer.StandardResizer; -import com.mojang.serialization.Codec; -import com.mojang.serialization.JsonOps; - import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.serialization.Codec; +import com.mojang.serialization.JsonOps; import org.junit.jupiter.api.Test; import java.util.Objects; @@ -37,7 +36,7 @@ public class CodecTest { // TODO fix tests that attempt to load the mc server - //@Test + // @Test void resizer() { TestUtil.bootstrap(); widgetTest(new Widget<>() @@ -52,13 +51,14 @@ void resizer() { .decoration()); } - //@Test + // @Test void drawable() { TestUtil.bootstrap(); drawableTest(IDrawable.EMPTY); drawableTest(IDrawable.NONE); decodeTest(new JsonPrimitive("null"), IDrawable.CODEC, IDrawable.EMPTY); - drawableTest(IDrawable.of(new Rectangle().color(Color.GREEN.main), GuiTextures.BOOKMARK, new Circle().color(Color.RED.main, Color.BLUE.main))); + drawableTest(IDrawable.of(new Rectangle().color(Color.GREEN.main), GuiTextures.BOOKMARK, + new Circle().color(Color.RED.main, Color.BLUE.main))); } @Test @@ -66,7 +66,8 @@ void text() { // NOTE: integer colors do not work properly when they have an alpha value due to a Minecraft bug. // I fixed this in TextColorMixin, but mixins are not applied in testing. test(ModularComponent.CODEC.mutableCodec(), Text.str("Hello"), false); - test(ModularComponent.CODEC.mutableCodec(), Text.str("World").style(Text.UNDERLINE).color(Color.withAlpha(Color.GREEN.main, 0)), false); + test(ModularComponent.CODEC.mutableCodec(), + Text.str("World").style(Text.UNDERLINE).color(Color.withAlpha(Color.GREEN.main, 0)), false); test(ModularComponent.CODEC.mutableCodec(), Text.comp( Text.str("Hello ").color(Color.withAlpha(Color.BLUE.main, 0)), Text.lang("World").scale(1.5f)).alignment(Alignment.BottomCenter), false); @@ -99,10 +100,11 @@ void color() { TestUtil.repeatRnd(10, CodecTest::testColorCMYK); } - //@Test + // @Test void widgetTheme() { TestUtil.bootstrap(); - test(IThemeApi.FALLBACK.getCodec().codec(), WidgetTheme.darkTextNoShadow(1, 2, GuiTextures.MENU_BACKGROUND), false); + test(IThemeApi.FALLBACK.getCodec().codec(), WidgetTheme.darkTextNoShadow(1, 2, GuiTextures.MENU_BACKGROUND), + false); } private static void testColorHex(Random rnd) { diff --git a/src/test/java/brachy/modularui/ColorTest.java b/src/test/java/brachy/modularui/ColorTest.java index 036bf623..70803a83 100644 --- a/src/test/java/brachy/modularui/ColorTest.java +++ b/src/test/java/brachy/modularui/ColorTest.java @@ -7,8 +7,8 @@ import java.util.Arrays; -import static org.junit.jupiter.api.AssertionFailureBuilder.assertionFailure; import static brachy.modularui.utils.Color.*; +import static org.junit.jupiter.api.AssertionFailureBuilder.assertionFailure; public class ColorTest { @@ -86,7 +86,8 @@ static void assertColor(int c1, int c2, int tolerance, String extraMsg) { throw assertionFailure() .expected(Arrays.toString(Color.getARGBValues(c1))) .actual(Arrays.toString(Color.getARGBValues(c2))) - .reason("Color components differ by " + Color.getLargestDiff(c1, c2) + ", but only " + tolerance + " is allowed. ") + .reason("Color components differ by " + Color.getLargestDiff(c1, c2) + ", but only " + tolerance + + " is allowed. ") .message(extraMsg) .build(); }