diff --git a/README.md b/README.md index 5100a22c6..3e2c92e7e 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Find our backup matrix space at [\#lambda-client:matrix.org](https://app.element ### Sophisticated User Experience * **Fine-Grained Control:** Access over **1000+ settings**, allowing you to tune every aspect of the client to your exact needs. -* **Advanced GUI:** The **Dear ImGui** interface is designed for clarity and depth, featuring quick search, context menus, and easy keybind editing. +* **Advanced GUI:** The **Jetpack Compose** interface is designed for clarity and depth, featuring quick search, context menus, and easy keybind editing. * **Automation Profiles:** Use linkable configs to apply complex configurations across multiple modules instantly. ### Stability & Safety diff --git a/build.gradle.kts b/build.gradle.kts index f96218fba..648e8c584 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -32,11 +32,14 @@ val kotlinVersion: String by project val ktorVersion: String by project val jacksonVersion: String by project val mockkVersion: String by project -val spairVersion: String by project val lwjglVersion: String by project val sodiumVersion: String by project val litematicaVersion: String by project val maLiLibVersion: String by project +val composeVersion: String by project +val skikoVersion: String by project + +val skikoPlatforms = listOf("windows-x64", "windows-arm64", "linux-x64", "linux-arm64", "macos-x64", "macos-arm64") val libs = file("libs") val targets = listOf("fabric.mod.json") @@ -46,6 +49,7 @@ val replacements = file("gradle.properties").inputStream().use { stream -> plugins { kotlin("jvm") version "2.3.21" + kotlin("plugin.compose") version "2.3.21" id("org.jetbrains.dokka") version "2.1.0" id("fabric-loom") version "1.17-SNAPSHOT" id("com.gradleup.shadow") version "9.3.0" @@ -72,6 +76,9 @@ configurations.all { if (requested.group == "org.lwjgl") { useVersion(lwjglVersion) } + if (requested.group == "org.jetbrains.skiko") { + useVersion(skikoVersion) + } } } @@ -81,6 +88,7 @@ repositories { maven("https://maven.2b2t.vc/releases") // Baritone maven("https://jitpack.io") // KDiscordIPC maven("https://api.modrinth.com/maven") + google() mavenCentral() // Allow the use of local libraries @@ -169,11 +177,19 @@ dependencies { includeLib("com.github.beanbag44:KDiscordIPC:$discordIPCVersion") includeLib("com.pngencoder:pngencoder:$pngEncoderVersion") - includeLib("com.lambda:lambda-imgui-java-binding:$spairVersion") - includeLib("com.lambda:lambda-imgui-java-lwjgl3:$spairVersion") - includeLib("com.lambda:lambda-imgui-java-natives-windows:$spairVersion") - includeLib("com.lambda:lambda-imgui-java-natives-linux:$spairVersion") - includeLib("com.lambda:lambda-imgui-java-natives-macos:$spairVersion") + + listOf("runtime:runtime", "ui:ui", "foundation:foundation").forEach { module -> + shadowLib("org.jetbrains.compose.$module-desktop:$composeVersion") { + exclude(group = "org.jetbrains.kotlin") + exclude(group = "org.jetbrains.kotlinx") + } + } + skikoPlatforms.forEach { platform -> + shadowLib("org.jetbrains.skiko:skiko-awt-runtime-$platform:$skikoVersion") { + exclude(group = "org.jetbrains.kotlin") + exclude(group = "org.jetbrains.kotlinx") + } + } // Ktor includeLib("io.ktor:ktor-client-core:$ktorVersion") diff --git a/gradle.properties b/gradle.properties index df5d67332..3c1beccc6 100644 --- a/gradle.properties +++ b/gradle.properties @@ -37,7 +37,9 @@ classGraphVersion=4.8.184 ktorVersion=3.3.3 jacksonVersion=3.1.4 mockkVersion=1.14.7 -spairVersion=1.90.0 +composeVersion=1.12.2 +# Must be the skiko version the Compose version above depends on +skikoVersion=0.150.2 # Fabric https://fabricmc.net/develop/ fabricLoaderVersion=0.19.5 diff --git a/src/main/java/com/lambda/mixin/MinecraftClientMixin.java b/src/main/java/com/lambda/mixin/MinecraftClientMixin.java index d20a73c7a..d41043882 100644 --- a/src/main/java/com/lambda/mixin/MinecraftClientMixin.java +++ b/src/main/java/com/lambda/mixin/MinecraftClientMixin.java @@ -19,8 +19,7 @@ import com.lambda.event.EventFlow; import com.lambda.event.events.*; -import com.lambda.gui.DearImGui; -import com.lambda.gui.components.ClickGuiLayout; +import com.lambda.gui.GuiConfig; import com.lambda.interaction.handler.handlers.TimerHandler; import com.lambda.module.modules.movement.BetterFirework; import com.lambda.module.modules.player.Interact; @@ -65,11 +64,6 @@ public class MinecraftClientMixin { @Shadow public int itemUseCooldown; - @Inject(method = "close", at = @At("HEAD")) - void closeImGui(CallbackInfo ci) { - DearImGui.INSTANCE.destroy(); - } - @WrapMethod(method = "render") void onLoopTick(boolean tick, Operation original) { com.lambda.graphics.RenderMain.preRender(); @@ -201,7 +195,7 @@ float getTargetMillisPerTick(float millis, Operation original) { @Inject(method = "updateWindowTitle", at = @At("HEAD"), cancellable = true) void updateWindowTitle(CallbackInfo ci) { - if (!ClickGuiLayout.getSetLambdaWindowTitle()) return; + if (!GuiConfig.getSetLambdaWindowTitle()) return; WindowUtils.setLambdaTitle(); ci.cancel(); } diff --git a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java index 43a26f2cf..00da2bbe4 100644 --- a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java +++ b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java @@ -27,16 +27,18 @@ import net.minecraft.client.input.KeyInput; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; +import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Mixin; @Mixin(Keyboard.class) public class KeyboardMixin { @WrapMethod(method = "onKey") private void onKey(long window, int action, KeyInput input, Operation original) { - EventFlow.post(new ButtonEvent.Keyboard.Press(input.key(), input.scancode(), action, input.modifiers())); + if (EventFlow.post(new ButtonEvent.Keyboard.Press(input.key(), input.scancode(), action, input.modifiers())).isCanceled()) return; original.call(window, action, input); int key = input.key(); - if (!InventoryMove.getShouldMove() || !InventoryMove.isKeyMovementRelated(key)) return; + if (!InventoryMove.isKeyMovementRelated(key)) return; + if (action != GLFW.GLFW_RELEASE && !InventoryMove.getShouldMove()) return; InputUtil.Key fromCode = InputUtil.fromKeyCode(input); KeyBinding.setKeyPressed(fromCode, action != 0); } diff --git a/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java b/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java new file mode 100644 index 000000000..52469a732 --- /dev/null +++ b/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java @@ -0,0 +1,35 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.mixin.render; + +import androidx.compose.ui.Actuals_skikoKt; +import com.lambda.gui.core.RenderThread; +import kotlin.Unit; +import kotlin.jvm.functions.Function0; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(value = Actuals_skikoKt.class, remap = false) +public class ComposeDelayMixin { + @Inject(method = "postDelayed", at = @At("HEAD"), cancellable = true, require = 1) + private static void delayOnRenderThread(long delayMillis, Function0 block, CallbackInfoReturnable cir) { + cir.setReturnValue(RenderThread.after(delayMillis, block)); + } +} diff --git a/src/main/java/com/lambda/mixin/render/GameRendererMixin.java b/src/main/java/com/lambda/mixin/render/GameRendererMixin.java index bc9bc9023..cf4304a15 100644 --- a/src/main/java/com/lambda/mixin/render/GameRendererMixin.java +++ b/src/main/java/com/lambda/mixin/render/GameRendererMixin.java @@ -22,7 +22,7 @@ import com.lambda.event.events.RenderEvent; import com.lambda.graphics.RenderMain; import com.lambda.graphics.outline.OutlineCapturingQueue; -import com.lambda.gui.DearImGui; +import com.lambda.gui.LambdaGui; import com.lambda.module.modules.render.BlockOutline; import com.lambda.module.modules.render.Bobbing; import com.lambda.module.modules.render.NoRender; @@ -91,7 +91,7 @@ private float modifyGetFov(float original) { @Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/render/GuiRenderer;render(Lcom/mojang/blaze3d/buffers/GpuBufferSlice;)V", shift = At.Shift.AFTER)) private void onGuiRenderComplete(RenderTickCounter tickCounter, boolean tick, CallbackInfo ci) { - DearImGui.INSTANCE.render(); + LambdaGui.INSTANCE.render(); } @WrapOperation(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;applyCursorTo(Lnet/minecraft/client/util/Window;)V")) @@ -102,7 +102,7 @@ private void applyCursorOverride(DrawContext context, Window window, Operation. + */ + +package com.lambda.mixin.render; + +import com.lambda.gui.render.ItemAtlas; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gl.Framebuffer; +import net.minecraft.client.gui.render.GuiRenderer; +import net.minecraft.client.util.Window; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(GuiRenderer.class) +public class GuiRendererMixin { + @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;getFramebuffer()Lnet/minecraft/client/gl/Framebuffer;"), require = 1) + private Framebuffer drawIntoItemAtlas(MinecraftClient client, Operation original) { + Framebuffer atlas = ItemAtlas.getTarget(); + return atlas != null ? atlas : original.call(client); + } + + @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferWidth()I"), require = 1) + private int itemAtlasWidth(Window window, Operation original) { + Framebuffer atlas = ItemAtlas.getTarget(); + return atlas != null ? atlas.textureWidth : original.call(window); + } + + @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferHeight()I"), require = 1) + private int itemAtlasHeight(Window window, Operation original) { + Framebuffer atlas = ItemAtlas.getTarget(); + return atlas != null ? atlas.textureHeight : original.call(window); + } + + @WrapOperation(method = {"renderPreparedDraws", "getWindowScaleFactor"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getScaleFactor()I"), require = 1) + private int itemAtlasScale(Window window, Operation original) { + return ItemAtlas.getTarget() != null ? ItemAtlas.getScale() : original.call(window); + } +} diff --git a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java new file mode 100644 index 000000000..54ea7aab9 --- /dev/null +++ b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java @@ -0,0 +1,44 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.mixin.render; + +import com.lambda.gui.GuiScreen; +import com.lambda.gui.LambdaGui; +import com.llamalad7.mixinextras.injector.ModifyReturnValue; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.option.InactivityFpsLimiter; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(InactivityFpsLimiter.class) +public class InactivityFpsLimiterMixin { + @Shadow + @Final + private MinecraftClient client; + + @ModifyReturnValue(method = "getLimitReason", at = @At("RETURN")) + private InactivityFpsLimiter.LimitReason liftMenuLimit(InactivityFpsLimiter.LimitReason reason) { + boolean shown = client.currentScreen == GuiScreen.INSTANCE || LambdaGui.INSTANCE.getLeaving(); + if (reason == InactivityFpsLimiter.LimitReason.OUT_OF_LEVEL_MENU && shown) { + return InactivityFpsLimiter.LimitReason.NONE; + } + return reason; + } +} diff --git a/src/main/java/com/lambda/mixin/render/ScreenMixin.java b/src/main/java/com/lambda/mixin/render/ScreenMixin.java index c6faa22e6..f65b471f5 100644 --- a/src/main/java/com/lambda/mixin/render/ScreenMixin.java +++ b/src/main/java/com/lambda/mixin/render/ScreenMixin.java @@ -17,8 +17,6 @@ package com.lambda.mixin.render; -import com.lambda.gui.components.QuickSearch; -import com.lambda.module.modules.client.AutoUpdater; import com.lambda.module.modules.render.ContainerPreview; import com.lambda.module.modules.render.NoRender; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; @@ -26,37 +24,13 @@ import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.input.KeyInput; -import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Screen.class) public class ScreenMixin { - @Inject(method = "keyPressed", at = @At("HEAD"), cancellable = true) - private void onKeyPressed(KeyInput input, CallbackInfoReturnable cir) { - if (input.key() == GLFW.GLFW_KEY_ESCAPE) { - if (QuickSearch.INSTANCE.isOpen()) { - QuickSearch.INSTANCE.close(); - cir.setReturnValue(true); - } else if (AutoUpdater.getShowFirstLaunchModal()) { - AutoUpdater.dismissFirstLaunchPrompt(); - cir.setReturnValue(true); - } else if (AutoUpdater.getShowInstallModal()) { - AutoUpdater.INSTANCE.disable(); - AutoUpdater.setShowInstallModal(false); - cir.setReturnValue(true); - } else if (AutoUpdater.getShowUninstallModal()) { - AutoUpdater.INSTANCE.enable(); - AutoUpdater.setShowUninstallModal(false); - cir.setReturnValue(true); - } - } - } - @Inject(method = "renderInGameBackground", at = @At("HEAD"), cancellable = true) private void injectRenderInGameBackground(DrawContext context, CallbackInfo ci) { if (NoRender.INSTANCE.isEnabled() && NoRender.getNoGuiShadow()) ci.cancel(); diff --git a/src/main/kotlin/com/lambda/Lambda.kt b/src/main/kotlin/com/lambda/Lambda.kt index 046f9f900..69dd1e6c9 100644 --- a/src/main/kotlin/com/lambda/Lambda.kt +++ b/src/main/kotlin/com/lambda/Lambda.kt @@ -25,7 +25,7 @@ import com.lambda.config.Serializer import com.lambda.core.Loader import com.lambda.event.events.ClientEvent import com.lambda.event.listener.UnsafeListener.Companion.listenOnceUnsafe -import com.lambda.gui.components.ClickGuiLayout +import com.lambda.gui.GuiConfig import com.lambda.util.ReflectionUtils.getInstances import com.lambda.util.WindowUtils.setLambdaWindowIcon import net.fabricmc.api.ClientModInitializer @@ -114,7 +114,7 @@ object Lambda : ClientModInitializer { // We want the opengl context to be created listenOnceUnsafe({ Int.MAX_VALUE }) { LOG.info("$MOD_NAME $VERSION initialized in ${Loader.initialize()} ms\n") - if (ClickGuiLayout.setLambdaWindowIcon) setLambdaWindowIcon() + if (GuiConfig.setLambdaWindowIcon) setLambdaWindowIcon() true } } diff --git a/src/main/kotlin/com/lambda/config/Config.kt b/src/main/kotlin/com/lambda/config/Config.kt index fe1d82ba8..f187034ec 100644 --- a/src/main/kotlin/com/lambda/config/Config.kt +++ b/src/main/kotlin/com/lambda/config/Config.kt @@ -46,7 +46,6 @@ import com.lambda.config.settings.numeric.FloatSetting import com.lambda.config.settings.numeric.IntegerSetting import com.lambda.config.settings.numeric.LongSetting import com.lambda.event.Muteable -import com.lambda.imgui.flag.ImGuiInputTextFlags import com.lambda.util.KeyCode import com.lambda.util.Nameable import net.minecraft.block.Block @@ -217,10 +216,9 @@ abstract class Config( name: String, defaultValue: String, multiline: Boolean = false, - flags: Int = ImGuiInputTextFlags.None, description: String = "", visibility: () -> Boolean = { true } - ) = setting(name) { layer -> StringSetting(name, description, this, layer, defaultValue, visibility, multiline, flags) } + ) = setting(name) { layer -> StringSetting(name, description, this, layer, defaultValue, visibility, multiline) } @ConfigEntryDsl @JvmName("collectionSetting1") diff --git a/src/main/kotlin/com/lambda/config/EntryLayer.kt b/src/main/kotlin/com/lambda/config/EntryLayer.kt index 1539307f7..9fb7d6e4e 100644 --- a/src/main/kotlin/com/lambda/config/EntryLayer.kt +++ b/src/main/kotlin/com/lambda/config/EntryLayer.kt @@ -103,4 +103,20 @@ sealed class ConfigBlockLayer { } internalForEach(this, emptyList()) } -} \ No newline at end of file +} + +fun EntryLayer>.holds(setting: Setting<*>): Boolean = + when (this) { + is EntryLayer.Single -> entry === setting + is EntryLayer.Multiple -> layers.any { it.holds(setting) } + else -> false + } + +fun EntryLayer.Multiple>.hasVisibleSettings(): Boolean = + layers.any { + when (it) { + is EntryLayer.Single -> it.entry.visibility() + is EntryLayer.Multiple -> it.hasVisibleSettings() + else -> false + } + } diff --git a/src/main/kotlin/com/lambda/config/automation/UserAutomationConfig.kt b/src/main/kotlin/com/lambda/config/automation/UserAutomationConfig.kt index e19d5ddc3..976678ea2 100644 --- a/src/main/kotlin/com/lambda/config/automation/UserAutomationConfig.kt +++ b/src/main/kotlin/com/lambda/config/automation/UserAutomationConfig.kt @@ -37,6 +37,13 @@ class UserAutomationConfig(name: String) : AutomationConfig(name, UserAutomation } } + fun delete() { + linkedModules.value.forEach { name -> + moduleNameMap[name]?.let { it.automationConfig = it.defaultAutomationConfig } + } + UserAutomationCategory.configs.remove(this) + } + private fun Module.removeLink() { (automationConfig as? UserAutomationConfig)?.linkedModules?.value?.remove(name) } diff --git a/src/main/kotlin/com/lambda/config/entries/Setting.kt b/src/main/kotlin/com/lambda/config/entries/Setting.kt index 17777d42a..691c1a505 100644 --- a/src/main/kotlin/com/lambda/config/entries/Setting.kt +++ b/src/main/kotlin/com/lambda/config/entries/Setting.kt @@ -17,6 +17,7 @@ package com.lambda.config.entries +import androidx.compose.runtime.Composable import com.lambda.Lambda.mapper import com.lambda.brigadier.CommandResult.Companion.failure import com.lambda.brigadier.CommandResult.Companion.success @@ -33,7 +34,6 @@ import com.lambda.config.EntryLayer import com.lambda.config.MultipleLayerType import com.lambda.config.entries.Setting.ValueListener import com.lambda.context.SafeContext -import com.lambda.gui.dsl.ImGuiBuilder import com.lambda.threading.runSafe import com.lambda.util.CommunicationUtils.info import com.lambda.util.Describable @@ -143,7 +143,8 @@ abstract class Setting( core = originalCore } - abstract fun ImGuiBuilder.buildLayout() + @Composable + open fun Gui() {} open fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(string("value as JSON")) { value -> diff --git a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt index 971dad7d5..86416a816 100644 --- a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt @@ -17,6 +17,11 @@ package com.lambda.config.settings +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp import com.lambda.brigadier.CommandResult.Companion.failure import com.lambda.brigadier.CommandResult.Companion.success import com.lambda.brigadier.argument.value @@ -26,7 +31,9 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.component.TextInput +import com.lambda.gui.core.observe +import com.lambda.gui.settings.Labeled import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess @@ -41,7 +48,17 @@ class CharSetting( defaultValue: Char, visibility: () -> Boolean ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() {} + @Composable + override fun Gui() { + val value by observe { value } + Labeled(name) { + TextInput( + value.toString(), + { text -> text.lastOrNull()?.let { this@CharSetting.value = it } }, + Modifier.width(18.dp) + ) + } + } override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(word(name)) { parameter -> diff --git a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt index 5a537789a..d23326fdd 100644 --- a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt @@ -17,10 +17,15 @@ package com.lambda.config.settings +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.component.Button +import com.lambda.gui.theme.Look class FunctionSetting R, R>( name: String, @@ -30,8 +35,6 @@ class FunctionSetting R, R>( layer: SettingEntryLayer, T>, visibility: () -> Boolean ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() { - button(name) { value() } - lambdaTooltip(description) - } + @Composable + override fun Gui() = Button(name, Modifier.fillMaxWidth().height(Look.rowHeight)) { value() } } diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index 23eb84d40..64f395d32 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -17,18 +17,53 @@ package com.lambda.config.settings +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.key +import androidx.compose.ui.unit.dp import com.lambda.config.Config import com.lambda.config.ConfigEditorD5l import com.lambda.config.SettingEditBuilder import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImGui -import com.lambda.imgui.ImGui.calcTextSize -import com.lambda.imgui.ImGui.dummy -import com.lambda.imgui.flag.ImGuiCol +import com.lambda.gui.component.KeyboardFocus +import com.lambda.gui.component.NumberInput +import com.lambda.gui.component.Text +import com.lambda.gui.component.isActivation +import com.lambda.gui.component.keyboardFocusable +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.component.scrubbable +import com.lambda.gui.core.observe +import com.lambda.gui.settings.ROW_INSET +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import java.math.BigDecimal +import java.math.RoundingMode import java.text.NumberFormat import java.util.* +import kotlin.math.abs + +private const val SAME = 1e-4 /** * @see [com.lambda.config.Config] @@ -51,51 +86,124 @@ abstract class NumericSetting( } private val formatter = NumberFormat.getNumberInstance(Locale.getDefault()) + private val lowest get() = range.start.decimal + private val highest get() = range.endInclusive.decimal + private val Number.decimal get() = BigDecimal(toString()) + + var appliedOnRelease = false - override fun toString() = "${formatter.format(value)}$unit" + override val isModified + get() = abs(originalCore.value.toDouble() - originalCore.defaultValue.toDouble()) > step.toDouble() * SAME - /** - * Subclasses must implement this to provide their specific slider widget. - */ - protected abstract fun ImGuiBuilder.buildSlider() + protected abstract fun convert(number: BigDecimal): T - override fun ImGuiBuilder.buildLayout() { - val showReset = isModified - val resetButtonText = "R" - val valueString = this@NumericSetting.toString() + override fun toString() = format(value) - buildSlider() - lambdaTooltip(description) + private fun format(value: T) = "${formatter.format(value)}$unit" - val itemRectMin = ImGui.getItemRectMin() - val itemRectMax = ImGui.getItemRectMax() - val textHeight = ImGui.getTextLineHeight() - val textY = itemRectMin.y + (itemRectMax.y - itemRectMin.y - textHeight) / 2.0f - val labelWidth = calcTextSize(name).x - val valueWidth = calcTextSize(valueString).x + private fun parse(text: String): T? = + text.replace(',', '.').toBigDecimalOrNull()?.let { convert(it.coerceIn(lowest, highest)) } - val labelEndPosX = itemRectMin.x + style.framePadding.x * 2 + labelWidth - val valueStartPosX = itemRectMax.x - style.framePadding.x * 2 - valueWidth + private fun fractionOf(value: T): Float { + val span = range.endInclusive.toDouble() - range.start.toDouble() + val fraction = ((value.toDouble() - range.start.toDouble()) / span).toFloat() + return if (span > 0 && !fraction.isNaN()) fraction.coerceIn(0f, 1f) + else 0f + } - windowDrawList.addText(itemRectMin.x + style.framePadding.x * 2, textY, ImGui.getColorU32(ImGuiCol.Text), name) - if (labelEndPosX < valueStartPosX) { - windowDrawList.addText(valueStartPosX, textY, ImGui.getColorU32(ImGuiCol.Text), valueString) + private fun at(fraction: Float): T = + when { + fraction <= 0f -> range.start + fraction >= 1f -> range.endInclusive + else -> onGrid(lowest + (highest - lowest) * fraction.toBigDecimal(), RoundingMode.HALF_UP) } - sameLine(0.0f, style.itemSpacing.x) - if (showReset) { - button("$resetButtonText##$name") { - reset() - } - onItemHover { - tooltip { text("Reset to default") } + private fun stepped(by: Int): T = + onGrid(value.decimal, if (by < 0) RoundingMode.CEILING else RoundingMode.FLOOR, by) + + private fun onGrid(target: BigDecimal, rounding: RoundingMode, offset: Int = 0): T { + val step = step.decimal + if (step.signum() <= 0) return convert(target.coerceIn(lowest, highest)) + val steps = (target - lowest).divide(step, 0, rounding) + offset.toBigDecimal() + return convert((lowest + step * steps).coerceIn(lowest, highest)) + } + + @Composable + override fun Gui() { + val colors = LambdaTheme.colors + val current by observe { value } + var typing by remember { mutableStateOf(false) } + val bar = remember { FocusRequester() } + var refocus by remember { mutableStateOf(false) } + + if (typing) { + NumberInput( + current, + ::parse, + { value = it }, + Modifier.fillMaxWidth(), + focused = true + ) { + typing = false + refocus = KeyboardFocus.visible } - } else { - dummy(calcTextSize(resetButtonText).x + style.framePadding.x * 2.0f, ImGui.getFrameHeight()) + return + } + if (refocus) LaunchedEffect(Unit) { + bar.requestFocus() + refocus = false + } + + var held by remember { mutableStateOf(null) } + val shown = held ?: current + val label = remember(shown, unit) { format(shown) } + val fraction by animateFloatAsState(fractionOf(shown)) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.track) + .drawBehind { + drawRect( + colors.trackFilled, + size = Size(size.width * fraction, size.height) + ) + } + .scrubbable(onEnd = { + held?.let { value = it } + held = null + }) { position, size -> + val dragged = at(position.x / size.width) + if (appliedOnRelease) held = dragged else value = dragged + } + .focusRequester(bar) + .keyboardFocusable { event -> + when { + event.key == Key.DirectionLeft -> value = stepped(-1) + event.key == Key.DirectionRight -> value = stepped(1) + event.isActivation -> typing = true + else -> return@keyboardFocusable false + } + true + } + .padding(horizontal = ROW_INSET) + ) { + Text(name, Modifier.weight(1f), colors.onControl, maxLines = 1) + Text( + text = label, + modifier = Modifier.mouseClickable(keyboard = false) { typing = true }, + color = colors.onControl, + maxLines = 1, + ) } } } +fun > S.appliedOnRelease() = apply { appliedOnRelease = true } + @Suppress("unchecked_cast") @ConfigEditorD5l fun SettingEditBuilder.range(range: ClosedRange) where T : Number, T : Comparable { diff --git a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt index 026ee1a0a..1a187531c 100644 --- a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt @@ -19,6 +19,15 @@ package com.lambda.config.settings +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp import com.lambda.brigadier.argument.greedyString import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -28,8 +37,12 @@ import com.lambda.config.ConfigEditorD5l import com.lambda.config.SettingEditBuilder import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.flag.ImGuiInputTextFlags +import com.lambda.gui.component.Text +import com.lambda.gui.component.TextInput +import com.lambda.gui.core.observe +import com.lambda.gui.settings.Labeled +import com.lambda.gui.settings.ROW_INSET +import com.lambda.gui.settings.TEXT_FIELD_WIDTH import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess @@ -44,15 +57,30 @@ class StringSetting( defaultValue: String, visibility: () -> Boolean, var multiline: Boolean = false, - var flags: Int = ImGuiInputTextFlags.None, ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() { - if (multiline) { - inputTextMultiline(name, ::value, flags = flags) - } else { - inputText(name, ::value, flags) + + @Composable + override fun Gui() { + val value by observe { value } + if (multiline) Column( + Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(1.dp) + ) { + Text(name, Modifier.padding(start = ROW_INSET, top = 1.dp), maxLines = 1) + TextInput( + value, + { this@StringSetting.value = it }, + Modifier.fillMaxWidth(), + singleLine = false + ) + } + else Labeled(name) { + TextInput( + value, + { this@StringSetting.value = it }, + Modifier.width(TEXT_FIELD_WIDTH) + ) } - lambdaTooltip(description) } override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { @@ -69,9 +97,3 @@ class StringSetting( fun SettingEditBuilder.multiline(multiline: Boolean) { (entries as Collection).forEach { it.multiline = multiline } } - -@Suppress("unchecked_cast") -@ConfigEditorD5l -fun SettingEditBuilder.flags(flags: Int) { - (entries as Collection).forEach { it.flags = flags } -} diff --git a/src/main/kotlin/com/lambda/config/settings/collections/BlockCollectionSetting.kt b/src/main/kotlin/com/lambda/config/settings/collections/BlockCollectionSetting.kt index bf9b158f6..c3356a650 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/BlockCollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/BlockCollectionSetting.kt @@ -21,8 +21,8 @@ import com.lambda.Lambda.typeFactory import com.lambda.config.Config import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.serializers.BlockSerializer -import com.lambda.gui.dsl.ImGuiBuilder import net.minecraft.block.Block +import net.minecraft.item.ItemStack class BlockCollectionSetting( name: String, @@ -43,5 +43,6 @@ class BlockCollectionSetting( typeFactory.constructCollectionType(MutableCollection::class.java, Block::class.java), serialize = true, ) { - override fun ImGuiBuilder.buildLayout() = buildDualPane("block") { BlockSerializer.stringify(it) } -} \ No newline at end of file + override fun label(item: Block) = BlockSerializer.stringify(item) + override fun icon(item: Block) = ItemStack(item.asItem()) +} diff --git a/src/main/kotlin/com/lambda/config/settings/collections/ClassCollectionSetting.kt b/src/main/kotlin/com/lambda/config/settings/collections/ClassCollectionSetting.kt index 22aa143f9..3db2b4b88 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/ClassCollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/ClassCollectionSetting.kt @@ -20,7 +20,6 @@ package com.lambda.config.settings.collections import com.lambda.Lambda.typeFactory import com.lambda.config.Config import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder import com.lambda.util.ReflectionUtils.className /** @@ -46,5 +45,5 @@ class ClassCollectionSetting( typeFactory.constructCollectionType(Collection::class.java, Any::class.java), serialize = false, ) { - override fun ImGuiBuilder.buildLayout() = buildDualPane("item") { it.className } -} \ No newline at end of file + override fun label(item: T) = item.className +} diff --git a/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt b/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt index bc01d1ef2..0dbded7a6 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt @@ -19,6 +19,7 @@ package com.lambda.config.settings.collections +import androidx.compose.runtime.Composable import com.lambda.config.Config import com.lambda.config.ConfigEditorD5l import com.lambda.config.SettingEditBuilder @@ -26,15 +27,9 @@ import com.lambda.config.entries.ConfigEntryDsl import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer import com.lambda.context.SafeContext -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImGui -import com.lambda.imgui.ImGui.getContentRegionAvail -import com.lambda.imgui.ImGuiListClipper -import com.lambda.imgui.callback.ImListClipperCallback -import com.lambda.imgui.flag.ImGuiChildFlags -import com.lambda.imgui.flag.ImGuiPopupFlags -import com.lambda.imgui.flag.ImGuiSelectableFlags.DontClosePopups +import com.lambda.gui.settings.CollectionButton import com.lambda.threading.runSafe +import net.minecraft.item.ItemStack import tools.jackson.databind.JavaType /** @@ -64,8 +59,6 @@ open class CollectionSetting( super.value = newVal.toMutableList() } - private var searchFilter = "" - val selectListeners = mutableListOf Unit>() val unsafeSelectListeners = mutableListOf<(R) -> Unit>() val deselectListeners = mutableListOf Unit>() @@ -76,105 +69,29 @@ open class CollectionSetting( value.size != defaultValue.size || defaultValue.any { !value.contains(it) } } - override fun ImGuiBuilder.buildLayout() = buildDualPane("item") { it.toString() } + @Composable + override fun Gui() = CollectionButton(this) - fun ImGuiBuilder.buildDualPane(itemName: String, toString: (R) -> String) { - val text = if (value.size == 1) itemName else "${itemName}s" - val popupId = "##$name-collection-popup" + open fun label(item: R): String = item.toString() - button("$name: ${value.size} $text") { - ImGui.openPopup(popupId) - } + open fun icon(item: R): ItemStack? = null - ImGui.setNextWindowSizeConstraints(500f, 0f, Float.MAX_VALUE, io.displaySize.y * 0.5f) - popupContextItem(popupId, ImGuiPopupFlags.None) { - inputText("##$name-SearchBox", ::searchFilter) - - val q = searchFilter.trim() - val filteredDeselected = immutableCollection - .filter { item -> !value.contains(item) && (q.isEmpty() || toString(item).contains(q, ignoreCase = true)) } - val filteredSelected = immutableCollection - .filter { item -> value.contains(item) && (q.isEmpty() || toString(item).contains(q, ignoreCase = true)) } - - val availableWidth = getContentRegionAvail().x - val swapButtonWidth = 30f - val paneWidth = (availableWidth - swapButtonWidth - style.itemSpacing.x * 2) / 2f - val paneHeight = 200f - - group { - textDisabled("Deselected (${filteredDeselected.size})") - child( - strId = "##$name-Deselected", - width = paneWidth, - height = paneHeight, - childFlags = ImGuiChildFlags.Border or ImGuiChildFlags.ResizeX or ImGuiChildFlags.ResizeY, - ) { - val deselectedCallback = object : ImListClipperCallback() { - override fun accept(index: Int) { - val v = filteredDeselected.getOrNull(index) ?: return - selectable( - label = toString(v), - flags = DontClosePopups - ) { - value.add(v) - unsafeSelectListeners.forEach { listener -> listener(v) } - runSafe { selectListeners.forEach { listener -> listener(v) } } - } - } - } - ImGuiListClipper.forEach(filteredDeselected.size, deselectedCallback) - } - } - - sameLine() - - group { - cursorPosY += paneHeight / 2f - button("<>", swapButtonWidth) { - val currentlySelected = value.toList() - val allItems = immutableCollection.toList() - value.clear() - allItems.forEach { item -> - if (!currentlySelected.contains(item)) { - value.add(item) - } - } - currentlySelected.forEach { v -> unsafeDeselectListeners.forEach { listener -> listener(v) } } - value.forEach { v -> unsafeSelectListeners.forEach { listener -> listener(v) } } - runSafe { - currentlySelected.forEach { v -> deselectListeners.forEach { listener -> listener(v) } } - value.forEach { v -> selectListeners.forEach { listener -> listener(v) } } - } - } - } - - sameLine() - - group { - textDisabled("Selected (${filteredSelected.size})") - child( - strId = "##$name-Selected", - width = paneWidth, - height = paneHeight, - childFlags = ImGuiChildFlags.Border or ImGuiChildFlags.ResizeX or ImGuiChildFlags.ResizeY, - ) { - val selectedCallback = object : ImListClipperCallback() { - override fun accept(index: Int) { - val v = filteredSelected.getOrNull(index) ?: return - selectable( - label = toString(v), - flags = DontClosePopups - ) { - value.remove(v) - unsafeDeselectListeners.forEach { listener -> listener(v) } - runSafe { deselectListeners.forEach { listener -> listener(v) } } - } - } - } - ImGuiListClipper.forEach(filteredSelected.size, selectedCallback) - } - } - } + fun select(item: R) { + if (item in value) return + value.add(item) + unsafeSelectListeners.forEach { it(item) } + runSafe { selectListeners.forEach { it(item) } } + } + + fun deselect(item: R) { + if (!value.remove(item)) return + unsafeDeselectListeners.forEach { it(item) } + runSafe { deselectListeners.forEach { it(item) } } + } + + fun invertSelection() { + val selected = value.toSet() + immutableCollection.forEach { if (it in selected) deselect(it) else select(it) } } } diff --git a/src/main/kotlin/com/lambda/config/settings/collections/FluidCollectionSetting.kt b/src/main/kotlin/com/lambda/config/settings/collections/FluidCollectionSetting.kt index 28dae8d4e..9eebca510 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/FluidCollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/FluidCollectionSetting.kt @@ -21,7 +21,6 @@ import com.lambda.Lambda.typeFactory import com.lambda.config.Config import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.serializers.FluidSerializer -import com.lambda.gui.dsl.ImGuiBuilder import net.minecraft.fluid.Fluid class FluidCollectionSetting( @@ -43,5 +42,5 @@ class FluidCollectionSetting( typeFactory.constructCollectionType(MutableCollection::class.java, Fluid::class.java), serialize = true, ) { - override fun ImGuiBuilder.buildLayout() = buildDualPane("block") { FluidSerializer.stringify(it) } -} \ No newline at end of file + override fun label(item: Fluid) = FluidSerializer.stringify(item) +} diff --git a/src/main/kotlin/com/lambda/config/settings/collections/ItemCollectionSetting.kt b/src/main/kotlin/com/lambda/config/settings/collections/ItemCollectionSetting.kt index 802a70a04..c8e25af70 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/ItemCollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/ItemCollectionSetting.kt @@ -21,8 +21,8 @@ import com.lambda.Lambda.typeFactory import com.lambda.config.Config import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.serializers.ItemSerializer -import com.lambda.gui.dsl.ImGuiBuilder import net.minecraft.item.Item +import net.minecraft.item.ItemStack class ItemCollectionSetting( name: String, @@ -39,5 +39,6 @@ class ItemCollectionSetting( typeFactory.constructCollectionType(Collection::class.java, Item::class.java), serialize = true, ) { - override fun ImGuiBuilder.buildLayout() = buildDualPane("item") { ItemSerializer.stringify(it) } -} \ No newline at end of file + override fun label(item: Item) = ItemSerializer.stringify(item) + override fun icon(item: Item) = ItemStack(item) +} diff --git a/src/main/kotlin/com/lambda/config/settings/collections/MapSetting.kt b/src/main/kotlin/com/lambda/config/settings/collections/MapSetting.kt index 1bf99c44c..6c982c49c 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/MapSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/MapSetting.kt @@ -20,7 +20,6 @@ package com.lambda.config.settings.collections import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder import tools.jackson.databind.JavaType class MapSetting( @@ -32,5 +31,4 @@ class MapSetting( defaultValue: MutableMap, val type: JavaType ) : Setting>(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() {} } \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt b/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt index c958fd1fa..64ebbe729 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt @@ -17,6 +17,16 @@ package com.lambda.config.settings.comparable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp import com.lambda.brigadier.argument.boolean import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -24,7 +34,12 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.component.Checkmark +import com.lambda.gui.component.Text +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.observe +import com.lambda.gui.settings.ROW_INSET +import com.lambda.gui.theme.Look import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess @@ -36,9 +51,21 @@ class BooleanSetting( visibility: () -> Boolean, defaultValue: Boolean ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() { - checkbox(name, ::value) - lambdaTooltip(description) + @Composable + override fun Gui() { + val checked by observe { value } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight) + .mouseClickable { value = !value } + .padding(horizontal = ROW_INSET) + ) { + Checkmark(checked) + Text(name, maxLines = 1) + } } override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { diff --git a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt index 30a93d1b4..ab05a32d7 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt @@ -17,6 +17,10 @@ package com.lambda.config.settings.comparable +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier import com.lambda.brigadier.CommandResult.Companion.failure import com.lambda.brigadier.CommandResult.Companion.success import com.lambda.brigadier.argument.value @@ -26,8 +30,9 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.util.Describable +import com.lambda.gui.component.Dropdown +import com.lambda.gui.core.observe +import com.lambda.gui.settings.ROW_INSET import com.lambda.util.StringUtils.capitalize import com.lambda.util.extension.CommandBuilder import com.lambda.util.extension.displayValue @@ -41,24 +46,16 @@ class EnumSetting>( visibility: () -> Boolean, defaultValue: T ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() { - val values = value.enumValues - val currentDisplay = value.displayValue - val currentIndex = value.ordinal - - combo("##$name", preview = "$name: $currentDisplay") { - values.forEachIndexed { idx, v -> - val isSelected = idx == currentIndex - - selectable(v.displayValue, isSelected) { - if (!isSelected) value = values[idx % values.size] - } - - (v as? Describable)?.let { lambdaTooltip(it.description) } - } - } - - lambdaTooltip(description) + @Composable + override fun Gui() { + val selected by observe { value } + Dropdown( + label = name, + options = selected.enumValues.asList(), + selected = selected, + optionLabel = { it.displayValue }, + modifier = Modifier.padding(start = ROW_INSET), + ) { value = it } } override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { diff --git a/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt index 0580c9470..3940101f5 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt @@ -17,6 +17,11 @@ package com.lambda.config.settings.complex +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier import com.lambda.Lambda.mc import com.lambda.brigadier.argument.integer import com.lambda.brigadier.argument.value @@ -25,8 +30,13 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.util.BlockUtils.blockPos +import com.lambda.gui.component.Button +import com.lambda.gui.component.NumberInput +import com.lambda.gui.component.Tooltip +import com.lambda.gui.core.observe +import com.lambda.gui.settings.Labeled +import com.lambda.gui.settings.NUMBER_FIELD_WIDTH +import com.lambda.gui.theme.Look import com.lambda.util.CommunicationUtils.info import com.lambda.util.extension.CommandBuilder import com.lambda.util.world.raycast.RayCastUtils.blockResult @@ -41,18 +51,35 @@ class BlockPosSetting( visibility: () -> Boolean, defaultValue: BlockPos ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() { - button("Set##$name") { - mc.crosshairTarget?.blockResult?.blockPos?.let { - value = it - } ?: info("No block under crosshair") - } - lambdaTooltip("Set the coordinates to the block you are currently looking at") - sameLine() - treeNode(name, id = name) { - inputVec3i("##$name", value) { value = it.blockPos } + @Composable + override fun Gui() { + val pos by observe { value.toImmutable() } + Labeled(name) { + NumberInput( + pos.x, + String::toIntOrNull, + { value = BlockPos(it, pos.y, pos.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + pos.y, + String::toIntOrNull, + { value = BlockPos(pos.x, it, pos.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + pos.z, + String::toIntOrNull, + { value = BlockPos(pos.x, pos.y, it) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + Tooltip("Use the block you are looking at") { + Button("Target", Modifier.height(Look.rowHeight)) { + mc.crosshairTarget?.blockResult?.blockPos?.let { value = it } + ?: this@BlockPosSetting.info("No block under crosshair") + } + } } - lambdaTooltip(description) } override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { diff --git a/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt index c5ea38965..542b72bff 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt @@ -17,6 +17,7 @@ package com.lambda.config.settings.complex +import androidx.compose.runtime.Composable import com.lambda.brigadier.argument.blockState import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -24,7 +25,7 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.settings.BlockPicker import com.lambda.util.extension.CommandBuilder import net.minecraft.block.Block import net.minecraft.command.CommandRegistryAccess @@ -37,7 +38,8 @@ class BlockSetting( visibility: () -> Boolean, defaultValue: Block ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() {} + @Composable + override fun Gui() = BlockPicker(this) override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(blockState(name, registry)) { argument -> diff --git a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt index b7a037159..e631564f5 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt @@ -17,6 +17,7 @@ package com.lambda.config.settings.complex +import androidx.compose.runtime.Composable import com.lambda.brigadier.argument.integer import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -25,7 +26,7 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.settings.ColorPicker import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess import java.awt.Color @@ -38,10 +39,8 @@ class ColorSetting( visibility: () -> Boolean, defaultValue: Color ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() { - colorEdit(name, ::value) - lambdaTooltip(description) - } + @Composable + override fun Gui() = ColorPicker(this) override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(integer("Red", 0, 255)) { red -> diff --git a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt index 5b069fd72..907ff2083 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -19,6 +19,19 @@ package com.lambda.config.settings.complex +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.unit.dp import com.fasterxml.jackson.annotation.JsonIncludeProperties import com.lambda.Lambda.mc import com.lambda.brigadier.CommandResult.Companion.failure @@ -37,12 +50,15 @@ import com.lambda.context.SafeContext import com.lambda.event.Muteable import com.lambda.event.events.ButtonEvent import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.flag.ImGuiCol -import com.lambda.imgui.flag.ImGuiHoveredFlags -import com.lambda.imgui.flag.ImGuiMouseButton +import com.lambda.gui.component.Text +import com.lambda.gui.component.Tooltip +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.Press +import com.lambda.gui.core.observe +import com.lambda.gui.settings.Labeled +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look import com.lambda.threading.runSafe -import com.lambda.util.InputUtils import com.lambda.util.KeyCode import com.lambda.util.Mouse import com.lambda.util.StringUtils.capitalize @@ -56,6 +72,7 @@ import org.lwjgl.glfw.GLFW.GLFW_MOD_CONTROL import org.lwjgl.glfw.GLFW.GLFW_MOD_NUM_LOCK import org.lwjgl.glfw.GLFW.GLFW_MOD_SHIFT import org.lwjgl.glfw.GLFW.GLFW_MOD_SUPER +import org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_LEFT class KeybindSetting( name: String, @@ -87,14 +104,16 @@ class KeybindSetting( private val releaseListeners = mutableListOf Unit>() private val unsafeReleaseListeners = mutableListOf<(ButtonEvent) -> Unit>() - private var listening = false - override val isMuted get() = muteable?.isMuted == true && !alwaysListening init { - listenUnsafe { event -> onButtonEvent(event) } - listenUnsafe { event -> onButtonEvent(event) } + listenUnsafe(alwaysListen = true) { event -> + if (recorder === this) record(event) else if (!isMuted) onButtonEvent(event) + } + listenUnsafe(alwaysListen = true) { event -> + if (recorder === this) record(event) else if (!isMuted) onButtonEvent(event) + } } private fun onButtonEvent(event: ButtonEvent) { @@ -116,74 +135,68 @@ class KeybindSetting( } } - override fun ImGuiBuilder.buildLayout() { - text(name) - sameLine() - - val bind = value - val preview = - if (listening) "Press any key…" - else bind.name - - withId("##Bind-${this@KeybindSetting.hashCode()}") { - if (listening) { - withStyleColor(ImGuiCol.Button, 0.20f, 0.50f, 1.00f, 1.00f) { - withStyleColor(ImGuiCol.ButtonHovered, 0.25f, 0.60f, 1.00f, 1.00f) { - withStyleColor(ImGuiCol.ButtonActive, 0.20f, 0.50f, 0.95f, 1.00f) { - button(preview) + @Composable + override fun Gui() { + val colors = LambdaTheme.colors + val bind by observe { value } + val recording = recorder === this + + Labeled(name) { + Tooltip("Click, then press a key or mouse button. Backspace unbinds, Escape cancels.") { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .height(Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(if (recording) colors.secondary else colors.control) + .mouseClickable { + val stoppedHere = stopped === this@KeybindSetting && stoppedBy == Press.id + if (!stoppedHere) recorder = this@KeybindSetting } - } + .padding(horizontal = 4.dp) + ) { + Text( + text = if (recording) "Press a key" else bind.name, + color = if (recording) colors.onSecondary else colors.onControl, + maxLines = 1, + ) } - } else { - button(preview) { listening = true } } } + } - lambdaTooltip { - if (!listening) description.ifBlank { "Click to set. Esc cancels. Backspace/Delete unbinds." } - else "Listening… Press a key to bind. Esc to cancel. Backspace/Delete to unbind." - } - - if (listening && !isAnyItemHovered && isMouseClicked(ImGuiMouseButton.Left)) { - listening = false - } - - sameLine() - withId("##Unbind-${this@KeybindSetting.hashCode()}") { - smallButton("Unbind") { - value = Bind.EMPTY - listening = false - } + private fun record(event: ButtonEvent.Keyboard.Press) { + event.cancel() + val isModifier = event.keyCode in GLFW_KEY_LEFT_SHIFT..GLFW_KEY_RIGHT_SUPER + if (event.isRepeated || event.isPressed == isModifier) return + when (val key = event.translated) { + KeyCode.Unbound -> return + KeyCode.Escape -> Unit + KeyCode.Backspace, KeyCode.Delete -> value = Bind.EMPTY + else -> value = Bind(key.code, if (isModifier) 0 else event.modifiers, -1) } - onItemHover(ImGuiHoveredFlags.Stationary) { - lambdaTooltip("Clear binding") - } - - if (listening) { - InputUtils.newMouseEvent() - ?.let { - value = Bind(0, it.modifiers, it.button) - listening = false - return - } + recorder = null + } - InputUtils.newKeyboardEvent() - ?.let { - val isModKey = it.keyCode in GLFW_KEY_LEFT_SHIFT..GLFW_KEY_RIGHT_SUPER + private fun record(event: ButtonEvent.Mouse.Click) { + if (!event.isPressed) return + recorder = null + stopped = this + stoppedBy = Press.id + 1 + if (event.button == GLFW_MOUSE_BUTTON_LEFT) return + event.cancel() + value = Bind(0, event.modifiers, event.button) + } - // If a mod key is pressed first ignore it unless it was released without any other keys - if ((it.isPressed && !isModKey) || (it.isReleased && isModKey)) { - when (it.translated) { - KeyCode.Escape -> {} - KeyCode.Backspace, KeyCode.Delete -> value = Bind.EMPTY - else -> value = Bind(it.translated.code, it.modifiers, -1) - } + companion object { + private var recorder: KeybindSetting? by mutableStateOf(null) + private var stopped: KeybindSetting? = null + private var stoppedBy = 0L - listening = false - } + internal val isRecording get() = recorder != null - return - } + internal fun stopRecording() { + recorder = null } } @@ -196,22 +209,23 @@ class KeybindSetting( } optional(boolean("mouse button")) { isMouseButton -> executeWithResult { - val isMouse = if (isMouseButton != null) isMouseButton().value() else false - var bind = Bind.EMPTY - if (isMouse) { - val num = try { - nameArg().value().toInt() - } catch (_: NumberFormatException) { - return@executeWithResult failure("${nameArg().value()} doesn't match with a mouse button") - } - bind = Bind(0, 0, mouse = num) - } else { - bind = try { - Bind(KeyCode.valueOf(nameArg().value()).code, 0) - } catch (_: IllegalArgumentException) { - return@executeWithResult failure("${nameArg().value()} doesn't match with a bind") + val isMouse = isMouseButton != null && isMouseButton().value() + val bind = + if (isMouse) { + val num = + try { + nameArg().value().toInt() + } catch (_: NumberFormatException) { + return@executeWithResult failure("${nameArg().value()} doesn't match with a mouse button") + } + Bind(0, 0, mouse = num) + } else { + try { + Bind(KeyCode.valueOf(nameArg().value()).code, 0) + } catch (_: IllegalArgumentException) { + return@executeWithResult failure("${nameArg().value()} doesn't match with a bind") + } } - } trySetValue(bind) return@executeWithResult success() @@ -239,7 +253,6 @@ class KeybindSetting( fun onReleaseUnsafe(block: (ButtonEvent) -> Unit) = apply { unsafeReleaseListeners.add(block) } } -@Suppress("unused") @JsonIncludeProperties("key", "modifiers", "mouse") data class Bind( val key: Int, diff --git a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt index 0110a0590..c55a370c5 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt @@ -17,6 +17,10 @@ package com.lambda.config.settings.complex +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier import com.lambda.brigadier.argument.double import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -24,7 +28,10 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.component.NumberInput +import com.lambda.gui.core.observe +import com.lambda.gui.settings.Labeled +import com.lambda.gui.settings.NUMBER_FIELD_WIDTH import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess import net.minecraft.util.math.Vec3d @@ -37,9 +44,31 @@ class Vec3dSetting( visibility: () -> Boolean, defaultValue: Vec3d ) : Setting(name, description, defaultValue, layer, config, visibility) { - override fun ImGuiBuilder.buildLayout() { - inputVec3d(name, ::value as Vec3d) // FixMe: what the fuck - lambdaTooltip(description) + @Composable + override fun Gui() { + val vec by observe { value } + Labeled(name) { + val parse = + { text: String -> text.toDoubleOrNull()?.takeIf(Double::isFinite) } + NumberInput( + vec.x, + parse, + { value = Vec3d(it, vec.y, vec.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + vec.y, + parse, + { value = Vec3d(vec.x, it, vec.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + vec.z, + parse, + { value = Vec3d(vec.x, vec.y, it) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + } } override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { diff --git a/src/main/kotlin/com/lambda/config/settings/numeric/DoubleSetting.kt b/src/main/kotlin/com/lambda/config/settings/numeric/DoubleSetting.kt index b63fc0bcf..2528eb8d7 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/DoubleSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/DoubleSetting.kt @@ -17,7 +17,6 @@ package com.lambda.config.settings.numeric - import com.lambda.brigadier.argument.double import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -25,12 +24,9 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.settings.NumericSetting -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.type.ImInt import com.lambda.util.extension.CommandBuilder -import com.lambda.util.math.MathUtils.roundToStep import net.minecraft.command.CommandRegistryAccess -import kotlin.math.roundToInt +import java.math.BigDecimal /** * @see [com.lambda.config.Config] @@ -46,16 +42,7 @@ class DoubleSetting( override var step: Double, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { - override fun ImGuiBuilder.buildSlider() { - val maxIndex = ((range.endInclusive - range.start) / step).toInt() - val currentIndex = ((value - range.start) / step).roundToInt() - val imInt = ImInt(currentIndex) - slider("##$name", imInt, 0, maxIndex, "") { - value = (range.start + imInt.get() * step) - .roundToStep(step) - .coerceIn(range) - } - } + override fun convert(number: BigDecimal) = number.toDouble() override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(double(name, range.start, range.endInclusive)) { parameter -> diff --git a/src/main/kotlin/com/lambda/config/settings/numeric/FloatSetting.kt b/src/main/kotlin/com/lambda/config/settings/numeric/FloatSetting.kt index 65b0483ec..e17cf2bd2 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/FloatSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/FloatSetting.kt @@ -24,12 +24,9 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.settings.NumericSetting -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.type.ImInt import com.lambda.util.extension.CommandBuilder -import com.lambda.util.math.MathUtils.roundToStep import net.minecraft.command.CommandRegistryAccess -import kotlin.math.roundToInt +import java.math.BigDecimal /** * @see [com.lambda.config.Config] @@ -45,16 +42,7 @@ class FloatSetting( override var step: Float = 1f, unit: String, ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { - override fun ImGuiBuilder.buildSlider() { - val maxIndex = ((range.endInclusive - range.start) / step).toInt() - val currentIndex = ((value - range.start) / step).roundToInt() - val imInt = ImInt(currentIndex) - slider("##$name", imInt, 0, maxIndex, "") { - value = (range.start + imInt.get() * step) - .roundToStep(step) - .coerceIn(range) - } - } + override fun convert(number: BigDecimal) = number.toFloat() override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(float(name, range.start, range.endInclusive)) { parameter -> diff --git a/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt b/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt index 496f9dd95..4c61ff945 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt @@ -24,9 +24,10 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.settings.NumericSetting -import com.lambda.gui.dsl.ImGuiBuilder import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess +import java.math.BigDecimal +import java.math.RoundingMode /** * @see [com.lambda.config.Config] @@ -42,9 +43,8 @@ class IntegerSetting( override var step: Int = 1, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { - override fun ImGuiBuilder.buildSlider() { - slider("##$name", ::value, range.start, range.endInclusive, "") - } + override fun convert(number: BigDecimal) = + number.setScale(0, RoundingMode.HALF_UP).toInt() override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(integer(name, range.start, range.endInclusive)) { parameter -> diff --git a/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt b/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt index 6d2512575..bfbb72325 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt @@ -24,10 +24,10 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.settings.NumericSetting -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.type.ImInt import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess +import java.math.BigDecimal +import java.math.RoundingMode /** * @see [com.lambda.config.Config] @@ -43,15 +43,7 @@ class LongSetting( override var step: Long = 1, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { - override fun ImGuiBuilder.buildSlider() { - // FixMe: No worky for super large numbers - val maxIndex = ((range.endInclusive - range.start) / step).toInt() - val currentIndex = ((value - range.start) / step).toInt() - val imInt = ImInt(currentIndex) - slider("##$name", imInt, 0, maxIndex, "") { - value = (range.start + imInt.get() * step).coerceIn(range) - } - } + override fun convert(number: BigDecimal) = number.setScale(0, RoundingMode.HALF_UP).toLong() override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(long(name, range.start, range.endInclusive)) { parameter -> diff --git a/src/main/kotlin/com/lambda/gui/snap/Guide.kt b/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt similarity index 55% rename from src/main/kotlin/com/lambda/gui/snap/Guide.kt rename to src/main/kotlin/com/lambda/event/events/ComposeEvent.kt index 9001658e1..e45fdfb11 100644 --- a/src/main/kotlin/com/lambda/gui/snap/Guide.kt +++ b/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt @@ -15,14 +15,26 @@ * along with this program. If not, see . */ -package com.lambda.gui.snap +package com.lambda.event.events -data class Guide( - val orientation: Orientation, - val pos: Float, - val strength: Int, - val kind: Kind -) { - enum class Orientation { Vertical, Horizontal } - enum class Kind { ElementEdge, ElementCenter, ScreenCenter, Grid } +import androidx.compose.runtime.Composable +import com.lambda.event.Event + +sealed class ComposeEvent : Event { + private val added = mutableListOf<@Composable () -> Unit>() + val contents: List<@Composable () -> Unit> get() = added + + fun content(content: @Composable () -> Unit) { + added += content + } + + sealed class Hud : ComposeEvent() { + class Pre : Hud() + class Post : Hud() + } + + sealed class Gui : ComposeEvent() { + class Pre : Gui() + class Post : Gui() + } } diff --git a/src/main/kotlin/com/lambda/event/events/GuiEvent.kt b/src/main/kotlin/com/lambda/event/events/GuiEvent.kt index 4cbd037f0..a5e3fa861 100644 --- a/src/main/kotlin/com/lambda/event/events/GuiEvent.kt +++ b/src/main/kotlin/com/lambda/event/events/GuiEvent.kt @@ -17,27 +17,12 @@ package com.lambda.event.events -import com.lambda.event.Event import com.lambda.event.callback.Cancellable import com.lambda.event.callback.ICancellable import net.minecraft.block.entity.SignBlockEntity import net.minecraft.client.gui.screen.Screen sealed class GuiEvent { - /** - * Triggered when a new ImGui frame is created and the client - * is allowed to submit any command from this point until [EndImguiFrame]. - */ - data object NewImguiFrame : Event - - /** - * Triggered when the previous ImGui frame is ended and the client - * is able to perform OpenGL calls. - * - * By default, the game's framebuffer is bound. - */ - data object EndImguiFrame : Event - /** * Triggered when the sign editor GUI is opened. Can be canceled. */ diff --git a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt index 911bb1d77..6eeff19c9 100644 --- a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt +++ b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt @@ -300,4 +300,61 @@ object LambdaRenderPipelines : Loadable { ) .build() ) + + private fun guiPass( + name: String, + fragmentShader: Identifier, + samplers: List, + uniform: String? = null, + blend: BlendFunction? = null, + ): RenderPipeline = + RenderPipelines.register( + RenderPipeline.builder() + .withLocation(Identifier.of("lambda", "pipeline/$name")) + .withVertexShader("core/screenquad") + .withFragmentShader(fragmentShader) + .apply { + samplers.forEach { withSampler(it) } + uniform?.let { withUniform(it, UniformType.UNIFORM_BUFFER) } + blend?.let { withBlend(it) } ?: withoutBlend() + } + .withDepthWrite(false) + .withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST) + .withCull(false) + .withVertexFormat(VertexFormats.EMPTY, VertexFormat.DrawMode.TRIANGLES) + .build() + ) + + val GUI_BLIT = + guiPass( + "gui_blit", + Identifier.ofVanilla("core/blit_screen"), + samplers = listOf("InSampler"), + blend = BlendFunction.TRANSLUCENT_PREMULTIPLIED_ALPHA + ) + + val GUI_COMPOSITE = + guiPass( + "gui_composite", + Identifier.of("lambda", "core/gui_composite"), + samplers = listOf("GuiSampler", "BackdropSampler", "HaloSampler"), + uniform = "GuiEffects", + blend = BlendFunction.TRANSLUCENT_PREMULTIPLIED_ALPHA + ) + + val GUI_BLUR_DOWN = + guiPass( + "gui_blur_down", + Identifier.of("lambda", "core/gui_blur_down"), + samplers = listOf("InSampler"), + uniform = "BlurSpread" + ) + + val GUI_BLUR_UP = + guiPass( + "gui_blur_up", + Identifier.of("lambda", "core/gui_blur_up"), + samplers = listOf("InSampler"), + uniform = "BlurSpread" + ) } diff --git a/src/main/kotlin/com/lambda/gui/DearImGui.kt b/src/main/kotlin/com/lambda/gui/DearImGui.kt deleted file mode 100644 index fba0d5cf1..000000000 --- a/src/main/kotlin/com/lambda/gui/DearImGui.kt +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui - -import com.lambda.Lambda.mc -import com.lambda.core.Loadable -import com.lambda.event.EventFlow.post -import com.lambda.event.events.GuiEvent -import com.lambda.gui.components.ClickGuiLayout -import com.lambda.imgui.ImFontConfig -import com.lambda.imgui.ImFontGlyphRangesBuilder -import com.lambda.imgui.ImGui -import com.lambda.imgui.ImGuiIO -import com.lambda.imgui.extension.implot.ImPlot -import com.lambda.imgui.flag.ImGuiConfigFlags -import com.lambda.imgui.gl3.ImGuiImplGl3 -import com.lambda.imgui.glfw.ImGuiImplGlfw -import com.lambda.util.stream -import com.mojang.blaze3d.opengl.GlStateManager -import com.mojang.blaze3d.systems.RenderSystem -import net.minecraft.client.gl.GlBackend -import net.minecraft.client.texture.GlTexture -import org.lwjgl.opengl.GL30.GL_FRAMEBUFFER -import kotlin.math.abs - -object DearImGui : Loadable { - val implGlfw = ImGuiImplGlfw() - val implGl3 = ImGuiImplGl3() - - const val EXTERNAL_LINK = '↗' - const val BREAD_CRUMB_SEPARATOR = '»' - const val BASE_FONT_SCALE = 13f - - val io: ImGuiIO get() = ImGui.getIO() - const val DEFAULT_FLAGS = ImGuiConfigFlags.NavEnableKeyboard or // Enable Keyboard Controls - ImGuiConfigFlags.NavEnableSetMousePos or // Move the cursor using the keyboard - ImGuiConfigFlags.DockingEnable - - private var lastScale = 0f - private var lastScaleChangeTimestamp = 0L - private var scaleChanged = false - private var targetScale = 0f - - private fun updateScale(scale: Float) { - val glyphRanges = ImFontGlyphRangesBuilder().apply { - addRanges(io.fonts.glyphRangesDefault) - addRanges(io.fonts.glyphRangesGreek) - addChar(EXTERNAL_LINK) - addChar(BREAD_CRUMB_SEPARATOR) - }.buildRanges() - val fontConfig = ImFontConfig() - val size = BASE_FONT_SCALE * scale - with(io.fonts) { - clear() - addFontFromMemoryTTF("fonts/FiraSans-Regular.ttf".stream.readAllBytes(), size, fontConfig, glyphRanges) - addFontFromMemoryTTF("fonts/FiraSans-Bold.ttf".stream.readAllBytes(), size, fontConfig, glyphRanges) - addFontFromMemoryTTF("fonts/MinecraftDefault-Regular.ttf".stream.readAllBytes(), size, fontConfig, glyphRanges) - build() - } - implGl3.createFontsTexture() - } - - fun render() { - val userPercent = ClickGuiLayout.scaleSetting / 100.0 - val dpi = ClickGuiLayout.deviceScaleMultiplier() - val base = ClickGuiLayout.BASE_SCALE_MULTI * dpi - val fontScaleSetting = ClickGuiLayout.fontScale - val scale = (base * userPercent * fontScaleSetting).toFloat() - - if (lastScale == 0f) { - targetScale = scale - updateScale(targetScale) - lastScale = targetScale - } - - if (scale > 0 && abs(scale - lastScale) > 0.001f) { - if (abs(scale - targetScale) > 0.001f) { - lastScaleChangeTimestamp = System.currentTimeMillis() - scaleChanged = true - targetScale = scale - } - } - - if (scaleChanged && (lastScaleChangeTimestamp + 1000 < System.currentTimeMillis())) { - updateScale(targetScale) - lastScale = targetScale - scaleChanged = false - } - - val framebuffer = mc.framebuffer - val prevFramebuffer = (framebuffer.getColorAttachment() as GlTexture).getOrCreateFramebuffer( - (RenderSystem.getDevice() as GlBackend).bufferManager, - null - ) - - // When the GUI is open over a menu screen, the in-game world blur (applied via the - // screen's GUI render layers) isn't available, so blur the whole framebuffer here — - // after the parent screen has fully rendered but before ImGui draws on top. - if (ClickGuiLayout.open && ClickGuiLayout.backgroundBlur && LambdaScreen.parentScreen != null) { - mc.gameRenderer.renderBlur() - } - - GlStateManager._glBindFramebuffer(GL_FRAMEBUFFER, prevFramebuffer) - - implGlfw.newFrame() - implGl3.newFrame() - - ClickGuiLayout.applyStyle(lastScale) - ImGui.newFrame() - - GuiEvent.NewImguiFrame.post() - ImGui.render() - GuiEvent.EndImguiFrame.post() - - implGl3.renderDrawData(ImGui.getDrawData()) - - GlStateManager._glBindFramebuffer(GL_FRAMEBUFFER, 0) - } - - fun destroy() { - implGlfw.shutdown() - implGl3.shutdown() - ImGui.destroyContext() - ImPlot.destroyContext() - } - - init { - ImGui.createContext() - ImPlot.createContext() - - io.configFlags = DEFAULT_FLAGS - io.iniFilename = "lambda.ini" - - implGlfw.init(mc.window.handle, true) - implGl3.init() - } -} diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt new file mode 100644 index 000000000..486fbee9c --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -0,0 +1,114 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui + +import com.lambda.config.Config +import com.lambda.config.Tab +import com.lambda.config.categories.GuiCategory +import com.lambda.config.entries.onValueChange +import com.lambda.core.Loadable +import com.lambda.util.KeyCode +import com.lambda.util.WindowUtils.setLambdaWindowIcon +import net.minecraft.SharedConstants +import net.minecraft.client.util.Icons +import java.awt.Color + +@Suppress("unused") +object GuiConfig : Loadable, Config("GUI", GuiCategory) { + private const val GENERAL_TAB = "General" + private const val SNAPPING_TAB = "Snapping" + + @Tab(GENERAL_TAB) val keybind by setting("Keybind", KeyCode.Y, "Opens and closes the click GUI", screenCheck = false) + .onPressUnsafe { LambdaGui.toggle() } + @Tab(GENERAL_TAB) val setLambdaWindowIcon by setting("Set Lambda Window Icon", true) + .onValueChange { _, to -> + if (to) setLambdaWindowIcon() + else { + val icon = + if (SharedConstants.getGameVersion().stable()) Icons.RELEASE + else Icons.SNAPSHOT + mc.window.setIcon(mc.defaultResourcePack, icon) + } + } + @JvmStatic + @Tab(GENERAL_TAB) val setLambdaWindowTitle by setting("Set Lambda Window Title", true) + .onValueChange { _, _ -> mc.updateWindowTitle() } + @Tab(GENERAL_TAB) val lambdaTitleAppendixName by setting("Append Username", true) { setLambdaWindowTitle } + .onValueChange { _, _ -> mc.updateWindowTitle() } + @Tab(GENERAL_TAB) val keepSettingsOpen by setting("Keep Settings Open", false, "Leaves a module's settings open when the click GUI closes, so they are still there when it opens again") + @Tab(GENERAL_TAB) private val resetWindowLayout by setting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded") + + @Tab(SNAPPING_TAB) val snapEnabled by setting("Enable Snapping", true, "Master toggle for snapping HUD elements and click GUI windows into line when they are dragged") + @Tab(SNAPPING_TAB) val snapKey by setting("Snap Key", KeyCode.LeftShift, "What is dragged only snaps while this is held. Unbind it to snap all the time.") { snapEnabled } + @Tab(SNAPPING_TAB) val showSnapLines by setting("Show Snap Lines", false, "Draw the grid, and the line an element snaps to, while it is dragged") { snapEnabled } + @Tab(SNAPPING_TAB) val gridSize by setting("Grid Size", 25f, 2f..128f, 1f, "Grid step") { snapEnabled } + @Tab(SNAPPING_TAB) val snapToEdges by setting("Snap To Element Edges", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToCenters by setting("Snap To Element Centers", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToScreenCenter by setting("Snap To Screen Center", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToGrid by setting("Snap To Grid", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceElement by setting("Snap Distance (Elements)", 20f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceScreen by setting("Snap Distance (Screen Center)", 14f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceGrid by setting("Snap Distance (Grid)", 12f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapLineColor by setting("Snap Line Color", Color(255, 160, 0, 220)) { snapEnabled && showSnapLines } + + internal data class WindowPlacement( + val x: Float, + val y: Float, + val collapsed: Boolean + ) { + val inRow get() = x.isNaN() || y.isNaN() + + companion object { + fun inRow(collapsed: Boolean) = WindowPlacement(Float.NaN, Float.NaN, collapsed) + } + } + + private var windowPlacements by property("") + private var decodedFrom: String? = null + private var decoded = emptyMap() + + internal var windows: Map + get() { + val saved = windowPlacements + if (saved != decodedFrom) { + decodedFrom = saved + decoded = saved.split(';').mapNotNull(::decodeWindow).toMap() + } + return decoded + } + set(value) { + windowPlacements = + value.entries.joinToString(";") { (tag, window) -> + "$tag:${window.x},${window.y},${window.collapsed}" + } + } + + internal fun resetWindows() { + windows = emptyMap() + } + + private fun decodeWindow(entry: String): Pair? { + val (tag, fields) = entry.split(':').takeIf { it.size == 2 } ?: return null + val (x, y, collapsed) = fields.split(',').takeIf { it.size == 3 } ?: return null + return tag to WindowPlacement( + x.toFloatOrNull() ?: return null, + y.toFloatOrNull() ?: return null, + collapsed.toBoolean() + ) + } +} diff --git a/src/main/kotlin/com/lambda/gui/GuiScreen.kt b/src/main/kotlin/com/lambda/gui/GuiScreen.kt new file mode 100644 index 000000000..f0ee54200 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/GuiScreen.kt @@ -0,0 +1,155 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui + +import androidx.compose.ui.geometry.Offset +import com.lambda.Lambda.mc +import com.lambda.config.settings.complex.KeybindSetting +import com.lambda.gui.clickgui.ClickGuiState +import com.lambda.gui.component.TextFocus +import com.lambda.module.modules.combat.autodisconnect.AutoDisconnectScreen +import com.lambda.util.render.CursorOverrideProvider +import net.minecraft.client.gui.Click +import net.minecraft.client.gui.DrawContext +import net.minecraft.client.gui.cursor.Cursor +import net.minecraft.client.gui.screen.Screen +import net.minecraft.client.gui.screen.TitleScreen +import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen +import net.minecraft.client.input.CharInput +import net.minecraft.client.input.KeyInput +import net.minecraft.text.Text +import org.lwjgl.glfw.GLFW + +object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { + private var parent: Screen? = null + + private val backgroundScreens = + listOf( + TitleScreen::class.java, + MultiplayerScreen::class.java, + AutoDisconnectScreen::class.java, + ) + + fun canOpenOver(screen: Screen?) = + screen == null || backgroundScreens.any { it.isInstance(screen) } + + internal fun show() { + parent = mc.currentScreen + (parent as? OverlayBackgroundScreen)?.onOverlaidByGui() + mc.setScreen(this) + } + + override fun close() { + val previous = parent + parent = null + mc.setScreen(previous) + } + + override fun removed() { + KeybindSetting.stopRecording() + LambdaGui.onScreenRemoved() + } + + override fun shouldPause() = false + + override fun render( + context: DrawContext, + mouseX: Int, + mouseY: Int, + deltaTicks: Float + ) = Unit + + override fun renderBackground( + context: DrawContext, + mouseX: Int, + mouseY: Int, + delta: Float + ) { + val parent = parent + if (parent != null) { + parent.renderBackground(context, -1, -1, delta) + parent.render(context, -1, -1, delta) + context.drawDeferredElements() + } + } + + override fun resize(width: Int, height: Int) { + super.resize(width, height) + parent?.resize(width, height) + } + + override fun getCursorOverride(mouseX: Int, mouseY: Int): Cursor? = LambdaGui.cursor + + override fun mouseMoved(mouseX: Double, mouseY: Double) { + LambdaGui.input?.move(scenePosition(mouseX, mouseY)) + } + + override fun mouseClicked(click: Click, doubled: Boolean): Boolean { + val position = scenePosition(click.x(), click.y()) + TextFocus.press(position) + LambdaGui.input?.run { + move(position) + button(click.button(), true, click.modifiers()) + } + return true + } + + override fun mouseReleased(click: Click): Boolean { + LambdaGui.input?.run { + move(scenePosition(click.x(), click.y())) + button(click.button(), false, click.modifiers()) + } + return true + } + + override fun mouseScrolled( + mouseX: Double, + mouseY: Double, + horizontalAmount: Double, + verticalAmount: Double + ): Boolean { + LambdaGui.input?.scroll(horizontalAmount, verticalAmount) + return true + } + + override fun keyPressed(input: KeyInput): Boolean { + if (LambdaGui.input?.key(input.key(), true, input.modifiers()) == true) return true + if (input.key() == GLFW.GLFW_KEY_F && input.modifiers() and GLFW.GLFW_MOD_CONTROL != 0) { + ClickGuiState.focusSearch = LambdaGui.screen == LambdaGui.Screen.ClickGui + return true + } + if (input.isEscape && LambdaGui.onEscape?.invoke() != true) LambdaGui.back() + return true + } + + override fun keyReleased(input: KeyInput): Boolean { + LambdaGui.input?.key(input.key(), false, input.modifiers()) + return true + } + + override fun charTyped(input: CharInput): Boolean { + LambdaGui.input?.type(input.codepoint()) + return true + } + + private fun scenePosition(x: Double, y: Double): Offset { + val scale = mc.window.scaleFactor + return Offset((x * scale).toFloat(), (y * scale).toFloat()) + } + +} diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt new file mode 100644 index 000000000..8f025534a --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -0,0 +1,414 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui + +import androidx.compose.animation.core.animate +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.graphics.layer.GraphicsLayer +import androidx.compose.ui.graphics.rememberGraphicsLayer +import androidx.compose.ui.platform.LocalClipboard +import androidx.compose.ui.unit.IntSize +import com.lambda.Lambda.LOG +import com.lambda.Lambda.mc +import com.lambda.config.settings.complex.KeybindSetting +import com.lambda.core.Loadable +import com.lambda.event.events.ClientEvent +import com.lambda.event.events.ComposeEvent +import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe +import com.lambda.gui.clickgui.ClickGui +import com.lambda.gui.component.KeyboardFocus +import com.lambda.gui.component.TextFocus +import com.lambda.gui.core.ComposeSlot +import com.lambda.gui.core.GameClipboard +import com.lambda.gui.core.LocalObservations +import com.lambda.gui.core.Observations +import com.lambda.gui.core.Retained +import com.lambda.gui.core.SceneHost +import com.lambda.gui.core.SceneInput +import com.lambda.gui.hud.Hud +import com.lambda.gui.hud.HudEditor +import com.lambda.gui.hud.HudLayer +import com.lambda.gui.render.GuiCompositor +import com.lambda.gui.render.ItemAtlas +import com.lambda.gui.settings.SettingsList +import com.lambda.gui.theme.GuiInterrupt +import com.lambda.gui.theme.GuiTransition +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Motion +import com.lambda.module.modules.client.AutoUpdater +import com.lambda.module.modules.client.Client +import com.lambda.module.modules.client.Style +import com.lambda.sound.LambdaSound +import com.lambda.sound.SoundHandler.play +import com.lambda.util.CommunicationUtils.warn +import kotlinx.coroutines.Job +import net.minecraft.client.gui.cursor.Cursor +import org.jetbrains.skia.FontMgr +import org.jetbrains.skia.impl.Library +import kotlin.concurrent.thread +import kotlin.math.abs + +object LambdaGui : Loadable { + private const val REFERENCE_HEIGHT = 540f + private const val MAX_FAILURES = 3 + private const val FAILURE_WINDOW_NANOS = 60_000_000_000L + + enum class Screen { + ClickGui, + HudEditor + } + + var screen: Screen? by mutableStateOf(null) + private set + + private var host: SceneHost? = null + private var failures = 0 + private var failedAt = 0L + private var broken = false + + private val beneathHud = ComposeSlot { ComposeEvent.Hud.Pre() } + private val aboveHud = ComposeSlot { ComposeEvent.Hud.Post() } + private val beneathGui = ComposeSlot { ComposeEvent.Gui.Pre() } + private val aboveGui = ComposeSlot { ComposeEvent.Gui.Post() } + private var underlay: GraphicsLayer? = null + private var layered by mutableStateOf(false) + + private var settled = true + private var warmingUp by mutableStateOf(false) + private var warmedUp = false + + private var shownPresence by mutableFloatStateOf(0f) + private var animation: Job? = null + var leaving by mutableStateOf(false) + private set + internal var restarts by mutableIntStateOf(0) + private set + internal val presence + get() = + if (warmingUp) 1f + else shownPresence + internal val transitions: Collection + get() = + if (leaving) Style.closeStyle + else Style.openStyle + internal val unfoldsOpen + get() = + Style.animations && + Style.openAnimation && + GuiTransition.Unfold in Style.openStyle + private val showsClickGui + get() = screen == Screen.ClickGui || leaving + internal val foldsClosed + get() = leaving && GuiTransition.Unfold in Style.closeStyle + + private val observations = Observations() + private val clickGuiObservations = Observations() + + internal val input: SceneInput? get() = host?.input + internal val cursor: Cursor? get() = host?.platform?.cursor + internal var onEscape: (() -> Boolean)? = null + + val isCapturingKeys get() = TextFocus.isTyping || KeybindSetting.isRecording + + init { + listenUnsafe { shutDown() } + } + + override fun load(): String { + thread(name = "Lambda GUI preload", isDaemon = true) { + runCatching { + prepareSkiko() + Library.staticLoad() + FontMgr.default + }.onFailure { LOG.warn("Could not preload the GUI's native library", it) } + } + return "Loaded GUI" + } + + fun toggle() { + if (isCapturingKeys) return + if (screen == null) open(Screen.ClickGui) + else close() + } + + fun close() { + val animated = + Style.animations && Style.closeAnimation && Style.closeStyle.isNotEmpty() + if (screen == Screen.ClickGui && animated) { + if (shownPresence < 1f) skipTo(1f) + leaving = true + } + GuiScreen.close() + } + + private fun skipTo(end: Float) { + if (Style.interruptedAnimation != GuiInterrupt.Finish) return + jumpTo(end) + restarts++ + } + + private fun jumpTo(value: Float) { + animation?.cancel() + shownPresence = value + } + + fun open(screen: Screen) { + if (broken) { + warn("Lambda's GUI stopped after repeated errors. Restart the game to bring it back.") + return + } + if (this.screen == null) { + if (!GuiScreen.canOpenOver(mc.currentScreen)) return + if (leaving) skipTo(0f) + else jumpTo(0f) + if (Client.clientSounds) LambdaSound.ModuleOn.play() + GuiScreen.show() + AutoUpdater.onGuiOpened() + } + leaving = false + this.screen = screen + } + + fun back() { + if (screen == Screen.HudEditor) screen = Screen.ClickGui + else close() + } + + internal fun onScreenRemoved() { + if (screen == null) return + if (Client.clientSounds) LambdaSound.ModuleOff.play() + screen = null + if (!leaving) jumpTo(0f) + settled = false + input?.release() + host?.platform?.cursor = null + } + + fun render() { + if (broken) return + val size = IntSize(mc.window.framebufferWidth, mc.window.framebufferHeight) + if (size.width <= 0 || size.height <= 0) return + val density = size.height / REFERENCE_HEIGHT * Style.scale + + if (!warmedUp) { + warmedUp = true + warmUp(size, density) + } + val showsGui = screen != null || leaving + beneathHud.collect() + aboveHud.collect() + beneathGui.collect(showsGui) + aboveGui.collect(showsGui) + val showsHud = !beneathHud.isEmpty || !aboveHud.isEmpty || screen == null && Hud.shown.isNotEmpty() + if (!showsGui && !showsHud && settled) return + layered = showsGui && showsHud + + try { + val host = host ?: createHost() + settled = true + + observations.refresh() + Look.refresh() + if (screen == Screen.ClickGui) clickGuiObservations.refresh() + val sceneChanged = host.advance(size, density) + val itemsChanged = ItemAtlas.render() + val redraw = sceneChanged || itemsChanged + if (redraw) host.draw(underlay.takeIf { layered }, ItemAtlas::import) + + if (layered) host.underlayTexture?.let(GuiCompositor::blit) + GuiCompositor.composite( + host.texture ?: return, + size.width, + size.height, + redraw, + effects(density) + ) + } catch (e: Throwable) { + if (e is OutOfMemoryError) throw e + fail(e) + } + } + + private fun fail(error: Throwable) { + val now = System.nanoTime() + if (now - failedAt > FAILURE_WINDOW_NANOS) failures = 0 + failedAt = now + broken = ++failures >= MAX_FAILURES + LOG.error( + if (broken) "Lambda's interface failed again and was switched off" + else "Lambda's interface failed and is being rebuilt", + error + ) + + val failed = host + host = null + underlay = null + ItemAtlas.release() + runCatching { failed?.closeAndFree() }.onFailure { + LOG.warn("Could not free the failed interface", it) + } + observations.active.clear() + clickGuiObservations.active.clear() + if (screen != null) GuiScreen.close() + warn( + if (broken) "Lambda's interface stopped after repeated errors. Check the log, and restart the game to bring it back." + else "Lambda's interface hit an error and was restarted. Check the log for what went wrong." + ) + } + + private fun warmUp(size: IntSize, density: Float) { + val start = System.nanoTime() + try { + val host = createHost() + warmingUp = true + host.advance(size, density) + host.draw() + warmingUp = false + host.advance(size, density) + LOG.info("Prepared the GUI in ${(System.nanoTime() - start) / 1_000_000} ms") + } catch (e: Throwable) { + LOG.warn("Could not prepare the GUI ahead of its first use", e) + warmingUp = false + val failed = host + host = null + ItemAtlas.release() + runCatching { failed?.closeAndFree() } + } + } + + private fun createHost(): SceneHost { + prepareSkiko() + return SceneHost(Motion) { Content() }.also { host = it } + } + + @Composable + private fun Content() { + CompositionLocalProvider( + LocalObservations provides observations, + LocalClipboard provides GameClipboard + ) { + LambdaTheme { + KeyboardFocus.Layer() + Reveal.Expiry() + Presence() + + Underlay { + beneathHud.Content() + if (screen == null) HudLayer() + aboveHud.Content() + } + beneathGui.Content() + if (screen == Screen.HudEditor) HudEditor() + Retained( + shown = showsClickGui || warmingUp, + clickGuiObservations + ) { + ClickGui() + } + aboveGui.Content() + if (warmingUp) WarmUp() + } + } + } + + @Composable + private fun Underlay(content: @Composable () -> Unit) { + val layer = rememberGraphicsLayer() + SideEffect { underlay = layer } + Box( + modifier = Modifier + .fillMaxSize() + .drawWithContent { + if (layered) layer.record { this@drawWithContent.drawContent() } + else drawContent() + }, + ) { content() } + } + + @Composable + private fun Presence() { + val present = screen == Screen.ClickGui + LaunchedEffect(present) { + animation = coroutineContext[Job] + val target = + if (present) 1f + else 0f + val animated = + if (present) Style.openAnimation && Style.openStyle.isNotEmpty() + else leaving + if (animated) { + val spec = Motion.gui(abs(target - shownPresence)) + animate(shownPresence, target, animationSpec = spec) { value, _ -> + shownPresence = value + } + } + else shownPresence = target + if (!present) leaving = false + } + } + + @Composable + private fun WarmUp() { + SettingsList(Style.settingLayers) + } + + private fun effects(density: Float): GuiCompositor.Effects { + if (screen == null && !leaving) return GuiCompositor.Effects.NONE + val strength = + if (showsClickGui) presence + else 1f + return GuiCompositor.Effects( + frost = + if (Style.blur) Style.blurRadius * density * strength + else 0f, + glow = + if (Style.glow && showsClickGui) Style.glowRadius * density + else 0f, + glowIntensity = Style.glowIntensity * strength, + glowColorA = Style.glowColorA, + glowColorB = Style.glowColorB, + dim = + if (Style.dimBackground && showsClickGui) Style.dimStrength * presence + else 0f, + ) + } + + private fun shutDown() { + host?.close() + host = null + } + + private fun prepareSkiko() { + if (System.getProperty("skiko.renderApi") != null) return + System.setProperty("skiko.renderApi", "OPENGL") + System.setProperty("skiko.macos.opengl.enabled", "true") + } +} diff --git a/src/main/kotlin/com/lambda/gui/LambdaScreen.kt b/src/main/kotlin/com/lambda/gui/LambdaScreen.kt deleted file mode 100644 index 64b3c2804..000000000 --- a/src/main/kotlin/com/lambda/gui/LambdaScreen.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui - -import com.lambda.gui.components.ClickGuiLayout -import net.minecraft.client.gui.DrawContext -import net.minecraft.client.gui.screen.Screen -import net.minecraft.text.Text - -object LambdaScreen : Screen(Text.of("Lambda")) { - /** - * The screen the GUI was opened over (e.g. the title screen). - * Null when opened in-game; in that case closing returns to gameplay. - */ - var parentScreen: Screen? = null - - override fun shouldPause() = false - override fun removed() = ClickGuiLayout.close() - override fun render(context: DrawContext?, mouseX: Int, mouseY: Int, deltaTicks: Float) {} - - override fun renderBackground(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { - if (parentScreen == null) { - // In-game: keep vanilla behavior (blur + darken the rendered world). - super.renderBackground(context, mouseX, mouseY, delta) - return - } - // Off-screen mouse coords keep the parent's widgets from showing a hover state. - parentScreen?.renderBackground(context, -1, -1, delta) - parentScreen?.render(context, -1, -1, delta) - // Flush deferred elements (e.g. widget text) so the darkening overlay covers them. - context.drawDeferredElements() - // NOTE: no GUI-layer applyBlur() here. MC's layer blur only blurs background - // layers, never foreground widgets. To blur the whole parent (widgets included) - // we run a framebuffer-level blur in DearImGui.render() after the full GUI pass. - } - - override fun resize(width: Int, height: Int) { - super.resize(width, height) - parentScreen?.resize(width, height) - } - - override fun close() { - val previous = parentScreen - parentScreen = null - client?.setScreen(previous) - } - - override fun applyBlur(context: DrawContext?) { - if (!ClickGuiLayout.backgroundBlur) return - super.applyBlur(context) - } - - override fun renderDarkening(context: DrawContext?) { - if (!ClickGuiLayout.backgroundDarkening) return - super.renderDarkening(context) - } -} diff --git a/src/main/kotlin/com/lambda/gui/MenuBar.kt b/src/main/kotlin/com/lambda/gui/MenuBar.kt deleted file mode 100644 index df50b2a31..000000000 --- a/src/main/kotlin/com/lambda/gui/MenuBar.kt +++ /dev/null @@ -1,534 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui - -import com.lambda.Lambda -import com.lambda.Lambda.REPO_URL -import com.lambda.Lambda.mc -import com.lambda.command.CommandRegistry -import com.lambda.config.ConfigLoader -import com.lambda.config.ConfigLoader.configs -import com.lambda.config.automation.AutomationConfig -import com.lambda.config.automation.UserAutomationConfig -import com.lambda.config.categories.UserAutomationCategory -import com.lambda.core.Loader -import com.lambda.event.EventFlow -import com.lambda.graphics.texture.TextureOwner.upload -import com.lambda.gui.DearImGui.EXTERNAL_LINK -import com.lambda.gui.components.ClickGuiLayout -import com.lambda.gui.components.HudGuiLayout -import com.lambda.gui.components.QuickSearch -import com.lambda.gui.components.SettingsWidget.buildConfigSettingsContext -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImGui -import com.lambda.imgui.flag.ImGuiCol -import com.lambda.imgui.flag.ImGuiStyleVar -import com.lambda.imgui.flag.ImGuiWindowFlags -import com.lambda.imgui.type.ImBoolean -import com.lambda.interaction.handler.handlers.BaritoneHandler -import com.lambda.module.ModuleRegistry -import com.lambda.module.ModuleRegistry.moduleNameMap -import com.lambda.module.ModuleTag -import com.lambda.network.LambdaAPI -import com.lambda.threading.runSafe -import com.lambda.util.CommunicationUtils.info -import com.lambda.util.Diagnostics.gatherDiagnostics -import com.lambda.util.FolderRegistry -import com.lambda.util.FolderRegistry.minecraft -import com.mojang.blaze3d.platform.TextureUtil -import net.fabricmc.loader.api.FabricLoader -import net.minecraft.client.gui.screen.DebugOptionsScreen -import net.minecraft.network.packet.c2s.play.ChangeGameModeC2SPacket -import net.minecraft.server.command.GameModeCommand -import net.minecraft.util.Util -import net.minecraft.world.GameMode -import java.util.* - -object MenuBar { - private var aboutRequested = false - var newConfigName = "" - val headerLogo = upload("textures/lambda_text_color.png") - val lambdaLogo = upload("textures/lambda.png") - val githubLogo = upload("textures/github_logo.png") - - var height = 0f - - fun ImGuiBuilder.buildMenuBar() { - mainMenuBar { - height = windowHeight - - lambdaMenu() - menu("HUD") { buildHudMenu() } - menu("GUI") { buildGuiMenu() } - menu("Modules") { buildModulesMenu() } - menu("Automation Configs") { buildAutomationConfigsMenu() } - menu("Minecraft") { buildMinecraftMenu() } - menu("Help") { buildHelpMenu() } - buildGitHubReference() - } - - if (aboutRequested) { - ImGui.openPopup("About Lambda") - aboutRequested = false - } - - aboutPopup() - } - - private fun ImGuiBuilder.lambdaMenu() { - ImGui.pushStyleColor(ImGuiCol.Text, 0) - val opened = ImGui.beginMenu("Lam") - - val headerW = itemRectMaxX - itemRectMinX - val headerH = itemRectMaxY - itemRectMinY - - val pad = 2f - val lambdaIconSize = (headerH - pad * 2f).coerceAtLeast(1f) - val iconX = itemRectMinX + (headerW - lambdaIconSize) * 0.5f - val iconY = itemRectMinY + (headerH - lambdaIconSize) * 0.5f - - foregroundDrawList.addImage( - lambdaLogo.id.toLong(), - iconX, iconY, - iconX + lambdaIconSize, iconY + lambdaIconSize - ) - ImGui.popStyleColor() - - if (opened) { - buildLambdaMenu() - ImGui.endMenu() - } - } - - private fun ImGuiBuilder.buildLambdaMenu() { - menu("Save Config...") { - menuItem("Save All Configs") { - ConfigLoader.configCategories.forEach { it.trySaveToFile(true) } - info("Saved ${ConfigLoader.configCategories.size} configuration files.") - } - ConfigLoader.configCategories.forEach { config -> - menuItem("Save ${config.name}") { - config.trySaveToFile(true) - info("Saved ${config.name}") - } - } - } - menu("Load Config...") { - menuItem("Load All Configs") { - ConfigLoader.configCategories.forEach { it.tryLoadFromFile() } - info("Loaded ${ConfigLoader.configCategories.size} configuration files.") - } - ConfigLoader.configCategories.forEach { config -> - menuItem("Load ${config.name}") { - config.tryLoadFromFile() - info("Loaded ${config.name}") - } - } - } - separator() - menu("Settings") { - menu("HUD Settings") { - buildConfigSettingsContext(HudGuiLayout) - } - menu("GUI Settings") { - buildConfigSettingsContext(ClickGuiLayout) - } - menu("Lambda API Settings") { - buildConfigSettingsContext(LambdaAPI) - } - menu("Baritone Settings") { - buildConfigSettingsContext(BaritoneHandler) - } - } - separator() - menu("Open Folder") { - menuItem("Open Lambda Folder") { - Util.getOperatingSystem().open(FolderRegistry.lambda) - } - menuItem("Open Config Folder") { - Util.getOperatingSystem().open(FolderRegistry.config) - } - menuItem("Open Packet Logs Folder") { - Util.getOperatingSystem().open(FolderRegistry.packetLogs) - } - menuItem("Open Replay Folder") { - Util.getOperatingSystem().open(FolderRegistry.replay) - } - menuItem("Open Cache Folder") { - Util.getOperatingSystem().open(FolderRegistry.cache) - } - menuItem("Open Capes Folder") { - Util.getOperatingSystem().open(FolderRegistry.capes) - } - menuItem("Open Structures Folder") { - Util.getOperatingSystem().open(FolderRegistry.structure) - } - menuItem("Open Maps Folder") { - Util.getOperatingSystem().open(FolderRegistry.maps) - } - } - separator() - menuItem("New Profile...", enabled = false) { - // ToDo (New Profile): - // - Open a modal "New Profile" with: - // [Profile Name] text input - // [Template] combo: Empty / Recommended Defaults / Copy from Current - // [Include HUD Layout] checkbox - // - On Create: instantiate and activate the profile, optionally copying values from current. - // - On Cancel: close modal with no changes. - } - menuItem("Import Profile...", enabled = false) { - // ToDo (Import Profile): - // - Show a file picker for profile file(s). - // - Preview dialog: profile name, version, module count, settings count, includes HUD? - // - Provide options: Merge into Current / Replace Current. - // - Apply with progress/rollback on failure; toast result. - } - menuItem("Export Current Profile...", enabled = false) { - // ToDo (Export Profile): - // - File save modal with checkboxes: - // [Include HUD Layout] [Include Keybinds] [Include Backups Metadata] - // - Create the export and toast result. - } - menu("Recent Profiles") { - // ToDo (MRU Profiles): - // - Populate from a most-recently-used (MRU) list persisted in preferences. - // - On click: switch active profile (confirm if unsaved changes). - menuItem("Example Profile", enabled = false) {} - } - separator() - menu("Autosave Settings") { - // ToDo: - // - Toggle autosave, set interval (1..60s), backup rotation count (0..20). - menuItem("Autosave on changes", selected = true, enabled = false) {} - menuItem("Autosave Interval: 10s", enabled = false) {} - menuItem("Rotate Backups: 5", enabled = false) {} - } - menu("Backup & Restore") { - // ToDo: - // - “Create Backup Now” and “Manage/Restore Backups” UIs; list with timestamps/comments. - menuItem("Create Backup Now", enabled = false) {} - menuItem("Restore From Backup...", enabled = false) {} - menuItem("Manage Backups...", enabled = false) {} - } - menuItem("Profiles & Scopes...", enabled = false) { - // ToDo (Profiles & Scopes Window): - // - Active Profile dropdown. - // - Scopes: Global / Per-Server / Per-World with enable overrides. - // - Show overridden-only list, origin badges, and precedence explanation. - } - separator() - menuItem("About...") { - aboutRequested = true - } - menuItem("Developer Mode", selected = ClickGuiLayout.developerMode) { - ClickGuiLayout.developerMode = !ClickGuiLayout.developerMode - } - separator() - menuItem("Close GUI", "Esc") { LambdaScreen.close() } - menuItem("Exit Client") { mc.scheduleStop() } - } - - private fun ImGuiBuilder.buildHudMenu() { - menuItem(if (HudGuiLayout.isLocked) "Unlock" else "Lock") { - HudGuiLayout.isLocked = !HudGuiLayout.isLocked - } - menuItem(if (HudGuiLayout.isShownInGUI) "Hide" else "Show") { - HudGuiLayout.isShownInGUI = !HudGuiLayout.isShownInGUI - } - separator() - menu("HUD Settings") { - buildConfigSettingsContext(HudGuiLayout) - } - } - - private fun ImGuiBuilder.buildGuiMenu() { - buildConfigSettingsContext(ClickGuiLayout) - } - - private fun ImGuiBuilder.buildModulesMenu() { - menu("Module Tag") { - ModuleTag.defaults.forEach { tag -> - checkbox(tag.name, ImBoolean(ModuleTag.isTagShown(tag))) { - ModuleTag.toggleTag(tag) - } - } - } - separator() - // By Tag → toggle whether each module is shown in the ClickGui layout - ModuleTag.defaults.forEach { tag -> - menu(tag.name) { - ModuleRegistry.modules - .filter { it.tag == tag } - .forEach { module -> - checkbox(module.name, module.showInClickGui::value) - } - } - } - } - - private fun ImGuiBuilder.buildAutomationConfigsMenu() { - button("New Config") { ImGui.openPopup("##new-config") } - popupContextWindow("##new-config") { - inputText("Name", ::newConfigName) - button("Create") { - if (newConfigName.isEmpty() && configs.none { it.name == newConfigName }) return@button - UserAutomationConfig(newConfigName) - newConfigName = "" - closeCurrentPopup() - return@button - } - sameLine() - button("Cancel") { - newConfigName = "" - closeCurrentPopup() - } - } - - UserAutomationCategory.configs.forEach { config -> - if (config !is UserAutomationConfig) throw IllegalStateException("All configs within UserAutomationConfigs must be UserAutomationConfigs!") - buildAutomationConfigSelectable(config) - } - buildAutomationConfigSelectable(AutomationConfig.DEFAULT) - } - - private fun ImGuiBuilder.buildAutomationConfigSelectable(config: AutomationConfig) { - ImGui.setNextWindowSizeConstraints(0f, 0f, Float.MAX_VALUE, io.displaySize.y * 0.5f) - menu(config.name) { - if (config is UserAutomationConfig) { - with(config.linkedModules) { buildLayout() } - button("Delete") { - config.linkedModules.value.forEach { - moduleNameMap[it]?.let { module -> - module.automationConfig = module.defaultAutomationConfig - } - } - UserAutomationCategory.configs.remove(config) - } - separator() - } - buildConfigSettingsContext(config) - } - } - - private fun ImGuiBuilder.buildMinecraftMenu() { - menu("Open Folder") { - menuItem("Open Minecraft Folder") { - Util.getOperatingSystem().open(minecraft) - } - menuItem("Open Saves Folder") { - Util.getOperatingSystem().open(mc.runDirectory.toPath().toAbsolutePath().resolve("saves").toFile()) - } - menuItem("Open Screenshots Folder") { - Util.getOperatingSystem().open(mc.runDirectory.toPath().toAbsolutePath().resolve("screenshots").toFile()) - } - menuItem("Open Resource Packs Folder") { - Util.getOperatingSystem().open(mc.runDirectory.toPath().toAbsolutePath().resolve("resourcepacks").toFile()) - } - menuItem("Open Mods Folder") { - Util.getOperatingSystem().open(mc.runDirectory.toPath().toAbsolutePath().resolve("mods").toFile()) - } - } - separator() - runSafe { - menu("Gamemode", enabled = GameModeCommand.PERMISSION_CHECK.allows(player.permissions)) { - menuItem("Survival", selected = interaction.gameMode == GameMode.SURVIVAL) { - connection.sendPacket(ChangeGameModeC2SPacket(GameMode.SURVIVAL)) - } - menuItem("Creative", selected = interaction.gameMode == GameMode.CREATIVE) { - connection.sendPacket(ChangeGameModeC2SPacket(GameMode.CREATIVE)) - } - menuItem("Adventure", selected = interaction.gameMode == GameMode.ADVENTURE) { - connection.sendPacket(ChangeGameModeC2SPacket(GameMode.ADVENTURE)) - } - menuItem("Spectator", selected = interaction.gameMode == GameMode.SPECTATOR) { - connection.sendPacket(ChangeGameModeC2SPacket(GameMode.SPECTATOR)) - } - } - menu("Debug Menu") { - menuItem("Show Advanced Tooltips", "F3+H", mc.options.advancedItemTooltips) { - mc.options.advancedItemTooltips = !mc.options.advancedItemTooltips - mc.options.write() - } - menuItem("Copy Location (as command)", "F3+C") { - val cmd = String.format( - Locale.ROOT, - "/execute in %s run tp @s %.2f %.2f %.2f %.2f %.2f", - world.registryKey.value, - player.x, player.y, player.z, player.yaw, player.pitch - ) - ImGui.setClipboardText(cmd) - info("Copied location command to clipboard.") - } - menuItem("Clear Chat", "F3+D") { - mc.inGameHud?.chatHud?.clear(false) - } - menuItem("Open Debug Entry Menu", "(new)") { // ToDo: Put actual keybind in - mc.setScreen(DebugOptionsScreen()) - } - - separator() - - menuItem( - label = "Pause On Lost Focus", - shortcut = "F3+Esc", - selected = mc.options.pauseOnLostFocus - ) { - mc.options.pauseOnLostFocus = !mc.options.pauseOnLostFocus - mc.options.write() - info("Pause on lost focus ${if (mc.options.pauseOnLostFocus) "enabled" else "disabled"}.") - } - - separator() - - menuItem("Reload Resource Packs", "F3+T") { - info("Reloading resource packs...") - mc.reloadResources() - } - - menuItem("Reload Chunks", "F3+A") { - mc.worldRenderer.reload() - } - - separator() - - menuItem("Show Debug Menu", "F3", mc.debugHudEntryList.isF3Enabled) { - mc.debugHudEntryList.toggleF3Enabled() - } - menuItem("Rendering Chart", "F3+1", mc.debugHud.renderingChartVisible) { - mc.debugHud.toggleRenderingChart() - } - menuItem("Rendering & Tick Charts", "F3+2", mc.debugHud.renderingAndTickChartsVisible) { - mc.debugHud.toggleRenderingAndTickCharts() - } - menuItem("Packet Size & Ping Charts", "F3+3", mc.debugHud.packetSizeAndPingChartsVisible) { - mc.debugHud.togglePacketSizeAndPingCharts() - } - - separator() - - menuItem("Start/Stop Profiler", "F3+L") { - mc.toggleDebugProfiler { message -> - info(message) - } - } - menuItem("Dump Dynamic Textures", "F3+S") { - val root = mc.runDirectory.toPath().toAbsolutePath() - val output = TextureUtil.getDebugTexturePath(root) - mc.textureManager.dumpDynamicTextures(output) - info("Dumped dynamic textures to: ${root.relativize(output)}") - } - } - } ?: menuItem("Debug (only available ingame)", enabled = false) - } - - private fun ImGuiBuilder.buildHelpMenu() { - menuItem("Quick Search...", "Shift+Shift") { - QuickSearch.open() - } - menuItem("Documentation $EXTERNAL_LINK") { - Util.getOperatingSystem().open("$REPO_URL/wiki") - } - menuItem("Report Issue $EXTERNAL_LINK") { - mc.keyboard.clipboard = gatherDiagnostics() - info("Copied diagnostics to clipboard. Please paste it in a new issue on GitHub and click “Submit new issue”. Thank you!") - Util.getOperatingSystem().open("$REPO_URL/issues") - } - menuItem("Check for Updates $EXTERNAL_LINK") { - // ToDo: - // - Check for a newer version, show availability & changelog, and allow opening release page. - // - Needs UpdateManager - Util.getOperatingSystem().open("$REPO_URL/releases") - } - } - - private fun ImGuiBuilder.aboutPopup() { - popupModal("About Lambda", ImGuiWindowFlags.AlwaysAutoResize or ImGuiWindowFlags.NoTitleBar) { - imageHorizontallyCentered(headerLogo.id.toLong(), 553f, 200f) - group { - text("Version: ${Lambda.VERSION}") - if (Lambda.isDebug) text("Development Environment") - text("Runtime: ${Loader.runtime}") - text("Modules: ${ModuleRegistry.modules.size}") - text("Commands: ${CommandRegistry.commands.size}") - val totalSettings = ConfigLoader.configCategories.sumOf { cfg -> - cfg.configs.sumOf { - var count = 0 - it.settingLayers.forEachEntry { _, _ -> count++ } - count - } - } - text("Settings: $totalSettings") - text("Synchronous listeners: ${EventFlow.syncListeners.size}") - text("Concurrent listeners: ${EventFlow.concurrentListeners.size}") - } - separator() - text("Authors") - FabricLoader.getInstance().getModContainer("lambda") - .orElseThrow { IllegalStateException("Could not find Lambda mod container!") } - .metadata - .authors - .forEach { author -> - if (author.name.isEmpty()) return@forEach - author.name.split(",").forEach { name -> - bulletText(name.trim()) - } - } - text("Thanks to all community members") - - separator() - group { - button("Copy Diagnostics") { - ImGui.setClipboardText(gatherDiagnostics()) - } - sameLine() - button("View License $EXTERNAL_LINK") { - Util.getOperatingSystem().open("$REPO_URL/blob/master/LICENSE.md") - } - sameLine() - button("Close") { - aboutRequested = false - closeCurrentPopup() - } - } - } - } - - private fun ImGuiBuilder.buildGitHubReference() { - val frameH = frameHeight - 2f - val iconSize = (frameH - 6f).coerceAtLeast(14f) - val spacingPx = 8f - - sameLine() - cursorPosX = windowContentRegionMaxX - iconSize - spacingPx - - withStyleVar(ImGuiStyleVar.FramePadding, 2f, 2f) { - withStyleColor(ImGuiCol.Button, 0x00000000) { - withStyleColor(ImGuiCol.ButtonHovered, 0x22FFFFFF) { - withStyleColor(ImGuiCol.ButtonActive, 0x44FFFFFF) { - val clicked = ImGui.imageButton("##github", githubLogo.id.toLong(), iconSize, iconSize) - lambdaTooltip("Open GitHub Repository $EXTERNAL_LINK") - if (clicked) { - Util.getOperatingSystem().open(REPO_URL) - } - } - } - } - } - } -} diff --git a/src/main/kotlin/com/lambda/gui/Notifications.kt b/src/main/kotlin/com/lambda/gui/Notifications.kt new file mode 100644 index 000000000..a550701f6 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/Notifications.kt @@ -0,0 +1,155 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui + +import androidx.compose.animation.core.Animatable +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import com.lambda.gui.component.ContentColor +import com.lambda.gui.component.Text +import com.lambda.gui.component.window +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Motion +import com.lambda.gui.theme.Type +import com.lambda.interaction.handler.handlers.NotificationHandler +import com.lambda.interaction.handler.handlers.NotificationHandler.Notification +import com.lambda.util.math.toCompose +import kotlin.math.roundToInt + +private val MARGIN = 6.dp +private val GAP = 4.dp +private val STRIPE = 2.dp + +@Composable +internal fun Notifications() { + val notifications = NotificationHandler.notifications + if (notifications.isEmpty()) return + val heights = remember { mutableStateMapOf() } + val density = LocalDensity.current + val scaled = Density(density.density * Look.notificationScale, density.fontScale) + CompositionLocalProvider(LocalDensity provides scaled) { + Stack(notifications, heights) + } +} + +@Composable +private fun Stack(notifications: List, heights: MutableMap) { + Box(Modifier.fillMaxSize()) { + notifications.forEach { notification -> + key(notification) { + val stacked = + notifications + .takeWhile { it !== notification } + .filterNot { it.dismissed } + .sumOf { heights[it] ?: 0 } + val beneath = notifications.takeWhile { it !== notification }.count { !it.dismissed } + Toast( + notification = notification, + stacked = stacked, + beneath = beneath, + height = heights[notification] ?: 0, + onMeasured = { heights[notification] = it }, + onGone = { + heights -= notification + NotificationHandler.remove(notification) + }, + modifier = Modifier.align(Alignment.BottomEnd) + ) + } + } + } +} + +@Composable +private fun Toast( + notification: Notification, + stacked: Int, + beneath: Int, + height: Int, + onMeasured: (height: Int) -> Unit, + onGone: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = LambdaTheme.colors + val density = LocalDensity.current + val reach = with(density) { (Look.notificationWidth + MARGIN * 4).toPx() } + val rise = + if (notification.dismissed) -height - with(density) { (MARGIN * 4).toPx() } + else with(density) { (MARGIN + GAP * beneath).toPx() } + stacked + val entered = remember { Animatable(0f) } + val risen = remember { Animatable(rise) } + LaunchedEffect(Unit) { entered.animateTo(1f, Motion.NOTIFICATIONS) } + LaunchedEffect(rise) { + risen.animateTo(rise, Motion.NOTIFICATIONS) + if (notification.dismissed) onGone() + } + + val shape = RoundedCornerShape(Look.panelRounding) + Row( + modifier + .offset { + IntOffset( + ((1f - entered.value) * reach).roundToInt() - MARGIN.roundToPx(), + -risen.value.roundToInt() + ) + } + .onSizeChanged { onMeasured(it.height) } + .width(Look.notificationWidth) + .height(IntrinsicSize.Min) + .window(colors.panel, colors.border, shape, floating = true) + ) { + Box( + Modifier + .width(STRIPE) + .fillMaxHeight() + .background(notification.accent?.toCompose() ?: colors.primary) + ) + ContentColor(colors.onSurface) { + Column(Modifier.padding(Look.panelPadding, Look.panelPadding / 2)) { + Text(notification.title, style = Type.label, maxLines = 1) + if (notification.message.isNotEmpty()) { + Text(notification.message, color = colors.onSurfaceVariant) + } + } + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/OverlayBackgroundScreen.kt b/src/main/kotlin/com/lambda/gui/OverlayBackgroundScreen.kt index 33ad955e7..1b8c1e625 100644 --- a/src/main/kotlin/com/lambda/gui/OverlayBackgroundScreen.kt +++ b/src/main/kotlin/com/lambda/gui/OverlayBackgroundScreen.kt @@ -19,7 +19,7 @@ package com.lambda.gui /** * Implemented by screens the click GUI can open over that hold resources (e.g. textures) - * which must survive being temporarily replaced by [LambdaScreen]. + * which must survive being temporarily replaced by [GuiScreen]. * * Opening the GUI calls [net.minecraft.client.MinecraftClient.setScreen], which fires * [net.minecraft.client.gui.screen.Screen.removed] on the screen being overlaid — screens diff --git a/src/main/kotlin/com/lambda/gui/Reveal.kt b/src/main/kotlin/com/lambda/gui/Reveal.kt new file mode 100644 index 000000000..2b1cccd47 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/Reveal.kt @@ -0,0 +1,84 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.lambda.config.Config +import com.lambda.config.automation.AutomationConfig +import com.lambda.config.entries.Setting +import com.lambda.gui.clickgui.ClickGuiDialog +import com.lambda.gui.clickgui.ClickGuiState +import com.lambda.gui.core.awaitFrames +import com.lambda.module.HudModule +import com.lambda.module.Module +import com.lambda.module.ModuleRegistry +import com.lambda.module.ModuleTag + +internal object Reveal { + private const val MILLIS = 1800L + + var module: Module? by mutableStateOf(null) + private set + var setting: Setting<*>? by mutableStateOf(null) + private set + + fun show(config: Config, setting: Setting<*>? = null) { + val owner = owner(config) + module = owner + this.setting = setting + when (owner) { + is HudModule -> LambdaGui.open(LambdaGui.Screen.HudEditor) + is Module -> uncover(owner) + else -> ClickGuiState.dialog = ClickGuiDialog.Settings(config) + } + } + + @Composable + fun Expiry() { + val module = module + val setting = setting + LaunchedEffect(module, setting) { + if (module == null && setting == null) return@LaunchedEffect + awaitFrames(MILLIS) + this@Reveal.module = null + this@Reveal.setting = null + } + } + + private fun owner(config: Config): Module? = config as? Module + ?: config.takeIf { it !== AutomationConfig.DEFAULT } + ?.let { + ModuleRegistry.modules.firstOrNull { module -> + module.automationConfig === config + } + } + + private fun uncover(module: Module) { + val tag = module.tag + if (tag == ModuleTag.DEBUG) ClickGuiState.developerMode = + true else ModuleTag.shownTags += tag + module.showInClickGui.value = true + GuiConfig.windows[tag.name]?.takeIf { it.collapsed }?.let { + GuiConfig.windows += tag.name to it.copy(collapsed = false) + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt new file mode 100644 index 000000000..8e924d63f --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/Snap.kt @@ -0,0 +1,147 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui + +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.dp +import com.lambda.config.settings.complex.Bind +import com.lambda.util.InputUtils.isSatisfied +import com.lambda.util.math.toCompose +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.roundToInt + +internal object Snap { + private const val MIN_GRID_STEP = 4f + private val GRID_COLOR = Color.White.copy(alpha = 0.11f) + + data class Guides(val x: Float?, val y: Float?) { + companion object { + val NONE = Guides(null, null) + } + } + + data class Result(val position: Offset, val guides: Guides) + + private class Target(val shift: Float, val guide: Float?) + + val isActive: Boolean + get() = + GuiConfig.snapEnabled && + (GuiConfig.snapKey == Bind.EMPTY || GuiConfig.snapKey.isSatisfied()) + + private fun gridStep(density: Density) = + with(density) { max(MIN_GRID_STEP, GuiConfig.gridSize.dp.toPx()) } + + fun free(element: Rect, area: Rect) = + Result(element.topLeft.keptIn(area, element.size), Guides.NONE) + + fun snap( + element: Rect, + others: Collection, + area: Rect, + density: Density, + spacing: Float = 0f + ): Result = + with(density) { + fun axis(start: (Rect) -> Float, end: (Rect) -> Float): Target { + fun center(rect: Rect) = (start(rect) + end(rect)) / 2 + val from = start(element) + val size = end(element) - from + fun startAt(at: Float, guide: Float? = at) = Target(at - from, guide) + fun endAt(at: Float, guide: Float? = at) = Target(at - size - from, guide) + fun centerAt(at: Float, guide: Float? = at) = Target(at - size / 2 - from, guide) + + val neighbours = + buildList { + if (GuiConfig.snapToEdges) { + add(startAt(start(area))) + add(endAt(end(area))) + others.forEach { other -> + add(startAt(start(other))) + add(endAt(end(other))) + add(startAt(end(other) + spacing, end(other) + spacing / 2)) + add(endAt(start(other) - spacing, start(other) - spacing / 2)) + } + } + if (GuiConfig.snapToCenters) others.forEach { add(centerAt(center(it))) } + } + val middle = center(area) + val screenCenter = + listOf( + startAt(middle), + centerAt(middle), + endAt(middle) + ).takeIf { GuiConfig.snapToScreenCenter }.orEmpty() + val step = gridStep(density) + fun onGrid(line: Float) = (line / step).roundToInt() * step + val grid = + listOf( + startAt(onGrid(from), null), + centerAt(onGrid(from + size / 2), null), + endAt(onGrid(from + size), null), + ).takeIf { GuiConfig.snapToGrid }.orEmpty() + + return listOf( + neighbours to GuiConfig.snapDistanceElement.dp.toPx(), + screenCenter to GuiConfig.snapDistanceScreen.dp.toPx(), + grid to GuiConfig.snapDistanceGrid.dp.toPx(), + ).firstNotNullOfOrNull { (targets, reach) -> + targets.minByOrNull { abs(it.shift) }?.takeIf { abs(it.shift) <= reach } + } ?: Target(0f, null) + } + + val x = axis({ it.left }, { it.right }) + val y = axis({ it.top }, { it.bottom }) + Result((element.topLeft + Offset(x.shift, y.shift)).keptIn(area, element.size), Guides(x.guide, y.guide)) + } + + fun Modifier.snapLines(drop: () -> Result?): Modifier = + drawWithContent { + val guides = drop()?.guides.takeIf { GuiConfig.showSnapLines } + if (guides != null && isActive && GuiConfig.snapToGrid) drawGrid() + drawContent() + if (guides != null) { + val color = GuiConfig.snapLineColor.toCompose() + guides.x?.let { drawLine(color, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } + guides.y?.let { drawLine(color, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } + } + } + + private fun DrawScope.drawGrid() { + val step = gridStep(this) + generateSequence(0f) { it + step }.takeWhile { it <= size.width } + .forEach { drawLine(GRID_COLOR, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } + generateSequence(0f) { it + step }.takeWhile { it <= size.height } + .forEach { drawLine(GRID_COLOR, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } + } + + private fun Offset.keptIn(area: Rect, element: Size) = + Offset( + x.coerceIn(area.left, max(area.left, area.right - element.width)), + y.coerceIn(area.top, max(area.top, area.bottom - element.height)) + ) +} diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt new file mode 100644 index 000000000..8c6e068de --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -0,0 +1,327 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.clickgui + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.MutableTransitionState +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.animation.expandVertically +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInRoot +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.DpOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.toSize +import com.lambda.gui.GuiConfig +import com.lambda.gui.LambdaGui +import com.lambda.gui.Reveal +import com.lambda.gui.Snap +import com.lambda.gui.component.ScrollColumn +import com.lambda.gui.component.SlidingText +import com.lambda.gui.component.Text +import com.lambda.gui.component.Tooltip +import com.lambda.gui.component.hoverHighlight +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.component.mouseDraggable +import com.lambda.gui.component.shadowed +import com.lambda.gui.component.window +import com.lambda.gui.core.LocalShown +import com.lambda.gui.core.observe +import com.lambda.gui.menu.MENU_BAR_HEIGHT +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Motion +import com.lambda.gui.theme.Type +import com.lambda.module.Module +import com.lambda.module.ModuleRegistry +import com.lambda.module.ModuleTag +import kotlin.math.absoluteValue + +private val REACH = 40.dp +private const val IN_ROW = 1.5f +private val EMBOSS = + Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05f), Color.Transparent)) + +@Composable +internal fun CategoryWindow( + tag: ModuleTag, + defaultPosition: DpOffset, + bounds: MutableMap, + snapping: Boolean, + onDrop: (Snap.Result?) -> Unit, + settings: OpenSettings, + inline: Boolean, + onFocus: () -> Unit, + modifier: Modifier = Modifier, +) { + val modules by + observe { + ModuleRegistry.modules.filter { it.tag == tag && it.showInClickGui.value } + } + if (modules.isEmpty()) return + + val colors = LambdaTheme.colors + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize.toSize() + val screenHeight = with(density) { screen.height.toDp() } + val area = + Rect( + 0f, + with(density) { MENU_BAR_HEIGHT.toPx() }, + screen.width, + screen.height + ) + + val placement by observe { GuiConfig.windows[tag.name] } + val position = placement?.takeUnless { it.inRow }?.let { DpOffset(it.x.dp, it.y.dp) } + val collapsed = placement?.collapsed ?: false + + var dragged by remember { mutableStateOf(null) } + val drop = + dragged?.let { corner -> + val window = Rect(corner, bounds[tag]?.size ?: Size.Zero) + if (snapping) { + Snap.snap( + window, + bounds.filterKeys { it != tag }.values, + area, + density, + with(density) { Look.windowGap.toPx() } + ) + } + else Snap.free(window, area) + } + if (drop != null) SideEffect { onDrop(drop) } + val shownPosition = + drop?.let { + with(density) { DpOffset(it.position.x.toDp(), it.position.y.toDp()) } + } ?: (position ?: defaultPosition).let { at -> + val screenWidth = with(density) { screen.width.toDp() } + DpOffset( + at.x.coerceIn( + 0.dp, + (screenWidth - Look.windowWidth).coerceAtLeast(0.dp) + ), + at.y.coerceIn( + MENU_BAR_HEIGHT, + (screenHeight - REACH).coerceAtLeast(MENU_BAR_HEIGHT) + ), + ) + } + val currentPosition by rememberUpdatedState(shownPosition) + DisposableEffect(tag) { + onDispose { bounds -= tag } + } + + fun place(at: DpOffset, collapsed: Boolean) { + val inRow = (at.x - defaultPosition.x).value.absoluteValue < IN_ROW && + (at.y - defaultPosition.y).value.absoluteValue < IN_ROW + GuiConfig.windows += tag.name to + if (inRow) GuiConfig.WindowPlacement.inRow(collapsed) + else GuiConfig.WindowPlacement(at.x.value, at.y.value, collapsed) + } + LaunchedEffect(placement) { + position?.let { place(it, collapsed) } + } + + Column( + modifier = modifier + .offset(shownPosition.x, shownPosition.y) + .width(Look.windowWidth) + .onGloballyPositioned { bounds[tag] = Rect(it.positionInRoot(), it.size.toSize()) } + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Press) onFocus() + } + } + } + .window(colors.surface, colors.border, RoundedCornerShape(Look.windowRounding)) + ) { + Text( + text = tag.name, + color = colors.onHeader, + style = Type.title.shadowed(), + maxLines = 1, + modifier = Modifier + .fillMaxWidth() + .background(colors.header) + .mouseDraggable( + onDragStart = { dragged = bounds[tag]?.topLeft }, + onDragEnd = { + if (dragged != null) place(currentPosition, collapsed) + dragged = null + onDrop(null) + }, + ) { delta -> dragged = dragged?.plus(delta) } + .mouseClickable(onRightClick = { + if (!collapsed) settings.close(modules) + place(currentPosition, !collapsed) + }) + .padding(horizontal = Look.modulePadding, vertical = 2.dp) + ) + + val shown = LocalShown.current + val folding = LambdaGui.foldsClosed + val unfolded = + remember(shown, LambdaGui.restarts) { + MutableTransitionState( + (folding || !LambdaGui.unfoldsOpen) && shown && !collapsed + ) + } + unfolded.targetState = shown && !folding && !collapsed + val settled = unfolded.isIdle && unfolded.currentState + val hanging = modules.mapNotNull(settings::panelOf) + SideEffect { hanging.forEach { it.settled = settled } } + AnimatedVisibility( + visibleState = unfolded, + enter = expandVertically(Motion.windows), + exit = + shrinkVertically( + if (folding) Motion.guiFold + else Motion.windows + ), + ) { + ScrollColumn( + Modifier.heightIn( + max = (screenHeight - shownPosition.y - 24.dp).coerceAtLeast(48.dp) + ) + ) { + modules.forEach { module -> + ModuleRow( + module = module, + isEdited = settings.isOpen(module), + pressedIn = !inline, + panel = settings.panelOf(module).takeUnless { inline }, + onEdit = { settings.toggle(module) }, + ) + if (inline) { + InlineSettings( + settings.stateOf(module), + open = settings.isOpen(module) + ) + } + } + } + } + } +} + +@Composable +private fun ModuleRow( + module: Module, + isEdited: Boolean, + pressedIn: Boolean, + panel: SettingsPanelState?, + onEdit: () -> Unit +) { + val colors = LambdaTheme.colors + val enabled by observe { module.isEnabled } + val fill by + animateColorAsState( + if (enabled) colors.moduleEnabled else Color.Transparent, + spring() + ) + val pressed by + animateColorAsState( + if (isEdited && pressedIn) colors.inset.copy(alpha = colors.inset.alpha / 2) + else Color.Transparent, + spring() + ) + + val revealed = Reveal.module === module && Reveal.setting == null + val lit by + animateColorAsState( + if (revealed) colors.onSurface.copy(alpha = 0.4f) else Color.Transparent, + tween(250) + ) + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(revealed) { + if (revealed) intoView.bringIntoView() + } + + Tooltip(module.description, Modifier.fillMaxWidth()) { + Box( + contentAlignment = Alignment.CenterStart, + modifier = Modifier + .fillMaxWidth() + .then( + if (panel == null) Modifier + else Modifier.onGloballyPositioned { + panel.row = Rect(it.positionInRoot(), it.size.toSize()) + } + ) + .bringIntoViewRequester(intoView) + .mouseClickable(onRightClick = onEdit) { + if (module.alwaysEnabled) onEdit() else module.toggle() + } + .background(fill) + .background(pressed) + .background(lit) + .hoverHighlight(colors.raised) + .then(if (Look.emboss) Modifier.background(EMBOSS) else Modifier) + .heightIn(min = Look.rowHeight) + .padding(horizontal = Look.modulePadding) + ) { + SlidingText( + text = module.name, + color = when { + enabled -> colors.onModuleEnabled + isEdited -> colors.onSurface + else -> colors.onSurfaceVariant + }, + style = Type.body.shadowed(), + ) + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt new file mode 100644 index 000000000..3a60767b1 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -0,0 +1,230 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.clickgui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.zIndex +import com.lambda.config.Config +import com.lambda.gui.GuiConfig +import com.lambda.gui.LambdaGui +import com.lambda.gui.Reveal +import com.lambda.gui.Snap +import com.lambda.gui.Snap.snapLines +import com.lambda.gui.component.Button +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.LocalShown +import com.lambda.gui.core.observe +import com.lambda.gui.menu.AboutDialog +import com.lambda.gui.menu.ConfigDialog +import com.lambda.gui.menu.LoaderPromptDialog +import com.lambda.gui.menu.MenuBar +import com.lambda.gui.menu.NewAutomationConfigDialog +import com.lambda.gui.theme.GuiTransition +import com.lambda.gui.theme.Look +import com.lambda.module.HudModule +import com.lambda.module.ModuleTag +import com.lambda.module.modules.client.AutoUpdater +import com.lambda.module.modules.client.Style + +private val SLIDE = 24.dp +private const val ZOOM = 0.92f + +internal val CLICK_GUI_CATEGORIES = ModuleTag.defaults - ModuleTag.HUD + +private class RowLayout(var row: Triple, var shown: Boolean = false) + +internal sealed interface ClickGuiDialog { + data object About : ClickGuiDialog + data object NewAutomationConfig : ClickGuiDialog + data class Settings(val config: Config) : ClickGuiDialog +} + +internal object ClickGuiState { + var dialog: ClickGuiDialog? by mutableStateOf(null) + var developerMode by mutableStateOf(false) + var focusSearch by mutableStateOf(false) +} + +@Composable +internal fun ClickGui() { + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize + val developerMode = ClickGuiState.developerMode + val tags by observe { + CLICK_GUI_CATEGORIES.filter(ModuleTag::isTagShown) + listOfNotNull( + ModuleTag.DEBUG.takeIf { developerMode } + ) + } + + val settings = remember { OpenSettings() } + val inline by observe { Style.inlineSettings } + + val revealedModule = Reveal.module + val revealedSetting = Reveal.setting + LaunchedEffect(revealedModule, revealedSetting) { + if ( + revealedModule != null && + revealedModule !is HudModule && + revealedSetting != null + ) { + settings.open(revealedModule) + } + } + + val shown = LocalShown.current + LaunchedEffect(shown) { + if (!shown && !GuiConfig.keepSettingsOpen) settings.forget() + } + + val row = Triple(Look.windowWidth, Look.windowGap, Look.windowTop) + val laidOut = remember { RowLayout(row) } + SideEffect { + if (row != laidOut.row && shown && laidOut.shown) { + GuiConfig.windows = + GuiConfig.windows.mapValues { + GuiConfig.WindowPlacement.inRow(it.value.collapsed) + } + } + laidOut.row = row + laidOut.shown = shown + } + + val stacking = remember { mutableStateListOf() } + val bounds = remember { mutableStateMapOf() } + val snapping by observe { Snap.isActive } + var drop by remember { mutableStateOf(null) } + + Box( + Modifier.fillMaxSize().mouseClickable( + keyboard = false, + onClick = settings::closeAll + ).snapLines { + drop + }.graphicsLayer { + val presence = LambdaGui.presence + val styles = LambdaGui.transitions + if (GuiTransition.Fade in styles) alpha = presence + if (GuiTransition.Slide in styles) { + translationY = (presence - 1f) * SLIDE.toPx() + } + if (GuiTransition.Zoom in styles) { + scaleX = ZOOM + (1f - ZOOM) * presence + scaleY = scaleX + } + } + ) { + val inRow = tags.count { it != ModuleTag.DEBUG } + val screenWidth = with(density) { screen.width.toDp() } + val pitch = + (Look.windowWidth + Look.windowGap) + .coerceAtMost( + (screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1) + ) + .coerceAtLeast(0.dp) + val rowWidth = Look.windowWidth + pitch * (inRow - 1) + val rowStart = ((screenWidth - rowWidth) / 2).coerceAtLeast(0.dp) + + tags.forEachIndexed { index, tag -> + key(tag) { + CategoryWindow( + tag = tag, + defaultPosition = DpOffset(rowStart + pitch * index, Look.windowTop), + bounds = bounds, + snapping = snapping, + onDrop = { drop = it }, + settings = settings, + inline = inline, + onFocus = { + stacking.remove(tag) + stacking.add(tag) + }, + modifier = Modifier.zIndex(stacking.indexOf(tag).toFloat()) + ) + } + } + + settings.panels.forEach { panel -> + key(panel.module) { + SettingsPanel( + panel = panel, + open = settings.isOpen(panel.module) && !inline, + windows = bounds, + onClosed = { settings.closed(panel.module) }, + modifier = Modifier.zIndex(stacking.size.toFloat()) + ) + } + } + + MenuBar( + Modifier + .align(Alignment.TopStart) + .zIndex(stacking.size + 1f) + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Press) settings.closeAll() + } + } + } + ) + Button( + label = "HUD Editor", + modifier = Modifier + .align(Alignment.BottomEnd) + .padding(4.dp) + .zIndex(stacking.size + 1f), + prominent = true, + ) { LambdaGui.open(LambdaGui.Screen.HudEditor) } + } + + val prompt = observe { AutoUpdater.prompt }.value + val closeDialog = { ClickGuiState.dialog = null } + val dialog = ClickGuiState.dialog + when { + prompt != null -> LoaderPromptDialog(prompt) + dialog is ClickGuiDialog.About -> AboutDialog(closeDialog) + dialog is ClickGuiDialog.NewAutomationConfig -> + NewAutomationConfigDialog(closeDialog) + dialog is ClickGuiDialog.Settings -> ConfigDialog(dialog.config, closeDialog) + } +} diff --git a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt new file mode 100644 index 000000000..79a51a955 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt @@ -0,0 +1,81 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.clickgui + +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.unit.dp +import com.lambda.gui.settings.PanelPage +import com.lambda.module.Module +import com.lambda.module.modules.client.Style + +internal class SettingsPanelState(val module: Module) { + var page by mutableStateOf(PanelPage.Settings) + var extension by mutableStateOf(0.dp) + var row by mutableStateOf(Rect.Zero) + var settled by mutableStateOf(false) +} + +@Stable +internal class OpenSettings { + private val states = HashMap() + private val open = mutableStateListOf() + private val closing = mutableStateListOf() + + val panels: List get() = (open + closing).map(::stateOf) + + fun stateOf(module: Module) = states.getOrPut(module) { SettingsPanelState(module) } + + fun panelOf(module: Module) = + if (module in open || module in closing) stateOf(module) + else null + + fun isOpen(module: Module) = module in open + + fun open(module: Module) { + if (!Style.multipleSettings) closeAll() + closing -= module + if (module !in open) open += module + } + + fun toggle(module: Module) = + if (isOpen(module)) close(module) + else open(module) + + fun close(module: Module) { + if (open.remove(module)) closing += module + } + + fun close(modules: Collection) = + open.filter { it in modules }.forEach(::close) + + fun closeAll() = open.toList().forEach(::close) + + fun closed(module: Module) { + closing -= module + } + + fun forget() { + open.clear() + closing.clear() + } +} diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt new file mode 100644 index 000000000..f98cd5698 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -0,0 +1,306 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.clickgui + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.AnimationVector1D +import androidx.compose.animation.core.MutableTransitionState +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.spring +import androidx.compose.animation.expandIn +import androidx.compose.animation.shrinkOut +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.drawWithCache +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.layout +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.lambda.gui.component.Expandable +import com.lambda.gui.component.LocalPopupHost +import com.lambda.gui.component.PopupHost +import com.lambda.gui.component.dropShadow +import com.lambda.gui.component.mouseDraggable +import com.lambda.gui.component.window +import com.lambda.gui.core.LocalShown +import com.lambda.gui.core.ResizeVerticalIcon +import com.lambda.gui.core.awaitFrames +import com.lambda.gui.menu.MENU_BAR_HEIGHT +import com.lambda.gui.settings.ModuleSettings +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Motion +import com.lambda.module.ModuleTag +import kotlinx.coroutines.launch +import kotlin.math.roundToInt + +private val MIN_WIDTH = 130.dp +private val MIN_HEIGHT = 120.dp +private val MIN_GRIP_HEIGHT = 3.dp +private val INSET_SHADOW = 5.dp +private const val SETTLE_MILLIS = 200L +private val WIDTH_CHANGE = spring(stiffness = Spring.StiffnessMedium) + +@Composable +internal fun SettingsPanel( + panel: SettingsPanelState, + open: Boolean, + windows: Map, + onClosed: () -> Unit, + modifier: Modifier = Modifier, +) { + val row = panel.row + val visibility = remember(LocalShown.current) { MutableTransitionState(false) } + val wanted = open && panel.settled && !row.isEmpty + val popups = remember { PopupHost() } + SideEffect { popups.closing = !wanted } + visibility.targetState = wanted + if (!open && visibility.isIdle && !visibility.currentState) { + SideEffect(onClosed) + return + } + if (row.isEmpty) return + + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize + var size by remember { mutableStateOf(IntSize.Zero) } + var unfolded by remember { mutableStateOf(0) } + + val scroll = rememberScrollState() + val screenHeight = with(density) { screen.height.toDp() } + val barBottom = with(density) { MENU_BAR_HEIGHT.toPx() } + val window = windows[panel.module.tag] + val top = + ( + if (window == null) row.top + else { + row.top.coerceIn( + window.top, + (window.bottom - row.height).coerceAtLeast(window.top) + ) + } + ).coerceAtLeast(barBottom) + val below = with(density) { (screen.height - top).toDp() }.coerceAtLeast(MIN_HEIGHT) + val highest = screenHeight - MENU_BAR_HEIGHT + val maxHeight = (below + panel.extension).coerceAtMost(highest) + + val overlap = with(density) { 1.dp.toPx() } + val fitsRight = row.right - overlap + size.width <= screen.width + val fitsLeft = row.left + overlap - size.width >= 0 + val flipped = !fitsRight && (fitsLeft || row.left > screen.width - row.right) + val lift = (top + unfolded - screen.height).coerceIn(0f, top - barBottom) + + val shape = + RoundedCornerShape( + topStart = if (flipped || lift > 0f) Look.panelRounding else 0.dp, + topEnd = if (!flipped || lift > 0f) Look.panelRounding else 0.dp, + bottomEnd = Look.panelRounding, + bottomStart = Look.panelRounding, + ) + val seam = + if (flipped) Alignment.TopEnd + else Alignment.TopStart + + Box( + modifier + .offset { + val room = (screen.width - size.width).coerceAtLeast(0) + IntOffset( + if (flipped) (row.left + overlap).roundToInt().coerceIn(screen.width - room, screen.width) + else (row.right - overlap).roundToInt().coerceIn(0, room), + (top - lift).roundToInt() + ) + } + .size(0.dp) + .wrapContentSize(seam, unbounded = true) + ) { + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier + .onSizeChanged { unfolded = it.height } + .onGloballyPositioned { popups.place(it.boundsInWindow()) } + .dropShadow(RoundedCornerShape(Look.panelRounding)) + .window(LambdaTheme.colors.panel, LambdaTheme.colors.border, shape), + enter = expandIn(Motion.panels, seam), + exit = shrinkOut(Motion.panels, seam), + ) { + Box( + Modifier + .widthIn(MIN_WIDTH, Look.settingsWidth) + .heightIn(max = maxHeight) + .widthOfContent() + .onSizeChanged { size = it } + ) { + CompositionLocalProvider(LocalPopupHost provides popups) { + Column(Modifier.padding(Look.panelPadding)) { + ModuleSettings( + panel.module, + panel.page, + { panel.page = it }, + scroll + ) + } + } + if (scroll.maxValue > 0 || lift > 0f) { + Grip( + onDragStart = { + panel.extension = panel.extension.coerceAtMost(with(density) { lift.toDp() }) + }, + onDrag = { up -> + val needed = panel.extension + with(density) { scroll.maxValue.toDp() } + panel.extension = + (panel.extension + up).coerceIn( + 0.dp, + needed + .coerceAtMost(highest - below) + .coerceAtLeast(0.dp) + ) + }, + modifier = Modifier.align(Alignment.TopCenter) + ) + } + } + } + } +} + +@Composable +internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(open) { + if (open) { + awaitFrames(SETTLE_MILLIS) + intoView.bringIntoView() + } + } + Expandable(open) { + val colors = LambdaTheme.colors + Column( + Modifier + .fillMaxWidth() + .bringIntoViewRequester(intoView) + .background(colors.panel) + .background(colors.inset.copy(alpha = colors.inset.alpha / 4)) + .drawWithCache { + val depth = INSET_SHADOW.toPx().coerceAtMost(size.height / 2) + val dark = colors.inset.copy(alpha = colors.inset.alpha / 2) + val top = Brush.verticalGradient(listOf(dark, Color.Transparent), 0f, depth) + val bottom = + Brush.verticalGradient( + listOf(Color.Transparent, dark), + size.height - depth, + size.height + ) + onDrawBehind { + drawRect(top, size = Size(size.width, depth)) + drawRect( + bottom, + Offset(0f, size.height - depth), + Size(size.width, depth) + ) + } + } + .padding(Look.panelPadding / 2) + ) { ModuleSettings(panel.module, panel.page, { panel.page = it }, scroll = null) } + } +} + +private fun Modifier.widthOfContent(): Modifier = + composed { + val scope = rememberCoroutineScope() + var width by remember { mutableStateOf?>(null) } + layout { measurable, constraints -> + val wanted = + measurable.maxIntrinsicWidth(constraints.maxHeight) + .coerceIn(constraints.minWidth, constraints.maxWidth).toFloat() + val current = width ?: Animatable(wanted).also { width = it } + if (current.targetValue != wanted) { + scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } + } + + val placeable = + measurable.measure( + Constraints.fixedWidth(current.value.roundToInt()).copy( + maxHeight = constraints.maxHeight + ) + ) + layout(placeable.width, placeable.height) { placeable.place(0, 0) } + } + } + +@Composable +private fun Grip( + onDragStart: () -> Unit, + onDrag: (up: Dp) -> Unit, + modifier: Modifier = Modifier +) { + val density = LocalDensity.current + val color = LambdaTheme.colors.onSurfaceVariant + Box( + contentAlignment = Alignment.Center, + modifier = modifier + .fillMaxWidth() + .height(Look.panelPadding.coerceAtLeast(MIN_GRIP_HEIGHT)) + .pointerHoverIcon(ResizeVerticalIcon) + .mouseDraggable(onDragStart = onDragStart) { delta -> + onDrag(with(density) { -delta.y.toDp() }) + } + ) { + Spacer(Modifier.size(16.dp, 1.dp).background(color, RoundedCornerShape(50))) + } +} diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt new file mode 100644 index 000000000..ee9ef830b --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -0,0 +1,317 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.LocalContentColor +import com.lambda.gui.theme.Look + +private const val TOGGLE_MILLIS = 150 +private val SECTION_BAR = 1.dp +private val LABEL_GAP = 3.dp + +@Composable +fun Button( + label: String, + modifier: Modifier = Modifier, + enabled: Boolean = true, + prominent: Boolean = false, + onClick: () -> Unit, +) { + val colors = LambdaTheme.colors + val fill = + if (prominent) colors.header + else colors.control + val text = + if (prominent) colors.onHeader + else colors.onControl + Box( + contentAlignment = Alignment.Center, + modifier = modifier + .heightIn(min = Look.rowHeight + 2.dp) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(fill) + .hoverHighlight(text.copy(alpha = if (enabled) 0.12f else 0f)) + .mouseClickable(enabled, onClick = onClick) + .padding(horizontal = 5.dp, vertical = 1.dp) + ) { + Text(label, color = if (enabled) text else colors.onSurfaceVariant, maxLines = 1) + } +} + +@Composable +fun Checkmark(checked: Boolean, modifier: Modifier = Modifier) { + val colors = LambdaTheme.colors + Canvas( + modifier + .size(9.dp) + .clip(RoundedCornerShape(Look.boxRounding)) + .background(if (checked) colors.primary else colors.track) + ) { + if (!checked) return@Canvas + val side = size.minDimension + drawPath( + path = Path().apply { + moveTo(side * 0.22f, side * 0.52f) + lineTo(side * 0.42f, side * 0.72f) + lineTo(side * 0.78f, side * 0.28f) + }, + color = colors.onPrimary, + style = Stroke(side * 0.16f, cap = StrokeCap.Round, join = StrokeJoin.Round) + ) + } +} + +@Composable +fun Ellipsis(modifier: Modifier = Modifier, color: Color = LocalContentColor.current) { + Canvas(modifier.size(7.dp, 5.dp)) { + val dot = 1.dp.toPx() + val top = (size.height - dot) / 2 + repeat(3) { + drawRect(color, Offset(it * (size.width - dot) / 2, top), Size(dot, dot)) + } + } +} + +@Composable +fun Chevron( + degrees: Float, + modifier: Modifier = Modifier, + color: Color = LocalContentColor.current +) { + Canvas(modifier.size(5.dp).rotate(degrees)) { + drawPath( + path = Path().apply { + moveTo(size.width * 0.2f, size.height * 0.1f) + lineTo(size.width * 0.9f, size.height * 0.5f) + lineTo(size.width * 0.2f, size.height * 0.9f) + close() + }, + color = color + ) + } +} + +@Composable +fun Expandable( + visible: Boolean, + modifier: Modifier = Modifier, + content: @Composable () -> Unit +) { + AnimatedVisibility( + visible = visible, + modifier = modifier, + enter = expandVertically(tween(TOGGLE_MILLIS)) + fadeIn(tween(TOGGLE_MILLIS)), + exit = shrinkVertically(tween(TOGGLE_MILLIS)) + fadeOut(tween(TOGGLE_MILLIS)), + ) { content() } +} + +@Composable +fun Section( + title: String, + revealed: Boolean = false, + content: @Composable ColumnScope.() -> Unit, +) { + val colors = LambdaTheme.colors + var expanded by remember { mutableStateOf(false) } + LaunchedEffect(revealed) { + if (revealed) expanded = true + } + val turn by animateFloatAsState(if (expanded) 90f else 0f, tween(TOGGLE_MILLIS)) + val rowHeight = Look.rowHeight + + Column( + Modifier + .fillMaxWidth() + .padding(top = 1.dp) + .drawWithContent { + drawContent() + if (size.height > rowHeight.toPx() + 1f) { + drawRect(colors.primary, size = Size(SECTION_BAR.toPx(), size.height)) + } + } + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.raised) + .mouseClickable { expanded = !expanded } + .padding(horizontal = 4.dp) + ) { + Chevron(turn, color = colors.onSurface) + Text(title, color = colors.onSurface, maxLines = 1) + } + Expandable(expanded) { + Column( + Modifier.fillMaxWidth().padding(start = Look.groupIndent, top = 1.dp), + content = content + ) + } + } +} + +@Composable +fun Chip( + onClick: () -> Unit, + modifier: Modifier = Modifier, + content: @Composable RowScope.() -> Unit +) { + val colors = LambdaTheme.colors + ContentColor(colors.onControl) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = modifier + .height(Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.control) + .hoverHighlight(colors.onControl.copy(alpha = 0.12f)) + .mouseClickable(onClick = onClick) + .padding(horizontal = 4.dp), + content = content + ) + } +} + +@Composable +fun Dropdown( + label: String, + options: List, + selected: T, + optionLabel: (T) -> String, + modifier: Modifier = Modifier, + onSelect: (T) -> Unit, +) { + val menu = remember { MenuState() } + var chip by remember { mutableStateOf(IntSize.Zero) } + LabeledRow(label, modifier) { + Box(Modifier.onSizeChanged { chip = it }) { + Chip(onClick = menu::toggle) { + SlidingText(optionLabel(selected), Modifier.weight(1f, fill = false)) + Chevron(90f) + } + Menu( + menu.isOpen, + onDismiss = menu::dismiss, + unfoldFrom = IntSize(chip.width, 0) + ) { + options.forEach { option -> + MenuItem(optionLabel(option), selected = option == selected) { + if (option != selected) onSelect(option) + } + } + } + } + } +} + +@Composable +fun LabeledRow( + label: String, + modifier: Modifier = Modifier, + editor: @Composable RowScope.() -> Unit +) { + Layout( + content = { + Text(label, maxLines = 1) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(LABEL_GAP), + content = editor + ) + }, + modifier = modifier.fillMaxWidth().heightIn(min = Look.rowHeight), + ) { (name, edited), constraints -> + val gap = LABEL_GAP.roundToPx() + val loose = constraints.copy(minWidth = 0, minHeight = 0) + val room = constraints.maxWidth + val wanted = edited.maxIntrinsicWidth(constraints.maxHeight) + val editorWidth = + if (!constraints.hasBoundedWidth) wanted + else { + wanted.coerceAtMost( + maxOf( + room - name.maxIntrinsicWidth(constraints.maxHeight) - gap, + room * 3 / 5 + ) + ) + } + val editor = edited.measure(loose.copy(maxWidth = editorWidth.coerceAtLeast(0))) + val nameRoom = + if (constraints.hasBoundedWidth) (room - editor.width - gap).coerceAtLeast(0) + else Constraints.Infinity + val text = name.measure(loose.copy(maxWidth = nameRoom)) + + val width = + if (constraints.hasBoundedWidth) room + else text.width + gap + editor.width + val height = maxOf(text.height, editor.height, constraints.minHeight) + layout(width, height) { + text.place(0, (height - text.height) / 2) + editor.place(width - editor.width, (height - editor.height) / 2) + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/component/Images.kt b/src/main/kotlin/com/lambda/gui/component/Images.kt new file mode 100644 index 000000000..558852697 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Images.kt @@ -0,0 +1,64 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.toComposeImageBitmap +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Dp +import com.lambda.gui.render.ItemAtlas +import com.lambda.gui.render.ItemAtlas.drawItem +import com.lambda.util.stream +import net.minecraft.item.ItemStack +import org.jetbrains.skia.Image +import kotlin.math.roundToInt + +@Composable +fun rememberTexture(path: String): ImageBitmap = + remember(path) { + path.stream + .use { Image.makeFromEncoded(it.readAllBytes()) } + .toComposeImageBitmap() + } + +@Composable +fun ItemIcon(stack: ItemStack, size: Dp, modifier: Modifier = Modifier) { + val slot = remember { ItemAtlas.Slot() } + val density = LocalDensity.current + val pixels = + with(density) { + ItemAtlas.ITEM * (size.toPx() / ItemAtlas.ITEM).roundToInt().coerceAtLeast(1) + } + SideEffect { + slot.stack = stack + slot.size = pixels + } + DisposableEffect(slot) { + ItemAtlas.add(slot) + onDispose { ItemAtlas.remove(slot) } + } + Spacer(modifier.size(with(density) { pixels.toDp() }).drawBehind { drawItem(slot) }) +} diff --git a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt new file mode 100644 index 000000000..58c89c7b4 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt @@ -0,0 +1,91 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.focusable +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.focus.FocusDirection +import androidx.compose.ui.focus.FocusManager +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme + +private val FOCUS_MARK = 1.dp + +internal object KeyboardFocus { + var visible by mutableStateOf(false) + + private val layers = ArrayList() + + fun move(direction: FocusDirection) = layers.lastOrNull()?.moveFocus(direction) == true + + @Composable + fun Layer() { + val manager = LocalFocusManager.current + DisposableEffect(manager) { + layers += manager + onDispose { layers -= manager } + } + } +} + +fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = + composed { + if (!LocalKeyboardReachable.current) return@composed Modifier + var focused by remember { mutableStateOf(false) } + val handle by rememberUpdatedState(onKey) + val mark = LambdaTheme.colors.onSurface + onFocusChanged { focused = it.isFocused } + .onKeyEvent { it.type == KeyEventType.KeyDown && KeyboardFocus.visible && handle(it) } + .focusable() + .drawWithContent { + drawContent() + if (!focused || !KeyboardFocus.visible) return@drawWithContent + val width = FOCUS_MARK.toPx() + drawRect( + mark, + Offset(width / 2, width / 2), + Size(size.width - width, size.height - width), + style = Stroke(width) + ) + } + } + +val LocalKeyboardReachable = compositionLocalOf { true } + +internal val KeyEvent.isActivation get() = key == Key.Enter || key == Key.Spacebar diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt new file mode 100644 index 000000000..9ed115f65 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -0,0 +1,179 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.PointerMatcher +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.drag +import androidx.compose.foundation.gestures.onDrag +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.isShiftPressed +import androidx.compose.ui.input.pointer.PointerButton +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.IntSize + +@OptIn(ExperimentalComposeUiApi::class) +fun Modifier.mouseClickable( + enabled: Boolean = true, + keyboard: Boolean = true, + onRightClick: (() -> Unit)? = null, + onClick: (() -> Unit)? = null, +): Modifier = + if (!enabled) this + else composed { + val onRelease = LocalClickOnRelease.current + val actionFor by rememberUpdatedState { button: PointerButton? -> + when (button) { + PointerButton.Primary -> onClick + PointerButton.Secondary -> onRightClick + else -> null + } + } + val keys = + if (!keyboard) Modifier + else Modifier.keyboardFocusable { event -> + val action = + if (event.isShiftPressed) onRightClick + else onClick ?: onRightClick + if (event.isActivation) action?.invoke() + event.isActivation && action != null + } + keys.pointerInput(onRelease) { + awaitPointerEventScope { + while (true) { + val press = awaitPointerEvent() + val down = press.changes.first() + val button = press.button + if (press.type != PointerEventType.Press || down.isConsumed || actionFor(button) == null) continue + down.consume() + if (!onRelease) { + actionFor(button)?.invoke() + continue + } + + while (true) { + val event = awaitPointerEvent() + val change = event.changes.first() + if (event.type == PointerEventType.Press) break + if (event.type != PointerEventType.Release || event.button != button) continue + change.consume() + val inside = change.position.x in 0f..size.width.toFloat() && + change.position.y in 0f..size.height.toFloat() + if (inside) actionFor(button)?.invoke() + break + } + } + } + } + } + +val LocalClickOnRelease = compositionLocalOf { false } + +fun Modifier.onMousePress( + button: PointerButton, + onPress: (position: Offset) -> Unit +): Modifier = + onPress { pressed, position -> + if (pressed == button) onPress(position) + pressed == button + } + +@OptIn(ExperimentalComposeUiApi::class) +private fun Modifier.onPress( + handle: (button: PointerButton?, position: Offset) -> Boolean +): Modifier = + composed { + val currentHandle by rememberUpdatedState(handle) + pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.first() + if (event.type != PointerEventType.Press || change.isConsumed) continue + if (currentHandle(event.button, change.position)) change.consume() + } + } + } + } + +fun Modifier.consumeClicks(): Modifier = + pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + if (event.type == PointerEventType.Press) event.changes.forEach { it.consume() } + } + } + } + +@OptIn(ExperimentalFoundationApi::class) +fun Modifier.mouseDraggable( + onDragStart: () -> Unit = {}, + onDragEnd: () -> Unit = {}, + onDrag: (Offset) -> Unit, +): Modifier = + onDrag( + matcher = PointerMatcher.mouse(PointerButton.Primary), + onDragStart = { onDragStart() }, + onDragCancel = onDragEnd, + onDragEnd = onDragEnd, + onDrag = onDrag, + ) + +fun Modifier.scrubbable( + onEnd: () -> Unit = {}, + onScrub: (position: Offset, size: IntSize) -> Unit +): Modifier = + composed { + val currentOnScrub by rememberUpdatedState(onScrub) + val currentOnEnd by rememberUpdatedState(onEnd) + pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown() + down.consume() + currentOnScrub(down.position, size) + drag(down.id) { change -> + change.consume() + currentOnScrub(change.position, size) + } + currentOnEnd() + } + } + } + +fun Modifier.hoverHighlight(color: Color): Modifier = + composed { + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() + hoverable(interactions).background(if (hovered) color else Color.Transparent) + } diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt new file mode 100644 index 000000000..911f4956d --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -0,0 +1,719 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.MutableTransitionState +import androidx.compose.animation.expandIn +import androidx.compose.animation.expandVertically +import androidx.compose.animation.shrinkOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.graphics.drawscope.translate +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.areAnyPressed +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.layout.positionInWindow +import androidx.compose.ui.platform.LocalClipboard +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.round +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties +import com.lambda.gui.core.GameClipboard +import com.lambda.gui.core.LocalShown +import com.lambda.gui.core.Press +import com.lambda.gui.core.awaitFrames +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Motion +import com.lambda.gui.theme.Type +import com.lambda.module.modules.client.Style +import kotlin.math.max + +@OptIn(ExperimentalComposeUiApi::class) +private val FLOATING = + PopupProperties( + focusable = true, + dismissOnBackPress = true, + dismissOnClickOutside = true, + clippingEnabled = true, + usePlatformDefaultWidth = false, + usePlatformInsets = true, + consumePointerInputOutside = false, + ) + +private val SLACK = 4.dp + +@Composable +private fun ScenePopup( + popupPositionProvider: PopupPositionProvider, + onDismissRequest: (() -> Unit)? = null, + properties: PopupProperties = PopupProperties(), + onKeyEvent: ((KeyEvent) -> Boolean)? = null, + content: @Composable () -> Unit, +) = + Popup(popupPositionProvider, onDismissRequest, properties, onKeyEvent = onKeyEvent) { + CompositionLocalProvider(LocalClipboard provides GameClipboard, content = content) + } + +enum class MenuPlacement { + Below, + + Beside, +} + +@Stable +class MenuState { + var isOpen by mutableStateOf(false) + private set + private var dismissedBy = -1L + + fun dismiss() { + isOpen = false + dismissedBy = Press.id + } + + fun toggle() { + if (dismissedBy != Press.id) isOpen = true + } +} + +@Composable +fun Menu( + open: Boolean, + onDismiss: () -> Unit, + placement: MenuPlacement = MenuPlacement.Below, + unfoldFrom: IntSize = IntSize.Zero, + attached: Boolean = false, + content: @Composable ColumnScope.() -> Unit, +) { + MenuPopup( + open, + remember(placement) { UnfoldingPosition(placement::place) }, + onDismiss, + unfoldFrom, + attached, + content + ) +} + +private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize) = + when (this) { + MenuPlacement.Below -> + IntOffset( + anchor.left, + if (anchor.bottom + popup.height <= window.height || + anchor.top - popup.height < 0 + ) { + anchor.bottom + } + else anchor.top - popup.height + ) + MenuPlacement.Beside -> + IntOffset( + if (anchor.right + popup.width <= window.width) anchor.right + else anchor.left - popup.width, + anchor.top + ) + } + +@Composable +fun Popout( + open: Boolean, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit +) { + val position = remember { UnfoldingPosition(MenuPlacement.Beside::place) } + FloatingPanel( + open, + position, + onDismiss, + RoundedCornerShape(Look.panelRounding) + ) { panel -> + Column(panel.padding(3.dp), content = content) + } +} + +@Composable +fun ContextMenu( + open: Boolean, + position: IntOffset, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit +) = + MenuPopup( + open, + remember(position) { UnfoldingPosition { _, _, _ -> position } }, + onDismiss, + IntSize.Zero, + false, + content + ) + +@Composable +fun rememberLast(value: T?): T? { + val last = remember { LastValue() } + if (value != null) last.value = value + return last.value +} + +private class LastValue { + var value: T? = null +} + +private val LocalMenuDismiss = staticCompositionLocalOf<(() -> Unit)?> { null } + +private val LocalMenuOpen = compositionLocalOf { true } + +@Composable +private fun MenuPopup( + open: Boolean, + position: UnfoldingPosition, + onDismiss: () -> Unit, + unfoldFrom: IntSize, + attached: Boolean, + content: @Composable ColumnScope.() -> Unit, +) { + val open = open && LocalMenuOpen.current + val dismissAll = LocalMenuDismiss.current ?: onDismiss + val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } + val shape = + when { + !attached -> RoundedCornerShape(Look.menuRounding) + position.upwards -> RoundedCornerShape(topStart = Look.menuRounding, topEnd = Look.menuRounding) + else -> RoundedCornerShape(bottomStart = Look.menuRounding, bottomEnd = Look.menuRounding) + } + FloatingPanel(open, position, onDismiss, shape, unfoldFrom) { panel -> + CompositionLocalProvider(LocalMenuDismiss provides dismissAll, LocalMenuOpen provides open) { + ScrollColumn( + modifier = Modifier + .heightIn(max = screenHeight) + .width(IntrinsicSize.Max) + .widthIn(min = maxOf(80.dp, with(LocalDensity.current) { unfoldFrom.width.toDp() })) + .then(panel) + .clip(shape), + content = content + ) + } + } +} + +class PopupHost { + var closing by mutableStateOf(false) + + var bounds by mutableStateOf(Rect.Zero) + private set + + var full = Rect.Zero + private set + + fun place(bounds: Rect) { + this.bounds = bounds + if (!closing) full = bounds + } +} + +val LocalPopupHost = compositionLocalOf { null } + +private fun Modifier.swallowedBy(host: PopupHost?): Modifier = + if (host == null) this + else composed { + var origin by remember { mutableStateOf(Offset.Zero) } + onGloballyPositioned { origin = it.positionInWindow() }.drawWithContent { + if (!host.closing) return@drawWithContent drawContent() + val full = host.full + val left = host.bounds + val slack = SLACK.toPx() + val dx = + when { + origin.x >= full.right - slack -> left.right - full.right + origin.x + size.width <= full.left + slack -> left.left - full.left + else -> null + } + val dy = + when { + origin.y >= full.bottom - slack -> left.bottom - full.bottom + origin.y + size.height <= full.top + slack -> left.top - full.top + else -> null + } + val far = 10_000f + clipRect( + if (dx == null) left.left - origin.x else -far, + if (dy == null) left.top - origin.y else -far, + if (dx == null) left.right - origin.x else far, + if (dy == null) left.bottom - origin.y else far, + ) { + translate(dx ?: 0f, dy ?: 0f) { this@drawWithContent.drawContent() } + } + } + } + +@Composable +private fun FloatingPanel( + open: Boolean, + position: UnfoldingPosition, + onDismiss: () -> Unit, + shape: Shape, + unfoldFrom: IntSize = IntSize.Zero, + content: @Composable (panel: Modifier) -> Unit, +) { + if (!LocalShown.current) { + if (open) SideEffect(onDismiss) + return + } + val visibility = remember { MutableTransitionState(false) } + visibility.targetState = open + if (!open && visibility.isIdle && !visibility.currentState) return + + val host = LocalPopupHost.current + if (host != null && host.closing && open) SideEffect(onDismiss) + val own = remember { PopupHost() } + SideEffect { own.closing = !open } + + val colors = LambdaTheme.colors + ScenePopup( + popupPositionProvider = position, + onDismissRequest = { if (open) onDismiss() }, + properties = FLOATING, + onKeyEvent = { open && it.dismissOnEscape(onDismiss) }, + ) { + if (open) KeyboardFocus.Layer() + ContentColor(colors.onSurface) { + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier + .swallowedBy(host) + .onGloballyPositioned { own.place(it.boundsInWindow()) } + .dropShadow(shape, close = true) + .window(colors.panel, colors.border, shape), + enter = expandIn(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, + exit = shrinkOut(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, + ) { + CompositionLocalProvider(LocalPopupHost provides own) { + content(Modifier.onSizeChanged { position.unfolded = it }) + } + } + } + } +} + +private class UnfoldingPosition( + private val position: (anchor: IntRect, window: IntSize, popup: IntSize) -> IntOffset, +) : PopupPositionProvider { + var unfolded = IntSize.Zero + + private var leftwards by mutableStateOf(false) + + var upwards by mutableStateOf(false) + private set + + val corner + get() = + when { + upwards -> + if (leftwards) Alignment.BottomEnd + else Alignment.BottomStart + else -> + if (leftwards) Alignment.TopEnd + else Alignment.TopStart + } + + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset { + val full = + IntSize( + max(unfolded.width, popupContentSize.width), + max(unfolded.height, popupContentSize.height) + ) + val wanted = position(anchorBounds, windowSize, full) + leftwards = wanted.x + full.width <= anchorBounds.left + upwards = wanted.y + full.height <= anchorBounds.top + val x = wanted.x.coerceIn(0, (windowSize.width - full.width).coerceAtLeast(0)) + val y = wanted.y.coerceIn(0, (windowSize.height - full.height).coerceAtLeast(0)) + return IntOffset( + if (leftwards) x + full.width - popupContentSize.width else x, + if (upwards) y + full.height - popupContentSize.height else y + ) + } +} + +@Composable +fun Suggestions( + open: Boolean, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit +) { + if (!LocalShown.current) { + if (open) SideEffect(onDismiss) + return + } + val visibility = remember { MutableTransitionState(false) } + visibility.targetState = open + if (!open && visibility.isIdle && !visibility.currentState) return + + val colors = LambdaTheme.colors + val shape = RoundedCornerShape(Look.menuRounding) + val screenHeight = + with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } + ScenePopup( + popupPositionProvider = remember { + positionProvider { anchor, window, popup -> + val centred = anchor.left + (anchor.width - popup.width) / 2 + IntOffset( + centred.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), + anchor.bottom + ) + } + }, + onDismissRequest = { if (open) onDismiss() }, + properties = PopupProperties(focusable = false), + ) { + ContentColor(colors.onSurface) { + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier + .dropShadow(shape) + .window(colors.panel, colors.border, shape), + enter = expandVertically(Motion.panels, Alignment.Top), + exit = shrinkVertically(Motion.panels, Alignment.Top), + ) { + ScrollColumn( + modifier = Modifier + .heightIn(max = screenHeight * 0.6f) + .width(IntrinsicSize.Max) + .animateContentSize(Motion.panels), + content = content + ) + } + } + } +} + +@Composable +fun MenuItem( + label: String, + enabled: Boolean = true, + checked: Boolean? = null, + selected: Boolean = false, + hint: String? = null, + onClick: () -> Unit, +) { + val colors = LambdaTheme.colors + val dismiss = LocalMenuDismiss.current + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .background(if (selected) colors.controlSelected else Color.Transparent) + .then( + if (!enabled) Modifier + else Modifier.hoverHighlight(colors.controlSelected).mouseClickable { + onClick() + if (checked == null) dismiss?.invoke() + } + ) + .padding(horizontal = 5.dp, vertical = 1.dp) + ) { + if (checked != null) Checkmark(checked, Modifier.padding(end = 3.dp)) + val color = + when { + !enabled -> colors.onSurfaceVariant + selected -> colors.secondary + else -> colors.onSurface + } + Text(label, Modifier.weight(1f), color, maxLines = 1) + if (hint != null) { + Text( + hint, + Modifier.padding(start = 12.dp), + colors.onSurfaceVariant, + Type.label, + maxLines = 1 + ) + } + } +} + +@Composable +fun Submenu( + label: String, + enabled: Boolean = true, + content: @Composable ColumnScope.() -> Unit +) { + val colors = LambdaTheme.colors + val menu = remember { MenuState() } + Box { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .then( + if (enabled) { + Modifier + .hoverHighlight(colors.controlSelected) + .mouseClickable(onClick = menu::toggle) + } + else Modifier + ) + .padding(horizontal = 5.dp, vertical = 1.dp) + ) { + Text( + label, + Modifier.weight(1f), + if (enabled) colors.onSurface else colors.onSurfaceVariant, + maxLines = 1 + ) + Chevron(0f, Modifier.padding(start = 12.dp), colors.onSurfaceVariant) + } + Menu( + menu.isOpen, + onDismiss = menu::dismiss, + MenuPlacement.Beside, + content = content + ) + } +} + +@Composable +fun MenuLabel(label: String) = + Text( + label, + Modifier.padding(horizontal = 5.dp, vertical = 1.dp), + LambdaTheme.colors.onSurfaceVariant, + maxLines = 1 + ) + +@Composable +fun MenuHelp(text: String, label: String = "Help") { + val colors = LambdaTheme.colors + Tooltip(text, Modifier.fillMaxWidth()) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .hoverHighlight(colors.raised) + .padding(horizontal = 5.dp, vertical = 1.dp) + ) { + Text(label, Modifier.weight(1f), colors.onSurfaceVariant, maxLines = 1) + Text( + "?", + Modifier.padding(start = 12.dp), + colors.onSurfaceVariant, + Type.label, + maxLines = 1 + ) + } + } +} + +@Composable +fun MenuDivider() = + Spacer( + Modifier + .fillMaxWidth() + .padding(horizontal = 3.dp, vertical = 1.dp) + .height(1.dp) + .background(LambdaTheme.colors.border) + ) + +@Composable +fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { + if (!LocalShown.current) { + if (onDismiss != null) SideEffect(onDismiss) + return + } + val colors = LambdaTheme.colors + ScenePopup( + popupPositionProvider = remember { + positionProvider { _, _, _ -> IntOffset.Zero } + }, + properties = PopupProperties(focusable = true), + onKeyEvent = { onDismiss != null && it.dismissOnEscape(onDismiss) }, + ) { + KeyboardFocus.Layer() + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .fillMaxSize() + .glass(Color.Black.copy(alpha = 0.35f), RectangleShape) + .mouseClickable(keyboard = false) { onDismiss?.invoke() } + ) { + ContentColor(colors.onSurface) { + Box( + modifier = Modifier + .window( + colors.panel, + colors.border, + RoundedCornerShape(Look.panelRounding), + floating = true + ) + .padding(6.dp), + content = content + ) + } + } + } +} + +@Composable +fun Tooltip( + text: String, + modifier: Modifier = Modifier, + content: @Composable () -> Unit +) { + if (text.isBlank()) { + Box(modifier) { content() } + return + } + val colors = LambdaTheme.colors + var hovered by remember { mutableStateOf(false) } + var visible by remember { mutableStateOf(false) } + var pointer by remember { mutableStateOf(Offset.Zero) } + var bounds by remember { mutableStateOf(Rect.Zero) } + LaunchedEffect(hovered) { + if (!hovered) return@LaunchedEffect + awaitFrames(Style.tooltipDelay.toLong()) + visible = true + } + + Box( + modifier + .onGloballyPositioned { bounds = it.boundsInWindow() } + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + when (event.type) { + PointerEventType.Enter -> hovered = !event.buttons.areAnyPressed + PointerEventType.Exit, PointerEventType.Press -> { + hovered = false + visible = false + } + } + if (!visible) pointer = event.changes.first().position + } + } + } + ) { + content() + if (visible && hovered) { + val below = with(LocalDensity.current) { 16.dp.roundToPx() } + ScenePopup( + popupPositionProvider = remember(pointer, bounds) { + positionProvider { _, window, popup -> + val at = (bounds.topLeft + pointer).round() + IntOffset(0, below) + IntOffset( + at.x.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), + at.y.coerceIn(0, (window.height - popup.height).coerceAtLeast(0)) + ) + } + }, + properties = PopupProperties(focusable = false), + ) { + Text( + text = text, + color = colors.onSurface, + style = Type.label, + modifier = Modifier + .widthIn(max = 220.dp) + .window(colors.panel, colors.border, RoundedCornerShape(Look.menuRounding)) + .padding(horizontal = 4.dp, vertical = 2.dp) + ) + } + } + } +} + +private fun KeyEvent.dismissOnEscape(onDismiss: () -> Unit): Boolean { + if (key != Key.Escape) return false + if (type == KeyEventType.KeyDown) onDismiss() + return true +} + +private fun positionProvider( + position: (anchor: IntRect, window: IntSize, popup: IntSize) -> IntOffset +) = + object : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ) = position(anchorBounds, windowSize, popupContentSize) + } + +private fun IntSize.coerceAtMost(other: IntSize) = IntSize(minOf(width, other.width), minOf(height, other.height)) diff --git a/src/main/kotlin/com/lambda/gui/component/Scroll.kt b/src/main/kotlin/com/lambda/gui/component/Scroll.kt new file mode 100644 index 000000000..784bf7c3a --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Scroll.kt @@ -0,0 +1,142 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.animation.core.EaseOutQuint +import androidx.compose.animation.core.animate +import androidx.compose.animation.core.tween +import androidx.compose.foundation.MutatePriority +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.ScrollbarStyle +import androidx.compose.foundation.VerticalScrollbar +import androidx.compose.foundation.gestures.ScrollableState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.rememberScrollbarAdapter +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.v2.ScrollbarAdapter +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Motion +import com.lambda.module.modules.client.Style +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch + +private val WHEEL_STEP = 14.dp +private val GLIDE = tween(durationMillis = 520, easing = EaseOutQuint) +private const val SCROLLBAR_FADE_MILLIS = 150 + +@Composable +fun ScrollColumn( + modifier: Modifier = Modifier, + scroll: ScrollState = rememberScrollState(), + content: @Composable ColumnScope.() -> Unit, +) { + Box(modifier.wheelScrollable(scroll)) { + Column(Modifier.verticalScroll(scroll), content = content) + if (scroll.maxValue > 0) Scrollbar(rememberScrollbarAdapter(scroll), Modifier.matchParentSize()) + } +} + +@Composable +fun Scrollbar(adapter: ScrollbarAdapter, modifier: Modifier) { + val colors = LambdaTheme.colors + Box(modifier) { + VerticalScrollbar( + adapter = adapter, + modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), + style = ScrollbarStyle( + minimalHeight = 12.dp, + thickness = 2.dp, + shape = RoundedCornerShape(1.dp), + hoverDurationMillis = SCROLLBAR_FADE_MILLIS, + unhoverColor = colors.onSurfaceVariant.copy(alpha = 0.5f), + hoverColor = colors.onSurface + ) + ) + } +} + +fun Modifier.wheelScrollable(state: ScrollableState): Modifier = + composed { + val scope = rememberCoroutineScope() + val notch = with(LocalDensity.current) { WHEEL_STEP.toPx() } + val glide = remember { WheelGlide() } + pointerInput(state, notch) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type != PointerEventType.Scroll) continue + val change = event.changes.first() + val distance = change.scrollDelta.y * notch * Style.scrollSpeed + val canFollow = + if (distance > 0) state.canScrollForward + else state.canScrollBackward + if (distance == 0f || !canFollow || change.isConsumed) continue + change.consume() + + val total = + distance + + if (glide.remaining * distance > 0) glide.remaining + else 0f + glide.job?.cancel() + glide.job = + scope.launch(Motion.SCROLL) { + var travelled = 0f + glide.remaining = total + try { + state.scroll(MutatePriority.UserInput) { + animate( + 0f, + total, + animationSpec = GLIDE + ) { value, _ -> + scrollBy(value - travelled) + travelled = value + glide.remaining = total - value + } + } + } finally { + if (glide.job === coroutineContext[Job]) { + glide.remaining = 0f + } + } + } + } + } + } + } + +private class WheelGlide { + var remaining = 0f + var job: Job? = null +} diff --git a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt new file mode 100644 index 000000000..479c3a07d --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt @@ -0,0 +1,105 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.keyframes +import androidx.compose.animation.core.tween +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.layout +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LocalContentColor +import com.lambda.gui.theme.Motion +import com.lambda.gui.theme.Type +import kotlinx.coroutines.withContext +import kotlin.math.roundToInt + +private val SLIDE_SPEED = 28.dp +private const val REST_MILLIS = 350 +private const val END_REST_MILLIS = 900 +private const val BACK_MILLIS = 250 + +@Composable +fun SlidingText( + text: String, + modifier: Modifier = Modifier, + color: Color = LocalContentColor.current, + style: TextStyle = Type.body, +) { + var overflow by remember { mutableIntStateOf(0) } + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() + val pixelsPerSecond = with(LocalDensity.current) { SLIDE_SPEED.toPx() } + + val slide = remember { Animatable(0f) } + LaunchedEffect(hovered, overflow) { + if (!hovered || overflow == 0) { + slide.animateTo(0f, tween(BACK_MILLIS)) + return@LaunchedEffect + } + val outMillis = (overflow / pixelsPerSecond * 1000).roundToInt().coerceAtLeast(BACK_MILLIS) + withContext(Motion.UNSCALED) { + slide.animateTo( + targetValue = 0f, + animationSpec = infiniteRepeatable( + keyframes { + durationMillis = REST_MILLIS + outMillis + END_REST_MILLIS + BACK_MILLIS + 0f at REST_MILLIS using LinearEasing + 1f at REST_MILLIS + outMillis + 1f at REST_MILLIS + outMillis + END_REST_MILLIS + } + ) + ) + } + } + + Text( + text = text, + color = color, + style = style, + softWrap = false, + modifier = modifier + .hoverable(interactions) + .clipToBounds() + .layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(maxWidth = Constraints.Infinity)) + overflow = + if (constraints.hasBoundedWidth) (placeable.width - constraints.maxWidth).coerceAtLeast(0) + else 0 + layout(placeable.width - overflow, placeable.height) { + placeable.place(-(slide.value * overflow).roundToInt(), 0) + } + } + ) +} diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt new file mode 100644 index 000000000..f619825ea --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -0,0 +1,179 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.border +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.draw.drawWithCache +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.BlendMode +import androidx.compose.ui.graphics.ClipOp +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.addOutline +import androidx.compose.ui.graphics.asSkiaPath +import androidx.compose.ui.graphics.drawscope.clipPath +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.graphics.drawscope.drawIntoCanvas +import androidx.compose.ui.graphics.skiaCanvas +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.Look +import org.jetbrains.skia.Canvas +import org.jetbrains.skia.ColorFilter +import org.jetbrains.skia.ColorMatrix +import org.jetbrains.skia.FilterBlurMode +import org.jetbrains.skia.FilterTileMode +import org.jetbrains.skia.ImageFilter +import org.jetbrains.skia.MaskFilter +import org.jetbrains.skia.Paint +import org.jetbrains.skia.Rect + +private val SHADOW_COLOR = Color.Black.copy(alpha = 0.55f) +private val SHADOW_BLUR = 5.dp +private val SHADOW_DROP = 2.dp +private val CLOSE_SHADOW_COLOR = Color.Black.copy(alpha = 0.85f) +private val CLOSE_SHADOW_BLUR = 3.dp +private val CLOSE_SHADOW_DROP = 2.dp + +private val DRAWN = + ImageFilter.makeColorFilter( + ColorFilter.makeMatrix( + ColorMatrix( + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 64f, 0f, + ) + ), + null, + null + ) + +private val REPLACE = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC } +private val WITHIN = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC_IN } + +fun Modifier.glass(color: Color, shape: Shape): Modifier = + clip(shape).composed { + val sigma = with(LocalDensity.current) { Look.backdropBlur.toPx() } + val underlay = Look.underlay + val blur = + remember(sigma, underlay) { + if (sigma <= 0f) return@remember null + val blurred = ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) + if (underlay >= 1f) blurred + else ImageFilter.makeColorFilter(faded(underlay), blurred, null) + } + drawBehind { + if (blur == null) { + drawRect(color, blendMode = BlendMode.Src) + return@drawBehind + } + drawIntoCanvas { canvas -> + canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), REPLACE, blur)) + canvas.skiaCanvas.restore() + } + drawRect(color) + } + } + +fun Modifier.window( + color: Color, + border: Color, + shape: Shape, + floating: Boolean = false +): Modifier = + (if (floating) dropShadow(shape) else this) + .border(Look.outlineWidth, if (Look.outlines) border else Color.Transparent, shape) + .glass(color, shape) + .clip(if (Look.outlines) Inset(shape, Look.outlineWidth / 2) else RectangleShape) + .consumeClicks() + +private data class Inset(private val shape: Shape, private val inset: Dp) : Shape { + override fun createOutline( + size: Size, + layoutDirection: LayoutDirection, + density: Density + ): Outline { + val edge = with(density) { inset.toPx() } + val inner = + Size( + (size.width - edge * 2).coerceAtLeast(0f), + (size.height - edge * 2).coerceAtLeast(0f) + ) + val path = Path().apply { addOutline(shape.createOutline(inner, layoutDirection, density)) } + path.translate(Offset(edge, edge)) + return Outline.Generic(path) + } +} + +fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = + drawWithCache { + val body = Path().apply { addOutline(shape.createOutline(size, layoutDirection, this@drawWithCache)) } + val drop = (if (close) CLOSE_SHADOW_DROP else SHADOW_DROP).toPx() + val blur = (if (close) CLOSE_SHADOW_BLUR else SHADOW_BLUR).toPx() + val reach = blur * 3 + val shadow = + Paint().apply { + color = (if (close) CLOSE_SHADOW_COLOR else SHADOW_COLOR).toArgb() + maskFilter = MaskFilter.makeBlur(FilterBlurMode.NORMAL, blur) + } + onDrawBehind { + if (!Look.shadows) return@onDrawBehind + clipPath(body, ClipOp.Difference) { + clipRect( + -reach, + drop - reach, + size.width + reach, + size.height + drop + reach + ) { + drawIntoCanvas { canvas -> + val skia = canvas.skiaCanvas + skia.saveLayer(Canvas.SaveLayerRec(null, null, DRAWN)) + skia.saveLayer(null, WITHIN) + skia.translate(0f, drop) + skia.drawPath(body.asSkiaPath(), shadow) + skia.restore() + skia.restore() + } + } + } + } + } + +private fun faded(fraction: Float) = + ColorFilter.makeMatrix( + ColorMatrix( + 1f, 0f, 0f, 0f, 0f, + 0f, 1f, 0f, 0f, 0f, + 0f, 0f, 1f, 0f, 0f, + 0f, 0f, 0f, fraction, 0f, + ) + ) diff --git a/src/main/kotlin/com/lambda/gui/component/Text.kt b/src/main/kotlin/com/lambda/gui/component/Text.kt new file mode 100644 index 000000000..ba8385a78 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Text.kt @@ -0,0 +1,78 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.text.BasicText +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shadow +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.LocalContentColor +import com.lambda.gui.theme.Type + +private val LocalTextShadow = compositionLocalOf { null } + +@Composable +fun Text( + text: String, + modifier: Modifier = Modifier, + color: Color = LocalContentColor.current, + style: TextStyle = Type.body, + maxLines: Int = Int.MAX_VALUE, + softWrap: Boolean = true, +) { + if (maxLines == 1) return SlidingText(text, modifier, color, style) + BasicText( + text = text, + modifier = modifier, + style = style.copy(color = color, shadow = style.shadow ?: LocalTextShadow.current), + maxLines = maxLines, + softWrap = softWrap, + overflow = if (maxLines == Int.MAX_VALUE) TextOverflow.Clip else TextOverflow.Ellipsis, + ) +} + +@Composable +fun ContentColor(color: Color, content: @Composable () -> Unit) = + CompositionLocalProvider(LocalContentColor provides color, content = content) + +@Composable +fun SoftTextShadow(content: @Composable () -> Unit) { + val density = LocalDensity.current + val color = LambdaTheme.colors.textShadow + val shadow = + remember(density, color) { + with(density) { Shadow(color, Offset(0f, 0.5.dp.toPx()), blurRadius = 1.5.dp.toPx()) } + } + CompositionLocalProvider(LocalTextShadow provides shadow, content = content) +} + +@Composable +fun TextStyle.shadowed(color: Color = LambdaTheme.colors.textShadow): TextStyle { + val offset = with(LocalDensity.current) { 1.dp.toPx() } + return copy(shadow = Shadow(color, Offset(offset, offset))) +} diff --git a/src/main/kotlin/com/lambda/gui/component/TextInput.kt b/src/main/kotlin/com/lambda/gui/component/TextInput.kt new file mode 100644 index 000000000..ea13cd7b4 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/TextInput.kt @@ -0,0 +1,185 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Type + +internal object TextFocus { + private val fields = mutableListOf() + + val isTyping get() = fields.isNotEmpty() + + fun press(position: Offset) = fields.filter { position !in it.bounds }.forEach { it.release() } + + fun add(field: Field) = fields.add(field) + fun remove(field: Field) = fields.remove(field) + + class Field(val release: () -> Unit) { + var bounds = Rect.Zero + } +} + +@Composable +fun TextInput( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + singleLine: Boolean = true, + placeholder: String = "", + style: TextStyle = Type.body, + focused: Boolean = false, + onDone: (() -> Unit)? = null, +) { + val colors = LambdaTheme.colors + var field by remember { mutableStateOf(TextFieldValue(value, TextRange(value.length))) } + var adopted by remember { mutableStateOf(value) } + if (value != adopted) { + adopted = value + if (value != field.text) field = TextFieldValue(value, TextRange(value.length)) + } + + val focus = remember { FocusRequester() } + var hadFocus by remember { mutableStateOf(false) } + var hasFocus by remember { mutableStateOf(false) } + if (focused) LaunchedEffect(Unit) { focus.requestFocus() } + val focusManager = LocalFocusManager.current + val typing = remember(focusManager) { TextFocus.Field { focusManager.clearFocus() } } + if (hasFocus) DisposableEffect(typing) { + TextFocus.add(typing) + onDispose { TextFocus.remove(typing) } + } + + BasicTextField( + value = field, + onValueChange = { + val edited = it.text != field.text + field = it + if (edited) onValueChange(it.text) + }, + enabled = LocalKeyboardReachable.current, + singleLine = singleLine, + textStyle = style.copy(color = colors.onControl), + cursorBrush = SolidColor(colors.onControl), + modifier = modifier + .heightIn(min = Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.input) + .onGloballyPositioned { typing.bounds = it.boundsInWindow() } + .focusRequester(focus) + .onFocusChanged { + hasFocus = it.isFocused + if (it.isFocused) hadFocus = true + else if (hadFocus) onDone?.invoke() + } + .onPreviewKeyEvent { event -> + if ( + onDone == null || + (event.key != Key.Enter && event.key != Key.Escape) + ) { + false + } + else { + if (event.type == KeyEventType.KeyDown) onDone() + true + } + } + .padding(horizontal = 3.dp, vertical = 1.dp), + decorationBox = { innerTextField -> + Box(contentAlignment = Alignment.CenterStart) { + if (field.text.isEmpty()) { + Text( + placeholder, + color = colors.onSurfaceVariant, + style = style, + maxLines = 1 + ) + } + innerTextField() + } + } + ) +} + +@Composable +fun NumberInput( + value: T, + parse: (String) -> T?, + onCommit: (T) -> Unit, + modifier: Modifier = Modifier, + focused: Boolean = false, + onDone: () -> Unit = {}, +) { + var draft by remember { mutableStateOf(null) } + fun finish(commit: Boolean) { + val typed = draft + draft = null + if (commit && typed != null) { + parse(typed.trim())?.takeIf { it != value }?.let(onCommit) + } + onDone() + } + TextInput( + value = draft ?: value.toString(), + onValueChange = { draft = it }, + modifier = modifier.onPreviewKeyEvent { event -> + if (event.key != Key.Escape) false + else { + if (event.type == KeyEventType.KeyDown) finish(commit = false) + true + } + }, + focused = focused, + onDone = { finish(commit = true) }, + ) +} diff --git a/src/main/kotlin/com/lambda/gui/components/ClickGuiLayout.kt b/src/main/kotlin/com/lambda/gui/components/ClickGuiLayout.kt deleted file mode 100644 index 973f570a0..000000000 --- a/src/main/kotlin/com/lambda/gui/components/ClickGuiLayout.kt +++ /dev/null @@ -1,558 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui.components - -import com.lambda.Lambda.mc -import com.lambda.config.Config -import com.lambda.config.Tab -import com.lambda.config.categories.GuiCategory -import com.lambda.config.entries.onValueChange -import com.lambda.core.Loadable -import com.lambda.event.events.GuiEvent -import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe -import com.lambda.gui.DearImGui -import com.lambda.gui.LambdaScreen -import com.lambda.gui.MenuBar -import com.lambda.gui.MenuBar.buildMenuBar -import com.lambda.gui.OverlayBackgroundScreen -import com.lambda.gui.components.QuickSearch.renderQuickSearch -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.gui.dsl.ImGuiBuilder.buildLayout -import com.lambda.gui.snap.Guide -import com.lambda.gui.snap.RectF -import com.lambda.gui.snap.SnapHandler -import com.lambda.gui.snap.SnapHandler.drawDragGrid -import com.lambda.gui.snap.SnapHandler.drawSnapLines -import com.lambda.gui.snap.SnapHandler.updateDragAndSnapping -import com.lambda.imgui.ImGui -import com.lambda.imgui.extension.implot.ImPlot -import com.lambda.imgui.flag.ImGuiCol -import com.lambda.imgui.flag.ImGuiCond -import com.lambda.imgui.flag.ImGuiHoveredFlags -import com.lambda.imgui.flag.ImGuiWindowFlags -import com.lambda.module.ModuleRegistry -import com.lambda.module.ModuleTag -import com.lambda.module.ModuleTag.Companion.shownTags -import com.lambda.module.modules.client.Client -import com.lambda.module.modules.combat.autodisconnect.AutoDisconnectScreen -import com.lambda.sound.LambdaSound -import com.lambda.sound.SoundHandler.play -import com.lambda.util.Describable -import com.lambda.util.KeyCode -import com.lambda.util.NamedEnum -import com.lambda.util.WindowUtils.setLambdaWindowIcon -import net.minecraft.SharedConstants -import net.minecraft.client.gui.screen.ChatScreen -import net.minecraft.client.gui.screen.Screen -import net.minecraft.client.gui.screen.TitleScreen -import net.minecraft.client.gui.screen.ingame.AnvilScreen -import net.minecraft.client.gui.screen.ingame.CommandBlockScreen -import net.minecraft.client.gui.screen.ingame.SignEditScreen -import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen -import net.minecraft.client.util.Icons -import java.awt.Color -import kotlin.math.abs - -@Suppress("unused") -object ClickGuiLayout : Loadable, Config( - "GUI", - GuiCategory -) { - var open = false - var developerMode = false - val keybind by setting("Keybind", KeyCode.Y, screenCheck = false) - .onPressUnsafe { - if (DearImGui.io.wantTextInput) return@onPressUnsafe - if (!open && !canOpenOver(mc.currentScreen)) return@onPressUnsafe - toggle() - } - - /** - * Screens (besides the in-game/null case) the GUI is allowed to open over. - * Add a class here to support opening the GUI on another screen. - */ - private val backgroundScreenTypes = mutableListOf( - TitleScreen::class.java, - MultiplayerScreen::class.java, - AutoDisconnectScreen::class.java, - ) - - /** True when the GUI may be opened over [screen]; null means in-game. */ - fun canOpenOver(screen: Screen?): Boolean = - screen == null || backgroundScreenTypes.any { it.isInstance(screen) } - - private var initialLayoutComplete = false - private var frameCount = 0 - private var activeDragWindowName: String? = null - private var mouseWasDown = false - private var dragOffsetX = 0f - private var dragOffsetY = 0f - private val lastBounds = mutableMapOf() - private val pendingSizes = mutableMapOf>() - private var activeResizeWindowName: String? = null - private var resizeLeftEdge = false - private var resizeRightEdge = false - private var resizeTopEdge = false - private var resizeBottomEdge = false - private var resizeGrabOffsetX = 0f - private var resizeGrabOffsetY = 0f - private val pendingPositions = mutableMapOf>() - private val snapOverlays = mutableMapOf() - - private const val GENERAL_TAB = "General" - private const val SNAPPING_TAB = "Snapping" - private const val SIZING_TAB = "Sizing" - private const val ROUNDING_TAB = "Rounding" - private const val COLORS_TAB = "Colors" - private const val FONT_TAB = "Font" - - @Suppress("unused") - enum class TooltipType( - override val displayName: String, - override val description: String, - val flag: Int - ) : NamedEnum, Describable { - Stationary("Stationary", "Show tooltip after the mouse stays still for a brief moment (~0.15s). Once shown, you can keep moving over the same item/window without waiting again.", ImGuiHoveredFlags.Stationary), - NoDelay("No Delay", "Show tooltip immediately when hovering (no waiting).", ImGuiHoveredFlags.DelayNone), - ShortDelay("Short Delay", "Show tooltip after a short delay (~0.15s), and only after the mouse has been still briefly on the item.", ImGuiHoveredFlags.DelayShort), - LongDelay("Long Delay", "Show tooltip after a longer delay (~0.40s), and only after the mouse has been still briefly on the item.", ImGuiHoveredFlags.DelayNormal) - } - - const val BASE_SCALE = 100 - const val BASE_SCALE_MULTI = 1.8 - - fun deviceScaleMultiplier(): Double { - val monitorWidth = mc.window.monitor?.currentVideoMode?.width?.toDouble() ?: return 1.0 - return (monitorWidth / 1920.0).coerceIn(0.5, 4.0) - } - - // General - @Tab(GENERAL_TAB) internal val scaleSetting by setting("Scale", BASE_SCALE, 50..300, 1, unit = "%") - @Tab(GENERAL_TAB) val alpha by setting("Alpha", 1.0f, 0.0f..1.0f, 0.01f) - @Tab(GENERAL_TAB) val disabledAlpha by setting("Disabled Alpha", 0.6f, 0.0f..1.0f, 0.01f) - @Tab(GENERAL_TAB) val tooltipType by setting("Tooltip Type", TooltipType.Stationary, description = "When to show the tooltip.") - @Tab(GENERAL_TAB) val setLambdaWindowIcon by setting("Set Lambda Window Icon", true) - .onValueChange { _, to -> - if (to) setLambdaWindowIcon() - else { - val icon = if (SharedConstants.getGameVersion().stable()) Icons.RELEASE else Icons.SNAPSHOT - mc.window.setIcon(mc.defaultResourcePack, icon) - } - } - @Tab(GENERAL_TAB) @JvmStatic val setLambdaWindowTitle by setting("Set Lambda Window Title", true).onValueChange { _, _ -> mc.updateWindowTitle() } - @Tab(GENERAL_TAB) val lambdaTitleAppendixName by setting("Append Username", true) { setLambdaWindowTitle }.onValueChange { _, _ -> mc.updateWindowTitle() } - @Tab(GENERAL_TAB) val backgroundBlur by setting("Background Blur", true) - @Tab(GENERAL_TAB) val backgroundDarkening by setting("Background Darkening", true) - - // Snapping - @Tab(SNAPPING_TAB) val snapEnabled by setting("Enable Snapping", true, "Master toggle for GUI/HUD snapping") - @Tab(SNAPPING_TAB) val gridSize by setting("Grid Size", 25f, 2f..128f, 1f, "Grid step in pixels") { snapEnabled } - @Tab(SNAPPING_TAB) val snapToEdges by setting("Snap To Element Edges", true) { snapEnabled } - @Tab(SNAPPING_TAB) val snapToCenters by setting("Snap To Element Centers", true) { snapEnabled } - @Tab(SNAPPING_TAB) val snapToScreenCenter by setting("Snap To Screen Center", true) { snapEnabled } - @Tab(SNAPPING_TAB) val snapToGrid by setting("Snap To Grid", true) { snapEnabled } - @Tab(SNAPPING_TAB) val snapDistanceElement by setting("Snap Distance (Elements)", 20f, 1f..48f, 1f, "Distance threshold in px") { snapEnabled } - @Tab(SNAPPING_TAB) val snapDistanceScreen by setting("Snap Distance (Screen Center)", 14f, 1f..48f, 1f) { snapEnabled } - @Tab(SNAPPING_TAB) val snapDistanceGrid by setting("Snap Distance (Grid)", 12f, 1f..48f, 1f) { snapEnabled } - @Tab(SNAPPING_TAB) val snapLineColor by setting("Snap Line Color", Color(255, 160, 0, 220)) { snapEnabled } - - // Sizing - @Tab(SIZING_TAB) val windowPaddingX by setting("Window Padding X", 8.0f, 0.0f..20.0f, 0.1f) - @Tab(SIZING_TAB) val windowPaddingY by setting("Window Padding Y", 8.0f, 0.0f..20.0f, 0.1f) - @Tab(SIZING_TAB) val windowMinSizeX by setting("Window Min Size X", 32.0f, 0.0f..100.0f, 1.0f) - @Tab(SIZING_TAB) val windowMinSizeY by setting("Window Min Size Y", 32.0f, 0.0f..100.0f, 1.0f) - @Tab(SIZING_TAB) val windowTitleAlignX by setting("Window Title Align X", 0.0f, 0.0f..1.0f, 0.01f) - @Tab(SIZING_TAB) val windowTitleAlignY by setting("Window Title Align Y", 0.5f, 0.0f..1.0f, 0.01f) - @Tab(SIZING_TAB) val framePaddingX by setting("Frame Padding X", 4.0f, 0.0f..20.0f, 0.1f) - @Tab(SIZING_TAB) val framePaddingY by setting("Frame Padding Y", 3.0f, 0.0f..20.0f, 0.1f) - @Tab(SIZING_TAB) val itemSpacingX by setting("Item Spacing X", 8.0f, 0.0f..20.0f, 0.1f) - @Tab(SIZING_TAB) val itemSpacingY by setting("Item Spacing Y", 4.0f, 0.0f..20.0f, 0.1f) - @Tab(SIZING_TAB) val itemInnerSpacingX by setting("Item Inner Spacing X", 4.0f, 0.0f..20.0f, 0.1f) - @Tab(SIZING_TAB) val itemInnerSpacingY by setting("Item Inner Spacing Y", 4.0f, 0.0f..20.0f, 0.1f) - @Tab(SIZING_TAB) val indentSpacing by setting("Indent Spacing", 21.0f, 0.0f..50.0f, 0.1f) - @Tab(SIZING_TAB) val scrollbarSize by setting("Scrollbar Size", 8.4f, 0.0f..30.0f, 0.1f) - @Tab(SIZING_TAB) val grabMinSize by setting("Grab Min Size", 10.0f, 0.0f..30.0f, 0.1f) - @Tab(SIZING_TAB) val windowBorderSize by setting("Window Border Size", 1.0f, 0.0f..5.0f, 0.1f) - @Tab(SIZING_TAB) val childBorderSize by setting("Child Border Size", 1.0f, 0.0f..5.0f, 0.1f) - @Tab(SIZING_TAB) val popupBorderSize by setting("Popup Border Size", 1.0f, 0.0f..5.0f, 0.1f) - @Tab(SIZING_TAB) val frameBorderSize by setting("Frame Border Size", 0.0f, 0.0f..5.0f, 0.1f) - @Tab(SIZING_TAB) val tabBorderSize by setting("Tab Border Size", 0.0f, 0.0f..5.0f, 0.1f) - - // Rounding - @Tab(ROUNDING_TAB) val windowRounding by setting("Window Rounding", 4.6f, 0.0f..12.0f, 0.1f) - @Tab(ROUNDING_TAB) val childRounding by setting("Child Rounding", 0.0f, 0.0f..12.0f, 0.1f) - @Tab(ROUNDING_TAB) val frameRounding by setting("Frame Rounding", 4.6f, 0.0f..12.0f, 0.1f) - @Tab(ROUNDING_TAB) val popupRounding by setting("Popup Rounding", 4.6f, 0.0f..12.0f, 0.1f) - @Tab(ROUNDING_TAB) val scrollbarRounding by setting("Scrollbar Rounding", 9.0f, 0.0f..12.0f, 0.1f) - @Tab(ROUNDING_TAB) val grabRounding by setting("Grab Rounding", 4.6f, 0.0f..12.0f, 0.1f) - @Tab(ROUNDING_TAB) val tabRounding by setting("Tab Rounding", 4.6f, 0.0f..12.0f, 0.1f) - @Tab(ROUNDING_TAB) val curveTessellationTol by setting("Curve Tessellation Tol", 1.25f, 0.1f..10.0f, 0.05f) - - // Font - @Tab(FONT_TAB) val fontScale by setting("Font Scale", 1.0, 0.5..2.0, 0.1) - - // Colors - @Tab(COLORS_TAB) val primaryColor by setting("Primary Color", Color(130, 200, 255)) - @Tab(COLORS_TAB) val secondaryColor by setting("Secondary Color", Color(225, 130, 225)) - - @Tab(COLORS_TAB) val text by setting("Text", Color(255, 255, 255, 255)) - @Tab(COLORS_TAB) val textDisabled by setting("Text Disabled", Color(128, 128, 128, 255)) - @Tab(COLORS_TAB) val windowBg by setting("Window Background", Color(35, 0, 14, 240)) - @Tab(COLORS_TAB) val childBg by setting("Child Background", Color(35, 0, 14, 240)) - @Tab(COLORS_TAB) val popupBg by setting("Popup Background", Color(35, 0, 14, 240)) - @Tab(COLORS_TAB) val border by setting("Border", Color(130, 12, 60, 240)) - @Tab(COLORS_TAB) val borderShadow by setting("Border Shadow", Color(51, 0, 21, 240)) - @Tab(COLORS_TAB) val frameBg by setting("Frame Background", Color(171, 32, 93, 102)) - @Tab(COLORS_TAB) val frameBgHovered by setting("Frame Background Hovered", Color(214, 45, 119, 102)) - @Tab(COLORS_TAB) val frameBgActive by setting("Frame Background Active", Color(255, 50, 140, 102)) - @Tab(COLORS_TAB) val titleBg by setting("Title Background", Color(125, 0, 50, 240)) - @Tab(COLORS_TAB) val titleBgActive by setting("Title Background Active", Color(162, 0, 68, 240)) - @Tab(COLORS_TAB) val titleBgCollapsed by setting("Title Background Collapsed", Color(35, 0, 14, 240)) - @Tab(COLORS_TAB) val menuBarBg by setting("MenuBar Background", Color(35, 0, 14, 240)) - @Tab(COLORS_TAB) val scrollbarBg by setting("Scrollbar Background", Color(35, 0, 14, 240)) - @Tab(COLORS_TAB) val scrollbarGrab by setting("Scrollbar Grab", Color(159, 30, 83, 240)) - @Tab(COLORS_TAB) val scrollbarGrabHovered by setting("Scrollbar Grab Hovered", Color(198, 40, 105, 240)) - @Tab(COLORS_TAB) val scrollbarGrabActive by setting("Scrollbar Grab Active", Color(235, 49, 126, 240)) - @Tab(COLORS_TAB) val checkMark by setting("Check Mark", Color(255, 64, 148, 220)) - @Tab(COLORS_TAB) val sliderGrab by setting("Slider Grab", Color(207, 46, 117, 200)) - @Tab(COLORS_TAB) val sliderGrabActive by setting("Slider Grab Active", Color(241, 67, 143, 200)) - @Tab(COLORS_TAB) val button by setting("Button", Color(171, 32, 93, 102)) - @Tab(COLORS_TAB) val buttonHovered by setting("Button Hovered", Color(214, 45, 119, 102)) - @Tab(COLORS_TAB) val buttonActive by setting("Button Active", Color(255, 50, 140, 102)) - @Tab(COLORS_TAB) val header by setting("Header", Color(192, 30, 94, 115)) - @Tab(COLORS_TAB) val headerHovered by setting("Header Hovered", Color(255, 59, 136, 115)) - @Tab(COLORS_TAB) val headerActive by setting("Header Active", Color(202, 36, 101, 115)) - @Tab(COLORS_TAB) val separator by setting("Separator", Color(107, 0, 47, 128)) - @Tab(COLORS_TAB) val separatorHovered by setting("Separator Hovered", Color(146, 0, 64, 128)) - @Tab(COLORS_TAB) val separatorActive by setting("Separator Active", Color(186, 0, 82, 128)) - @Tab(COLORS_TAB) val resizeGrip by setting("Resize Grip", Color(214, 45, 119, 102)) - @Tab(COLORS_TAB) val resizeGripHovered by setting("Resize Grip Hovered", Color(214, 45, 119, 102)) - @Tab(COLORS_TAB) val resizeGripActive by setting("Resize Grip Active", Color(214, 45, 119, 102)) - @Tab(COLORS_TAB) val tab by setting("Tab", Color(121, 21, 65, 140)) - @Tab(COLORS_TAB) val tabHovered by setting("Tab Hovered", Color(169, 34, 94, 140)) - @Tab(COLORS_TAB) val tabActive by setting("Tab Active", Color(209, 34, 112, 140)) - @Tab(COLORS_TAB) val tabUnfocused by setting("Tab Unfocused", Color(121, 21, 65, 120)) - @Tab(COLORS_TAB) val tabUnfocusedActive by setting("Tab Unfocused Active", Color(196, 36, 107, 120)) - @Tab(COLORS_TAB) val dockingPreview by setting("Docking Preview", Color(208, 47, 117, 102)) - @Tab(COLORS_TAB) val dockingEmptyBg by setting("Docking Empty Background", Color(35, 0, 14, 240)) - @Tab(COLORS_TAB) val plotLines by setting("Plot Lines", Color(178, 36, 95, 240)) - @Tab(COLORS_TAB) val plotLinesHovered by setting("Plot Lines Hovered", Color(209, 40, 110, 240)) - @Tab(COLORS_TAB) val plotHistogram by setting("Plot Histogram", Color(192, 32, 91, 255)) - @Tab(COLORS_TAB) val plotHistogramHovered by setting("Plot Histogram Hovered", Color(226, 38, 108, 255)) - @Tab(COLORS_TAB) val tableHeaderBg by setting("Table Header Background", Color(75, 0, 31, 240)) - @Tab(COLORS_TAB) val tableBorderStrong by setting("Table Border Strong", Color(88, 0, 36, 240)) - @Tab(COLORS_TAB) val tableBorderLight by setting("Table Border Light", Color(67, 0, 28, 240)) - @Tab(COLORS_TAB) val tableRowBg by setting("Table Row Background", Color(35, 0, 14, 240)) - @Tab(COLORS_TAB) val tableRowBgAlt by setting("Table Row Background Alt", Color(242, 140, 182, 240)) - @Tab(COLORS_TAB) val textSelectedBg by setting("Text Selected Background", Color(218, 54, 121, 240)) - @Tab(COLORS_TAB) val dragDropTarget by setting("Drag Drop Target", Color(218, 54, 121, 240)) - @Tab(COLORS_TAB) val navHighlight by setting("Nav Highlight", Color(218, 54, 121, 240)) - @Tab(COLORS_TAB) val navWindowingHighlight by setting("Nav Windowing Highlight", Color(242, 140, 182, 240)) - @Tab(COLORS_TAB) val navWindowingDimBg by setting("Nav Windowing Dim Background", Color(242, 140, 182, 240)) - @Tab(COLORS_TAB) val modalWindowDimBg by setting("Modal Window Dim Background", Color(35, 0, 14, 90)) - - init { - listenUnsafe { - if (!open) return@listenUnsafe - - buildLayout { - buildMenuBar() - val vp = ImGui.getMainViewport() - SnapHandler.beginFrame(vp.sizeX, vp.sizeY, io.fontGlobalScale) - - val mouseDown = io.mouseDown[0] - val mouseReleasedThisFrame = !mouseDown && mouseWasDown - mouseWasDown = mouseDown - - if (mouseReleasedThisFrame) { - activeDragWindowName = null - activeResizeWindowName?.let { pendingSizes.remove(it) } - activeResizeWindowName = null - } - - pendingPositions.clear() - snapOverlays.clear() - - if (mouseDown) { - activeDragWindowName?.let { name -> - lastBounds[name]?.let { bounds -> - updateDragAndSnapping( - name, bounds, dragOffsetX, dragOffsetY, pendingPositions, snapOverlays - ) - drawDragGrid() - } - } - activeResizeWindowName?.let { name -> - lastBounds[name]?.let { bounds -> - updateResizeAndSnapping(name, bounds) - drawDragGrid() - } - } - } - - val tags = if (developerMode) shownTags + ModuleTag.DEBUG else shownTags - if (tags.isEmpty()) return@buildLayout - - var nextX = 20f - val baseY = MenuBar.height + 10f - - tags.forEach { tag -> - val override = pendingPositions[tag.name] - if (override != null) { - ImGui.setNextWindowPos(override.first, override.second) - } else if (frameCount >= 1) { - ImGui.setNextWindowPos(nextX, baseY, ImGuiCond.FirstUseEver) - } - - pendingSizes[tag.name]?.let { (w, h) -> - ImGui.setNextWindowSizeConstraints(w, h, w, h) - } - - window(tag.name, flags = ImGuiWindowFlags.NoCollapse) { - ModuleRegistry.modules - .filter { it.tag == tag && it.showInClickGui.value } - .forEach { with(ModuleEntry(it)) { buildLayout() } } - - snapOverlays[tag.name]?.let { vis -> - drawSnapLines(vis.snapX, vis.kindX, vis.snapY, vis.kindY) - } - - val rect = RectF(windowPos.x, windowPos.y, windowSize.x, windowSize.y) - if (mouseDown) claimInteraction(tag.name, rect) - - SnapHandler.registerElement(tag.name, rect) - lastBounds[tag.name] = rect - - nextX += ImGui.getWindowWidth() + 20f - } - } - - if (frameCount++ == 1) { - initialLayoutComplete = true - } - - renderQuickSearch() - - if (developerMode) { - ImGui.showDemoWindow() - ImPlot.showDemoWindow() - } - } - } - } - - private fun ImGuiBuilder.claimInteraction(name: String, rect: RectF) { - if (activeDragWindowName != null || activeResizeWindowName != null) return - val previous = lastBounds[name] ?: return - - val movedX = abs(rect.x - previous.x) > 0.5f - val movedY = abs(rect.y - previous.y) > 0.5f - val sizedX = abs(rect.w - previous.w) > 0.5f - val sizedY = abs(rect.h - previous.h) > 0.5f - - when { - sizedX || sizedY -> { - val grip = ImGui.getFontSize() * 1.35f - val toLeft = io.mousePos.x - rect.left - val toRight = rect.right - io.mousePos.x - val toTop = io.mousePos.y - rect.top - val toBottom = rect.bottom - io.mousePos.y - - activeResizeWindowName = name - resizeLeftEdge = toLeft <= grip && toLeft < toRight - resizeRightEdge = toRight <= grip && toRight <= toLeft - resizeTopEdge = toTop <= grip && toTop < toBottom - resizeBottomEdge = toBottom <= grip && toBottom <= toTop - - if (sizedX && !resizeLeftEdge && !resizeRightEdge) resizeRightEdge = true - if (sizedY && !resizeTopEdge && !resizeBottomEdge) resizeBottomEdge = true - - resizeGrabOffsetX = io.mousePos.x - if (resizeLeftEdge) rect.left else rect.right - resizeGrabOffsetY = io.mousePos.y - if (resizeTopEdge) rect.top else rect.bottom - } - movedX || movedY -> { - activeDragWindowName = name - dragOffsetX = io.mousePos.x - rect.x - dragOffsetY = io.mousePos.y - rect.y - } - } - } - - private fun ImGuiBuilder.updateResizeAndSnapping(name: String, bounds: RectF) { - var x = bounds.x - var y = bounds.y - var width = bounds.w - var height = bounds.h - var snapX: Float? = null - var snapY: Float? = null - var kindX: Guide.Kind? = null - var kindY: Guide.Kind? = null - - fun snapped(offset: Float, mouse: Float, orientation: Guide.Orientation): Pair { - val proposed = mouse - offset - val snap = SnapHandler.snapEdge(proposed, orientation, name) - return (snap.pos ?: proposed) to snap.kind - } - - if (resizeLeftEdge || resizeRightEdge) { - val (edge, kind) = snapped(resizeGrabOffsetX, io.mousePos.x, Guide.Orientation.Vertical) - if (resizeLeftEdge) { - x = edge.coerceAtMost(bounds.right - style.windowMinSize.x) - width = bounds.right - x - } else { - width = (edge - bounds.left).coerceAtLeast(style.windowMinSize.x) - } - snapX = edge - kindX = kind - } - - if (resizeTopEdge || resizeBottomEdge) { - val (edge, kind) = snapped(resizeGrabOffsetY, io.mousePos.y, Guide.Orientation.Horizontal) - if (resizeTopEdge) { - y = edge.coerceAtMost(bounds.bottom - style.windowMinSize.y) - height = bounds.bottom - y - } else { - height = (edge - bounds.top).coerceAtLeast(style.windowMinSize.y) - } - snapY = edge - kindY = kind - } - - pendingSizes[name] = width to height - if (resizeLeftEdge || resizeTopEdge) pendingPositions[name] = x to y - snapOverlays[name] = SnapHandler.SnapVisual(snapX, snapY, kindX, kindY) - } - - val Screen?.hasInput: Boolean - get() = this is ChatScreen || - this is SignEditScreen || - this is AnvilScreen || - this is CommandBlockScreen - - fun toggle() { - if (open) { - LambdaScreen.close() - } else { - val current = mc.currentScreen - if (current.hasInput) return - if (Client.clientSounds) LambdaSound.ModuleOn.play() - LambdaScreen.parentScreen = if (current is LambdaScreen) null else current - (current as? OverlayBackgroundScreen)?.onOverlaidByGui() - mc.setScreen(LambdaScreen) - open = true - frameCount = 0 - initialLayoutComplete = false - } - } - - fun close() { - if (Client.clientSounds) LambdaSound.ModuleOff.play() - open = false - } - - fun applyStyle(scale: Float) { - val style = ImGui.getStyle() - - style.alpha = alpha - style.disabledAlpha = disabledAlpha - style.windowPadding.set(windowPaddingX * scale, windowPaddingY * scale) - style.windowMinSize.set(windowMinSizeX * scale, windowMinSizeY * scale) - style.windowTitleAlign.set(windowTitleAlignX, windowTitleAlignY) - style.windowRounding = windowRounding * scale - style.windowBorderSize = windowBorderSize * scale - style.childRounding = childRounding * scale - style.childBorderSize = childBorderSize * scale - style.popupRounding = popupRounding * scale - style.popupBorderSize = popupBorderSize * scale - style.framePadding.set(framePaddingX * scale, framePaddingY * scale) - style.frameRounding = frameRounding * scale - style.frameBorderSize = frameBorderSize * scale - style.itemSpacing.set(itemSpacingX * scale, itemSpacingY * scale) - style.itemInnerSpacing.set(itemInnerSpacingX * scale, itemInnerSpacingY * scale) - style.indentSpacing = indentSpacing * scale - style.scrollbarSize = scrollbarSize * scale - style.scrollbarRounding = scrollbarRounding * scale - style.grabMinSize = grabMinSize * scale - style.grabRounding = grabRounding * scale - style.tabRounding = tabRounding * scale - style.tabBorderSize = tabBorderSize * scale - style.curveTessellationTol = curveTessellationTol * scale - - setColor(ImGuiCol.Text, text) - setColor(ImGuiCol.TextDisabled, textDisabled) - setColor(ImGuiCol.WindowBg, windowBg) - setColor(ImGuiCol.ChildBg, childBg) - setColor(ImGuiCol.PopupBg, popupBg) - setColor(ImGuiCol.Border, border) - setColor(ImGuiCol.BorderShadow, borderShadow) - setColor(ImGuiCol.FrameBg, frameBg) - setColor(ImGuiCol.FrameBgHovered, frameBgHovered) - setColor(ImGuiCol.FrameBgActive, frameBgActive) - setColor(ImGuiCol.TitleBg, titleBg) - setColor(ImGuiCol.TitleBgActive, titleBgActive) - setColor(ImGuiCol.TitleBgCollapsed, titleBgCollapsed) - setColor(ImGuiCol.MenuBarBg, menuBarBg) - setColor(ImGuiCol.ScrollbarBg, scrollbarBg) - setColor(ImGuiCol.ScrollbarGrab, scrollbarGrab) - setColor(ImGuiCol.ScrollbarGrabHovered, scrollbarGrabHovered) - setColor(ImGuiCol.ScrollbarGrabActive, scrollbarGrabActive) - setColor(ImGuiCol.CheckMark, checkMark) - setColor(ImGuiCol.SliderGrab, sliderGrab) - setColor(ImGuiCol.SliderGrabActive, sliderGrabActive) - setColor(ImGuiCol.Button, button) - setColor(ImGuiCol.ButtonHovered, buttonHovered) - setColor(ImGuiCol.ButtonActive, buttonActive) - setColor(ImGuiCol.Header, header) - setColor(ImGuiCol.HeaderHovered, headerHovered) - setColor(ImGuiCol.HeaderActive, headerActive) - setColor(ImGuiCol.Separator, separator) - setColor(ImGuiCol.SeparatorHovered, separatorHovered) - setColor(ImGuiCol.SeparatorActive, separatorActive) - setColor(ImGuiCol.ResizeGrip, resizeGrip) - setColor(ImGuiCol.ResizeGripHovered, resizeGripHovered) - setColor(ImGuiCol.ResizeGripActive, resizeGripActive) - setColor(ImGuiCol.Tab, tab) - setColor(ImGuiCol.TabHovered, tabHovered) - setColor(ImGuiCol.TabActive, tabActive) - setColor(ImGuiCol.TabUnfocused, tabUnfocused) - setColor(ImGuiCol.TabUnfocusedActive, tabUnfocusedActive) - setColor(ImGuiCol.DockingPreview, dockingPreview) - setColor(ImGuiCol.DockingEmptyBg, dockingEmptyBg) - setColor(ImGuiCol.PlotLines, plotLines) - setColor(ImGuiCol.PlotLinesHovered, plotLinesHovered) - setColor(ImGuiCol.PlotHistogram, plotHistogram) - setColor(ImGuiCol.PlotHistogramHovered, plotHistogramHovered) - setColor(ImGuiCol.TableHeaderBg, tableHeaderBg) - setColor(ImGuiCol.TableBorderStrong, tableBorderStrong) - setColor(ImGuiCol.TableBorderLight, tableBorderLight) - setColor(ImGuiCol.TableRowBg, tableRowBg) - setColor(ImGuiCol.TableRowBgAlt, tableRowBgAlt) - setColor(ImGuiCol.TextSelectedBg, textSelectedBg) - setColor(ImGuiCol.DragDropTarget, dragDropTarget) - setColor(ImGuiCol.NavHighlight, navHighlight) - setColor(ImGuiCol.NavWindowingHighlight, navWindowingHighlight) - setColor(ImGuiCol.NavWindowingDimBg, navWindowingDimBg) - setColor(ImGuiCol.ModalWindowDimBg, modalWindowDimBg) - } - - private fun setColor(imGuiCol: Int, color: Color) { - val style = ImGui.getStyle() - val comp = color.getRGBComponents(null) - style.setColor(imGuiCol, comp[0], comp[1], comp[2], comp[3]) - } -} diff --git a/src/main/kotlin/com/lambda/gui/components/HudGuiLayout.kt b/src/main/kotlin/com/lambda/gui/components/HudGuiLayout.kt deleted file mode 100644 index 908805e6f..000000000 --- a/src/main/kotlin/com/lambda/gui/components/HudGuiLayout.kt +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui.components - -import com.lambda.config.Config -import com.lambda.config.categories.HudCategory -import com.lambda.core.Loadable -import com.lambda.event.events.GuiEvent -import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.components.SettingsWidget.buildConfigSettingsContext -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.gui.dsl.ImGuiBuilder.buildLayout -import com.lambda.gui.snap.RectF -import com.lambda.gui.snap.SnapHandler -import com.lambda.gui.snap.SnapHandler.drawDragGrid -import com.lambda.gui.snap.SnapHandler.drawSnapLines -import com.lambda.gui.snap.SnapHandler.updateDragAndSnapping -import com.lambda.imgui.ImColor -import com.lambda.imgui.ImDrawList -import com.lambda.imgui.ImGui -import com.lambda.imgui.flag.ImDrawListFlags -import com.lambda.imgui.flag.ImGuiCol -import com.lambda.imgui.flag.ImGuiStyleVar -import com.lambda.imgui.flag.ImGuiWindowFlags -import com.lambda.module.HudModule -import com.lambda.module.ModuleRegistry -import java.awt.Color -import kotlin.math.PI - -object HudGuiLayout : Loadable, Config( - "HUD", - HudCategory -) { - val showInScreens by setting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The Lambda GUI always shows them.") - - // HUD Outline - val hudOutlineCornerRadius by setting("HUD Corner Radius", 6.0f, 0.5f..24.0f, 0.5f) - val hudOutlineHaloColor by setting("HUD Corner Halo Color", Color(140, 140, 140, 90)) - val hudOutlineBorderColor by setting("HUD Corner Border Color", Color(190, 190, 190, 200)) - val hudOutlineHaloThickness by setting("HUD Corner Halo Thickness", 3.0f, 1.0f..6.0f, 0.5f) - val hudOutlineBorderThickness by setting("HUD Corner Border Thickness", 1.5f, 1.0f..4.0f, 0.5f) - val hudOutlineCornerInflate by setting("HUD Corner Inflate", 1.0f, 0.0f..4.0f, 0.5f, "Extra radius for the halo arc") - - const val DEFAULT_HUD_FLAGS = - ImGuiWindowFlags.NoDecoration or - ImGuiWindowFlags.NoBackground or - ImGuiWindowFlags.AlwaysAutoResize or - ImGuiWindowFlags.NoDocking - private var activeDragHudName: String? = null - private var mouseWasDown = false - private var dragOffsetX = 0f - private var dragOffsetY = 0f - private val lastBounds = mutableMapOf() - private val pendingPositions = mutableMapOf>() - private val snapOverlays = mutableMapOf() - private var mousePressedThisFrameGlobal = false - - var isShownInGUI = true - var isLocked = false - - private const val PI_F = PI.toFloat() - private const val HALF_PI_F = (0.5f * PI).toFloat() - private const val THREE_HALVES_PI_F = (1.5f * PI).toFloat() - private const val TWO_PI_F = (2f * PI).toFloat() - - init { - listen { - if (mc.options.hudHidden) return@listen - if (!ClickGuiLayout.open && mc.currentScreen != null && !showInScreens) return@listen - - buildLayout { - if (ClickGuiLayout.open && !isShownInGUI) { - popupContextVoid("##hud-background") { - menuItem(if (isShownInGUI) "Hide HUD" else "Show HUD") { - isShownInGUI = !isShownInGUI - } - separator() - menu("HUD Settings") { - buildConfigSettingsContext(this@HudGuiLayout) - } - menu("GUI Settings") { - buildConfigSettingsContext(ClickGuiLayout) - } - } - return@buildLayout - } - - val mouseDown = io.mouseDown[0] - val mousePressedThisFrame = mouseDown && !mouseWasDown - val mouseReleasedThisFrame = !mouseDown && mouseWasDown - mouseWasDown = mouseDown - mousePressedThisFrameGlobal = mousePressedThisFrame - - if (mouseReleasedThisFrame || !ClickGuiLayout.open || isLocked) { - activeDragHudName = null - } - - pendingPositions.clear() - snapOverlays.clear() - - val (huds, notShown) = ModuleRegistry.modules - .filterIsInstance() - .partition { it.isEnabled } - notShown.forEach { SnapHandler.unregisterElement(it.name) } - - if (ClickGuiLayout.open) { - registerContextMenu(notShown) - - if (!isLocked) { - activeDragHudName?.let { drag -> - lastBounds[drag]?.let { bounds -> - if (mouseDown) updateDragAndSnapping( - drag, bounds, dragOffsetX, dragOffsetY, pendingPositions, snapOverlays - ) - } - drawDragGrid() - } - } - } - - huds.forEach { hud -> - registerHudElement(hud) - } - } - } - } - - private fun ImGuiBuilder.registerHudElement(hud: HudModule) { - val override = pendingPositions[hud.name] - if (override != null) { - ImGui.setNextWindowPos(override.first, override.second) - } - - val bg = hud.backgroundColor.value - val hasBg = bg.alpha > 0 - val baseFlags = if (hasBg) { - DEFAULT_HUD_FLAGS and ImGuiWindowFlags.NoBackground.inv() - } else DEFAULT_HUD_FLAGS - var hudFlags = if (!ClickGuiLayout.open || isLocked) { - baseFlags or ImGuiWindowFlags.NoMove - } else baseFlags - if (!ClickGuiLayout.open) hudFlags = hudFlags or ImGuiWindowFlags.NoInputs - - val pushedColor = if (hasBg) { - val packed = ImColor.rgba(bg.red, bg.green, bg.blue, bg.alpha) - ImGui.pushStyleColor(ImGuiCol.WindowBg, packed) - true - } else false - - withStyleVar(ImGuiStyleVar.WindowBorderSize, 0f) { - window("##${hud.name}", flags = hudFlags) { - if (ClickGuiLayout.open && !isLocked && activeDragHudName == null && mousePressedThisFrameGlobal && ImGui.isWindowHovered()) { - val mx = io.mousePos.x - val my = io.mousePos.y - activeDragHudName = hud.name - dragOffsetX = mx - windowPos.x - dragOffsetY = my - windowPos.y - } - - snapOverlays[hud.name]?.let { visual -> - drawSnapLines(visual.snapX, visual.kindX, visual.snapY, visual.kindY) - } - with(hud) { buildLayout() } - - if (ClickGuiLayout.open) { - popupContextWindow("##ctx-${hud.name}") { - menuItem("Remove HUD Element") { - hud.disable() - SnapHandler.unregisterElement(hud.name) - } - separator() - buildConfigSettingsContext(hud) - } - - if (!isLocked) drawHudCornerArcs(windowDrawList, windowPos.x, windowPos.y, windowSize.x, windowSize.y) - } - val rect = RectF(windowPos.x, windowPos.y, windowSize.x, windowSize.y) - SnapHandler.registerElement(hud.name, rect) - lastBounds[hud.name] = rect - } - } - - if (pushedColor) { - ImGui.popStyleColor() - } - } - - private fun ImGuiBuilder.registerContextMenu(notShown: List) { - popupContextVoid("##hud-background") { - menuItem(if (isLocked) "Unlock HUD" else "Lock HUD") { - isLocked = !isLocked - } - menuItem(if (isShownInGUI) "Hide HUD" else "Show HUD") { - isShownInGUI = !isShownInGUI - } - separator() - if (notShown.isEmpty()) { - textDisabled("No hidden HUD elements") - } else { - menu("Add HUD Element") { - notShown.sortedBy { it.name.lowercase() }.forEach { hud -> - menuItem("+ ${hud.name}") { - val mx = io.mousePos.x - val my = io.mousePos.y - hud.enable() - pendingPositions[hud.name] = mx to my - } - } - } - } - separator() - menu("HUD Settings") { - buildConfigSettingsContext(this@HudGuiLayout) - } - menu("GUI Settings") { - buildConfigSettingsContext(ClickGuiLayout) - } - } - } - - private fun ImGuiBuilder.drawHudCornerArcs(draw: ImDrawList, x: Float, y: Float, w: Float, h: Float) { - val baseRadius = hudOutlineCornerRadius - val rounding = if (baseRadius > 0f) baseRadius else style.windowRounding - val inflate = hudOutlineCornerInflate - - draw.pushClipRectFullScreen() - - val haloRadius = (rounding + inflate + 0.5f * hudOutlineHaloThickness + 1.0f).coerceAtLeast(0f) - val borderRadius = (rounding + 0.5f * hudOutlineBorderThickness + 0.75f).coerceAtLeast(0f) - - drawCornerArcs( - draw, - x, y, w, h, - haloRadius, - awtToImColor(hudOutlineHaloColor), - hudOutlineHaloThickness - ) - drawCornerArcs( - draw, - x, y, w, h, - borderRadius, - awtToImColor(hudOutlineBorderColor), - hudOutlineBorderThickness - ) - - draw.popClipRect() - } - - private fun awtToImColor(c: Color) = ImColor.rgba(c.red, c.green, c.blue, c.alpha) - - private fun drawCornerArcs( - draw: ImDrawList, - x: Float, y: Float, w: Float, h: Float, - radius: Float, - color: Int, - thickness: Float - ) { - if (radius <= 0f || thickness <= 0f) return - val tlCx = x + radius - val tlCy = y + radius - val trCx = x + w - radius - val trCy = y + radius - val brCx = x + w - radius - val brCy = y + h - radius - val blCx = x + radius - val blCy = y + h - radius - - fun strokeArc(cx: Float, cy: Float, start: Float, end: Float) { - draw.pathClear() - draw.pathArcTo(cx, cy, radius, start, end, 0) - draw.pathStroke(color, ImDrawListFlags.None, thickness) - } - - // TL: pi -> 1.5pi - strokeArc(tlCx, tlCy, PI_F, THREE_HALVES_PI_F) - // TR: 1.5pi -> 2pi - strokeArc(trCx, trCy, THREE_HALVES_PI_F, TWO_PI_F) - // BR: 0 -> 0.5pi - strokeArc(brCx, brCy, 0f, HALF_PI_F) - // BL: 0.5pi -> pi - strokeArc(blCx, blCy, HALF_PI_F, PI_F) - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/gui/components/ModuleEntry.kt b/src/main/kotlin/com/lambda/gui/components/ModuleEntry.kt deleted file mode 100644 index 7c73ae9ab..000000000 --- a/src/main/kotlin/com/lambda/gui/components/ModuleEntry.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui.components - -import com.lambda.gui.Layout -import com.lambda.gui.components.SettingsWidget.buildConfigSettingsContext -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImGui -import com.lambda.imgui.flag.ImGuiHoveredFlags -import com.lambda.imgui.flag.ImGuiPopupFlags -import com.lambda.module.Module - -class ModuleEntry(val module: Module): Layout { - override fun ImGuiBuilder.buildLayout() { - selectable(module.name, selected = module.isEnabled) { - module.toggle() - } - lambdaTooltip(module.description) - - val popupId = "##ctx-${module.name}" - val entryId = getId(popupId) - - onItemHover(ImGuiHoveredFlags.AllowWhenBlockedByPopup) { - if (isMouseClicked() && isPopupOpen(popupId)) suppressedEntryId = entryId - if (isMouseReleased() && suppressedEntryId != entryId) openPopup(popupId) - } - - if (isMouseReleased() && suppressedEntryId == entryId) suppressedEntryId = null - - ImGui.setNextWindowSizeConstraints(0f, 0f, Float.MAX_VALUE, io.displaySize.y * 0.5f) - popupContextItem(popupId, ImGuiPopupFlags.MouseButtonRight) { - buildConfigSettingsContext(module) - } - } - - private companion object { - /** Entry whose reopen is pending suppression; only one item can be pressed at a time. */ - var suppressedEntryId: Int? = null - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/gui/components/QuickSearch.kt b/src/main/kotlin/com/lambda/gui/components/QuickSearch.kt deleted file mode 100644 index e21cec084..000000000 --- a/src/main/kotlin/com/lambda/gui/components/QuickSearch.kt +++ /dev/null @@ -1,342 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui.components - -import com.lambda.Lambda.mc -import com.lambda.command.CommandRegistry -import com.lambda.command.LambdaCommand -import com.lambda.config.Config -import com.lambda.config.ConfigLoader -import com.lambda.config.entries.Setting -import com.lambda.event.events.ButtonEvent -import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe -import com.lambda.gui.LambdaScreen -import com.lambda.gui.Layout -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImGui -import com.lambda.imgui.flag.ImGuiHoveredFlags -import com.lambda.imgui.flag.ImGuiInputTextFlags -import com.lambda.imgui.flag.ImGuiMouseButton -import com.lambda.imgui.flag.ImGuiStyleVar -import com.lambda.imgui.flag.ImGuiWindowFlags -import com.lambda.imgui.type.ImString -import com.lambda.module.HudModule -import com.lambda.module.Module -import com.lambda.module.ModuleRegistry -import com.lambda.module.modules.client.AutoUpdater -import com.lambda.util.KeyCode -import com.lambda.util.StringUtils.capitalize -import com.lambda.util.StringUtils.levenshteinDistance -import net.minecraft.client.gui.screen.ChatScreen -import kotlin.math.max - -// ToDo: Add support for searching of menu bar entries -@Suppress("unused") -object QuickSearch { - private val searchInput = ImString(256) - var isOpen = false - private set - private var shouldFocus = false - private var pendingClose = false - private var lastShiftPressTime = 0L - private var lastShiftKeyCode = -1 - - private const val DOUBLE_SHIFT_WINDOW_MS = 500L - private const val MAX_RESULTS = 50 - private const val POPUP_ID = "QuickSearch" - const val WINDOW_FLAGS = - ImGuiWindowFlags.AlwaysAutoResize or - ImGuiWindowFlags.NoTitleBar or - ImGuiWindowFlags.NoMove or - ImGuiWindowFlags.NoResize or - ImGuiWindowFlags.NoScrollbar or - ImGuiWindowFlags.NoScrollWithMouse - - init { - listenUnsafe { event -> - if (mc.currentScreen !is LambdaScreen) return@listenUnsafe - handleKeyPress(event) - } - } - - interface SearchResult : Layout { - val breadcrumb: String - } - - private class ModuleResult(val module: Module) : SearchResult { - override val breadcrumb = if (module is HudModule) "HUD" else "Module" - - override fun ImGuiBuilder.buildLayout() { - with(ModuleEntry(module)) { - buildLayout { - withItemWidth(ImGui.getContentRegionAvailX()) { - buildLayout() - } - } - } - } - } - - private class CommandResult(val command: LambdaCommand) : SearchResult { - override val breadcrumb = "Command" - override fun ImGuiBuilder.buildLayout() { - text(command.name.capitalize()) - sameLine() - smallButton("Insert") { mc.setScreen(ChatScreen("${CommandRegistry.prefix}${command.name} ", true)) } - if (command.description.isNotBlank()) { - sameLine() - textDisabled(command.description) - } - } - } - - private class SettingResult(val setting: Setting<*>, val config: Config) : SearchResult { - override val breadcrumb: String by lazy { buildSettingBreadcrumb(config.name, setting) } - - override fun ImGuiBuilder.buildLayout() { - with(setting) { - buildLayout { - withItemWidth(ImGui.getContentRegionAvailX()) { - buildLayout() - } - } - } - } - } - - fun open() { - isOpen = true - shouldFocus = true - pendingClose = false - searchInput.clear() - } - - fun close() { - isOpen = false - shouldFocus = false - pendingClose = true - } - - fun toggle() { - if (isOpen) close() else open() - } - - fun ImGuiBuilder.renderQuickSearch() { - if (!isOpen && !pendingClose) return - if (isOpen) openPopup(POPUP_ID) - - ImGui.setNextFrameWantCaptureKeyboard(true) - - val maxW = io.displaySize.x * 0.5f - val maxH = io.displaySize.y * 0.5f - - val popupX = (io.displaySize.x - maxW) * 0.5f - val popupY = io.displaySize.y * 0.3f - ImGui.setNextWindowPos(popupX, popupY) - ImGui.setNextWindowSize(maxW, 0f) - ImGui.setNextWindowSizeConstraints(0f, 0f, maxW, maxH) - - popupModal(POPUP_ID, WINDOW_FLAGS) { - if (pendingClose) { - pendingClose = false - closeCurrentPopup() - return@popupModal - } - - if (isMouseClicked(ImGuiMouseButton.Left) && !isWindowHovered(ImGuiHoveredFlags.RootAndChildWindows)) { - close() - return@popupModal - } - - if (shouldFocus) { - ImGui.setKeyboardFocusHere() - shouldFocus = false - } - - withItemWidth(ImGui.getContentRegionAvailX()) { - withStyleVar(ImGuiStyleVar.FramePadding, style.framePadding.x, style.framePadding.y) { - ImGui.inputTextWithHint( - "##qs-input", - "Type to search modules, settings, and commands...", - searchInput, - ImGuiInputTextFlags.AutoSelectAll - ) - } - } - - val query = searchInput.get().trim() - if (query.isEmpty()) return@popupModal - - val results = SearchService.performSearch(query) - if (results.isEmpty()) { - textDisabled("Nothing found.") - return@popupModal - } - - val rowH = frameHeightWithSpacing - val topArea = cursorPosY + style.windowPadding.y - val listH = (results.size * rowH).coerceAtMost(maxH - topArea).coerceAtLeast(rowH) - - child("qs_rows", 0f, listH, false) { - results.forEachIndexed { idx, result -> - withId(idx) { - with(result) { - if (breadcrumb.isNotBlank()) { - textDisabled(breadcrumb) - sameLine() - } - buildLayout() - } - } - } - } - } - } - - private object SearchService { - private data class RankedSearchResult(val result: SearchResult, val score: Int) - - private const val MODULE_PRIORITY_BONUS = 300 - private const val HUD_MODULE_PRIORITY_BONUS = 270 - private const val COMMAND_PRIORITY_BONUS = 200 - - /** - * Calculates a relevance score for a query against a target string. - * Returns 0 for no match. Higher scores are better. - * The `lenient` flag adjusts the threshold for fuzzy matching. - */ - private fun calculateScore(query: String, target: String, lenient: Boolean = false): Int { - if (query.isEmpty() || target.isEmpty()) return 0 - - // 1. Strong Matches (Exact, Prefix, Substring) - if (target == query) return 200 - if (target.startsWith(query)) { - val completeness = (query.length * 50) / target.length - return 100 + completeness // Score: 101 - 150 - } - if (target.contains(query)) { - val completeness = (query.length * 40) / target.length - return 50 + completeness // Score: 51 - 90 - } - - // 2. Weak Match (Fuzzy) - val distance = query.levenshteinDistance(target) - val strictThreshold = (query.length / 3).coerceAtLeast(1).coerceAtMost(4) - val lenientThreshold = (query.length / 2).coerceAtLeast(2).coerceAtMost(6) - val threshold = if (lenient) lenientThreshold else strictThreshold - - return if (distance <= threshold) { - (50 - (distance * 10)).coerceAtLeast(1) // Score: 1-40 - } else { - 0 - } - } - - /** - * Performs a search and returns a list of ranked results. This is the internal - * implementation that can be run in strict or lenient mode. - */ - private fun searchInternal(query: String, lenient: Boolean): List { - val lowerCaseQuery = query.lowercase() - - val moduleResults = ModuleRegistry.modules.mapNotNull { module -> - val nameScore = calculateScore(lowerCaseQuery, module.name.lowercase(), lenient) - val tagScore = calculateScore(lowerCaseQuery, module.tag.name.lowercase(), lenient) - val bestScore = max(nameScore, tagScore) - - if (bestScore > 0) { - when(module) { - is HudModule -> RankedSearchResult(ModuleResult(module), bestScore + HUD_MODULE_PRIORITY_BONUS) - else -> RankedSearchResult(ModuleResult(module), bestScore + MODULE_PRIORITY_BONUS) - } - } else null - } - - val commandResults = CommandRegistry.commands.mapNotNull { command -> - val nameScore = calculateScore(lowerCaseQuery, command.name.lowercase(), lenient) - val aliasScore = command.aliases.maxOfOrNull { calculateScore(lowerCaseQuery, it.lowercase(), lenient) } ?: 0 - val bestScore = max(nameScore, aliasScore) - - if (bestScore > 0) { - RankedSearchResult(CommandResult(command), bestScore + COMMAND_PRIORITY_BONUS) - } else null - } - - val settingResults = buildList { - ConfigLoader.configCategories.forEach { category -> - category.configs.forEach { config -> - config.settingLayers.forEachEntry { _, single -> - val setting = single.entry - if (setting.visibility()) { - val score = calculateScore(lowerCaseQuery, setting.name.lowercase(), lenient) - if (score > 0) add(RankedSearchResult(SettingResult(setting, config), score)) - } - } - } - } - } - - return moduleResults + commandResults + settingResults - } - - /** - * Main search entry point. It first attempts a strict search. If no results - * are found, it falls back to a more lenient fuzzy search. - */ - fun performSearch(query: String): List { - // First pass: strict search for high-quality matches. - val strictResults = searchInternal(query, lenient = false) - if (strictResults.isNotEmpty()) { - return strictResults - .sortedByDescending { it.score } - .map { it.result } - .take(MAX_RESULTS) - } - - // Second pass: if nothing was found, perform a more generous fuzzy search. - return searchInternal(query, lenient = true) - .sortedByDescending { it.score } - .map { it.result } - .take(MAX_RESULTS) - } - } - - private fun buildSettingBreadcrumb(configName: String, setting: Setting<*>): String { - val path = setting.getConfigCommandPath() - return if (path.isEmpty()) configName - else "$configName » ${path.joinToString(" » ")}" - } - - private fun handleKeyPress(event: ButtonEvent.Keyboard.Press) { - if (AutoUpdater.showInstallModal || AutoUpdater.showUninstallModal) return - if ((!event.isPressed || event.isRepeated) || - !(event.keyCode == KeyCode.LeftShift.code || event.keyCode == KeyCode.RightShift.code)) return - - val currentTime = System.currentTimeMillis() - if (lastShiftKeyCode == event.keyCode && - currentTime - lastShiftPressTime <= DOUBLE_SHIFT_WINDOW_MS - ) { - toggle() - lastShiftPressTime = 0L - lastShiftKeyCode = -1 - } else { - lastShiftPressTime = currentTime - lastShiftKeyCode = event.keyCode - } - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/gui/components/SettingsWidget.kt b/src/main/kotlin/com/lambda/gui/components/SettingsWidget.kt deleted file mode 100644 index 99816455f..000000000 --- a/src/main/kotlin/com/lambda/gui/components/SettingsWidget.kt +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui.components - -import com.lambda.config.Config -import com.lambda.config.EntryLayer -import com.lambda.config.automation.AutomationConfig -import com.lambda.config.automation.IMutableAutomationConfig -import com.lambda.config.automation.UserAutomationConfig -import com.lambda.config.categories.UserAutomationCategory -import com.lambda.config.entries.Setting -import com.lambda.config.entries.SettingEntryLayer -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImGui -import com.lambda.imgui.flag.ImGuiPopupFlags -import com.lambda.imgui.flag.ImGuiTabBarFlags -import com.lambda.module.HudModule -import com.lambda.module.Module -import com.lambda.module.modules.client.AutoUpdater - -object SettingsWidget { - /** - * Builds the settings context popup content for the given config. - */ - fun ImGuiBuilder.buildConfigSettingsContext(config: Config) { - group { - if (config is Module && config != AutoUpdater) { - button("Module Settings") { - ImGui.openPopup("##module-settings-popup-${config.name}") - } - lambdaTooltip("General module settings") - ImGui.setNextWindowSizeConstraints(0f, 0f, Float.MAX_VALUE, io.displaySize.y * 0.5f) - popupContextItem("##module-settings-popup-${config.name}", ImGuiPopupFlags.None) { - with(config.keybindSetting) { buildLayout() } - with(config.prioritySetting) { buildLayout() } - with(config.disableOnReleaseSetting) { buildLayout() } - with(config.drawSetting) { buildLayout() } - if (config is HudModule) { - with(config.backgroundColor) { buildLayout() } - } - smallButton("Reset") { - config.resetSettings() - } - lambdaTooltip("Resets all settings for this module to their default values") - } - } - if (config is IMutableAutomationConfig && config.automationConfig !== AutomationConfig.DEFAULT) { - button("Automation Config") { - ImGui.openPopup("##automation-config-popup-${config.name}") - } - if (config.backingAutomationConfig !== config.defaultAutomationConfig) { - sameLine() - text("(${config.backingAutomationConfig.name})") - } - ImGui.setNextWindowSizeConstraints(0f, 0f, Float.MAX_VALUE, io.displaySize.y * 0.5f) - popupContextItem("##automation-config-popup-${config.name}", ImGuiPopupFlags.None) { - combo("##LinkedConfig", preview = "Linked Config: ${config.backingAutomationConfig.name}") { - val addItem: (Config) -> Unit = { item -> - val selected = item === config.backingAutomationConfig - - selectable(item.name, selected) { - if (!selected) { - (config.backingAutomationConfig as? UserAutomationConfig)?.linkedModules?.value?.remove(config.name) - (item as? UserAutomationConfig)?.linkedModules?.value?.add(config.name) - config.automationConfig = item as? AutomationConfig ?: return@selectable - } - } - } - addItem(config.defaultAutomationConfig) - UserAutomationCategory.configs.forEach { addItem(it) } - } - buildConfigSettingsContext(config.automationConfig) - } - } - } - - if (!hasVisibleSettings(config.settingLayers)) return - separator() - drawLayers(config.settingLayers, config.name) - } - - private fun ImGuiBuilder.drawLayers(root: EntryLayer.Multiple>, idPrefix: String) { - var tabsDrawn = false - - root.layers.forEach { layer -> - when (layer) { - is EntryLayer.Single> -> drawSetting(layer.entry) - is EntryLayer.Group -> { - if (hasVisibleSettings(layer)) { - treeNode("${layer.name}##$idPrefix-group-${layer.name}") { - drawLayers(layer, "$idPrefix-${layer.name}") - } - } - } - is EntryLayer.Tab -> { - if (!tabsDrawn) { - tabsDrawn = true - val allTabs = root.layers - .filterIsInstance>>() - .filter { hasVisibleSettings(it) } - if (allTabs.isNotEmpty()) { - tabBar("##$idPrefix-tabs", ImGuiTabBarFlags.FittingPolicyResizeDown) { - allTabs.forEach { tab -> - tabItem(tab.name) { - drawLayers(tab, "$idPrefix-${tab.name}") - } - } - } - } - } - } - else -> {} - } - } - } - - private fun ImGuiBuilder.drawSetting(setting: Setting<*>) { - if (!setting.visibility()) return - if (setting.disabled()) ImGui.beginDisabled() - with(setting) { buildLayout() } - if (setting.disabled()) ImGui.endDisabled() - } - - private fun hasVisibleSettings(layer: EntryLayer.Multiple>): Boolean = - layer.layers.any { layer -> - when (layer) { - is SettingEntryLayer<*, *> -> layer.entry.visibility() - is EntryLayer.Multiple> -> hasVisibleSettings(layer) - else -> false - } - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt b/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt new file mode 100644 index 000000000..d44d114e7 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt @@ -0,0 +1,40 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.lambda.event.EventFlow.post +import com.lambda.event.events.ComposeEvent + +internal class ComposeSlot(private val event: () -> ComposeEvent) { + private var contents by mutableStateOf(emptyList<@Composable () -> Unit>()) + val isEmpty get() = contents.isEmpty() + + fun collect(active: Boolean = true) { + val collected = + if (active) event().post().contents + else emptyList() + if (collected != contents) contents = collected + } + + @Composable + fun Content() = contents.forEach { it() } +} diff --git a/src/main/kotlin/com/lambda/gui/Layout.kt b/src/main/kotlin/com/lambda/gui/core/Frames.kt similarity index 75% rename from src/main/kotlin/com/lambda/gui/Layout.kt rename to src/main/kotlin/com/lambda/gui/core/Frames.kt index 3a6562db9..dcb2c69f5 100644 --- a/src/main/kotlin/com/lambda/gui/Layout.kt +++ b/src/main/kotlin/com/lambda/gui/core/Frames.kt @@ -15,10 +15,11 @@ * along with this program. If not, see . */ -package com.lambda.gui +package com.lambda.gui.core -import com.lambda.gui.dsl.ImGuiBuilder +import androidx.compose.runtime.withFrameNanos -interface Layout { - fun ImGuiBuilder.buildLayout() -} \ No newline at end of file +suspend fun awaitFrames(millis: Long) { + val start = withFrameNanos { it } + while (withFrameNanos { it } - start < millis * 1_000_000) Unit +} diff --git a/src/main/kotlin/com/lambda/gui/core/GlState.kt b/src/main/kotlin/com/lambda/gui/core/GlState.kt new file mode 100644 index 000000000..ef8382c87 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/GlState.kt @@ -0,0 +1,198 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import org.lwjgl.opengl.GL11.GL_BLEND +import org.lwjgl.opengl.GL11.GL_COLOR_WRITEMASK +import org.lwjgl.opengl.GL11.GL_CULL_FACE +import org.lwjgl.opengl.GL11.GL_DEPTH_TEST +import org.lwjgl.opengl.GL11.GL_DEPTH_WRITEMASK +import org.lwjgl.opengl.GL11.GL_SCISSOR_BOX +import org.lwjgl.opengl.GL11.GL_SCISSOR_TEST +import org.lwjgl.opengl.GL11.GL_STENCIL_TEST +import org.lwjgl.opengl.GL11.GL_TEXTURE_2D +import org.lwjgl.opengl.GL11.GL_TEXTURE_BINDING_2D +import org.lwjgl.opengl.GL11.GL_UNPACK_ALIGNMENT +import org.lwjgl.opengl.GL11.GL_UNPACK_LSB_FIRST +import org.lwjgl.opengl.GL11.GL_UNPACK_ROW_LENGTH +import org.lwjgl.opengl.GL11.GL_UNPACK_SKIP_PIXELS +import org.lwjgl.opengl.GL11.GL_UNPACK_SKIP_ROWS +import org.lwjgl.opengl.GL11.GL_UNPACK_SWAP_BYTES +import org.lwjgl.opengl.GL11.GL_VIEWPORT +import org.lwjgl.opengl.GL11.glBindTexture +import org.lwjgl.opengl.GL11.glColorMask +import org.lwjgl.opengl.GL11.glDepthMask +import org.lwjgl.opengl.GL11.glDisable +import org.lwjgl.opengl.GL11.glEnable +import org.lwjgl.opengl.GL11.glGetBoolean +import org.lwjgl.opengl.GL11.glGetBooleanv +import org.lwjgl.opengl.GL11.glGetInteger +import org.lwjgl.opengl.GL11.glGetIntegerv +import org.lwjgl.opengl.GL11.glIsEnabled +import org.lwjgl.opengl.GL11.glPixelStorei +import org.lwjgl.opengl.GL11.glScissor +import org.lwjgl.opengl.GL11.glViewport +import org.lwjgl.opengl.GL12.GL_UNPACK_IMAGE_HEIGHT +import org.lwjgl.opengl.GL12.GL_UNPACK_SKIP_IMAGES +import org.lwjgl.opengl.GL13.GL_ACTIVE_TEXTURE +import org.lwjgl.opengl.GL13.GL_TEXTURE0 +import org.lwjgl.opengl.GL13.glActiveTexture +import org.lwjgl.opengl.GL14.GL_BLEND_DST_ALPHA +import org.lwjgl.opengl.GL14.GL_BLEND_DST_RGB +import org.lwjgl.opengl.GL14.GL_BLEND_SRC_ALPHA +import org.lwjgl.opengl.GL14.GL_BLEND_SRC_RGB +import org.lwjgl.opengl.GL14.glBlendFuncSeparate +import org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER +import org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER_BINDING +import org.lwjgl.opengl.GL15.glBindBuffer +import org.lwjgl.opengl.GL20.GL_BLEND_EQUATION_ALPHA +import org.lwjgl.opengl.GL20.GL_BLEND_EQUATION_RGB +import org.lwjgl.opengl.GL20.GL_CURRENT_PROGRAM +import org.lwjgl.opengl.GL20.glBlendEquationSeparate +import org.lwjgl.opengl.GL20.glUseProgram +import org.lwjgl.opengl.GL21.GL_PIXEL_PACK_BUFFER +import org.lwjgl.opengl.GL21.GL_PIXEL_PACK_BUFFER_BINDING +import org.lwjgl.opengl.GL21.GL_PIXEL_UNPACK_BUFFER +import org.lwjgl.opengl.GL21.GL_PIXEL_UNPACK_BUFFER_BINDING +import org.lwjgl.opengl.GL30.GL_DRAW_FRAMEBUFFER +import org.lwjgl.opengl.GL30.GL_DRAW_FRAMEBUFFER_BINDING +import org.lwjgl.opengl.GL30.GL_READ_FRAMEBUFFER +import org.lwjgl.opengl.GL30.GL_READ_FRAMEBUFFER_BINDING +import org.lwjgl.opengl.GL30.GL_VERTEX_ARRAY_BINDING +import org.lwjgl.opengl.GL30.glBindFramebuffer +import org.lwjgl.opengl.GL30.glBindVertexArray +import org.lwjgl.opengl.GL33.GL_SAMPLER_BINDING +import org.lwjgl.opengl.GL33.glBindSampler +import org.lwjgl.system.MemoryStack + +internal object GlState { + private const val TEXTURE_UNITS = 12 + + private val UNPACK_PARAMETERS = + intArrayOf( + GL_UNPACK_SWAP_BYTES, + GL_UNPACK_LSB_FIRST, + GL_UNPACK_ROW_LENGTH, + GL_UNPACK_IMAGE_HEIGHT, + GL_UNPACK_SKIP_ROWS, + GL_UNPACK_SKIP_PIXELS, + GL_UNPACK_SKIP_IMAGES, + GL_UNPACK_ALIGNMENT + ) + private val UNPACK_DEFAULTS = intArrayOf(0, 0, 0, 0, 0, 0, 0, 4) + private val CAPABILITIES = + intArrayOf( + GL_BLEND, + GL_CULL_FACE, + GL_DEPTH_TEST, + GL_STENCIL_TEST, + GL_SCISSOR_TEST + ) + + private val textures = IntArray(TEXTURE_UNITS) + private val samplers = IntArray(TEXTURE_UNITS) + private val unpack = IntArray(UNPACK_PARAMETERS.size) + private val capabilities = BooleanArray(CAPABILITIES.size) + private val viewport = IntArray(4) + private val scissor = IntArray(4) + + inline fun borrow(block: () -> T): T { + val restore = capture() + try { + prepare() + return block() + } finally { + restore() + } + } + + fun prepare() { + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) + glBindBuffer(GL_PIXEL_PACK_BUFFER, 0) + UNPACK_PARAMETERS.forEachIndexed { index, parameter -> + glPixelStorei(parameter, UNPACK_DEFAULTS[index]) + } + } + + fun capture(): () -> Unit { + val activeTexture = glGetInteger(GL_ACTIVE_TEXTURE) + repeat(TEXTURE_UNITS) { unit -> + glActiveTexture(GL_TEXTURE0 + unit) + textures[unit] = glGetInteger(GL_TEXTURE_BINDING_2D) + samplers[unit] = glGetInteger(GL_SAMPLER_BINDING) + } + glActiveTexture(activeTexture) + + val program = glGetInteger(GL_CURRENT_PROGRAM) + val vertexArray = glGetInteger(GL_VERTEX_ARRAY_BINDING) + val arrayBuffer = glGetInteger(GL_ARRAY_BUFFER_BINDING) + val unpackBuffer = glGetInteger(GL_PIXEL_UNPACK_BUFFER_BINDING) + val packBuffer = glGetInteger(GL_PIXEL_PACK_BUFFER_BINDING) + val drawFramebuffer = glGetInteger(GL_DRAW_FRAMEBUFFER_BINDING) + val readFramebuffer = glGetInteger(GL_READ_FRAMEBUFFER_BINDING) + val blendSrcRgb = glGetInteger(GL_BLEND_SRC_RGB) + val blendDstRgb = glGetInteger(GL_BLEND_DST_RGB) + val blendSrcAlpha = glGetInteger(GL_BLEND_SRC_ALPHA) + val blendDstAlpha = glGetInteger(GL_BLEND_DST_ALPHA) + val blendEquationRgb = glGetInteger(GL_BLEND_EQUATION_RGB) + val blendEquationAlpha = glGetInteger(GL_BLEND_EQUATION_ALPHA) + val depthMask = glGetBoolean(GL_DEPTH_WRITEMASK) + val colorMask = + MemoryStack.stackPush().use { stack -> + val mask = stack.malloc(4) + glGetBooleanv(GL_COLOR_WRITEMASK, mask) + BooleanArray(4) { mask[it].toInt() != 0 } + } + glGetIntegerv(GL_VIEWPORT, viewport) + glGetIntegerv(GL_SCISSOR_BOX, scissor) + CAPABILITIES.forEachIndexed { index, capability -> + capabilities[index] = glIsEnabled(capability) + } + UNPACK_PARAMETERS.forEachIndexed { index, parameter -> + unpack[index] = glGetInteger(parameter) + } + + return { + glUseProgram(program) + repeat(TEXTURE_UNITS) { unit -> + glActiveTexture(GL_TEXTURE0 + unit) + glBindTexture(GL_TEXTURE_2D, textures[unit]) + glBindSampler(unit, samplers[unit]) + } + glActiveTexture(activeTexture) + glBindVertexArray(vertexArray) + glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, unpackBuffer) + glBindBuffer(GL_PIXEL_PACK_BUFFER, packBuffer) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFramebuffer) + glBindFramebuffer(GL_READ_FRAMEBUFFER, readFramebuffer) + glBlendEquationSeparate(blendEquationRgb, blendEquationAlpha) + glBlendFuncSeparate(blendSrcRgb, blendDstRgb, blendSrcAlpha, blendDstAlpha) + glDepthMask(depthMask) + glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]) + glViewport(viewport[0], viewport[1], viewport[2], viewport[3]) + glScissor(scissor[0], scissor[1], scissor[2], scissor[3]) + CAPABILITIES.forEachIndexed { index, capability -> + if (capabilities[index]) glEnable(capability) else glDisable(capability) + } + UNPACK_PARAMETERS.forEachIndexed { index, parameter -> + glPixelStorei(parameter, unpack[index]) + } + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/core/Observe.kt b/src/main/kotlin/com/lambda/gui/core/Observe.kt new file mode 100644 index 000000000..ebea6223b --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/Observe.kt @@ -0,0 +1,58 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.staticCompositionLocalOf +import com.lambda.context.SafeContext +import com.lambda.threading.runSafe + +@Composable +fun observe(read: () -> T): State { + val observations = LocalObservations.current + val observation = remember { Observation(read) } + observation.read = read + DisposableEffect(observations) { + observations.active += observation + onDispose { observations.active -= observation } + } + return observation.state +} + +@Composable +fun observeSafe(read: SafeContext.() -> T): State = observe { runSafe(read) } + +internal class Observation(var read: () -> T) { + val state = mutableStateOf(read()) + + fun refresh() { + state.value = read() + } +} + +internal class Observations { + val active = ArrayList>() + + fun refresh() = active.forEach { it.refresh() } +} + +internal val LocalObservations = staticCompositionLocalOf { error("observe was called outside the interface") } diff --git a/src/main/kotlin/com/lambda/gui/core/RenderThread.kt b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt new file mode 100644 index 000000000..b6dacb820 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt @@ -0,0 +1,43 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import com.lambda.Lambda.mc +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlin.coroutines.CoroutineContext +import kotlin.time.Duration.Companion.milliseconds + +object RenderThread : CoroutineDispatcher() { + private val scope = CoroutineScope(this + SupervisorJob()) + + override fun isDispatchNeeded(context: CoroutineContext) = !mc.isOnThread + + override fun dispatch(context: CoroutineContext, block: Runnable) = mc.send(block) + + @JvmStatic + fun after(millis: Long, block: () -> Unit): Job = + scope.launch { + delay(millis.milliseconds) + block() + } +} diff --git a/src/main/kotlin/com/lambda/gui/core/Retained.kt b/src/main/kotlin/com/lambda/gui/core/Retained.kt new file mode 100644 index 000000000..b6f37f4e7 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/Retained.kt @@ -0,0 +1,48 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.layout + +val LocalShown = compositionLocalOf { true } + +@Composable +internal fun Retained( + shown: Boolean, + observations: Observations, + content: @Composable () -> Unit +) { + CompositionLocalProvider( + LocalShown provides shown, + LocalObservations provides observations + ) { + Box( + Modifier.layout { measurable, constraints -> + val placeable = measurable.measure(constraints) + layout(placeable.width, placeable.height) { + if (shown) placeable.place(0, 0) + } + } + ) { content() } + } +} diff --git a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt new file mode 100644 index 000000000..2f40b41fc --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt @@ -0,0 +1,232 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import androidx.compose.runtime.Composable +import androidx.compose.ui.InternalComposeUiApi +import androidx.compose.ui.graphics.asComposeCanvas +import androidx.compose.ui.graphics.drawscope.CanvasDrawScope +import androidx.compose.ui.graphics.layer.GraphicsLayer +import androidx.compose.ui.graphics.layer.drawLayer +import androidx.compose.ui.platform.FrameRecomposer +import androidx.compose.ui.scene.CanvasLayersComposeScene +import androidx.compose.ui.scene.ComposeScene +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.toSize +import com.mojang.blaze3d.systems.RenderSystem +import com.mojang.blaze3d.textures.GpuTexture +import com.mojang.blaze3d.textures.GpuTextureView +import com.mojang.blaze3d.textures.TextureFormat +import net.minecraft.client.texture.GlTexture +import org.jetbrains.skia.BackendRenderTarget +import org.jetbrains.skia.Color +import org.jetbrains.skia.ColorSpace +import org.jetbrains.skia.DirectContext +import org.jetbrains.skia.FramebufferFormat +import org.jetbrains.skia.Surface +import org.jetbrains.skia.SurfaceColorFormat +import org.jetbrains.skia.SurfaceOrigin +import org.lwjgl.opengl.GL11.GL_TEXTURE_2D +import org.lwjgl.opengl.GL30.GL_COLOR_ATTACHMENT0 +import org.lwjgl.opengl.GL30.GL_DEPTH24_STENCIL8 +import org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT +import org.lwjgl.opengl.GL30.GL_FRAMEBUFFER +import org.lwjgl.opengl.GL30.GL_RENDERBUFFER +import org.lwjgl.opengl.GL30.glBindFramebuffer +import org.lwjgl.opengl.GL30.glBindRenderbuffer +import org.lwjgl.opengl.GL30.glDeleteFramebuffers +import org.lwjgl.opengl.GL30.glDeleteRenderbuffers +import org.lwjgl.opengl.GL30.glFramebufferRenderbuffer +import org.lwjgl.opengl.GL30.glFramebufferTexture2D +import org.lwjgl.opengl.GL30.glGenFramebuffers +import org.lwjgl.opengl.GL30.glGenRenderbuffers +import org.lwjgl.opengl.GL30.glRenderbufferStorage +import kotlin.coroutines.CoroutineContext + +@OptIn(InternalComposeUiApi::class) +internal class SceneHost( + context: CoroutineContext, + content: @Composable () -> Unit +) : AutoCloseable { + val platform = ScenePlatform() + + private val recomposer = FrameRecomposer(RenderThread + context) + private var invalidated = true + + private val scene: ComposeScene = + CanvasLayersComposeScene( + frameRecomposer = recomposer, + platformContext = platform, + invalidateDraw = { invalidated = true }, + ).also { it.setContent(content = content) } + + val input = SceneInput(scene) + + private var skia: DirectContext? = null + private var target: SkiaTarget? = null + private var underlayTarget: SkiaTarget? = null + + val texture: GpuTextureView? get() = target?.view + val underlayTexture: GpuTextureView? get() = underlayTarget?.view + + fun advance(size: IntSize, density: Float): Boolean { + if (scene.size != size || scene.density.density != density) { + scene.density = Density(density) + scene.size = size + platform.resize(size, density) + invalidated = true + } + recomposer.performFrame(System.nanoTime()) + scene.measureAndLayout() + return invalidated || scene.hasPendingDraw || target == null + } + + fun draw(underlay: GraphicsLayer? = null, beforeScene: (DirectContext) -> Unit = {}) { + val size = scene.size ?: return + val outgrown = + listOfNotNull( + target?.takeIf { it.size != size }, + underlayTarget?.takeIf { it.size != size || underlay == null } + ) + val target = target?.takeIf { it !in outgrown } ?: SkiaTarget(size).also { target = it } + val underlayTarget = + if (underlay == null) null + else underlayTarget?.takeIf { it !in outgrown } ?: SkiaTarget(size) + this.underlayTarget = underlayTarget + GlState.borrow { + val skia = skia ?: DirectContext.makeGL().also { skia = it } + outgrown.forEach { it.detach() } + val surface = target.attach(skia) + val underlaySurface = underlayTarget?.attach(skia) + skia.resetGLAll() + beforeScene(skia) + surface.canvas.clear(Color.TRANSPARENT) + scene.draw(surface.canvas.asComposeCanvas()) + surface.flushAndSubmit() + if (underlay != null && underlaySurface != null) { + underlaySurface.canvas.clear(Color.TRANSPARENT) + CanvasDrawScope().draw( + scene.density, + LayoutDirection.Ltr, + underlaySurface.canvas.asComposeCanvas(), + size.toSize() + ) { drawLayer(underlay) } + underlaySurface.flushAndSubmit() + } + } + outgrown.forEach { it.close() } + invalidated = false + } + + override fun close() { + scene.close() + recomposer.close() + } + + fun closeAndFree() { + runCatching { scene.close() } + runCatching { recomposer.close() } + val freed = listOfNotNull(target, underlayTarget) + target = null + underlayTarget = null + GlState.borrow { + freed.forEach { it.detach() } + skia?.close() + } + skia = null + freed.forEach { it.close() } + } +} + +private class SkiaTarget(val size: IntSize) : AutoCloseable { + private val texture: GpuTexture = + RenderSystem.getDevice().createTexture( + { "Lambda GUI" }, + GpuTexture.USAGE_RENDER_ATTACHMENT or GpuTexture.USAGE_TEXTURE_BINDING, + TextureFormat.RGBA8, + size.width, size.height, 1, 1 + ) + val view: GpuTextureView = RenderSystem.getDevice().createTextureView(texture) + + private var framebuffer = 0 + private var stencil = 0 + private var renderTarget: BackendRenderTarget? = null + private var surface: Surface? = null + + fun attach(skia: DirectContext): Surface = surface + ?: run { + framebuffer = glGenFramebuffers() + stencil = glGenRenderbuffers() + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) + glFramebufferTexture2D( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + (texture as GlTexture).glId, + 0 + ) + glBindRenderbuffer(GL_RENDERBUFFER, stencil) + glRenderbufferStorage( + GL_RENDERBUFFER, + GL_DEPTH24_STENCIL8, + size.width, + size.height + ) + glFramebufferRenderbuffer( + GL_FRAMEBUFFER, + GL_DEPTH_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, + stencil + ) + + val renderTarget = + BackendRenderTarget.makeGL( + size.width, + size.height, + 0, + 8, + framebuffer, + FramebufferFormat.GR_GL_RGBA8 + ).also { renderTarget = it } + Surface.makeFromBackendRenderTarget( + skia, + renderTarget, + SurfaceOrigin.BOTTOM_LEFT, + SurfaceColorFormat.RGBA_8888, + ColorSpace.sRGB + )?.also { surface = it } ?: error("Skia rejected the GUI render target") + } + + fun detach() { + surface?.close() + surface = null + renderTarget?.close() + renderTarget = null + if (framebuffer != 0) glDeleteFramebuffers(framebuffer) + if (stencil != 0) glDeleteRenderbuffers(stencil) + framebuffer = 0 + stencil = 0 + } + + override fun close() { + view.close() + texture.close() + } +} diff --git a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt new file mode 100644 index 000000000..858774b77 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt @@ -0,0 +1,218 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import androidx.compose.ui.InternalComposeUiApi +import androidx.compose.ui.focus.FocusDirection +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.pointer.PointerButton +import androidx.compose.ui.input.pointer.PointerButtons +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerKeyboardModifiers +import androidx.compose.ui.scene.ComposeScene +import com.lambda.gui.component.KeyboardFocus +import org.lwjgl.glfw.GLFW +import java.awt.Component +import java.awt.event.KeyEvent as AwtKeyEvent + +internal object Press { + var id = 0L + private set + + fun begin() { + id++ + } +} + +@OptIn(InternalComposeUiApi::class) +internal class SceneInput(private val scene: ComposeScene) { + private var position = Offset.Zero + private var pressedButtons = 0 + + fun move(position: Offset) { + this.position = position + pointer(PointerEventType.Move) + } + + fun button(button: Int, pressed: Boolean, modifiers: Int) { + val mask = 1 shl button + pressedButtons = + if (pressed) pressedButtons or mask + else pressedButtons and mask.inv() + if (pressed) { + Press.begin() + KeyboardFocus.visible = false + } + pointer( + if (pressed) PointerEventType.Press else PointerEventType.Release, + button.toPointerButton(), + modifiers + ) + } + + fun scroll(horizontal: Double, vertical: Double) { + pointer( + PointerEventType.Scroll, + scroll = Offset(horizontal.toFloat(), -vertical.toFloat()) * LINES_PER_NOTCH + ) + } + + fun key(key: Int, pressed: Boolean, modifiers: Int): Boolean { + if (pressed) Press.begin() + val shift = modifiers and GLFW.GLFW_MOD_SHIFT != 0 + val direction = + when (key.takeIf { pressed }) { + GLFW.GLFW_KEY_TAB -> + if (shift) FocusDirection.Previous + else FocusDirection.Next + GLFW.GLFW_KEY_UP -> FocusDirection.Up + GLFW.GLFW_KEY_DOWN -> FocusDirection.Down + GLFW.GLFW_KEY_LEFT -> FocusDirection.Left + GLFW.GLFW_KEY_RIGHT -> FocusDirection.Right + else -> null + } + if (direction != null) KeyboardFocus.visible = true + + val handled = + scene.sendKeyEvent( + KeyEvent( + key = Key(key.toAwtKeyCode()), + type = if (pressed) KeyEventType.KeyDown else KeyEventType.KeyUp, + isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, + isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, + isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, + isShiftPressed = shift, + ) + ) + if (handled || direction == null) return handled + val inOrder = + when (direction) { + FocusDirection.Up, FocusDirection.Left -> FocusDirection.Previous + else -> FocusDirection.Next + } + return KeyboardFocus.move(direction) || direction != inOrder && KeyboardFocus.move(inOrder) + } + + fun type(codePoint: Int): Boolean = + Character.toChars(codePoint).fold(false) { handled, char -> + val typed = + AwtKeyEvent( + awtSource, + AwtKeyEvent.KEY_TYPED, + System.currentTimeMillis(), + 0, + AwtKeyEvent.VK_UNDEFINED, + char + ) + scene.sendKeyEvent( + KeyEvent( + key = Key.Unknown, + type = KeyEventType.Unknown, + codePoint = char.code, + nativeEvent = typed + ) + ) || handled + } + + fun release() { + pressedButtons = 0 + position = OFF_SCREEN + pointer(PointerEventType.Exit) + scene.cancelPointerInput() + scene.focusManager.releaseFocus() + KeyboardFocus.visible = false + } + + private fun pointer( + type: PointerEventType, + button: PointerButton? = null, + modifiers: Int = 0, + scroll: Offset = Offset.Zero, + ) { + scene.sendPointerEvent( + eventType = type, + position = position, + scrollDelta = scroll, + buttons = PointerButtons( + isPrimaryPressed = pressedButtons and 0b1 != 0, + isSecondaryPressed = pressedButtons and 0b10 != 0, + isTertiaryPressed = pressedButtons and 0b100 != 0, + isBackPressed = pressedButtons and 0b1000 != 0, + isForwardPressed = pressedButtons and 0b10000 != 0, + ), + keyboardModifiers = PointerKeyboardModifiers( + isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, + isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, + isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, + isShiftPressed = modifiers and GLFW.GLFW_MOD_SHIFT != 0, + ), + button = button, + ) + } + + private companion object { + val OFF_SCREEN = Offset(-1e6f, -1e6f) + + const val LINES_PER_NOTCH = 3f + + val awtSource = object : Component() {} + + fun Int.toPointerButton() = + when (this) { + GLFW.GLFW_MOUSE_BUTTON_LEFT -> PointerButton.Primary + GLFW.GLFW_MOUSE_BUTTON_RIGHT -> PointerButton.Secondary + GLFW.GLFW_MOUSE_BUTTON_MIDDLE -> PointerButton.Tertiary + GLFW.GLFW_MOUSE_BUTTON_4 -> PointerButton.Back + GLFW.GLFW_MOUSE_BUTTON_5 -> PointerButton.Forward + else -> null + } + + fun Int.toAwtKeyCode() = + when (this) { + GLFW.GLFW_KEY_ESCAPE -> AwtKeyEvent.VK_ESCAPE + GLFW.GLFW_KEY_ENTER, GLFW.GLFW_KEY_KP_ENTER -> AwtKeyEvent.VK_ENTER + GLFW.GLFW_KEY_TAB -> AwtKeyEvent.VK_TAB + GLFW.GLFW_KEY_SPACE -> AwtKeyEvent.VK_SPACE + GLFW.GLFW_KEY_BACKSPACE -> AwtKeyEvent.VK_BACK_SPACE + GLFW.GLFW_KEY_INSERT -> AwtKeyEvent.VK_INSERT + GLFW.GLFW_KEY_DELETE -> AwtKeyEvent.VK_DELETE + GLFW.GLFW_KEY_RIGHT -> AwtKeyEvent.VK_RIGHT + GLFW.GLFW_KEY_LEFT -> AwtKeyEvent.VK_LEFT + GLFW.GLFW_KEY_DOWN -> AwtKeyEvent.VK_DOWN + GLFW.GLFW_KEY_UP -> AwtKeyEvent.VK_UP + GLFW.GLFW_KEY_PAGE_UP -> AwtKeyEvent.VK_PAGE_UP + GLFW.GLFW_KEY_PAGE_DOWN -> AwtKeyEvent.VK_PAGE_DOWN + GLFW.GLFW_KEY_HOME -> AwtKeyEvent.VK_HOME + GLFW.GLFW_KEY_END -> AwtKeyEvent.VK_END + GLFW.GLFW_KEY_LEFT_SHIFT, GLFW.GLFW_KEY_RIGHT_SHIFT -> + AwtKeyEvent.VK_SHIFT + GLFW.GLFW_KEY_LEFT_CONTROL, GLFW.GLFW_KEY_RIGHT_CONTROL -> + AwtKeyEvent.VK_CONTROL + GLFW.GLFW_KEY_LEFT_ALT, GLFW.GLFW_KEY_RIGHT_ALT -> AwtKeyEvent.VK_ALT + GLFW.GLFW_KEY_LEFT_SUPER, GLFW.GLFW_KEY_RIGHT_SUPER -> AwtKeyEvent.VK_META + in GLFW.GLFW_KEY_A..GLFW.GLFW_KEY_Z, + in GLFW.GLFW_KEY_0..GLFW.GLFW_KEY_9 -> this + in GLFW.GLFW_KEY_F1..GLFW.GLFW_KEY_F12 -> + AwtKeyEvent.VK_F1 + (this - GLFW.GLFW_KEY_F1) + else -> AwtKeyEvent.VK_UNDEFINED + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt new file mode 100644 index 000000000..579123235 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt @@ -0,0 +1,89 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.InternalComposeUiApi +import androidx.compose.ui.input.pointer.PointerIcon +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.Clipboard +import androidx.compose.ui.platform.PlatformContext +import androidx.compose.ui.platform.WindowInfo +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.lambda.Lambda.mc +import net.minecraft.client.gui.cursor.Cursor +import net.minecraft.client.gui.cursor.StandardCursors +import java.awt.datatransfer.DataFlavor +import java.awt.datatransfer.StringSelection +import java.awt.datatransfer.Transferable + +@OptIn(InternalComposeUiApi::class) +internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { + private val window = + object : WindowInfo { + override val isWindowFocused get() = true + override var containerSize by mutableStateOf(IntSize.Zero) + override var containerDpSize by mutableStateOf(DpSize.Zero) + } + var cursor: Cursor? = null + + override val windowInfo: WindowInfo get() = window + + fun resize(size: IntSize, density: Float) { + window.containerSize = size + window.containerDpSize = DpSize((size.width / density).dp, (size.height / density).dp) + } + + override fun setPointerIcon(pointerIcon: PointerIcon) { + cursor = + when (pointerIcon) { + PointerIcon.Text -> StandardCursors.IBEAM + PointerIcon.Hand -> StandardCursors.POINTING_HAND + PointerIcon.Crosshair -> StandardCursors.CROSSHAIR + ResizeVerticalIcon -> StandardCursors.RESIZE_NS + else -> null + } + } +} + +object ResizeVerticalIcon : PointerIcon + +@OptIn(ExperimentalComposeUiApi::class) +internal object GameClipboard : Clipboard { + @Suppress("OVERRIDE_DEPRECATION") + override val nativeClipboard: Any get() = this + + override suspend fun getClipEntry(): ClipEntry? = + mc.keyboard.clipboard.takeIf { it.isNotEmpty() }?.let { + ClipEntry(StringSelection(it)) + } + + override suspend fun setClipEntry(clipEntry: ClipEntry?) { + val transferable = clipEntry?.nativeClipEntry as? Transferable + mc.keyboard.clipboard = + transferable + ?.takeIf { it.isDataFlavorSupported(DataFlavor.stringFlavor) } + ?.getTransferData(DataFlavor.stringFlavor) as? String + ?: "" + } +} diff --git a/src/main/kotlin/com/lambda/gui/dsl/ImGuiBuilder.kt b/src/main/kotlin/com/lambda/gui/dsl/ImGuiBuilder.kt deleted file mode 100644 index 0031980d7..000000000 --- a/src/main/kotlin/com/lambda/gui/dsl/ImGuiBuilder.kt +++ /dev/null @@ -1,2078 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -@file:Suppress("unused") - -package com.lambda.gui.dsl - -import com.lambda.gui.components.ClickGuiLayout -import com.lambda.imgui.ImDrawList -import com.lambda.imgui.ImFont -import com.lambda.imgui.ImGui -import com.lambda.imgui.ImGui.begin -import com.lambda.imgui.ImGui.beginChild -import com.lambda.imgui.ImGui.beginCombo -import com.lambda.imgui.ImGui.beginDragDropSource -import com.lambda.imgui.ImGui.beginDragDropTarget -import com.lambda.imgui.ImGui.beginGroup -import com.lambda.imgui.ImGui.beginMainMenuBar -import com.lambda.imgui.ImGui.beginMenu -import com.lambda.imgui.ImGui.beginMenuBar -import com.lambda.imgui.ImGui.beginPopup -import com.lambda.imgui.ImGui.beginPopupContextItem -import com.lambda.imgui.ImGui.beginPopupContextVoid -import com.lambda.imgui.ImGui.beginPopupContextWindow -import com.lambda.imgui.ImGui.beginPopupModal -import com.lambda.imgui.ImGui.beginTabBar -import com.lambda.imgui.ImGui.beginTabItem -import com.lambda.imgui.ImGui.beginTooltip -import com.lambda.imgui.ImGui.calcTextSize -import com.lambda.imgui.ImGui.collapsingHeader -import com.lambda.imgui.ImGui.colorButton -import com.lambda.imgui.ImGui.colorEdit4 -import com.lambda.imgui.ImGui.colorPicker4 -import com.lambda.imgui.ImGui.dragFloat -import com.lambda.imgui.ImGui.dragInt -import com.lambda.imgui.ImGui.end -import com.lambda.imgui.ImGui.endChild -import com.lambda.imgui.ImGui.endCombo -import com.lambda.imgui.ImGui.endDragDropSource -import com.lambda.imgui.ImGui.endDragDropTarget -import com.lambda.imgui.ImGui.endGroup -import com.lambda.imgui.ImGui.endMainMenuBar -import com.lambda.imgui.ImGui.endMenu -import com.lambda.imgui.ImGui.endMenuBar -import com.lambda.imgui.ImGui.endPopup -import com.lambda.imgui.ImGui.endTabBar -import com.lambda.imgui.ImGui.endTabItem -import com.lambda.imgui.ImGui.endTooltip -import com.lambda.imgui.ImGui.getBackgroundDrawList -import com.lambda.imgui.ImGui.getColorU32 -import com.lambda.imgui.ImGui.getContentRegionAvail -import com.lambda.imgui.ImGui.getCursorPosX -import com.lambda.imgui.ImGui.getCursorPosY -import com.lambda.imgui.ImGui.getFont -import com.lambda.imgui.ImGui.getFontSize -import com.lambda.imgui.ImGui.getForegroundDrawList -import com.lambda.imgui.ImGui.getFrameHeight -import com.lambda.imgui.ImGui.getFrameHeightWithSpacing -import com.lambda.imgui.ImGui.getIO -import com.lambda.imgui.ImGui.getItemID -import com.lambda.imgui.ImGui.getItemRectMaxX -import com.lambda.imgui.ImGui.getItemRectMaxY -import com.lambda.imgui.ImGui.getItemRectMinX -import com.lambda.imgui.ImGui.getItemRectMinY -import com.lambda.imgui.ImGui.getStyle -import com.lambda.imgui.ImGui.getVersion -import com.lambda.imgui.ImGui.getWindowContentRegionMaxX -import com.lambda.imgui.ImGui.getWindowContentRegionMaxY -import com.lambda.imgui.ImGui.getWindowDrawList -import com.lambda.imgui.ImGui.getWindowHeight -import com.lambda.imgui.ImGui.getWindowPos -import com.lambda.imgui.ImGui.getWindowPosX -import com.lambda.imgui.ImGui.getWindowPosY -import com.lambda.imgui.ImGui.getWindowSize -import com.lambda.imgui.ImGui.getWindowViewport -import com.lambda.imgui.ImGui.getWindowWidth -import com.lambda.imgui.ImGui.image -import com.lambda.imgui.ImGui.inputDouble -import com.lambda.imgui.ImGui.inputFloat -import com.lambda.imgui.ImGui.inputFloat2 -import com.lambda.imgui.ImGui.inputFloat3 -import com.lambda.imgui.ImGui.inputFloat4 -import com.lambda.imgui.ImGui.isAnyItemActive -import com.lambda.imgui.ImGui.isAnyItemFocused -import com.lambda.imgui.ImGui.isAnyItemHovered -import com.lambda.imgui.ImGui.isItemActivated -import com.lambda.imgui.ImGui.isItemActive -import com.lambda.imgui.ImGui.isItemClicked -import com.lambda.imgui.ImGui.isItemDeactivated -import com.lambda.imgui.ImGui.isItemDeactivatedAfterEdit -import com.lambda.imgui.ImGui.isItemEdited -import com.lambda.imgui.ImGui.isItemFocused -import com.lambda.imgui.ImGui.isItemHovered -import com.lambda.imgui.ImGui.isItemToggledOpen -import com.lambda.imgui.ImGui.isWindowAppearing -import com.lambda.imgui.ImGui.isWindowCollapsed -import com.lambda.imgui.ImGui.plotHistogram -import com.lambda.imgui.ImGui.plotLines -import com.lambda.imgui.ImGui.popFont -import com.lambda.imgui.ImGui.popID -import com.lambda.imgui.ImGui.popItemWidth -import com.lambda.imgui.ImGui.popStyleColor -import com.lambda.imgui.ImGui.popStyleVar -import com.lambda.imgui.ImGui.popTextWrapPos -import com.lambda.imgui.ImGui.pushFont -import com.lambda.imgui.ImGui.pushID -import com.lambda.imgui.ImGui.pushItemWidth -import com.lambda.imgui.ImGui.pushStyleColor -import com.lambda.imgui.ImGui.pushStyleVar -import com.lambda.imgui.ImGui.pushTextWrapPos -import com.lambda.imgui.ImGui.setClipboardText -import com.lambda.imgui.ImGui.setCursorPosX -import com.lambda.imgui.ImGui.setCursorPosY -import com.lambda.imgui.ImGui.sliderFloat -import com.lambda.imgui.ImGui.sliderInt -import com.lambda.imgui.ImGui.textColored -import com.lambda.imgui.ImGui.textUnformatted -import com.lambda.imgui.ImGui.treeNode -import com.lambda.imgui.ImGui.treePop -import com.lambda.imgui.ImGuiIO -import com.lambda.imgui.ImGuiStyle -import com.lambda.imgui.ImGuiTextFilter -import com.lambda.imgui.ImGuiViewport -import com.lambda.imgui.ImVec2 -import com.lambda.imgui.flag.ImDrawListFlags -import com.lambda.imgui.flag.ImGuiChildFlags -import com.lambda.imgui.flag.ImGuiCol -import com.lambda.imgui.flag.ImGuiColorEditFlags -import com.lambda.imgui.flag.ImGuiComboFlags -import com.lambda.imgui.flag.ImGuiDir -import com.lambda.imgui.flag.ImGuiHoveredFlags -import com.lambda.imgui.flag.ImGuiInputTextFlags -import com.lambda.imgui.flag.ImGuiMouseButton -import com.lambda.imgui.flag.ImGuiPopupFlags -import com.lambda.imgui.flag.ImGuiSelectableFlags -import com.lambda.imgui.flag.ImGuiTabBarFlags -import com.lambda.imgui.flag.ImGuiTreeNodeFlags -import com.lambda.imgui.flag.ImGuiWindowFlags -import com.lambda.imgui.type.ImBoolean -import com.lambda.imgui.type.ImDouble -import com.lambda.imgui.type.ImFloat -import com.lambda.imgui.type.ImInt -import com.lambda.imgui.type.ImString -import com.lambda.util.math.Vec2d -import net.minecraft.util.math.Vec2f -import net.minecraft.util.math.Vec3d -import net.minecraft.util.math.Vec3i -import java.awt.Color -import kotlin.reflect.KMutableProperty0 - -typealias ProcedureBlock = ImGuiBuilder.() -> Unit -typealias WrappedBlock = ImGuiBuilder.(In) -> Out - -@DslMarker -annotation class ImGuiDsl - -/** - * Kotlin DSL wrapper for ImGui Java bindings. - * Provides a more idiomatic Kotlin interface to ImGui functionality. - */ -@ImGuiDsl -object ImGuiBuilder { - /** - * Access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags). - */ - val io: ImGuiIO get() = getIO() - - /** - * Access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame! - */ - val style: ImGuiStyle get() = getStyle() - - /** - * Get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp) - */ - val version: String get() = getVersion() - - val isWindowAppearing: Boolean get() = isWindowAppearing() - val isWindowCollapsed: Boolean get() = isWindowCollapsed() - - /** - * Returns the current window position in screen space - * - * It is unlikely you need to use this. Consider using current layout pos instead, GetScreenCursorPos(). - */ - val windowPos: ImVec2 get() = getWindowPos() - val windowX: Float get() = getWindowPosX() - val windowY: Float get() = getWindowPosY() - - /** - * Returns the current window size - * It is unlikely you need to use this. Consider using GetScreenCursorPos() and GetContentRegionAvail() instead. - */ - val windowSize: ImVec2 get() = getWindowSize() - val windowWidth: Float get() = getWindowWidth() - val windowHeight: Float get() = getWindowHeight() - - /** - * Returns the viewport associated to the current window. - */ - val windowViewport: ImGuiViewport get() = getWindowViewport() - - /** - * Returns whether any item hovered and usable (not blocked by a popup, etc.). - */ - val isAnyItemHovered: Boolean get() = isAnyItemHovered() - - /** - * Returns whether: - * - Any button is being held - * - Any text field is being edited - * - Any item is being held and allows interaction - */ - val isAnyItemActive: Boolean get() = isAnyItemActive() - - /** - * Returns whether any item is focused via keyboard/gamepad navigation - */ - val isAnyItemFocused: Boolean get() = isAnyItemFocused() - - /** - * Executes the specified block if the current window is hovered, based on the provided flags. - * - * @param flags Optional flags to control the behavior of the hover state. The default value is `ImGuiWindowFlags.None`. - * @param block A lambda block of code to be executed when the window is hovered. - */ - fun onWindowFocus(flags: Int = ImGuiWindowFlags.None, block: ProcedureBlock) = - if (isWindowHovered(flags)) block() else Unit - - /** - * Executes a given block of code when the current ImGui window is being hovered. - * - * @param flags Optional flag settings for specifying conditions under which the window hover is detected. - * Defaults to `ImGuiWindowFlags.None`. - * @param block The block of code to execute when the hover condition is met. - */ - fun onWindowHover(flags: Int = ImGuiWindowFlags.None, block: ProcedureBlock) = - if (isWindowHovered(flags)) block() else Unit - - /** - * Executes the given block of code if the current ImGui item is hovered. - * - * @param flags Customization flags for determining hover behavior. Defaults to `ImGuiHoveredFlags.None`. - * @param block The block of code to execute when the item is hovered. - */ - fun onItemHover(flags: Int = ImGuiHoveredFlags.None, block: ProcedureBlock) = - if (isItemHovered(flags)) block() else Unit - - /** - * Executes the provided block of code if the current item is active in the ImGui context. - * - * @param block The block of code to be executed when the item is active. - */ - fun onItemActive(block: ProcedureBlock) = - if (isItemActive()) block() else Unit - - /** - * Executes the given [block] when the currently active item in the ImGui interface gains focus. - * - * @param block The block of code to execute if the current item is focused. - */ - fun onItemFocus(block: ProcedureBlock) = - if (isItemFocused()) block() else Unit - - /** - * Returns whether the last hovered item is clicked on - * - * IsMouseClicked(mouseButton) && IsItemHovered() - * - * this is NOT equivalent to the behavior of e.g. Button(). Read comments in function definition. - */ - fun onItemClick(button: Int = ImGuiMouseButton.Right, block: ProcedureBlock) = - if (isItemClicked(button)) block() else Unit - - /** - * Returns whether [button] went down this frame, regardless of what is hovered. - * - * Unlike [onItemClick] this does not imply the last item is hovered, so it can be combined with - * [onItemHover] to observe clicks on items that are blocked by an open popup. - */ - fun isMouseClicked(button: Int = ImGuiMouseButton.Right, repeat: Boolean = false): Boolean = - ImGui.isMouseClicked(button, repeat) - - /** - * Returns whether [button] was released this frame, regardless of what is hovered. - */ - fun isMouseReleased(button: Int = ImGuiMouseButton.Right): Boolean = - ImGui.isMouseReleased(button) - - /** - * Returns whether the current window is hovered. - */ - fun isWindowHovered(flags: Int = ImGuiHoveredFlags.None): Boolean = - ImGui.isWindowHovered(flags) - - /** - * Resolves [strId] against the current window and ID stack, so the same string used in two - * places yields two distinct ids. - */ - fun getId(strId: String): Int = ImGui.getID(strId) - - /** - * Returns whether: - * - The last item modified its value in this frame - * - Was pressed - */ - val isItemEdited: Boolean get() = isItemEdited() - - /** - * Returns whether the last item was made active. - */ - val isItemActivated: Boolean get() = isItemActivated() - - /** - * Returns whether the last item was made inactive - * - * Useful for Undo/Redo patterns with widgets that require continuous editing. - */ - val isItemDeactivated: Boolean get() = isItemDeactivated() - - /** - * Returns whether the last item was made inactive and its value was changed when active (e.g. Slider/Drag moved). - * - * Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). - */ - val isItemDeactivatedAfterEdit: Boolean get() = isItemDeactivatedAfterEdit() - - /** - * Returns whether the last item state toggled (set by TreeNode()). - */ - val isItemToggledOpen: Boolean get() = isItemToggledOpen() - - /** - * Returns the ID of last item (~~ often same ImGui::GetID(label) beforehand) - */ - val itemID: Int get() = getItemID() - - - val font: ImFont get() = getFont() - - /** - * Returns the font size (= height in pixels) with the current scale applied. - */ - val fontSize: Int get() = getFontSize() - - - /** - * Add basic help/info block (not a window) on how to manipulate ImGui as an end-user (mouse/keyboard controls). - */ - fun showUserGuide() = ImGui.showUserGuide() - - inline fun window( - name: String, - open: KMutableProperty0, - flags: Int = ImGuiWindowFlags.None, - block: ProcedureBlock - ) = - withBool(open) { window(name, it, flags, block) } - - inline fun window( - name: String, - open: ImBoolean? = null, - flags: Int = ImGuiWindowFlags.None, - block: ProcedureBlock - ) { - if (open != null) begin(name, open, flags) - else begin(name, flags) - - block() - - end() - } - - inline fun child( - strId: String, - width: Float = 0f, - height: Float = 0f, - border: Boolean = false, - windowFlags: Int = ImGuiWindowFlags.None, - block: ProcedureBlock - ) { - if (beginChild(strId, width, height, border, windowFlags)) - block() - - endChild() - } - - inline fun child( - strId: String, - width: Float = 0f, - height: Float = 0f, - childFlags: Int = ImGuiChildFlags.None, - windowFlags: Int = ImGuiWindowFlags.None, - block: ProcedureBlock - ) { - if (beginChild(strId, width, height, childFlags, windowFlags)) - block() - - endChild() - } - - /** - * Raw text without formatting. - * - * Roughly equivalent to Text("%s", text) but: - * - doesn't require null terminated string if 'textEnd' is specified, - * - it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. - * - * @param text The text to display - */ - fun text(text: String) = textUnformatted(text) - - /** - * Text with coloring - * - * @param text The text to display - */ - fun textColored(text: String, color: Color) { - val floats = floatArrayOf(0f, 0f, 0f, 0f) - val (r, g, b, a) = color.getColorComponents(floats) - textColored(r, g, b, a, text) - } - - /** - * Text with disabled coloring. - * - * @param text The text to display - */ - fun textDisabled(text: String) = ImGui.textDisabled(text) - - /** - * Text that can be copied to clipboard. - * - * @param text The text to display - */ - fun textCopyable(text: String) { - text(text) - onItemHover { - if (isMouseClicked(ImGuiMouseButton.Left)) { - setClipboardText(text) - } - } - } - - /** - * Formatted text (similar to printf). - * - * @param fmt Format string - * @param args Arguments for formatting - * - * @see printf() family functions - */ - fun textFmt(fmt: String, vararg args: Any) = text(fmt.format(*args)) - - /** - * Text with a bullet point. - * - * @param text The text to display - */ - fun bulletText(text: String) = ImGui.bulletText(text) - - /** - * Label with text aligned to the right. - * - * @param text The text to display - */ - fun textRightAligned(text: String) { - val width = calcTextSize(text).x - setCursorPosX(windowWidth - width - style.framePadding.x) - text(text) - } - - /** - * Creates a button. - * - * @param label The button text - * @param width Width of the button (0.0f = auto) - * @param height Height of the button (0.0f = auto) - * @param block Action to perform when clicked - */ - inline fun button(label: String, width: Float = 0f, height: Float = 0f, block: ProcedureBlock = {}) { - if (ImGui.button(label, width, height)) - block() - } - - /** - * Creates a small button. - * - * @param label The button text - * @param block Action to perform when clicked - */ - inline fun smallButton(label: String, block: ProcedureBlock = {}) { - if (ImGui.smallButton(label)) - block() - } - - /** - * Creates an invisible button. - * - * @param strId Unique identifier - * @param width Width of the button - * @param height Height of the button - * @param flags Button flags - * @param block Action to perform when clicked - */ - inline fun invisibleButton(strId: String, width: Float, height: Float, flags: Int = 0, block: ProcedureBlock = {}) { - if (ImGui.invisibleButton(strId, width, height, flags)) - block() - } - - /** - * Creates an arrow button. - * - * @param strId Unique identifier - * @param dir Direction of the arrow (default is None) - * @param block Action to perform when clicked - * - * @see ImGuiDir - */ - inline fun arrowButton(strId: String, dir: Int = ImGuiDir.None, block: ProcedureBlock = {}) { - if (ImGui.arrowButton(strId, dir)) - block() - } - - /** - * Creates a checkbox. - * - * @param label Label for the checkbox - * @param bool Boolean property to bind to - * @param block Action to perform when changed - */ - inline fun checkbox(label: String, bool: KMutableProperty0, block: ProcedureBlock = {}) = - withBool(bool) { checkbox(label, it, block) } - - /** - * Creates a checkbox. - * - * @param label Label for the checkbox - * @param bool ImBoolean to bind to - * @param block Action to perform if checked - */ - inline fun checkbox(label: String, bool: ImBoolean, block: ProcedureBlock = {}) { - if (ImGui.checkbox(label, bool)) block() - } - - /** - * Creates a radio button group. - * - * @param label Label for the group - * @param current Currently selected index - * @param items Items in the group - * @param block Action to perform when selection changes - */ - inline fun radioButtons( - label: String, - current: KMutableProperty0, - items: List>, - block: (T) -> Unit = {} - ) { - text(label) - indent() - for ((itemLabel, itemValue) in items) { - if (ImGui.radioButton(itemLabel, current.get() == itemValue)) { - current.set(itemValue) - block(itemValue) - } - sameLine() - } - unindent() - } - - /** - * Creates a single radio button. - * - * @param label Label for the button - * @param active Whether the button is active - * @param block Action to perform when clicked - */ - inline fun radioButton(label: String, active: Boolean, block: ProcedureBlock = {}) { - if (ImGui.radioButton(label, active)) block() - } - - inline fun combo( - label: String, - preview: String?, - flags: Int = ImGuiComboFlags.None, - block: () -> Unit = {}, - ) { - if (beginCombo(label, preview, flags)) { - block() - endCombo() - } - } - - /** - * Creates a combo box. - * - * @param label Label for the combo - * @param currentItem Currently selected index - * @param items Items in the combo - * @param heightInItems Height in items (-1 = auto) - * @param block Action to perform when selection changes - */ - inline fun combo( - label: String, - currentItem: KMutableProperty0, - items: Array, - heightInItems: Int = -1, - block: (ImInt) -> Unit = {}, - ) = withInt(currentItem) { combo(label, it, items, heightInItems, block) } - - inline fun combo( - label: String, - currentItem: KMutableProperty0, - items: Collection, - heightInItems: Int = -1, - block: (ImInt) -> Unit = {}, - ) = combo(label, currentItem, items.toTypedArray(), heightInItems, block) - - inline fun combo( - label: String, - currentItem: ImInt, - items: Array, - heightInItems: Int = -1, - block: (ImInt) -> Unit = {}, - ) { - if (ImGui.combo(label, currentItem, items, heightInItems)) - block(currentItem) - } - - inline fun combo( - label: String, - currentItem: ImInt, - items: Collection, - heightInItems: Int = -1, - block: (ImInt) -> Unit = {}, - ) = combo(label, currentItem, items.toTypedArray(), heightInItems, block) - - /** - * Creates a drag slider for float values. - * - * @param label Label for the slider - * @param value Current value - * @param vSpeed Speed of dragging - * @param vMin Minimum value - * @param vMax Maximum value - * @param format Display format - * @param flags Slider flags - * @param block Action to perform when value changes - */ - inline fun drag( - label: String, - value: KMutableProperty0, - vSpeed: Float = 1.0f, - vMin: Float = 0.0f, - vMax: Float = 0.0f, - format: String = "%.3f", - flags: Int = 0, - block: (ImFloat) -> Unit = {}, - ) = withFloat(value) { drag(label, it, vSpeed, vMin, vMax, format, flags, block) } - - inline fun drag( - label: String, - value: ImFloat, - vSpeed: Float = 1.0f, - vMin: Float = 0.0f, - vMax: Float = 0.0f, - format: String = "%.3f", - flags: Int = 0, - block: (ImFloat) -> Unit = {}, - ) { - if (dragFloat(label, value.data, vSpeed, vMin, vMax, format, flags)) - block(value) - } - - /** - * Creates a drag slider for int values. - * - * @param label Label for the slider - * @param value Current value - * @param vSpeed Speed of dragging - * @param vMin Minimum value - * @param vMax Maximum value - * @param format Display format - * @param flags Slider flags - * @param block Action to perform when value changes - */ - inline fun drag( - label: String, - value: KMutableProperty0, - vSpeed: Float = 1.0f, - vMin: Int = 0, - vMax: Int = 0, - format: String = "%d", - flags: Int = 0, - block: (ImInt) -> Unit = {}, - ) = withInt(value) { drag(label, it, vSpeed, vMin, vMax, format, flags, block) } - - inline fun drag( - label: String, - value: ImInt, - vSpeed: Float = 1.0f, - vMin: Int = 0, - vMax: Int = 0, - format: String = "%d", - flags: Int = 0, - block: (ImInt) -> Unit = {}, - ) { - if (dragInt(label, value.data, vSpeed, vMin, vMax, format, flags)) - block(value) - } - - /** - * Creates a slider for float values. - * - * @param label Label for the slider - * @param value Current value - * @param vMin Minimum value - * @param vMax Maximum value - * @param format Display format - * @param flags Slider flags - * @param block Action to perform when value changes - */ - inline fun slider( - label: String, - value: KMutableProperty0, - vMin: Float, - vMax: Float, - format: String = "%.3f", - flags: Int = 0, - block: (ImFloat) -> Unit = {}, - ) = withFloat(value) { slider(label, it, vMin, vMax, format, flags, block) } - - inline fun slider( - label: String, - value: ImFloat, - vMin: Float, - vMax: Float, - format: String = "%.3f", - flags: Int = 0, - block: (ImFloat) -> Unit = {}, - ) { - if (sliderFloat(label, value.data, vMin, vMax, format, flags)) - block(value) - } - - /** - * Creates a slider for int values. - * - * @param label Label for the slider - * @param value Current value - * @param vMin Minimum value - * @param vMax Maximum value - * @param format Display format - * @param flags Slider flags - * @param block Action to perform when value changes - */ - inline fun slider( - label: String, - value: KMutableProperty0, - vMin: Int, - vMax: Int, - format: String = "%d", - flags: Int = 0, - block: (ImInt) -> Unit = {}, - ) = withInt(value) { slider(label, it, vMin, vMax, format, flags, block) } - - inline fun slider( - label: String, - value: ImInt, - vMin: Int, - vMax: Int, - format: String = "%d", - flags: Int = 0, - block: (ImInt) -> Unit = {}, - ) { - if (sliderInt(label, value.data, vMin, vMax, format, flags)) - block(value) - } - - /** - * Creates a single integer input field. - * - * @param label Label for the input - * @param value Current integer value - * @param step Step for increment/decrement - * @param stepFast Fast step for increment/decrement - * @param flags Input flags - * @param block Action to perform when value changes - */ - inline fun inputInt( - label: String, - value: KMutableProperty0, - step: Int = 1, - stepFast: Int = 100, - flags: Int = 0, - block: (ImInt) -> Unit = {} - ) = withInt(value) { inputInt(label, it, step, stepFast, flags, block) } - - inline fun inputInt( - label: String, - value: ImInt, - step: Int = 1, - stepFast: Int = 100, - flags: Int = 0, - block: (ImInt) -> Unit = {} - ) { - if (ImGui.inputInt(label, value, step, stepFast, flags)) - block(value) - } - - /** - * Creates a 2-component integer input field. - * - * @param label Label for the input - * @param values Current integer values (will be modified) - * @param flags Input flags - * @param block Action to perform when values change - */ - inline fun inputInt2( - label: String, - values: IntArray, - flags: Int = 0, - block: (IntArray) -> Unit = {} - ) { - if (ImGui.inputInt2(label, values, flags)) - block(values) - } - - /** - * Creates a 3-component integer input field. - * - * @param label Label for the input - * @param values Current integer values (will be modified) - * @param flags Input flags - * @param block Action to perform when values change - */ - inline fun inputInt3( - label: String, - values: IntArray, - flags: Int = ImGuiInputTextFlags.None, - block: (IntArray) -> Unit = {} - ) { - if (ImGui.inputInt3(label, values, flags)) - block(values) - } - - inline fun inputVec3i( - label: String, - vec: Vec3i, - flags: Int = ImGuiInputTextFlags.None, - block: (Vec3i) -> Unit = {} - ) { - val ints = intArrayOf(vec.x, vec.y, vec.z) - - if (ImGui.inputInt3(label, ints, flags)) - block(Vec3i(ints[0], ints[1], ints[2])) - } - - /** - * Creates a 4-component integer input field. - * - * @param label Label for the input - * @param values Current integer values (will be modified) - * @param flags Input flags - * @param block Action to perform when values change - */ - inline fun inputInt4( - label: String, - values: IntArray, - flags: Int = ImGuiInputTextFlags.None, - block: (IntArray) -> Unit = {} - ) { - if (ImGui.inputInt4(label, values, flags)) - block(values) - } - - /** - * Creates a single float input field. - * - * @param label Label for the input - * @param value Current float value - * @param step Step for increment/decrement - * @param stepFast Fast step for increment/decrement - * @param format Display format string - * @param flags Input flags - * @param block Action to perform when value changes - */ - inline fun inputFloat( - label: String, - value: KMutableProperty0, - step: Float = 0f, - stepFast: Float = 0f, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (ImFloat) -> Unit = {} - ) = withFloat(value) { inputFloat(label, it, step, stepFast, decimals, format, flags, block) } - - inline fun inputFloat( - label: String, - value: ImFloat, - step: Float = 0f, - stepFast: Float = 0f, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (ImFloat) -> Unit = {} - ) { - if (inputFloat(label, value, step, stepFast, format, flags)) - block(value) - } - - /** - * Creates a 2-component float input field. - * - * @param label Label for the input - * @param values Current float values (will be modified) - * @param format Display format string - * @param flags Input flags - * @param block Action to perform when values change - */ - inline fun inputFloat2( - label: String, - values: FloatArray, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (FloatArray) -> Unit = {} - ) { - if (inputFloat2(label, values, format, flags)) - block(values) - } - - inline fun inputVec2f( - label: String, - vec: Vec2f, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (Vec2f) -> Unit = {} - ) { - val floats = floatArrayOf(vec.x, vec.y) - - if (inputFloat2(label, floats, format, flags)) - block(Vec2f(floats[0], floats[1])) - } - - /** - * Creates a 3-component float input field. - * - * @param label Label for the input - * @param values Current float values (will be modified) - * @param format Display format string - * @param flags Input flags - * @param block Action to perform when values change - */ - inline fun inputFloat3( - label: String, - values: FloatArray, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (FloatArray) -> Unit = {} - ) { - if (inputFloat3(label, values, format, flags)) - block(values) - } - - /** - * Creates a 4-component float input field. - * - * @param label Label for the input - * @param values Current float values (will be modified) - * @param format Display format string - * @param flags Input flags - * @param block Action to perform when values change - */ - inline fun inputFloat4( - label: String, - values: FloatArray, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (FloatArray) -> Unit = {} - ) { - if (inputFloat4(label, values, format, flags)) - block(values) - } - - /** - * Creates a single double input field. - * - * @param label Label for the input - * @param value Current double value - * @param step Step for increment/decrement - * @param stepFast Fast step for increment/decrement - * @param format Display format string - * @param flags Input flags - * @param block Action to perform when value changes - */ - inline fun inputDouble( - label: String, - value: KMutableProperty0, - step: Double = 0.0, - stepFast: Double = 0.0, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (Double) -> Unit = {}, - ) = withDouble(value) { - if (inputDouble(label, it, step, stepFast, format, flags)) { - value.set(it.get()) - block(it.get()) - } - } - - /** - * Creates a [Vec2d] input field. - * - * @param label Label for the input - * @param vec Current float values (will be modified) - * @param format Display format string - * @param flags Input flags - * @param block Action to perform when values change - */ - inline fun inputVec2d( - label: String, - vec: Vec2d, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (Vec2d) -> Unit = {}, - ) { - val doubles = floatArrayOf(vec.x.toFloat(), vec.y.toFloat()) - - if (inputFloat3(label, doubles, format, flags)) - block(Vec2d(doubles[0], doubles[1])) - } - - /** - * Creates a [Vec3d] input field. - * - * @param label Label for the input - * @param vec Current float values (will be modified) - * @param format Display format string - * @param flags Input flags - * @param block Action to perform when values change - */ - inline fun inputVec3d( - label: String, - vec: Vec3d, - decimals: Int = 2, - format: String = "%.${decimals}f", - flags: Int = ImGuiInputTextFlags.None, - block: (Vec3d) -> Unit = {}, - ) { - val doubles = floatArrayOf(vec.x.toFloat(), vec.y.toFloat(), vec.z.toFloat()) - - if (inputFloat3(label, doubles, format, flags)) - block(Vec3d(doubles[0].toDouble(), doubles[1].toDouble(), doubles[2].toDouble())) - } - - /** - * Creates a text input field. - * - * @param label Label for the input - * @param value Current text value - * @param flags Input flags - * @param block Action to perform when text changes - * - * @see ImGuiInputTextFlags - */ - inline fun inputText( - label: String, - value: KMutableProperty0, - flags: Int = ImGuiInputTextFlags.None, - block: (ImString) -> Unit = {}, - ) = withString(value) { inputText(label, it, flags, block) } - - inline fun inputText( - label: String, - value: ImString, - flags: Int = ImGuiInputTextFlags.None, - block: (ImString) -> Unit = {}, - ) { - if (ImGui.inputText(label, value, flags)) - block(value) - } - - /** - * Creates a multi-line text input field with optional size constraints. - * - * @param label Label displayed for the input field - * @param value Mutable string property that holds the current text value - * @param width Width of the input field in pixels (0.0f = auto-resize) - * @param height Height of the input field in pixels (0.0f = auto-resize) - * @param flags Additional input flags - * @param block Optional callback that executes when the text changes, - * providing access to the underlying ImString - * - * @see ImGuiInputTextFlags - */ - inline fun inputTextMultiline( - label: String, - value: KMutableProperty0, - width: Float = 0f, - height: Float = 0f, - flags: Int = 0, - block: (ImString) -> Unit = {}, - ) = withString(value) { inputTextMultiline(label, it, width, height, flags, block) } - - inline fun inputTextMultiline( - label: String, - value: ImString, - width: Float = 0f, - height: Float = 0f, - flags: Int = 0, - block: (ImString) -> Unit = {}, - ) { - if (ImGui.inputTextMultiline(label, value, width, height, flags)) - block(value) - } - - /** - * Color button and picker combined - */ - inline fun colorEdit( - label: String, - color: KMutableProperty0, - flags: Int = ImGuiColorEditFlags.None, - block: (Color) -> Unit = {}, - ) { - val default = floatArrayOf(0f, 0f, 0f, 0f) - val col = color.get() - val components = col.getComponents(default) - - if (colorEdit4(label, components)) { - val (r, g, b, a) = components - - color.set(Color(r, g, b, a)) - block(col) - } - } - - /** - * Creates a color picker. - * - * @param label Label for the picker - * @param color Current color value - * @param flags Picker flags - * @param block Action to perform when color changes - * - * @see ImGuiColorEditFlags - */ - @JvmName("colorPickerReference") - inline fun colorPicker( - label: String, - color: KMutableProperty0, - flags: Int = ImGuiColorEditFlags.None, - block: (Color) -> Unit = {}, - ) { - val default = floatArrayOf(0f, 0f, 0f, 0f) - val col = color.get() - val components = col.getComponents(default) - - if (colorPicker4(label, components, flags)) { - val (r, g, b, a) = components - - color.set(Color(r, g, b, a)) - block(col) - } - } - - inline fun colorPicker( - label: String, - color: KMutableProperty0, - flags: Int = ImGuiColorEditFlags.None, - block: (FloatArray) -> Unit = {}, - ) { - val col = color.get() - if (colorPicker4(label, col, flags)) { - color.set(col) - block(col) - } - } - - /** - * Creates a color button. - * - * @param descId Description ID - * @param color Color value - * @param flags Button flags - * @param block Action to perform when clicked - * - * @see ImGuiColorEditFlags - */ - inline fun colorButton( - descId: String, - color: Color, - flags: Int = ImGuiColorEditFlags.None, - block: ProcedureBlock = {} - ) { - val floats = floatArrayOf(0f, 0f, 0f, 0f) - val (r, g, b, a) = color.getColorComponents(floats) - - if (colorButton(descId, r, g, b, a, flags)) - block() - } - - /** - * Creates a tree node. - * - * @param label Label for the node - * @param block Content of the node when expanded - */ - inline fun treeNode(label: String, block: ProcedureBlock) { - if (treeNode(label)) { - block() - treePop() - } - } - - /** - * Creates a tree node with a unique ID. - * - * @param label Label for the node - * @param id Unique identifier - * @param block Content of the node when expanded - */ - inline fun treeNode(label: String, id: String, block: ProcedureBlock) { - if (treeNode(id, label)) { - block() - treePop() - } - } - - /** - * Creates a collapsing header. - * - * @param label Label for the header - * @param flags TreeNode flags - * @param block Content of the header when expanded - * - * @see ImGuiTreeNodeFlags - */ - inline fun collapsingHeader(label: String, flags: Int = ImGuiTreeNodeFlags.None, block: ProcedureBlock) { - if (collapsingHeader(label, flags)) - block() - } - - /** - * Creates a text filer - */ - inline fun filter(label: String, defaultFilter: String = "", block: (ImGuiTextFilter) -> Unit) = - ImGuiTextFilter(defaultFilter).apply { draw(label) }.apply(block) - - /** - * Creates a selectable item. - * - * @param label Label for the item - * @param selected Whether the item is selected - * @param flags Selectable flags - * @param size Size of the item - * @param block Action to perform when clicked - * - * @see ImGuiSelectableFlags - */ - inline fun selectable( - label: String, - selected: Boolean = false, - flags: Int = ImGuiSelectableFlags.None, - size: ImVec2 = ImVec2(), - block: ProcedureBlock = {}, - ) { - if (ImGui.selectable(label, selected, flags, size)) - block() - } - - /** - * Creates a list box. - * - * @param label Label for the list - * @param currentItem Currently selected index - * @param items Items in the list - * @param heightInItems Height in items (-1 = auto) - */ - fun listBox( - label: String, - currentItem: KMutableProperty0, - items: Array, - heightInItems: Int = -1, - ) = withInt(currentItem) { listBox(label, it, items, heightInItems) } - - fun listBox( - label: String, - currentItem: KMutableProperty0, - items: Collection, - heightInItems: Int = -1, - ) = listBox(label, currentItem, items.toTypedArray(), heightInItems) - - fun listBox( - label: String, - currentItem: ImInt, - items: Array, - heightInItems: Int = -1, - ) = ImGui.listBox(label, currentItem, items, heightInItems) - - fun listBox( - label: String, - currentItem: ImInt, - items: Collection, - heightInItems: Int = -1, - ) = listBox(label, currentItem, items.toTypedArray(), heightInItems) - - /** - * Creates a plot of float values. - * - * @param label Label for the plot - * @param values Values to plot - * @param valuesOffset Offset in the values array - * @param overlayText Text to overlay - * @param scaleMin Minimum scale value - * @param scaleMax Maximum scale value - * @param graphSize Size of the graph - * @param stride Sample decimation step (>= 1). Use 0/1 for contiguous data. - */ - fun plotLines( - label: String, - values: FloatArray, - valuesOffset: Int = 0, - overlayText: String = "", - scaleMin: Float = Float.MAX_VALUE, - scaleMax: Float = Float.MAX_VALUE, - graphSize: ImVec2 = ImVec2(), - stride: Int = 0, - ) { - val (src, sMin, sMax) = preparePlotSeries(values, stride, scaleMin, scaleMax) - val count = src.size - val offset = if (count == 0) 0 else valuesOffset.coerceIn(0, count - 1) - if (count < 2) { - plotLines(label, floatArrayOf(), 0, 0, overlayText, sMin, sMax, graphSize.x, graphSize.y) - return - } - plotLines(label, src, count, offset, overlayText, sMin, sMax, graphSize.x, graphSize.y) - } - - /** - * Creates a plot of histogram values. - * - * @param label Label for the plot - * @param values Values to plot - * @param valuesOffset Offset in the values array - * @param overlayText Text to overlay - * @param scaleMin Minimum scale value - * @param scaleMax Maximum scale value - * @param graphSize Size of the graph - * @param stride Sample decimation step (>= 1). Use 0/1 for contiguous data. - */ - fun plotHistogram( - label: String, - values: FloatArray, - valuesOffset: Int = 0, - overlayText: String = "", - scaleMin: Float = Float.MAX_VALUE, - scaleMax: Float = Float.MAX_VALUE, - graphSize: ImVec2 = ImVec2(), - stride: Int = 0, - ) { - val (src, sMin, sMax) = preparePlotSeries(values, stride, scaleMin, scaleMax) - val count = src.size - val offset = if (count == 0) 0 else valuesOffset.coerceIn(0, count - 1) - if (count < 1) { - plotHistogram(label, floatArrayOf(), 0, 0, overlayText, sMin, sMax, graphSize.x, graphSize.y) - return - } - plotHistogram(label, src, count, offset, overlayText, sMin, sMax, graphSize.x, graphSize.y) - } - - private fun preparePlotSeries( - values: FloatArray, - stride: Int, - scaleMin: Float, - scaleMax: Float - ): Triple { - val contiguous = (stride <= 1) - val src = if (contiguous) { - values - } else { - val outSize = (values.size + stride - 1) / stride - val out = FloatArray(outSize) - var i = 0 - var j = 0 - while (i < values.size) { - out[j++] = values[i] - i += stride - } - out - } - var sMin = scaleMin - var sMax = scaleMax - if (sMin == Float.MAX_VALUE && sMax == Float.MAX_VALUE) { - var minV = Float.POSITIVE_INFINITY - var maxV = Float.NEGATIVE_INFINITY - for (v in src) if (v.isFinite()) { - if (v < minV) minV = v - if (v > maxV) maxV = v - } - if (!minV.isFinite() || !maxV.isFinite()) { - minV = 0f; maxV = 1f - } - if (minV == maxV) { - val base = if (minV == 0f) 1f else kotlin.math.abs(minV) - val pad = base * 0.01f - minV -= pad - maxV += pad - } - sMin = minV - sMax = maxV - } - return Triple(src, sMin, sMax) - } - - /** - * Creates a main menu bar. - * - * @param block Content of the menu bar - */ - inline fun mainMenuBar(block: ProcedureBlock) { - if (beginMainMenuBar()) { - block() - endMainMenuBar() - } - } - - /** - * Append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). - * - * @param block Content of the menu bar - */ - inline fun menuBar(block: ProcedureBlock) { - if (beginMenuBar()) { - block() - endMenuBar() - } - } - - /** - * Create a sub-menu entry. - * - * @param label Label for the menu - * @param enabled Whether the menu is enabled - * @param block Content of the menu - */ - inline fun menu(label: String, enabled: Boolean = true, block: ProcedureBlock) { - if (beginMenu(label, enabled)) { - block() - endMenu() - } - } - - /** - * Creates an item in the sub-menu - * - * Shortcuts are displayed for convenience but not processed by ImGui at the moment. - * - * @param label Label for the item - * @param shortcut Shortcut text - * @param selected Whether the item is selected - * @param enabled Whether the item is enabled - * @param block Action to perform when clicked - */ - inline fun menuItem( - label: String, - shortcut: String = "", - selected: Boolean = false, - enabled: Boolean = true, - block: ProcedureBlock = {}, - ) { - if (ImGui.menuItem(label, shortcut, selected, enabled)) - block() - } - - /** - * Creates a tooltip window. - * - * @param block Content of the tooltip - */ - inline fun tooltip(block: ProcedureBlock) { - beginTooltip() - block() - endTooltip() - } - - /** - * Displays a tooltip with the specified description when the current ImGui item is hovered. - * - * @param description The text content to display in the tooltip. - */ - fun lambdaTooltip(description: String) { - if (description.isBlank()) return - onItemHover(ClickGuiLayout.tooltipType.flag) { - tooltip { - withTextWrapPos(fontSize * 35f) { - textUnformatted(description) - } - } - } - } - - fun lambdaTooltip(description: () -> String) { - lambdaTooltip(description()) - } - - fun openPopup(strId: String, flags: Int = ImGuiPopupFlags.None) = - ImGui.openPopup(strId, flags) - - /** - * Returns whether the popup identified by [strId] is currently open. - * - * The id is resolved against the current window, matching [openPopup] and the `popupContext*` helpers. - */ - fun isPopupOpen(strId: String, flags: Int = ImGuiPopupFlags.None): Boolean = - ImGui.isPopupOpen(strId, flags) - - /** - * Closes the popup currently being built. Must be called from inside a `popup*` block. - */ - fun closeCurrentPopup() = ImGui.closeCurrentPopup() - - /** - * Creates a popup. You must first call [openPopup] with the same [strId] - * - * @param strId Unique identifier - * @param flags Popup flags - * @param block Content of the popup - */ - inline fun popup(strId: String, flags: Int = ImGuiPopupFlags.AnyPopup, block: ProcedureBlock) { - if (beginPopup(strId, flags)) { - block() - endPopup() - } - } - - /** - * Creates a context popup for an item. - * - * @param strId Unique identifier - * @param popupFlags Popup flags - * @param block Content of the popup - */ - inline fun popupContextItem( - strId: String = "", - popupFlags: Int = ImGuiPopupFlags.MouseButtonRight, - block: ProcedureBlock - ) { - if (beginPopupContextItem(strId, popupFlags)) { - block() - endPopup() - } - } - - /** - * Creates a context popup for a window. - * - * @param strId Unique identifier - * @param popupFlags Popup flags - * @param block Content of the popup - */ - inline fun popupContextWindow( - strId: String = "", - popupFlags: Int = ImGuiPopupFlags.MouseButtonRight, - block: ProcedureBlock - ) { - if (beginPopupContextWindow(strId, popupFlags)) { - block() - endPopup() - } - } - - /** - * Creates a context popup in empty space. - * - * @param strId Unique identifier - * @param popupFlags Popup flags - * @param block Content of the popup - */ - inline fun popupContextVoid( - strId: String = "", - popupFlags: Int = ImGuiPopupFlags.MouseButtonRight, - block: ProcedureBlock - ) { - if (beginPopupContextVoid(strId, popupFlags)) { - block() - endPopup() - } - } - - /** - * Creates a modal popup. - * - * @param title Title of the modal - * @param value Boolean reference to control visibility - * @param windowFlags Additional window flags - * @param block Content of the modal - * - * @see ImGuiPopupFlags - */ - inline fun popupModal( - title: String, - value: KMutableProperty0, - windowFlags: Int = ImGuiWindowFlags.None, - block: ProcedureBlock, - ) { - if (withBool(value) { beginPopupModal(title, it, windowFlags) }) { - block() - endPopup() - } - } - - inline fun popupModal( - title: String, - windowFlags: Int = ImGuiWindowFlags.None, - block: ProcedureBlock, - ) { - if (beginPopupModal(title, windowFlags)) { - block() - endPopup() - } - } - - /** - * Creates a tab bar. - * - * @param strId Unique identifier - * @param flags Tab bar flags - * @param block Content of the tab bar - * - * @see ImGuiTabBarFlags - */ - inline fun tabBar(strId: String, flags: Int = ImGuiTabBarFlags.None, block: ProcedureBlock) { - if (beginTabBar(strId, flags)) { - block() - endTabBar() - } - } - - /** - * Creates a tab item. - * - * @param label Label for the tab - * @param value Boolean reference to control visibility - * @param flags Tab item flags - * @param block Content of the tab - * - * @see ImGuiTabBarFlags - */ - inline fun tabItem( - label: String, - value: KMutableProperty0, - flags: Int = 0, - block: ProcedureBlock, - ) { - if (withBool(value) { beginTabItem(label, it, flags) }) { - block() - endTabItem() - } - } - - inline fun tabItem( - label: String, - flags: Int = ImGuiTabBarFlags.None, - block: ProcedureBlock, - ) { - if (beginTabItem(label, flags)) { - block() - endTabItem() - } - } - - /** - * Creates a drag and drop source. - * - * @param flags Drag and drop flags - * @param block Content of the source - */ - inline fun dragDropSource(flags: Int = 0, block: ProcedureBlock) { - if (beginDragDropSource(flags)) { - block() - endDragDropSource() - } - } - - /** - * Creates a drag and drop target. - * - * You can call AcceptDragDropPayload() in the [block] - * - * @param block Content of the target - */ - inline fun dragDropTarget(block: ProcedureBlock) { - if (beginDragDropTarget()) { - block() - endDragDropTarget() - } - } - - /** - * Places the next item on the same line. - * - * @param offsetFromStartX Offset from the start - * @param spacing Spacing between items - */ - fun sameLine(offsetFromStartX: Float = 0f, spacing: Float = -1f) = - ImGui.sameLine(offsetFromStartX, spacing) - - /** - * Adds vertical spacing. - */ - fun spacing() = ImGui.spacing() - - /** - * Adds a separator line. - */ - fun separator() = ImGui.separator() - - /** - * Indents the next widgets. - * @param indentWidth Width of the indent - */ - fun indent(indentWidth: Float = 0f) = ImGui.indent(indentWidth) - - /** - * Unindents the next widgets. - * @param indentWidth Width of the unindent - */ - fun unindent(indentWidth: Float = 0f) = ImGui.unindent(indentWidth) - - /** - * Groups the next widgets together. - * - * @param block Content of the group - */ - inline fun group(block: ProcedureBlock) { - beginGroup() - block() - endGroup() - } - - /** - * Creates a new line. - */ - fun newLine() = ImGui.newLine() - - /** - * Moves to the next column (in a columns layout). - */ - fun nextColumn() = ImGui.nextColumn() - - /** - * Sets the scroll position. - * - * @param x Horizontal scroll position ratio - * @param y Vertical scroll position ratio - */ - fun setScrollHere(x: Float = 0.5f, y: Float = 0.5f) { - setScrollHereX(x) - setScrollHereY(y) - } - - /** - * Sets the vertical scroll position. - * - * @param y Vertical scroll position ratio - */ - fun setScrollHereY(y: Float = 0.5f) = ImGui.setScrollHereY(y) - - /** - * Sets the horizontal scroll position. - * @param centerXRatio Ratio for centering - */ - fun setScrollHereX(centerXRatio: Float = 0.5f) = ImGui.setScrollHereX(centerXRatio) - - /** - * Push integer into the ID stack (will hash integer). - * - * @param id Integer ID - * @param block Content of the scope - */ - inline fun withId(id: Int, block: ProcedureBlock) { - pushID(id) - block() - popID() - } - - /** - * Push string into the ID stack (will hash string). - * - * @param id String ID - * @param block Content of the scope - */ - inline fun withId(id: String, block: ProcedureBlock) { - pushID(id) - block() - popID() - } - - /** - * Push integer into the ID stack (will hash integer). - * - * @param id Enum ID (uses ordinal) - * @param block Content of the scope - */ - inline fun > withId(id: E, block: ProcedureBlock) { - pushID(id.ordinal) - block() - popID() - } - - /** - * Creates a scope with custom style colors. - * - * @param idx Color index (see ImGuiCol) - * @param col Color value (RGB) - * @param block Content of the scope - * - * See: https://github.com/ocornut/imgui/wiki/Styling - */ - inline fun withStyleColor(idx: Int, col: Int, block: ProcedureBlock) { - pushStyleColor(idx, col) - block() - popStyleColor() - } - - inline fun withStyleColor(idx: Int, color: Color, block: ProcedureBlock) = - withStyleColor(idx, color.rgb, block) - - inline fun withStyleColor(idx: Int, red: Float, green: Float, blue: Float, alpha: Float, block: ProcedureBlock) { - pushStyleColor(idx, red, green, blue, alpha) - block() - popStyleColor() - } - - inline fun withStyleColor(idx: Int, color: FloatArray, block: ProcedureBlock) { - pushStyleColor(idx, color[0], color[1], color[2], color[3]) - block() - popStyleColor() - } - - inline fun withStyleColor(idx: Int, red: Int, green: Int, blue: Int, alpha: Int, block: ProcedureBlock) { - pushStyleColor(idx, red, green, blue, alpha) - block() - popStyleColor() - } - - /** - * Creates a scope with custom style variables. - * - * @param styleVar Style variable index - * @param value Float value - * @param block Content of the scope - * - * @see com.lambda.imgui.flag.ImGuiStyleVar - */ - inline fun withStyleVar(styleVar: Int, value: Float, block: ProcedureBlock) { - pushStyleVar(styleVar, value) - block() - popStyleVar() - } - - /** - * Creates a scope with custom style variables. - * - * @param styleVar Style variable index - * @param valueX First float value - * @param valueY Second float value - * @param block Content of the scope - * - * * @see imgui.flag.ImGuiStyleVar - */ - inline fun withStyleVar(styleVar: Int, valueX: Float, valueY: Float, block: ProcedureBlock) { - pushStyleVar(styleVar, valueX, valueY) - block() - popStyleVar() - } - - /** - * Push width of items for common large "item+label" widgets. - * - * - if >0.0f: width in pixels - * - if <0.0f align xx pixels to the right of window - * - * (so -1.0f always align width to the right side). - * - * @param itemWidth Width in pixels - * @param block Content of the scope - */ - inline fun withItemWidth(itemWidth: Int, block: ProcedureBlock) = withItemWidth(itemWidth.toFloat(), block) - - inline fun withItemWidth(itemWidth: Float, block: ProcedureBlock) { - pushItemWidth(itemWidth) - block() - popItemWidth() - } - - /** - * Push Word-wrapping positions for Text*() commands. - * - if <0.0f: no wrapping - * - if 0.0f: wrap to end of window (or column) - * - if >0.0f: wrap at 'wrap_posX' position in window local space - * - * @param wrapPos Position to wrap at - * @param block Content of the scope - */ - inline fun withTextWrapPos(wrapPos: Float = 0f, block: ProcedureBlock) { - pushTextWrapPos(wrapPos) - block() - popTextWrapPos() - } - - /** - * Creates a scope with custom font. - * - * @param font Font to use - * @param block Content of the scope - */ - inline fun withFont(font: ImFont, block: ProcedureBlock) { - pushFont(font) - block() - popFont() - } - - inline fun withBool(property: KMutableProperty0, block: WrappedBlock) = - ImBoolean(property()).let { v -> block(v).also { property.set(v.get()) } } - - inline fun withBool(value: Boolean, block: WrappedBlock) = - block(ImBoolean(value)) - - inline fun withFloat(value: Float, block: WrappedBlock) = - block(ImFloat(value)) - - inline fun withDouble(value: Double, block: WrappedBlock) = - block(ImDouble(value)) - - inline fun withDouble(property: KMutableProperty0, block: WrappedBlock) = - ImDouble(property()).let { v -> block(v).also { property.set(v.get()) } } - - inline fun withFloat(property: KMutableProperty0, block: WrappedBlock) = - ImFloat(property()).let { v -> block(v).also { property.set(v.get()) } } - - inline fun withInt(property: KMutableProperty0, block: WrappedBlock) = - ImInt(property()).let { v -> block(v).also { property.set(v.get()) } } - - inline fun withVec2(value: Vec2d, block: WrappedBlock) = - block(ImVec2(value.x.toFloat(), value.y.toFloat())) - - inline fun withVec2(x: Double, y: Double, block: WrappedBlock) = - block(ImVec2(x.toFloat(), y.toFloat())) - - inline fun withVec2(x: Float, y: Float, block: WrappedBlock) = - block(ImVec2(x, y)) - - inline fun withString( - property: KMutableProperty0, - allowedChars: String = "", - isResizable: Boolean = true, - size: Int = 10, - block: WrappedBlock, - ) { - val string = ImString(property()) - string.inputData.allowedChars = allowedChars - string.inputData.isResizable = isResizable - string.inputData.resizeFactor = size - - block(string) - - property.set(string.get()) - } - - /** - * Gets the current draw list for custom drawing. - */ - val windowDrawList: ImDrawList get() = getWindowDrawList() - - /** - * Gets the background draw list for custom drawing. - */ - val backgroundDrawList: ImDrawList get() = getBackgroundDrawList() - - /** - * Gets the foreground draw list for custom drawing. - */ - val foregroundDrawList: ImDrawList get() = getForegroundDrawList() - - /** - * Represents the minimum X-coordinate of the current item's rectangle in the UI. - * - * This value is typically used to calculate the dimensions or positioning - * of graphical elements relative to the current UI item. - */ - val itemRectMinX: Float get() = getItemRectMinX() - - val itemRectMinY: Float get() = getItemRectMinY() - - val itemRectMaxX: Float get() = getItemRectMaxX() - - val itemRectMaxY: Float get() = getItemRectMaxY() - - val frameHeight: Float get() = getFrameHeight() - - val frameHeightWithSpacing: Float get() = getFrameHeightWithSpacing() - - val windowContentRegionMaxX: Float get() = getWindowContentRegionMaxX() - - val windowContentRegionMaxY: Float get() = getWindowContentRegionMaxY() - - /** - * Creates a frame with optional border. - */ - fun ImDrawList.addFrame( - minX: Float, - minY: Float, - maxX: Float, - maxY: Float, - col: Int, - border: Boolean = true, - rounding: Float = getStyle().frameRounding - ) { - addRectFilled(minX, minY, maxX, maxY, col, rounding) - - val borderSize = getStyle().frameBorderSize - - if (border && borderSize > 0) { - addRect( - minX + 1f, minY + 1f, maxX + 1f, maxY + 1f, - getColorU32(ImGuiCol.BorderShadow), rounding, ImDrawListFlags.None, borderSize - ) - - addRect( - minX, minY, maxX, maxY, - getColorU32(ImGuiCol.Border), rounding, ImDrawListFlags.None, borderSize - ) - } - } - - var cursorPosX: Float get() = getCursorPosX(); set(value) { - setCursorPosX(value) - } - - var cursorPosY: Float get() = getCursorPosY(); set(value) { - setCursorPosY(value) - } - - fun imageHorizontallyCentered(textureId: Long, width: Float, height: Float) { - val contentW = getContentRegionAvail().x - val offsetX = (contentW - width) * 0.5f - cursorPosX += maxOf(0f, offsetX) - image(textureId, width, height) - } - - fun buildLayout(block: ProcedureBlock) { - block() - } -} diff --git a/src/main/kotlin/com/lambda/gui/dsl/ImStorageDsl.kt b/src/main/kotlin/com/lambda/gui/dsl/ImStorageDsl.kt deleted file mode 100644 index 0c8e3cb4d..000000000 --- a/src/main/kotlin/com/lambda/gui/dsl/ImStorageDsl.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui.dsl - -import com.lambda.imgui.ImGui.getID -import com.lambda.imgui.ImGui.getStateStorage -import com.lambda.imgui.ImGuiStorage -import kotlin.properties.ReadWriteProperty -import kotlin.reflect.KProperty - -object ImStorageDsl { - /** - * Returns a hash of a string for the [ImGuiStorage] - */ - val String.imHash: Int get() = getID(this) - - /** - * Current persistent per-window storage (store e.g. tree node open/close state) - */ - val storage: ImGuiStorage get() = getStateStorage() - - inline fun get(hash: Int, default: T) = - when (T::class) { - Boolean::class -> storage.getBool(hash, default as Boolean) - Int::class -> storage.getInt(hash, default as Int) - Float::class -> storage.getFloat(hash, default as Float) - else -> throw IllegalStateException("Unknown type '${T::class}'") - } as T - - inline fun set(hash: Int, value: T) = - when (T::class) { - Boolean::class -> storage.setBool(hash, value as Boolean) - Int::class -> storage.setInt(hash, value as Int) - Float::class -> storage.setFloat(hash, value as Float) - else -> throw IllegalStateException("Unknown type '${T::class}'") - } - - inline fun imProperty(str: String, default: T) = object : ReadWriteProperty { - // There is something I don't quite understand about kotlin typing 'smart' inference. - // If you don't provide a value of type T, the compiler panics and uses a type that isn't of type T (??) - override fun getValue(thisRef: Any?, property: KProperty<*>): T = get(str.imHash, default) - override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = set(str.imHash, value) - } -} diff --git a/src/main/kotlin/com/lambda/gui/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt new file mode 100644 index 000000000..ab09ddc2f --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -0,0 +1,142 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.hud + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.layout +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.unit.dp +import com.lambda.Lambda.mc +import com.lambda.config.Config +import com.lambda.config.categories.HudCategory +import com.lambda.core.Loadable +import com.lambda.gui.GuiScreen +import com.lambda.gui.component.Text +import com.lambda.gui.component.shadowed +import com.lambda.gui.core.observe +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Type +import com.lambda.module.HudModule +import com.lambda.module.ModuleRegistry +import com.lambda.util.math.toCompose +import kotlin.math.roundToInt + +private val HUD_TEXT_SHADOW = Color.Black.copy(alpha = 0.75f) +private val ELEMENT_PADDING = 1.dp + +object HudConfig : Loadable, Config("HUD", HudCategory) { + val showInScreens by setting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The HUD editor always shows them.") + val textColor by setting("Text Color", java.awt.Color.WHITE, "Colour of HUD text") + val scale by setting("Scale", 1f, 0.5f..3f, 0.05f, "Size of HUD text") +} + +internal object Hud { + val modules: List by lazy { ModuleRegistry.modules.filterIsInstance() } + + val enabled: List + get() = modules.filter { it.isEnabled } + + val shown: List + get() { + val screen = mc.currentScreen + val covered = screen != null && screen !is GuiScreen && !HudConfig.showInScreens + return if (mc.world == null || mc.options.hudHidden || covered) emptyList() + else enabled + } +} + +@Composable +internal fun HudLayer(editor: HudEditorState? = null) { + val shown by observe { + if (editor != null) Hud.enabled + else Hud.shown + } + Box(Modifier.fillMaxSize()) { + shown.forEach { hud -> + key(hud) { HudElement(hud, editor) } + } + } +} + +@Composable +private fun HudElement(hud: HudModule, editor: HudEditorState?) { + val anchor by observe { Offset(hud.anchorX, hud.anchorY) } + val background by observe { hud.backgroundColor.value.toCompose() } + var empty by remember { mutableStateOf(false) } + if (editor != null) DisposableEffect(hud) { + onDispose { editor.bounds -= hud } + } + + Box( + Modifier + .layout { measurable, constraints -> + val placeable = + measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) + val roomX = (constraints.maxWidth - placeable.width).coerceAtLeast(0) + val roomY = (constraints.maxHeight - placeable.height).coerceAtLeast(0) + val dragged = editor?.shownPosition(hud) + layout(constraints.maxWidth, constraints.maxHeight) { + placeable.place( + (dragged?.x ?: (roomX * anchor.x)) + .roundToInt() + .coerceIn(0, roomX), + (dragged?.y ?: (roomY * anchor.y)) + .roundToInt() + .coerceIn(0, roomY) + ) + } + } + .then(if (editor != null) Modifier.hudEditable(hud, editor) else Modifier) + .clipToBounds() + .background(background) + .padding(ELEMENT_PADDING) + ) { + Box(Modifier.onSizeChanged { empty = it.width == 0 || it.height == 0 }) { hud.Content() } + if (editor != null && empty) HudText(hud.name, color = LambdaTheme.colors.onSurfaceVariant) + } +} + +@Composable +fun HudText(text: String, modifier: Modifier = Modifier, color: Color? = null) { + val hudColor by observe { HudConfig.textColor.toCompose() } + val scale by observe { HudConfig.scale } + val size = Type.body.fontSize * scale + Text( + text, + modifier, + color ?: hudColor, + Type.body.copy( + fontSize = size, + lineHeight = size * 1.25f + ).shadowed(HUD_TEXT_SHADOW) + ) +} diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt new file mode 100644 index 000000000..71bac86e2 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -0,0 +1,342 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.hud + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.MutableTransitionState +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.spring +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.drag +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.State +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.PointerButton +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.positionChange +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.layout.positionInRoot +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.round +import androidx.compose.ui.unit.toSize +import com.lambda.config.Config +import com.lambda.config.settings.complex.Bind +import com.lambda.gui.GuiConfig +import com.lambda.gui.LambdaGui +import com.lambda.gui.Reveal +import com.lambda.gui.Snap +import com.lambda.gui.Snap.snapLines +import com.lambda.gui.component.ContextMenu +import com.lambda.gui.component.MenuDivider +import com.lambda.gui.component.MenuHelp +import com.lambda.gui.component.MenuItem +import com.lambda.gui.component.MenuLabel +import com.lambda.gui.component.onMousePress +import com.lambda.gui.component.rememberLast +import com.lambda.gui.component.window +import com.lambda.gui.core.observe +import com.lambda.gui.settings.ConfigSettings +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.module.HudModule + +private val PANEL_SCALE = spring(stiffness = Spring.StiffnessMedium) + +internal class HudEditorState(snapping: State) { + val snapping by snapping + + val bounds = mutableStateMapOf() + + var dragged by mutableStateOf(null) + var draggedTo by mutableStateOf(Offset.Zero) + + var menu by mutableStateOf?>(null) + private set + + var menusOpened by mutableStateOf(0) + private set + + fun openMenu(position: Offset, hud: HudModule?) { + menu = position to hud + menusOpened++ + } + + fun closeMenu() { + menu = null + } + + var configuring by mutableStateOf(null) + private set + + var panelPosition by mutableStateOf(Offset.Zero) + + var panelBounds = Rect.Zero + + fun configure(config: Config?, position: Offset? = null) { + configuring = config + if (config != null) panelPosition = position + ?: Offset( + screen.width / 2 - 120 * density.density, + screen.height * 0.15f + ) + } + + var screen = Size.Zero + var density = Density(1f) + + val drop: Snap.Result? by + derivedStateOf { + val hud = dragged ?: return@derivedStateOf null + val element = Rect(draggedTo, bounds[hud]?.size ?: return@derivedStateOf null) + if (this.snapping) { + Snap.snap( + element, + bounds.filterKeys { it != hud }.values, + Rect(Offset.Zero, screen), + density + ) + } + else Snap.free(element, Rect(Offset.Zero, screen)) + } + + fun shownPosition(hud: HudModule) = drop?.position.takeIf { dragged == hud } +} + +@Composable +internal fun HudEditor() { + val snapping = observe { Snap.isActive } + val editor = remember { HudEditorState(snapping) } + editor.screen = LocalWindowInfo.current.containerSize.toSize() + editor.density = LocalDensity.current + + val revealedElement = Reveal.module as? HudModule + val revealedSetting = Reveal.setting + LaunchedEffect(revealedElement, revealedSetting) { + if (revealedElement != null && revealedSetting != null) editor.configure(revealedElement) + } + + Box( + Modifier + .fillMaxSize() + .onMousePress(PointerButton.Secondary) { editor.openMenu(it, null) } + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type != PointerEventType.Press || editor.configuring == null) continue + if (event.changes.first().position !in editor.panelBounds) editor.configure(null) + } + } + } + .snapLines { editor.drop } + ) { + HudLayer(editor) + rememberLast(editor.configuring)?.let { config -> + key(config) { ElementSettings(config, editor.configuring === config, editor) } + } + } + + rememberLast(editor.menu)?.let { (position, hud) -> + key(editor.menusOpened) { + ContextMenu( + editor.menu != null, + position.round(), + onDismiss = editor::closeMenu + ) { + if (hud != null) ElementMenu(hud, editor) + else ScreenMenu(position, editor) + } + } + } +} + +@Composable +private fun ElementMenu(hud: HudModule, editor: HudEditorState) { + MenuLabel(hud.name) + MenuItem("Settings...") { editor.configure(hud, editor.menu?.first) } + MenuItem("Remove") { hud.disable() } + MenuDivider() + EditorHelp() +} + +@Composable +private fun EditorHelp() { + val snapping by observe { + when { + !GuiConfig.snapEnabled -> "" + GuiConfig.snapKey == Bind.EMPTY -> " Elements snap into line." + else -> " Hold ${GuiConfig.snapKey.name} to snap it into line." + } + } + MenuHelp("Drag an element to move it.$snapping Right click an element to remove or configure it, or the empty screen to add one.") +} + +@Composable +private fun ScreenMenu(position: Offset, editor: HudEditorState) { + val screen = LocalWindowInfo.current.containerSize + val hidden by observe { Hud.modules.filter { !it.isEnabled }.sortedBy { it.name.lowercase() } } + if (hidden.isEmpty()) MenuLabel("Every HUD element is shown") + else { + MenuLabel("Add HUD Element") + hidden.forEach { hud -> + MenuItem(hud.name) { + hud.anchorX = (position.x / screen.width).coerceIn(0f, 1f) + hud.anchorY = (position.y / screen.height).coerceIn(0f, 1f) + hud.enable() + } + } + } + MenuDivider() + MenuItem("HUD Settings...") { editor.configure(HudConfig, position) } + EditorHelp() + MenuItem("Back") { LambdaGui.back() } +} + +@Composable +private fun ElementSettings(config: Config, open: Boolean, editor: HudEditorState) { + val colors = LambdaTheme.colors + val density = LocalDensity.current + val maxHeight = with(density) { editor.screen.height.toDp() } * 0.6f + var size by remember { mutableStateOf(IntSize.Zero) } + val room = + Offset( + (editor.screen.width - size.width).coerceAtLeast(0f), + (editor.screen.height - size.height).coerceAtLeast(0f) + ) + val position = + Offset( + editor.panelPosition.x.coerceIn(0f, room.x), + editor.panelPosition.y.coerceIn(0f, room.y) + ) + val shownAt by rememberUpdatedState(position) + if (open) editor.panelBounds = Rect(position, size.toSize()) + DisposableEffect(Unit) { + LambdaGui.onEscape = { (editor.configuring != null).also { editor.configure(null) } } + onDispose { LambdaGui.onEscape = null } + } + + val visibility = remember { MutableTransitionState(false) } + visibility.targetState = open + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier.offset { position.round() }, + enter = scaleIn(PANEL_SCALE), + exit = scaleOut(PANEL_SCALE), + ) { + ConfigSettings( + config = config, + maxHeight = maxHeight, + onDone = { editor.configure(null) }, + modifier = Modifier + .onSizeChanged { size = it } + .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) + .pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown() + down.consume() + editor.panelPosition = shownAt + drag(down.id) { change -> + editor.panelPosition += change.positionChange() + change.consume() + } + } + } + .padding(6.dp) + .width(200.dp) + ) + } +} + +internal fun Modifier.hudEditable(hud: HudModule, editor: HudEditorState): Modifier = + this + .onGloballyPositioned { editor.bounds[hud] = Rect(it.positionInRoot(), it.size.toSize()) } + .onMousePress(PointerButton.Secondary) { position -> + editor.bounds[hud]?.let { editor.openMenu(it.topLeft + position, hud) } + } + .pointerInput(hud) { + awaitEachGesture { + val down = awaitFirstDown() + val origin = editor.bounds[hud] ?: return@awaitEachGesture + down.consume() + + editor.draggedTo = origin.topLeft + editor.dragged = hud + try { + drag(down.id) { change -> + editor.draggedTo += change.positionChange() + change.consume() + } + } finally { + val dropped = editor.drop?.position ?: origin.topLeft + val room = editor.screen - origin.size + hud.anchorX = + if (room.width > 0f) (dropped.x / room.width).coerceIn(0f, 1f) + else 0f + hud.anchorY = + if (room.height > 0f) (dropped.y / room.height).coerceIn(0f, 1f) + else 0f + editor.dragged = null + } + } + } + .drawBehind { + val width = Look.outlineWidth.toPx() + val alpha = + if (editor.dragged == hud || Reveal.module === hud) 0.9f + else 0.35f + drawRect( + color = Color.White.copy(alpha = alpha), + topLeft = Offset(width / 2, width / 2), + size = Size(size.width - width, size.height - width), + style = Stroke(width) + ) + } + +private operator fun Size.minus(other: Size) = Size(width - other.width, height - other.height) diff --git a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt new file mode 100644 index 000000000..c1419279f --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -0,0 +1,210 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.menu + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.dp +import com.lambda.Lambda +import com.lambda.Lambda.REPO_URL +import com.lambda.Lambda.mc +import com.lambda.command.CommandRegistry +import com.lambda.config.Config +import com.lambda.config.ConfigLoader +import com.lambda.config.automation.UserAutomationConfig +import com.lambda.core.Loader +import com.lambda.event.EventFlow +import com.lambda.gui.component.Button +import com.lambda.gui.component.Dialog +import com.lambda.gui.component.Text +import com.lambda.gui.component.TextInput +import com.lambda.gui.component.rememberTexture +import com.lambda.gui.core.LocalShown +import com.lambda.gui.settings.ConfigSettings +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Type +import com.lambda.module.ModuleRegistry +import com.lambda.module.modules.client.AutoUpdater +import com.lambda.util.Diagnostics.gatherDiagnostics +import net.fabricmc.loader.api.FabricLoader +import net.minecraft.util.Util + +@Composable +internal fun ConfigDialog(config: Config, onDismiss: () -> Unit) { + val maxHeight = + with(LocalDensity.current) { + LocalWindowInfo.current.containerSize.height.toDp() + } * 0.7f + Dialog(onDismiss) { + ConfigSettings(config, maxHeight, onDismiss, Modifier.width(240.dp)) + } +} + +@Composable +internal fun NewAutomationConfigDialog(onDismiss: () -> Unit) { + var name by remember { mutableStateOf("") } + val isAvailable = name.isNotBlank() && ConfigLoader.configs.none { it.name == name } + + fun create() { + if (!isAvailable) return + UserAutomationConfig(name) + onDismiss() + } + + Dialog(onDismiss) { + Column(Modifier.width(180.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("New Automation Config", style = Type.title) + TextInput( + name, + { name = it }, + Modifier.fillMaxWidth(), + placeholder = "Name", + focused = true + ) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Spacer(Modifier.weight(1f)) + Button("Cancel", onClick = onDismiss) + Button("Create", enabled = isAvailable, onClick = ::create) + } + } + } +} + +@Composable +internal fun AboutDialog(onDismiss: () -> Unit) { + val colors = LambdaTheme.colors + val facts = + remember { + val settings = + ConfigLoader.configCategories.sumOf { category -> + category.configs.sumOf { config -> + var count = 0 + config.settingLayers.forEachEntry { _, _ -> count++ } + count + } + } + listOfNotNull( + "Version: ${Lambda.VERSION}", + "Development Environment".takeIf { Lambda.isDebug }, + "Runtime: ${Loader.runtime}", + "Modules: ${ModuleRegistry.modules.size}", + "Commands: ${CommandRegistry.commands.size}", + "Settings: $settings", + "Synchronous listeners: ${EventFlow.syncListeners.size}", + "Concurrent listeners: ${EventFlow.concurrentListeners.size}", + ) + } + val authors = + remember { + FabricLoader.getInstance() + .getModContainer("lambda") + .orElseThrow().metadata.authors + .flatMap { it.name.split(",") } + .map { it.trim() } + .filter { it.isNotEmpty() } + } + + Dialog(onDismiss) { + Column(Modifier.width(240.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Image( + bitmap = rememberTexture("textures/lambda_text_color.png"), + contentDescription = "Lambda", + modifier = Modifier.fillMaxWidth().padding(bottom = 4.dp) + ) + facts.forEach { Text(it) } + Text("Authors", Modifier.padding(top = 6.dp), style = Type.title) + authors.forEach { Text("• $it") } + Text( + "Thanks to all community members", + Modifier.padding(top = 2.dp), + colors.onSurfaceVariant + ) + Row( + Modifier.fillMaxWidth().padding(top = 6.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Button("Copy Diagnostics") { mc.keyboard.clipboard = gatherDiagnostics() } + Button("View License") { + Util.getOperatingSystem().open("$REPO_URL/blob/master/LICENSE.md") + } + Spacer(Modifier.weight(1f)) + Button("Close", onClick = onDismiss) + } + } + } +} + +@Composable +internal fun LoaderPromptDialog(prompt: AutoUpdater.Prompt) { + if (!LocalShown.current && prompt == AutoUpdater.Prompt.FirstLaunch) return + val colors = LambdaTheme.colors + Dialog(onDismiss = { AutoUpdater.answerPrompt(accepted = false) }) { + Column(Modifier.width(260.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + when (prompt) { + AutoUpdater.Prompt.Uninstall -> { + Text("Uninstall Lambda Loader?", style = Type.title) + Text("This will close the client automatically once the uninstall is finished.") + } + AutoUpdater.Prompt.FirstLaunch, AutoUpdater.Prompt.Install -> { + Text("Switch to Lambda Loader?", style = Type.title) + Text("Lambda Loader replaces this version-specific Lambda jar with a lightweight bootstrap that keeps Lambda up to date.") + Text("• Automatic updates on launch\n• No manual jar replacement") + Text("If you choose to switch, Lambda will install the loader and close the game so changes apply on next start.") + Text( + "You can change this later from the AutoUpdater module.", + color = colors.onSurfaceVariant + ) + } + } + Row( + Modifier.fillMaxWidth().padding(top = 4.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Button( + label = when (prompt) { + AutoUpdater.Prompt.FirstLaunch -> "Keep Current Jar" + else -> "Cancel" + }, + modifier = Modifier.weight(1f) + ) { AutoUpdater.answerPrompt(accepted = false) } + Button( + label = + if (prompt == AutoUpdater.Prompt.Uninstall) "Uninstall" + else "Switch To Loader", + modifier = Modifier.weight(1f) + ) { AutoUpdater.answerPrompt(accepted = true) } + } + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt new file mode 100644 index 000000000..3cf0067d7 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -0,0 +1,540 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.menu + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.FilterQuality +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.isShiftPressed +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.lambda.Lambda.REPO_URL +import com.lambda.Lambda.mc +import com.lambda.config.ConfigLoader +import com.lambda.config.automation.AutomationConfig +import com.lambda.config.automation.UserAutomationConfig +import com.lambda.config.categories.UserAutomationCategory +import com.lambda.gui.GuiConfig +import com.lambda.gui.LambdaGui +import com.lambda.gui.clickgui.CLICK_GUI_CATEGORIES +import com.lambda.gui.clickgui.ClickGuiDialog +import com.lambda.gui.clickgui.ClickGuiState +import com.lambda.gui.component.Menu +import com.lambda.gui.component.MenuDivider +import com.lambda.gui.component.MenuItem +import com.lambda.gui.component.MenuLabel +import com.lambda.gui.component.MenuState +import com.lambda.gui.component.Submenu +import com.lambda.gui.component.Suggestions +import com.lambda.gui.component.Text +import com.lambda.gui.component.TextInput +import com.lambda.gui.component.consumeClicks +import com.lambda.gui.component.glass +import com.lambda.gui.component.hoverHighlight +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.component.rememberLast +import com.lambda.gui.component.rememberTexture +import com.lambda.gui.core.observe +import com.lambda.gui.core.observeSafe +import com.lambda.gui.hud.HudConfig +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Type +import com.lambda.interaction.handler.handlers.BaritoneHandler +import com.lambda.module.ModuleRegistry +import com.lambda.module.ModuleTag +import com.lambda.network.LambdaAPI +import com.lambda.threading.runSafe +import com.lambda.util.CommunicationUtils.info +import com.lambda.util.Diagnostics.gatherDiagnostics +import com.lambda.util.FolderRegistry +import com.mojang.blaze3d.platform.TextureUtil +import net.minecraft.client.gui.screen.DebugOptionsScreen +import net.minecraft.network.packet.c2s.play.ChangeGameModeC2SPacket +import net.minecraft.server.command.GameModeCommand +import net.minecraft.util.Util +import net.minecraft.world.GameMode +import java.nio.file.Path +import java.util.* + +internal val MENU_BAR_HEIGHT = 15.dp +private val ICON_SIZE = 9.dp +private val SEARCH_WIDTH = 150.dp + +@Composable +internal fun MenuBar(modifier: Modifier = Modifier) { + val colors = LambdaTheme.colors + var bar by remember { mutableStateOf(IntSize.Zero) } + var menus by remember { mutableStateOf(IntSize.Zero) } + var search by remember { mutableStateOf(IntSize.Zero) } + Box( + contentAlignment = Alignment.Center, + modifier = modifier + .fillMaxWidth() + .height(MENU_BAR_HEIGHT) + .onSizeChanged { bar = it } + .glass(colors.surface, RectangleShape) + .consumeClicks() + ) { + Row( + Modifier + .align(Alignment.CenterStart) + .fillMaxHeight() + .onSizeChanged { menus = it }, + verticalAlignment = Alignment.CenterVertically + ) { + BarMenu("Lambda", icon = "textures/lambda.png") { LambdaMenu() } + BarMenu("Modules") { ModulesMenu() } + BarMenu("Automation") { AutomationMenu() } + BarMenu("Minecraft") { MinecraftMenu() } + BarMenu("Help") { HelpMenu() } + } + SearchField( + Modifier + .onSizeChanged { search = it } + .offset { + IntOffset( + (menus.width - (bar.width - search.width) / 2).coerceAtLeast(0), + 0 + ) + } + ) + } +} + +@Composable +private fun BarMenu( + label: String, + icon: String? = null, + content: @Composable ColumnScope.() -> Unit +) { + val menu = remember { MenuState() } + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .fillMaxHeight() + .hoverHighlight(LambdaTheme.colors.controlSelected) + .mouseClickable(onClick = menu::toggle) + .padding(horizontal = 6.dp) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + if (icon != null) { + Image( + rememberTexture(icon), + contentDescription = null, + Modifier.size(ICON_SIZE), + filterQuality = FilterQuality.High + ) + } + Text(label, maxLines = 1) + } + Menu(menu.isOpen, onDismiss = menu::dismiss, content = content) + } +} + +@Composable +private fun SearchField(modifier: Modifier = Modifier) { + val focus = LocalFocusManager.current + val field = remember { FocusRequester() } + val asked = ClickGuiState.focusSearch + LaunchedEffect(asked) { + if (asked) field.requestFocus() + ClickGuiState.focusSearch = false + } + var query by remember { mutableStateOf("") } + var listed by remember { mutableStateOf(false) } + val results = remember(query) { Search.find(query.trim()) } + val open = listed && query.isNotBlank() + val shown = rememberLast(results.takeIf { open }).orEmpty() + var marked by remember(results) { mutableStateOf(0) } + + fun choose(result: Search.Result) { + query = "" + listed = false + focus.clearFocus() + result.choose() + } + + Box( + modifier.onPreviewKeyEvent { event -> + when { + event.type != KeyEventType.KeyDown -> false + event.key == Key.Escape && query.isNotEmpty() -> { + query = "" + listed = false + true + } + event.key == Key.Enter -> { + if (open) results.getOrNull(marked)?.let(::choose) + true + } + !open || results.isEmpty() -> false + event.key == Key.DirectionDown || + event.key == Key.Tab && !event.isShiftPressed -> { + marked = (marked + 1).mod(results.size) + true + } + event.key == Key.DirectionUp || event.key == Key.Tab -> { + marked = (marked - 1).mod(results.size) + true + } + else -> false + } + } + ) { + TextInput( + value = query, + onValueChange = { + query = it + listed = true + }, + modifier = Modifier.width(SEARCH_WIDTH).focusRequester(field), + placeholder = "Search modules and settings", + ) + Suggestions(open, onDismiss = { listed = false }) { + if (shown.isEmpty()) MenuLabel("Nothing found") + shown.forEachIndexed { index, result -> + ResultRow( + result, + marked = index == marked, + onPoint = { marked = index } + ) { + choose(result) + } + } + } + } +} + +@Composable +private fun ResultRow( + result: Search.Result, + marked: Boolean, + onPoint: () -> Unit, + onClick: () -> Unit +) { + val colors = LambdaTheme.colors + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(marked) { + if (marked) intoView.bringIntoView() + } + val point by rememberUpdatedState(onPoint) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .widthIn(min = SEARCH_WIDTH) + .bringIntoViewRequester(intoView) + .background(if (marked) colors.controlSelected else Color.Transparent) + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + if (awaitPointerEvent().type == PointerEventType.Move) point() + } + } + } + .mouseClickable(keyboard = false, onClick = onClick) + .padding(horizontal = 5.dp, vertical = 1.dp) + ) { + Text(result.name, maxLines = 1) + Spacer(Modifier.weight(1f).widthIn(min = 10.dp)) + Text( + result.origin, + color = colors.onSurfaceVariant, + style = Type.label, + maxLines = 1 + ) + } +} + +@Composable +private fun LambdaMenu() { + Submenu("Save Config") { + MenuItem("Save All Configs") { + ConfigLoader.configCategories.forEach { it.trySaveToFile(true) } + GuiConfig.info( + "Saved ${ConfigLoader.configCategories.size} configuration files." + ) + } + ConfigLoader.configCategories.forEach { category -> + MenuItem("Save ${category.name}") { + category.trySaveToFile(true) + GuiConfig.info("Saved ${category.name}") + } + } + } + Submenu("Load Config") { + MenuItem("Load All Configs") { + ConfigLoader.configCategories.forEach { it.tryLoadFromFile() } + GuiConfig.info( + "Loaded ${ConfigLoader.configCategories.size} configuration files." + ) + } + ConfigLoader.configCategories.forEach { category -> + MenuItem("Load ${category.name}") { + category.tryLoadFromFile() + GuiConfig.info("Loaded ${category.name}") + } + } + } + MenuDivider() + Submenu("Settings") { + MenuItem("GUI Settings...") { + ClickGuiState.dialog = ClickGuiDialog.Settings(GuiConfig) + } + MenuItem("HUD Settings...") { + ClickGuiState.dialog = ClickGuiDialog.Settings(HudConfig) + } + MenuItem("Lambda API Settings...") { + ClickGuiState.dialog = ClickGuiDialog.Settings(LambdaAPI) + } + MenuItem("Baritone Settings...") { + ClickGuiState.dialog = ClickGuiDialog.Settings(BaritoneHandler) + } + MenuDivider() + MenuItem("Reset Window Layout") { GuiConfig.resetWindows() } + } + Submenu("Open Folder") { + FolderItem("Lambda Folder", FolderRegistry.lambda) + FolderItem("Config Folder", FolderRegistry.config) + FolderItem("Packet Logs Folder", FolderRegistry.packetLogs) + FolderItem("Replay Folder", FolderRegistry.replay) + FolderItem("Cache Folder", FolderRegistry.cache) + FolderItem("Capes Folder", FolderRegistry.capes) + FolderItem("Structures Folder", FolderRegistry.structure) + FolderItem("Maps Folder", FolderRegistry.maps) + } + MenuDivider() + MenuItem("About...") { ClickGuiState.dialog = ClickGuiDialog.About } + MenuItem("Developer Mode", checked = ClickGuiState.developerMode) { + ClickGuiState.developerMode = !ClickGuiState.developerMode + } + MenuDivider() + MenuItem("Close GUI", hint = "Esc") { LambdaGui.back() } + MenuItem("Exit Client") { mc.scheduleStop() } +} + +@Composable +private fun ModulesMenu() { + Submenu("Shown Categories") { + CLICK_GUI_CATEGORIES.forEach { tag -> + val shown by observe { ModuleTag.isTagShown(tag) } + MenuItem(tag.name, checked = shown) { ModuleTag.toggleTag(tag) } + } + } + MenuDivider() + CLICK_GUI_CATEGORIES.forEach { tag -> + Submenu(tag.name) { + ModuleRegistry.modules.filter { it.tag == tag }.forEach { module -> + val shown by observe { module.showInClickGui.value } + MenuItem(module.name, checked = shown) { + module.showInClickGui.value = !shown + } + } + } + } +} + +@Composable +private fun AutomationMenu() { + val configs by + observe { + UserAutomationCategory.configs.filterIsInstance() + } + MenuItem("New Config...") { + ClickGuiState.dialog = ClickGuiDialog.NewAutomationConfig + } + MenuDivider() + configs.forEach { config -> + MenuItem("${config.name}...") { + ClickGuiState.dialog = ClickGuiDialog.Settings(config) + } + } + MenuItem("${AutomationConfig.DEFAULT.name}...") { + ClickGuiState.dialog = ClickGuiDialog.Settings(AutomationConfig.DEFAULT) + } +} + +@Composable +private fun MinecraftMenu() { + val gameDirectory = mc.runDirectory.toPath().toAbsolutePath() + Submenu("Open Folder") { + FolderItem("Minecraft Folder", gameDirectory) + FolderItem("Saves Folder", gameDirectory.resolve("saves")) + FolderItem("Screenshots Folder", gameDirectory.resolve("screenshots")) + FolderItem("Resource Packs Folder", gameDirectory.resolve("resourcepacks")) + FolderItem("Mods Folder", gameDirectory.resolve("mods")) + } + MenuDivider() + + val gameMode by observeSafe { interaction.gameMode } + val mayChangeGameMode by + observeSafe { GameModeCommand.PERMISSION_CHECK.allows(player.permissions) } + if (gameMode == null) { + MenuItem("Debug (only available in game)", enabled = false) {} + return + } + Submenu("Gamemode", enabled = mayChangeGameMode == true) { + GameMode.entries.forEach { mode -> + MenuItem( + mode.name.lowercase().replaceFirstChar { it.uppercase() }, + checked = gameMode == mode + ) { + runSafe { connection.sendPacket(ChangeGameModeC2SPacket(mode)) } + } + } + } + Submenu("Debug") { + val options = mc.options + MenuItem( + "Show Advanced Tooltips", + hint = "F3+H", + checked = observe { options.advancedItemTooltips }.value + ) { + options.advancedItemTooltips = !options.advancedItemTooltips + options.write() + } + MenuItem( + "Pause On Lost Focus", + hint = "F3+Esc", + checked = observe { options.pauseOnLostFocus }.value + ) { + options.pauseOnLostFocus = !options.pauseOnLostFocus + options.write() + } + MenuItem( + "Show Debug Menu", + hint = "F3", + checked = observe { mc.debugHudEntryList.isF3Enabled }.value + ) { + mc.debugHudEntryList.toggleF3Enabled() + } + MenuItem( + "Rendering Chart", + hint = "F3+1", + checked = observe { mc.debugHud.renderingChartVisible }.value + ) { + mc.debugHud.toggleRenderingChart() + } + MenuItem( + "Rendering & Tick Charts", + hint = "F3+2", + checked = observe { mc.debugHud.renderingAndTickChartsVisible }.value + ) { + mc.debugHud.toggleRenderingAndTickCharts() + } + MenuItem( + "Packet Size & Ping Charts", + hint = "F3+3", + checked = observe { mc.debugHud.packetSizeAndPingChartsVisible }.value + ) { + mc.debugHud.togglePacketSizeAndPingCharts() + } + MenuDivider() + MenuItem("Copy Location (as command)", hint = "F3+C") { + runSafe { + mc.keyboard.clipboard = + String.format( + Locale.ROOT, + "/execute in %s run tp @s %.2f %.2f %.2f %.2f %.2f", + world.registryKey.value, + player.x, + player.y, + player.z, + player.yaw, + player.pitch + ) + GuiConfig.info("Copied location command to clipboard.") + } + } + MenuItem("Clear Chat", hint = "F3+D") { mc.inGameHud?.chatHud?.clear(false) } + MenuItem("Open Debug Options") { mc.setScreen(DebugOptionsScreen()) } + MenuDivider() + MenuItem("Reload Resource Packs", hint = "F3+T") { + GuiConfig.info("Reloading resource packs...") + mc.reloadResources() + } + MenuItem("Reload Chunks", hint = "F3+A") { mc.worldRenderer.reload() } + MenuItem("Start/Stop Profiler", hint = "F3+L") { + mc.toggleDebugProfiler { GuiConfig.info(it) } + } + MenuItem("Dump Dynamic Textures", hint = "F3+S") { + val output = TextureUtil.getDebugTexturePath(gameDirectory) + mc.textureManager.dumpDynamicTextures(output) + GuiConfig.info( + "Dumped dynamic textures to: ${gameDirectory.relativize(output)}" + ) + } + } +} + +@Composable +private fun HelpMenu() { + MenuItem("Documentation") { Util.getOperatingSystem().open("$REPO_URL/wiki") } + MenuItem("GitHub Repository") { Util.getOperatingSystem().open(REPO_URL) } + MenuItem("Report Issue") { + mc.keyboard.clipboard = gatherDiagnostics() + GuiConfig.info("Copied diagnostics to clipboard. Please paste it in a new issue on GitHub and click \"Submit new issue\". Thank you!") + Util.getOperatingSystem().open("$REPO_URL/issues") + } + MenuItem("Check for Updates") { Util.getOperatingSystem().open("$REPO_URL/releases") } +} + +@Composable +private fun FolderItem(label: String, folder: Path) = + MenuItem("Open $label") { Util.getOperatingSystem().open(folder) } diff --git a/src/main/kotlin/com/lambda/gui/menu/Search.kt b/src/main/kotlin/com/lambda/gui/menu/Search.kt new file mode 100644 index 000000000..5dd745eb8 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt @@ -0,0 +1,148 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.menu + +import com.lambda.Lambda.mc +import com.lambda.command.CommandRegistry +import com.lambda.command.LambdaCommand +import com.lambda.config.Config +import com.lambda.config.ConfigLoader +import com.lambda.config.entries.Setting +import com.lambda.gui.Reveal +import com.lambda.gui.clickgui.ClickGuiState +import com.lambda.module.HudModule +import com.lambda.module.Module +import com.lambda.module.ModuleRegistry +import com.lambda.module.ModuleTag +import com.lambda.util.StringUtils.levenshteinDistance +import net.minecraft.client.gui.screen.ChatScreen + +internal object Search { + sealed interface Result { + val name: String + + val origin: String + + fun choose() + + class OfModule(val module: Module) : Result { + override val name get() = module.name + override val origin = + if (module is HudModule) "HUD element" + else "${module.tag.name} module" + override fun choose() = Reveal.show(module) + } + + class OfSetting( + val setting: Setting<*>, + val config: Config, + path: List + ) : Result { + override val name get() = setting.name + override val origin = (listOf(config.name) + path).joinToString(" \u00bb ") + override fun choose() = Reveal.show(config, setting) + } + + class OfCommand(val command: LambdaCommand) : Result { + override val name = "${CommandRegistry.prefix}${command.name}" + override val origin = "Command" + override fun choose() = mc.setScreen(ChatScreen("${CommandRegistry.prefix}${command.name} ", true)) + } + } + + private const val MAX_RESULTS = 30 + + private const val MODULE_BONUS = 300 + private const val HUD_MODULE_BONUS = 270 + private const val COMMAND_BONUS = 200 + + fun find(query: String): List { + if (query.isEmpty()) return emptyList() + val needle = query.lowercase() + return rank(needle, lenient = false).ifEmpty { rank(needle, lenient = true) } + .sortedByDescending { it.second } + .take(MAX_RESULTS) + .map { it.first } + } + + private fun rank(query: String, lenient: Boolean): List> = + buildList { + fun consider(result: () -> Result, bonus: Int, vararg names: String) { + val score = names.maxOf { score(query, it.lowercase(), lenient) } + if (score > 0) add(result() to score + bonus) + } + + fun hidden(config: Any) = + config is Module && + config.tag == ModuleTag.DEBUG && + !ClickGuiState.developerMode + + ModuleRegistry.modules.forEach { module -> + if (hidden(module)) return@forEach + consider( + { Result.OfModule(module) }, + if (module is HudModule) HUD_MODULE_BONUS else MODULE_BONUS, + module.name, + module.tag.name + ) + } + CommandRegistry.commands.forEach { command -> + consider( + { Result.OfCommand(command) }, + COMMAND_BONUS, + command.name, + *command.aliases.toTypedArray() + ) + } + ConfigLoader.configCategories.forEach { category -> + category.configs.forEach { config -> + if (hidden(config)) return@forEach + config.settingLayers.forEachEntry { path, single -> + val setting = single.entry + if (setting.visibility()) { + consider( + { + Result.OfSetting( + setting, + config, + path.map { it.name } + ) + }, + 0, + setting.name + ) + } + } + } + } + } + + private fun score(query: String, target: String, lenient: Boolean): Int { + if (target.isEmpty()) return 0 + if (target == query) return 200 + if (target.startsWith(query)) return 100 + query.length * 50 / target.length + if (target.contains(query)) return 50 + query.length * 40 / target.length + + val distance = query.levenshteinDistance(target) + val allowed = + if (lenient) (query.length / 2).coerceIn(2, 6) + else (query.length / 3).coerceIn(1, 4) + return if (distance <= allowed) (50 - distance * 10).coerceAtLeast(1) + else 0 + } +} diff --git a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt new file mode 100644 index 000000000..0caddf426 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt @@ -0,0 +1,144 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.render + +import com.lambda.graphics.mc.LambdaRenderPipelines +import com.mojang.blaze3d.buffers.GpuBuffer +import com.mojang.blaze3d.buffers.Std140Builder +import com.mojang.blaze3d.pipeline.RenderPipeline +import com.mojang.blaze3d.systems.RenderSystem +import com.mojang.blaze3d.textures.FilterMode +import com.mojang.blaze3d.textures.GpuTexture +import com.mojang.blaze3d.textures.GpuTextureView +import com.mojang.blaze3d.textures.TextureFormat +import org.lwjgl.system.MemoryStack +import java.util.* +import kotlin.math.ceil +import kotlin.math.log2 + +internal class BlurPyramid(private val name: String) { + private var levels = emptyList() + private var width = 0 + private var height = 0 + + private val spreadUniform: GpuBuffer = + RenderSystem.getDevice().createBuffer( + { "$name spread" }, + GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, + SPREAD_UNIFORM_SIZE + ) + private var spread = Float.NaN + + fun blur( + source: GpuTextureView, + width: Int, + height: Int, + radius: Float + ): GpuTextureView { + resize(width, height) + val depth = + (ceil(log2(radius.coerceAtLeast(1f))).toInt() - 1).coerceIn(1, levels.size) + writeSpread((radius / (1 shl depth)).coerceIn(MIN_SPREAD, MAX_SPREAD)) + + var input = source + repeat(depth) { index -> + pass(LambdaRenderPipelines.GUI_BLUR_DOWN, input, levels[index].view) + input = levels[index].view + } + (depth - 2 downTo 0).forEach { index -> + pass(LambdaRenderPipelines.GUI_BLUR_UP, input, levels[index].view) + input = levels[index].view + } + return input + } + + private fun pass( + pipeline: RenderPipeline, + input: GpuTextureView, + output: GpuTextureView + ) { + RenderSystem.getDevice().createCommandEncoder() + .createRenderPass({ name }, output, OptionalInt.empty()) + .use { pass -> + pass.setPipeline(pipeline) + pass.bindTexture( + "InSampler", + input, + RenderSystem.getSamplerCache().get(FilterMode.LINEAR) + ) + pass.setUniform("BlurSpread", spreadUniform) + pass.draw(0, 3) + } + } + + private fun writeSpread(value: Float) { + if (value == spread) return + spread = value + MemoryStack.stackPush().use { stack -> + val data = + Std140Builder.onStack( + stack, + SPREAD_UNIFORM_SIZE.toInt() + ).putFloat(value).get() + RenderSystem.getDevice().createCommandEncoder().writeToBuffer( + spreadUniform.slice(), + data + ) + } + } + + private fun resize(width: Int, height: Int) { + if (width == this.width && height == this.height) return + levels.forEach { it.close() } + levels = + (1..MAX_DEPTH).map { + Level( + "$name level $it", + (width shr it).coerceAtLeast(1), + (height shr it).coerceAtLeast(1) + ) + } + this.width = width + this.height = height + } + + private class Level(label: String, width: Int, height: Int) : AutoCloseable { + private val texture: GpuTexture = + RenderSystem.getDevice().createTexture( + { label }, + GpuTexture.USAGE_RENDER_ATTACHMENT or GpuTexture.USAGE_TEXTURE_BINDING, + TextureFormat.RGBA8, + width, height, 1, 1 + ) + val view: GpuTextureView = RenderSystem.getDevice().createTextureView(texture) + + override fun close() { + view.close() + texture.close() + } + } + + private companion object { + const val MAX_DEPTH = 6 + + const val MIN_SPREAD = 0.5f + const val MAX_SPREAD = 2f + + const val SPREAD_UNIFORM_SIZE = 16L + } +} diff --git a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt new file mode 100644 index 000000000..ccf13555a --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt @@ -0,0 +1,146 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.render + +import com.lambda.Lambda.mc +import com.lambda.graphics.mc.LambdaRenderPipelines +import com.mojang.blaze3d.buffers.GpuBuffer +import com.mojang.blaze3d.buffers.Std140Builder +import com.mojang.blaze3d.buffers.Std140SizeCalculator +import com.mojang.blaze3d.systems.RenderSystem +import com.mojang.blaze3d.textures.FilterMode +import com.mojang.blaze3d.textures.GpuTextureView +import org.lwjgl.system.MemoryStack +import java.awt.Color +import java.util.* + +internal object GuiCompositor { + data class Effects( + val frost: Float = 0f, + val glow: Float = 0f, + val glowIntensity: Float = 0f, + val glowColorA: Color = Color.WHITE, + val glowColorB: Color = Color.WHITE, + val dim: Float = 0f, + ) { + companion object { + val NONE = Effects() + } + } + + private val backdrop by lazy { BlurPyramid("Lambda GUI backdrop") } + private val halo by lazy { BlurPyramid("Lambda GUI glow") } + private var haloView: GpuTextureView? = null + private var haloRadius = 0f + + private val uniformSize = + Std140SizeCalculator() + .putVec4() + .putVec4() + .putFloat() + .putFloat() + .putFloat() + .putFloat() + .align(16) + .get() + private val uniforms: GpuBuffer by lazy { + RenderSystem.getDevice().createBuffer( + { "Lambda GUI effects" }, + GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, + uniformSize.toLong() + ) + } + + fun composite( + gui: GpuTextureView, + width: Int, + height: Int, + guiChanged: Boolean, + effects: Effects + ) { + val screen = mc.framebuffer.colorAttachmentView ?: return + val linear = RenderSystem.getSamplerCache().get(FilterMode.LINEAR) + val nearest = RenderSystem.getSamplerCache().get(FilterMode.NEAREST) + + if (effects.frost <= 0f && effects.glow <= 0f && effects.dim <= 0f) { + haloView = null + return blit(gui) + } + + val backdropView = + if (effects.frost > 0f) backdrop.blur(screen, width, height, effects.frost) + else gui + if (effects.glow <= 0f) haloView = null + else if (guiChanged || haloView == null || haloRadius != effects.glow) { + haloView = halo.blur(gui, width, height, effects.glow) + haloRadius = effects.glow + } + + writeUniforms(effects) + RenderSystem.getDevice().createCommandEncoder() + .createRenderPass({ "Lambda GUI" }, screen, OptionalInt.empty()) + .use { pass -> + pass.setPipeline(LambdaRenderPipelines.GUI_COMPOSITE) + pass.bindTexture("GuiSampler", gui, nearest) + pass.bindTexture("BackdropSampler", backdropView, linear) + pass.bindTexture("HaloSampler", haloView ?: gui, linear) + pass.setUniform("GuiEffects", uniforms) + pass.draw(0, 3) + } + } + + fun blit(layer: GpuTextureView) { + val screen = mc.framebuffer.colorAttachmentView ?: return + val nearest = RenderSystem.getSamplerCache().get(FilterMode.NEAREST) + RenderSystem.getDevice().createCommandEncoder() + .createRenderPass({ "Lambda GUI" }, screen, OptionalInt.empty()) + .use { pass -> + pass.setPipeline(LambdaRenderPipelines.GUI_BLIT) + pass.bindTexture("InSampler", layer, nearest) + pass.draw(0, 3) + } + } + + private fun writeUniforms(effects: Effects) { + MemoryStack.stackPush().use { stack -> + val data = + Std140Builder.onStack(stack, uniformSize) + .putColor(effects.glowColorA) + .putColor(effects.glowColorB) + .putFloat(if (effects.glow > 0f) effects.glowIntensity else 0f) + .putFloat(if (effects.frost > 0f) 1f else 0f) + .putFloat((System.currentTimeMillis() % GLOW_CYCLE_MILLIS) / 1000f) + .putFloat(effects.dim) + .get() + RenderSystem.getDevice().createCommandEncoder().writeToBuffer( + uniforms.slice(), + data + ) + } + } + + private fun Std140Builder.putColor(color: Color) = + putVec4( + color.red / 255f, + color.green / 255f, + color.blue / 255f, + color.alpha / 255f + ) + + private const val GLOW_CYCLE_MILLIS = 3_141_592L +} diff --git a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt new file mode 100644 index 000000000..25fa5739a --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt @@ -0,0 +1,251 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.render + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.neverEqualPolicy +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.drawIntoCanvas +import androidx.compose.ui.graphics.skiaCanvas +import com.lambda.Lambda.mc +import com.mojang.blaze3d.systems.RenderSystem +import net.minecraft.client.gl.Framebuffer +import net.minecraft.client.gl.GlBackend +import net.minecraft.client.gl.SimpleFramebuffer +import net.minecraft.client.gui.DrawContext +import net.minecraft.client.gui.render.GuiRenderer +import net.minecraft.client.gui.render.state.GuiRenderState +import net.minecraft.client.render.fog.FogRenderer +import net.minecraft.client.texture.GlTexture +import net.minecraft.item.ItemStack +import org.jetbrains.skia.BackendRenderTarget +import org.jetbrains.skia.ColorSpace +import org.jetbrains.skia.ContentChangeMode +import org.jetbrains.skia.DirectContext +import org.jetbrains.skia.FramebufferFormat +import org.jetbrains.skia.Image +import org.jetbrains.skia.Rect +import org.jetbrains.skia.SamplingMode +import org.jetbrains.skia.Surface +import org.jetbrains.skia.SurfaceColorFormat +import org.jetbrains.skia.SurfaceOrigin +import kotlin.math.ceil + +object ItemAtlas { + class Slot { + var stack: ItemStack = ItemStack.EMPTY + + var size = 0 + + internal var rendered: ItemStack = ItemStack.EMPTY + } + + @JvmStatic + var target: Framebuffer? = null + private set + + @JvmStatic + var scale = 1 + private set + + private val slots = ArrayList() + private var strip: Strip? = null + private var pendingImport = false + private var rearranged = false + + private val state = GuiRenderState() + private val context by lazy { DrawContext(mc, state, 0, 0) } + private val renderer by lazy { + GuiRenderer( + state, + mc.bufferBuilders.entityVertexConsumers, + mc.gameRenderer.entityRenderCommandQueue, + mc.gameRenderer.entityRenderDispatcher, + emptyList() + ) + } + + private var renderedModels = emptyList() + private var renderedAt = 0L + + private var image: Image? by mutableStateOf(null, neverEqualPolicy()) + + fun add(slot: Slot) { + slots += slot + rearranged = true + } + + fun remove(slot: Slot) { + slots -= slot + rearranged = true + } + + fun DrawScope.drawItem(slot: Slot) { + val strip = image ?: return + val index = slots.indexOf(slot) + val cell = CELL * scale + if (index < 0 || slot.rendered.isEmpty || (index + 1) * cell > strip.width) return + drawIntoCanvas { canvas -> + canvas.skiaCanvas.drawImageRect( + strip, + Rect.makeXYWH(index * cell.toFloat(), 0f, cell.toFloat(), cell.toFloat()), + Rect.makeWH(size.width * CELL / ITEM, size.height * CELL / ITEM), + SamplingMode.LINEAR, + null, + true + ) + } + } + + fun render(): Boolean { + if (slots.isEmpty()) { + if (strip == null) return false + strip?.close() + strip = null + pendingImport = true + return true + } + val scale = ceil(slots.maxOf { it.size } / ITEM.toFloat()).toInt() + if (scale <= 0) return false + + slots.forEachIndexed { index, slot -> + context.drawItem(slot.stack, index * CELL, 0) + context.drawStackOverlay(mc.textRenderer, slot.stack, index * CELL, 0) + } + val models = ArrayList() + var moving = + slots.any { + it.stack.hasGlint() || mc.player?.itemCooldownManager?.isCoolingDown(it.stack) == true + } + state.forEachItemElement { + models += it.state().modelKey + moving = moving || it.state().isAnimated + } + val changed = + rearranged || scale != this.scale || models != renderedModels || + slots.any { !ItemStack.areEqual(it.stack, it.rendered) } + val now = System.nanoTime() + if (!changed && !(moving && now - renderedAt >= ANIMATION_INTERVAL)) { + state.clear() + return false + } + renderedAt = now + + val width = slots.size * CELL * scale + val height = CELL * scale + val strip = strip?.takeIf { it.width == width && it.height == height } + ?: run { + strip?.close() + Strip(width, height).also { strip = it } + } + this.scale = scale + rearranged = false + renderedModels = models + slots.forEach { it.rendered = it.stack.copy() } + draw(strip.framebuffer) + pendingImport = true + return true + } + + fun release() { + slots.clear() + image?.close() + image = null + strip?.close() + strip = null + pendingImport = false + renderedModels = emptyList() + } + + fun import(skia: DirectContext) { + if (!pendingImport) return + pendingImport = false + val previous = image + image = strip?.snapshot(skia) + previous?.close() + } + + private fun draw(framebuffer: Framebuffer) { + RenderSystem.getDevice().createCommandEncoder() + .clearColorAndDepthTextures( + framebuffer.colorAttachment, + 0, + framebuffer.depthAttachment, + 1.0 + ) + + val projection = RenderSystem.getProjectionMatrixBuffer() + val projectionType = RenderSystem.getProjectionType() + target = framebuffer + try { + renderer.incrementFrame() + renderer.render(mc.gameRenderer.fogRenderer.getFogBuffer(FogRenderer.FogType.NONE)) + } finally { + target = null + if (projection != null) RenderSystem.setProjectionMatrix(projection, projectionType) + } + } + + private class Strip(val width: Int, val height: Int) : AutoCloseable { + val framebuffer = SimpleFramebuffer("Lambda GUI items", width, height, true) + + private val glFramebuffer = + (framebuffer.colorAttachment as GlTexture) + .getOrCreateFramebuffer((RenderSystem.getDevice() as GlBackend).bufferManager, null) + private var renderTarget: BackendRenderTarget? = null + private var surface: Surface? = null + + fun snapshot(skia: DirectContext): Image? { + val surface = surface + ?: run { + val renderTarget = + BackendRenderTarget.makeGL( + width, + height, + 0, + 0, + glFramebuffer, + FramebufferFormat.GR_GL_RGBA8 + ).also { renderTarget = it } + Surface.makeFromBackendRenderTarget( + skia, + renderTarget, + SurfaceOrigin.BOTTOM_LEFT, + SurfaceColorFormat.RGBA_8888, + ColorSpace.sRGB + ).also { surface = it } + } ?: return null + surface.notifyContentWillChange(ContentChangeMode.DISCARD) + return surface.makeImageSnapshot() + } + + override fun close() { + surface?.close() + renderTarget?.close() + framebuffer.delete() + } + } + + private const val ANIMATION_INTERVAL = 1_000_000_000L / 75 + + const val ITEM = 16 + + private const val CELL = 18 +} diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt new file mode 100644 index 000000000..b4382e18f --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -0,0 +1,232 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.settings + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollbarAdapter +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.unit.dp +import com.lambda.config.serializers.BlockSerializer +import com.lambda.config.settings.collections.CollectionSetting +import com.lambda.config.settings.complex.BlockSetting +import com.lambda.gui.component.Button +import com.lambda.gui.component.Chip +import com.lambda.gui.component.Dialog +import com.lambda.gui.component.Ellipsis +import com.lambda.gui.component.ItemIcon +import com.lambda.gui.component.Scrollbar +import com.lambda.gui.component.Text +import com.lambda.gui.component.TextInput +import com.lambda.gui.component.hoverHighlight +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.component.wheelScrollable +import com.lambda.gui.core.observe +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Type +import net.minecraft.item.ItemStack +import net.minecraft.registry.Registries + +private val ICON_SIZE = 8.dp + +@Composable +internal fun CollectionButton(setting: CollectionSetting) { + val count by observe { setting.value.size } + var editing by remember { mutableStateOf(false) } + + Labeled(setting.name) { + Chip(onClick = { editing = true }) { + Text("$count selected", Modifier.weight(1f, fill = false), maxLines = 1) + Ellipsis() + } + } + if (editing) CollectionWindow(setting) { editing = false } +} + +@Composable +private fun CollectionWindow( + setting: CollectionSetting, + onDismiss: () -> Unit +) { + val selected by observe { setting.value.toSet() } + val entries = + remember(setting.immutableCollection) { + setting.immutableCollection.map { + Entry(it, setting.label(it), setting.icon(it)) + } + } + var query by remember { mutableStateOf("") } + val matching = + remember(entries, query) { + entries.filter { it.label.contains(query.trim(), ignoreCase = true) } + } + val (chosen, available) = + remember(matching, selected) { matching.partition { it.item in selected } } + + Dialog(onDismiss) { + Column(Modifier.width(360.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text(setting.name) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + TextInput( + query, + { query = it }, + Modifier.weight(1f), + placeholder = "Search ${setting.name}", + focused = true + ) + Button("Invert", Modifier.height(Look.rowHeight)) { + setting.invertSelection() + } + } + Row( + Modifier.height(220.dp), + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + Pane("Available (${available.size})", available, Modifier.weight(1f)) { + setting.select(it) + } + Pane("Selected (${chosen.size})", chosen, Modifier.weight(1f)) { + setting.deselect(it) + } + } + } + } +} + +@Composable +internal fun BlockPicker(setting: BlockSetting) { + val block by observe { setting.value } + var picking by remember { mutableStateOf(false) } + + Labeled(setting.name) { + Chip(onClick = { picking = true }) { + Box(Modifier.size(ICON_SIZE)) { + ItemIcon(ItemStack(block.asItem()), ICON_SIZE) + } + Text( + BlockSerializer.stringify(block), + Modifier.weight(1f, fill = false), + maxLines = 1 + ) + Ellipsis() + } + } + if (!picking) return + + val entries = + remember { + Registries.BLOCK.map { + Entry(it, BlockSerializer.stringify(it), ItemStack(it.asItem())) + } + } + var query by remember { mutableStateOf("") } + val matching = + remember(query) { + entries.filter { it.label.contains(query.trim(), ignoreCase = true) } + } + Dialog(onDismiss = { picking = false }) { + Column(Modifier.width(200.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text(setting.name) + TextInput( + query, + { query = it }, + Modifier.fillMaxWidth(), + placeholder = "Search blocks", + focused = true + ) + Pane("Blocks (${matching.size})", matching, Modifier.height(220.dp)) { + setting.value = it + picking = false + } + } + } +} + +private class Entry(val item: R, val label: String, val icon: ItemStack?) + +@Composable +private fun Pane( + title: String, + entries: List>, + modifier: Modifier, + onClick: (R) -> Unit +) { + val colors = LambdaTheme.colors + Column(modifier.fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(title, color = colors.onSurfaceVariant, style = Type.label) + val list = rememberLazyListState() + Box( + Modifier + .fillMaxSize() + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.input) + ) { + LazyColumn( + state = list, + modifier = Modifier.fillMaxSize().wheelScrollable(list) + ) { + items(entries) { entry -> + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight) + .hoverHighlight(colors.controlSelected) + .mouseClickable { onClick(entry.item) } + .padding(horizontal = 4.dp) + ) { + if (entry.icon != null) Box(Modifier.size(ICON_SIZE)) { + ItemIcon(entry.icon, ICON_SIZE) + } + Text(entry.label, color = colors.onControl, maxLines = 1) + } + } + } + if (list.canScrollForward || list.canScrollBackward) { + Scrollbar(rememberScrollbarAdapter(list), Modifier.matchParentSize()) + } + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt new file mode 100644 index 000000000..869c99f04 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt @@ -0,0 +1,270 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.dp +import com.lambda.config.settings.complex.ColorSetting +import com.lambda.gui.component.MenuState +import com.lambda.gui.component.NumberInput +import com.lambda.gui.component.Popout +import com.lambda.gui.component.Text +import com.lambda.gui.component.TextInput +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.component.scrubbable +import com.lambda.gui.core.observe +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Type +import com.lambda.util.math.toCompose +import kotlin.math.roundToInt +import java.awt.Color as AwtColor + +private val PICKER_WIDTH = 130.dp +private val HUES = (0..6).map { Color.hsv(it * 60f % 360f, 1f, 1f) } + +@Composable +internal fun ColorPicker(setting: ColorSetting) { + val color by observe { setting.value } + val picker = remember { MenuState() } + + Labeled(setting.name, Modifier.mouseClickable(onClick = picker::toggle)) { + Box(Modifier.padding(end = 2.dp)) { + Spacer( + Modifier + .size(20.dp, 9.dp) + .clip(RoundedCornerShape(Look.boxRounding)) + .drawBehind { + drawCheckerboard() + drawRect(color.toCompose()) + } + ) + Popout(picker.isOpen, onDismiss = picker::dismiss) { + Column(Modifier.width(PICKER_WIDTH)) { + Picker(color) { setting.value = it } + } + } + } + } +} + +@Composable +private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { + val colors = LambdaTheme.colors + + var hsb by + remember { + mutableStateOf(AwtColor.RGBtoHSB(color.red, color.green, color.blue, null)) + } + var adopted by remember { mutableStateOf(color) } + if (color != adopted) { + adopted = color + val shown = AwtColor.HSBtoRGB(hsb[0], hsb[1], hsb[2]) and 0xFFFFFF + if (shown != color.rgb and 0xFFFFFF) { + hsb = AwtColor.RGBtoHSB(color.red, color.green, color.blue, null) + } + } + + fun pick( + hue: Float = hsb[0], + saturation: Float = hsb[1], + brightness: Float = hsb[2], + alpha: Int = color.alpha + ) { + hsb = floatArrayOf(hue, saturation, brightness) + val rgb = AwtColor.HSBtoRGB(hue, saturation, brightness) + onColorChange(AwtColor(rgb and 0xFFFFFF or (alpha shl 24), true)) + } + + Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { + Spacer( + Modifier + .fillMaxWidth() + .aspectRatio(1.4f) + .clip(RoundedCornerShape(Look.boxRounding)) + .drawBehind { + drawRect(Color.hsv(hsb[0] * 360f, 1f, 1f)) + drawRect(Brush.horizontalGradient(listOf(Color.White, Color.Transparent))) + drawRect(Brush.verticalGradient(listOf(Color.Transparent, Color.Black))) + val center = Offset(hsb[1] * size.width, (1f - hsb[2]) * size.height) + drawCircle( + Color.Black, + 3.5.dp.toPx(), + center, + style = Stroke(1.dp.toPx()) + ) + drawCircle( + Color.White, + 3.dp.toPx(), + center, + style = Stroke(1.dp.toPx()) + ) + } + .scrubbable { position, size -> + pick( + saturation = (position.x / size.width).coerceIn(0f, 1f), + brightness = 1f - (position.y / size.height).coerceIn(0f, 1f) + ) + } + ) + Bar(hsb[0], onChange = { pick(hue = it) }) { + drawRect(Brush.horizontalGradient(HUES)) + } + Bar(color.alpha / 255f, onChange = { pick(alpha = (it * 255).roundToInt()) }) { + drawCheckerboard() + drawRect( + Brush.horizontalGradient( + listOf(Color.Transparent, color.toCompose().copy(alpha = 1f)) + ) + ) + } + + Row(horizontalArrangement = Arrangement.spacedBy(2.dp)) { + Channel("R", color.red) { + onColorChange(AwtColor(it, color.green, color.blue, color.alpha)) + } + Channel("G", color.green) { + onColorChange(AwtColor(color.red, it, color.blue, color.alpha)) + } + Channel("B", color.blue) { + onColorChange(AwtColor(color.red, color.green, it, color.alpha)) + } + Channel("A", color.alpha) { + onColorChange(AwtColor(color.red, color.green, color.blue, it)) + } + } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text("Hex", color = colors.onSurfaceVariant, style = Type.label) + TextInput( + color.toHex(), + { text -> parseHex(text)?.let(onColorChange) }, + Modifier.weight(1f), + style = Type.label + ) + } + } +} + +@Composable +private fun Bar( + fraction: Float, + onChange: (Float) -> Unit, + background: DrawScope.() -> Unit +) { + Spacer( + Modifier + .fillMaxWidth() + .height(10.dp) + .clip(RoundedCornerShape(Look.boxRounding)) + .drawBehind { + background() + val thumb = Size(4.dp.toPx(), size.height) + val left = Offset(fraction * (size.width - thumb.width), 0f) + val corner = CornerRadius(1.dp.toPx()) + drawRoundRect(Color.White, left, thumb, corner) + drawRoundRect( + Color.Black, + left, + thumb, + corner, + style = Stroke(0.5.dp.toPx()) + ) + } + .scrubbable { position, size -> + onChange((position.x / size.width).coerceIn(0f, 1f)) + } + ) +} + +@Composable +private fun RowScope.Channel(label: String, value: Int, onChange: (Int) -> Unit) { + Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) { + Text(label, color = LambdaTheme.colors.onSurfaceVariant, style = Type.label) + NumberInput( + value, + { it.toIntOrNull()?.coerceIn(0, 255) }, + onChange, + Modifier.fillMaxWidth() + ) + } +} + +private fun DrawScope.drawCheckerboard() { + val cell = 4.dp.toPx() + drawRect(Color(0xFFCCCCCC)) + var row = 0 + while (row * cell < size.height) { + var column = row % 2 + while (column * cell < size.width) { + drawRect( + Color(0xFF999999), + Offset(column * cell, row * cell), + Size(cell, cell) + ) + column += 2 + } + row++ + } +} + +private fun AwtColor.toHex() = + if (alpha == 255) "#%02X%02X%02X".format(red, green, blue) + else "#%02X%02X%02X%02X".format(red, green, blue, alpha) + +private fun parseHex(text: String): AwtColor? { + val digits = text.removePrefix("#") + if ( + digits.length != 6 && digits.length != 8 || + digits.any { it.digitToIntOrNull(16) == null } + ) { + return null + } + val channels = digits.chunked(2).map { it.toIntOrNull(16) ?: return null } + return AwtColor(channels[0], channels[1], channels[2], channels.getOrElse(3) { 255 }) +} diff --git a/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt new file mode 100644 index 000000000..217a10d04 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt @@ -0,0 +1,86 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.lambda.config.Config +import com.lambda.config.automation.UserAutomationConfig +import com.lambda.gui.component.Button +import com.lambda.gui.component.ScrollColumn +import com.lambda.gui.component.SoftTextShadow +import com.lambda.gui.component.Text +import com.lambda.gui.theme.Type +import com.lambda.module.Module + +@Composable +internal fun ConfigSettings( + config: Config, + maxHeight: Dp, + onDone: () -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + "${config.name} Settings", + Modifier.fillMaxWidth().padding(horizontal = 4.dp), + style = Type.title + ) + if (config is Module) { + var page by remember(config) { mutableStateOf(PanelPage.Settings) } + Column(Modifier.heightIn(max = maxHeight)) { + ModuleSettings(config, page, { page = it }, rememberScrollState()) + } + } else { + ScrollColumn(Modifier.heightIn(max = maxHeight)) { + SoftTextShadow { + if (config is UserAutomationConfig) SettingRow(config.linkedModules) + SettingsList(config.settingLayers) + } + } + } + Row( + Modifier.fillMaxWidth().padding(horizontal = 4.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + if (config is UserAutomationConfig) { + Button("Delete") { + config.delete() + onDone() + } + } + Spacer(Modifier.weight(1f)) + if (config !is Module) Button("Reset") { config.resetSettings() } + Button("Done", onClick = onDone) + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt new file mode 100644 index 000000000..99d7731ed --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt @@ -0,0 +1,230 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.settings + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.unit.dp +import com.lambda.config.automation.AutomationConfig +import com.lambda.config.automation.UserAutomationConfig +import com.lambda.config.categories.UserAutomationCategory +import com.lambda.config.entries.Setting +import com.lambda.config.hasVisibleSettings +import com.lambda.config.holds +import com.lambda.gui.Reveal +import com.lambda.gui.component.Button +import com.lambda.gui.component.Dropdown +import com.lambda.gui.component.LocalClickOnRelease +import com.lambda.gui.component.ScrollColumn +import com.lambda.gui.component.SoftTextShadow +import com.lambda.gui.component.Text +import com.lambda.gui.component.Tooltip +import com.lambda.gui.component.hoverHighlight +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.observe +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.module.Module +import com.lambda.module.modules.client.AutoUpdater +import kotlinx.coroutines.launch + +internal enum class PanelPage(val title: String) { + Settings("Settings"), + Module("Module"), + Automation("Automation"), +} + +@Composable +internal fun ColumnScope.ModuleSettings( + module: Module, + selected: PanelPage, + onSelect: (PanelPage) -> Unit, + scroll: ScrollState? +) { + val pages = pagesOf(module) + val page = selected.takeIf { it in pages } ?: PanelPage.Settings + val revealed = Reveal.setting.takeIf { Reveal.module === module } + LaunchedEffect(revealed) { + if (revealed != null) onSelect(pageOf(module, revealed)) + } + val scope = rememberCoroutineScope() + + SoftTextShadow { + if (pages.size > 1) PageStrip(pages, page) { + onSelect(it) + if (scroll != null) scope.launch { scroll.scrollTo(0) } + } + val turned = + @Composable { + AnimatedContent( + targetState = page, + modifier = Modifier.fillMaxWidth(), + transitionSpec = { pageTurn(towardsEnd = targetState > initialState) } + ) { shown -> + Column(Modifier.fillMaxWidth()) { + when (shown) { + PanelPage.Settings -> SettingsPage(module) + PanelPage.Module -> ModulePage(module) + PanelPage.Automation -> AutomationPage(module) + } + } + } + } + if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } + else turned() + } +} + +private fun pagesOf(module: Module): List = + when { + module == AutoUpdater -> listOf(PanelPage.Settings) + module.automationConfig === AutomationConfig.DEFAULT -> + listOf(PanelPage.Settings, PanelPage.Module) + else -> PanelPage.entries + } + +private fun pageOf(module: Module, setting: Setting<*>): PanelPage = + when { + module.automationConfig !== AutomationConfig.DEFAULT && + module.automationConfig.settingLayers.holds(setting) -> PanelPage.Automation + setting in moduleSettings(module) -> PanelPage.Module + else -> PanelPage.Settings + } + +private fun moduleSettings(module: Module): List> = + listOfNotNull( + module.keybindSetting.takeUnless { module.alwaysEnabled }, + module.prioritySetting, + module.disableOnReleaseSetting.takeUnless { module.alwaysEnabled }, + module.drawSetting.takeUnless { module.alwaysEnabled }, + ) + +@Composable +private fun PageStrip( + pages: List, + selected: PanelPage, + onSelect: (PanelPage) -> Unit +) { + val colors = LambdaTheme.colors + Row(Modifier.fillMaxWidth().padding(bottom = 2.dp)) { + pages.forEach { page -> + val isSelected = page == selected + val line by animateColorAsState(if (isSelected) colors.secondary else colors.raised) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .weight(page.title.length + 2f) + .height(Look.rowHeight + 1.dp) + .hoverHighlight(colors.raised) + .mouseClickable { onSelect(page) } + .drawBehind { + val thickness = 1.dp.toPx() + drawRect( + line, + Offset(0f, size.height - thickness), + Size(size.width, thickness) + ) + } + .padding(horizontal = 4.dp) + ) { + Text( + page.title, + color = if (isSelected) colors.onSurface else colors.onSurfaceVariant, + maxLines = 1, + softWrap = false + ) + } + } + } +} + +@Composable +private fun SettingsPage(module: Module) { + val any by observe { module.settingLayers.hasVisibleSettings() } + if (any) SettingsList(module.settingLayers) + else { + Box( + Modifier.fillMaxWidth().padding(vertical = 4.dp), + contentAlignment = Alignment.Center + ) { + Text("No settings", color = LambdaTheme.colors.onSurfaceVariant) + } + } +} + +@Composable +private fun AutomationPage(module: Module) { + val linked by observe { module.backingAutomationConfig } + CompositionLocalProvider(LocalClickOnRelease provides true) { + AutomationConfigSelector(module, linked) + } + key(linked) { SettingsList(module.automationConfig.settingLayers) } +} + +@Composable +private fun ModulePage(module: Module) { + moduleSettings(module).forEach { SettingRow(it) } + Tooltip( + "Resets all settings for this module to their default values", + Modifier.fillMaxWidth() + ) { + CompositionLocalProvider(LocalClickOnRelease provides true) { + Button("Reset", Modifier.settingCell().height(Look.rowHeight)) { + module.resetSettings() + } + } + } +} + +@Composable +private fun AutomationConfigSelector(module: Module, linked: AutomationConfig) { + val options by observe { + listOf(module.defaultAutomationConfig) + + UserAutomationCategory.configs.filterIsInstance() + } + Dropdown( + label = "Linked Config", + options = options, + selected = linked, + optionLabel = { it.name }, + modifier = Modifier.settingCell().padding(start = ROW_INSET), + ) { selected -> + (module.backingAutomationConfig as? UserAutomationConfig)?.linkedModules?.value?.remove(module.name) + (selected as? UserAutomationConfig)?.linkedModules?.value?.add(module.name) + module.automationConfig = selected + } +} diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt new file mode 100644 index 000000000..6ae14cd30 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -0,0 +1,124 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.settings + +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.dp +import com.lambda.config.entries.Setting +import com.lambda.gui.Reveal +import com.lambda.gui.component.LabeledRow +import com.lambda.gui.component.LocalClickOnRelease +import com.lambda.gui.component.LocalKeyboardReachable +import com.lambda.gui.component.Tooltip +import com.lambda.gui.component.hoverHighlight +import com.lambda.gui.core.awaitFrames +import com.lambda.gui.core.observe +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look + +private const val SETTLE_MILLIS = 250L +internal val TEXT_FIELD_WIDTH = 90.dp +internal val NUMBER_FIELD_WIDTH = 34.dp +internal val ROW_INSET = 3.dp + +@Composable +fun SettingRow(setting: Setting<*>) { + val disabled by observe { setting.disabled() } + + val revealed = Reveal.setting === setting + val lit by + animateColorAsState( + if (revealed) LambdaTheme.colors.onSurface.copy(alpha = 0.35f) + else Color.Transparent, + tween(250) + ) + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(revealed) { + if (revealed) { + awaitFrames(SETTLE_MILLIS) + intoView.bringIntoView() + } + } + + Tooltip(setting.description, Modifier.fillMaxWidth()) { + Box( + Modifier + .settingCell() + .bringIntoViewRequester(intoView) + .drawWithContent { + drawContent() + drawRect(lit) + } + .enabled(!disabled) + ) { + CompositionLocalProvider( + LocalClickOnRelease provides true, + LocalKeyboardReachable provides !disabled + ) { + key(setting) { setting.Gui() } + } + } + } +} + +internal fun Modifier.settingCell(): Modifier = + composed { + fillMaxWidth() + .padding(vertical = Look.settingSpacing / 2) + .clip(RoundedCornerShape(Look.controlRounding)) + .hoverHighlight(LambdaTheme.colors.hover) + } + +private fun Modifier.enabled(enabled: Boolean): Modifier = + if (enabled) this + else alpha(0.5f).pointerInput(Unit) { + awaitPointerEventScope { + while (true) awaitPointerEvent(PointerEventPass.Initial).changes.forEach { + it.consume() + } + } + } + +@Composable +internal fun Labeled( + name: String, + modifier: Modifier = Modifier, + editor: @Composable RowScope.() -> Unit +) = LabeledRow(name, modifier.padding(start = ROW_INSET), editor) diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt new file mode 100644 index 000000000..0a17882c9 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -0,0 +1,187 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.settings + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.AnimatedContentTransitionScope +import androidx.compose.animation.ContentTransform +import androidx.compose.animation.SizeTransform +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideOutHorizontally +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.lambda.config.EntryLayer +import com.lambda.config.MultipleLayerType +import com.lambda.config.entries.Setting +import com.lambda.config.hasVisibleSettings +import com.lambda.config.holds +import com.lambda.gui.Reveal +import com.lambda.gui.component.Chevron +import com.lambda.gui.component.ContentColor +import com.lambda.gui.component.Expandable +import com.lambda.gui.component.Menu +import com.lambda.gui.component.MenuItem +import com.lambda.gui.component.MenuState +import com.lambda.gui.component.Section +import com.lambda.gui.component.Text +import com.lambda.gui.component.hoverHighlight +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.observe +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Motion +import com.lambda.gui.theme.Type + +@Composable +fun SettingsList(layer: EntryLayer>) { + when (layer) { + is EntryLayer.Single -> { + val setting = layer.entry + val visible by observe { setting.visibility() } + Expandable(visible) { SettingRow(setting) } + } + + is EntryLayer.Multiple -> { + val hasVisibleSettings by observe { layer.hasVisibleSettings() } + if (!hasVisibleSettings) return + + val tabs = layer.layers.filterIsInstance>>() + when { + layer.multipleType == MultipleLayerType.Group -> + Section( + layer.name, + revealed = Reveal.setting?.let(layer::holds) == true + ) { + Children(layer) + } + else -> + Column(Modifier.fillMaxWidth()) { + layer.layers.filter { it !is EntryLayer.Tab }.forEach { SettingsList(it) } + if (tabs.isNotEmpty()) Tabs(tabs) + } + } + } + } +} + +@Composable +private fun Children(layer: EntryLayer.Multiple>) = + layer.layers.forEach { SettingsList(it) } + +@Composable +private fun Tabs(tabs: List>>) { + val shown by observe { tabs.filter { it.hasVisibleSettings() } } + if (shown.isEmpty()) return + var selectedName by remember { mutableStateOf(shown.first().name) } + val selected = shown.firstOrNull { it.name == selectedName } ?: shown.first() + val revealed = Reveal.setting + LaunchedEffect(revealed) { + if (revealed != null) { + shown.firstOrNull { it.holds(revealed) }?.let { selectedName = it.name } + } + } + + Column(Modifier.fillMaxWidth().padding(top = 1.dp)) { + TabPicker(shown.map { it.name }, selected.name) { selectedName = it } + AnimatedContent( + targetState = selected, + modifier = Modifier.fillMaxWidth(), + transitionSpec = { pageTurn(towardsEnd = shown.indexOf(targetState) > shown.indexOf(initialState)) }, + ) { tab -> + Column(Modifier.fillMaxWidth().padding(vertical = 1.dp)) { Children(tab) } + } + } +} + +@Composable +private fun TabPicker(names: List, selected: String, onSelect: (String) -> Unit) { + val colors = LambdaTheme.colors + val menu = remember { MenuState() } + var band by remember { mutableStateOf(IntSize.Zero) } + val choice = names.size > 1 + + Box(Modifier.fillMaxWidth().onSizeChanged { band = it }) { + ContentColor(colors.onHeader) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight + 2.dp) + .clip(RoundedCornerShape(topStart = Look.windowRounding, topEnd = Look.windowRounding)) + .background(colors.header) + .then( + if (!choice) Modifier + else { + Modifier + .hoverHighlight(colors.onHeader.copy(alpha = 0.12f)) + .mouseClickable(onClick = menu::toggle) + } + ) + .padding(horizontal = 6.dp) + ) { + Text(selected, Modifier.weight(1f), style = Type.title, maxLines = 1) + if (choice) Chevron(90f) + } + } + Menu( + menu.isOpen, + onDismiss = menu::dismiss, + unfoldFrom = IntSize(band.width, 0), + attached = true + ) { + names.forEach { name -> + MenuItem(name, selected = name == selected) { + if (name != selected) onSelect(name) + } + } + } + } +} + +internal fun AnimatedContentTransitionScope<*>.pageTurn(towardsEnd: Boolean): ContentTransform { + val millis = Motion.pageMillis + val slide = tween(millis) + return (fadeIn(tween(millis)) + slideInHorizontally(slide) { if (towardsEnd) it / 5 else -it / 5 }) + .togetherWith(fadeOut(tween(millis / 2)) + slideOutHorizontally(slide) { if (towardsEnd) -it / 5 else it / 5 }) + .using(SizeTransform(clip = true) { _, _ -> tween(millis) }) +} diff --git a/src/main/kotlin/com/lambda/gui/snap/RectF.kt b/src/main/kotlin/com/lambda/gui/snap/RectF.kt deleted file mode 100644 index 31826d268..000000000 --- a/src/main/kotlin/com/lambda/gui/snap/RectF.kt +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui.snap - -data class RectF(val x: Float, val y: Float, val w: Float, val h: Float) { - val left get() = x - val right get() = x + w - val top get() = y - val bottom get() = y + h - val cx get() = x + w * 0.5f - val cy get() = y + h * 0.5f -} \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/gui/snap/SnapHandler.kt b/src/main/kotlin/com/lambda/gui/snap/SnapHandler.kt deleted file mode 100644 index 0bbf2dd59..000000000 --- a/src/main/kotlin/com/lambda/gui/snap/SnapHandler.kt +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright 2026 Lambda - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.lambda.gui.snap - -import com.lambda.core.Loadable -import com.lambda.event.events.GuiEvent -import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.components.ClickGuiLayout.gridSize -import com.lambda.gui.components.ClickGuiLayout.snapDistanceElement -import com.lambda.gui.components.ClickGuiLayout.snapDistanceGrid -import com.lambda.gui.components.ClickGuiLayout.snapDistanceScreen -import com.lambda.gui.components.ClickGuiLayout.snapEnabled -import com.lambda.gui.components.ClickGuiLayout.snapLineColor -import com.lambda.gui.components.ClickGuiLayout.snapToCenters -import com.lambda.gui.components.ClickGuiLayout.snapToEdges -import com.lambda.gui.components.ClickGuiLayout.snapToGrid -import com.lambda.gui.components.ClickGuiLayout.snapToScreenCenter -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImColor -import com.lambda.imgui.ImGui -import kotlin.math.abs -import kotlin.math.max - -object SnapHandler : Loadable { - private data class SnapGuide(val guide: Guide, val sourceId: String?) - private val frameGuides = ArrayList(512) - private val elementRects = LinkedHashMap() - private var viewW = 0f - private var viewH = 0f - private var scale = 1f - private var lastInitFrame = -1 - - data class SnapVisual( - val snapX: Float?, - val snapY: Float?, - val kindX: Guide.Kind?, - val kindY: Guide.Kind? - ) - - init { - listen { - val vp = ImGui.getMainViewport() - val io = ImGui.getIO() - beginFrame(vp.sizeX, vp.sizeY, io.fontGlobalScale) - } - } - - fun beginFrame(viewWidth: Float, viewHeight: Float, uiScale: Float) { - val frame = ImGui.getFrameCount() - if (frame == lastInitFrame) return - lastInitFrame = frame - - viewW = max(1f, viewWidth) - viewH = max(1f, viewHeight) - scale = max(0.5f, uiScale) - frameGuides.clear() - - if (snapEnabled && snapToScreenCenter) { - frameGuides += SnapGuide(Guide(Guide.Orientation.Vertical, viewW * 0.5f, 30, Guide.Kind.ScreenCenter), null) - frameGuides += SnapGuide(Guide(Guide.Orientation.Horizontal, viewH * 0.5f, 30, Guide.Kind.ScreenCenter), null) - } - - if (snapEnabled && snapToGrid && gridSize > 0f) { - val step = max(4f, gridSize * scale) - var x = 0f - while (x <= viewW) { - frameGuides += SnapGuide(Guide(Guide.Orientation.Vertical, x, 10, Guide.Kind.Grid), null) - x += step - } - var y = 0f - while (y <= viewH) { - frameGuides += SnapGuide(Guide(Guide.Orientation.Horizontal, y, 10, Guide.Kind.Grid), null) - y += step - } - } - - elementRects.forEach { (id, r) -> addElementGuides(id, r) } - } - - fun registerElement(id: String, rect: RectF) { - elementRects[id] = rect - } - - fun unregisterElement(id: String) { - elementRects.remove(id) - } - - private fun addElementGuides(sourceId: String, r: RectF) { - if (snapEnabled && snapToEdges) { - frameGuides += SnapGuide(Guide(Guide.Orientation.Vertical, r.left, 100, Guide.Kind.ElementEdge), sourceId) - frameGuides += SnapGuide(Guide(Guide.Orientation.Vertical, r.right, 100, Guide.Kind.ElementEdge), sourceId) - frameGuides += SnapGuide(Guide(Guide.Orientation.Horizontal, r.top, 100, Guide.Kind.ElementEdge), sourceId) - frameGuides += SnapGuide(Guide(Guide.Orientation.Horizontal, r.bottom, 100, Guide.Kind.ElementEdge), sourceId) - } - if (snapEnabled && snapToCenters) { - frameGuides += SnapGuide(Guide(Guide.Orientation.Vertical, r.cx, 80, Guide.Kind.ElementCenter), sourceId) - frameGuides += SnapGuide(Guide(Guide.Orientation.Horizontal, r.cy, 80, Guide.Kind.ElementCenter), sourceId) - } - } - - data class SnapResult( - val dx: Float, - val dy: Float, - val snapX: Float?, - val snapY: Float?, - val kindX: Guide.Kind?, - val kindY: Guide.Kind? - ) - - private fun thresholdFor(kind: Guide.Kind): Float = when (kind) { - Guide.Kind.ElementEdge, Guide.Kind.ElementCenter -> snapDistanceElement * scale - Guide.Kind.ScreenCenter -> snapDistanceScreen * scale - Guide.Kind.Grid -> snapDistanceGrid * scale - } - - private fun score(dist: Float, strength: Int): Float = dist - strength * 0.08f - - fun computeSnap(proposed: RectF, currentId: String?): SnapResult { - data class Best(var s: Float = Float.POSITIVE_INFINITY, var d: Float = 0f, var p: Float? = null, var k: Guide.Kind? = null) - val bestElemX = Best(); val bestElemY = Best() - val bestScreenX = Best(); val bestScreenY = Best() - val bestGridX = Best(); val bestGridY = Best() - - fun consider(g: Guide, point: Float, out: Best) { - val dist = abs(point - g.pos) - if (dist <= max(1f, thresholdFor(g.kind))) { - val sc = score(dist, g.strength) - if (sc < out.s) { out.s = sc; out.d = g.pos - point; out.p = g.pos; out.k = g.kind } - } - } - - fun processAxis( - g: Guide, - points: FloatArray, - tier: String, - elem: Best, - screen: Best, - grid: Best - ) { - when (tier) { - "elem" -> for (p in points) consider(g, p, elem) - "screen" -> for (p in points) consider(g, p, screen) - "grid" -> for (p in points) consider(g, p, grid) - } - } - - frameGuides.forEach { sg -> - val g = sg.guide - val isSelf = (currentId != null && sg.sourceId == currentId) - val tier = when (g.kind) { - Guide.Kind.ElementEdge, Guide.Kind.ElementCenter -> if (isSelf) null else "elem" - Guide.Kind.ScreenCenter -> "screen" - Guide.Kind.Grid -> "grid" - } ?: return@forEach - - when (g.orientation) { - Guide.Orientation.Vertical -> { - val points = floatArrayOf(proposed.left, proposed.cx, proposed.right) - processAxis(g, points, tier, bestElemX, bestScreenX, bestGridX) - } - Guide.Orientation.Horizontal -> { - val points = floatArrayOf(proposed.top, proposed.cy, proposed.bottom) - processAxis(g, points, tier, bestElemY, bestScreenY, bestGridY) - } - } - } - - val choiceX = when { - bestElemX.s.isFinite() -> bestElemX - bestScreenX.s.isFinite() -> bestScreenX - bestGridX.s.isFinite() -> bestGridX - else -> Best() - } - val choiceY = when { - bestElemY.s.isFinite() -> bestElemY - bestScreenY.s.isFinite() -> bestScreenY - bestGridY.s.isFinite() -> bestGridY - else -> Best() - } - - return SnapResult( - dx = if (choiceX.s.isFinite()) choiceX.d else 0f, - dy = if (choiceY.s.isFinite()) choiceY.d else 0f, - snapX = choiceX.p, snapY = choiceY.p, - kindX = choiceX.k, kindY = choiceY.k - ) - } - - data class EdgeSnapResult(val pos: Float?, val kind: Guide.Kind?) - - fun snapEdge(pos: Float, orientation: Guide.Orientation, currentId: String?): EdgeSnapResult { - class Best { - var s = Float.POSITIVE_INFINITY - var p: Float? = null - var k: Guide.Kind? = null - } - - val elem = Best(); val screen = Best(); val grid = Best() - - frameGuides.forEach { sg -> - val g = sg.guide - if (g.orientation != orientation) return@forEach - - val out = when (g.kind) { - Guide.Kind.ElementEdge, Guide.Kind.ElementCenter -> - if (sg.sourceId == currentId) return@forEach else elem - Guide.Kind.ScreenCenter -> screen - Guide.Kind.Grid -> grid - } - - val dist = abs(pos - g.pos) - if (dist > max(1f, thresholdFor(g.kind))) return@forEach - - val sc = score(dist, g.strength) - if (sc < out.s) { out.s = sc; out.p = g.pos; out.k = g.kind } - } - - val choice = when { - elem.s.isFinite() -> elem - screen.s.isFinite() -> screen - grid.s.isFinite() -> grid - else -> return EdgeSnapResult(null, null) - } - return EdgeSnapResult(choice.p, choice.k) - } - - fun ImGuiBuilder.drawSnapLines(snapX: Float?, kindX: Guide.Kind?, snapY: Float?, kindY: Guide.Kind?) { - val draw = foregroundDrawList - val showX = kindX == Guide.Kind.ElementEdge || kindX == Guide.Kind.ElementCenter - val showY = kindY == Guide.Kind.ElementEdge || kindY == Guide.Kind.ElementCenter - if (!showX && !showY) return - - val col = ImColor.rgba(snapLineColor.red, snapLineColor.green, snapLineColor.blue, snapLineColor.alpha) - val thick = 2f - if (showX && snapX != null) draw.addLine(snapX, 0f, snapX, viewH, col, thick) - if (showY && snapY != null) draw.addLine(0f, snapY, viewW, snapY, col, thick) - } - - fun ImGuiBuilder.drawDragGrid() { - if (!snapEnabled || !snapToGrid) return - val step = max(4f, gridSize * io.fontGlobalScale) - if (step <= 0f) return - - val vp = ImGui.getMainViewport() - val x0 = vp.posX - val y0 = vp.posY - val x1 = vp.posX + vp.sizeX - val y1 = vp.posY + vp.sizeY - val col = ImColor.rgba(255, 255, 255, 28) - val thickness = 1f - - var x = x0 - while (x <= x1 + 0.5f) { - backgroundDrawList.addLine(x, y0, x, y1, col, thickness) - x += step - } - var y = y0 - while (y <= y1 + 0.5f) { - backgroundDrawList.addLine(x0, y, x1, y, col, thickness) - y += step - } - } - - fun ImGuiBuilder.updateDragAndSnapping( - id: String, - lastBound: RectF, - dragOffsetX: Float, - dragOffsetY: Float, - pendingPositions: MutableMap>, - snapOverlays: MutableMap - ) { - val mx = io.mousePos.x - val my = io.mousePos.y - val targetX = mx - dragOffsetX - val targetY = my - dragOffsetY - val proposed = RectF(targetX, targetY, lastBound.w, lastBound.h) - val snap = computeSnap(proposed, id) - var finalX = targetX + snap.dx - var finalY = targetY + snap.dy - - val vp = ImGui.getMainViewport() - val minX = vp.posX - val minY = vp.posY - val maxX = vp.posX + vp.sizeX - lastBound.w - val maxY = vp.posY + vp.sizeY - lastBound.h - - finalX = if (lastBound.w >= vp.sizeX) minX else finalX.coerceIn(minX, maxX) - finalY = if (lastBound.h >= vp.sizeY) minY else finalY.coerceIn(minY, maxY) - - pendingPositions[id] = finalX to finalY - snapOverlays[id] = SnapVisual(snap.snapX, snap.snapY, snap.kindX, snap.kindY) - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt new file mode 100644 index 000000000..3cdb687f2 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -0,0 +1,278 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.theme + +import androidx.compose.animation.core.FiniteAnimationSpec +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.VisibilityThreshold +import androidx.compose.animation.core.snap +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.foundation.text.selection.LocalTextSelectionColors +import androidx.compose.foundation.text.selection.TextSelectionColors +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.runtime.State +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.MotionDurationScale +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.platform.Font +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.LineHeightStyle +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.lambda.gui.core.Observation +import com.lambda.gui.core.Observations +import com.lambda.gui.core.observe +import com.lambda.module.modules.client.Style +import com.lambda.util.NamedEnum +import com.lambda.util.stream +import kotlin.math.roundToInt + +private const val LINE_HEIGHT = 10.95f + +private val ON_LIGHT_ACCENT = Color(0xFF1B1024) + +@Immutable +data class Palette( + val primary: Color, + val secondary: Color, + val surface: Color, + val panel: Color, + val inset: Color, + val onSurface: Color, + val onSurfaceVariant: Color, + val header: Color, + val onHeader: Color, + val moduleEnabled: Color, + val onModuleEnabled: Color, + val control: Color, + val controlSelected: Color, + val onControl: Color, + val track: Color, + val input: Color, + val border: Color, + val textShadow: Color, +) { + val onPrimary = primary.contrast() + val onSecondary = secondary.contrast() + val trackFilled = + if (onControl.luminance() > 0.5f) primary + else primary.copy(alpha = 0.6f) + val raised = onSurface.copy(alpha = 0.11f) + val hover = onSurface.copy(alpha = 0.06f) + + private fun Color.contrast() = + if (luminance() > 0.2f) ON_LIGHT_ACCENT + else Color.White +} + +internal object Look { + private val observations = Observations() + + val windowRounding by style { Style.windowRounding.dp } + val panelRounding by style { Style.panelRounding.dp } + val menuRounding by style { Style.menuRounding.dp } + val controlRounding by style { Style.controlRounding.dp } + val boxRounding get() = controlRounding / 2 + + val outlines by style { Style.outlines } + val outlineWidth by style { Style.outlineWidth.dp } + val shadows by style { Style.shadows } + val emboss by style { Style.emboss } + val backdropBlur by style { if (Style.blur) (Style.blurRadius / 2f).dp else 0.dp } + val underlay by style { 1f - Style.layerFade } + + val rowHeight by style { Style.elementHeight.dp } + val windowWidth by style { Style.windowWidth.dp } + val settingsWidth by style { Style.settingsWidth.dp } + val notificationScale by style { Style.notificationScale } + val notificationWidth by style { Style.notificationWidth.dp } + val windowGap by style { Style.windowGap.dp } + val windowTop by style { Style.windowTop.dp } + val modulePadding by style { Style.modulePadding.dp } + val panelPadding by style { Style.panelPadding.dp } + val settingSpacing by style { Style.settingSpacing.dp } + val groupIndent by style { Style.groupIndent.dp } + + fun refresh() = observations.refresh() + + private fun style(read: () -> T): State = + Observation(read).also { observations.active += it }.state +} + +internal object Motion : MotionDurationScale { + private const val PAGE_MILLIS = 160 + private const val GUI_MILLIS = 180 + private const val NOTIFICATION_MILLIS = 260 + private val UNFOLDING = + spring( + stiffness = Spring.StiffnessMedium, + visibilityThreshold = IntSize.VisibilityThreshold + ) + + val SCROLL = + object : MotionDurationScale { + override val scaleFactor get() = + if (Style.smoothScrolling) 1f + else 0f + } + + val NOTIFICATIONS: FiniteAnimationSpec = tween(NOTIFICATION_MILLIS) + + val UNSCALED = + object : MotionDurationScale { + override val scaleFactor get() = 1f + } + + override val scaleFactor get() = + if (Style.animations) 1f / Style.animationSpeed + else 0f + + val windows: FiniteAnimationSpec + get() = if (Style.windowAnimations) spring() else snap() + val panels: FiniteAnimationSpec + get() = if (Style.panelAnimations) UNFOLDING else snap() + val pageMillis + get() = if (Style.pageAnimations) PAGE_MILLIS else 0 + fun gui(distance: Float): FiniteAnimationSpec = + tween((GUI_MILLIS * distance).roundToInt()) + val guiFold: FiniteAnimationSpec + get() = tween(GUI_MILLIS) +} + +enum class GuiTransition(override val displayName: String) : NamedEnum { + Unfold("Unfold"), + Fade("Fade"), + Slide("Slide"), + Zoom("Zoom"), +} + +enum class GuiInterrupt(override val displayName: String) : NamedEnum { + Reverse("Reverse"), + Finish("Skip To End"), +} + +enum class GuiFont( + override val displayName: String, + val size: TextUnit, + val smallSize: TextUnit, + val titleWeight: FontWeight +) : NamedEnum { + Minecraft("Minecraft", 12.sp, 12.sp, FontWeight.Normal), + FiraSans("Fira Sans", 10.sp, 9.sp, FontWeight.Bold), + System("System", 10.sp, 9.sp, FontWeight.Bold); + + val family: FontFamily by lazy { + fun font(file: String, weight: FontWeight) = + Font(file, "fonts/$file".stream.use { it.readAllBytes() }, weight) + when (this) { + Minecraft -> + FontFamily(font("MinecraftDefault-Regular.ttf", FontWeight.Normal)) + FiraSans -> + FontFamily( + font("FiraSans-Regular.ttf", FontWeight.Normal), + font("FiraSans-Bold.ttf", FontWeight.Bold) + ) + System -> FontFamily.SansSerif + } + } +} + +@Immutable +private class Typography(font: GuiFont, scale: Float = 1f) { + val title = compact(font, font.size * scale, font.titleWeight) + val body = compact(font, font.size * scale) + val label = compact(font, font.smallSize * scale) + + private fun compact( + font: GuiFont, + size: TextUnit, + weight: FontWeight = FontWeight.Normal + ) = + TextStyle( + fontFamily = font.family, + fontWeight = weight, + fontSize = size, + lineHeight = if (font == GuiFont.Minecraft) size else size * 1.25f, + lineHeightStyle = LineHeightStyle( + LineHeightStyle.Alignment.Center, + LineHeightStyle.Trim.Both + ), + ) +} + +object Type { + val title: TextStyle @Composable @ReadOnlyComposable get() = LocalTypography.current.title + val body: TextStyle @Composable @ReadOnlyComposable get() = LocalTypography.current.body + val label: TextStyle @Composable @ReadOnlyComposable get() = LocalTypography.current.label +} + +object LambdaTheme { + val colors: Palette + @Composable @ReadOnlyComposable get() = LocalPalette.current +} + +private val LocalPalette = + staticCompositionLocalOf { error("No LambdaTheme in this composition") } +private val LocalTypography = + staticCompositionLocalOf { error("No LambdaTheme in this composition") } + +val LocalContentColor = compositionLocalOf { Color.White } + +@Composable +fun LambdaTheme(content: @Composable () -> Unit) { + val palette by observe { Style.palette } + val font by observe { Style.font } + val fontSize by observe { Style.fontSize } + val measurer = rememberTextMeasurer() + val typography = + remember(font, fontSize) { + if (font == GuiFont.Minecraft) return@remember Typography(font, fontSize) + val line = + measurer.measure( + "Ag", + Typography(font).body, + density = Density(1f) + ).size.height + Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f) * fontSize) + } + CompositionLocalProvider( + LocalPalette provides palette, + LocalTypography provides typography, + LocalTextSelectionColors provides + TextSelectionColors( + palette.primary, + palette.primary.copy(alpha = 0.4f) + ), + LocalContentColor provides palette.onSurface, + content = content + ) +} diff --git a/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt new file mode 100644 index 000000000..a467ec9f7 --- /dev/null +++ b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt @@ -0,0 +1,68 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.interaction.handler.handlers + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.lambda.Lambda.mc +import com.lambda.core.Loadable +import com.lambda.event.events.ComposeEvent +import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe +import com.lambda.gui.Notifications +import com.lambda.gui.core.RenderThread +import com.lambda.module.modules.client.Style +import java.awt.Color + +object NotificationHandler : Loadable { + private const val MAX_KEPT = 40 + + private val kept = mutableStateListOf() + val notifications: List get() = kept + + init { + listenUnsafe { event -> + if (kept.isNotEmpty()) event.content { Notifications() } + } + } + + override fun load() = "Loaded Notification Handler" + + fun notify(title: String, message: String = "", accent: Color? = null) = + mc.execute { + val notification = Notification(title, message, accent) + kept += notification + if (kept.size > MAX_KEPT) kept.removeRange(0, kept.size - MAX_KEPT) + kept.filterNot { it.dismissed } + .dropLast(Style.maxNotifications) + .forEach { it.dismissed = true } + RenderThread.after((Style.notificationSeconds * 1000).toLong()) { + notification.dismissed = true + } + } + + fun remove(notification: Notification) { + kept -= notification + } + + class Notification(val title: String, val message: String, val accent: Color?) { + var dismissed by mutableStateOf(false) + internal set + } +} diff --git a/src/main/kotlin/com/lambda/module/HudModule.kt b/src/main/kotlin/com/lambda/module/HudModule.kt index 5a4372b02..330d1f82a 100644 --- a/src/main/kotlin/com/lambda/module/HudModule.kt +++ b/src/main/kotlin/com/lambda/module/HudModule.kt @@ -17,8 +17,8 @@ package com.lambda.module +import androidx.compose.runtime.Composable import com.lambda.config.settings.complex.Bind -import com.lambda.gui.Layout import java.awt.Color abstract class HudModule( @@ -28,6 +28,26 @@ abstract class HudModule( alwaysListening: Boolean = false, enabledByDefault: Boolean = false, defaultKeybind: Bind = Bind.EMPTY, -) : Module(name, description, tag, alwaysListening, enabledByDefault, defaultKeybind = defaultKeybind), Layout { +) : Module( + name, + description, + tag, + alwaysListening, + enabledByDefault, + defaultKeybind = defaultKeybind +) { val backgroundColor = setting("Background Color", Color(0, 0, 0, 0)) + + var anchorX by setting("HUD X", DEFAULT_ANCHOR, 0f..1f, 0.001f) { false } + var anchorY by setting("HUD Y", (DEFAULT_ANCHOR + DEFAULT_SPACING * created++).coerceAtMost(1f), 0f..1f, 0.001f) { false } + + @Composable + abstract fun Content() + + private companion object { + const val DEFAULT_ANCHOR = 0.01f + + const val DEFAULT_SPACING = 0.06f + var created = 0 + } } diff --git a/src/main/kotlin/com/lambda/module/Module.kt b/src/main/kotlin/com/lambda/module/Module.kt index a5ab332b1..2f73164a5 100644 --- a/src/main/kotlin/com/lambda/module/Module.kt +++ b/src/main/kotlin/com/lambda/module/Module.kt @@ -125,7 +125,8 @@ abstract class Module( enabledByDefault: Boolean = false, modulePriority: Int = 0, defaultKeybind: Bind = Bind.EMPTY, - autoDisable: Boolean = false + autoDisable: Boolean = false, + val alwaysEnabled: Boolean = false, ) : Nameable, Muteable, OwnerPriority, Config(name, ModuleCategory), IMutableAutomationConfig by MutableAutomationConfig() { @@ -145,8 +146,11 @@ abstract class Module( val drawSetting = setting("Draw", true, "Draws the module in the module list hud element") { false } val showInClickGui = setting("Show In ClickGui", true, "Shows the module in the ClickGui layout") { false } - var isEnabled by isEnabledSetting - private set + var isEnabled: Boolean + get() = alwaysEnabled || isEnabledSetting.value + private set(value) { + isEnabledSetting.value = value + } val isDisabled get() = !isEnabled val keybind by keybindSetting @@ -170,18 +174,21 @@ abstract class Module( @ModuleDsl fun enable() { + if (alwaysEnabled) return ModuleEvent.Enabled(this@Module).post() isEnabled = true } @ModuleDsl fun disable() { + if (alwaysEnabled) return ModuleEvent.Disabled(this@Module).post() isEnabled = false } @ModuleDsl fun toggle() { + if (alwaysEnabled) return ModuleEvent.Toggle(this@Module, !isEnabled).post() if (isEnabled) disable() else enable() } diff --git a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt index 4d3dd975e..7e41ea5b4 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt @@ -18,13 +18,7 @@ package com.lambda.module.modules.client import com.lambda.Lambda.mc -import com.lambda.event.events.GuiEvent -import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.LambdaScreen -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.gui.dsl.ImGuiBuilder.popupModal -import com.lambda.imgui.ImGui -import com.lambda.imgui.flag.ImGuiWindowFlags +import com.lambda.gui.LambdaGui import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.threading.runIO @@ -48,9 +42,10 @@ object AutoUpdater : Module( private var loaderPromptHandled by property(false) - @JvmStatic var showFirstLaunchModal = false - @JvmStatic var showInstallModal = false - @JvmStatic var showUninstallModal = false + internal enum class Prompt { FirstLaunch, Install, Uninstall } + + internal var prompt: Prompt? = null + private set private var firstLaunchStateInitialized = false private const val MAVEN_URL = "https://maven.lambda-client.org" @@ -64,102 +59,41 @@ object AutoUpdater : Module( Dev } - const val WINDOW_FLAGS = - ImGuiWindowFlags.AlwaysAutoResize or - ImGuiWindowFlags.NoMove or - ImGuiWindowFlags.NoResize or - ImGuiWindowFlags.NoScrollbar or - ImGuiWindowFlags.NoScrollWithMouse - init { - onEnableUnsafe { - if (mc.currentScreen is LambdaScreen && !showUninstallModal) - showInstallModal = true - showUninstallModal = false - } - - onDisableUnsafe { - if (mc.currentScreen is LambdaScreen && !showInstallModal) - showUninstallModal = true - showInstallModal = false - } - - listen(alwaysListen = true) { - initializeFirstLaunchStateIfNeeded() - - if (showFirstLaunchModal) { - if (mc.currentScreen !is LambdaScreen) return@listen - - ImGui.openPopup("Loader Installation Wizard") - popupModal("Loader Installation Wizard", WINDOW_FLAGS) { - renderLoaderInstallExplanation() - - val buttonWidth = (ImGui.getContentRegionAvailX() - ImGui.getStyle().itemSpacing.x) / 2f - - button("Switch To Loader", buttonWidth, 0f) { - completeFirstLaunchPrompt() - showInstallModal = false - showUninstallModal = false - installLoader() - } - - sameLine() - - button("Keep Current Jar", buttonWidth, 0f) { - completeFirstLaunchPrompt() - } - } - return@listen - } - - showFirstLaunchModal = false - - if (showInstallModal) { - ImGui.openPopup("Loader Installation Wizard") - popupModal("Loader Installation Wizard", WINDOW_FLAGS) { - renderLoaderInstallExplanation() - - val buttonWidth = (ImGui.getContentRegionAvailX() - ImGui.getStyle().itemSpacing.x) / 2f - - button("Switch To Loader", buttonWidth, 0f) { - installLoader() - showInstallModal = false - } - - sameLine() - - button("Cancel", buttonWidth, 0f) { - disable() - } - } - return@listen - } - - showInstallModal = false - - if (showUninstallModal) { - ImGui.openPopup("Uninstall Loader") - popupModal("Uninstall Loader", WINDOW_FLAGS) { - text("Do you want to uninstall Lambda Loader?") - separator() - text("This will close the client automatically once the uninstall is finished.") - spacing() + onEnableUnsafe { prompt = Prompt.Install.takeIf { LambdaGui.screen != null && prompt != Prompt.Uninstall } } + onDisableUnsafe { prompt = Prompt.Uninstall.takeIf { LambdaGui.screen != null && prompt != Prompt.Install } } + } - button("Uninstall", 120f, 0f) { - installClient() - showUninstallModal = false - } + internal fun onGuiOpened() { + if (firstLaunchStateInitialized) return + firstLaunchStateInitialized = true - sameLine() + if (FabricLoader.getInstance().isModLoaded("lambda-loader")) { + loaderPromptHandled = true + if (!isEnabled) enable() + return + } + if (!loaderPromptHandled) prompt = Prompt.FirstLaunch + } - button("Cancel", 120f, 0f) { - enable() - } - } - return@listen + internal fun answerPrompt(accepted: Boolean) { + when (prompt) { + Prompt.FirstLaunch -> { + loaderPromptHandled = true + prompt = null + if (accepted) installLoader() } - - showUninstallModal = false + Prompt.Install -> + if (accepted) { + prompt = null + installLoader() + } else disable() + Prompt.Uninstall -> + if (accepted) { + prompt = null + installClient() + } else enable() + null -> Unit } } @@ -363,47 +297,4 @@ object AutoUpdater : Module( val modContainer = fabricLoader.getModContainer(modId) return modContainer.get().origin.paths[0].toAbsolutePath() } - - private fun initializeFirstLaunchStateIfNeeded() { - if (firstLaunchStateInitialized) return - firstLaunchStateInitialized = true - - val usingLoader = FabricLoader.getInstance().isModLoaded("lambda-loader") - if (usingLoader) { - completeFirstLaunchPrompt() - if (!isEnabled) enable() - return - } - - showFirstLaunchModal = !loaderPromptHandled - } - - private fun ImGuiBuilder.renderLoaderInstallExplanation() { - text("Switch to Lambda Loader?") - separator() - spacing() - text("Lambda Loader replaces this version-specific Lambda jar") - text("with a lightweight bootstrap that keeps Lambda up to date.") - spacing() - text("Benefits:") - text("- Automatic updates on launch") - text("- No manual jar replacement") - spacing() - text("If you choose to switch, Lambda will install the loader") - text("and close the game so changes apply on next start.") - spacing() - separator() - text("You can change this later from the AutoUpdater module.") - spacing() - } - - @JvmStatic - fun dismissFirstLaunchPrompt() { - completeFirstLaunchPrompt() - } - - private fun completeFirstLaunchPrompt() { - loaderPromptHandled = true - showFirstLaunchModal = false - } } diff --git a/src/main/kotlin/com/lambda/module/modules/client/Client.kt b/src/main/kotlin/com/lambda/module/modules/client/Client.kt index 56449d62e..5c349d334 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Client.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Client.kt @@ -29,7 +29,7 @@ object Client : Module( name = "Client", description = "Global settings for Lambda", tag = ModuleTag.CLIENT, - enabledByDefault = true + alwaysEnabled = true, ) { private const val GENERAL_TAB = "General" private const val DEBUG_TAB = "Debug" diff --git a/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt b/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt index 40a791379..78789fa2c 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt @@ -19,6 +19,7 @@ package com.lambda.module.modules.client import com.lambda.event.events.ModuleEvent import com.lambda.event.listener.SafeListener.Companion.listen +import com.lambda.interaction.handler.handlers.NotificationHandler import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.util.CommunicationUtils.log @@ -38,16 +39,17 @@ object ModuleNotifier : Module( tag = ModuleTag.CLIENT, enabledByDefault = true ) { - var notifyTarget by setting("Notify Target", setOf(NotifyTarget.ActionBar), NotifyTarget.entries.toSet(), description = "Where to send notifications when modules are toggled") + var notifyTarget by setting("Notify Target", setOf(NotifyTarget.Notification), NotifyTarget.entries.toSet(), description = "Where to send notifications when modules are toggled") enum class NotifyTarget(override val displayName: String, override val description: String) : Describable, NamedEnum { Chat("Chat", "Sends a message to chat when a module is toggled"), - ActionBar("Action Bar", "Sends a message to the action bar when a module is toggled"), ; + ActionBar("Action Bar", "Sends a message to the action bar when a module is toggled"), + Notification("Notification", "Slides a notification in at the lower right of the screen when a module is toggled"), ; } init { listen { event -> - logToTargets(event.module) { + logToTargets(event.module, "Enabled", Color(Colors.GREEN)) { color(Color(Colors.GREEN)) { literal("on") } @@ -55,7 +57,7 @@ object ModuleNotifier : Module( } listen { event -> - logToTargets(event.module) { + logToTargets(event.module, "Disabled", Color(Colors.RED)) { color(Color(Colors.RED)) { literal("off") } @@ -63,7 +65,10 @@ object ModuleNotifier : Module( } } - private fun logToTargets(module: Module, action: TextBuilder.() -> Unit) { + private fun logToTargets(module: Module, state: String, color: Color, action: TextBuilder.() -> Unit) { + if (NotifyTarget.Notification in notifyTarget) { + NotificationHandler.notify(module.name, state, color) + } if (NotifyTarget.Chat in notifyTarget) { module.log(buildText(action)) } diff --git a/src/main/kotlin/com/lambda/module/modules/client/Style.kt b/src/main/kotlin/com/lambda/module/modules/client/Style.kt new file mode 100644 index 000000000..292b0dd21 --- /dev/null +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -0,0 +1,259 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.module.modules.client + +import com.lambda.config.Config +import com.lambda.config.ConfigBlock +import com.lambda.config.Group +import com.lambda.config.settings.appliedOnRelease +import com.lambda.gui.theme.GuiFont +import com.lambda.gui.theme.GuiInterrupt +import com.lambda.gui.theme.GuiTransition +import com.lambda.gui.theme.Palette +import com.lambda.module.Module +import com.lambda.module.ModuleTag +import com.lambda.util.NamedEnum +import com.lambda.util.math.toCompose +import org.jetbrains.skiko.SystemTheme +import org.jetbrains.skiko.currentSystemTheme +import java.awt.Color + +object Style : Module( + name = "Style", + description = "How Lambda's interface looks", + tag = ModuleTag.CLIENT, + alwaysEnabled = true, +) { + private const val BACKDROP_GROUP = "Backdrop" + private const val SHAPE_GROUP = "Shape" + private const val LAYOUT_GROUP = "Layout" + private const val MOTION_GROUP = "Motion" + private const val NOTIFICATIONS_GROUP = "Notifications" + private const val DARK_THEME_GROUP = "Dark Theme" + private const val LIGHT_THEME_GROUP = "Light Theme" + + private enum class ThemeMode(override val displayName: String) : NamedEnum { + Auto("Auto"), + Dark("Dark"), + Light("Light"), + } + + private val themeMode by setting("Theme", ThemeMode.Dark, "Auto follows the theme of your operating system") + val font by setting("Font", GuiFont.Minecraft, "The Minecraft font is sharpest where the interface is a whole number of times its natural size: at 1080p and 2160p with a scale of 1") + val fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") + val scale by setting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() + + @Group(BACKDROP_GROUP) val dimBackground by setting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") + @Group(BACKDROP_GROUP) val dimStrength by setting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } + @Group(BACKDROP_GROUP) val blur by setting("Blur", true, "Blurs what is behind windows for a frosted glass look") + @Group(BACKDROP_GROUP) val blurRadius by setting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } + @Group(BACKDROP_GROUP) val layerFade by setting("Layer Fade", 0.5f, 0f..1f, 0.05f, "How far the interface fades out underneath a panel, menu or window opened over it, letting the game show there instead so the two do not run together") { blur } + @Group(BACKDROP_GROUP) val glow by setting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") + @Group(BACKDROP_GROUP) val glowRadius by setting("Glow Radius", 17f, 1f..100f, 1f) { glow } + @Group(BACKDROP_GROUP) val glowIntensity by setting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } + + @Group(SHAPE_GROUP) val windowRounding by setting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") + @Group(SHAPE_GROUP) val panelRounding by setting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") + @Group(SHAPE_GROUP) val menuRounding by setting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") + @Group(SHAPE_GROUP) val controlRounding by setting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") + @Group(SHAPE_GROUP) val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") + @Group(SHAPE_GROUP) val outlineWidth by setting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } + @Group(SHAPE_GROUP) val shadows by setting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") + @Group(SHAPE_GROUP) val emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") + + @Group(LAYOUT_GROUP) val elementHeight by setting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") + @Group(LAYOUT_GROUP) val windowWidth by setting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") + @Group(LAYOUT_GROUP) val settingsWidth by setting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") + @Group(LAYOUT_GROUP) val windowGap by setting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") + @Group(LAYOUT_GROUP) val windowTop by setting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") + @Group(LAYOUT_GROUP) val modulePadding by setting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") + @Group(LAYOUT_GROUP) val panelPadding by setting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") + @Group(LAYOUT_GROUP) val settingSpacing by setting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") + @Group(LAYOUT_GROUP) val groupIndent by setting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") + @Group(LAYOUT_GROUP) val inlineSettings by setting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") + @Group(LAYOUT_GROUP) val multipleSettings by setting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") + + @Group(MOTION_GROUP) val animations by setting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") + @Group(MOTION_GROUP) val animationSpeed by setting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } + @Group(MOTION_GROUP) val openAnimation by setting("Open Animation", true, "Animates the click GUI in when it opens") { animations } + @Group(MOTION_GROUP) val openStyle by setting("Open Style", setOf(GuiTransition.Unfold), GuiTransition.entries.toSet(), "What the click GUI does as it comes in, any of them together: its windows unfold out of their headers, and all of it fades, slides down or zooms in") { animations && openAnimation } + @Group(MOTION_GROUP) val closeAnimation by setting("Close Animation", true, "Animates the click GUI out when it closes. The game has the mouse and keyboard back at once: the animation only plays over it") { animations } + @Group(MOTION_GROUP) val closeStyle by setting("Close Style", setOf(GuiTransition.Unfold, GuiTransition.Fade), GuiTransition.entries.toSet(), "What the click GUI does as it goes out, any of them together: its windows fold into their headers, and all of it fades, slides up or zooms out") { animations && closeAnimation } + @Group(MOTION_GROUP) val interruptedAnimation by setting("Interrupted Animation", GuiInterrupt.Reverse, "What happens when the click GUI is opened or closed again before its animation is done: it turns around from where it is, or skips to the end and plays the other one in full") { animations && (openAnimation || closeAnimation) } + @Group(MOTION_GROUP) val windowAnimations by setting("Window Animations", true, "Category windows unfold out of their headers") { animations } + @Group(MOTION_GROUP) val panelAnimations by setting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } + @Group(MOTION_GROUP) val pageAnimations by setting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } + @Group(MOTION_GROUP) val smoothScrolling by setting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") + @Group(MOTION_GROUP) val scrollSpeed by setting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") + @Group(MOTION_GROUP) val tooltipDelay by setting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") + + @Group(NOTIFICATIONS_GROUP) val notificationScale by setting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface") + @Group(NOTIFICATIONS_GROUP) val notificationWidth by setting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines") + @Group(NOTIFICATIONS_GROUP) val notificationSeconds by setting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it slides away") + @Group(NOTIFICATIONS_GROUP) val maxNotifications by setting("Max Notifications", 5, 1..12, 1, "How many notifications stack before the oldest slides off the bottom of the screen") + + @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( + PaletteSettings( + this, + primary = Color(214, 77, 113), + secondary = Color(255, 141, 128), + surface = Color(69, 48, 55, 165), + panel = Color(55, 38, 45, 200), + inset = Color(0, 0, 0, 190), + onSurface = Color(246, 236, 239), + onSurfaceVariant = Color(184, 156, 166), + header = Color(222, 53, 101), + onHeader = Color(255, 246, 248), + moduleEnabled = Color(161, 42, 75), + onModuleEnabled = Color(255, 240, 244), + control = Color(214, 77, 113), + controlSelected = Color(92, 64, 75), + onControl = Color(246, 236, 239), + track = Color(38, 28, 32, 230), + input = Color(32, 23, 26, 230), + border = Color(128, 92, 104, 235), + textShadow = Color(0, 0, 0, 150), + glowA = Color(222, 53, 101), + glowB = Color(255, 141, 128), + ) + ) + + @Group(LIGHT_THEME_GROUP) private val lightTheme by configBlock( + PaletteSettings( + this, + primary = Color(222, 53, 101), + secondary = Color(209, 74, 59), + surface = Color(250, 236, 241, 228), + panel = Color(244, 226, 232, 240), + inset = Color(120, 0, 40, 68), + onSurface = Color(61, 40, 47), + onSurfaceVariant = Color(110, 86, 95), + header = Color(222, 53, 101), + onHeader = Color(255, 250, 251), + moduleEnabled = Color(232, 84, 126), + onModuleEnabled = Color(255, 250, 251), + control = Color(240, 139, 166), + controlSelected = Color(224, 197, 206), + onControl = Color(61, 40, 47), + track = Color(209, 192, 199, 220), + input = Color(255, 250, 252, 210), + border = Color(184, 154, 164, 238), + textShadow = Color(0, 0, 0, 0), + glowA = Color(222, 53, 101), + glowB = Color(255, 141, 128), + ) + ) + + private val theme: PaletteSettings + get() = + when (themeMode) { + ThemeMode.Dark -> darkTheme + ThemeMode.Light -> lightTheme + ThemeMode.Auto -> + if (SystemAppearance.isDark) darkTheme + else lightTheme + } + + val palette: Palette get() = theme.toPalette() + val glowColorA: Color get() = theme.glowA + val glowColorB: Color get() = theme.glowB + + private object SystemAppearance { + private const val REFRESH_MILLIS = 1000L + + private var checkedAt = 0L + private var dark = true + + val isDark: Boolean + get() { + val now = System.currentTimeMillis() + if (now - checkedAt > REFRESH_MILLIS) { + checkedAt = now + dark = currentSystemTheme != SystemTheme.LIGHT + } + return dark + } + } +} + +class PaletteSettings( + override val c: Config, + primary: Color, + secondary: Color, + surface: Color, + panel: Color, + inset: Color, + onSurface: Color, + onSurfaceVariant: Color, + header: Color, + onHeader: Color, + moduleEnabled: Color, + onModuleEnabled: Color, + control: Color, + controlSelected: Color, + onControl: Color, + track: Color, + input: Color, + border: Color, + textShadow: Color, + glowA: Color, + glowB: Color, +) : ConfigBlock { + private val primary by c.setting("Primary", primary, "Accent colour: the fill of sliders and ticked boxes") + private val secondary by c.setting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") + private val surface by c.setting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") + private val panel by c.setting("Panel", panel, "Fill of settings panels, menus and dialogs") + private val inset by c.setting("Inset", inset, "Shade behind settings that open under their module, and over the module whose settings are open beside it") + private val onSurface by c.setting("On Surface", onSurface, "Text on windows") + private val onSurfaceVariant by c.setting("On Surface Variant", onSurfaceVariant, "Subdued text on windows") + private val header by c.setting("Header", header) + private val onHeader by c.setting("On Header", onHeader) + private val moduleEnabled by c.setting("Module Enabled", moduleEnabled) + private val onModuleEnabled by c.setting("On Module Enabled", onModuleEnabled) + private val control by c.setting("Control", control, "Fill of dropdowns, buttons and key caps") + private val controlSelected by c.setting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") + private val onControl by c.setting("On Control", onControl) + private val track by c.setting("Slider Track", track) + private val input by c.setting("Text Field", input) + private val border by c.setting("Border", border) + private val textShadow by c.setting("Text Shadow", textShadow) + val glowA by c.setting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { Style.glow } + val glowB by c.setting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { Style.glow } + + fun toPalette() = + Palette( + primary = primary.toCompose(), + secondary = secondary.toCompose(), + surface = surface.toCompose(), + panel = panel.toCompose(), + inset = inset.toCompose(), + onSurface = onSurface.toCompose(), + onSurfaceVariant = onSurfaceVariant.toCompose(), + header = header.toCompose(), + onHeader = onHeader.toCompose(), + moduleEnabled = moduleEnabled.toCompose(), + onModuleEnabled = onModuleEnabled.toCompose(), + control = control.toCompose(), + controlSelected = controlSelected.toCompose(), + onControl = onControl.toCompose(), + track = track.toCompose(), + input = input.toCompose(), + border = border.toCompose(), + textShadow = textShadow.toCompose(), + ) +} diff --git a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt index f6562419b..66129f462 100644 --- a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt +++ b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt @@ -25,10 +25,10 @@ import com.lambda.event.events.PlayerEvent import com.lambda.event.events.TickEvent import com.lambda.event.events.WorldEvent import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.components.ClickGuiLayout import com.lambda.interaction.handler.handlers.FriendHandler import com.lambda.module.Module import com.lambda.module.ModuleTag +import com.lambda.module.modules.client.Style import com.lambda.module.modules.network.AutoReconnect import com.lambda.sound.SoundHandler.playSound import com.lambda.util.CommunicationUtils @@ -44,6 +44,7 @@ import com.lambda.util.extension.fullHealth import com.lambda.util.extension.tickDeltaF import com.lambda.util.item.ItemStackUtils.bundleStacks import com.lambda.util.item.ItemStackUtils.shulkerBoxStacks +import com.lambda.util.math.toAwt import com.lambda.util.player.MovementUtils.moveDelta import com.lambda.util.player.PlayerUtils.isIn2b2tQueue import com.lambda.util.player.SlotUtils.allStacks @@ -654,7 +655,9 @@ object AutoDisconnect : Module( buildText { text(effect.effectType.value().name) if (effect.amplifier > 0) literal(" ${effect.amplifier + 1}") - color(ClickGuiLayout.textDisabled) { literal(" (${effectDuration(effect)})") } + color(Style.palette.onSurfaceVariant.toAwt()) { + literal(" (${effectDuration(effect)})") + } } ) } @@ -741,7 +744,7 @@ object AutoDisconnect : Module( val customName = stack.get(DataComponentTypes.CUSTOM_NAME) if (customName != null) { text(stack.itemName) - color(ClickGuiLayout.textDisabled) { + color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (") text(customName) literal(")") @@ -751,11 +754,13 @@ object AutoDisconnect : Module( } if (stack.isDamageable) { - color(ClickGuiLayout.textDisabled) { literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") } + color(Style.palette.onSurfaceVariant.toAwt()) { + literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") + } } if (stack.maxCount > 1) { - color(ClickGuiLayout.textDisabled) { literal(" (${stack.count})") } + color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.count})") } } if (selected) { diff --git a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt index 17fe66f20..e9196fbff 100644 --- a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt +++ b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt @@ -17,7 +17,8 @@ package com.lambda.module.modules.combat.autodisconnect -import com.lambda.gui.components.ClickGuiLayout +import androidx.compose.ui.graphics.toArgb +import com.lambda.module.modules.client.Style import com.lambda.util.text.buildText import com.lambda.util.text.highlighted import com.lambda.util.text.text @@ -267,13 +268,10 @@ class DisconnectDetailsWidget( const val HOVER_PADDING = 2 const val HOVER_RADIUS = 1 - // Pulled live from the click GUI theme so the panel matches the user's colors. - val COLOR_TEXT get() = ClickGuiLayout.text.rgb - val COLOR_BACKGROUND get() = ClickGuiLayout.windowBg.rgb - val COLOR_BORDER get() = ClickGuiLayout.border.rgb - val COLOR_HOVER_BACKGROUND get() = ClickGuiLayout.headerHovered.rgb - - // Header text tinted by compositing the highlight color over the text color. - val COLOR_HEADER get() = ClickGuiLayout.text.rgb//composite(COLOR_TEXT, COLOR_HOVER_BACKGROUND) + val COLOR_TEXT get() = Style.palette.onSurface.toArgb() + val COLOR_BACKGROUND get() = Style.palette.panel.toArgb() + val COLOR_BORDER get() = Style.palette.border.toArgb() + val COLOR_HOVER_BACKGROUND get() = Style.palette.controlSelected.toArgb() + val COLOR_HEADER get() = COLOR_TEXT } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/AccountName.kt b/src/main/kotlin/com/lambda/module/modules/hud/AccountName.kt index 859694b81..d25f8825f 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/AccountName.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/AccountName.kt @@ -17,10 +17,12 @@ package com.lambda.module.modules.hud -import com.lambda.gui.dsl.ImGuiBuilder +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import com.lambda.gui.core.observeSafe +import com.lambda.gui.hud.HudText import com.lambda.module.HudModule import com.lambda.module.ModuleTag -import com.lambda.threading.runSafe @Suppress("unused") object AccountName : HudModule( @@ -28,7 +30,9 @@ object AccountName : HudModule( description = "Displays the current accounts name", tag = ModuleTag.HUD ) { - override fun ImGuiBuilder.buildLayout() { - runSafe { text(player.name.string) } + @Composable + override fun Content() { + val name by observeSafe { player.name.string } + name?.let { HudText(it) } } } \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt new file mode 100644 index 000000000..d65f8cd53 --- /dev/null +++ b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt @@ -0,0 +1,80 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.module.modules.hud + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.unit.dp +import com.lambda.gui.component.ItemIcon +import com.lambda.gui.core.observe +import com.lambda.gui.core.observeSafe +import com.lambda.gui.hud.HudText +import com.lambda.module.HudModule +import com.lambda.module.ModuleTag +import com.lambda.util.NamedEnum +import net.minecraft.entity.EquipmentSlot + +@Suppress("unused") +object Armor : HudModule( + name = "Armor", + description = "Shows the armor you are wearing, as it looks in your inventory", + tag = ModuleTag.HUD, +) { + private enum class Layout(override val displayName: String) : NamedEnum { + Horizontal("Horizontal"), + Vertical("Vertical"), + } + + private val layout by setting("Layout", Layout.Horizontal) + private val iconSize by setting("Icon Size", 16f, 8f..64f, 1f, "Items are drawn at the nearest whole multiple of their 16 pixels, as Minecraft draws them") + + private val slots = + listOf( + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + ) + + @Composable + override fun Content() { + val worn by observeSafe { slots.map(player::getEquippedStack).filterNot { it.isEmpty } } + val layout by observe { layout } + val size by observe { iconSize.dp } + + val pieces = worn.orEmpty() + if (pieces.isEmpty()) { + HudText("No armor") + return + } + val spacing = Arrangement.spacedBy(size / 8) + when (layout) { + Layout.Horizontal -> + Row(horizontalArrangement = spacing) { + pieces.forEach { ItemIcon(it, size) } + } + Layout.Vertical -> + Column(verticalArrangement = spacing) { + pieces.forEach { ItemIcon(it, size) } + } + } + } +} diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Baritone.kt b/src/main/kotlin/com/lambda/module/modules/hud/Baritone.kt index 7d3ce6e16..03de639e0 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Baritone.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Baritone.kt @@ -17,7 +17,10 @@ package com.lambda.module.modules.hud -import com.lambda.gui.dsl.ImGuiBuilder +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import com.lambda.gui.core.observe +import com.lambda.gui.hud.HudText import com.lambda.interaction.construction.simulation.BuildGoal import com.lambda.interaction.handler.handlers.BaritoneHandler import com.lambda.module.HudModule @@ -29,17 +32,18 @@ object Baritone : HudModule( description = "Look inside of Baritones head", tag = ModuleTag.HUD, ) { - override fun ImGuiBuilder.buildLayout() { - if (!BaritoneHandler.baritoneAvailable) { - text("Baritone is not loaded") - return - } + @Composable + override fun Content() { + val status by observe { status() } + HudText(status) + } - BaritoneHandler.primary?.customGoalProcess?.goal?.let { - when(it) { - is BuildGoal -> text("Lambda Simulation: ${it.sim}") - else -> text("Baritone: $it") - } - } ?: text("No Baritone Process Running") + private fun status(): String { + if (!BaritoneHandler.baritoneAvailable) return "Baritone is not loaded" + return when (val goal = BaritoneHandler.primary?.customGoalProcess?.goal) { + null -> "No Baritone Process Running" + is BuildGoal -> "Lambda Simulation: ${goal.sim}" + else -> "Baritone: $goal" + } } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt b/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt index e3c169e51..b06deaf31 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt @@ -17,14 +17,17 @@ package com.lambda.module.modules.hud +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue import com.lambda.config.Tab import com.lambda.config.blocks.FormatterSettings import com.lambda.config.editSetting import com.lambda.config.withEdits -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.context.SafeContext +import com.lambda.gui.core.observeSafe +import com.lambda.gui.hud.HudText import com.lambda.module.HudModule import com.lambda.module.ModuleTag -import com.lambda.threading.runSafe import com.lambda.util.FormattingUtils.format import com.lambda.util.extension.dimensionName import com.lambda.util.extension.isNether @@ -51,26 +54,44 @@ object Coordinates : HudModule( // ::group.edit { defaultValue(FormatterConfig.TupleGrouping.SquareBrackets) } // } - override fun ImGuiBuilder.buildLayout() { - runSafe { - val position = player.pos.format(formatter) - val otherDimensionPos = // ToDo: The system has forced my hand, too bad!. We need to find a way to allow duplicate setting names. - if (world.isNether) player.overworldCoord.let { Vec2d(it.x, it.z) }.format(formatter.locale, formatter.separator, "[", "]", formatter.precision) - else player.netherCoord.let { Vec2d(it.x, it.z) }.format(formatter.locale, formatter.separator, "[", "]", formatter.precision) + @Composable + override fun Content() { + val coordinates by observeSafe { coordinates() } + coordinates?.let { HudText(it) } + } + + private fun SafeContext.coordinates(): String { + val position = player.pos.format(formatter) + val otherDimensionPos = + if (world.isNether) { + player.overworldCoord.let { Vec2d(it.x, it.z) }.format( + formatter.locale, + formatter.separator, + "[", + "]", + formatter.precision + ) + } + else { + player.netherCoord.let { Vec2d(it.x, it.z) }.format( + formatter.locale, + formatter.separator, + "[", + "]", + formatter.precision + ) + } - val text = - if (showCurrentDimensionOnly) position - else "$position $otherDimensionPos" + val text = + if (showCurrentDimensionOnly) position + else "$position $otherDimensionPos" - val withDimension = - if (showDimension) "$text ${world.dimensionName}" - else text + val withDimension = + if (showDimension) "$text ${world.dimensionName}" + else text - val withBiome = - if (showBiome) "$withDimension in ${beautifyBiome(world.getBiome(player.blockPos).idAsString)}" - else withDimension - textCopyable(withBiome) - } + return if (showBiome) "$withDimension in ${beautifyBiome(world.getBiome(player.blockPos).idAsString)}" + else withDimension } fun beautifyBiome(biome: String): String = biome diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Fps.kt b/src/main/kotlin/com/lambda/module/modules/hud/Fps.kt index 87f425840..78d6c9e89 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Fps.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Fps.kt @@ -17,9 +17,12 @@ package com.lambda.module.modules.hud +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue import com.lambda.event.events.RenderEvent import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.core.observe +import com.lambda.gui.hud.HudText import com.lambda.module.HudModule import com.lambda.module.ModuleTag import com.lambda.util.collections.LimitedDecayQueue @@ -60,7 +63,9 @@ object Fps : HudModule( } } - override fun ImGuiBuilder.buildLayout() { - text("FPS: $fps") + @Composable + override fun Content() { + val fps by observe { fps } + HudText("FPS: $fps") } } \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt b/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt index ef45c76b3..c4c7683da 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt @@ -17,12 +17,17 @@ package com.lambda.module.modules.hud -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.flag.ImGuiCol +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.graphics.Color +import com.lambda.config.settings.complex.Bind +import com.lambda.gui.core.observe +import com.lambda.gui.hud.HudText import com.lambda.module.HudModule import com.lambda.module.ModuleRegistry import com.lambda.module.ModuleTag -import java.awt.Color @Suppress("unused") object ModuleList : HudModule( @@ -36,20 +41,29 @@ object ModuleList : HudModule( drawSetting.value = false } - override fun ImGuiBuilder.buildLayout() { - val enabled = ModuleRegistry.modules.filter { it.isEnabled && it.draw } - - enabled.forEach { - val bound = it.keybind.key != 0 || it.keybind.mouse != -1 - if (onlyBound && !bound) return@forEach - text(it.name) - - if (showKeybind) { - val color = if (!bound) Color.RED else Color.GREEN - - sameLine() - withStyleColor(ImGuiCol.Text, color) { text(" [${it.keybind.name}]") } - } + @Composable + override fun Content() { + val entries by observe { + ModuleRegistry.modules + .filter { it.isEnabled && it.draw && !it.alwaysEnabled } + .map { it.name to it.keybind.takeIf { bind -> bind.key != 0 || bind.mouse != -1 } } + .filter { (_, bind) -> bind != null || !onlyBound } + } + val showKeybind by observe { showKeybind } + Column { + entries.forEach { (name, bind) -> + Row { + HudText(name) + if (showKeybind) { + HudText( + " [${(bind ?: Bind.EMPTY).name}]", + color = + if (bind != null) Color.Green + else Color.Red + ) + } + } + } } } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Rotation.kt b/src/main/kotlin/com/lambda/module/modules/hud/Rotation.kt index 767a31207..ef77934ef 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Rotation.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Rotation.kt @@ -17,13 +17,15 @@ package com.lambda.module.modules.hud +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue import com.lambda.config.blocks.FormatterSettings import com.lambda.config.editSetting import com.lambda.config.withEdits -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.core.observeSafe +import com.lambda.gui.hud.HudText import com.lambda.module.HudModule import com.lambda.module.ModuleTag -import com.lambda.threading.runSafe import com.lambda.util.FormattingUtils.format @Suppress("unused") @@ -37,10 +39,9 @@ object Rotation : HudModule( ::timeFormat.editSetting { hide() } } - override fun ImGuiBuilder.buildLayout() { - runSafe { - val rotation = player.rotationClient.format(formatter) - textCopyable(rotation) - } + @Composable + override fun Content() { + val rotation by observeSafe { player.rotationClient.format(formatter) } + rotation?.let { HudText(it) } } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Speedometer.kt b/src/main/kotlin/com/lambda/module/modules/hud/Speedometer.kt index 2030ba102..bf095f41d 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Speedometer.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Speedometer.kt @@ -17,10 +17,13 @@ package com.lambda.module.modules.hud +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue import com.lambda.context.SafeContext import com.lambda.event.events.TickEvent import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.dsl.ImGuiBuilder +import com.lambda.gui.core.observe +import com.lambda.gui.hud.HudText import com.lambda.module.HudModule import com.lambda.module.ModuleTag import com.lambda.util.SpeedUnit @@ -66,7 +69,9 @@ object Speedometer : HudModule( speedUnit.convertFromMinecraft(vecDelta.length()) } - override fun ImGuiBuilder.buildLayout() { - text("Speed: %.2f %s".format(speed, speedUnit.unitName)) + @Composable + override fun Content() { + val text by observe { "Speed: %.2f %s".format(speed, speedUnit.unitName) } + HudText(text) } } \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/module/modules/hud/TaskFlowHud.kt b/src/main/kotlin/com/lambda/module/modules/hud/TaskFlowHud.kt index 31de0284d..108de9564 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/TaskFlowHud.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/TaskFlowHud.kt @@ -17,7 +17,10 @@ package com.lambda.module.modules.hud -import com.lambda.gui.dsl.ImGuiBuilder +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import com.lambda.gui.core.observe +import com.lambda.gui.hud.HudText import com.lambda.module.HudModule import com.lambda.module.ModuleTag import com.lambda.module.modules.client.Client @@ -28,7 +31,9 @@ object TaskFlowHud : HudModule( name = "TaskFlowHud", tag = ModuleTag.HUD, ) { - override fun ImGuiBuilder.buildLayout() { - text(RootTask.taskTree(Client.showInvisibleTasks)) + @Composable + override fun Content() { + val tasks by observe { RootTask.taskTree(Client.showInvisibleTasks) } + HudText(tasks) } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt b/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt index 2e9104e06..c36621201 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt @@ -17,13 +17,28 @@ package com.lambda.module.modules.hud -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImVec2 +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import com.lambda.gui.core.observe +import com.lambda.gui.hud.HudConfig +import com.lambda.gui.hud.HudText import com.lambda.module.HudModule import com.lambda.module.ModuleTag import com.lambda.util.FormattingUtils.format import com.lambda.util.ServerTPSUtils import com.lambda.util.ServerTPSUtils.recentData +import com.lambda.util.math.toCompose @Suppress("unused") object Tps : HudModule( @@ -37,26 +52,44 @@ object Tps : HudModule( private val graphWidth by setting("Graph Width", 200f, 10f..500f, 1f) private val graphStride by setting("Graph Stride", 1, 1..20, 1) - override fun ImGuiBuilder.buildLayout() { - val data = recentData(format) + @Composable + override fun Content() { + val format by observe { format } + val data by observe { recentData(format).toList() } if (data.isEmpty()) { - text("No ${format.displayName} data yet") + HudText("No ${format.displayName} data yet") return } - val current = data.last() - val avg = data.average().toFloat() + val average = data.average().toFloat() + val showGraph by observe { showGraph } if (!showGraph) { - text("${format.displayName}: ${avg.format()}${format.unit}") + HudText("${format.displayName}: ${average.format()}${format.unit}") return } - val overlay = "cur ${current.format()}${format.unit} | avg ${avg.format()}${format.unit}" - plotLines( - label = "##TPSPlot", - values = data, - overlayText = overlay, - graphSize = ImVec2(graphWidth, graphHeight), - stride = graphStride - ) + val size by observe { DpSize(graphWidth.dp, graphHeight.dp) } + val stride by observe { graphStride } + val lineColor by observe { HudConfig.textColor.toCompose() } + Box( + Modifier.size(size).drawBehind { drawGraph(data, stride, lineColor) }, + Alignment.TopCenter + ) { + HudText("cur ${data.last().format()}${format.unit} | avg ${average.format()}${format.unit}") + } + } + + private fun DrawScope.drawGraph(values: List, stride: Int, color: Color) { + drawRect(Color.Black.copy(alpha = 0.35f)) + val points = values.filterIndexed { index, _ -> index % stride == 0 } + if (points.size < 2) return + val min = points.min() + val range = (points.max() - min).takeIf { it > 0f } ?: 1f + val path = Path() + points.forEachIndexed { index, value -> + val x = index * size.width / (points.size - 1) + val y = size.height - (value - min) / range * size.height + if (index == 0) path.moveTo(x, y) else path.lineTo(x, y) + } + drawPath(path, color, style = Stroke(1.5.dp.toPx())) } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt b/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt index c932d1428..748d17b05 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt @@ -17,9 +17,14 @@ package com.lambda.module.modules.hud -import com.lambda.graphics.texture.TextureOwner.upload -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImGui +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.lambda.gui.component.rememberTexture +import com.lambda.gui.core.observe import com.lambda.module.HudModule import com.lambda.module.ModuleTag @@ -29,12 +34,16 @@ object Watermark : HudModule( tag = ModuleTag.HUD, enabledByDefault = true, ) { - private val texture = upload("textures/lambda.png") private val scale by setting("Scale", 0.15f, 0.01f..1f, 0.01f) - override fun ImGuiBuilder.buildLayout() { - val width = texture.width * scale - val height = texture.height * scale - ImGui.image(texture.id.toLong(), width, height) + @Composable + override fun Content() { + val logo = rememberTexture("textures/lambda.png") + val scale by observe { scale } + Image( + logo, + "Lambda", + Modifier.size((logo.width * scale).dp, (logo.height * scale).dp) + ) } } diff --git a/src/main/kotlin/com/lambda/module/modules/movement/BackTrack.kt b/src/main/kotlin/com/lambda/module/modules/movement/BackTrack.kt index abcfe1088..c23a860d0 100644 --- a/src/main/kotlin/com/lambda/module/modules/movement/BackTrack.kt +++ b/src/main/kotlin/com/lambda/module/modules/movement/BackTrack.kt @@ -25,7 +25,6 @@ import com.lambda.event.events.TickEvent import com.lambda.event.listener.SafeListener.Companion.listen import com.lambda.graphics.mc.renderer.ImmediateRenderer.Companion.immediateRenderer import com.lambda.graphics.util.DynamicAABB -import com.lambda.gui.components.ClickGuiLayout import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.module.modules.combat.KillAura @@ -60,6 +59,8 @@ object BackTrack : Module( description = "Gives reach advantage by delaying your packets", tag = ModuleTag.MOVEMENT, ) { + private val BOX_COLOR = Color(130, 200, 255) + private val outbound by setting("Outbound", true) private val mode by setting("Mode", Mode.Fixed) private val delay by setting("Delay", 500, 100..2000) { mode == Mode.Fixed } @@ -172,7 +173,7 @@ object BackTrack : Module( immediateRenderer("BackTrack Immediate Renderer") { val target = target ?: return@immediateRenderer - val c1 = ClickGuiLayout.primaryColor + val c1 = BOX_COLOR val c2 = Color.RED val p = target.hurtTime / 10.0 val c = lerp(p, c1, c2) diff --git a/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt b/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt index eca5c391e..4b2d12a48 100644 --- a/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt +++ b/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt @@ -24,7 +24,6 @@ import com.lambda.event.listener.SafeListener.Companion.listen import com.lambda.graphics.mc.renderer.ImmediateRenderer.Companion.immediateRenderer import com.lambda.graphics.mc.renderer.TickedRenderer.Companion.tickedRenderer import com.lambda.graphics.util.DynamicAABB -import com.lambda.gui.components.ClickGuiLayout import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.module.modules.combat.KillAura @@ -40,6 +39,7 @@ import net.minecraft.network.packet.s2c.play.EntityVelocityUpdateS2CPacket import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Box import net.minecraft.util.math.Vec3d +import java.awt.Color import java.util.concurrent.ConcurrentLinkedDeque object Blink : Module( @@ -47,6 +47,8 @@ object Blink : Module( description = "Holds packets", tag = ModuleTag.MOVEMENT, ) { + private val BOX_COLOR = Color(130, 200, 255) + private var delay by setting("Delay", 500, 50..10000, 10) private val shiftVelocity by setting("Shift velocity", true) private val requiresAura by setting("Requires Aura", false) @@ -71,7 +73,7 @@ object Blink : Module( } immediateRenderer("Blink Immediate Renderer") { - val color = ClickGuiLayout.primaryColor + val color = BOX_COLOR box(box.update(lastBox).box(mc.tickDelta) ?: return@immediateRenderer) { colors(color.setAlpha(0.3), color) } diff --git a/src/main/kotlin/com/lambda/module/modules/player/InventoryMove.kt b/src/main/kotlin/com/lambda/module/modules/player/InventoryMove.kt index d6aed9e9d..04509c022 100644 --- a/src/main/kotlin/com/lambda/module/modules/player/InventoryMove.kt +++ b/src/main/kotlin/com/lambda/module/modules/player/InventoryMove.kt @@ -21,7 +21,8 @@ import com.lambda.Lambda.mc import com.lambda.config.blocks.RotationConfig import com.lambda.event.events.TickEvent import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.LambdaScreen +import com.lambda.gui.GuiScreen +import com.lambda.gui.LambdaGui import com.lambda.interaction.manager.managers.rotating.RotationMode import com.lambda.interaction.manager.managers.rotating.rotationRequest import com.lambda.module.Module @@ -67,7 +68,7 @@ object InventoryMove : Module( this is AbstractSignEditScreen || this is AnvilScreen || this is AbstractCommandBlockScreen || - (this is LambdaScreen && !clickGui) || + (this is GuiScreen && (!clickGui || LambdaGui.isCapturingKeys)) || this is BookEditScreen || this == null diff --git a/src/main/kotlin/com/lambda/module/modules/player/Replay.kt b/src/main/kotlin/com/lambda/module/modules/player/Replay.kt index 5213b46d5..27137b50d 100644 --- a/src/main/kotlin/com/lambda/module/modules/player/Replay.kt +++ b/src/main/kotlin/com/lambda/module/modules/player/Replay.kt @@ -32,7 +32,6 @@ import com.lambda.event.EventFlow.lambdaScope import com.lambda.event.events.MovementEvent import com.lambda.event.events.TickEvent import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.components.ClickGuiLayout import com.lambda.interaction.handler.handlers.TimerHandler import com.lambda.interaction.manager.managers.rotating.Rotation import com.lambda.interaction.manager.managers.rotating.RotationMode @@ -67,6 +66,7 @@ import net.minecraft.client.input.Input import net.minecraft.sound.SoundEvents import net.minecraft.util.PlayerInput import net.minecraft.util.math.Vec3d +import java.awt.Color import java.io.File import java.lang.reflect.Type import java.time.format.DateTimeFormatter @@ -87,6 +87,9 @@ object Replay : Module( tag = ModuleTag.PLAYER, autoDisable = true ) { + private val HIGHLIGHT_COLOR = Color(130, 200, 255) + private val ACTION_COLOR = Color(225, 130, 225) + private val record by setting("Record", KeyCode.R) .onPress { handleRecord() } private val play by setting("Play / Stop", KeyCode.C) @@ -197,11 +200,11 @@ object Replay : Module( val index = recordings.indexOf(saving) this@Replay.info(buildText { literal("Auto saved #") - color(ClickGuiLayout.primaryColor) { literal("$index") } + color(HIGHLIGHT_COLOR) { literal("$index") } literal(" of ") - color(ClickGuiLayout.primaryColor) { literal(saving.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(saving.duration.toString()) } literal(" at ") - color(ClickGuiLayout.primaryColor) { literal(saving.endPos.format(precision = 1)) } + color(HIGHLIGHT_COLOR) { literal(saving.endPos.format(precision = 1)) } playMessage(saving) saveMessage(saving) pruneMessage(saving) @@ -219,9 +222,9 @@ object Replay : Module( buffer = playback?.duplicate() this@Replay.info(buildText { if (repeats > 0) { - color(ClickGuiLayout.primaryColor) { literal("[$repeats / $loops]") } + color(HIGHLIGHT_COLOR) { literal("[$repeats / $loops]") } } else { - color(ClickGuiLayout.primaryColor) { literal("[$repeats/∞]") } + color(HIGHLIGHT_COLOR) { literal("[$repeats/∞]") } } literal(" Replay looped.") }) @@ -232,7 +235,7 @@ object Replay : Module( state = State.Inactive this@Replay.info(buildText { literal("Replay finished after ") - color(ClickGuiLayout.primaryColor) { literal(playback?.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(playback?.duration.toString()) } literal(".") }) return@listen @@ -257,9 +260,9 @@ object Replay : Module( info(buildText { literal("Recording #${recordings.indexOf(deserialized)} ") - color(ClickGuiLayout.primaryColor) { literal(file.nameWithoutExtension) } + color(HIGHLIGHT_COLOR) { literal(file.nameWithoutExtension) } literal(" loaded. Duration: ") - color(ClickGuiLayout.primaryColor) { literal(deserialized.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(deserialized.duration.toString()) } playMessage(deserialized) pruneMessage(deserialized) }) @@ -288,9 +291,9 @@ object Replay : Module( playback = recording info(buildText { literal("Replaying recording #") - color(ClickGuiLayout.primaryColor) { literal(index.toString()) } + color(HIGHLIGHT_COLOR) { literal(index.toString()) } literal(" of ") - color(ClickGuiLayout.primaryColor) { literal(recording.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(recording.duration.toString()) } }) return CommandResult.success() } @@ -304,13 +307,13 @@ object Replay : Module( recordings.add(pruned) info(buildText { literal("Shortened recording #") - color(ClickGuiLayout.primaryColor) { literal(recordings.indexOf(toShorten).toString()) } + color(HIGHLIGHT_COLOR) { literal(recordings.indexOf(toShorten).toString()) } literal(" of ") - color(ClickGuiLayout.primaryColor) { literal(toShorten.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(toShorten.duration.toString()) } literal(" to new recording #") - color(ClickGuiLayout.primaryColor) { literal(recordings.indexOf(pruned).toString()) } + color(HIGHLIGHT_COLOR) { literal(recordings.indexOf(pruned).toString()) } literal(" of ") - color(ClickGuiLayout.primaryColor) { literal(pruned.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(pruned.duration.toString()) } playMessage(pruned) saveMessage(pruned) }) @@ -326,7 +329,7 @@ object Replay : Module( buffer = it.duplicate() info(buildText { literal("Replaying most recent recording #${recordings.indexOf(it)}. Duration: ") - color(ClickGuiLayout.primaryColor) { literal(it.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(it.duration.toString()) } }) } ?: run { this@Replay.warn("No recording to replay.") @@ -370,9 +373,9 @@ object Replay : Module( recordings.add(rec) this@Replay.info(buildText { literal("Stopped recording #") - color(ClickGuiLayout.primaryColor) { literal("${recordings.indexOf(rec)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(rec)}") } literal(" of ") - color(ClickGuiLayout.primaryColor) { literal(rec.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(rec.duration.toString()) } literal(".") playMessage(rec) saveMessage(rec) @@ -387,9 +390,9 @@ object Replay : Module( recordings.add(checkRec) this@Replay.info(buildText { literal("Checkpoint #") - color(ClickGuiLayout.primaryColor) { literal("${recordings.indexOf(checkRec)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(checkRec)}") } literal(" created at ") - color(ClickGuiLayout.primaryColor) { literal(checkRec.endPos.format(precision = 0)) } + color(HIGHLIGHT_COLOR) { literal(checkRec.endPos.format(precision = 0)) } literal(".") playMessage(checkRec) saveMessage(checkRec) @@ -408,9 +411,9 @@ object Replay : Module( playMode = PlayMode.entries[(playMode.ordinal + 1) % PlayMode.entries.size] info(buildText { literal("Set play mode to ") - color(ClickGuiLayout.primaryColor) { literal(playMode.name) } + color(HIGHLIGHT_COLOR) { literal(playMode.name) } literal(" (previously ") - color(ClickGuiLayout.primaryColor) { literal(oldMode.name) } + color(HIGHLIGHT_COLOR) { literal(oldMode.name) } literal(")") }) } @@ -430,30 +433,30 @@ object Replay : Module( this@Replay.info(buildText { literal("Saved recording #") - color(ClickGuiLayout.primaryColor) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(" of ") - color(ClickGuiLayout.primaryColor) { literal(recording.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(recording.duration.toString()) } literal(" in file ") - color(ClickGuiLayout.primaryColor) { literal(name) } + color(HIGHLIGHT_COLOR) { literal(name) } val filePath = file.toPath().pathString hoverEvent(HoverEvents.showText(buildText { literal("Open file ") - color(ClickGuiLayout.primaryColor) { literal(filePath) } + color(HIGHLIGHT_COLOR) { literal(filePath) } })) { clickEvent(ClickEvents.openFile(filePath)) { literal(" [") - color(ClickGuiLayout.secondaryColor) { literal("OPEN FILE") } + color(ACTION_COLOR) { literal("OPEN FILE") } literal("]") } } val parentPath = file.parentFile.toPath().pathString hoverEvent(HoverEvents.showText(buildText { literal("Open folder ") - color(ClickGuiLayout.primaryColor) { literal(parentPath) } + color(HIGHLIGHT_COLOR) { literal(parentPath) } })) { clickEvent(ClickEvents.openFile(parentPath)) { literal(" [") - color(ClickGuiLayout.secondaryColor) { literal("OPEN FOLDER") } + color(ACTION_COLOR) { literal("OPEN FOLDER") } literal("]") } } @@ -464,12 +467,12 @@ object Replay : Module( private fun TextBuilder.playMessage(recording: Recording) { hoverEvent(HoverEvents.showText(buildText { literal("Click to replay recording #") - color(ClickGuiLayout.primaryColor) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(".") })) { clickEvent(ClickEvents.suggestCommand(";replay play ${recordings.indexOf(recording)}")) { literal(" [") - color(ClickGuiLayout.secondaryColor) { + color(ACTION_COLOR) { literal("PLAY") } literal("]") @@ -482,17 +485,17 @@ object Replay : Module( hoverEvent(HoverEvents.showText(buildText { literal(" Recording can be shortened by ") - color(ClickGuiLayout.primaryColor) { + color(HIGHLIGHT_COLOR) { literal(recording.pruneTimesave.toString()) } literal(" by removing idles and cyclic paths.") })) { clickEvent(ClickEvents.suggestCommand(";replay prune ${recordings.indexOf(recording)}")) { literal(" [") - color(ClickGuiLayout.secondaryColor) { + color(ACTION_COLOR) { literal("PRUNE ") } - color(ClickGuiLayout.primaryColor) { + color(HIGHLIGHT_COLOR) { literal("${recording.pruneTimesave}") } literal("]") @@ -503,12 +506,12 @@ object Replay : Module( private fun TextBuilder.saveMessage(recording: Recording) { hoverEvent(HoverEvents.showText(buildText { literal("Click to save recording #") - color(ClickGuiLayout.primaryColor) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(".") })) { clickEvent(ClickEvents.suggestCommand(";replay save ${recordings.indexOf(recording)} ${getTime(fileFormatter).sanitizeForFilename()}")) { literal(" [") - color(ClickGuiLayout.secondaryColor) { literal("SAVE") } + color(ACTION_COLOR) { literal("SAVE") } literal("]") } } @@ -528,7 +531,7 @@ object Replay : Module( } this@Replay.info(buildText { literal("Postprocessing finished. Shortened recording by ") - color(ClickGuiLayout.primaryColor) { literal((duration - pruned.duration).toString()) } + color(HIGHLIGHT_COLOR) { literal((duration - pruned.duration).toString()) } literal(".") }) return pruned diff --git a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt index 144fca7a4..b7b312d6f 100644 --- a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt +++ b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt @@ -24,12 +24,13 @@ import com.lambda.command.LambdaCommand import com.lambda.config.ConfigLoader import com.lambda.core.Loader import com.lambda.event.EventFlow -import com.lambda.gui.components.ClickGuiLayout import com.lambda.module.Module import com.lambda.module.ModuleRegistry +import com.lambda.module.modules.client.Style import com.lambda.threading.runSafe import com.lambda.threading.runSafeGameScheduled import com.lambda.util.StringUtils.capitalize +import com.lambda.util.math.toAwt import com.lambda.util.text.HoverEvents import com.lambda.util.text.TextBuilder import com.lambda.util.text.buildText @@ -152,7 +153,7 @@ object CommunicationUtils { if (command.usage.isNotBlank()) { literal("\n") literal("Usage: ") - color(ClickGuiLayout.primaryColor) { + color(Style.palette.primary.toAwt()) { literal(command.usage) } } @@ -160,7 +161,7 @@ object CommunicationUtils { literal("\n") literal("Aliases: ") joinToText(command.aliases) { - color(ClickGuiLayout.primaryColor) { + color(Style.palette.primary.toAwt()) { literal(it) } } @@ -179,7 +180,7 @@ object CommunicationUtils { literal("\n") } literal("Keybind: ") - color(ClickGuiLayout.primaryColor) { + color(Style.palette.primary.toAwt()) { if (module.keybind.key != 0 || module.keybind.mouse > -1) { literal(module.keybind.name) } else { diff --git a/src/main/kotlin/com/lambda/util/InputUtils.kt b/src/main/kotlin/com/lambda/util/InputUtils.kt index 6eed21518..e51fef76c 100644 --- a/src/main/kotlin/com/lambda/util/InputUtils.kt +++ b/src/main/kotlin/com/lambda/util/InputUtils.kt @@ -20,94 +20,23 @@ package com.lambda.util import com.lambda.Lambda.mc import com.lambda.config.settings.complex.Bind import com.lambda.context.SafeContext -import com.lambda.event.events.ButtonEvent -import it.unimi.dsi.fastutil.ints.Int2IntArrayMap -import org.lwjgl.glfw.GLFW -import org.lwjgl.glfw.GLFW.GLFW_KEY_LEFT_ALT -import org.lwjgl.glfw.GLFW.GLFW_KEY_LEFT_CONTROL -import org.lwjgl.glfw.GLFW.GLFW_KEY_LEFT_SHIFT -import org.lwjgl.glfw.GLFW.GLFW_KEY_LEFT_SUPER -import org.lwjgl.glfw.GLFW.GLFW_KEY_RIGHT_ALT -import org.lwjgl.glfw.GLFW.GLFW_KEY_RIGHT_CONTROL -import org.lwjgl.glfw.GLFW.GLFW_KEY_RIGHT_SHIFT -import org.lwjgl.glfw.GLFW.GLFW_KEY_RIGHT_SUPER -import org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_1 -import org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_8 +import net.minecraft.client.util.InputUtil import org.lwjgl.glfw.GLFW.GLFW_PRESS import org.lwjgl.glfw.GLFW.glfwGetKey import org.lwjgl.glfw.GLFW.glfwGetMouseButton object InputUtils { - private val lastPressedKeys = Int2IntArrayMap() // Keep track of the previously pressed keys to report GLFW_RELEASE states - private val Int.pressedOrRepeated get() = this == 1 || this == 2 - private val keys = KeyCode.entries.map { it.code }.filter { it > 0 } - private val scancodes = keys.associateWith { GLFW.glfwGetKeyScancode(it) } - - private val mouses = GLFW_MOUSE_BUTTON_1..GLFW_MOUSE_BUTTON_8 - - private val modMap = mapOf( - GLFW_KEY_LEFT_SHIFT to 0x1, - GLFW_KEY_RIGHT_SHIFT to 0x1, - GLFW_KEY_LEFT_CONTROL to 0x2, - GLFW_KEY_RIGHT_CONTROL to 0x2, - GLFW_KEY_LEFT_ALT to 0x4, - GLFW_KEY_RIGHT_ALT to 0x4, - GLFW_KEY_LEFT_SUPER to 0x8, - GLFW_KEY_RIGHT_SUPER to 0x8, - ) - - /** - * Returns whether any of the key-codes (not scan-codes) are being pressed - */ fun SafeContext.isKeyPressed(vararg keys: Int) = keys.any { glfwGetKey(mc.window.handle, it) >= GLFW_PRESS } - /** - * Creates a new event from the currently pressed keys. - * Note: This function is extremely expensive to execute, it is recommended to not use - * it unless you absolutely need to. Additionally, you might screw with the key cache. - */ - fun newKeyboardEvent(): ButtonEvent.Keyboard.Press? { - val pressedKeys = keys - .associateWith { glfwGetKey(mc.window.handle, it) } - .filter { (key, state) -> state >= GLFW_PRESS || lastPressedKeys[key] >= GLFW_PRESS } - .also { lastPressedKeys.clear() } - .onEach { (key, state) -> lastPressedKeys[key] = state } - - val mods = pressedKeys.keys - .filter { it in GLFW_KEY_LEFT_SHIFT..GLFW_KEY_RIGHT_SUPER && lastPressedKeys.keys.firstOrNull()?.equals(it) == false } - .foldRight(0) { v, acc -> acc or modMap.getValue(v) } - - val key = pressedKeys - .firstNotNullOfOrNull { (key, state) -> key to state } ?: return null - - val scancode = scancodes.getOrElse(key.first) { 0 } - - return ButtonEvent.Keyboard.Press(key.first, scancode, key.second, mods) - } - - /** - * Creates a new mouse event from the current glfw states. - */ - fun newMouseEvent(): ButtonEvent.Mouse.Click? { - val mods = (GLFW_KEY_LEFT_SHIFT..GLFW_KEY_RIGHT_SUPER) - .filter { glfwGetKey(mc.window.handle, it) >= GLFW_PRESS } - .foldRight(0) { v, acc -> acc or modMap.getValue(v) } - - val mouse = mouses - .firstOrNull { glfwGetMouseButton(mc.window.handle, it) == GLFW_PRESS } - ?: return null - - return ButtonEvent.Mouse.Click(mouse, GLFW_PRESS, mods) - } - fun Bind.isSatisfied(): Boolean = - (key == -1 || glfwGetKey(mc.window.handle, key).pressedOrRepeated) && - (mouse == -1 || glfwGetMouseButton(mc.window.handle, mouse).pressedOrRepeated) && - trueMods.all { glfwGetKey(mc.window.handle, it.code).pressedOrRepeated } + (isKeyBind || isMouseBind) && + (!isKeyBind || InputUtil.isKeyPressed(mc.window, key)) && + (!isMouseBind || glfwGetMouseButton(mc.window.handle, mouse).pressedOrRepeated) && + trueMods.all { InputUtil.isKeyPressed(mc.window, it.code) } @JvmStatic fun isKeyMovementRelated(key: Int): Boolean { diff --git a/src/main/kotlin/com/lambda/util/WindowUtils.kt b/src/main/kotlin/com/lambda/util/WindowUtils.kt index c8e269a88..b4c339cf1 100644 --- a/src/main/kotlin/com/lambda/util/WindowUtils.kt +++ b/src/main/kotlin/com/lambda/util/WindowUtils.kt @@ -21,7 +21,7 @@ import com.lambda.Lambda.MOD_NAME import com.lambda.Lambda.SYMBOL import com.lambda.Lambda.VERSION import com.lambda.Lambda.mc -import com.lambda.gui.components.ClickGuiLayout.lambdaTitleAppendixName +import com.lambda.gui.GuiConfig.lambdaTitleAppendixName import net.minecraft.client.util.MacWindowUtil import org.lwjgl.glfw.GLFW import org.lwjgl.glfw.GLFWImage diff --git a/src/main/kotlin/com/lambda/util/math/Color.kt b/src/main/kotlin/com/lambda/util/math/Color.kt index 6c1eebdf5..8abe724f4 100644 --- a/src/main/kotlin/com/lambda/util/math/Color.kt +++ b/src/main/kotlin/com/lambda/util/math/Color.kt @@ -17,6 +17,7 @@ package com.lambda.util.math +import androidx.compose.ui.graphics.toArgb import net.minecraft.util.math.Vec3d import java.awt.Color @@ -35,3 +36,7 @@ val Color.b get() = blue / 255.0 val Color.a get() = alpha / 255.0 val Color.vec3d get() = Vec3d(r, g, b) + +fun Color.toCompose() = androidx.compose.ui.graphics.Color(red, green, blue, alpha) + +fun androidx.compose.ui.graphics.Color.toAwt() = Color(toArgb(), true) diff --git a/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh b/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh new file mode 100644 index 000000000..0bc8370d2 --- /dev/null +++ b/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh @@ -0,0 +1,23 @@ +#version 330 + +uniform sampler2D InSampler; + +layout(std140) uniform BlurSpread { + float Spread; +}; + +in vec2 texCoord; + +out vec4 fragColor; + +void main() { + vec2 texel = Spread / vec2(textureSize(InSampler, 0)); + + vec4 sum = texture(InSampler, texCoord) * 4.0; + sum += texture(InSampler, texCoord + vec2(-texel.x, -texel.y)); + sum += texture(InSampler, texCoord + vec2( texel.x, -texel.y)); + sum += texture(InSampler, texCoord + vec2(-texel.x, texel.y)); + sum += texture(InSampler, texCoord + vec2( texel.x, texel.y)); + + fragColor = sum / 8.0; +} diff --git a/src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh b/src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh new file mode 100644 index 000000000..a6034ef27 --- /dev/null +++ b/src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh @@ -0,0 +1,27 @@ +#version 330 + +uniform sampler2D InSampler; + +layout(std140) uniform BlurSpread { + float Spread; +}; + +in vec2 texCoord; + +out vec4 fragColor; + +void main() { + vec2 texel = Spread / vec2(textureSize(InSampler, 0)); + vec2 near = texel * 0.5; + + vec4 sum = texture(InSampler, texCoord + vec2(-texel.x, 0.0)); + sum += texture(InSampler, texCoord + vec2( texel.x, 0.0)); + sum += texture(InSampler, texCoord + vec2(0.0, -texel.y)); + sum += texture(InSampler, texCoord + vec2(0.0, texel.y)); + sum += texture(InSampler, texCoord + vec2(-near.x, -near.y)) * 2.0; + sum += texture(InSampler, texCoord + vec2( near.x, -near.y)) * 2.0; + sum += texture(InSampler, texCoord + vec2(-near.x, near.y)) * 2.0; + sum += texture(InSampler, texCoord + vec2( near.x, near.y)) * 2.0; + + fragColor = sum / 12.0; +} diff --git a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh new file mode 100644 index 000000000..b7d4f8130 --- /dev/null +++ b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh @@ -0,0 +1,40 @@ +#version 330 + +uniform sampler2D GuiSampler; +uniform sampler2D BackdropSampler; +uniform sampler2D HaloSampler; + +layout(std140) uniform GuiEffects { + vec4 GlowColorA; + vec4 GlowColorB; + float GlowIntensity; + float Frost; + float Time; + float Dim; +}; + +const vec3 DIM_COLOR = vec3(16.0 / 255.0); + +in vec2 texCoord; + +out vec4 fragColor; + +void main() { + vec4 gui = texture(GuiSampler, texCoord); + + float covered = clamp(gui.a * 64.0, 0.0, 1.0); + + float frost = Frost * covered; + vec3 backdrop = mix(texture(BackdropSampler, texCoord).rgb, DIM_COLOR, Dim); + vec4 under = vec4(backdrop, 1.0) * frost; + + if (GlowIntensity > 0.0) { + float halo = clamp(texture(HaloSampler, texCoord).a * 2.0, 0.0, 1.0); + float glow = clamp(pow(halo, 1.5) * GlowIntensity, 0.0, 1.0) * (1.0 - covered); + float wave = 0.5 + 0.5 * sin(Time * 2.0 + texCoord.x * 5.0 + texCoord.y * 3.0); + under += vec4(mix(GlowColorA.rgb, GlowColorB.rgb, wave), 1.0) * glow * (1.0 - frost); + } + + vec4 over = gui + under * (1.0 - gui.a); + fragColor = over + vec4(DIM_COLOR, 1.0) * Dim * (1.0 - over.a); +} diff --git a/src/main/resources/lambda.accesswidener b/src/main/resources/lambda.accesswidener index 07ef6fdad..213b08978 100644 --- a/src/main/resources/lambda.accesswidener +++ b/src/main/resources/lambda.accesswidener @@ -5,6 +5,7 @@ transitive-accessible field net/minecraft/client/MinecraftClient attackCooldown transitive-accessible field net/minecraft/client/MinecraftClient paused Z transitive-accessible field net/minecraft/client/MinecraftClient thread Ljava/lang/Thread; transitive-accessible field net/minecraft/client/MinecraftClient uptimeInTicks J +transitive-accessible field net/minecraft/client/render/GameRenderer fogRenderer Lnet/minecraft/client/render/fog/FogRenderer; transitive-accessible field net/minecraft/client/input/Input movementVector Lnet/minecraft/util/math/Vec2f; transitive-accessible field net/minecraft/client/option/KeyBinding boundKey Lnet/minecraft/client/util/InputUtil$Key; transitive-accessible method net/minecraft/client/MinecraftClient getWindowTitle ()Ljava/lang/String; diff --git a/src/main/resources/lambda.mixins.json b/src/main/resources/lambda.mixins.json index eb22aca53..b3af81985 100644 --- a/src/main/resources/lambda.mixins.json +++ b/src/main/resources/lambda.mixins.json @@ -44,6 +44,7 @@ "render.ChatScreenMixin", "render.ChunkBorderDebugRendererMixin", "render.ChunkOcclusionDataBuilderMixin", + "render.ComposeDelayMixin", "render.ConnectScreenMixin", "render.DisconnectedScreenMixin", "render.DrawContextMixin", @@ -54,9 +55,11 @@ "render.FluidRendererMixin", "render.FogRendererMixin", "render.GameRendererMixin", + "render.GuiRendererMixin", "render.HandledScreenMixin", "render.HeadFeatureRendererMixin", "render.HeldItemRendererMixin", + "render.InactivityFpsLimiterMixin", "render.InGameHudMixin", "render.InGameOverlayRendererMixin", "render.ItemFrameEntityRendererMixin",