orig
EventFlow.post(new ButtonEvent.Keyboard.Press(input.key(), input.scancode(), action, input.modifiers()));
original.call(window, action, input);
int key = input.key();
- if (!InventoryMove.getShouldMove() || !InventoryMove.isKeyMovementRelated(key)) return;
+ if (!InventoryMove.isKeyMovementRelated(key)) return;
+ // A release always goes through, or a key held down while a text field took the focus would stay down
+ 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..8fe497385
--- /dev/null
+++ b/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java
@@ -0,0 +1,46 @@
+/*
+ * 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 kotlin.Unit;
+import kotlin.jvm.functions.Function0;
+import net.minecraft.client.MinecraftClient;
+import org.spongepowered.asm.mixin.Mixin;
+import org.spongepowered.asm.mixin.injection.At;
+import org.spongepowered.asm.mixin.injection.ModifyVariable;
+
+/**
+ * Keeps the work Compose puts off until later on the render thread.
+ *
+ * Compose waits on AWT's event thread and then does the work right there, which in a desktop
+ * application is the thread its interface lives on. Lambda's interface lives on the render
+ * thread, so that work, the bookkeeping of where every element is, ran alongside a layout in
+ * progress and now and then lost an element, which took the whole interface down with
+ * "LayoutNode not found in RectList".
+ */
+@Mixin(value = Actuals_skikoKt.class, remap = false)
+public class ComposeDelayMixin {
+ @ModifyVariable(method = "postDelayed", at = @At("HEAD"), argsOnly = true, require = 1)
+ private static Function0 runOnRenderThread(Function0 block) {
+ return () -> {
+ MinecraftClient.getInstance().execute(block::invoke);
+ return Unit.INSTANCE;
+ };
+ }
+}
diff --git a/src/main/java/com/lambda/mixin/render/GameRendererMixin.java b/src/main/java/com/lambda/mixin/render/GameRendererMixin.java
index bc9bc9023..a2ea9f39a 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,9 @@ 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;
+
+/**
+ * Lets Lambda's GUI have Minecraft draw its item icons. The GUI renderer always draws to the
+ * window; while {@link ItemAtlas} is rendering, it is told that the atlas is the window, so
+ * what it draws lands there instead, at the atlas' size and scale.
+ */
+@Mixin(GuiRenderer.class)
+public class GuiRendererMixin {
+ @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;getFramebuffer()Lnet/minecraft/client/gl/Framebuffer;"))
+ 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"))
+ 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"))
+ 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"))
+ 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..926b8cfaf
--- /dev/null
+++ b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java
@@ -0,0 +1,49 @@
+/*
+ * 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.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;
+
+/**
+ * Lets Lambda's interface run at the player's own frame rate outside a world.
+ *
+ * Minecraft holds its menus to 60 frames a second while no world is loaded, which is fine for
+ * a title screen and makes the click GUI and the HUD editor opened over one visibly less smooth
+ * than they are in game. Minimised and idle windows keep their limits.
+ */
+@Mixin(InactivityFpsLimiter.class)
+public class InactivityFpsLimiterMixin {
+ @Shadow
+ @Final
+ private MinecraftClient client;
+
+ @ModifyReturnValue(method = "getLimitReason", at = @At("RETURN"))
+ private InactivityFpsLimiter.LimitReason liftMenuLimit(InactivityFpsLimiter.LimitReason reason) {
+ if (reason == InactivityFpsLimiter.LimitReason.OUT_OF_LEVEL_MENU && client.currentScreen == GuiScreen.INSTANCE) {
+ 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..b448ec2ce 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
@@ -49,10 +49,9 @@ object Lambda : ClientModInitializer {
const val SYMBOL = "λ"
const val APP_ID = "1221289599427416127"
const val REPO_URL = "https://github.com/lambda-client/lambda"
- val VERSION: String =
- FabricLoader.getInstance()
- .getModContainer("lambda").orElseThrow()
- .metadata.version.friendlyString
+ val VERSION: String = FabricLoader.getInstance()
+ .getModContainer("lambda").orElseThrow()
+ .metadata.version.friendlyString
val LOG: Logger = LogManager.getLogger(SYMBOL)
@@ -114,7 +113,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/entries/Setting.kt b/src/main/kotlin/com/lambda/config/entries/Setting.kt
index 17777d42a..9f367d26f 100644
--- a/src/main/kotlin/com/lambda/config/entries/Setting.kt
+++ b/src/main/kotlin/com/lambda/config/entries/Setting.kt
@@ -33,7 +33,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,8 +142,6 @@ abstract class Setting(
core = originalCore
}
- abstract fun ImGuiBuilder.buildLayout()
-
open fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(string("value as JSON")) { value ->
executeWithResult {
diff --git a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt
index 971dad7d5..c2962b58a 100644
--- a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt
@@ -26,7 +26,6 @@ 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.extension.CommandBuilder
import net.minecraft.command.CommandRegistryAccess
@@ -41,8 +40,6 @@ class CharSetting(
defaultValue: Char,
visibility: () -> Boolean
) : Setting(name, description, defaultValue, layer, config, visibility) {
- override fun ImGuiBuilder.buildLayout() {}
-
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(word(name)) { parameter ->
executeWithResult {
diff --git a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt
index 5a537789a..9dc2a42f0 100644
--- a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt
@@ -20,7 +20,6 @@ package com.lambda.config.settings
import com.lambda.config.Config
import com.lambda.config.entries.Setting
import com.lambda.config.entries.SettingEntryLayer
-import com.lambda.gui.dsl.ImGuiBuilder
class FunctionSetting R, R>(
name: String,
@@ -30,8 +29,4 @@ 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)
- }
}
diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt
index 23eb84d40..e2d4a9d4d 100644
--- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt
@@ -22,11 +22,6 @@ 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 java.text.NumberFormat
import java.util.*
@@ -57,43 +52,7 @@ abstract class NumericSetting(
/**
* Subclasses must implement this to provide their specific slider widget.
*/
- protected abstract fun ImGuiBuilder.buildSlider()
- override fun ImGuiBuilder.buildLayout() {
- val showReset = isModified
- val resetButtonText = "R"
- val valueString = this@NumericSetting.toString()
-
- buildSlider()
- lambdaTooltip(description)
-
- 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
-
- val labelEndPosX = itemRectMin.x + style.framePadding.x * 2 + labelWidth
- val valueStartPosX = itemRectMax.x - style.framePadding.x * 2 - valueWidth
-
- 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)
- }
-
- sameLine(0.0f, style.itemSpacing.x)
- if (showReset) {
- button("$resetButtonText##$name") {
- reset()
- }
- onItemHover {
- tooltip { text("Reset to default") }
- }
- } else {
- dummy(calcTextSize(resetButtonText).x + style.framePadding.x * 2.0f, ImGui.getFrameHeight())
- }
- }
}
@Suppress("unchecked_cast")
diff --git a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt
index 026ee1a0a..3d8920ac6 100644
--- a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt
@@ -28,8 +28,6 @@ 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.util.extension.CommandBuilder
import net.minecraft.command.CommandRegistryAccess
@@ -44,16 +42,7 @@ 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)
- }
- lambdaTooltip(description)
- }
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(greedyString(name)) { parameter ->
@@ -69,9 +58,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..b6717f62a 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,7 @@ 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)
+ // Blocks without an item of their own, like fire or water, come out empty and show nothing
+ 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..98399ec4b 100644
--- a/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt
@@ -26,15 +26,8 @@ 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.threading.runSafe
+import net.minecraft.item.ItemStack
import tools.jackson.databind.JavaType
/**
@@ -64,8 +57,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 +67,29 @@ open class CollectionSetting(
value.size != defaultValue.size || defaultValue.any { !value.contains(it) }
}
- override fun ImGuiBuilder.buildLayout() = buildDualPane("item") { it.toString() }
+ /** How [item] is shown to the user */
+ open fun label(item: R): String = item.toString()
- fun ImGuiBuilder.buildDualPane(itemName: String, toString: (R) -> String) {
- val text = if (value.size == 1) itemName else "${itemName}s"
- val popupId = "##$name-collection-popup"
+ /** What Minecraft shows [item] as in an inventory, for settings of game content; null for the rest */
+ open fun icon(item: R): ItemStack? = null
- button("$name: ${value.size} $text") {
- ImGui.openPopup(popupId)
- }
+ fun select(item: R) {
+ if (item in value) return
+ value.add(item)
+ unsafeSelectListeners.forEach { it(item) }
+ runSafe { selectListeners.forEach { it(item) } }
+ }
- 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 deselect(item: R) {
+ if (!value.remove(item)) return
+ unsafeDeselectListeners.forEach { it(item) }
+ runSafe { deselectListeners.forEach { it(item) } }
+ }
+
+ /** Selects everything that was not selected, and the other way around */
+ 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..0341ce676 100644
--- a/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt
@@ -24,7 +24,6 @@ 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.extension.CommandBuilder
import net.minecraft.command.CommandRegistryAccess
@@ -36,11 +35,6 @@ class BooleanSetting(
visibility: () -> Boolean,
defaultValue: Boolean
) : Setting(name, description, defaultValue, layer, config, visibility) {
- override fun ImGuiBuilder.buildLayout() {
- checkbox(name, ::value)
- lambdaTooltip(description)
- }
-
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(boolean(name)) { parameter ->
execute {
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..b7883b477 100644
--- a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt
@@ -26,11 +26,8 @@ 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.util.StringUtils.capitalize
import com.lambda.util.extension.CommandBuilder
-import com.lambda.util.extension.displayValue
import net.minecraft.command.CommandRegistryAccess
class EnumSetting>(
@@ -41,26 +38,6 @@ 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)
- }
-
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(word(name)) { parameter ->
suggests { _, builder ->
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..f5f9fa4ef 100644
--- a/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt
@@ -17,7 +17,6 @@
package com.lambda.config.settings.complex
-import com.lambda.Lambda.mc
import com.lambda.brigadier.argument.integer
import com.lambda.brigadier.argument.value
import com.lambda.brigadier.execute
@@ -25,11 +24,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.util.BlockUtils.blockPos
-import com.lambda.util.CommunicationUtils.info
import com.lambda.util.extension.CommandBuilder
-import com.lambda.util.world.raycast.RayCastUtils.blockResult
import net.minecraft.command.CommandRegistryAccess
import net.minecraft.util.math.BlockPos
@@ -41,20 +36,6 @@ 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 }
- }
- lambdaTooltip(description)
- }
-
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(integer("X", -30000000, 30000000)) { x ->
required(integer("Y", -64, 319)) { y ->
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..eff9f5319 100644
--- a/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt
@@ -24,7 +24,6 @@ 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.extension.CommandBuilder
import net.minecraft.block.Block
import net.minecraft.command.CommandRegistryAccess
@@ -37,8 +36,6 @@ class BlockSetting(
visibility: () -> Boolean,
defaultValue: Block
) : Setting(name, description, defaultValue, layer, config, visibility) {
- override fun ImGuiBuilder.buildLayout() {}
-
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(blockState(name, registry)) { argument ->
execute {
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..08c697b52 100644
--- a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt
@@ -25,7 +25,6 @@ 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.extension.CommandBuilder
import net.minecraft.command.CommandRegistryAccess
import java.awt.Color
@@ -38,11 +37,6 @@ class ColorSetting(
visibility: () -> Boolean,
defaultValue: Color
) : Setting(name, description, defaultValue, layer, config, visibility) {
- override fun ImGuiBuilder.buildLayout() {
- colorEdit(name, ::value)
- lambdaTooltip(description)
- }
-
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(integer("Red", 0, 255)) { red ->
required(integer("Green", 0, 255)) { green ->
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..fe1a92e62 100644
--- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt
@@ -37,19 +37,12 @@ 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.threading.runSafe
-import com.lambda.util.InputUtils
import com.lambda.util.KeyCode
import com.lambda.util.Mouse
import com.lambda.util.StringUtils.capitalize
import com.lambda.util.extension.CommandBuilder
import net.minecraft.command.CommandRegistryAccess
-import org.lwjgl.glfw.GLFW.GLFW_KEY_LEFT_SHIFT
-import org.lwjgl.glfw.GLFW.GLFW_KEY_RIGHT_SUPER
import org.lwjgl.glfw.GLFW.GLFW_MOD_ALT
import org.lwjgl.glfw.GLFW.GLFW_MOD_CAPS_LOCK
import org.lwjgl.glfw.GLFW.GLFW_MOD_CONTROL
@@ -87,8 +80,6 @@ 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
@@ -116,77 +107,6 @@ 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)
- }
- }
- }
- } 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
- }
- }
- onItemHover(ImGuiHoveredFlags.Stationary) {
- lambdaTooltip("Clear binding")
- }
-
- if (listening) {
- InputUtils.newMouseEvent()
- ?.let {
- value = Bind(0, it.modifiers, it.button)
- listening = false
- return
- }
-
- InputUtils.newKeyboardEvent()
- ?.let {
- val isModKey = it.keyCode in GLFW_KEY_LEFT_SHIFT..GLFW_KEY_RIGHT_SUPER
-
- // 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)
- }
-
- listening = false
- }
-
- return
- }
- }
- }
-
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(word(name)) { nameArg ->
suggests { _, builder ->
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..9a2506c8f 100644
--- a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt
@@ -24,7 +24,6 @@ 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.extension.CommandBuilder
import net.minecraft.command.CommandRegistryAccess
import net.minecraft.util.math.Vec3d
@@ -37,11 +36,6 @@ 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)
- }
-
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(double("X", -30000000.0, 30000000.0)) { x ->
required(double("Y", -64.0, 255.0)) { y ->
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..5c72d8a87 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,8 @@ 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
/**
* @see [com.lambda.config.Config]
@@ -46,17 +41,6 @@ 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 CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(double(name, range.start, range.endInclusive)) { parameter ->
execute {
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..2e749b9a9 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,8 @@ 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
/**
* @see [com.lambda.config.Config]
@@ -45,17 +41,6 @@ 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 CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(float(name, range.start, range.endInclusive)) { parameter ->
execute {
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..7aa14e4b2 100644
--- a/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt
@@ -24,7 +24,6 @@ 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
@@ -42,10 +41,6 @@ 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 CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(integer(name, range.start, range.endInclusive)) { parameter ->
execute {
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..462b6221f 100644
--- a/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt
@@ -24,8 +24,6 @@ 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
@@ -43,16 +41,6 @@ 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 CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(long(name, range.start, range.endInclusive)) { parameter ->
execute {
diff --git a/src/main/kotlin/com/lambda/event/events/GuiEvent.kt b/src/main/kotlin/com/lambda/event/events/GuiEvent.kt
index 4cbd037f0..d4dd346f4 100644
--- a/src/main/kotlin/com/lambda/event/events/GuiEvent.kt
+++ b/src/main/kotlin/com/lambda/event/events/GuiEvent.kt
@@ -24,20 +24,6 @@ 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..ad2c0aee1 100644
--- a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt
+++ b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt
@@ -300,4 +300,63 @@ object LambdaRenderPipelines : Loadable {
)
.build()
)
+
+ /**
+ * A fullscreen pass for the GUI: one triangle from the vanilla screen quad shader, drawn
+ * without a vertex buffer, sampling [samplers] and optionally blending over the target.
+ */
+ 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()
+ )
+
+ /** Draws the GUI texture, which has premultiplied alpha, over the game as it is */
+ val GUI_BLIT = guiPass(
+ "gui_blit",
+ Identifier.ofVanilla("core/blit_screen"),
+ samplers = listOf("InSampler"),
+ blend = BlendFunction.TRANSLUCENT_PREMULTIPLIED_ALPHA
+ )
+
+ /** [GUI_BLIT] with the frosted backdrop and the glow mixed in underneath */
+ 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..db8883e64
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt
@@ -0,0 +1,118 @@
+/*
+ * 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.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 java.awt.Color
+import net.minecraft.SharedConstants
+import net.minecraft.client.util.Icons
+
+/**
+ * Settings of the interface that are about how it behaves rather than how it looks; for that,
+ * see the [com.lambda.module.modules.client.Style] module.
+ */
+@Suppress("unused")
+object GuiConfig : Loadable, Config("GUI", GuiCategory) {
+ private const val GENERAL_TAB = "General"
+ private const val SNAPPING_TAB = "Snapping"
+ private const val COLORS_TAB = "Colors"
+
+ // Unsafe, so the GUI also opens from the menus where there is no player yet
+ @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) var 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) val resetWindowLayout by setting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded")
+
+ // Dragging HUD elements in the HUD editor and windows in the click GUI
+ @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 }
+
+ // Colours of things Lambda draws outside its own interface: chat messages and vanilla screens
+ @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 border by setting("Border", Color(130, 12, 60, 240))
+ @Tab(COLORS_TAB) val headerHovered by setting("Header Hovered", Color(255, 59, 136, 115))
+
+ /** A category window's position, in dp from the top left of the screen, and whether it is collapsed */
+ data class WindowPlacement(val x: Float, val y: Float, val collapsed: Boolean)
+
+ // Persisted as "Combat:120.0,80.0,false;Render:..." since it is state rather than a setting
+ private var windowPlacements by property("")
+ private var decodedFrom: String? = null
+ private var decoded = emptyMap()
+
+ /** Where the user left each category window, by tag name. Windows never moved are absent. */
+ 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}"
+ }
+ }
+
+ /** Forgets where the category windows were moved to, which puts them back in their row */
+ 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..63fef2c52
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/GuiScreen.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
+
+import androidx.compose.ui.geometry.Offset
+import com.lambda.Lambda.mc
+import com.lambda.config.settings.complex.Bind
+import com.lambda.event.events.ButtonEvent
+import com.lambda.gui.component.TextFocus
+import com.lambda.module.modules.client.Style
+import com.lambda.module.modules.combat.autodisconnect.AutoDisconnectScreen
+import com.lambda.util.KeyCode
+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
+
+/**
+ * The Minecraft screen behind every [LambdaGui.Screen]. It draws nothing itself: it frees the
+ * cursor, keeps the game from reacting to input, and hands that input to the Compose scene.
+ */
+object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider {
+ /** The screen the GUI was opened over, such as the title screen. Null when opened in game. */
+ private var parent: Screen? = null
+
+ /**
+ * Set while a keybind setting waits for the user to press what they want to bind. The next
+ * key or mouse button goes to it instead of the interface; null means the user cancelled.
+ */
+ internal var keybindRecorder: ((Bind?) -> Unit)? = null
+
+ /** Screens, besides none at all, that the GUI may be opened over */
+ 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
+ // The parent comes back when the GUI closes, so it must keep what removed() would free
+ (parent as? OverlayBackgroundScreen)?.onOverlaidByGui()
+ mc.setScreen(this)
+ }
+
+ override fun close() {
+ val previous = parent
+ parent = null
+ mc.setScreen(previous)
+ }
+
+ override fun removed() {
+ keybindRecorder?.invoke(null)
+ keybindRecorder = null
+ LambdaGui.onScreenRemoved()
+ }
+
+ override fun shouldPause() = false
+
+ // The interface is drawn by LambdaGui.render once the whole vanilla GUI is on screen
+ 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) {
+ // Off-screen mouse coordinates keep the parent's widgets from looking hovered
+ parent.renderBackground(context, -1, -1, delta)
+ parent.render(context, -1, -1, delta)
+ context.drawDeferredElements()
+ }
+ // Over the world or the screen the GUI was opened on, whichever is behind it. Drawn here
+ // rather than asked of Minecraft, whose own darkening NoRender can switch off for every
+ // other screen: this one has its own setting.
+ if (Style.dimBackground && LambdaGui.screen == LambdaGui.Screen.ClickGui) {
+ val alpha = (Style.dimStrength * 255).toInt().coerceIn(0, 255)
+ context.fill(0, 0, width, height, (alpha shl 24) or DIM_COLOR)
+ }
+ }
+
+ 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 {
+ keybindRecorder?.let { record ->
+ keybindRecorder = null
+ if (click.button() != GLFW.GLFW_MOUSE_BUTTON_LEFT) {
+ record(Bind(0, click.modifiers(), click.button()))
+ return true
+ }
+ // The left button abandons the recording, and then is the click it would have been
+ record(null)
+ }
+ val position = scenePosition(click.x(), click.y())
+ // Pressing anywhere else is done typing, as in any other window
+ 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 (recordKey(input, pressed = true)) return true
+ if (LambdaGui.input?.key(input.key(), true, input.modifiers()) == true) return true
+ if (input.isEscape && LambdaGui.onEscape?.invoke() != true) LambdaGui.back()
+ return true
+ }
+
+ override fun keyReleased(input: KeyInput): Boolean {
+ if (recordKey(input, pressed = false)) return true
+ LambdaGui.input?.key(input.key(), false, input.modifiers())
+ return true
+ }
+
+ override fun charTyped(input: CharInput): Boolean {
+ LambdaGui.input?.type(input.codepoint())
+ return true
+ }
+
+ /**
+ * Feeds a key to the [keybindRecorder]. A modifier pressed on its own is only bound when it is
+ * released again, so holding it to combine with another key still works.
+ */
+ private fun recordKey(input: KeyInput, pressed: Boolean): Boolean {
+ val record = keybindRecorder ?: return false
+ val key = ButtonEvent.Keyboard.Press(
+ input.key(), input.scancode(), if (pressed) GLFW.GLFW_PRESS else GLFW.GLFW_RELEASE, input.modifiers()
+ ).translated
+ val isModifier = input.key() in GLFW.GLFW_KEY_LEFT_SHIFT..GLFW.GLFW_KEY_RIGHT_SUPER
+ if (pressed == isModifier) return true
+
+ record(
+ when (key) {
+ KeyCode.Escape -> null
+ KeyCode.Backspace, KeyCode.Delete -> Bind.EMPTY
+ // A released modifier still reports itself as held; it is the key here, not a modifier
+ else -> Bind(key.code, if (isModifier) 0 else input.modifiers(), -1)
+ }
+ )
+ keybindRecorder = null
+ return true
+ }
+
+ /** The interface is laid out in framebuffer pixels; Minecraft reports the mouse in scaled GUI units */
+ private fun scenePosition(x: Double, y: Double): Offset {
+ val scale = mc.window.scaleFactor
+ return Offset((x * scale).toFloat(), (y * scale).toFloat())
+ }
+
+ /** The near black Minecraft darkens the world with behind a menu */
+ private const val DIM_COLOR = 0x101010
+}
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..750e0892c
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt
@@ -0,0 +1,290 @@
+/*
+ * 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.CompositionLocalProvider
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+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.core.Loadable
+import com.lambda.event.events.ClientEvent
+import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe
+import com.lambda.graphics.mc.LambdaRenderPipelines
+import com.lambda.gui.clickgui.ClickGui
+import com.lambda.gui.clickgui.Reveal
+import com.lambda.gui.component.TextFocus
+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.awaitFrames
+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.LambdaTheme
+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 kotlin.concurrent.thread
+import net.minecraft.client.gui.cursor.Cursor
+import org.jetbrains.skia.FontMgr
+import org.jetbrains.skia.impl.Library
+
+/**
+ * Lambda's interface: the HUD drawn over the game, and the screens opened on top of it.
+ *
+ * All of it is one Compose scene that lives for as long as the client does. What it shows follows
+ * [screen]; the Minecraft-side [GuiScreen] only exists to route input into it while one is open.
+ */
+object LambdaGui : Loadable {
+ enum class Screen {
+ ClickGui,
+
+ /** Reached from the click GUI, and returns to it */
+ HudEditor,
+ }
+
+ /** The screen that is open, or null while only the HUD shows */
+ var screen: Screen? by mutableStateOf(null)
+ private set
+
+ private var host: SceneHost? = null
+ private var broken = false
+
+ private val observations = Observations()
+
+ /** What the click GUI observes, on its own because it stays composed while closed: see [Content] */
+ private val clickGuiObservations = Observations()
+
+ /** Whether the scene has had a frame since the screen closed, to put away what was open on it */
+ private var settled = true
+
+ /** Set for the one frame in which [warmUp] draws the click GUI without it being open */
+ private var warmingUp by mutableStateOf(false)
+ private var warmedUp = false
+
+ internal val input: SceneInput? get() = host?.input
+
+ /** Cursor the element under the pointer wants, or null for the default */
+ internal val cursor: Cursor? get() = host?.platform?.cursor
+
+ /** True while key presses belong to the interface: a text field is focused or a keybind is being recorded */
+ val isCapturingKeys get() = TextFocus.isTyping || GuiScreen.keybindRecorder != null
+
+ init {
+ listenUnsafe { close() }
+ }
+
+ override fun load(): String {
+ // Loading Skia's native library and listing the system fonts take a noticeable moment,
+ // and neither needs the render thread. Doing them now keeps the first frame from paying.
+ 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) }
+ }
+ // Registered this early, the compositor's shaders are compiled along with the game's own
+ // while it loads, rather than on the frame the GUI first needs them
+ LambdaRenderPipelines.GUI_COMPOSITE
+ return "Loaded GUI"
+ }
+
+ fun toggle() {
+ if (isCapturingKeys) return
+ if (screen == null) open(Screen.ClickGui) else GuiScreen.close()
+ }
+
+ fun open(screen: Screen) {
+ if (broken) {
+ warn("Lambda's interface stopped after an error. Check the log, and restart the game to bring it back.")
+ return
+ }
+ if (this.screen == null) {
+ if (!GuiScreen.canOpenOver(mc.currentScreen)) return
+ if (Client.clientSounds) LambdaSound.ModuleOn.play()
+ GuiScreen.show()
+ AutoUpdater.onGuiOpened()
+ }
+ this.screen = screen
+ }
+
+ /** Leaves the open screen: the HUD editor for the click GUI, the click GUI for the game */
+ /**
+ * What Escape closes before it leaves the screen, when nothing in the interface took the
+ * key: set by whatever is open over a screen without being a popup. Returns whether it closed.
+ */
+ internal var onEscape: (() -> Boolean)? = null
+
+ fun back() {
+ if (screen == Screen.HudEditor) screen = Screen.ClickGui else GuiScreen.close()
+ }
+
+ /** Called by [GuiScreen] when Minecraft takes it down, whatever the reason */
+ internal fun onScreenRemoved() {
+ if (screen == null) return
+ if (Client.clientSounds) LambdaSound.ModuleOff.play()
+ screen = null
+ settled = false
+ input?.release()
+ host?.platform?.cursor = null
+ }
+
+ /**
+ * Draws the interface over the frame. Called once per frame, after the game and its own GUI
+ * have been drawn.
+ */
+ 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)
+ }
+ if (screen == null && Hud.shown.isEmpty() && settled) return
+
+ try {
+ val host = host ?: createHost()
+ settled = true
+
+ observations.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(beforeScene = ItemAtlas::import)
+
+ GuiCompositor.composite(host.texture ?: return, size.width, size.height, redraw, effects(density))
+ } catch (e: Throwable) {
+ // A scene that threw is in no state to draw the next frame; stop rather than throw every frame
+ broken = true
+ LOG.error("Lambda's interface failed and was switched off", e)
+ if (screen != null) GuiScreen.close()
+ }
+ }
+
+ /**
+ * Builds the interface and draws the click GUI once without showing it. This runs on the
+ * game's first frame, which is spent behind the loading screen, and takes everything that
+ * makes a first time slow with it: loading Compose's and Skia's classes, composing the
+ * click GUI, creating Skia's context and render target, compiling its shaders and
+ * rasterising the glyphs. Without it, all of that would freeze the game for a second the
+ * moment the GUI is first opened.
+ */
+ 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) {
+ // Nothing is lost but the head start: the real thing starts over with a scene of its own
+ LOG.warn("Could not prepare the GUI ahead of its first use", e)
+ warmingUp = false
+ runCatching { close() }
+ host = null
+ }
+ }
+
+ private fun createHost(): SceneHost {
+ prepareSkiko()
+ return SceneHost { Content() }.also { host = it }
+ }
+
+ @Composable
+ private fun Content() {
+ CompositionLocalProvider(LocalObservations provides observations, LocalClipboard provides GameClipboard) {
+ LambdaTheme {
+ // What the search pointed at is lit for a moment, wherever it is shown
+ val revealed = Reveal.module ?: Reveal.setting
+ LaunchedEffect(revealed) {
+ if (revealed != null) {
+ awaitFrames(Reveal.MILLIS)
+ Reveal.clear()
+ }
+ }
+
+ if (screen == Screen.HudEditor) HudEditor() else HudLayer()
+ // Composed once and kept, so that opening the click GUI only has to show it
+ Retained(shown = screen == Screen.ClickGui || warmingUp, clickGuiObservations) { ClickGui() }
+ if (warmingUp) WarmUp()
+ }
+ }
+ }
+
+ /** What [warmUp] draws besides the click GUI itself: the settings, which open later */
+ @Composable
+ private fun WarmUp() {
+ SettingsList(Style.settingLayers)
+ }
+
+ /**
+ * The game is only frosted behind an open screen, and only the click GUI glows: the HUD on
+ * its own has to cost nothing, and the HUD editor shows the HUD as it looks in game.
+ */
+ private fun effects(density: Float) = when (screen) {
+ null -> GuiCompositor.Effects.NONE
+ else -> GuiCompositor.Effects(
+ frost = if (Style.blur) Style.blurRadius * density else 0f,
+ glow = if (Style.glow && screen == Screen.ClickGui) Style.glowRadius * density else 0f,
+ glowIntensity = Style.glowIntensity,
+ glowColorA = Style.glowColorA,
+ glowColorB = Style.glowColorB,
+ )
+ }
+
+ private fun close() {
+ host?.close()
+ host = null
+ }
+
+ /** Skia will not create an OpenGL context on macOS unless told to before it loads */
+ private fun prepareSkiko() {
+ if (System.getProperty("skiko.renderApi") != null) return
+ System.setProperty("skiko.renderApi", "OPENGL")
+ System.setProperty("skiko.macos.opengl.enabled", "true")
+ }
+
+ /**
+ * The interface is laid out for a screen this many dp tall and scaled to fit the real one.
+ * At 1080p that makes a dp two pixels, the size of a unit of Minecraft's GUI at scale 2.
+ */
+ private const val REFERENCE_HEIGHT = 540f
+}
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/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/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt
new file mode 100644
index 000000000..982fb78e3
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/Snap.kt
@@ -0,0 +1,123 @@
+/*
+ * 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 androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
+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 kotlin.math.abs
+import kotlin.math.max
+import kotlin.math.roundToInt
+
+/**
+ * Where something that is dragged ends up, in scene pixels: on the screen, and snapped into
+ * line with its surroundings while the snap key is held. HUD elements in the HUD editor and
+ * the windows of the click GUI are placed by it alike.
+ *
+ * Each axis is snapped on its own, and the guides come in tiers: the other elements and the
+ * screen edges are tried first, then the centre of the screen, then the grid. The first tier
+ * with a guide in reach wins, and within it the guide closest to any of the element's three
+ * lines (its two edges and its centre) does.
+ */
+internal object Snap {
+ /** The guides the element snapped to, drawn while dragging. Null where it snapped to nothing worth showing. */
+ 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)
+
+ /** Whether a dragged element snaps right now: snapping is on and its key, if it has one, is held */
+ val isActive: Boolean
+ get() = GuiConfig.snapEnabled && (GuiConfig.snapKey == Bind.EMPTY || GuiConfig.snapKey.isSatisfied())
+
+ /** [element] left where it was dragged to, only kept on the [screen] */
+ fun free(element: Rect, screen: Size) = Result(element.topLeft.keptOn(screen, element.size), Guides.NONE)
+
+ /**
+ * The [lines] of the element along one axis, positions to snap them to, and how close a line
+ * has to be to one. Grid snaps are not drawn.
+ */
+ private class Tier(val lines: List, val reach: Float, val shown: Boolean, val nearest: (line: Float) -> Float?)
+
+ /**
+ * [element] moved onto the nearest guide in reach, of the [others] and the [screen].
+ *
+ * @param spacing the room left between [element] and one of the [others] it is snapped
+ * beside, in pixels. Two that are lined up edge on edge are still exactly in line.
+ */
+ fun snap(element: Rect, others: Collection, screen: Size, density: Density, spacing: Float = 0f): Result = with(density) {
+ fun tiers(extent: Float, start: (Rect) -> Float, end: (Rect) -> Float): List {
+ fun center(rect: Rect) = (start(rect) + end(rect)) / 2
+ val lines = listOf(start(element), center(element), end(element))
+
+ // Against its neighbours, everything is taken to be half the spacing larger all
+ // round. Side by side that leaves the spacing between two; in line it changes nothing.
+ val half = spacing / 2
+ val spacedLines = listOf(start(element) - half, center(element), end(element) + half)
+ val neighbourGuides = buildList {
+ if (GuiConfig.snapToEdges) {
+ add(-half)
+ add(extent + half)
+ others.forEach {
+ add(start(it) - half)
+ add(end(it) + half)
+ }
+ }
+ if (GuiConfig.snapToCenters) others.forEach { add(center(it)) }
+ }
+ val gridStep = max(4f, GuiConfig.gridSize.dp.toPx())
+ return listOfNotNull(
+ Tier(spacedLines, GuiConfig.snapDistanceElement.dp.toPx(), shown = true) { line ->
+ neighbourGuides.minByOrNull { abs(it - line) }
+ },
+ Tier(lines, GuiConfig.snapDistanceScreen.dp.toPx(), shown = true) { extent / 2 }
+ .takeIf { GuiConfig.snapToScreenCenter },
+ Tier(lines, GuiConfig.snapDistanceGrid.dp.toPx(), shown = false) { line -> (line / gridStep).roundToInt() * gridStep }
+ .takeIf { GuiConfig.snapToGrid },
+ )
+ }
+
+ val (shiftX, guideX) = snapAxis(tiers(screen.width, { it.left }, { it.right }))
+ val (shiftY, guideY) = snapAxis(tiers(screen.height, { it.top }, { it.bottom }))
+ Result((element.topLeft + Offset(shiftX, shiftY)).keptOn(screen, element.size), Guides(guideX, guideY))
+ }
+
+ /** How far to move along the axis to reach the best guide, and that guide if it should be drawn */
+ private fun snapAxis(tiers: List): Pair {
+ for (tier in tiers) {
+ val (line, guide) = tier.lines
+ .mapNotNull { line -> tier.nearest(line)?.let { line to it } }
+ .minByOrNull { (line, guide) -> abs(guide - line) }
+ ?: continue
+ if (abs(guide - line) <= tier.reach) return guide - line to guide.takeIf { tier.shown }
+ }
+ return 0f to null
+ }
+
+ private fun Offset.keptOn(screen: Size, element: Size) = Offset(
+ x.coerceIn(0f, max(0f, screen.width - element.width)),
+ y.coerceIn(0f, max(0f, screen.height - 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..ad131bdbe
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt
@@ -0,0 +1,255 @@
+/*
+ * 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.MutableTransitionState
+import androidx.compose.animation.animateColorAsState
+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.ExperimentalFoundationApi
+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.SideEffect
+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.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.Size
+import androidx.compose.ui.geometry.Rect
+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.Snap
+import com.lambda.gui.component.ScrollColumn
+import com.lambda.gui.component.SlidingText
+import com.lambda.gui.component.hoverHighlight
+import com.lambda.gui.component.Tooltip
+import com.lambda.gui.component.mouseClickable
+import com.lambda.gui.component.mouseDraggable
+import com.lambda.gui.component.window
+import com.lambda.gui.core.LocalShown
+import com.lambda.gui.core.observe
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.Radius
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+import com.lambda.gui.theme.shadowed
+import com.lambda.module.Module
+import com.lambda.module.ModuleRegistry
+import com.lambda.module.ModuleTag
+
+internal val CategoryWindowWidth = 100.dp
+internal val CategoryWindowGap = 2.dp
+
+/** Room between the edge of a window and the text of its rows */
+private val RowPadding = 4.dp
+
+/**
+ * A draggable window listing the modules of [tag]. Left click on a module toggles it, right click
+ * opens its settings; right click on the header folds the window away.
+ *
+ * Until it has been dragged somewhere it sits at [defaultPosition]. It goes exactly where it is
+ * dragged, unless [snapping], when it lines up with the screen, the grid and the other windows,
+ * whose places are kept in [bounds]. Beside another window it snaps to the distance they have
+ * in their row, so one that was moved by accident can be put straight back.
+ */
+@Composable
+internal fun CategoryWindow(
+ tag: ModuleTag,
+ defaultPosition: DpOffset,
+ bounds: MutableMap,
+ snapping: Boolean,
+ edited: Module?,
+ panels: List,
+ onEdit: (Module) -> Unit,
+ 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() }
+
+ // Where the window was left and whether it is folded away live in the config alone,
+ // so resetting the layout there is all it takes to put the window back
+ val placement by observe { GuiConfig.windows[tag.name] }
+ val position = placement?.let { DpOffset(it.x.dp, it.y.dp) }
+ val collapsed = placement?.collapsed ?: false
+
+ // Where the pointer has taken the window's corner while it is being dragged, in pixels.
+ // Where the window is shown, and left, follows from it and from whether it snaps right now.
+ var dragged by remember { mutableStateOf(null) }
+ val shownPosition = dragged?.let { corner ->
+ val window = Rect(corner, bounds[tag]?.size ?: Size.Zero)
+ val placed =
+ if (snapping) Snap.snap(window, bounds.filterKeys { it != tag }.values, screen, density, with(density) { CategoryWindowGap.toPx() })
+ else Snap.free(window, screen)
+ with(density) { DpOffset(placed.position.x.toDp(), placed.position.y.toDp()) }
+ } ?: position ?: defaultPosition
+ val currentPosition by rememberUpdatedState(shownPosition)
+ DisposableEffect(tag) {
+ onDispose { bounds -= tag }
+ }
+
+ fun place(at: DpOffset, collapsed: Boolean) {
+ GuiConfig.windows += tag.name to GuiConfig.WindowPlacement(at.x.value, at.y.value, collapsed)
+ }
+
+ Column(
+ modifier = modifier
+ .offset(shownPosition.x, shownPosition.y)
+ .width(CategoryWindowWidth)
+ .onGloballyPositioned { bounds[tag] = Rect(it.positionInRoot(), it.size.toSize()) }
+ .pointerInput(Unit) {
+ // Seen on the way down to the children, so any press inside raises the window
+ awaitPointerEventScope {
+ while (true) {
+ if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) onFocus()
+ }
+ }
+ }
+ .window(colors.surface, colors.border, RoundedCornerShape(Radius.Medium))
+ ) {
+ 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
+ },
+ ) { delta -> dragged = dragged?.plus(delta) }
+ .mouseClickable(onRightClick = {
+ // Settings hang off a row of the list, and go with it
+ if (!collapsed) edited?.takeIf { it in modules }?.let(onEdit)
+ place(currentPosition, !collapsed)
+ })
+ .padding(horizontal = RowPadding, vertical = 2.dp)
+ )
+
+ // Unfolds out of its header each time the GUI is opened as well as when it is unfolded
+ // by hand. Closing the GUI takes it away at once: the list starts over, folded, unseen.
+ val shown = LocalShown.current
+ val unfolded = remember(shown) { MutableTransitionState(false) }
+ unfolded.targetState = shown && !collapsed
+ // Settings hanging off a row wait for the rows to be where they will stay
+ val settled = unfolded.isIdle && unfolded.currentState
+ SideEffect { panels.forEach { if (it.module in modules) it.settled = settled } }
+ AnimatedVisibility(
+ visibleState = unfolded,
+ enter = expandVertically(spring()),
+ exit = shrinkVertically(spring()),
+ ) {
+ // Never taller than the room left under the header, however far down the window sits
+ ScrollColumn(Modifier.heightIn(max = (screenHeight - shownPosition.y - 24.dp).coerceAtLeast(48.dp))) {
+ modules.forEach { module ->
+ ModuleRow(
+ module = module,
+ isEdited = module == edited,
+ panel = panels.find { it.module == module },
+ onEdit = { onEdit(module) },
+ )
+ }
+ }
+ }
+ }
+}
+
+/** One module of the list. While its settings [panel] is on screen the row tells it where it is. */
+@OptIn(ExperimentalFoundationApi::class)
+@Composable
+private fun ModuleRow(module: Module, isEdited: 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())
+ // Pressed in like a button that is held down, for as long as its settings are out
+ val pressed by animateColorAsState(if (isEdited) colors.inset else Color.Transparent, spring())
+
+ // Lit and brought into view while it is what the search points at
+ val revealed = Reveal.module === module && Reveal.setting == null
+ // In the colour of text, white on the dark theme: nothing else in the interface is filled with it
+ 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(
+ modifier = Modifier
+ .fillMaxWidth()
+ .then(
+ if (panel == null) Modifier
+ else Modifier.onGloballyPositioned { panel.row = Rect(it.positionInRoot(), it.size.toSize()) }
+ )
+ .bringIntoViewRequester(intoView)
+ .background(fill)
+ .background(pressed)
+ .background(lit)
+ // A shade lighter under the pointer, or darker in the light theme
+ .hoverHighlight(colors.raised)
+ // One that is always enabled has nothing to toggle: either click opens its settings
+ .mouseClickable(onRightClick = onEdit) { if (module.alwaysEnabled) onEdit() else module.toggle() }
+ .padding(horizontal = RowPadding, vertical = 1.dp)
+ ) {
+ // A name too long for the window slides along rather than being cut short
+ SlidingText(
+ text = module.name,
+ color = if (enabled || isEdited) colors.onModuleEnabled 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..4d00b3a98
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt
@@ -0,0 +1,194 @@
+/*
+ * 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.ui.input.pointer.PointerEventPass
+import androidx.compose.ui.input.pointer.PointerEventType
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.runtime.LaunchedEffect
+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.platform.LocalDensity
+import androidx.compose.ui.platform.LocalWindowInfo
+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.Snap
+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.module.HudModule
+import com.lambda.module.Module
+import com.lambda.module.modules.client.AutoUpdater
+import com.lambda.module.ModuleTag
+
+/** How far from the top of the screen the category windows are lined up until they are moved: clear of the buttons, with room to drag them up */
+private val WindowRowTop = 94.dp
+
+/**
+ * The categories the click GUI has a window for. HUD elements are not among them: they are
+ * added, removed and set up where they are arranged, in the HUD editor.
+ */
+internal val ClickGuiCategories = ModuleTag.defaults - ModuleTag.HUD
+
+/** A window the click GUI shows over everything else until it is dismissed */
+internal sealed interface ClickGuiDialog {
+ data object About : ClickGuiDialog
+ data object NewAutomationConfig : ClickGuiDialog
+ data class Settings(val config: Config) : ClickGuiDialog
+}
+
+/** What is open in the click GUI. Lives outside the composition so a keybind can open the search. */
+internal object ClickGuiState {
+ var dialog: ClickGuiDialog? by mutableStateOf(null)
+ var developerMode by mutableStateOf(false)
+}
+
+/**
+ * The click GUI: a window of modules for every shown category, the settings of whichever
+ * module was last right-clicked, popped out beside it, a menu bar along the top for everything
+ * else, and the way to the HUD editor in the corner.
+ */
+@Composable
+internal fun ClickGui() {
+ val density = LocalDensity.current
+ val screen = LocalWindowInfo.current.containerSize
+ val developerMode = ClickGuiState.developerMode
+ val tags by observe {
+ ClickGuiCategories.filter(ModuleTag::isTagShown) + listOfNotNull(ModuleTag.DEBUG.takeIf { developerMode })
+ }
+
+ // The module whose settings are open. Its panel stays in the list until it has folded away,
+ // so clicking from module to module leaves several on screen, each finishing its own animation
+ var edited by remember { mutableStateOf(null) }
+ val panels = remember { mutableStateListOf() }
+ // Every panel that has been open, so one that is opened again is as tall as it was left
+ val panelStates = remember { HashMap() }
+ fun edit(module: Module) {
+ edited = module
+ val panel = panelStates.getOrPut(module) { SettingsPanelState(module) }
+ if (panel !in panels) panels += panel
+ }
+
+ // A setting the search points at is shown in the settings of its module
+ val revealedModule = Reveal.module
+ val revealedSetting = Reveal.setting
+ LaunchedEffect(revealedModule, revealedSetting) {
+ if (revealedModule != null && revealedModule !is HudModule && revealedSetting != null) edit(revealedModule)
+ }
+
+ // Put away, the click GUI closes the settings that were open, unless they are to be kept
+ val shown = LocalShown.current
+ LaunchedEffect(shown) {
+ if (!shown && !GuiConfig.keepSettingsOpen) {
+ edited = null
+ panels.clear()
+ }
+ }
+
+ // Most recently clicked last, so it is drawn on top
+ val stacking = remember { mutableStateListOf() }
+ // Where every window is, in scene pixels: what a dragged one snaps against while the snap key is held
+ val bounds = remember { mutableStateMapOf() }
+ val snapping by observe { Snap.isActive }
+
+ Box(Modifier.fillMaxSize().mouseClickable { edited = null }) {
+ // The row is centred without the debug window, which takes the place after its end:
+ // turning developer mode on or off leaves every other window where it is
+ val inRow = tags.count { it != ModuleTag.DEBUG }
+ val rowWidth = CategoryWindowWidth * inRow + CategoryWindowGap * (inRow - 1)
+ val rowStart = (with(density) { screen.width.toDp() } - rowWidth) / 2
+
+ tags.forEachIndexed { index, tag ->
+ key(tag) {
+ CategoryWindow(
+ tag = tag,
+ defaultPosition = DpOffset(rowStart + (CategoryWindowWidth + CategoryWindowGap) * index, WindowRowTop),
+ bounds = bounds,
+ snapping = snapping,
+ edited = edited,
+ panels = panels,
+ onEdit = { module -> if (module == edited) edited = null else edit(module) },
+ onFocus = {
+ stacking.remove(tag)
+ stacking.add(tag)
+ },
+ modifier = Modifier.zIndex(stacking.indexOf(tag).toFloat())
+ )
+ }
+ }
+
+ panels.forEach { panel ->
+ key(panel.module) {
+ SettingsPanel(
+ panel = panel,
+ open = panel.module == edited,
+ onClosed = { panels -= panel },
+ modifier = Modifier.zIndex(stacking.size.toFloat())
+ )
+ }
+ }
+
+ MenuBar(
+ Modifier
+ .align(Alignment.TopStart)
+ .zIndex(stacking.size + 1f)
+ // A press anywhere on the bar puts the open settings away, as one on the empty screen does
+ .pointerInput(Unit) {
+ awaitPointerEventScope {
+ while (true) {
+ if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) edited = null
+ }
+ }
+ }
+ )
+ Button(
+ label = "HUD Editor",
+ modifier = Modifier.align(Alignment.BottomEnd).padding(4.dp).zIndex(stacking.size + 1f)
+ ) { LambdaGui.open(LambdaGui.Screen.HudEditor) }
+ }
+
+ val prompt by observe { AutoUpdater.prompt }
+ prompt?.let { LoaderPromptDialog(it) } ?: when (val dialog = ClickGuiState.dialog) {
+ ClickGuiDialog.About -> AboutDialog(onDismiss = { ClickGuiState.dialog = null })
+ ClickGuiDialog.NewAutomationConfig -> NewAutomationConfigDialog(onDismiss = { ClickGuiState.dialog = null })
+ is ClickGuiDialog.Settings -> ConfigDialog(dialog.config, onDismiss = { ClickGuiState.dialog = null })
+ null -> Unit
+ }
+}
diff --git a/src/main/kotlin/com/lambda/gui/clickgui/Reveal.kt b/src/main/kotlin/com/lambda/gui/clickgui/Reveal.kt
new file mode 100644
index 000000000..eef7fd68f
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/clickgui/Reveal.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.clickgui
+
+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.GuiConfig
+import com.lambda.gui.LambdaGui
+import com.lambda.module.HudModule
+import com.lambda.module.Module
+import com.lambda.module.ModuleRegistry
+import com.lambda.module.ModuleTag
+
+/**
+ * What a search result points at, shown where it lives instead of in the list of results.
+ *
+ * A module's category is brought back if it was hidden or folded away, and the module is lit
+ * for a moment. A setting has the panel or window it is in opened on the right tab, with the
+ * groups around it unfolded, and is lit there. Whatever draws a module or a setting looks here
+ * to see whether it is the one.
+ */
+internal object Reveal {
+ var module: Module? by mutableStateOf(null)
+ private set
+ var setting: Setting<*>? by mutableStateOf(null)
+ private set
+
+ /** How long what was revealed stays lit */
+ const val MILLIS = 1800L
+
+ fun show(module: Module) = show(module, null)
+
+ /** Shows [setting] of [config], or [config] itself when it is a module and no setting is given */
+ fun show(config: Config, setting: Setting<*>?) {
+ val owner = owner(config)
+ module = owner
+ this.setting = setting
+ when (owner) {
+ // HUD elements live in the HUD editor, which opens the element's settings for a setting
+ is HudModule -> LambdaGui.open(LambdaGui.Screen.HudEditor)
+ // ...modules in the click GUI, which opens the module's settings for a setting
+ is Module -> uncover(owner)
+ // The rest only have the window their menu entry opens
+ else -> ClickGuiState.dialog = ClickGuiDialog.Settings(config)
+ }
+ }
+
+ /**
+ * The module whose settings show [config]: the module itself, or the one whose own automation
+ * config it is, which is listed in its settings under "Automation Config"
+ */
+ private fun owner(config: Config): Module? =
+ config as? Module ?: config.takeIf { it !== AutomationConfig.DEFAULT }
+ ?.let { ModuleRegistry.modules.firstOrNull { module -> module.automationConfig === config } }
+
+ fun clear() {
+ module = null
+ setting = null
+ }
+
+ /** Makes sure the row of [module] is on screen to be pointed at */
+ 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/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt
new file mode 100644
index 000000000..f783f7839
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt
@@ -0,0 +1,446 @@
+/*
+ * 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.AnimatedContent
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.animateColorAsState
+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.Row
+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.width
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.layout.wrapContentSize
+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.key
+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.drawBehind
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.input.pointer.pointerHoverIcon
+import androidx.compose.ui.layout.layout
+import androidx.compose.ui.layout.boundsInWindow
+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.config.automation.AutomationConfig
+import com.lambda.config.automation.UserAutomationConfig
+import com.lambda.config.categories.UserAutomationCategory
+import com.lambda.config.entries.Setting
+import com.lambda.gui.component.Button
+import com.lambda.gui.component.Dropdown
+import com.lambda.gui.component.LocalClickOnRelease
+import com.lambda.gui.component.LocalPopupHost
+import com.lambda.gui.component.PopupHost
+import com.lambda.gui.component.RowHeight
+import com.lambda.gui.component.ScrollColumn
+import com.lambda.gui.component.Tooltip
+import com.lambda.gui.component.Unfold
+import com.lambda.gui.component.dropShadow
+import com.lambda.gui.component.hoverHighlight
+import com.lambda.gui.component.mouseClickable
+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.observe
+import com.lambda.gui.menu.MenuBarHeight
+import com.lambda.gui.settings.SettingRow
+import com.lambda.gui.settings.SettingsList
+import com.lambda.gui.settings.hasVisibleSettings
+import com.lambda.gui.settings.holds
+import com.lambda.gui.settings.pageTurn
+import com.lambda.gui.settings.settingCell
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.Radius
+import com.lambda.gui.theme.SoftTextShadow
+import com.lambda.gui.theme.Text
+import com.lambda.module.HudModule
+import com.lambda.module.Module
+import com.lambda.module.modules.client.AutoUpdater
+import kotlin.math.roundToInt
+import kotlinx.coroutines.launch
+
+/** The panel never gets narrower than this, even when every setting has a short name */
+private val MinWidth = 130.dp
+
+/** Room between the edge of the panel and what it lists, the same on every side */
+private val Padding = 4.dp
+
+/** A panel is given at least this much height, even under a module at the bottom of the screen */
+private val MinHeight = 120.dp
+
+/** ...nor wider than this, so one long name cannot swallow the screen */
+private val MaxWidth = 260.dp
+
+/** The settings of [module] as a panel on screen, and the [row] of the module list it hangs off */
+internal class SettingsPanelState(val module: Module) {
+ /** Where the module's row is, in scene pixels. Kept current by the row itself. */
+ var row by mutableStateOf(Rect.Zero)
+
+ /** How much taller than the room under its row the user has made the panel, by dragging its top edge up */
+ var extension by mutableStateOf(0.dp)
+
+ /** Whether the list the row is in has finished unfolding. Kept current by the category window. */
+ var settled by mutableStateOf(false)
+
+ /** Which of its pages is turned to, kept while the panel is shut */
+ var page by mutableStateOf(PanelPage.Settings)
+}
+
+/**
+ * A module's settings, popped out of its category window beside the row that opened it.
+ *
+ * It opens to the right of the row and flips to the left when that would run off the screen.
+ * It hangs from the top of the row and stays there: settings too long for the room underneath
+ * scroll, so nothing moves under the pointer when a group is unfolded. While they scroll, the
+ * top edge of the panel has a grip, and dragging that up makes the panel taller, above the row,
+ * by as much as the user likes and the settings need, though never up under the menu bar. It unfolds while [open]
+ * and folds away once it is not, calling [onClosed] when there is nothing left of it. Both
+ * animations run on their own, so one panel can open while another is still closing.
+ */
+@Composable
+internal fun SettingsPanel(panel: SettingsPanelState, open: Boolean, onClosed: () -> Unit, modifier: Modifier = Modifier) {
+ val row = panel.row
+ // The row reports where it is once it has been laid out with the panel attached
+ if (row.isEmpty) return
+
+ // Starts over, folded, each time the GUI is opened: a panel that was kept open unfolds
+ // again, and only once the list its row is in has, so it does not ride the row down
+ val visibility = remember(LocalShown.current) { MutableTransitionState(false) }
+ val wanted = open && panel.settled
+ // A menu left open on one of its settings folds away with the panel, inside what is left of it
+ val popups = remember { PopupHost() }
+ SideEffect { popups.closing = !wanted }
+ visibility.targetState = wanted
+ if (!open && visibility.isIdle && !visibility.currentState) {
+ SideEffect(onClosed)
+ return
+ }
+
+ val density = LocalDensity.current
+ val screen = LocalWindowInfo.current.containerSize
+ var size by remember { mutableStateOf(IntSize.Zero) }
+ // How much of its height is unfolded right now
+ var unfolded by remember { mutableStateOf(0) }
+
+ // The room it may take: what is left under the top of the row, and what the user has
+ // added by dragging the top edge up. A row at the very bottom still gets a panel tall enough to use.
+ val scroll = rememberScrollState()
+ val screenHeight = with(density) { screen.height.toDp() }
+ val below = with(density) { (screen.height - row.top).toDp() }.coerceAtLeast(MinHeight)
+ // Never up under the menu bar, where its top edge, and the grip on it, could not be reached again
+ val highest = screenHeight - MenuBarHeight
+ val maxHeight = (below + panel.extension).coerceAtMost(highest)
+
+ // One dp of overlap lets the panel's border sit on the window's, so the seam is a single line
+ val overlap = with(density) { 1.dp.toPx() }
+ val flipped = row.right - overlap + size.width > screen.width && row.left + overlap - size.width >= 0
+ val lift = (row.top + unfolded - screen.height)
+ .coerceIn(0f, (row.top - with(density) { MenuBarHeight.toPx() }).coerceAtLeast(0f))
+
+ // Square only on the corner that touches the row, which is no corner at all once lifted
+ val shape = RoundedCornerShape(
+ topStart = if (flipped || lift > 0f) Radius.Large else 0.dp,
+ topEnd = if (!flipped || lift > 0f) Radius.Large else 0.dp,
+ bottomEnd = Radius.Large,
+ bottomStart = Radius.Large,
+ )
+ val seam = if (flipped) Alignment.TopEnd else Alignment.TopStart
+
+ Box(
+ modifier
+ .offset {
+ IntOffset(
+ (if (flipped) row.left + overlap else row.right - overlap).roundToInt(),
+ (row.top - lift).roundToInt()
+ )
+ }
+ // A point on the seam: the panel grows out of it, to whichever side it opens
+ .size(0.dp)
+ .wrapContentSize(seam, unbounded = true)
+ ) {
+ // Unfolded by size alone. A fade would draw the panel into a layer of its own first,
+ // where there is nothing behind the glass for it to blur.
+ AnimatedVisibility(
+ visibleState = visibility,
+ // The shadow is cast by what is unfolded, from outside the clip that does the unfolding
+ modifier = Modifier
+ .onSizeChanged { unfolded = it.height }
+ .onGloballyPositioned { popups.place(it.boundsInWindow()) }
+ .dropShadow(RoundedCornerShape(Radius.Large)),
+ enter = expandIn(Unfold, seam),
+ exit = shrinkOut(Unfold, seam),
+ ) {
+ val colors = LambdaTheme.colors
+ Box(
+ Modifier
+ .widthIn(MinWidth, MaxWidth)
+ // Bounded before the intrinsic width is asked for: that query passes the
+ // height on, and the scrolling content cannot answer for an infinite one
+ .heightIn(max = maxHeight)
+ .widthOfContent()
+ .onSizeChanged { size = it }
+ .window(colors.panel, colors.border, shape)
+ ) {
+ val pages = remember(panel.module) { pagesOf(panel.module) }
+ val page = panel.page.takeIf { it in pages } ?: PanelPage.Settings
+ // A setting the search points at is on one of the pages: that one is turned to
+ val revealed = Reveal.setting.takeIf { Reveal.module === panel.module }
+ LaunchedEffect(revealed) {
+ if (revealed != null) panel.page = pageOf(panel.module, revealed)
+ }
+ val scope = rememberCoroutineScope()
+
+ CompositionLocalProvider(LocalPopupHost provides popups) {
+ Column(Modifier.padding(Padding)) {
+ SoftTextShadow {
+ // Stays put over the page, which scrolls under it
+ if (pages.size > 1) PageStrip(pages, page) {
+ panel.page = it
+ // A page turned to by hand starts at its top
+ scope.launch { scroll.scrollTo(0) }
+ }
+ ScrollColumn(Modifier.weight(1f, fill = false), scroll) {
+ // Turned like the tabs a module's settings bring
+ AnimatedContent(
+ targetState = page,
+ modifier = Modifier.fillMaxWidth(),
+ transitionSpec = { pageTurn(towardsEnd = targetState > initialState) },
+ ) { shown ->
+ Column(Modifier.fillMaxWidth()) {
+ when (shown) {
+ PanelPage.Settings -> SettingsPage(panel.module)
+ PanelPage.Module -> ModulePage(panel.module)
+ PanelPage.Automation -> AutomationPage(panel.module)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ // Only there while there is something to gain from it, or to take back
+ if (scroll.maxValue > 0 || lift > 0f) {
+ Grip(
+ onDragStart = {
+ // Whatever was added but is not in use, the settings having got shorter since, is let go
+ 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)
+ )
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Makes the element as wide as what it holds would like to be, and when that changes, a group
+ * having been unfolded or folded away, takes it there over a moment rather than at once.
+ */
+private fun Modifier.widthOfContent(): Modifier = composed {
+ val scope = rememberCoroutineScope()
+ // Created at the width first asked for, so a panel opens at its size instead of growing into it
+ 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, WidthChange) }
+
+ val placeable = measurable.measure(Constraints.fixedWidth(current.value.roundToInt()).copy(maxHeight = constraints.maxHeight))
+ layout(placeable.width, placeable.height) { placeable.place(0, 0) }
+ }
+}
+
+private val WidthChange = spring(stiffness = Spring.StiffnessMedium)
+
+/**
+ * The grip along the top edge of a panel whose settings scroll. Dragging it [up] by some
+ * distance, or down by a negative one, is how the panel is made taller and shorter.
+ */
+@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(Padding)
+ .pointerHoverIcon(ResizeVerticalIcon)
+ .mouseDraggable(onDragStart = onDragStart) { delta -> onDrag(with(density) { -delta.y.toDp() }) }
+ ) {
+ Spacer(Modifier.size(16.dp, 1.dp).background(color, RoundedCornerShape(50)))
+ }
+}
+
+/**
+ * What a settings panel can show. A module's own settings are the first page, and what every
+ * module has is kept off it on pages of its own, so the first is never longer than the module
+ * makes it.
+ */
+internal enum class PanelPage(val title: String) {
+ Settings("Settings"),
+ Module("Module"),
+ Automation("Automation"),
+}
+
+/** The pages [module] has: all of them, short of the automation of a module that has none */
+private fun pagesOf(module: Module): List = when {
+ module == AutoUpdater -> listOf(PanelPage.Settings)
+ module.automationConfig === AutomationConfig.DEFAULT -> listOf(PanelPage.Settings, PanelPage.Module)
+ else -> PanelPage.entries
+}
+
+/** The page of [module]'s panel that [setting] is on */
+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(
+ // What only matters to a module that can be toggled is left out for one that cannot
+ module.keybindSetting.takeUnless { module.alwaysEnabled },
+ module.prioritySetting,
+ module.disableOnReleaseSetting.takeUnless { module.alwaysEnabled },
+ module.drawSetting.takeUnless { module.alwaysEnabled },
+ (module as? HudModule)?.backgroundColor,
+)
+
+/**
+ * The strip along the top of a panel that turns its pages. It spans the panel in equal parts
+ * and marks the chosen page with a line under its name, where the tabs a module's settings
+ * bring are filled: the two are told apart at a glance when one sits over the other.
+ */
+@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.primary else colors.raised)
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .weight(1f)
+ .height(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)
+ }
+ }
+ }
+}
+
+/** The module's own settings */
+@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)
+ }
+}
+
+/** Which automation config the module follows, and that config's settings */
+@Composable
+private fun AutomationPage(module: Module) {
+ val linked by observe { module.backingAutomationConfig }
+ // Among the settings and changed like one: when the button is let go
+ CompositionLocalProvider(LocalClickOnRelease provides true) { AutomationConfigSelector(module, linked) }
+ // The linked config's values are aliased into the module's own, so the list is
+ // rebuilt when the link changes to pick up the swapped ones
+ key(linked) { SettingsList(module.automationConfig.settingLayers) }
+}
+
+/** The settings every module has */
+@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(RowHeight)) { module.resetSettings() }
+ }
+ }
+}
+
+/** Picks which automation config the module follows: its own, or one of the user's */
+@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 = 3.dp),
+ ) { 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/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt
new file mode 100644
index 000000000..98e6a264c
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt
@@ -0,0 +1,494 @@
+/*
+ * 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.ScrollState
+import androidx.compose.foundation.ScrollbarStyle
+import androidx.compose.foundation.VerticalScrollbar
+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.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.rememberScrollState
+import androidx.compose.foundation.rememberScrollbarAdapter
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.v2.ScrollbarAdapter
+import androidx.compose.foundation.verticalScroll
+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.draw.drawWithContent
+import androidx.compose.ui.draw.rotate
+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.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.StrokeJoin
+import androidx.compose.ui.graphics.drawscope.Stroke
+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.layout.onSizeChanged
+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.IntSize
+import androidx.compose.ui.unit.dp
+import com.lambda.gui.theme.ContentColor
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.LocalContentColor
+import com.lambda.gui.theme.Radius
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+
+/** How tall a row of a list or a control is at least, so stacked ones line up: a line of text and a hair of room */
+val RowHeight = 13.dp
+
+private const val TOGGLE_MILLIS = 150
+
+@Composable
+fun Button(
+ label: String,
+ modifier: Modifier = Modifier,
+ enabled: Boolean = true,
+ onClick: () -> Unit,
+) {
+ val colors = LambdaTheme.colors
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = modifier
+ .heightIn(min = RowHeight + 2.dp)
+ .clip(RoundedCornerShape(Radius.Small))
+ .background(colors.control)
+ .hoverHighlight(colors.onControl.copy(alpha = if (enabled) 0.12f else 0f))
+ .mouseClickable(enabled, onClick = onClick)
+ .padding(horizontal = 5.dp, vertical = 1.dp)
+ ) {
+ Text(label, color = if (enabled) colors.onControl else colors.onSurfaceVariant, maxLines = 1)
+ }
+}
+
+/** The box of a checkbox, or the tick in front of a checked menu item */
+@Composable
+fun Checkmark(checked: Boolean, modifier: Modifier = Modifier) {
+ val colors = LambdaTheme.colors
+ Canvas(
+ modifier
+ .size(9.dp)
+ .clip(RoundedCornerShape(Radius.ExtraSmall))
+ // Empty, it is the grey of a slider's track, which stands out on a panel without an outline
+ .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)
+ )
+ }
+}
+
+/**
+ * Three dots in a row: what a chip ends in when clicking it opens a window to edit its value
+ * in, where a [Chevron] would point at a list that is not going to drop out of it.
+ */
+@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)) }
+ }
+}
+
+/** A small triangle pointing right, turned by [degrees]: 90 points it down, -90 up */
+@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
+ )
+ }
+}
+
+/**
+ * The [TextInput]s that hold the keyboard focus, one at most in the interface and in each popup
+ * over it. While any does, keys are typed into it, so nothing else may act on them: no keybind,
+ * and no walking around with the GUI open.
+ */
+internal object TextFocus {
+ private val fields = mutableListOf()
+
+ val isTyping get() = fields.isNotEmpty()
+
+ /** A press at [position], in scene pixels, takes the focus from every field it is not on */
+ 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) {
+ /** Where the field is, in scene pixels */
+ var bounds = Rect.Zero
+ }
+}
+
+/**
+ * A single or multi line text field.
+ *
+ * The text being edited is kept here and [onValueChange] reports every edit, so [value] may lag
+ * behind or disagree (a setting can refuse or correct what was typed) without the caret jumping:
+ * the field only adopts [value] when it changes from outside.
+ *
+ * @param focused take the keyboard focus as soon as the field appears
+ * @param onDone called when the user is finished with the field: on Enter, Escape or loss of focus
+ */
+@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() } }
+ // Kept for as long as it has the focus, however it loses it, even by leaving the screen
+ 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)
+ },
+ singleLine = singleLine,
+ textStyle = style.copy(color = colors.onControl),
+ cursorBrush = SolidColor(colors.onControl),
+ modifier = modifier
+ .heightIn(min = RowHeight)
+ .clip(RoundedCornerShape(Radius.Small))
+ .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()
+ }
+ }
+ )
+}
+
+/**
+ * A [TextInput] for a number. What is typed is kept as typed, so "1." is not rewritten to "1.0"
+ * mid-keystroke; it gives way to [value] only when that changes to a different number.
+ */
+@Composable
+fun NumberInput(
+ value: Number,
+ onValueChange: (Double) -> Unit,
+ modifier: Modifier = Modifier,
+ focused: Boolean = false,
+ onDone: (() -> Unit)? = null,
+) {
+ var text by remember { mutableStateOf(value.toString()) }
+ var adopted by remember { mutableStateOf(value) }
+ if (value != adopted) {
+ adopted = value
+ if (text.toDoubleOrNull() != value.toDouble()) text = value.toString()
+ }
+ TextInput(
+ value = text,
+ onValueChange = {
+ text = it
+ it.toDoubleOrNull()?.let(onValueChange)
+ },
+ modifier = modifier,
+ focused = focused,
+ onDone = onDone,
+ )
+}
+
+/**
+ * A column that scrolls when it is too tall, with a slim scrollbar while it does. Pass a
+ * [scroll] state to know from outside whether, and how far, it can.
+ */
+@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())
+ }
+}
+
+/**
+ * The slim bar along the right edge of [modifier]'s area that every scrolling list shows, and
+ * that can be dragged. Show it only while there is something to scroll.
+ */
+@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 = TOGGLE_MILLIS,
+ unhoverColor = colors.onSurfaceVariant.copy(alpha = 0.5f),
+ hoverColor = colors.onSurface
+ )
+ )
+ }
+}
+
+/** Content that unfolds vertically, the way every collapsible part of the interface opens */
+@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() }
+}
+
+/**
+ * A titled section that is collapsed until its header is clicked. [tooltip] explains the header.
+ *
+ * The header is a raised strip. Unfolded, a bar in the accent colour runs from the top of the
+ * header down its edge to the end of what it holds, which is set in beside the bar: header and
+ * content read as one bracket, also when a section sits inside another.
+ *
+ * @param revealed unfolds the section, for when something in it is to be pointed at
+ */
+@Composable
+fun Section(
+ title: String,
+ suffix: String? = null,
+ tooltip: String = "",
+ initiallyExpanded: Boolean = false,
+ revealed: Boolean = false,
+ content: @Composable ColumnScope.() -> Unit,
+) {
+ val colors = LambdaTheme.colors
+ var expanded by remember { mutableStateOf(initiallyExpanded) }
+ LaunchedEffect(revealed) {
+ if (revealed) expanded = true
+ }
+ val turn by animateFloatAsState(if (expanded) 90f else 0f, tween(TOGGLE_MILLIS))
+
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .padding(top = 1.dp)
+ .drawWithContent {
+ drawContent()
+ // Taller than its header, the section has something unfolded, or is unfolding
+ if (size.height > RowHeight.toPx() + 1f) {
+ drawRect(colors.primary, size = Size(SectionBar.toPx(), size.height))
+ }
+ }
+ ) {
+ Tooltip(tooltip, Modifier.fillMaxWidth()) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(3.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .heightIn(min = RowHeight)
+ .clip(RoundedCornerShape(Radius.Small))
+ .background(colors.raised)
+ .mouseClickable { expanded = !expanded }
+ .padding(horizontal = 4.dp)
+ ) {
+ Chevron(turn, color = colors.onSurface)
+ Text(title, color = colors.onSurface, maxLines = 1)
+ if (suffix != null) Text(suffix, color = colors.onSurfaceVariant, style = Type.label, maxLines = 1)
+ }
+ }
+ Expandable(expanded) {
+ Column(Modifier.fillMaxWidth().padding(start = SectionIndent, top = 1.dp), content = content)
+ }
+ }
+}
+
+private val SectionBar = 1.dp
+
+/** How far what a section holds is set in, clear of the bar */
+private val SectionIndent = 5.dp
+
+/**
+ * A value shown at the end of a setting's row as something to click: the chosen option of a
+ * dropdown, the size of a collection. As tall as a row, whatever it holds.
+ */
+@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(RowHeight)
+ .clip(RoundedCornerShape(Radius.Small))
+ .background(colors.control)
+ .hoverHighlight(colors.onControl.copy(alpha = 0.12f))
+ .mouseClickable(onClick = onClick)
+ .padding(horizontal = 4.dp),
+ content = content
+ )
+ }
+}
+
+/**
+ * A row with [label] and, at its end, the [selected] one of [options] on a [Chip]. Clicking the
+ * chip lists the options in a menu over the interface, so picking one moves nothing around it.
+ */
+@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) }
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(4.dp),
+ modifier = modifier.fillMaxWidth().heightIn(min = RowHeight)
+ ) {
+ Text(label, maxLines = 1)
+ // The chip has what the label leaves: a choice too long for it slides along under the
+ // pointer, as a module's name does, rather than running over the label
+ Box(Modifier.weight(1f), contentAlignment = Alignment.CenterEnd) {
+ Box(Modifier.onSizeChanged { chip = it }) {
+ Chip(onClick = menu::toggle) {
+ SlidingText(optionLabel(selected), Modifier.weight(1f, fill = false))
+ Chevron(90f)
+ }
+ // Drops out from under the chip, as wide as it, and folds all the way back up into it
+ 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)
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/** Fills whatever space is left with nothing, centring [text] in it: what a list shows when empty */
+@Composable
+fun EmptyHint(text: String, modifier: Modifier = Modifier) {
+ Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Text(text, color = LambdaTheme.colors.onSurfaceVariant, style = Type.label)
+ }
+}
diff --git a/src/main/kotlin/com/lambda/gui/Layout.kt b/src/main/kotlin/com/lambda/gui/component/Images.kt
similarity index 56%
rename from src/main/kotlin/com/lambda/gui/Layout.kt
rename to src/main/kotlin/com/lambda/gui/component/Images.kt
index 3a6562db9..cd5cd07dd 100644
--- a/src/main/kotlin/com/lambda/gui/Layout.kt
+++ b/src/main/kotlin/com/lambda/gui/component/Images.kt
@@ -15,10 +15,16 @@
* along with this program. If not, see .
*/
-package com.lambda.gui
+package com.lambda.gui.component
-import com.lambda.gui.dsl.ImGuiBuilder
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.toComposeImageBitmap
+import com.lambda.util.stream
+import org.jetbrains.skia.Image
-interface Layout {
- fun ImGuiBuilder.buildLayout()
-}
\ No newline at end of file
+/** One of Lambda's own images, by its path under `assets/lambda/` */
+@Composable
+fun rememberTexture(path: String): ImageBitmap =
+ remember(path) { path.stream.use { Image.makeFromEncoded(it.readAllBytes()) }.toComposeImageBitmap() }
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..e9715d49e
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt
@@ -0,0 +1,267 @@
+/*
+ * 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.ExperimentalFoundationApi
+import androidx.compose.foundation.MutatePriority
+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.ScrollableState
+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.rememberCoroutineScope
+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.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.platform.LocalDensity
+import androidx.compose.ui.unit.IntSize
+import androidx.compose.ui.unit.dp
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.launch
+
+/**
+ * Makes an element respond to mouse clicks, one callback per button.
+ *
+ * ```
+ * Modifier.mouseClickable(onRightClick = { openSettings() }) { module.toggle() }
+ * ```
+ *
+ * A click acts the moment the button goes down: nothing waits for the release, for a double
+ * click that might follow, or for an animation to finish, so the interface answers at once
+ * however fast it is clicked.
+ *
+ * Under [LocalClickOnRelease], which a setting is, it acts when the button is let go over the
+ * element it went down on instead: a value is not changed by a press that was a slip, as long
+ * as the pointer is moved off before letting go.
+ *
+ * Handled clicks are consumed: an element underneath never sees them.
+ */
+@OptIn(ExperimentalComposeUiApi::class)
+fun Modifier.mouseClickable(
+ enabled: Boolean = true,
+ onRightClick: (() -> Unit)? = null,
+ onMiddleClick: (() -> 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
+ PointerButton.Tertiary -> onMiddleClick
+ else -> null
+ }
+ }
+ 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()
+ Click.pressedAt = System.nanoTime()
+ if (!onRelease) {
+ actionFor(button)?.invoke()
+ continue
+ }
+
+ // Whatever the pointer does in between, it is where the button comes up that counts
+ while (true) {
+ val event = awaitPointerEvent()
+ val change = event.changes.first()
+ // A press of another button means this one's release was never seen
+ 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
+ }
+ }
+ }
+ }
+ }
+
+/** Whether clicks on what is inside act when the button is let go rather than when it goes down, see [mouseClickable] */
+val LocalClickOnRelease = compositionLocalOf { false }
+
+/** The click being handled, for what has to tell it from the press that began it */
+internal object Click {
+ /** When the button went down for the click whose action runs now, by [System.nanoTime] */
+ var pressedAt = 0L
+}
+
+/**
+ * Calls [onPress] the moment [button] goes down on the element, with where the pointer is inside
+ * it. For when the position matters, such as opening a context menu under the pointer.
+ */
+fun Modifier.onMousePress(button: PointerButton, onPress: (position: Offset) -> Unit): Modifier =
+ onPress { pressed, position ->
+ if (pressed == button) onPress(position)
+ pressed == button
+ }
+
+/**
+ * Offers every press on the element that nothing inside it took to [handle], which returns
+ * whether the press was for it; if so, nothing further out gets to see it.
+ */
+@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()
+ }
+ }
+ }
+}
+
+/**
+ * Swallows presses that nothing inside the element handled, so clicking the bare part of a
+ * window is not mistaken for clicking whatever lies behind it.
+ */
+fun Modifier.consumeClicks(): Modifier = pointerInput(Unit) {
+ awaitPointerEventScope {
+ while (true) {
+ val event = awaitPointerEvent()
+ if (event.type == PointerEventType.Press) event.changes.forEach { it.consume() }
+ }
+ }
+}
+
+/** Calls [onDrag] with the distance the pointer moved while the left button is held on the element */
+@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,
+)
+
+/**
+ * For sliders and pickers: reports where the pointer is, relative to the element, from the moment
+ * the left button goes down on it until it is released, wherever the pointer has wandered by then.
+ */
+fun Modifier.scrubbable(onScrub: (position: Offset, size: IntSize) -> Unit): Modifier = composed {
+ val currentOnScrub by rememberUpdatedState(onScrub)
+ pointerInput(Unit) {
+ awaitEachGesture {
+ // On a desktop only the left button counts as the first down of a gesture
+ val down = awaitFirstDown()
+ down.consume()
+ currentOnScrub(down.position, size)
+ drag(down.id) { change ->
+ change.consume()
+ currentOnScrub(change.position, size)
+ }
+ }
+ }
+}
+
+/**
+ * Scrolls [state] with the mouse wheel, in place of the scrolling a list comes with, which
+ * moves at one speed and is over in a tenth of a second. Here every notch sets the content off
+ * fast and lets it glide to rest, and further notches add to the distance still to go.
+ *
+ * Put it on the element around the list. A notch the list cannot follow, being at its end, is
+ * left for whatever scrolls outside of it.
+ */
+fun Modifier.wheelScrollable(state: ScrollableState): Modifier = composed {
+ val scope = rememberCoroutineScope()
+ val notch = with(LocalDensity.current) { WheelStep.toPx() }
+ val glide = remember { WheelGlide() }
+ pointerInput(state, notch) {
+ awaitPointerEventScope {
+ while (true) {
+ // On the way down, so the list's own wheel handling never gets to see the notch
+ val event = awaitPointerEvent(PointerEventPass.Initial)
+ if (event.type != PointerEventType.Scroll) continue
+ val change = event.changes.first()
+ val distance = change.scrollDelta.y * notch
+ val canFollow = if (distance > 0) state.canScrollForward else state.canScrollBackward
+ if (distance == 0f || !canFollow || change.isConsumed) continue
+ change.consume()
+
+ // What is left of the glide in progress is added to, unless the wheel turned round
+ val total = distance + if (glide.remaining * distance > 0) glide.remaining else 0f
+ glide.job?.cancel()
+ glide.job = scope.launch {
+ var travelled = 0f
+ glide.remaining = total
+ state.scroll(MutatePriority.UserInput) {
+ animate(0f, total, animationSpec = Glide) { value, _ ->
+ scrollBy(value - travelled)
+ travelled = value
+ glide.remaining = total - value
+ }
+ }
+ glide.remaining = 0f
+ }
+ }
+ }
+ }
+}
+
+/** The glide a list is in: how far it still has to go, and the animation taking it there */
+private class WheelGlide {
+ var remaining = 0f
+ var job: Job? = null
+}
+
+/** How far one line of the wheel takes a list; a notch is three lines, so three rows */
+private val WheelStep = 14.dp
+
+/** Off fast and a long time settling: most of the distance is covered in the first third */
+private val Glide = tween(durationMillis = 520, easing = EaseOutQuint)
+
+/** Fills the element with [color] while the pointer is over it */
+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..82def3c4d
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt
@@ -0,0 +1,694 @@
+/*
+ * 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.MutableTransitionState
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.VisibilityThreshold
+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.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.ui.graphics.drawscope.translate
+import androidx.compose.ui.layout.positionInWindow
+import androidx.compose.ui.graphics.drawscope.clipRect
+import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.composed
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.mutableIntStateOf
+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.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.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.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.LocalShown
+import com.lambda.gui.core.awaitFrames
+import com.lambda.gui.theme.ContentColor
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.Radius
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+import kotlin.math.max
+
+/** Where a [Menu] opens relative to the element it is declared in */
+enum class MenuPlacement {
+ /** Under the element, left edges aligned, or over it where the window ends first: a dropdown */
+ Below,
+
+ /** Beside the element, top edges aligned: a submenu */
+ Beside,
+}
+
+/**
+ * Whether a menu is open, kept by whatever opens it.
+ *
+ * A press outside a menu closes it and then goes on to what was pressed. When that is the
+ * very thing that opens the menu, [toggle], whether called by that press or once the button is
+ * let go, knows the menu was closed by the press of this same click and leaves it closed: clicking an open menu's
+ * button shuts it rather than opening it again.
+ */
+@Stable
+class MenuState {
+ var isOpen by mutableStateOf(false)
+ private set
+ private var dismissedAt = Long.MIN_VALUE
+
+ fun dismiss() {
+ isOpen = false
+ dismissedAt = System.nanoTime()
+ }
+
+ fun toggle() {
+ if (dismissedAt < Click.pressedAt - SAME_PRESS_NANOS) isOpen = true
+ }
+
+ private companion object {
+ /** The menu closes a moment before the press reaches what was pressed: this far apart they are one press */
+ const val SAME_PRESS_NANOS = 50_000_000L
+ }
+}
+
+/**
+ * What every floating panel shares: it has the keyboard, so Escape reaches it, but a press
+ * outside it is not swallowed. The press closes the panel, and every other one it missed, and
+ * then does what it would have done without them: one click is enough to get from an open
+ * menu to another, however deeply the first was nested.
+ */
+@OptIn(ExperimentalComposeUiApi::class)
+private val Floating = PopupProperties(
+ focusable = true,
+ dismissOnBackPress = true,
+ dismissOnClickOutside = true,
+ clippingEnabled = true,
+ usePlatformDefaultWidth = false,
+ usePlatformInsets = true,
+ consumePointerInputOutside = false,
+)
+
+/**
+ * A menu that floats above everything else, attached to the element it is called inside. It
+ * unfolds while [open] and folds back into the element once it is not, starting from and
+ * ending at [unfoldFrom], the size of the element it slides out of, or a point. It asks to close
+ * through [onDismiss] on Escape, a click anywhere outside of it, or the interface closing.
+ *
+ * ```
+ * val menu = remember { MenuState() }
+ * Box {
+ * Button("File", onClick = menu::toggle)
+ * Menu(menu.isOpen, onDismiss = menu::dismiss) {
+ * MenuItem("Save") { save() }
+ * }
+ * }
+ * ```
+ */
+@Composable
+fun Menu(
+ open: Boolean,
+ onDismiss: () -> Unit,
+ placement: MenuPlacement = MenuPlacement.Below,
+ unfoldFrom: IntSize = IntSize.Zero,
+ content: @Composable ColumnScope.() -> Unit,
+) {
+ MenuPopup(open, remember(placement) { UnfoldingPosition(placement::place) }, onDismiss, unfoldFrom, 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
+ )
+ // Flips to the other side when the window ends before the popup does
+ MenuPlacement.Beside -> IntOffset(
+ if (anchor.right + popup.width <= window.width) anchor.right else anchor.left - popup.width,
+ anchor.top
+ )
+}
+
+/**
+ * A panel that pops out beside the element it is called inside, the way a module's settings pop
+ * out of its row: for an editor too big to sit in a row of its own. Like those it unfolds out
+ * of the row while [open] and folds back into it once it is not. It asks to close through
+ * [onDismiss] on Escape, a click anywhere outside of it, or the interface closing.
+ */
+@Composable
+fun Popout(open: Boolean, onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) {
+ val position = remember { UnfoldingPosition(MenuPlacement.Beside::place) }
+ FloatingPanel(open, position, onDismiss, RoundedCornerShape(Radius.Large)) { panel ->
+ Column(panel.padding(3.dp), content = content)
+ }
+}
+
+/** A [Menu] at [position], in scene pixels: the one a right click opens under the pointer */
+@Composable
+fun ContextMenu(open: Boolean, position: IntOffset, onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) =
+ MenuPopup(open, remember(position) { UnfoldingPosition { _, _, _ -> position } }, onDismiss, IntSize.Zero, content)
+
+/**
+ * [value], or while that is null, what it last was: what a popup goes on showing while it folds
+ * away after the thing it showed has been let go.
+ */
+@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
+}
+
+/** Closes the whole chain of open menus, set by the outermost one */
+private val LocalMenuDismiss = staticCompositionLocalOf<(() -> Unit)?> { null }
+
+/** Whether the menu around is open, so the submenus in it fold away along with it */
+private val LocalMenuOpen = compositionLocalOf { true }
+
+@Composable
+private fun MenuPopup(
+ open: Boolean,
+ position: UnfoldingPosition,
+ onDismiss: () -> Unit,
+ unfoldFrom: IntSize,
+ content: @Composable ColumnScope.() -> Unit,
+) {
+ val open = open && LocalMenuOpen.current
+ val dismissAll = LocalMenuDismiss.current ?: onDismiss
+ val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() }
+ FloatingPanel(open, position, onDismiss, RoundedCornerShape(Radius.Medium), unfoldFrom) { panel ->
+ CompositionLocalProvider(LocalMenuDismiss provides dismissAll, LocalMenuOpen provides open) {
+ ScrollColumn(
+ modifier = Modifier
+ // Bounded before the intrinsic width is asked for, which passes the height on
+ .heightIn(max = screenHeight)
+ .width(IntrinsicSize.Max)
+ // As wide as the element it drops out of, at least
+ .widthIn(min = maxOf(80.dp, with(LocalDensity.current) { unfoldFrom.width.toDp() }))
+ .then(panel)
+ .padding(vertical = 1.dp),
+ content = content
+ )
+ }
+ }
+}
+
+/**
+ * Every floating panel opens and folds away on the spring a module's settings panel does, quick
+ * enough to keep up with fast clicking. Nothing waits for it: a press is acted on at once.
+ */
+val Unfold = spring(stiffness = Spring.StiffnessMedium, visibilityThreshold = IntSize.VisibilityThreshold)
+
+/**
+ * The part of the interface some floating panels are open on behalf of: the settings panel
+ * whose settings have menus, or a menu with a submenu beside it. While it is [closing] its
+ * panels shut too, and are swallowed by its own folding away. One that lies over it is drawn
+ * only inside what is left of it. One that hangs off an edge of it, as a submenu does, rides
+ * that edge inwards and is cut off where the host ends along it. Nothing is left in the air.
+ */
+class PopupHost {
+ var closing by mutableStateOf(false)
+
+ /** What is on screen of it right now, in the window */
+ var bounds by mutableStateOf(Rect.Zero)
+ private set
+
+ /** What was on screen of it when it started to close */
+ var full = Rect.Zero
+ private set
+
+ fun place(bounds: Rect) {
+ this.bounds = bounds
+ if (!closing) full = bounds
+ }
+}
+
+/** The [PopupHost] the floating panels opened from here belong to, if there is one */
+val LocalPopupHost = compositionLocalOf { null }
+
+/** Lets [host] swallow the element as it closes, as [PopupHost] describes */
+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()
+ // Off which edge of the host it hangs, if any, and how far that edge has come in
+ 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
+ }
+ // Cut to the host along an edge it does not hang off, far past its shadow along one it does
+ 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() }
+ }
+ }
+}
+
+/** How far into its host a panel may reach and still count as hanging off its edge */
+private val Slack = 4.dp
+
+/**
+ * What every floating panel shares. While [open] it unfolds out of the corner that touches the
+ * element it belongs to, and once it is not it folds back into that corner before it is gone.
+ * It takes input as [Floating] says, except while folding away: then it asks for nothing and
+ * lets every key through.
+ *
+ * [content] is the panel, given the [Modifier] that makes it one.
+ */
+@Composable
+private fun FloatingPanel(
+ open: Boolean,
+ position: UnfoldingPosition,
+ onDismiss: () -> Unit,
+ shape: Shape,
+ unfoldFrom: IntSize = IntSize.Zero,
+ content: @Composable (panel: Modifier) -> Unit,
+) {
+ // Gone at once with the interface, which leaves nothing on screen to fold away
+ if (!LocalShown.current) {
+ if (open) SideEffect(onDismiss)
+ return
+ }
+ val visibility = remember { MutableTransitionState(false) }
+ visibility.targetState = open
+ if (!open && visibility.isIdle && !visibility.currentState) return
+
+ // Shut when what it belongs to is going, which swallows it, and host to what is opened from it in turn
+ val host = LocalPopupHost.current
+ if (host != null && host.closing && open) SideEffect(onDismiss)
+ val own = remember { PopupHost() }
+ SideEffect { own.closing = !open }
+
+ val colors = LambdaTheme.colors
+ Popup(
+ popupPositionProvider = position,
+ onDismissRequest = { if (open) onDismiss() },
+ properties = Floating,
+ onKeyEvent = { open && it.dismissOnEscape(onDismiss) },
+ ) {
+ ContentColor(colors.onSurface) {
+ // Unfolded by size alone, as a fade would draw it into a layer of its own with nothing behind the glass to blur
+ AnimatedVisibility(
+ visibleState = visibility,
+ // The shadow is cast by what is unfolded, from outside the clip that does the unfolding
+ modifier = Modifier
+ .swallowedBy(host)
+ .onGloballyPositioned { own.place(it.boundsInWindow()) }
+ .dropShadow(shape, close = true),
+ enter = expandIn(Unfold, position.corner) { it.coerceAtMost(unfoldFrom) },
+ exit = shrinkOut(Unfold, position.corner) { it.coerceAtMost(unfoldFrom) },
+ ) {
+ CompositionLocalProvider(LocalPopupHost provides own) {
+ content(Modifier.onSizeChanged { position.unfolded = it }.window(colors.panel, colors.border, shape))
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Places a popup that unfolds: where [position] puts it, kept on the screen, as big as it will
+ * be once it is all there rather than as big as it is partway. That settles which side it
+ * opens to before it starts to grow, and it grows away from the element that opened it.
+ */
+private class UnfoldingPosition(
+ private val position: (anchor: IntRect, window: IntSize, popup: IntSize) -> IntOffset,
+) : PopupPositionProvider {
+ /** The size of the popup once unfolded, kept current by the popup */
+ var unfolded = IntSize.Zero
+
+ /** Whether it opened to the left of its element, and so grows leftwards */
+ private var leftwards by mutableStateOf(false)
+
+ /** Whether it opened above its element, and so grows upwards */
+ private var upwards by mutableStateOf(false)
+
+ /** The corner it grows out of */
+ 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
+ // Wherever it opens, all of it stays on the screen
+ val x = wanted.x.coerceIn(0, (windowSize.width - full.width).coerceAtLeast(0))
+ val y = wanted.y.coerceIn(0, (windowSize.height - full.height).coerceAtLeast(0))
+ // Growing leftwards or upwards, it is the far edge that stays where it is
+ return IntOffset(
+ if (leftwards) x + full.width - popupContentSize.width else x,
+ if (upwards) y + full.height - popupContentSize.height else y
+ )
+ }
+}
+
+/**
+ * A list that drops down under the element it is called inside while that element keeps the
+ * keyboard: what a search field shows its results in. Its right edge lines up with the
+ * element's. A press outside of it calls [onDismiss].
+ */
+@Composable
+fun Suggestions(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) {
+ if (!LocalShown.current) {
+ SideEffect(onDismiss)
+ return
+ }
+ val colors = LambdaTheme.colors
+ val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() }
+ Popup(
+ popupPositionProvider = remember {
+ positionProvider { anchor, _, popup -> IntOffset((anchor.right - popup.width).coerceAtLeast(0), anchor.bottom) }
+ },
+ onDismissRequest = onDismiss,
+ properties = PopupProperties(focusable = false),
+ ) {
+ ContentColor(colors.onSurface) {
+ ScrollColumn(
+ modifier = Modifier
+ .heightIn(max = screenHeight * 0.6f)
+ .width(IntrinsicSize.Max)
+ .window(colors.panel, colors.border, RoundedCornerShape(Radius.Medium), floating = true)
+ .padding(vertical = 1.dp),
+ content = content
+ )
+ }
+ }
+}
+
+/**
+ * An entry of a [Menu]. Choosing it closes the menu, unless it is a [checked] item, which is
+ * expected to be flipped back and forth. [selected] marks the one of several that is in effect.
+ */
+@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()
+ // The chosen one is filled like a ticked box, so it stands out from the rest at a glance
+ .background(if (selected) colors.primary else Color.Transparent)
+ .then(
+ if (!enabled) Modifier
+ else Modifier.hoverHighlight(colors.header).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.onControl
+ 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)
+ }
+}
+
+/** A [MenuItem] that opens another menu beside it when clicked */
+@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.header).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)
+
+/**
+ * A menu entry that only explains: resting the pointer on it shows [text], and clicking it does
+ * nothing, so the menu stays open to be read from.
+ */
+@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)
+)
+
+/**
+ * A window in the middle of the screen that takes all input until it is closed. Clicking the
+ * dimmed area around it, pressing Escape or closing the interface calls [onDismiss]; pass null
+ * for a dialog that must be answered through its own buttons.
+ */
+@Composable
+fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) {
+ // One that has to be answered waits for the interface to come back
+ if (!LocalShown.current) {
+ if (onDismiss != null) SideEffect(onDismiss)
+ return
+ }
+ val colors = LambdaTheme.colors
+ Popup(
+ popupPositionProvider = remember { positionProvider { _, _, _ -> IntOffset.Zero } },
+ properties = PopupProperties(focusable = true),
+ onKeyEvent = { onDismiss != null && it.dismissOnEscape(onDismiss) },
+ ) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .fillMaxSize()
+ .glass(Color.Black.copy(alpha = 0.35f), RectangleShape)
+ .mouseClickable { onDismiss?.invoke() }
+ ) {
+ ContentColor(colors.onSurface) {
+ Box(
+ modifier = Modifier
+ .window(colors.panel, colors.border, RoundedCornerShape(Radius.Large), floating = true)
+ .padding(6.dp),
+ content = content
+ )
+ }
+ }
+ }
+}
+
+/**
+ * Shows [text] under the pointer once it has rested on [content] for a moment, until it leaves
+ * or presses. Blank text shows nothing.
+ *
+ * Compose's own `TooltipArea` takes any pointer movement as hovering. When the pointer moves
+ * from the interface into a popup, the interface still hears of that move, at the pointer's new
+ * position, and nothing after it: whatever lies under the popup there would put up its tooltip.
+ * So only a real entry counts here.
+ */
+@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(TOOLTIP_DELAY_MILLIS)
+ 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() }
+ Popup(
+ 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(Radius.Medium))
+ .padding(horizontal = 4.dp, vertical = 2.dp)
+ )
+ }
+ }
+ }
+}
+
+/** How long the pointer rests on something before its tooltip shows */
+private const val TOOLTIP_DELAY_MILLIS = 500L
+
+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/SlidingText.kt b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt
new file mode 100644
index 000000000..ca410c54c
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt
@@ -0,0 +1,119 @@
+/*
+ * 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.Text
+import com.lambda.gui.theme.Type
+import kotlin.math.roundToInt
+
+/**
+ * A single line of text. When it is too long for the room it is given it is cut off, and
+ * resting the pointer on it has it slide along until its end has come into view, wait, and
+ * slide back, for as long as the pointer stays. Taking the pointer away slides it home from
+ * wherever it had got to.
+ *
+ * The way back is always the quick one: reading starts over at the beginning, and the sooner
+ * the text is there the better.
+ */
+@Composable
+fun SlidingText(
+ text: String,
+ modifier: Modifier = Modifier,
+ color: Color = LocalContentColor.current,
+ style: TextStyle = Type.body,
+) {
+ // How many pixels of the text do not fit, found out when it is laid out
+ var overflow by remember { mutableIntStateOf(0) }
+ val interactions = remember { MutableInteractionSource() }
+ val hovered by interactions.collectIsHoveredAsState()
+ val pixelsPerSecond = with(LocalDensity.current) { SlideSpeed.toPx() }
+
+ // How far along the text is, from 0 at home to 1 with its end in view
+ 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)
+ 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) {
+ // Moved by whole pixels, which keeps a pixel font sharp on the way
+ placeable.place(-(slide.value * overflow).roundToInt(), 0)
+ }
+ }
+ )
+}
+
+/** How fast the text moves towards its end: slow enough to read along */
+private val SlideSpeed = 28.dp
+
+/** Time before the text sets off, so that passing over it does not set it moving */
+private const val REST_MILLIS = 350
+
+/** Time at rest with the end in view */
+private const val END_REST_MILLIS = 900
+
+/** Time to slide home, however far that is */
+private const val BACK_MILLIS = 250
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..0e52a5eb6
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt
@@ -0,0 +1,162 @@
+/*
+ * 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.graphics.BlendMode
+import androidx.compose.ui.graphics.ClipOp
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Path
+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.dp
+import com.lambda.gui.theme.Hairline
+import com.lambda.gui.theme.LocalBackdropBlur
+import com.lambda.gui.theme.LocalOutlines
+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
+
+/**
+ * Makes the element a pane of frosted glass in [shape]: everything behind it is blurred, and
+ * [color] tints the result.
+ *
+ * "Behind" has two halves. The game is frosted by the compositor wherever the interface covers
+ * it, see [com.lambda.gui.render.GuiCompositor]. What the interface itself drew underneath, such
+ * as the window a settings panel has opened over, is blurred here, so it reads as part of the
+ * same background rather than showing through sharp or being cut out.
+ *
+ * With the blur switched off the pane simply replaces what is beneath it: stacked panes of
+ * translucent text over text would be unreadable.
+ */
+fun Modifier.glass(color: Color, shape: Shape): Modifier = clip(shape).composed {
+ val sigma = with(LocalDensity.current) { LocalBackdropBlur.current.toPx() }
+ val blur = remember(sigma) { if (sigma > 0f) ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) else null }
+ drawBehind {
+ if (blur == null) {
+ drawRect(color, blendMode = BlendMode.Src)
+ return@drawBehind
+ }
+ drawIntoCanvas { canvas ->
+ // A layer that starts out as the blurred copy of what is under it and is put back
+ // in place of the original, not over it, or the sharp version would show through
+ canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), Replace, blur))
+ canvas.skiaCanvas.restore()
+ }
+ drawRect(color)
+ }
+}
+
+/**
+ * The look every window, panel and menu shares: frosted glass in [shape] with a hairline
+ * border, unless outlines are switched off in the style. One that is [floating] over the rest
+ * of the interface also casts a shadow.
+ */
+fun Modifier.window(color: Color, border: Color, shape: Shape, floating: Boolean = false): Modifier =
+ (if (floating) dropShadow(shape) else this)
+ .glass(color, shape)
+ .composed { if (LocalOutlines.current) Modifier.border(Hairline, border, shape) else Modifier }
+ .consumeClicks()
+
+/**
+ * Casts a soft shadow from the element onto the interface beneath it: it is what separates a
+ * panel from the window it has opened over when both are glass of nearly the same tint.
+ *
+ * The shadow only falls on what the interface has already drawn, never on the bare game. To
+ * the compositor every pixel of the interface is something to frost the game behind and to
+ * glow around, see [com.lambda.gui.render.GuiCompositor], and a shadow lying on the world would
+ * be given both. Nor is anything drawn inside [shape]: the element is glass, and a shadow
+ * underneath it would darken what shows through.
+ *
+ * A [close] shadow is darker and tighter: for the small popups that open over a settings panel,
+ * whose soft shadow would be lost on the panel's dark glass.
+ */
+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) CloseShadowDrop else ShadowDrop).toPx()
+ val blur = (if (close) CloseShadowBlur else ShadowBlur).toPx()
+ val reach = blur * 3
+ val shadow = Paint().apply {
+ color = (if (close) CloseShadowColor else ShadowColor).toArgb()
+ maskFilter = MaskFilter.makeBlur(FilterBlurMode.NORMAL, blur)
+ }
+ onDrawBehind {
+ clipPath(body, ClipOp.Difference) {
+ clipRect(-reach, drop - reach, size.width + reach, size.height + drop + reach) {
+ drawIntoCanvas { canvas ->
+ val skia = canvas.skiaCanvas
+ // A layer that starts out as a stencil of what the interface has drawn here.
+ // The shadow is drawn on a layer of its own and put onto the stencil keeping
+ // only what lies inside it: a shadow cut to the shape of the interface.
+ 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 val ShadowColor = Color.Black.copy(alpha = 0.55f)
+private val ShadowBlur = 5.dp
+private val ShadowDrop = 2.dp
+private val CloseShadowColor = Color.Black.copy(alpha = 0.85f)
+private val CloseShadowBlur = 3.dp
+private val CloseShadowDrop = 2.dp
+
+/**
+ * Turns what has been drawn into its stencil: black wherever there is anything at all. The
+ * gain is the compositor's, so the stencil covers exactly what it treats as interface.
+ */
+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 }
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/snap/Guide.kt b/src/main/kotlin/com/lambda/gui/core/Frames.kt
similarity index 58%
rename from src/main/kotlin/com/lambda/gui/snap/Guide.kt
rename to src/main/kotlin/com/lambda/gui/core/Frames.kt
index 9001658e1..6517a4203 100644
--- a/src/main/kotlin/com/lambda/gui/snap/Guide.kt
+++ b/src/main/kotlin/com/lambda/gui/core/Frames.kt
@@ -15,14 +15,16 @@
* along with this program. If not, see .
*/
-package com.lambda.gui.snap
+package com.lambda.gui.core
-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.withFrameNanos
+
+/**
+ * Waits until [millis] of the interface's own time have passed. That time only runs while the
+ * interface is being drawn, so nothing times out behind a closed screen, and the wait ends on
+ * the thread the interface lives on, which a plain delay would not.
+ */
+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..c66c59806
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/core/GlState.kt
@@ -0,0 +1,188 @@
+/*
+ * 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
+
+/**
+ * Lends the game's OpenGL context to Skia.
+ *
+ * Minecraft tracks the GL state it has set and skips calls it believes are redundant, so anything
+ * Skia changes behind its back has to be put back exactly. [borrow] records the state Skia touches,
+ * gives the block the defaults Skia expects, and restores the recording afterwards.
+ */
+internal object GlState {
+ /** Texture units Minecraft tracks; Skia never binds a unit past these that the game also uses */
+ 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()
+ }
+ }
+
+ /**
+ * Skia uploads textures (its glyph atlas, most visibly) assuming default pixel-store state and
+ * no pixel buffer bound; Minecraft leaves both however its last upload needed them.
+ */
+ fun prepare() {
+ glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0)
+ glBindBuffer(GL_PIXEL_PACK_BUFFER, 0)
+ UNPACK_PARAMETERS.forEachIndexed { index, parameter -> glPixelStorei(parameter, UNPACK_DEFAULTS[index]) }
+ }
+
+ /** Records the current state and returns the function that reinstates it */
+ fun capture(): () -> Unit {
+ val activeTexture = glGetInteger(GL_ACTIVE_TEXTURE)
+ for (unit in 0 until TEXTURE_UNITS) {
+ 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)
+ for (unit in 0 until TEXTURE_UNITS) {
+ 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..910393c8e
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/core/Observe.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.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
+
+/**
+ * Turns anything the client knows into Compose state: a setting, whether a module is enabled,
+ * the player's position.
+ *
+ * None of that is observable, and most of it changes from code that has never heard of the GUI.
+ * So [read] is simply evaluated once per frame, and the caller recomposes only when the result is
+ * not equal to the last one. That keeps the model free of GUI concerns and makes the interface
+ * redraw exactly when something it shows has changed.
+ *
+ * ```
+ * val enabled by observe { module.isEnabled }
+ * ```
+ *
+ * [read] runs on the client thread every frame for as long as the caller is composed, so keep it
+ * to reading: return an immutable value, and copy a collection that is mutated in place.
+ */
+@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
+}
+
+/** [observe] for values that need the player and world; null while there is neither */
+@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()
+ }
+}
+
+/**
+ * The values one part of the interface observes. A part that stays composed while it is not on
+ * screen gets a group of its own, see [Retained], which is then simply not refreshed.
+ */
+internal class Observations {
+ val active = ArrayList>()
+
+ /** Re-reads every observed value. Called once per frame, before composition. */
+ fun refresh() = active.forEach { it.refresh() }
+}
+
+/** The group [observe] adds to */
+internal val LocalObservations = staticCompositionLocalOf { error("observe was called outside the interface") }
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..4498d2bab
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/core/Retained.kt
@@ -0,0 +1,52 @@
+/*
+ * 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
+
+/**
+ * Whether the part of the interface this is read in is on screen. False inside a hidden
+ * [Retained], where a popup has to hold back: it floats above everything, hidden or not.
+ */
+val LocalShown = compositionLocalOf { true }
+
+/**
+ * Keeps [content] composed whether or not it is [shown], so that showing it is a matter of
+ * putting it on the screen rather than of building it, which for the click GUI's hundreds of
+ * rows takes long enough to be felt as a stutter.
+ *
+ * While hidden, the content is neither drawn nor reachable by the pointer, and nothing it
+ * observes is re-read: its observations join [observations], which the owner leaves alone
+ * meanwhile. It costs nothing but the memory it is kept in.
+ */
+@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..5fc77d616
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt
@@ -0,0 +1,164 @@
+/*
+ * 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.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 com.mojang.blaze3d.systems.RenderSystem
+import com.mojang.blaze3d.textures.GpuTexture
+import com.mojang.blaze3d.textures.GpuTextureView
+import com.mojang.blaze3d.textures.TextureFormat
+import kotlinx.coroutines.Dispatchers
+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
+
+/**
+ * A Compose scene that renders into a texture through Skia, on the game's own OpenGL context.
+ *
+ * The scene is retained: [advance] runs composition, animation and layout every frame, which is
+ * cheap when nothing changed, and reports whether any pixel did. Only then does [draw] have to
+ * hand the context to Skia, so an idle interface costs the game nothing but compositing [texture].
+ */
+@OptIn(InternalComposeUiApi::class)
+internal class SceneHost(content: @Composable () -> Unit) : AutoCloseable {
+ val platform = ScenePlatform()
+
+ private val recomposer = FrameRecomposer(Dispatchers.Unconfined)
+ 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
+
+ /** What the scene last drew, premultiplied; null until the first [draw] */
+ val texture: GpuTextureView? get() = target?.view
+
+ /** Brings the scene up to date for this frame and returns whether it has to be drawn again */
+ 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
+ }
+
+ /** Draws the scene. [beforeScene] runs first with Skia in control of the context, to import textures. */
+ fun draw(beforeScene: (DirectContext) -> Unit = {}) {
+ val size = scene.size ?: return
+ GlState.borrow {
+ val skia = skia ?: DirectContext.makeGL().also { skia = it }
+ val target = target?.takeIf { it.size == size } ?: run {
+ target?.close()
+ SkiaTarget(skia, size).also { target = it }
+ }
+ // Everything the game did since the last draw happened behind Skia's back
+ skia.resetGLAll()
+ beforeScene(skia)
+ target.surface.canvas.clear(Color.TRANSPARENT)
+ scene.draw(target.surface.canvas.asComposeCanvas())
+ target.surface.flushAndSubmit()
+ }
+ invalidated = false
+ }
+
+ /** Stops the scene. Its GPU resources are left to die with the context, which is going away too. */
+ override fun close() {
+ scene.close()
+ recomposer.close()
+ }
+}
+
+/**
+ * The texture Skia draws the scene into. The colour texture belongs to the game so its pipelines
+ * can sample it; the framebuffer around it is ours because Skia needs a stencil buffer for clips.
+ */
+private class SkiaTarget(skia: DirectContext, 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 val framebuffer = glGenFramebuffers()
+ private val stencil = glGenRenderbuffers()
+ private val renderTarget: BackendRenderTarget
+ val surface: Surface
+
+ init {
+ 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)
+
+ renderTarget = BackendRenderTarget.makeGL(size.width, size.height, 0, 8, framebuffer, FramebufferFormat.GR_GL_RGBA8)
+ surface = Surface.makeFromBackendRenderTarget(
+ skia, renderTarget, SurfaceOrigin.BOTTOM_LEFT, SurfaceColorFormat.RGBA_8888, ColorSpace.sRGB
+ ) ?: error("Skia rejected the GUI render target")
+ }
+
+ override fun close() {
+ surface.close()
+ renderTarget.close()
+ glDeleteFramebuffers(framebuffer)
+ glDeleteRenderbuffers(stencil)
+ 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..aed8d101f
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt
@@ -0,0 +1,168 @@
+/*
+ * 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.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 java.awt.Component
+import java.awt.event.KeyEvent as AwtKeyEvent
+import org.lwjgl.glfw.GLFW
+
+/**
+ * Translates the game's GLFW input into the pointer and key events a Compose scene consumes.
+ * Positions are in framebuffer pixels, which is the scene's coordinate space.
+ */
+@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()
+ pointer(if (pressed) PointerEventType.Press else PointerEventType.Release, button.toPointerButton(), modifiers)
+ }
+
+ fun scroll(horizontal: Double, vertical: Double) {
+ // GLFW counts a notch away from the user as positive, Compose one towards the user
+ pointer(PointerEventType.Scroll, scroll = Offset(horizontal.toFloat(), -vertical.toFloat()) * LINES_PER_NOTCH)
+ }
+
+ /** Returns whether something in the scene handled the key */
+ fun key(key: Int, pressed: Boolean, modifiers: Int): Boolean =
+ 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 = modifiers and GLFW.GLFW_MOD_SHIFT != 0,
+ )
+ )
+
+ /**
+ * Sends a typed character. Compose's desktop text fields only accept text from an AWT
+ * `KEY_TYPED` event, so one is built to carry the character; it never touches the AWT queue.
+ */
+ 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
+ }
+
+ /** Ends every interaction in progress, for when the scene stops receiving input */
+ fun release() {
+ pressedButtons = 0
+ // The pointer leaves for somewhere off the screen, and before anything is cancelled:
+ // a tooltip only goes once the pointer is outside its element, and the element only
+ // hears of it while it still counts as being under the pointer
+ position = OFF_SCREEN
+ pointer(PointerEventType.Exit)
+ scene.cancelPointerInput()
+ scene.focusManager.releaseFocus()
+ }
+
+ 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 {
+ /** Where the pointer is taken to be once the scene has no input: nowhere any element is */
+ val OFF_SCREEN = Offset(-1e6f, -1e6f)
+
+ /** A desktop scrolls three lines per wheel notch; Compose expects the event to say so */
+ 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
+ }
+
+ /** Compose identifies keys by AWT key code. Letters and digits share theirs with GLFW. */
+ 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_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, GLFW.GLFW_KEY_SPACE -> 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..64b230e8b
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt
@@ -0,0 +1,119 @@
+/*
+ * 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.PlatformTextInputMethodRequest
+import androidx.compose.ui.platform.WindowInfo
+import androidx.compose.ui.text.input.EditCommand
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.ImeOptions
+import androidx.compose.ui.text.input.PlatformTextInputService
+import androidx.compose.ui.text.input.TextFieldValue
+import androidx.compose.ui.unit.DpSize
+import androidx.compose.ui.unit.IntSize
+import androidx.compose.ui.unit.dp
+import com.lambda.Lambda.mc
+import java.awt.datatransfer.DataFlavor
+import java.awt.datatransfer.StringSelection
+import java.awt.datatransfer.Transferable
+import kotlinx.coroutines.awaitCancellation
+import net.minecraft.client.gui.cursor.Cursor
+import net.minecraft.client.gui.cursor.StandardCursors
+
+/**
+ * Stands in for the operating-system window Compose normally lives in: the scene asks it how big
+ * the window is, where text input goes and which cursor to show, and the answers come from the game.
+ */
+@OptIn(InternalComposeUiApi::class, ExperimentalComposeUiApi::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)
+ }
+ /** The cursor the element under the pointer asked for, or null for the default arrow */
+ 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
+ }
+ }
+
+ // Typed characters reach text fields as key events, so neither input path has an IME to drive
+ override suspend fun startInputMethod(request: PlatformTextInputMethodRequest): Nothing = awaitCancellation()
+
+ @Suppress("OVERRIDE_DEPRECATION", "DEPRECATION")
+ override val textInputService = object : PlatformTextInputService {
+ override fun startInput(
+ value: TextFieldValue,
+ imeOptions: ImeOptions,
+ onEditCommand: (List) -> Unit,
+ onImeActionPerformed: (ImeAction) -> Unit,
+ ) = Unit
+
+ override fun stopInput() = Unit
+
+ override fun showSoftwareKeyboard() = Unit
+ override fun hideSoftwareKeyboard() = Unit
+ override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) = Unit
+ }
+}
+
+/** The pointer over an edge that can be dragged up and down. Use it with `Modifier.pointerHoverIcon`. */
+object ResizeVerticalIcon : PointerIcon
+
+/**
+ * Copy and paste through the game's clipboard. Compose's own goes through AWT, which Minecraft
+ * runs headless and so has no clipboard at all.
+ */
+@OptIn(ExperimentalComposeUiApi::class)
+internal object GameClipboard : Clipboard {
+ 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..79aa6711c
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt
@@ -0,0 +1,169 @@
+/*
+ * 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.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+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.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clipToBounds
+import androidx.compose.ui.draw.drawBehind
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.layout
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.unit.Dp
+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.core.observe
+import com.lambda.gui.render.ItemAtlas
+import com.lambda.gui.render.ItemAtlas.drawItem
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+import com.lambda.gui.theme.shadowed
+import com.lambda.gui.theme.toCompose
+import com.lambda.module.HudModule
+import com.lambda.module.ModuleRegistry
+import kotlin.math.roundToInt
+import net.minecraft.item.ItemStack
+
+/** Settings shared by every HUD element, and by the editor that arranges them */
+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 Lambda GUI 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() }
+
+ /**
+ * The elements to draw right now. None outside a world or with the HUD hidden (F1), and none
+ * behind a Minecraft screen unless [HudConfig.showInScreens]; Lambda's own screens always show them.
+ */
+ 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 modules.filter { it.isEnabled }
+ }
+}
+
+/** The shadow under HUD text, as dark as Minecraft's own: the text lies on the world, not on the interface */
+private val HudTextShadow = Color.Black.copy(alpha = 0.75f)
+
+/**
+ * Space between the edge of an element and its content: one pixel of the Minecraft font, the
+ * least that keeps text off the edge of a background and leaves the editor's outline a place.
+ */
+private val ElementPadding = 1.dp
+
+/**
+ * Every enabled HUD element, at its place on the screen. With an [editor] the elements can be
+ * dragged around and right-clicked; without one they are only drawn.
+ */
+@Composable
+internal fun HudLayer(editor: HudEditorState? = null) {
+ val shown by observe { 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() }
+ if (editor != null) DisposableEffect(hud) {
+ onDispose { editor.bounds -= hud }
+ }
+
+ Box(
+ Modifier
+ // The element is measured freely and then placed by its anchor: the fraction of
+ // the room it has to move in, so it stays against the edge it was docked to.
+ // Whatever the anchor or a drag says, all of it stays on the screen: it is measured
+ // no larger than the screen, and placed no further than the room it leaves.
+ .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)
+ // An element with more to show than fits the screen is cut off at its own edge
+ .clipToBounds()
+ .background(background)
+ .padding(ElementPadding)
+ ) {
+ hud.Content()
+ }
+}
+
+/** HUD text: the HUD's colour unless given one, its size, and a shadow to stay readable over the world */
+@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(HudTextShadow))
+}
+
+/**
+ * [stack] as Minecraft draws it in an inventory slot, with its damage bar and stack count.
+ * Draws nothing for an empty stack.
+ *
+ * Minecraft only ever draws an item at a whole multiple of its 16 pixels, which is what keeps
+ * the pixel art crisp. So does this: the icon takes the multiple nearest to [size].
+ */
+@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/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt
new file mode 100644
index 000000000..856b03909
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt
@@ -0,0 +1,412 @@
+/*
+ * 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.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+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.heightIn
+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.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.drawBehind
+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.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.Snap
+import com.lambda.gui.clickgui.Reveal
+import com.lambda.gui.component.Button
+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.ScrollColumn
+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.SettingsList
+import com.lambda.gui.theme.Hairline
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.Radius
+import com.lambda.gui.theme.SoftTextShadow
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+import com.lambda.gui.theme.toCompose
+import com.lambda.module.HudModule
+import kotlin.math.max
+
+/**
+ * What the editor knows while it is open: where the elements are and what is happening to them.
+ *
+ * @param snapping whether a dragged element snaps right now, which changes mid-drag as the snap
+ * key is pressed and let go
+ */
+internal class HudEditorState(snapping: State) {
+ val snapping by snapping
+
+ /** Where every element currently is, in scene pixels: what a dragged element snaps against */
+ val bounds = mutableStateMapOf()
+
+ /** The element being dragged, and where the pointer has taken its top left corner */
+ var dragged by mutableStateOf(null)
+ var draggedTo by mutableStateOf(Offset.Zero)
+
+ /** The context menu that is open: where, and on which element, or null for the empty screen */
+ var menu by mutableStateOf?>(null)
+ private set
+
+ /** How many menus have been opened: each is a menu of its own, which unfolds anew */
+ var menusOpened by mutableStateOf(0)
+ private set
+
+ fun openMenu(position: Offset, hud: HudModule?) {
+ menu = position to hud
+ menusOpened++
+ }
+
+ fun closeMenu() {
+ menu = null
+ }
+
+ /** The config whose settings panel is open: an element's, or the HUD's own */
+ var configuring by mutableStateOf(null)
+ private set
+
+ /** Where the top left corner of that panel is, in scene pixels: where it opened, until it is dragged */
+ var panelPosition by mutableStateOf(Offset.Zero)
+
+ /** What the panel covers of the screen, kept current by the panel itself */
+ var panelBounds = Rect.Zero
+
+ /** Opens the settings of [config] at [position], or near the top of the screen's middle */
+ 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)
+ }
+
+ /** The screen the elements are laid out in: its size in scene pixels, and how many of those make a dp */
+ var screen = Size.Zero
+ var density = Density(1f)
+
+ /**
+ * Where the dragged element belongs: where the pointer took it, snapped if [snapping]. It is
+ * shown there for as long as the drag lasts, overriding its saved anchor, and left there after.
+ */
+ 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, screen, density)
+ else Snap.free(element, screen)
+ }
+
+ fun shownPosition(hud: HudModule) = drop?.position.takeIf { dragged == hud }
+}
+
+/**
+ * The HUD editor: the HUD as it appears in game, with every element draggable. A right click
+ * on an element removes or configures it, and one on the empty screen adds the ones not shown.
+ */
+@Composable
+internal fun HudEditor() {
+ val snapping = observe { Snap.isActive }
+ val editor = remember { HudEditorState(snapping) }
+ editor.screen = LocalWindowInfo.current.containerSize.toSize()
+ editor.density = LocalDensity.current
+
+ // A setting the search points at is shown in the settings of its element
+ val revealedElement = Reveal.module as? HudModule
+ val revealedSetting = Reveal.setting
+ LaunchedEffect(revealedElement, revealedSetting) {
+ if (revealedElement != null && revealedSetting != null) editor.configure(revealedElement)
+ }
+
+ val showSnapLines by observe { GuiConfig.showSnapLines }
+ val snapLineColor by observe { GuiConfig.snapLineColor.toCompose() }
+
+ Box(
+ Modifier
+ .fillMaxSize()
+ // Elements take the presses they handle, so one that arrives here was on the empty screen
+ .onMousePress(PointerButton.Secondary) { editor.openMenu(it, null) }
+ .pointerInput(Unit) {
+ // Seen on the way down, before whatever was pressed: a press off the settings
+ // panel closes it, and then does what it would have done anyway
+ 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)
+ }
+ }
+ }
+ .drawWithContent {
+ val guides = editor.drop?.guides.takeIf { showSnapLines }
+ if (guides != null && editor.snapping) drawGrid()
+ drawContent()
+ if (guides != null) drawGuides(guides, snapLineColor)
+ }
+ ) {
+ HudLayer(editor)
+ // Beside the HUD rather than over all of it, so a change shows on the element as it is made
+ // Still there while it shrinks away after it was closed
+ rememberLast(editor.configuring)?.let { config -> key(config) { SettingsPanel(config, editor.configuring === config, editor) } }
+ }
+
+ // Still there while the menu folds away after it was closed
+ rememberLast(editor.menu)?.let { (position, hud) ->
+ // One menu per right click, so a click elsewhere with a menu open unfolds the new one
+ 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()
+}
+
+/** How the editor is used, told by a menu entry to whoever rests the pointer on it */
+@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) {
+ // New elements appear where the menu was opened
+ 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() }
+}
+
+/**
+ * The settings of [config] in a panel over the editor, which leaves the HUD in view and in
+ * reach: an element can be watched changing, and moved, with its settings open. The panel is
+ * dragged by its title, and stays on the screen.
+ */
+@Composable
+private fun SettingsPanel(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) }
+ // Kept on the screen, wherever it was opened or dragged to
+ 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())
+ // Escape closes the panel before it leaves the editor
+ DisposableEffect(Unit) {
+ LambdaGui.onEscape = { (editor.configuring != null).also { editor.configure(null) } }
+ onDispose { LambdaGui.onEscape = null }
+ }
+
+ // Grows out of its middle and shrinks back into it. By size alone: a fade would draw it
+ // into a layer of its own, with nothing behind the glass for it to blur.
+ val visibility = remember { MutableTransitionState(false) }
+ visibility.targetState = open
+ AnimatedVisibility(
+ visibleState = visibility,
+ modifier = Modifier.offset { position.round() },
+ enter = scaleIn(PanelScale),
+ exit = scaleOut(PanelScale),
+ ) {
+ Column(
+ verticalArrangement = Arrangement.spacedBy(4.dp),
+ modifier = Modifier
+ .onSizeChanged { size = it }
+ .window(colors.panel, colors.border, RoundedCornerShape(Radius.Large), floating = true)
+ // Dragged by any part of it that is not a control: those take their presses first
+ .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)
+ ) {
+ Text("${config.name} Settings", Modifier.fillMaxWidth().padding(horizontal = 4.dp), style = Type.title)
+ ScrollColumn(Modifier.heightIn(max = maxHeight)) {
+ SoftTextShadow { SettingsList(config.settingLayers) }
+ }
+ Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Spacer(Modifier.weight(1f))
+ Button("Reset") { config.resetSettings() }
+ Button("Close") { editor.configure(null) }
+ }
+ }
+ }
+}
+
+private val PanelScale = spring(stiffness = Spring.StiffnessMedium)
+
+/**
+ * Makes a HUD element movable: a left drag moves it and saves where it ends up, a right click
+ * opens its menu. An outline shows how far the element reaches, brighter on the one being moved
+ * and on one the search points at.
+ */
+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 {
+ // Saved as the fraction of the free room, so the element keeps to its edge when the window is resized
+ 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 {
+ // Half of the element's padding, so the outline never touches what it is drawn around
+ val width = Hairline.toPx()
+ drawRect(
+ color = Color.White.copy(alpha = if (editor.dragged == hud || Reveal.module === hud) 0.9f else 0.35f),
+ topLeft = Offset(width / 2, width / 2),
+ size = Size(size.width - width, size.height - width),
+ style = Stroke(width)
+ )
+ }
+
+/** The snapping grid, behind the elements while one of them is being snapped */
+private fun DrawScope.drawGrid() {
+ if (!GuiConfig.snapToGrid) return
+ val step = max(4f, GuiConfig.gridSize.dp.toPx())
+ val color = Color.White.copy(alpha = 0.11f)
+ var x = 0f
+ while (x <= size.width) {
+ drawLine(color, Offset(x, 0f), Offset(x, size.height), Stroke.HairlineWidth)
+ x += step
+ }
+ var y = 0f
+ while (y <= size.height) {
+ drawLine(color, Offset(0f, y), Offset(size.width, y), Stroke.HairlineWidth)
+ y += step
+ }
+}
+
+/** The lines the dragged element has snapped to, a single pixel wide whatever the screen */
+private fun DrawScope.drawGuides(guides: Snap.Guides, color: Color) {
+ 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 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..696c3c3c3
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt
@@ -0,0 +1,211 @@
+/*
+ * 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.heightIn
+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.config.categories.UserAutomationCategory
+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.ScrollColumn
+import com.lambda.gui.component.TextInput
+import com.lambda.gui.component.rememberTexture
+import com.lambda.gui.settings.SettingRow
+import com.lambda.gui.settings.SettingsList
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.SoftTextShadow
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+import com.lambda.module.ModuleRegistry
+import com.lambda.module.ModuleRegistry.moduleNameMap
+import com.lambda.module.modules.client.AutoUpdater
+import com.lambda.util.Diagnostics.gatherDiagnostics
+import net.fabricmc.loader.api.FabricLoader
+import net.minecraft.util.Util
+
+/** Every setting of [config] in a window of its own, for configs that are not a module */
+@Composable
+internal fun ConfigDialog(config: Config, onDismiss: () -> Unit) {
+ val maxHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } * 0.7f
+ Dialog(onDismiss) {
+ Column(Modifier.width(240.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text("${config.name} Settings", Modifier.padding(horizontal = 4.dp), style = Type.title)
+ 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") {
+ // Modules following the config go back to their own before it disappears
+ config.linkedModules.value.forEach { name ->
+ moduleNameMap[name]?.let { it.automationConfig = it.defaultAutomationConfig }
+ }
+ UserAutomationCategory.configs.remove(config)
+ onDismiss()
+ }
+ }
+ Spacer(Modifier.weight(1f))
+ Button("Reset") { config.resetSettings() }
+ Button("Done", onClick = onDismiss)
+ }
+ }
+ }
+}
+
+@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)
+ }
+ }
+ }
+}
+
+/** Asks before the auto updater swaps the jar: it restarts the game, so it is never done unprompted */
+@Composable
+internal fun LoaderPromptDialog(prompt: AutoUpdater.Prompt) {
+ 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..80f4c25f6
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt
@@ -0,0 +1,384 @@
+/*
+ * 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.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.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.widthIn
+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.graphics.RectangleShape
+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.platform.LocalFocusManager
+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.ClickGuiCategories
+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.consumeClicks
+import com.lambda.gui.component.glass
+import com.lambda.gui.component.TextInput
+import com.lambda.gui.component.hoverHighlight
+import com.lambda.gui.component.mouseClickable
+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.Text
+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 java.nio.file.Path
+import java.util.Locale
+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
+
+internal val MenuBarHeight = 15.dp
+
+/**
+ * The strip across the top of the click GUI. Everything that is not a module is in one of its
+ * menus, and its search field finds modules and settings and shows where they are.
+ */
+@Composable
+internal fun MenuBar(modifier: Modifier = Modifier) {
+ val colors = LambdaTheme.colors
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = modifier
+ .fillMaxWidth()
+ .height(MenuBarHeight)
+ // Glass like a window, but running from edge to edge it needs no outline
+ .glass(colors.surface, RectangleShape)
+ .consumeClicks()
+ ) {
+ Row(Modifier.align(Alignment.CenterStart).fillMaxHeight(), verticalAlignment = Alignment.CenterVertically) {
+ BarMenu("Lambda") { LambdaMenu() }
+ BarMenu("Modules") { ModulesMenu() }
+ BarMenu("Automation") { AutomationMenu() }
+ BarMenu("Minecraft") { MinecraftMenu() }
+ BarMenu("Help") { HelpMenu() }
+ }
+ SearchField()
+ }
+}
+
+/** An entry of the bar that drops a menu down underneath itself */
+@Composable
+private fun BarMenu(label: String, content: @Composable ColumnScope.() -> Unit) {
+ val menu = remember { MenuState() }
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .fillMaxHeight()
+ .hoverHighlight(LambdaTheme.colors.header)
+ .mouseClickable(onClick = menu::toggle)
+ .padding(horizontal = 6.dp)
+ ) {
+ Text(label, maxLines = 1)
+ Menu(menu.isOpen, onDismiss = menu::dismiss, content = content)
+ }
+}
+
+/**
+ * The search field of the bar. Results drop down under it as the query is typed; Enter takes
+ * the first, a click any, and Escape empties the field.
+ */
+@Composable
+private fun SearchField(modifier: Modifier = Modifier) {
+ val focus = LocalFocusManager.current
+ var query by remember { mutableStateOf("") }
+ // The results can be put away with a click elsewhere, and come back with the next keystroke
+ var listed by remember { mutableStateOf(false) }
+ val results = remember(query) { Search.find(query.trim()) }
+
+ 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.Enter -> {
+ results.firstOrNull()?.let(::choose)
+ true
+ }
+ // An empty field lets Escape through, to close the click GUI as it does anywhere else
+ event.key == Key.Escape && query.isNotEmpty() -> {
+ query = ""
+ listed = false
+ true
+ }
+ else -> false
+ }
+ }
+ ) {
+ TextInput(
+ value = query,
+ onValueChange = {
+ query = it
+ listed = true
+ },
+ modifier = Modifier.width(SearchWidth),
+ placeholder = "Search modules and settings",
+ )
+ if (listed && query.isNotBlank()) Suggestions(onDismiss = { listed = false }) {
+ if (results.isEmpty()) MenuLabel("Nothing found")
+ results.forEach { result -> ResultRow(result) { choose(result) } }
+ }
+ }
+}
+
+@Composable
+private fun ResultRow(result: Search.Result, onClick: () -> Unit) {
+ val colors = LambdaTheme.colors
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .widthIn(min = SearchWidth)
+ .hoverHighlight(colors.header)
+ .mouseClickable(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)
+ }
+}
+
+private val SearchWidth = 150.dp
+
+@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() }
+}
+
+/** Which categories have a window, and which modules are listed in them */
+@Composable
+private fun ModulesMenu() {
+ Submenu("Shown Categories") {
+ ClickGuiCategories.forEach { tag ->
+ val shown by observe { ModuleTag.isTagShown(tag) }
+ MenuItem(tag.name, checked = shown) { ModuleTag.toggleTag(tag) }
+ }
+ }
+ MenuDivider()
+ ClickGuiCategories.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..761a5dd10
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt
@@ -0,0 +1,117 @@
+/*
+ * 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.clickgui.Reveal
+import com.lambda.module.HudModule
+import com.lambda.module.Module
+import com.lambda.module.ModuleRegistry
+import com.lambda.util.StringUtils.capitalize
+import com.lambda.util.StringUtils.levenshteinDistance
+import net.minecraft.client.gui.screen.ChatScreen
+
+/**
+ * Finds modules, settings and commands by name. Choosing a result does not change anything:
+ * a module or a setting is shown where it lives, see [Reveal], and a command is put into chat.
+ */
+internal object Search {
+ sealed interface Result {
+ val name: String
+
+ /** Where the result comes from, shown beside its name */
+ 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) : Result {
+ override val name get() = setting.name
+ override val origin = (listOf(config.name) + setting.getConfigCommandPath()).dropLast(1).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
+
+ // Results of a kind rank together, so a module is never buried under settings that share its name
+ private const val MODULE_BONUS = 300
+ private const val HUD_MODULE_BONUS = 270
+ private const val COMMAND_BONUS = 200
+
+ /** The best matches for [query], strict ones if there are any and fuzzier ones otherwise */
+ 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)
+ }
+
+ ModuleRegistry.modules.forEach { module ->
+ 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 ->
+ config.settingLayers.forEachEntry { _, single ->
+ val setting = single.entry
+ if (setting.visibility()) consider({ Result.OfSetting(setting, config) }, 0, setting.name)
+ }
+ }
+ }
+ }
+
+ /** How well [target] matches [query], from 200 for the same word down to 0 for no match */
+ 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
+
+ // Not contained: allow a few typos, more of them in a longer query
+ 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..5cfe00757
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt
@@ -0,0 +1,128 @@
+/*
+ * 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 java.util.OptionalInt
+import kotlin.math.ceil
+import kotlin.math.log2
+import org.lwjgl.system.MemoryStack
+
+/**
+ * A dual Kawase blur.
+ *
+ * Instead of sampling a wide kernel at full resolution, the image is halved a few times and then
+ * doubled back up, each step a handful of bilinear taps. Every level costs a quarter of the one
+ * before it, so the whole blur is cheaper than a single full resolution pass and its cost barely
+ * grows with the radius: a larger radius just adds a smaller level.
+ *
+ * The result is left at half the source resolution. A blur has no detail a full resolution copy
+ * would show, and skipping the last upsample avoids the one pass that touches every pixel.
+ */
+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
+
+ /** Blurs [source], which is [width] by [height], by about [radius] pixels */
+ fun blur(source: GpuTextureView, width: Int, height: Int, radius: Float): GpuTextureView {
+ resize(width, height)
+ // Each level doubles the reach of the one above; the spread covers what is left over
+ 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
+ for (index in 0 until depth) {
+ pass(LambdaRenderPipelines.GUI_BLUR_DOWN, input, levels[index].view)
+ input = levels[index].view
+ }
+ for (index in depth - 2 downTo 0) {
+ 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 {
+ /** Deep enough for a radius of over a hundred pixels */
+ const val MAX_DEPTH = 6
+
+ /** Past two texels the taps stop overlapping and the blur breaks up into copies */
+ const val MIN_SPREAD = 0.5f
+ const val MAX_SPREAD = 2f
+
+ /** A lone float, padded to the 16 bytes a std140 block rounds up to */
+ 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..5fbe357f7
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt
@@ -0,0 +1,129 @@
+/*
+ * 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 java.awt.Color
+import java.util.OptionalInt
+import org.lwjgl.system.MemoryStack
+
+/**
+ * Puts the GUI texture on screen, in one pass over the game's framebuffer.
+ *
+ * The effects live here rather than in the GUI's own drawing so that they cost nothing the GUI
+ * has to redraw for: the game behind a frosted window changes every frame, but the window does
+ * not, and the glow only depends on the GUI's silhouette, so its blur is reused until that changes.
+ */
+internal object GuiCompositor {
+ /**
+ * @property frost blur radius, in pixels, of the game behind the GUI; zero for none
+ * @property glow blur radius, in pixels, of the glow around the GUI; zero for none
+ */
+ 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,
+ ) {
+ 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
+
+ // std140 rounds a block up to a multiple of its largest member, the 16 byte vec4
+ private val uniformSize = Std140SizeCalculator().putVec4().putVec4().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()
+ )
+ }
+
+ /**
+ * Draws [gui] over the game.
+ *
+ * @param guiChanged whether [gui] was redrawn since the last call
+ */
+ 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) {
+ haloView = null
+ RenderSystem.getDevice().createCommandEncoder()
+ .createRenderPass({ "Lambda GUI" }, screen, OptionalInt.empty())
+ .use { pass ->
+ pass.setPipeline(LambdaRenderPipelines.GUI_BLIT)
+ pass.bindTexture("InSampler", gui, nearest)
+ pass.draw(0, 3)
+ }
+ return
+ }
+
+ 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)
+ }
+ }
+
+ 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)
+ .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)
+
+ /** The glow's colour wave repeats every pi seconds; wrapping on a multiple keeps it seamless */
+ 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..e62421d96
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt
@@ -0,0 +1,255 @@
+/*
+ * 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 kotlin.math.ceil
+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
+
+/**
+ * Item stacks for the GUI, drawn by Minecraft exactly as it draws them in an inventory slot:
+ * the model with its trims, dyes and glint, and over it the damage bar, the stack count and
+ * the cooldown sweep.
+ *
+ * Nothing about an item is drawn by Lambda. Every icon on screen owns a [Slot] in one strip of
+ * cells, the stacks are handed to a [DrawContext] the way a screen would, and a [GuiRenderer] of
+ * our own renders what that recorded into the strip's framebuffer instead of the window (see
+ * `GuiRendererMixin`). [import] then copies the strip into the Skia [image] the icons draw from.
+ * Both only happen when something about a stack changed.
+ */
+object ItemAtlas {
+ /** A cell in the atlas. Set [stack] and [size] to say what it should hold. */
+ class Slot {
+ var stack: ItemStack = ItemStack.EMPTY
+
+ /** Edge length the icon is drawn at, in pixels: a multiple of [ITEM] to come out pixel for pixel */
+ var size = 0
+
+ /** The stack as it was last rendered, a copy because the live one mutates */
+ internal var rendered: ItemStack = ItemStack.EMPTY
+ }
+
+ /**
+ * The framebuffer the GUI renderer has to draw into in place of the window, set for as long
+ * as the atlas is being rendered. [scale] is the GUI scale it renders at meanwhile.
+ */
+ @JvmStatic
+ var target: Framebuffer? = null
+ private set
+
+ /**
+ * The GUI scale the items are rendered at, a whole number as Minecraft's own always is:
+ * the first that covers the largest icon. Smaller icons are scaled down from it.
+ */
+ @JvmStatic
+ var scale = 1
+ private set
+
+ private val slots = ArrayList()
+ private var strip: Strip? = null
+ private var pendingImport = 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()
+ )
+ }
+
+ /** What decides how each item's model looks, as of the last render: see [render] */
+ private var renderedModels = emptyList()
+ private var renderedAt = 0L
+
+ /** The strip. A new instance every time the items were rendered, so reading it redraws the reader. */
+ private var image: Image? by mutableStateOf(null, neverEqualPolicy())
+
+ fun add(slot: Slot) {
+ slots += slot
+ }
+
+ fun remove(slot: Slot) {
+ slots -= slot
+ }
+
+ /** Draws [slot]'s item over the scope, its count hanging over the corner as it does over a slot's */
+ 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
+ )
+ }
+ }
+
+ /** Renders the items if any changed. Returns whether [import] has something new to pick up. */
+ 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
+
+ // Recorded every frame, as the game records its own slots. It costs next to nothing and
+ // is the only way to learn that a compass turned or a bow was drawn: only the model knows.
+ 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 = scale != this.scale || models != renderedModels ||
+ slots.any { !ItemStack.areEqual(it.stack, it.rendered) }
+ // What moves by itself, a glint or a cooldown, is redrawn at a steady rate instead of on
+ // every frame. It looks no different, and at a high frame rate costs a fraction.
+ 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
+ renderedModels = models
+ slots.forEach { it.rendered = it.stack.copy() }
+ draw(strip.framebuffer)
+ pendingImport = true
+ return true
+ }
+
+ /** Copies what [render] drew into [image]. Runs while Skia holds the GL context. */
+ fun import(skia: DirectContext) {
+ if (!pendingImport) return
+ pendingImport = false
+ val previous = image
+ image = strip?.snapshot(skia)
+ // Safe at once: anything Skia recorded with the old strip holds its own reference to it
+ previous?.close()
+ }
+
+ /** Has the GUI renderer draw what [context] recorded into [framebuffer] */
+ 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 {
+ // A frame of its own each time, or the renderer would keep showing the glint it cached
+ renderer.incrementFrame()
+ renderer.render(mc.gameRenderer.fogRenderer.getFogBuffer(FogRenderer.FogType.NONE))
+ } finally {
+ target = null
+ if (projection != null) RenderSystem.setProjectionMatrix(projection, projectionType)
+ }
+ }
+
+ /** The framebuffer the items are rendered into, and the Skia surface wrapped around it to copy them out */
+ private class Strip(val width: Int, val height: Int) : AutoCloseable {
+ val framebuffer = SimpleFramebuffer("Lambda GUI items", width, height, true)
+
+ // Resolved now, as game rendering, so no framebuffer object is created once Skia has the context
+ 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
+ // The game drew into the framebuffer behind Skia's back; without this the
+ // snapshot Skia cached the first time would be handed out forever
+ surface.notifyContentWillChange(ContentChangeMode.DISCARD)
+ return surface.makeImageSnapshot()
+ }
+
+ override fun close() {
+ surface?.close()
+ renderTarget?.close()
+ framebuffer.delete()
+ }
+ }
+
+ /** Nanoseconds between two renders of items that animate: 75 a second, enough for any shimmer */
+ private const val ANIMATION_INTERVAL = 1_000_000_000L / 75
+
+ /** Edge length of an item, in the units Minecraft lays its GUI out in */
+ const val ITEM = 16
+
+ /** Edge length of a cell: an item, and the two units a stack count's shadow reaches past it */
+ 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..b4602bdf5
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.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.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.Ellipsis
+import com.lambda.gui.component.Chip
+import com.lambda.gui.component.Dialog
+import com.lambda.gui.component.RowHeight
+import com.lambda.gui.component.Scrollbar
+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.hud.ItemIcon
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.Radius
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+import net.minecraft.item.ItemStack
+import net.minecraft.registry.Registries
+
+/**
+ * A collection setting: its name and, on a chip, how much of it is selected. The chip opens the
+ * editor in a window of its own, as the lists it holds would never fit into a row.
+ */
+@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", maxLines = 1)
+ Ellipsis()
+ }
+ }
+ if (editing) CollectionWindow(setting) { editing = false }
+}
+
+/**
+ * Two lists side by side, what can be selected and what is. Clicking an entry moves it across,
+ * and the search narrows both.
+ */
+@Composable
+private fun CollectionWindow(setting: CollectionSetting, onDismiss: () -> Unit) {
+ // Selections are edited in place, so a copy is what tells one frame's selection from the next
+ 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(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) }
+ }
+ }
+ }
+}
+
+/**
+ * A setting that is one block: its name and, on a chip, the block with its icon. The chip opens
+ * a window listing every block, where clicking one picks 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(IconSize)) { ItemIcon(ItemStack(block.asItem()), IconSize) }
+ Text(BlockSerializer.stringify(block), 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
+ }
+ }
+ }
+}
+
+/** One of the things a collection can hold, with what it is shown as */
+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)
+ // Lazy, because a list of every block or item in the game runs to over a thousand rows
+ val list = rememberLazyListState()
+ Box(Modifier.fillMaxSize().clip(RoundedCornerShape(Radius.Small)).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 = RowHeight)
+ .hoverHighlight(colors.controlSelected)
+ .mouseClickable { onClick(entry.item) }
+ .padding(horizontal = 4.dp)
+ ) {
+ // A slot of the same width for every entry, even one with nothing in it, so the names line up
+ if (entry.icon != null) Box(Modifier.size(IconSize)) { ItemIcon(entry.icon, IconSize) }
+ Text(entry.label, color = colors.onControl, maxLines = 1)
+ }
+ }
+ }
+ if (list.canScrollForward || list.canScrollBackward) Scrollbar(rememberScrollbarAdapter(list), Modifier.matchParentSize())
+ }
+ }
+}
+
+/** Edge length of an entry's icon: the 16 pixels Minecraft draws an item at, at 1080p */
+private val IconSize = 8.dp
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..5d9f3ad94
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.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.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.heightIn
+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.NumberInput
+import com.lambda.gui.component.MenuState
+import com.lambda.gui.component.Popout
+import com.lambda.gui.component.RowHeight
+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.Radius
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+import com.lambda.gui.theme.toCompose
+import java.awt.Color as AwtColor
+import kotlin.math.roundToInt
+
+/**
+ * A colour setting: its name and a swatch, which opens a picker beside the row when clicked.
+ * The picker works in hue, saturation and brightness, and offers the channels and a hex code
+ * to type.
+ */
+@Composable
+internal fun ColorPicker(setting: ColorSetting) {
+ val color by observe { setting.value }
+ // Kept like a menu's, so clicking the row again shuts the picker it opened
+ 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(Radius.ExtraSmall))
+ .drawBehind {
+ drawCheckerboard()
+ drawRect(color.toCompose())
+ }
+ )
+ Popout(picker.isOpen, onDismiss = picker::dismiss) {
+ Column(Modifier.width(PickerWidth)) { Picker(color) { setting.value = it } }
+ }
+ }
+ }
+}
+
+private val PickerWidth = 130.dp
+
+@Composable
+private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) {
+ val colors = LambdaTheme.colors
+
+ // Hue and saturation are kept here, because the colour alone forgets them: every grey has
+ // no hue and black has no saturation, and the picker should not jump when dragged there.
+ 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
+ if (AwtColor.HSBtoRGB(hsb[0], hsb[1], hsb[2]) and 0xFFFFFF != 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)) {
+ // Saturation across, brightness up
+ Spacer(
+ Modifier
+ .fillMaxWidth()
+ .aspectRatio(1.4f)
+ .clip(RoundedCornerShape(Radius.ExtraSmall))
+ .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)
+ }
+ }
+}
+
+/** A horizontal strip painted by [background], with a thumb at [fraction] that drags along it */
+@Composable
+private fun Bar(fraction: Float, onChange: (Float) -> Unit, background: DrawScope.() -> Unit) {
+ Spacer(
+ Modifier
+ .fillMaxWidth()
+ .height(10.dp)
+ .clip(RoundedCornerShape(Radius.ExtraSmall))
+ .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, { onChange(it.roundToInt().coerceIn(0, 255)) }, Modifier.fillMaxWidth())
+ }
+}
+
+/** The grey chequers a translucent colour is shown over */
+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)
+
+/** Reads "#RRGGBB" or "#RRGGBBAA", with or without the hash */
+private fun parseHex(text: String): AwtColor? {
+ val digits = text.removePrefix("#")
+ if (digits.length != 6 && digits.length != 8) 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 })
+}
+
+private val HUES = (0..6).map { Color.hsv(it * 60f % 360f, 1f, 1f) }
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..41b0e2cac
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt
@@ -0,0 +1,374 @@
+/*
+ * 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.animateFloatAsState
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.ExperimentalFoundationApi
+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.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.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.CompositionLocalProvider
+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.composed
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.drawBehind
+import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+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.Lambda.mc
+import com.lambda.config.entries.Setting
+import com.lambda.config.settings.CharSetting
+import com.lambda.config.settings.FunctionSetting
+import com.lambda.config.settings.NumericSetting
+import com.lambda.config.settings.StringSetting
+import com.lambda.config.settings.collections.CollectionSetting
+import com.lambda.config.settings.comparable.BooleanSetting
+import com.lambda.config.settings.comparable.EnumSetting
+import com.lambda.config.settings.complex.BlockPosSetting
+import com.lambda.config.settings.complex.BlockSetting
+import com.lambda.config.settings.complex.ColorSetting
+import com.lambda.config.settings.complex.KeybindSetting
+import com.lambda.config.settings.complex.Vec3dSetting
+import com.lambda.gui.GuiScreen
+import com.lambda.gui.clickgui.Reveal
+import com.lambda.gui.component.Button
+import com.lambda.gui.component.Checkmark
+import com.lambda.gui.component.Dropdown
+import com.lambda.gui.component.LocalClickOnRelease
+import com.lambda.gui.component.NumberInput
+import com.lambda.gui.component.RowHeight
+import com.lambda.gui.component.TextInput
+import com.lambda.gui.component.Tooltip
+import com.lambda.gui.component.hoverHighlight
+import com.lambda.gui.component.mouseClickable
+import com.lambda.gui.component.scrubbable
+import com.lambda.gui.core.awaitFrames
+import com.lambda.gui.core.observe
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.Radius
+import com.lambda.gui.theme.Text
+import com.lambda.util.BlockUtils.blockPos
+import com.lambda.util.CommunicationUtils.info
+import com.lambda.util.extension.displayValue
+import com.lambda.util.world.raycast.RayCastUtils.blockResult
+import kotlin.math.roundToInt
+import kotlin.math.roundToLong
+import net.minecraft.util.math.BlockPos
+import net.minecraft.util.math.Vec3d
+
+/**
+ * The editor for one setting, whatever its type. The description is its tooltip. A right click
+ * does nothing to a setting: in this interface it only ever opens and closes things.
+ *
+ * Every editor is one row tall, so a list of settings reads as a list, and each kind looks
+ * unlike the others, so it is plain at a glance what a row is: a tick box, a bar that fills,
+ * a chip with an arrow, a key cap, a swatch, a field to type in. Editors that need more room
+ * than a row open over the interface instead of pushing the rows below apart.
+ *
+ * Nothing is drawn around or between them. The row under the pointer is lit, which shows
+ * how far it reaches and which value belongs to which name.
+ *
+ * Settings without an editor here (a block, a map) can only be changed with the config command.
+ */
+@OptIn(ExperimentalFoundationApi::class)
+@Composable
+fun SettingRow(setting: Setting<*>) {
+ val disabled by observe { setting.disabled() }
+
+ // Lit and scrolled to while it is what the search points at, once the tab has turned to it
+ // and the groups around it have unfolded
+ 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)
+ // Over what the row holds: a slider fills its row and would hide a light behind it
+ .drawWithContent {
+ drawContent()
+ drawRect(lit)
+ }
+ .enabled(!disabled)
+ ) {
+ // A setting is changed when the button is let go, so a slip of the hand can be taken back
+ CompositionLocalProvider(LocalClickOnRelease provides true) {
+ when (setting) {
+ is BooleanSetting -> Toggle(setting)
+ is NumericSetting<*> -> Slider(setting)
+ is EnumSetting<*> -> EnumDropdown(setting)
+ is StringSetting -> TextField(setting)
+ is CharSetting -> CharField(setting)
+ is ColorSetting -> ColorPicker(setting)
+ is KeybindSetting -> KeybindButton(setting)
+ is FunctionSetting<*, *> -> Button(setting.name, Modifier.fillMaxWidth().height(RowHeight)) { setting.value() }
+ is CollectionSetting<*> -> CollectionButton(setting)
+ is BlockSetting -> BlockPicker(setting)
+ is BlockPosSetting -> BlockPosFields(setting)
+ is Vec3dSetting -> Vec3dFields(setting)
+ }
+ }
+ }
+ }
+}
+
+/**
+ * The room a setting takes in a list: the width of the panel, lit while the pointer is on it.
+ * For what is listed among settings without being one, too.
+ */
+internal fun Modifier.settingCell(): Modifier = composed {
+ fillMaxWidth()
+ .padding(vertical = 0.5.dp)
+ .clip(RoundedCornerShape(Radius.Small))
+ .hoverHighlight(LambdaTheme.colors.hover)
+}
+
+/** How long a tab takes to turn and a group to unfold, before a setting in them is where it will stay */
+private const val SETTLE_MILLIS = 250L
+
+/** Dims the element and keeps the pointer from reaching it while not [enabled] */
+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() }
+ }
+ }
+
+/** The shape most settings share: the [name], and at the end of the row whatever edits the value */
+@Composable
+internal fun Labeled(name: String, modifier: Modifier = Modifier, editor: @Composable RowScope.() -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(3.dp),
+ modifier = modifier.fillMaxWidth().heightIn(min = RowHeight).padding(start = 3.dp)
+ ) {
+ Text(name, Modifier.weight(1f), maxLines = 1)
+ editor()
+ }
+}
+
+@Composable
+private fun Toggle(setting: BooleanSetting) {
+ val checked by observe { setting.value }
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(3.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .heightIn(min = RowHeight)
+ .mouseClickable { setting.value = !setting.value }
+ .padding(horizontal = 3.dp)
+ ) {
+ Checkmark(checked)
+ Text(setting.name, maxLines = 1)
+ }
+}
+
+/**
+ * A bar filled up to the value. Dragging anywhere on it sets the value; clicking the number
+ * swaps the bar for a text field to type an exact one, for ranges with more steps than pixels.
+ */
+@Composable
+private fun Slider(setting: NumericSetting) where T : Number, T : Comparable {
+ val colors = LambdaTheme.colors
+ val value by observe { setting.value }
+ val label by observe { setting.toString() }
+ var typing by remember { mutableStateOf(false) }
+
+ if (typing) {
+ NumberInput(value, { setting.value = setting.convert(it) }, Modifier.fillMaxWidth(), focused = true) {
+ typing = false
+ }
+ return
+ }
+
+ val min = setting.range.start.toDouble()
+ val max = setting.range.endInclusive.toDouble()
+ // The value moves in steps; the bar glides from one to the next
+ val fraction by animateFloatAsState(((value.toDouble() - min) / (max - min)).toFloat().coerceIn(0f, 1f))
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .heightIn(min = RowHeight)
+ .clip(RoundedCornerShape(Radius.Small))
+ .background(colors.track)
+ .drawBehind { drawRect(colors.primary, size = Size(size.width * fraction, size.height)) }
+ .scrubbable { position, size ->
+ val steps = ((position.x / size.width).coerceIn(0f, 1f) * (max - min) / setting.step.toDouble()).roundToLong()
+ setting.value = setting.convert(min + steps * setting.step.toDouble())
+ }
+ .padding(horizontal = 3.dp)
+ ) {
+ Text(setting.name, Modifier.weight(1f), colors.onControl)
+ Text(label, Modifier.mouseClickable { typing = true }, colors.onControl, maxLines = 1)
+ }
+}
+
+/** A double as the setting's own number type; the setting clamps it to its range */
+@Suppress("UNCHECKED_CAST")
+private fun NumericSetting.convert(number: Double): T where T : Number, T : Comparable =
+ when (value) {
+ is Int -> number.roundToInt()
+ is Long -> number.roundToLong()
+ is Float -> number.toFloat()
+ else -> number
+ } as T
+
+@Composable
+private fun > EnumDropdown(setting: EnumSetting) {
+ val selected by observe { setting.value }
+ Dropdown(
+ label = setting.name,
+ options = selected.declaringJavaClass.enumConstants.asList(),
+ selected = selected,
+ optionLabel = { it.displayValue },
+ modifier = Modifier.padding(start = 3.dp),
+ ) { setting.value = it }
+}
+
+@Composable
+private fun TextField(setting: StringSetting) {
+ val value by observe { setting.value }
+ // Text that runs over several lines is the one editor that cannot keep to a row
+ if (setting.multiline) Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ Text(setting.name, Modifier.padding(start = 3.dp, top = 1.dp))
+ TextInput(value, { setting.value = it }, Modifier.fillMaxWidth(), singleLine = false)
+ }
+ else Labeled(setting.name) {
+ TextInput(value, { setting.value = it }, Modifier.width(TextFieldWidth))
+ }
+}
+
+@Composable
+private fun CharField(setting: CharSetting) {
+ val value by observe { setting.value }
+ Labeled(setting.name) {
+ // The field holds a single character: whatever is typed last replaces it
+ TextInput(value.toString(), { text -> text.lastOrNull()?.let { setting.value = it } }, Modifier.width(18.dp))
+ }
+}
+
+/**
+ * Shows the bind as the cap of a key and, once clicked, records the next key or mouse button as
+ * the new one. The recording itself happens in [GuiScreen], which sees the raw input before the
+ * interface does.
+ */
+@Composable
+private fun KeybindButton(setting: KeybindSetting) {
+ val colors = LambdaTheme.colors
+ val bind by observe { setting.value }
+ var recording by remember { mutableStateOf(false) }
+ DisposableEffect(Unit) {
+ onDispose { if (recording) GuiScreen.keybindRecorder = null }
+ }
+
+ Labeled(setting.name) {
+ Tooltip("Click, then press a key or mouse button. Backspace unbinds, Escape cancels.") {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .height(RowHeight)
+ .clip(RoundedCornerShape(Radius.Small))
+ .background(if (recording) colors.primary else colors.track)
+ .mouseClickable {
+ recording = true
+ GuiScreen.keybindRecorder = { recorded ->
+ recorded?.let { setting.value = it }
+ recording = false
+ }
+ }
+ .padding(horizontal = 4.dp)
+ ) {
+ Text(
+ text = if (recording) "Press a key" else bind.name,
+ color = if (recording) colors.onPrimary else colors.onSurface,
+ maxLines = 1,
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun BlockPosFields(setting: BlockPosSetting) {
+ val value by observe { setting.value.toImmutable() }
+ Labeled(setting.name) {
+ NumberInput(value.x, { setting.value = BlockPos(it.roundToInt(), value.y, value.z) }, Modifier.width(NumberFieldWidth))
+ NumberInput(value.y, { setting.value = BlockPos(value.x, it.roundToInt(), value.z) }, Modifier.width(NumberFieldWidth))
+ NumberInput(value.z, { setting.value = BlockPos(value.x, value.y, it.roundToInt()) }, Modifier.width(NumberFieldWidth))
+ Tooltip("Use the block you are looking at") {
+ Button("Target", Modifier.height(RowHeight)) {
+ mc.crosshairTarget?.blockResult?.blockPos?.let { setting.value = it }
+ ?: setting.info("No block under crosshair")
+ }
+ }
+ }
+}
+
+@Composable
+private fun Vec3dFields(setting: Vec3dSetting) {
+ val value by observe { setting.value }
+ Labeled(setting.name) {
+ NumberInput(value.x, { setting.value = Vec3d(it, value.y, value.z) }, Modifier.width(NumberFieldWidth))
+ NumberInput(value.y, { setting.value = Vec3d(value.x, it, value.z) }, Modifier.width(NumberFieldWidth))
+ NumberInput(value.z, { setting.value = Vec3d(value.x, value.y, it) }, Modifier.width(NumberFieldWidth))
+ }
+}
+
+/** Width of the field a line of text is typed into, beside its name */
+private val TextFieldWidth = 90.dp
+
+/** Width of each field of a position; longer numbers scroll inside it */
+private val NumberFieldWidth = 34.dp
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..bf554dd71
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt
@@ -0,0 +1,204 @@
+/*
+ * 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.animateColorAsState
+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.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.wrapContentWidth
+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.graphics.Color
+import androidx.compose.ui.layout.layout
+import androidx.compose.ui.unit.IntOffset
+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.gui.clickgui.Reveal
+import com.lambda.gui.component.Expandable
+import com.lambda.gui.component.Section
+import com.lambda.gui.component.mouseClickable
+import com.lambda.gui.core.observe
+import com.lambda.gui.theme.LambdaTheme
+import com.lambda.gui.theme.Radius
+import com.lambda.gui.theme.Text
+import com.lambda.gui.theme.Type
+
+/**
+ * The settings of a config as they are organised in code: tabs become a strip that swaps the
+ * page under it, groups become collapsible sections, and a setting appears only while it is
+ * visible. A group is nested under its heading, a tab's page framed under its tab.
+ */
+@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()) {
+ // Whatever is not in a tab is shown above the tabs, whichever one is selected
+ 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) }
+
+/**
+ * Tabs over the page of whichever one is chosen. The names wrap onto as many lines as they
+ * need, as splitting the width evenly would squeeze long ones in a narrow panel.
+ *
+ * The tabs decide everything that is shown under them, so they are the strongest thing in a
+ * panel: a band across its width, with the chosen tab filled in the colour of a window's header.
+ * Changing tabs slides the new page in from the side its tab is on while the page grows or
+ * shrinks to fit in height; in width the pages are kept alike.
+ */
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun Tabs(tabs: List>>) {
+ val colors = LambdaTheme.colors
+ val shown by observe { tabs.filter { it.hasVisibleSettings() } }
+ if (shown.isEmpty()) return
+ var selectedName by remember { mutableStateOf(shown.first().name) }
+ // The selection can stop having anything visible in it
+ val selected = shown.firstOrNull { it.name == selectedName } ?: shown.first()
+ // A setting the search points at is on one of the pages: that one is turned to
+ val revealed = Reveal.setting
+ LaunchedEffect(revealed) {
+ if (revealed != null) shown.firstOrNull { it.holds(revealed) }?.let { selectedName = it.name }
+ }
+ // How wide each page wanted to be when it was last shown. Every page is given the width of
+ // the widest, so changing tabs does not change the width of the panel, while a page that
+ // gets narrower, a group in it having been folded away, lets the panel shrink again.
+ val widths = remember { HashMap() }
+
+ Column(Modifier.fillMaxWidth().padding(top = 1.dp)) {
+ val shape = RoundedCornerShape(Radius.Small)
+ FlowRow(Modifier.fillMaxWidth().clip(shape).background(colors.raised)) {
+ shown.forEach { tab ->
+ val isSelected = tab === selected
+ // Filled like an enabled module: the same bright, see-through crimson for "this one is on"
+ val fill by animateColorAsState(if (isSelected) colors.moduleEnabled else Color.Transparent, tween(TAB_MILLIS))
+ Text(
+ text = tab.name,
+ color = if (isSelected) colors.onModuleEnabled else colors.onSurfaceVariant,
+ maxLines = 1,
+ softWrap = false,
+ modifier = Modifier
+ // The only tab left, the others having nothing to show, takes the whole
+ // strip: a heading over one page rather than a choice of one
+ .then(if (shown.size == 1) Modifier.fillMaxWidth() else Modifier)
+ .clip(shape)
+ .background(fill)
+ .mouseClickable { selectedName = tab.name }
+ .padding(horizontal = 6.dp, vertical = 2.dp)
+ // ...with its name in the middle, as a heading's is
+ .then(if (shown.size == 1) Modifier.wrapContentWidth(Alignment.CenterHorizontally) else Modifier)
+ )
+ }
+ }
+ AnimatedContent(
+ targetState = selected,
+ modifier = Modifier.fillMaxWidth(),
+ transitionSpec = { pageTurn(towardsEnd = shown.indexOf(targetState) > shown.indexOf(initialState)) },
+ ) { tab ->
+ Column(
+ Modifier
+ .layout { measurable, constraints ->
+ widths[tab.name] = measurable.maxIntrinsicWidth(constraints.maxHeight)
+ val widest = widths.values.max().coerceIn(constraints.minWidth, constraints.maxWidth)
+ val placeable = measurable.measure(constraints.copy(minWidth = widest))
+ // Stated outright as well: asked how wide it would like to be, rather
+ // than measured, the page answers through this without the minimum applied
+ layout(maxOf(placeable.width, widest), placeable.height) { placeable.place(0, 0) }
+ }
+ .fillMaxWidth()
+ .padding(vertical = 1.dp)
+ ) { Children(tab) }
+ }
+ }
+}
+
+private const val TAB_MILLIS = 160
+
+/**
+ * How one page gives way to another, under tabs or the strip of a settings panel: the new one
+ * slides in from the side its tab is on, [towardsEnd] or from the start, while the room they
+ * are in grows or shrinks to fit it.
+ */
+internal fun AnimatedContentTransitionScope<*>.pageTurn(towardsEnd: Boolean): ContentTransform {
+ val slide = tween(TAB_MILLIS)
+ return (fadeIn(tween(TAB_MILLIS)) + slideInHorizontally(slide) { if (towardsEnd) it / 5 else -it / 5 })
+ .togetherWith(fadeOut(tween(TAB_MILLIS / 2)) + slideOutHorizontally(slide) { if (towardsEnd) -it / 5 else it / 5 })
+ .using(SizeTransform(clip = true) { _, _ -> tween(TAB_MILLIS) })
+}
+
+/** Whether [setting] is somewhere in the layer, at any depth */
+internal fun EntryLayer>.holds(setting: Setting<*>): Boolean = when (this) {
+ is EntryLayer.Single -> entry === setting
+ is EntryLayer.Multiple -> layers.any { it.holds(setting) }
+ else -> false
+}
+
+/** Whether the layer holds a setting that is visible right now, at any depth */
+internal 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/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..1cdac730c
--- /dev/null
+++ b/src/main/kotlin/com/lambda/gui/theme/Theme.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.theme
+
+import androidx.compose.foundation.text.BasicText
+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.compositionLocalOf
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.staticCompositionLocalOf
+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.graphics.luminance
+import androidx.compose.ui.platform.LocalDensity
+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.style.LineHeightStyle
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.TextUnit
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.lambda.gui.core.observe
+import com.lambda.module.modules.client.Style
+import com.lambda.util.NamedEnum
+import com.lambda.util.stream
+
+/**
+ * Every colour the interface uses, named for what it is for. Built from the [Style] module's
+ * settings, so a colour picked there shows up everywhere at once.
+ */
+@Immutable
+data class Palette(
+ /** Accent: sliders, checked boxes, the selected tab, the outline of the module being edited */
+ val primary: Color,
+ val secondary: Color,
+ /** Fill of windows, tinted over the frosted game */
+ val surface: Color,
+ /** Fill of what opens over a window: a module's settings, menus, dialogs */
+ val panel: Color,
+ /** Shade over what is pressed in: the module whose settings are open */
+ val inset: Color,
+ val onSurface: Color,
+ val onSurfaceVariant: Color,
+ val header: Color,
+ val onHeader: Color,
+ val moduleEnabled: Color,
+ val onModuleEnabled: Color,
+ /** Fill of dropdowns, buttons and unchecked boxes */
+ val control: Color,
+ /** Fill of the list a dropdown opens */
+ val controlMenu: Color,
+ val controlSelected: Color,
+ val onControl: Color,
+ /** The unfilled part of a slider */
+ val track: Color,
+ /** Fill of text fields */
+ val input: Color,
+ val border: Color,
+ val textShadow: Color,
+) {
+ /** Text drawn on [primary]: whichever of dark and white stands out */
+ val onPrimary: Color = if (primary.luminance() > 0.35f) Color(0xFF1B1024) else Color.White
+
+ /** Laid over a surface to lift something off it: the heading of a group, the chosen tab */
+ val raised: Color = onSurface.copy(alpha = 0.11f)
+
+ /** Laid under the row the pointer is on, which shows how far it reaches */
+ val hover: Color = onSurface.copy(alpha = 0.06f)
+}
+
+/**
+ * How thick outlines are: one pixel at 1080p, and never less than one anywhere. Outlines are
+ * there to finish an edge, not to be looked at.
+ */
+val Hairline = 0.5.dp
+
+/** Corner radii, by how much room the component has */
+object Radius {
+ /** Checkboxes, colour swatches, the small parts inside a control */
+ val ExtraSmall = 1.dp
+
+ /** Controls and the blocks settings are grouped in */
+ val Small = 2.dp
+
+ /** Windows, menus and tooltips */
+ val Medium = 3.dp
+
+ /** The panels that pop out of a window, and dialogs */
+ val Large = 5.dp
+}
+
+/**
+ * The fonts the interface can be set in. Each comes with the size it reads well at: the
+ * Minecraft font is drawn on a grid of twelve to the em, so at 12 sp one of its pixels is one
+ * dp, which is two screen pixels at 1080p, the size of Minecraft's own text at GUI scale 2.
+ */
+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
+ }
+ }
+}
+
+/** The text styles of a [GuiFont]. Lines are exactly as tall as the type, so rows are spaced by their padding alone. */
+@Immutable
+class Typography(font: GuiFont) {
+ val title = compact(font, font.size, font.titleWeight)
+ val body = compact(font, font.size)
+
+ /** For what is secondary to the text beside it. No smaller than [body] in a pixel font, which cannot shrink. */
+ val label = compact(font, font.smallSize)
+
+ private fun compact(font: GuiFont, size: TextUnit, weight: FontWeight = FontWeight.Normal) = TextStyle(
+ fontFamily = font.family,
+ fontWeight = weight,
+ fontSize = size,
+ lineHeight = size,
+ lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.Both),
+ )
+}
+
+/** The text styles of the font in use: `Type.body`, `Type.title`, `Type.label` */
+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") }
+
+/** Colour text takes when none is given. Set it for a subtree with [ContentColor]. */
+val LocalContentColor = compositionLocalOf { Color.White }
+
+/**
+ * How much glass blurs the interface beneath it, as the sigma of a Gaussian; zero for not at
+ * all. See [com.lambda.gui.component.glass].
+ */
+val LocalBackdropBlur = staticCompositionLocalOf { 0.dp }
+
+/** Whether windows, panels and menus are drawn with a hairline border, see [com.lambda.gui.component.window] */
+val LocalOutlines = staticCompositionLocalOf { true }
+
+@Composable
+fun LambdaTheme(content: @Composable () -> Unit) {
+ val palette by observe { Style.palette }
+ // Half the radius the game behind is blurred with, which is about what a sigma amounts to
+ val backdropBlur by observe { if (Style.blur) (Style.blurRadius / 2f).dp else 0.dp }
+ val font by observe { Style.font }
+ val outlines by observe { Style.outlines }
+ CompositionLocalProvider(
+ LocalPalette provides palette,
+ LocalTypography provides remember(font) { Typography(font) },
+ // Selected text is marked in the accent colour rather than in Compose's own blue
+ LocalTextSelectionColors provides TextSelectionColors(palette.primary, palette.primary.copy(alpha = 0.4f)),
+ LocalContentColor provides palette.onSurface,
+ LocalBackdropBlur provides backdropBlur,
+ LocalOutlines provides outlines,
+ content = content
+ )
+}
+
+@Composable
+fun ContentColor(color: Color, content: @Composable () -> Unit) =
+ CompositionLocalProvider(LocalContentColor provides color, content = content)
+
+/** The shadow a [Text] is drawn over when its style does not bring one. Set for a subtree with [SoftTextShadow]. */
+private val LocalTextShadow = compositionLocalOf { null }
+
+/**
+ * Draws all the text in [content] over a soft shadow, just enough to lift it off glass that
+ * lets a bright or busy background through.
+ */
+@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 Text(
+ text: String,
+ modifier: Modifier = Modifier,
+ color: Color = LocalContentColor.current,
+ style: TextStyle = Type.body,
+ maxLines: Int = Int.MAX_VALUE,
+ softWrap: Boolean = true,
+) {
+ 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,
+ )
+}
+
+/**
+ * This style with a hard drop shadow, for text that sits on a busy or translucent background.
+ * The shadow is the theme's unless a [color] is given.
+ */
+@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)))
+}
+
+fun java.awt.Color.toCompose() = Color(red, green, blue, alpha)
diff --git a/src/main/kotlin/com/lambda/module/HudModule.kt b/src/main/kotlin/com/lambda/module/HudModule.kt
index 5a4372b02..f05ac8671 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,29 @@ 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))
+
+ /**
+ * Where the element sits, as the fraction of the room it has to move in: 0 puts it against
+ * the left or top edge of the screen and 1 against the right or bottom. A fraction keeps an
+ * element docked to its edge when the window changes size. Set by dragging it in the HUD editor.
+ */
+ 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 }
+
+ /**
+ * The element as it is drawn. Read whatever it shows through
+ * [com.lambda.gui.core.observe], so it is redrawn when that changes and only then.
+ */
+ @Composable
+ abstract fun Content()
+
+ private companion object {
+ const val DEFAULT_ANCHOR = 0.01f
+
+ /** Elements start out one under the other down the left edge, rather than in a pile */
+ 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..4d0762f6c 100644
--- a/src/main/kotlin/com/lambda/module/Module.kt
+++ b/src/main/kotlin/com/lambda/module/Module.kt
@@ -125,7 +125,12 @@ abstract class Module(
enabledByDefault: Boolean = false,
modulePriority: Int = 0,
defaultKeybind: Bind = Bind.EMPTY,
- autoDisable: Boolean = false
+ autoDisable: Boolean = false,
+ /**
+ * For a module that does nothing by being enabled, only holding settings that always apply:
+ * it counts as enabled at all times, whatever was saved, and cannot be disabled or toggled.
+ */
+ val alwaysEnabled: Boolean = false,
) : Nameable, Muteable, OwnerPriority, Config(name, ModuleCategory),
IMutableAutomationConfig by MutableAutomationConfig()
{
@@ -145,8 +150,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 +178,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..4bd4ed871 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,11 @@ object AutoUpdater : Module(
private var loaderPromptHandled by property(false)
- @JvmStatic var showFirstLaunchModal = false
- @JvmStatic var showInstallModal = false
- @JvmStatic var showUninstallModal = false
+ /** A question the click GUI puts to the user before the jar is swapped, which restarts the game */
+ enum class Prompt { FirstLaunch, Install, Uninstall }
+
+ var prompt: Prompt? = null
+ private set
private var firstLaunchStateInitialized = false
private const val MAVEN_URL = "https://maven.lambda-client.org"
@@ -64,102 +60,42 @@ 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()
+ // Toggling the module from the GUI asks first; the answer either goes ahead or toggles it back,
+ // which lands here again with the prompt still up and only takes it down
+ 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
- }
+ /** Called when the click GUI opens, the first of which decides whether to offer the loader */
+ 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
+ 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 +299,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/Style.kt b/src/main/kotlin/com/lambda/module/modules/client/Style.kt
new file mode 100644
index 000000000..87c3754aa
--- /dev/null
+++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt
@@ -0,0 +1,212 @@
+/*
+ * 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.gui.theme.GuiFont
+import com.lambda.gui.theme.Palette
+import com.lambda.gui.theme.toCompose
+import com.lambda.module.Module
+import com.lambda.module.ModuleTag
+import com.lambda.util.NamedEnum
+import java.awt.Color
+import org.jetbrains.skiko.SystemTheme
+import org.jetbrains.skiko.currentSystemTheme
+
+object Style : Module(
+ name = "Style",
+ description = "How Lambda's interface looks",
+ tag = ModuleTag.CLIENT,
+ alwaysEnabled = true,
+) {
+ 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.Auto, "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 scale by setting("Scale", 1f, 0.5f..2f, 0.05f, "Size of the interface")
+ val dimBackground by setting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows")
+ 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 }
+
+ val blur by setting("Blur", true, "Blurs what is behind windows for a frosted glass look")
+ val blurRadius by setting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur }
+
+ val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass")
+
+ val glow by setting("Glow", true, "Surrounds the click GUI with a glow")
+ val glowRadius by setting("Glow Radius", 17f, 1f..100f, 1f) { glow }
+ val glowIntensity by setting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow }
+ val glowColorA by setting("Glow Color 1", Color(176, 0, 70)) { glow }
+ val glowColorB by setting("Glow Color 2", Color(255, 94, 128)) { glow }
+
+ // Both themes are built from the colours of Lambda's logo and nothing else: its light rose
+ // (255, 94, 128), its red (214, 55, 88), its crimson (176, 0, 70), and the two shades it is
+ // shadowed with, (107, 27, 44) and (88, 0, 35). The glow above runs from crimson to rose.
+ @Group(DARK_THEME_GROUP) private val darkTheme by configBlock(
+ PaletteSettings(
+ this,
+ primary = Color(214, 55, 88),
+ secondary = Color(255, 94, 128),
+ surface = Color(18, 0, 7, 80),
+ panel = Color(16, 12, 14, 140),
+ inset = Color(0, 0, 0, 90),
+ onSurface = Color(240, 240, 245),
+ onSurfaceVariant = Color(140, 140, 150),
+ header = Color(176, 0, 70, 240),
+ onHeader = Color(240, 240, 245),
+ // A step under the header: the name of a category stays the strongest thing in its window
+ moduleEnabled = Color(205, 10, 80, 175),
+ onModuleEnabled = Color(240, 240, 245),
+ // Controls are filled in the colour of a slider's fill and a ticked box, so all of them read as one kind of thing
+ control = Color(214, 55, 88, 240),
+ controlMenu = Color(48, 16, 23),
+ controlSelected = Color(88, 32, 45),
+ onControl = Color(255, 255, 255),
+ // Wells cut into the panel, darker than any glass they sit on so they never blend into it
+ track = Color(22, 18, 20, 220),
+ input = Color(14, 11, 13, 220),
+ border = Color(140, 0, 56, 235),
+ textShadow = Color(0, 0, 0, 180),
+ )
+ )
+
+ // Light glass has to be nearly solid: dark text over whatever the game shows through it
+ // cannot be read, and a shadow under dark text only smears it
+ @Group(LIGHT_THEME_GROUP) private val lightTheme by configBlock(
+ PaletteSettings(
+ this,
+ primary = Color(214, 55, 88),
+ secondary = Color(176, 0, 70),
+ surface = Color(252, 246, 247, 205),
+ panel = Color(247, 244, 245, 222),
+ inset = Color(120, 0, 40, 34),
+ onSurface = Color(40, 14, 20),
+ onSurfaceVariant = Color(128, 102, 108),
+ header = Color(214, 55, 88, 242),
+ onHeader = Color(255, 250, 251),
+ moduleEnabled = Color(250, 180, 198, 190),
+ onModuleEnabled = Color(120, 0, 48),
+ control = Color(214, 55, 88, 242),
+ controlMenu = Color(246, 232, 235),
+ controlSelected = Color(236, 198, 208),
+ onControl = Color(40, 14, 20),
+ track = Color(214, 196, 201, 228),
+ input = Color(255, 255, 255, 235),
+ border = Color(216, 134, 150, 238),
+ textShadow = Color(0, 0, 0, 0),
+ )
+ )
+
+ val palette: Palette
+ get() = when (themeMode) {
+ ThemeMode.Dark -> darkTheme
+ ThemeMode.Light -> lightTheme
+ ThemeMode.Auto -> if (SystemAppearance.isDark) darkTheme else lightTheme
+ }.toPalette()
+
+ /** Asking the operating system is not free, so the answer is reused for a moment */
+ 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,
+ controlMenu: Color,
+ controlSelected: Color,
+ onControl: Color,
+ track: Color,
+ input: Color,
+ border: Color,
+ textShadow: Color,
+) : ConfigBlock {
+ private val primary by c.setting("Primary", primary, "Accent colour of sliders, checkboxes and selections")
+ private val secondary by c.setting("Secondary", secondary)
+ 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 over the module whose settings are open, which looks pressed in")
+ 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 unchecked boxes")
+ private val controlMenu by c.setting("Control Menu", controlMenu, "Fill of an open dropdown's list")
+ private val controlSelected by c.setting("Control Selected", controlSelected)
+ 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)
+
+ 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(),
+ controlMenu = controlMenu.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..1e3c4c127 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,7 +25,7 @@ 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.gui.GuiConfig
import com.lambda.interaction.handler.handlers.FriendHandler
import com.lambda.module.Module
import com.lambda.module.ModuleTag
@@ -654,7 +654,7 @@ object AutoDisconnect : Module(
buildText {
text(effect.effectType.value().name)
if (effect.amplifier > 0) literal(" ${effect.amplifier + 1}")
- color(ClickGuiLayout.textDisabled) { literal(" (${effectDuration(effect)})") }
+ color(GuiConfig.textDisabled) { literal(" (${effectDuration(effect)})") }
}
)
}
@@ -741,7 +741,7 @@ object AutoDisconnect : Module(
val customName = stack.get(DataComponentTypes.CUSTOM_NAME)
if (customName != null) {
text(stack.itemName)
- color(ClickGuiLayout.textDisabled) {
+ color(GuiConfig.textDisabled) {
literal(" (")
text(customName)
literal(")")
@@ -751,11 +751,11 @@ object AutoDisconnect : Module(
}
if (stack.isDamageable) {
- color(ClickGuiLayout.textDisabled) { literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") }
+ color(GuiConfig.textDisabled) { literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") }
}
if (stack.maxCount > 1) {
- color(ClickGuiLayout.textDisabled) { literal(" (${stack.count})") }
+ color(GuiConfig.textDisabled) { 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..4b6d6ca43 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,7 @@
package com.lambda.module.modules.combat.autodisconnect
-import com.lambda.gui.components.ClickGuiLayout
+import com.lambda.gui.GuiConfig
import com.lambda.util.text.buildText
import com.lambda.util.text.highlighted
import com.lambda.util.text.text
@@ -268,12 +268,12 @@ class DisconnectDetailsWidget(
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
+ val COLOR_TEXT get() = GuiConfig.text.rgb
+ val COLOR_BACKGROUND get() = GuiConfig.windowBg.rgb
+ val COLOR_BORDER get() = GuiConfig.border.rgb
+ val COLOR_HOVER_BACKGROUND get() = GuiConfig.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_HEADER get() = GuiConfig.text.rgb//composite(COLOR_TEXT, COLOR_HOVER_BACKGROUND)
}
}
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..0b32ec44a
--- /dev/null
+++ b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt
@@ -0,0 +1,70 @@
+/*
+ * 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.core.observe
+import com.lambda.gui.core.observeSafe
+import com.lambda.gui.hud.HudText
+import com.lambda.gui.hud.ItemIcon
+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() {
+ // The stacks themselves: an icon keeps up with the wear on the one it was given
+ 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
+ }
+ // Spaced like the slots of an inventory
+ 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..5c521d6ed 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,28 @@ 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 = // 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)
- 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..3c97ac908 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,24 @@ 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() {
+ // Every listed module with its keybind, which is null for a module that has none
+ val entries by observe {
+ ModuleRegistry.modules
+ // One that is always enabled says nothing by being listed
+ .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..417510ac7 100644
--- a/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt
+++ b/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt
@@ -17,8 +17,23 @@
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.gui.theme.toCompose
import com.lambda.module.HudModule
import com.lambda.module.ModuleTag
import com.lambda.util.FormattingUtils.format
@@ -37,26 +52,42 @@ 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}")
+ }
+ }
+
+ /** A line through every [stride]th sample, scaled to the range of the samples, over a dim backdrop */
+ 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..ee48d37d4 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,13 @@ 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 }
+ // Sized in dp from the image's own pixels, so the watermark grows with the screen
+ 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..cefa3e41e 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,7 @@ 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.gui.GuiConfig
import com.lambda.module.Module
import com.lambda.module.ModuleTag
import com.lambda.module.modules.combat.KillAura
@@ -172,7 +172,7 @@ object BackTrack : Module(
immediateRenderer("BackTrack Immediate Renderer") {
val target = target ?: return@immediateRenderer
- val c1 = ClickGuiLayout.primaryColor
+ val c1 = GuiConfig.primaryColor
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..c14c669f2 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,7 @@ 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.gui.GuiConfig
import com.lambda.module.Module
import com.lambda.module.ModuleTag
import com.lambda.module.modules.combat.KillAura
@@ -71,7 +71,7 @@ object Blink : Module(
}
immediateRenderer("Blink Immediate Renderer") {
- val color = ClickGuiLayout.primaryColor
+ val color = GuiConfig.primaryColor
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..b614c817c 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,7 @@ 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.gui.GuiConfig
import com.lambda.interaction.handler.handlers.TimerHandler
import com.lambda.interaction.manager.managers.rotating.Rotation
import com.lambda.interaction.manager.managers.rotating.RotationMode
@@ -197,11 +197,11 @@ object Replay : Module(
val index = recordings.indexOf(saving)
this@Replay.info(buildText {
literal("Auto saved #")
- color(ClickGuiLayout.primaryColor) { literal("$index") }
+ color(GuiConfig.primaryColor) { literal("$index") }
literal(" of ")
- color(ClickGuiLayout.primaryColor) { literal(saving.duration.toString()) }
+ color(GuiConfig.primaryColor) { literal(saving.duration.toString()) }
literal(" at ")
- color(ClickGuiLayout.primaryColor) { literal(saving.endPos.format(precision = 1)) }
+ color(GuiConfig.primaryColor) { literal(saving.endPos.format(precision = 1)) }
playMessage(saving)
saveMessage(saving)
pruneMessage(saving)
@@ -219,9 +219,9 @@ object Replay : Module(
buffer = playback?.duplicate()
this@Replay.info(buildText {
if (repeats > 0) {
- color(ClickGuiLayout.primaryColor) { literal("[$repeats / $loops]") }
+ color(GuiConfig.primaryColor) { literal("[$repeats / $loops]") }
} else {
- color(ClickGuiLayout.primaryColor) { literal("[$repeats/∞]") }
+ color(GuiConfig.primaryColor) { literal("[$repeats/∞]") }
}
literal(" Replay looped.")
})
@@ -232,7 +232,7 @@ object Replay : Module(
state = State.Inactive
this@Replay.info(buildText {
literal("Replay finished after ")
- color(ClickGuiLayout.primaryColor) { literal(playback?.duration.toString()) }
+ color(GuiConfig.primaryColor) { literal(playback?.duration.toString()) }
literal(".")
})
return@listen
@@ -257,9 +257,9 @@ object Replay : Module(
info(buildText {
literal("Recording #${recordings.indexOf(deserialized)} ")
- color(ClickGuiLayout.primaryColor) { literal(file.nameWithoutExtension) }
+ color(GuiConfig.primaryColor) { literal(file.nameWithoutExtension) }
literal(" loaded. Duration: ")
- color(ClickGuiLayout.primaryColor) { literal(deserialized.duration.toString()) }
+ color(GuiConfig.primaryColor) { literal(deserialized.duration.toString()) }
playMessage(deserialized)
pruneMessage(deserialized)
})
@@ -288,9 +288,9 @@ object Replay : Module(
playback = recording
info(buildText {
literal("Replaying recording #")
- color(ClickGuiLayout.primaryColor) { literal(index.toString()) }
+ color(GuiConfig.primaryColor) { literal(index.toString()) }
literal(" of ")
- color(ClickGuiLayout.primaryColor) { literal(recording.duration.toString()) }
+ color(GuiConfig.primaryColor) { literal(recording.duration.toString()) }
})
return CommandResult.success()
}
@@ -304,13 +304,13 @@ object Replay : Module(
recordings.add(pruned)
info(buildText {
literal("Shortened recording #")
- color(ClickGuiLayout.primaryColor) { literal(recordings.indexOf(toShorten).toString()) }
+ color(GuiConfig.primaryColor) { literal(recordings.indexOf(toShorten).toString()) }
literal(" of ")
- color(ClickGuiLayout.primaryColor) { literal(toShorten.duration.toString()) }
+ color(GuiConfig.primaryColor) { literal(toShorten.duration.toString()) }
literal(" to new recording #")
- color(ClickGuiLayout.primaryColor) { literal(recordings.indexOf(pruned).toString()) }
+ color(GuiConfig.primaryColor) { literal(recordings.indexOf(pruned).toString()) }
literal(" of ")
- color(ClickGuiLayout.primaryColor) { literal(pruned.duration.toString()) }
+ color(GuiConfig.primaryColor) { literal(pruned.duration.toString()) }
playMessage(pruned)
saveMessage(pruned)
})
@@ -326,7 +326,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(GuiConfig.primaryColor) { literal(it.duration.toString()) }
})
} ?: run {
this@Replay.warn("No recording to replay.")
@@ -370,9 +370,9 @@ object Replay : Module(
recordings.add(rec)
this@Replay.info(buildText {
literal("Stopped recording #")
- color(ClickGuiLayout.primaryColor) { literal("${recordings.indexOf(rec)}") }
+ color(GuiConfig.primaryColor) { literal("${recordings.indexOf(rec)}") }
literal(" of ")
- color(ClickGuiLayout.primaryColor) { literal(rec.duration.toString()) }
+ color(GuiConfig.primaryColor) { literal(rec.duration.toString()) }
literal(".")
playMessage(rec)
saveMessage(rec)
@@ -387,9 +387,9 @@ object Replay : Module(
recordings.add(checkRec)
this@Replay.info(buildText {
literal("Checkpoint #")
- color(ClickGuiLayout.primaryColor) { literal("${recordings.indexOf(checkRec)}") }
+ color(GuiConfig.primaryColor) { literal("${recordings.indexOf(checkRec)}") }
literal(" created at ")
- color(ClickGuiLayout.primaryColor) { literal(checkRec.endPos.format(precision = 0)) }
+ color(GuiConfig.primaryColor) { literal(checkRec.endPos.format(precision = 0)) }
literal(".")
playMessage(checkRec)
saveMessage(checkRec)
@@ -408,9 +408,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(GuiConfig.primaryColor) { literal(playMode.name) }
literal(" (previously ")
- color(ClickGuiLayout.primaryColor) { literal(oldMode.name) }
+ color(GuiConfig.primaryColor) { literal(oldMode.name) }
literal(")")
})
}
@@ -430,30 +430,30 @@ object Replay : Module(
this@Replay.info(buildText {
literal("Saved recording #")
- color(ClickGuiLayout.primaryColor) { literal("${recordings.indexOf(recording)}") }
+ color(GuiConfig.primaryColor) { literal("${recordings.indexOf(recording)}") }
literal(" of ")
- color(ClickGuiLayout.primaryColor) { literal(recording.duration.toString()) }
+ color(GuiConfig.primaryColor) { literal(recording.duration.toString()) }
literal(" in file ")
- color(ClickGuiLayout.primaryColor) { literal(name) }
+ color(GuiConfig.primaryColor) { literal(name) }
val filePath = file.toPath().pathString
hoverEvent(HoverEvents.showText(buildText {
literal("Open file ")
- color(ClickGuiLayout.primaryColor) { literal(filePath) }
+ color(GuiConfig.primaryColor) { literal(filePath) }
})) {
clickEvent(ClickEvents.openFile(filePath)) {
literal(" [")
- color(ClickGuiLayout.secondaryColor) { literal("OPEN FILE") }
+ color(GuiConfig.secondaryColor) { literal("OPEN FILE") }
literal("]")
}
}
val parentPath = file.parentFile.toPath().pathString
hoverEvent(HoverEvents.showText(buildText {
literal("Open folder ")
- color(ClickGuiLayout.primaryColor) { literal(parentPath) }
+ color(GuiConfig.primaryColor) { literal(parentPath) }
})) {
clickEvent(ClickEvents.openFile(parentPath)) {
literal(" [")
- color(ClickGuiLayout.secondaryColor) { literal("OPEN FOLDER") }
+ color(GuiConfig.secondaryColor) { literal("OPEN FOLDER") }
literal("]")
}
}
@@ -464,12 +464,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(GuiConfig.primaryColor) { literal("${recordings.indexOf(recording)}") }
literal(".")
})) {
clickEvent(ClickEvents.suggestCommand(";replay play ${recordings.indexOf(recording)}")) {
literal(" [")
- color(ClickGuiLayout.secondaryColor) {
+ color(GuiConfig.secondaryColor) {
literal("PLAY")
}
literal("]")
@@ -482,17 +482,17 @@ object Replay : Module(
hoverEvent(HoverEvents.showText(buildText {
literal(" Recording can be shortened by ")
- color(ClickGuiLayout.primaryColor) {
+ color(GuiConfig.primaryColor) {
literal(recording.pruneTimesave.toString())
}
literal(" by removing idles and cyclic paths.")
})) {
clickEvent(ClickEvents.suggestCommand(";replay prune ${recordings.indexOf(recording)}")) {
literal(" [")
- color(ClickGuiLayout.secondaryColor) {
+ color(GuiConfig.secondaryColor) {
literal("PRUNE ")
}
- color(ClickGuiLayout.primaryColor) {
+ color(GuiConfig.primaryColor) {
literal("${recording.pruneTimesave}")
}
literal("]")
@@ -503,12 +503,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(GuiConfig.primaryColor) { literal("${recordings.indexOf(recording)}") }
literal(".")
})) {
clickEvent(ClickEvents.suggestCommand(";replay save ${recordings.indexOf(recording)} ${getTime(fileFormatter).sanitizeForFilename()}")) {
literal(" [")
- color(ClickGuiLayout.secondaryColor) { literal("SAVE") }
+ color(GuiConfig.secondaryColor) { literal("SAVE") }
literal("]")
}
}
@@ -528,7 +528,7 @@ object Replay : Module(
}
this@Replay.info(buildText {
literal("Postprocessing finished. Shortened recording by ")
- color(ClickGuiLayout.primaryColor) { literal((duration - pruned.duration).toString()) }
+ color(GuiConfig.primaryColor) { 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..188cf2b90 100644
--- a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt
+++ b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt
@@ -24,7 +24,7 @@ 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.gui.GuiConfig
import com.lambda.module.Module
import com.lambda.module.ModuleRegistry
import com.lambda.threading.runSafe
@@ -152,7 +152,7 @@ object CommunicationUtils {
if (command.usage.isNotBlank()) {
literal("\n")
literal("Usage: ")
- color(ClickGuiLayout.primaryColor) {
+ color(GuiConfig.primaryColor) {
literal(command.usage)
}
}
@@ -160,7 +160,7 @@ object CommunicationUtils {
literal("\n")
literal("Aliases: ")
joinToText(command.aliases) {
- color(ClickGuiLayout.primaryColor) {
+ color(GuiConfig.primaryColor) {
literal(it)
}
}
@@ -179,7 +179,7 @@ object CommunicationUtils {
literal("\n")
}
literal("Keybind: ")
- color(ClickGuiLayout.primaryColor) {
+ color(GuiConfig.primaryColor) {
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..24446de97 100644
--- a/src/main/kotlin/com/lambda/util/InputUtils.kt
+++ b/src/main/kotlin/com/lambda/util/InputUtils.kt
@@ -20,94 +20,24 @@ 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)
- }
-
+ /** Whether everything the bind is made of is held down right now. Never true for an unbound one. */
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/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..14700c833
--- /dev/null
+++ b/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh
@@ -0,0 +1,26 @@
+#version 330
+
+// Downsampling half of a dual Kawase blur: the target is half the size of InSampler, so the
+// centre tap and the four diagonal ones each average a 2x2 block through bilinear filtering.
+
+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..8e31793d2
--- /dev/null
+++ b/src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh
@@ -0,0 +1,30 @@
+#version 330
+
+// Upsampling half of a dual Kawase blur: the target is twice the size of InSampler. Eight taps
+// in a diamond, the near ones weighted double, spread the low resolution image back out smoothly.
+
+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..2386c9206
--- /dev/null
+++ b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh
@@ -0,0 +1,41 @@
+#version 330
+
+// Lays the GUI over the game. Wherever the GUI drew anything the game behind it is swapped for
+// its blurred copy, which is what makes translucent windows look like frosted glass; around the
+// GUI a blurred copy of its own silhouette is tinted into a glow.
+
+uniform sampler2D GuiSampler; // The GUI as Compose drew it, premultiplied alpha
+uniform sampler2D BackdropSampler; // The game, blurred
+uniform sampler2D HaloSampler; // The GUI, blurred
+
+layout(std140) uniform GuiEffects {
+ vec4 GlowColorA;
+ vec4 GlowColorB;
+ float GlowIntensity;
+ float Frost;
+ float Time;
+};
+
+in vec2 texCoord;
+
+out vec4 fragColor;
+
+void main() {
+ vec4 gui = texture(GuiSampler, texCoord);
+
+ // Coverage rather than alpha: a window tinted at 30% is still wholly a window
+ float covered = clamp(gui.a * 64.0, 0.0, 1.0);
+
+ float frost = Frost * covered;
+ vec4 under = vec4(texture(BackdropSampler, texCoord).rgb, 1.0) * frost;
+
+ if (GlowIntensity > 0.0) {
+ // A straight edge blurs to half coverage, so doubling makes the glow start at full strength
+ 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);
+ }
+
+ fragColor = gui + under * (1.0 - gui.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..96919147f 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,6 +55,8 @@
"render.FluidRendererMixin",
"render.FogRendererMixin",
"render.GameRendererMixin",
+ "render.GuiRendererMixin",
+ "render.InactivityFpsLimiterMixin",
"render.HandledScreenMixin",
"render.HeadFeatureRendererMixin",
"render.HeldItemRendererMixin",
From cc5fb8d700ead5d637882e6b5e31be13a65e819a Mon Sep 17 00:00:00 2001
From: beanbag44 <107891830+beanbag44@users.noreply.github.com>
Date: Sun, 15 Nov 2026 14:05:44 +0000
Subject: [PATCH 02/34] import cleanup
---
src/gametest/kotlin/com/lambda/GuiTest.kt | 4 ++--
src/main/kotlin/com/lambda/event/events/GuiEvent.kt | 1 -
src/main/kotlin/com/lambda/gui/GuiConfig.kt | 3 +--
src/main/kotlin/com/lambda/gui/LambdaGui.kt | 6 ++++--
.../kotlin/com/lambda/gui/clickgui/CategoryWindow.kt | 9 ++++-----
src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt | 8 ++++----
.../kotlin/com/lambda/gui/clickgui/SettingsPanel.kt | 5 ++---
src/main/kotlin/com/lambda/gui/component/Pointer.kt | 2 +-
src/main/kotlin/com/lambda/gui/component/Popups.kt | 12 +++++-------
src/main/kotlin/com/lambda/gui/core/SceneInput.kt | 2 +-
src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt | 6 +++---
src/main/kotlin/com/lambda/gui/hud/Hud.kt | 2 +-
src/main/kotlin/com/lambda/gui/hud/HudEditor.kt | 1 -
src/main/kotlin/com/lambda/gui/menu/MenuBar.kt | 6 +++---
src/main/kotlin/com/lambda/gui/menu/Search.kt | 1 -
src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt | 4 ++--
.../kotlin/com/lambda/gui/render/GuiCompositor.kt | 4 ++--
src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt | 4 +++-
.../com/lambda/gui/settings/CollectionEditor.kt | 2 +-
.../kotlin/com/lambda/gui/settings/ColorPicker.kt | 6 ++----
.../kotlin/com/lambda/gui/settings/SettingRow.kt | 6 ++----
.../kotlin/com/lambda/gui/settings/SettingsList.kt | 1 -
.../kotlin/com/lambda/module/modules/client/Style.kt | 2 +-
src/main/resources/lambda.mixins.json | 2 +-
24 files changed, 45 insertions(+), 54 deletions(-)
diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt
index e6f4e967c..837e4e8b4 100644
--- a/src/gametest/kotlin/com/lambda/GuiTest.kt
+++ b/src/gametest/kotlin/com/lambda/GuiTest.kt
@@ -20,15 +20,15 @@ package com.lambda
import com.lambda.gui.GuiConfig
import com.lambda.gui.LambdaGui
import com.lambda.module.ModuleRegistry
+import com.lambda.module.modules.client.AutoUpdater
import com.lambda.module.modules.hud.Armor
import com.lambda.module.modules.hud.Coordinates
import com.lambda.module.modules.hud.Fps
-import com.lambda.module.modules.client.AutoUpdater
-import kotlin.math.abs
import net.fabricmc.fabric.api.client.gametest.v1.FabricClientGameTest
import net.fabricmc.fabric.api.client.gametest.v1.context.ClientGameTestContext
import net.minecraft.client.gui.screen.world.WorldCreator
import org.lwjgl.glfw.GLFW
+import kotlin.math.abs
/**
* Walks through the interface the way a user would and takes a screenshot at every stop, so a
diff --git a/src/main/kotlin/com/lambda/event/events/GuiEvent.kt b/src/main/kotlin/com/lambda/event/events/GuiEvent.kt
index d4dd346f4..a5e3fa861 100644
--- a/src/main/kotlin/com/lambda/event/events/GuiEvent.kt
+++ b/src/main/kotlin/com/lambda/event/events/GuiEvent.kt
@@ -17,7 +17,6 @@
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
diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt
index db8883e64..a3566502d 100644
--- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt
+++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt
@@ -17,7 +17,6 @@
package com.lambda.gui
-import com.lambda.Lambda.mc
import com.lambda.config.Config
import com.lambda.config.Tab
import com.lambda.config.categories.GuiCategory
@@ -25,9 +24,9 @@ import com.lambda.config.entries.onValueChange
import com.lambda.core.Loadable
import com.lambda.util.KeyCode
import com.lambda.util.WindowUtils.setLambdaWindowIcon
-import java.awt.Color
import net.minecraft.SharedConstants
import net.minecraft.client.util.Icons
+import java.awt.Color
/**
* Settings of the interface that are about how it behaves rather than how it looks; for that,
diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt
index 750e0892c..6af0ab671 100644
--- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt
+++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt
@@ -31,6 +31,8 @@ import com.lambda.core.Loadable
import com.lambda.event.events.ClientEvent
import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe
import com.lambda.graphics.mc.LambdaRenderPipelines
+import com.lambda.gui.LambdaGui.Content
+import com.lambda.gui.LambdaGui.warmUp
import com.lambda.gui.clickgui.ClickGui
import com.lambda.gui.clickgui.Reveal
import com.lambda.gui.component.TextFocus
@@ -39,8 +41,8 @@ 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.awaitFrames
import com.lambda.gui.core.SceneInput
+import com.lambda.gui.core.awaitFrames
import com.lambda.gui.hud.Hud
import com.lambda.gui.hud.HudEditor
import com.lambda.gui.hud.HudLayer
@@ -54,10 +56,10 @@ 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 kotlin.concurrent.thread
import net.minecraft.client.gui.cursor.Cursor
import org.jetbrains.skia.FontMgr
import org.jetbrains.skia.impl.Library
+import kotlin.concurrent.thread
/**
* Lambda's interface: the HUD drawn over the game, and the screens opened on top of it.
diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt
index ad131bdbe..e645be38c 100644
--- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt
+++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt
@@ -18,8 +18,8 @@
package com.lambda.gui.clickgui
import androidx.compose.animation.AnimatedVisibility
-import androidx.compose.animation.core.MutableTransitionState
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
@@ -37,19 +37,18 @@ 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.SideEffect
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.Modifier
-import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
-import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerEventType
@@ -65,8 +64,8 @@ import com.lambda.gui.GuiConfig
import com.lambda.gui.Snap
import com.lambda.gui.component.ScrollColumn
import com.lambda.gui.component.SlidingText
-import com.lambda.gui.component.hoverHighlight
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.window
diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt
index 4d00b3a98..66f554772 100644
--- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt
+++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt
@@ -21,9 +21,6 @@ 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.ui.input.pointer.PointerEventPass
-import androidx.compose.ui.input.pointer.PointerEventType
-import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
@@ -35,6 +32,9 @@ 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.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.DpOffset
@@ -55,8 +55,8 @@ import com.lambda.gui.menu.MenuBar
import com.lambda.gui.menu.NewAutomationConfigDialog
import com.lambda.module.HudModule
import com.lambda.module.Module
-import com.lambda.module.modules.client.AutoUpdater
import com.lambda.module.ModuleTag
+import com.lambda.module.modules.client.AutoUpdater
/** How far from the top of the screen the category windows are lined up until they are moved: clear of the buttons, with room to drag them up */
private val WindowRowTop = 94.dp
diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt
index f783f7839..c00edf1f3 100644
--- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt
+++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt
@@ -38,7 +38,6 @@ 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.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
@@ -61,8 +60,8 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.input.pointer.pointerHoverIcon
-import androidx.compose.ui.layout.layout
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
@@ -107,8 +106,8 @@ import com.lambda.gui.theme.Text
import com.lambda.module.HudModule
import com.lambda.module.Module
import com.lambda.module.modules.client.AutoUpdater
-import kotlin.math.roundToInt
import kotlinx.coroutines.launch
+import kotlin.math.roundToInt
/** The panel never gets narrower than this, even when every setting has a short name */
private val MinWidth = 130.dp
diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt
index e9715d49e..4d0edd69b 100644
--- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt
+++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt
@@ -24,10 +24,10 @@ import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.PointerMatcher
import androidx.compose.foundation.background
+import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.drag
-import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.onDrag
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt
index 82def3c4d..604c1458d 100644
--- a/src/main/kotlin/com/lambda/gui/component/Popups.kt
+++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt
@@ -41,13 +41,6 @@ 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.ui.graphics.drawscope.translate
-import androidx.compose.ui.layout.positionInWindow
-import androidx.compose.ui.graphics.drawscope.clipRect
-import androidx.compose.ui.draw.drawWithContent
-import androidx.compose.ui.composed
-import androidx.compose.runtime.DisposableEffect
-import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
@@ -61,11 +54,15 @@ 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.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
@@ -78,6 +75,7 @@ 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.LocalDensity
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.unit.IntOffset
diff --git a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt
index aed8d101f..ad609b7ca 100644
--- a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt
+++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt
@@ -27,9 +27,9 @@ 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 org.lwjgl.glfw.GLFW
import java.awt.Component
import java.awt.event.KeyEvent as AwtKeyEvent
-import org.lwjgl.glfw.GLFW
/**
* Translates the game's GLFW input into the pointer and key events a Compose scene consumes.
diff --git a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt
index 64b230e8b..52829a1d1 100644
--- a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt
+++ b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt
@@ -37,12 +37,12 @@ import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import com.lambda.Lambda.mc
-import java.awt.datatransfer.DataFlavor
-import java.awt.datatransfer.StringSelection
-import java.awt.datatransfer.Transferable
import kotlinx.coroutines.awaitCancellation
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
/**
* Stands in for the operating-system window Compose normally lives in: the scene asks it how big
diff --git a/src/main/kotlin/com/lambda/gui/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt
index 79aa6711c..d6b44ab25 100644
--- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt
+++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt
@@ -52,8 +52,8 @@ import com.lambda.gui.theme.shadowed
import com.lambda.gui.theme.toCompose
import com.lambda.module.HudModule
import com.lambda.module.ModuleRegistry
-import kotlin.math.roundToInt
import net.minecraft.item.ItemStack
+import kotlin.math.roundToInt
/** Settings shared by every HUD element, and by the editor that arranges them */
object HudConfig : Loadable, Config("HUD", HudCategory) {
diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt
index 856b03909..505936005 100644
--- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt
+++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt
@@ -50,7 +50,6 @@ 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.draw.drawBehind
import androidx.compose.ui.draw.drawWithContent
diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt
index 80f4c25f6..71220a4e0 100644
--- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt
+++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt
@@ -60,9 +60,9 @@ 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.TextInput
import com.lambda.gui.component.consumeClicks
import com.lambda.gui.component.glass
-import com.lambda.gui.component.TextInput
import com.lambda.gui.component.hoverHighlight
import com.lambda.gui.component.mouseClickable
import com.lambda.gui.core.observe
@@ -80,13 +80,13 @@ import com.lambda.util.CommunicationUtils.info
import com.lambda.util.Diagnostics.gatherDiagnostics
import com.lambda.util.FolderRegistry
import com.mojang.blaze3d.platform.TextureUtil
-import java.nio.file.Path
-import java.util.Locale
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 MenuBarHeight = 15.dp
diff --git a/src/main/kotlin/com/lambda/gui/menu/Search.kt b/src/main/kotlin/com/lambda/gui/menu/Search.kt
index 761a5dd10..4bd52697d 100644
--- a/src/main/kotlin/com/lambda/gui/menu/Search.kt
+++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt
@@ -27,7 +27,6 @@ import com.lambda.gui.clickgui.Reveal
import com.lambda.module.HudModule
import com.lambda.module.Module
import com.lambda.module.ModuleRegistry
-import com.lambda.util.StringUtils.capitalize
import com.lambda.util.StringUtils.levenshteinDistance
import net.minecraft.client.gui.screen.ChatScreen
diff --git a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt
index 5cfe00757..df7baf876 100644
--- a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt
+++ b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt
@@ -26,10 +26,10 @@ 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 java.util.OptionalInt
+import org.lwjgl.system.MemoryStack
+import java.util.*
import kotlin.math.ceil
import kotlin.math.log2
-import org.lwjgl.system.MemoryStack
/**
* A dual Kawase blur.
diff --git a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt
index 5fbe357f7..453f1ffc1 100644
--- a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt
+++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt
@@ -25,9 +25,9 @@ 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 java.awt.Color
-import java.util.OptionalInt
import org.lwjgl.system.MemoryStack
+import java.awt.Color
+import java.util.*
/**
* Puts the GUI texture on screen, in one pass over the game's framebuffer.
diff --git a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt
index e62421d96..6385ff783 100644
--- a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt
+++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt
@@ -25,8 +25,9 @@ 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.lambda.gui.render.ItemAtlas.context
+import com.lambda.gui.render.ItemAtlas.image
import com.mojang.blaze3d.systems.RenderSystem
-import kotlin.math.ceil
import net.minecraft.client.gl.Framebuffer
import net.minecraft.client.gl.GlBackend
import net.minecraft.client.gl.SimpleFramebuffer
@@ -47,6 +48,7 @@ import org.jetbrains.skia.SamplingMode
import org.jetbrains.skia.Surface
import org.jetbrains.skia.SurfaceColorFormat
import org.jetbrains.skia.SurfaceOrigin
+import kotlin.math.ceil
/**
* Item stacks for the GUI, drawn by Minecraft exactly as it draws them in an inventory slot:
diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt
index b4602bdf5..828d4a507 100644
--- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt
+++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt
@@ -48,9 +48,9 @@ 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.Ellipsis
import com.lambda.gui.component.Chip
import com.lambda.gui.component.Dialog
+import com.lambda.gui.component.Ellipsis
import com.lambda.gui.component.RowHeight
import com.lambda.gui.component.Scrollbar
import com.lambda.gui.component.TextInput
diff --git a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt
index 5d9f3ad94..07b3747bd 100644
--- a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt
+++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt
@@ -26,7 +26,6 @@ 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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
@@ -49,10 +48,9 @@ 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.NumberInput
import com.lambda.gui.component.MenuState
+import com.lambda.gui.component.NumberInput
import com.lambda.gui.component.Popout
-import com.lambda.gui.component.RowHeight
import com.lambda.gui.component.TextInput
import com.lambda.gui.component.mouseClickable
import com.lambda.gui.component.scrubbable
@@ -62,8 +60,8 @@ import com.lambda.gui.theme.Radius
import com.lambda.gui.theme.Text
import com.lambda.gui.theme.Type
import com.lambda.gui.theme.toCompose
-import java.awt.Color as AwtColor
import kotlin.math.roundToInt
+import java.awt.Color as AwtColor
/**
* A colour setting: its name and a swatch, which opens a picker beside the row when clicked.
diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt
index 41b0e2cac..53a59531d 100644
--- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt
+++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt
@@ -50,7 +50,6 @@ import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.drawWithContent
-import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.PointerEventPass
@@ -88,14 +87,13 @@ import com.lambda.gui.core.observe
import com.lambda.gui.theme.LambdaTheme
import com.lambda.gui.theme.Radius
import com.lambda.gui.theme.Text
-import com.lambda.util.BlockUtils.blockPos
import com.lambda.util.CommunicationUtils.info
import com.lambda.util.extension.displayValue
import com.lambda.util.world.raycast.RayCastUtils.blockResult
-import kotlin.math.roundToInt
-import kotlin.math.roundToLong
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
+import kotlin.math.roundToInt
+import kotlin.math.roundToLong
/**
* The editor for one setting, whatever its type. The description is its tooltip. A right click
diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt
index bf554dd71..9b80a8d07 100644
--- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt
+++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt
@@ -60,7 +60,6 @@ import com.lambda.gui.core.observe
import com.lambda.gui.theme.LambdaTheme
import com.lambda.gui.theme.Radius
import com.lambda.gui.theme.Text
-import com.lambda.gui.theme.Type
/**
* The settings of a config as they are organised in code: tabs become a strip that swaps the
diff --git a/src/main/kotlin/com/lambda/module/modules/client/Style.kt b/src/main/kotlin/com/lambda/module/modules/client/Style.kt
index 87c3754aa..4e92dbd58 100644
--- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt
+++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt
@@ -26,9 +26,9 @@ import com.lambda.gui.theme.toCompose
import com.lambda.module.Module
import com.lambda.module.ModuleTag
import com.lambda.util.NamedEnum
-import java.awt.Color
import org.jetbrains.skiko.SystemTheme
import org.jetbrains.skiko.currentSystemTheme
+import java.awt.Color
object Style : Module(
name = "Style",
diff --git a/src/main/resources/lambda.mixins.json b/src/main/resources/lambda.mixins.json
index 96919147f..b3af81985 100644
--- a/src/main/resources/lambda.mixins.json
+++ b/src/main/resources/lambda.mixins.json
@@ -56,10 +56,10 @@
"render.FogRendererMixin",
"render.GameRendererMixin",
"render.GuiRendererMixin",
- "render.InactivityFpsLimiterMixin",
"render.HandledScreenMixin",
"render.HeadFeatureRendererMixin",
"render.HeldItemRendererMixin",
+ "render.InactivityFpsLimiterMixin",
"render.InGameHudMixin",
"render.InGameOverlayRendererMixin",
"render.ItemFrameEntityRendererMixin",
From c9089a0a675cffb8b1dc36d0ecae6bab55f0ad9f Mon Sep 17 00:00:00 2001
From: beanbag44 <107891830+beanbag44@users.noreply.github.com>
Date: Sun, 15 Nov 2026 17:32:05 +0000
Subject: [PATCH 03/34] layer fading
---
src/gametest/kotlin/com/lambda/GuiTest.kt | 14 +++++++++++
src/main/kotlin/com/lambda/gui/LambdaGui.kt | 8 ++++++-
.../com/lambda/gui/component/Surface.kt | 23 ++++++++++++++++++-
src/main/kotlin/com/lambda/gui/menu/Search.kt | 8 +++++++
src/main/kotlin/com/lambda/gui/theme/Theme.kt | 11 +++++++++
.../com/lambda/module/modules/client/Style.kt | 13 ++++++-----
6 files changed, 69 insertions(+), 8 deletions(-)
diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt
index 837e4e8b4..0dca1296d 100644
--- a/src/gametest/kotlin/com/lambda/GuiTest.kt
+++ b/src/gametest/kotlin/com/lambda/GuiTest.kt
@@ -474,6 +474,20 @@ object GuiTest : FabricClientGameTest {
context.runOnClient { GuiConfig.keepSettingsOpen = false }
context.closeGui()
+ // The light theme, picked the way a player picks it, in the settings of Style
+ context.openClickGui()
+ context.click(dpX = 830.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.waitTicks(10)
+ context.click(dpX = 760.0, dpY = 201.0)
+ context.waitTicks(10)
+ context.click(dpX = 760.0, dpY = 243.0)
+ context.waitTicks(10)
+ context.takeScreenshot("gui-12a-light-theme")
+ context.click(dpX = 110.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.waitTicks(10)
+ context.takeScreenshot("gui-12b-light-theme-settings")
+ context.closeGui()
+
singleplayer.close()
}
diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt
index 6af0ab671..f2fc8e1af 100644
--- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt
+++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt
@@ -243,7 +243,13 @@ object LambdaGui : Loadable {
}
}
- if (screen == Screen.HudEditor) HudEditor() else HudLayer()
+ // The HUD is for the game, and for other screens if the user says so. The click
+ // GUI never has it: it would only sit under the windows and get in their way.
+ when (screen) {
+ Screen.HudEditor -> HudEditor()
+ Screen.ClickGui -> Unit
+ null -> HudLayer()
+ }
// Composed once and kept, so that opening the click GUI only has to show it
Retained(shown = screen == Screen.ClickGui || warmingUp, clickGuiObservations) { ClickGui() }
if (warmingUp) WarmUp()
diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt
index 0e52a5eb6..5781fe682 100644
--- a/src/main/kotlin/com/lambda/gui/component/Surface.kt
+++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt
@@ -41,6 +41,7 @@ import androidx.compose.ui.unit.dp
import com.lambda.gui.theme.Hairline
import com.lambda.gui.theme.LocalBackdropBlur
import com.lambda.gui.theme.LocalOutlines
+import com.lambda.gui.theme.LocalUnderlay
import org.jetbrains.skia.Canvas
import org.jetbrains.skia.ColorFilter
import org.jetbrains.skia.ColorMatrix
@@ -60,12 +61,22 @@ import org.jetbrains.skia.Rect
* as the window a settings panel has opened over, is blurred here, so it reads as part of the
* same background rather than showing through sharp or being cut out.
*
+ * That half is also faded, to [LocalUnderlay] of what it was: the modules of the window under a
+ * settings panel are still there, faintly, and the game takes their place behind the glass.
+ *
* With the blur switched off the pane simply replaces what is beneath it: stacked panes of
* translucent text over text would be unreadable.
*/
fun Modifier.glass(color: Color, shape: Shape): Modifier = clip(shape).composed {
val sigma = with(LocalDensity.current) { LocalBackdropBlur.current.toPx() }
- val blur = remember(sigma) { if (sigma > 0f) ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) else null }
+ val underlay = LocalUnderlay.current
+ val blur = remember(sigma, underlay) {
+ if (sigma <= 0f) return@remember null
+ val blurred = ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP)
+ // Thinned out as well as blurred: where the interface is fainter the compositor lets
+ // more of the game through, so what the pane lies over does not crowd what is on it
+ if (underlay >= 1f) blurred else ImageFilter.makeColorFilter(faded(underlay), blurred, null)
+ }
drawBehind {
if (blur == null) {
drawRect(color, blendMode = BlendMode.Src)
@@ -158,5 +169,15 @@ private val Drawn = ImageFilter.makeColorFilter(
null
)
+/** Scales the opacity of what it is applied to by [fraction] */
+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,
+ )
+)
+
private val Replace = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC }
private val Within = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC_IN }
diff --git a/src/main/kotlin/com/lambda/gui/menu/Search.kt b/src/main/kotlin/com/lambda/gui/menu/Search.kt
index 4bd52697d..646950e99 100644
--- a/src/main/kotlin/com/lambda/gui/menu/Search.kt
+++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt
@@ -23,10 +23,12 @@ 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.clickgui.ClickGuiState
import com.lambda.gui.clickgui.Reveal
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
@@ -85,7 +87,12 @@ internal object Search {
if (score > 0) add(result() to score + bonus)
}
+ // Debug modules and what they hold are for developers: without developer mode, which
+ // is what shows their window, the search does not know them either
+ 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 ->
@@ -93,6 +100,7 @@ internal object Search {
}
ConfigLoader.configCategories.forEach { category ->
category.configs.forEach { config ->
+ if (hidden(config)) return@forEach
config.settingLayers.forEachEntry { _, single ->
val setting = single.entry
if (setting.visibility()) consider({ Result.OfSetting(setting, config) }, 0, setting.name)
diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt
index 1cdac730c..29a2cb12b 100644
--- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt
+++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt
@@ -43,6 +43,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
+import com.lambda.gui.component.SlidingText
import com.lambda.gui.core.observe
import com.lambda.module.modules.client.Style
import com.lambda.util.NamedEnum
@@ -176,6 +177,12 @@ val LocalContentColor = compositionLocalOf { Color.White }
*/
val LocalBackdropBlur = staticCompositionLocalOf { 0.dp }
+/**
+ * How much of the interface beneath a pane of glass is left to show through it, from all of it
+ * at one to none at zero. See [com.lambda.gui.component.glass].
+ */
+val LocalUnderlay = staticCompositionLocalOf { 1f }
+
/** Whether windows, panels and menus are drawn with a hairline border, see [com.lambda.gui.component.window] */
val LocalOutlines = staticCompositionLocalOf { true }
@@ -186,6 +193,7 @@ fun LambdaTheme(content: @Composable () -> Unit) {
val backdropBlur by observe { if (Style.blur) (Style.blurRadius / 2f).dp else 0.dp }
val font by observe { Style.font }
val outlines by observe { Style.outlines }
+ val underlay by observe { 1f - Style.layerFade }
CompositionLocalProvider(
LocalPalette provides palette,
LocalTypography provides remember(font) { Typography(font) },
@@ -194,6 +202,7 @@ fun LambdaTheme(content: @Composable () -> Unit) {
LocalContentColor provides palette.onSurface,
LocalBackdropBlur provides backdropBlur,
LocalOutlines provides outlines,
+ LocalUnderlay provides underlay,
content = content
)
}
@@ -228,6 +237,8 @@ fun Text(
maxLines: Int = Int.MAX_VALUE,
softWrap: Boolean = true,
) {
+ // A single line too long for its room is never cut short with dots: it slides under the pointer
+ if (maxLines == 1) return SlidingText(text, modifier, color, style)
BasicText(
text = text,
modifier = modifier,
diff --git a/src/main/kotlin/com/lambda/module/modules/client/Style.kt b/src/main/kotlin/com/lambda/module/modules/client/Style.kt
index 4e92dbd58..62a50005f 100644
--- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt
+++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt
@@ -54,6 +54,7 @@ object Style : Module(
val blur by setting("Blur", true, "Blurs what is behind windows for a frosted glass look")
val blurRadius by setting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur }
+ 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 }
val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass")
val glow by setting("Glow", true, "Surrounds the click GUI with a glow")
@@ -100,21 +101,21 @@ object Style : Module(
this,
primary = Color(214, 55, 88),
secondary = Color(176, 0, 70),
- surface = Color(252, 246, 247, 205),
- panel = Color(247, 244, 245, 222),
+ surface = Color(252, 246, 247, 135),
+ panel = Color(247, 244, 245, 175),
inset = Color(120, 0, 40, 34),
onSurface = Color(40, 14, 20),
onSurfaceVariant = Color(128, 102, 108),
header = Color(214, 55, 88, 242),
onHeader = Color(255, 250, 251),
- moduleEnabled = Color(250, 180, 198, 190),
- onModuleEnabled = Color(120, 0, 48),
+ moduleEnabled = Color(226, 72, 104, 190),
+ onModuleEnabled = Color(255, 250, 251),
control = Color(214, 55, 88, 242),
controlMenu = Color(246, 232, 235),
controlSelected = Color(236, 198, 208),
onControl = Color(40, 14, 20),
- track = Color(214, 196, 201, 228),
- input = Color(255, 255, 255, 235),
+ track = Color(214, 196, 201, 200),
+ input = Color(255, 255, 255, 200),
border = Color(216, 134, 150, 238),
textShadow = Color(0, 0, 0, 0),
)
From 86d21c68daf4cbb0cbb0896fe6228fda51427394 Mon Sep 17 00:00:00 2001
From: beanbag44 <107891830+beanbag44@users.noreply.github.com>
Date: Mon, 16 Nov 2026 01:40:31 +0000
Subject: [PATCH 04/34] attempt to keep all fonts the same visible size and
prevent line wrapping for settings
---
src/gametest/kotlin/com/lambda/GuiTest.kt | 11 +++++++++
.../com/lambda/gui/settings/SettingRow.kt | 4 ++--
src/main/kotlin/com/lambda/gui/theme/Theme.kt | 24 +++++++++++++++----
3 files changed, 32 insertions(+), 7 deletions(-)
diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt
index 0dca1296d..190d9f5d1 100644
--- a/src/gametest/kotlin/com/lambda/GuiTest.kt
+++ b/src/gametest/kotlin/com/lambda/GuiTest.kt
@@ -488,6 +488,17 @@ object GuiTest : FabricClientGameTest {
context.takeScreenshot("gui-12b-light-theme-settings")
context.closeGui()
+ // Another font, picked the same way: the interface keeps its proportions
+ context.openClickGui()
+ context.click(dpX = 830.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.waitTicks(10)
+ context.click(dpX = 760.0, dpY = 215.0)
+ context.waitTicks(10)
+ context.click(dpX = 760.0, dpY = 243.0)
+ context.waitTicks(10)
+ context.takeScreenshot("gui-13-fira-sans")
+ context.closeGui()
+
singleplayer.close()
}
diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt
index 53a59531d..1b5ef07fe 100644
--- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt
+++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt
@@ -249,7 +249,7 @@ private fun Slider(setting: NumericSetting) where T : Number, T : Compara
}
.padding(horizontal = 3.dp)
) {
- Text(setting.name, Modifier.weight(1f), colors.onControl)
+ Text(setting.name, Modifier.weight(1f), colors.onControl, maxLines = 1)
Text(label, Modifier.mouseClickable { typing = true }, colors.onControl, maxLines = 1)
}
}
@@ -281,7 +281,7 @@ private fun TextField(setting: StringSetting) {
val value by observe { setting.value }
// Text that runs over several lines is the one editor that cannot keep to a row
if (setting.multiline) Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(1.dp)) {
- Text(setting.name, Modifier.padding(start = 3.dp, top = 1.dp))
+ Text(setting.name, Modifier.padding(start = 3.dp, top = 1.dp), maxLines = 1)
TextInput(value, { setting.value = it }, Modifier.fillMaxWidth(), singleLine = false)
}
else Labeled(setting.name) {
diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt
index 29a2cb12b..2c948f03b 100644
--- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt
+++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt
@@ -21,6 +21,8 @@ import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.selection.LocalTextSelectionColors
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.runtime.Composable
+import androidx.compose.ui.unit.Density
+import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.ReadOnlyComposable
@@ -137,12 +139,12 @@ enum class GuiFont(override val displayName: String, val size: TextUnit, val sma
/** The text styles of a [GuiFont]. Lines are exactly as tall as the type, so rows are spaced by their padding alone. */
@Immutable
-class Typography(font: GuiFont) {
- val title = compact(font, font.size, font.titleWeight)
- val body = compact(font, font.size)
+class Typography(font: GuiFont, scale: Float = 1f) {
+ val title = compact(font, font.size * scale, font.titleWeight)
+ val body = compact(font, font.size * scale)
/** For what is secondary to the text beside it. No smaller than [body] in a pixel font, which cannot shrink. */
- val label = compact(font, font.smallSize)
+ val label = compact(font, font.smallSize * scale)
private fun compact(font: GuiFont, size: TextUnit, weight: FontWeight = FontWeight.Normal) = TextStyle(
fontFamily = font.family,
@@ -186,6 +188,9 @@ val LocalUnderlay = staticCompositionLocalOf { 1f }
/** Whether windows, panels and menus are drawn with a hairline border, see [com.lambda.gui.component.window] */
val LocalOutlines = staticCompositionLocalOf { true }
+/** How tall a line of the Minecraft font is, in dp, and so how tall any font's may be. A shade under, as heights round up. */
+private const val LINE_HEIGHT = 10.95f
+
@Composable
fun LambdaTheme(content: @Composable () -> Unit) {
val palette by observe { Style.palette }
@@ -193,10 +198,19 @@ fun LambdaTheme(content: @Composable () -> Unit) {
val backdropBlur by observe { if (Style.blur) (Style.blurRadius / 2f).dp else 0.dp }
val font by observe { Style.font }
val outlines by observe { Style.outlines }
+ // Every row is built around the line of the Minecraft font. A font that asks for a taller
+ // line at its size, for more room above and below its letters, is set that much smaller:
+ // its lines keep the room they ask for, and the rows keep their height.
+ val measurer = rememberTextMeasurer()
+ val typography = remember(font) {
+ if (font == GuiFont.Minecraft) return@remember Typography(font)
+ val line = measurer.measure("Ag", Typography(font).body, density = Density(1f)).size.height
+ Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f))
+ }
val underlay by observe { 1f - Style.layerFade }
CompositionLocalProvider(
LocalPalette provides palette,
- LocalTypography provides remember(font) { Typography(font) },
+ LocalTypography provides typography,
// Selected text is marked in the accent colour rather than in Compose's own blue
LocalTextSelectionColors provides TextSelectionColors(palette.primary, palette.primary.copy(alpha = 0.4f)),
LocalContentColor provides palette.onSurface,
From 30c898c7715bff9e330ff75103714a0e9739fa10 Mon Sep 17 00:00:00 2001
From: beanbag44 <107891830+beanbag44@users.noreply.github.com>
Date: Wed, 18 Nov 2026 01:07:00 +0000
Subject: [PATCH 05/34] smaller font and element height and optional embossing
---
src/gametest/kotlin/com/lambda/GuiTest.kt | 110 ++++----
.../com/lambda/config/entries/Setting.kt | 11 +
.../com/lambda/config/settings/CharSetting.kt | 17 ++
.../lambda/config/settings/FunctionSetting.kt | 9 +
.../lambda/config/settings/NumericSetting.kt | 80 +++++-
.../lambda/config/settings/StringSetting.kt | 28 +++
.../settings/collections/CollectionSetting.kt | 6 +
.../settings/comparable/BooleanSetting.kt | 33 +++
.../config/settings/comparable/EnumSetting.kt | 21 ++
.../settings/complex/BlockPosSetting.kt | 33 +++
.../config/settings/complex/BlockSetting.kt | 6 +
.../config/settings/complex/ColorSetting.kt | 6 +
.../config/settings/complex/KeybindSetting.kt | 65 +++++
.../config/settings/complex/Vec3dSetting.kt | 19 ++
src/main/kotlin/com/lambda/gui/LambdaGui.kt | 4 +-
.../com/lambda/gui/clickgui/CategoryWindow.kt | 24 +-
.../com/lambda/gui/component/Controls.kt | 14 +-
.../com/lambda/gui/settings/SettingRow.kt | 234 +-----------------
src/main/kotlin/com/lambda/gui/theme/Theme.kt | 17 +-
.../com/lambda/module/modules/client/Style.kt | 7 +-
20 files changed, 456 insertions(+), 288 deletions(-)
diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt
index 190d9f5d1..fda919ec8 100644
--- a/src/gametest/kotlin/com/lambda/GuiTest.kt
+++ b/src/gametest/kotlin/com/lambda/GuiTest.kt
@@ -21,6 +21,7 @@ import com.lambda.gui.GuiConfig
import com.lambda.gui.LambdaGui
import com.lambda.module.ModuleRegistry
import com.lambda.module.modules.client.AutoUpdater
+import com.lambda.module.modules.client.Style
import com.lambda.module.modules.hud.Armor
import com.lambda.module.modules.hud.Coordinates
import com.lambda.module.modules.hud.Fps
@@ -55,37 +56,46 @@ object GuiTest : FabricClientGameTest {
context.waitTicks(10)
context.takeScreenshot("gui-1-title-screen")
+ // That was the interface as it comes. The places clicked from here on are those of the
+ // Minecraft font at its full size and of rows 13 dp tall, which is set here rather than
+ // left to the defaults, so that the defaults can change without moving every click.
+ context.runOnClient {
+ Style.fontSize = 1f
+ Style.elementHeight = 13f
+ }
+ context.waitTicks(5)
+
// A left click on the first module of the first window toggles it
val enabledBefore = context.enabledModules()
- context.click(dpX = 110.0, dpY = 115.0)
+ context.click(dpX = 150.0, dpY = 115.0)
check(context.enabledModules() != enabledBefore) { "Clicking a module did not toggle it" }
context.takeScreenshot("gui-1-module-enabled")
- context.click(dpX = 110.0, dpY = 115.0)
+ context.click(dpX = 150.0, dpY = 115.0)
// A module is toggled the moment the button goes down, not when it is let go
val enabledBeforePress = context.enabledModules()
- context.input.setCursorPos(110.0 * DENSITY, 115.0 * DENSITY)
+ context.input.setCursorPos(150.0 * DENSITY, 115.0 * DENSITY)
context.waitTicks(2)
context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(3)
check(context.enabledModules() != enabledBeforePress) { "A module was not toggled by the press" }
context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(3)
- context.click(dpX = 110.0, dpY = 115.0)
+ context.click(dpX = 150.0, dpY = 115.0)
// A name too long for its window slides along while the pointer rests on it, and home after
- context.input.setCursorPos(210.0 * DENSITY, 193.0 * DENSITY)
+ context.input.setCursorPos(240.0 * DENSITY, 193.0 * DENSITY)
context.waitTicks(30)
context.takeScreenshot("gui-1a-long-name-hovered")
- context.input.setCursorPos(210.0 * DENSITY, 60.0 * DENSITY)
+ context.input.setCursorPos(240.0 * DENSITY, 60.0 * DENSITY)
context.waitTicks(10)
context.takeScreenshot("gui-1b-long-name-left")
// A window goes exactly where it is dragged by its header...
- context.input.setCursorPos(630.0 * DENSITY, 101.0 * DENSITY)
+ context.input.setCursorPos(620.0 * DENSITY, 101.0 * DENSITY)
context.dragBy(3.5, 7.5)
val free = context.windowPlacement("Network")
- check(abs(free.x - 586.5f) < 0.6f && abs(free.y - 101.5f) < 0.6f) { "A dragged window did not follow the pointer: $free" }
+ check(abs(free.x - 576.5f) < 0.6f && abs(free.y - 101.5f) < 0.6f) { "A dragged window did not follow the pointer: $free" }
// ...and with the snap key held it lines up with its neighbours instead
context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT)
@@ -93,7 +103,7 @@ object GuiTest : FabricClientGameTest {
context.dragBy(2.0, 2.0)
context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT)
val snapped = context.windowPlacement("Network")
- check(abs(snapped.x - 583f) < 0.1f) { "A window dragged with the snap key held did not snap back between its neighbours: $snapped" }
+ check(abs(snapped.x - 573f) < 0.1f) { "A window dragged with the snap key held did not snap back between its neighbours: $snapped" }
// Resetting the layout forgets every placement, which puts the windows back in their row
context.runOnClient { GuiConfig.resetWindows() }
@@ -101,11 +111,11 @@ object GuiTest : FabricClientGameTest {
check(context.computeOnClient { GuiConfig.windows.isEmpty() }) { "Resetting the layout left a window placed" }
// A right click pops its settings out beside it, over the next window, which blurs behind it
- context.click(dpX = 110.0, dpY = 115.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 150.0, dpY = 115.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.takeScreenshot("gui-2-module-settings")
// Right clicking another module straight away has one panel fold while the other opens
- context.input.setCursorPos(110.0 * DENSITY, 128.0 * DENSITY)
+ context.input.setCursorPos(150.0 * DENSITY, 128.0 * DENSITY)
context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.waitTicks(1)
context.takeScreenshot("gui-2a-switching-settings")
@@ -113,42 +123,42 @@ object GuiTest : FabricClientGameTest {
// KillAura sorts its settings into tabs and groups: a group unfolds into a darker block,
// and the page slides over when another tab is picked
- context.click(dpX = 110.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
// What every module has is kept off its own settings, on pages the strip at the top turns to
- context.click(dpX = 268.5, dpY = 198.0)
+ context.click(dpX = 298.5, dpY = 198.0)
context.takeScreenshot("gui-2c2-module-page")
- context.input.setCursorPos(330.0 * DENSITY, 198.0 * DENSITY)
+ context.input.setCursorPos(360.0 * DENSITY, 198.0 * DENSITY)
context.waitTicks(2)
context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(1)
context.takeScreenshot("gui-2c3-page-turning")
context.waitTicks(10)
context.takeScreenshot("gui-2c1-automation-page")
- context.input.setCursorPos(231.0 * DENSITY, 247.0 * DENSITY)
+ context.input.setCursorPos(261.0 * DENSITY, 247.0 * DENSITY)
context.waitTicks(2)
context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(1)
context.takeScreenshot("gui-2c0-group-unfolding")
context.waitTicks(10)
context.takeScreenshot("gui-2c-group")
- context.click(dpX = 231.0, dpY = 247.0)
- context.click(dpX = 206.5, dpY = 198.0)
+ context.click(dpX = 261.0, dpY = 247.0)
+ context.click(dpX = 236.5, dpY = 198.0)
// A setting is changed when the button is let go: pressed on a toggle and let go off it, nothing changes
- context.input.setCursorPos(220.0 * DENSITY, 231.0 * DENSITY)
+ context.input.setCursorPos(250.0 * DENSITY, 231.0 * DENSITY)
context.waitTicks(2)
context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(3)
context.takeScreenshot("gui-2g3-setting-pressed")
- context.input.setCursorPos(220.0 * DENSITY, 150.0 * DENSITY)
+ context.input.setCursorPos(250.0 * DENSITY, 150.0 * DENSITY)
context.waitTicks(2)
context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(3)
context.takeScreenshot("gui-2g4-setting-click-cancelled")
// An enum lists its options over the panel, without moving the settings under it
- context.input.setCursorPos(290.0 * DENSITY, 273.0 * DENSITY)
+ context.input.setCursorPos(320.0 * DENSITY, 273.0 * DENSITY)
context.waitTicks(2)
context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(1)
@@ -161,7 +171,7 @@ object GuiTest : FabricClientGameTest {
context.waitTicks(2)
context.takeScreenshot("gui-2g2-dropdown-folded-in")
context.waitTicks(3)
- context.input.setCursorPos(266.0 * DENSITY, 216.0 * DENSITY)
+ context.input.setCursorPos(296.0 * DENSITY, 216.0 * DENSITY)
context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(1)
context.takeScreenshot("gui-2d-tab-changing")
@@ -169,7 +179,7 @@ object GuiTest : FabricClientGameTest {
context.takeScreenshot("gui-2e-tab-changed")
// A collection is edited in a window of its own, each entry with its icon
- context.input.setCursorPos(330.0 * DENSITY, 260.0 * DENSITY)
+ context.input.setCursorPos(360.0 * DENSITY, 260.0 * DENSITY)
context.waitTicks(2)
context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT)
context.waitTicks(1)
@@ -188,13 +198,13 @@ object GuiTest : FabricClientGameTest {
// Settings too long for the room under their module scroll, and the top edge of the
// panel then has a grip that drags it taller, up past the module
- context.click(dpX = 330.0, dpY = 198.0)
+ context.click(dpX = 360.0, dpY = 198.0)
// Unfolded from the last up, so none moves before it is clicked
- for (y in listOf(289.0, 275.0, 261.0, 247.0)) context.click(dpX = 231.0, dpY = y)
+ for (y in listOf(289.0, 275.0, 261.0, 247.0)) context.click(dpX = 261.0, dpY = y)
context.takeScreenshot("gui-2i-scrolling")
// The wheel sets the list off fast and lets it glide to rest
- context.input.setCursorPos(260.0 * DENSITY, 400.0 * DENSITY)
+ context.input.setCursorPos(290.0 * DENSITY, 400.0 * DENSITY)
context.waitTicks(2)
context.input.scroll(-2.0)
context.waitTicks(1)
@@ -203,7 +213,7 @@ object GuiTest : FabricClientGameTest {
context.takeScreenshot("gui-2i2-wheel-settled")
context.input.scroll(10.0)
context.waitTicks(15)
- context.input.setCursorPos(287.0 * DENSITY, 189.0 * DENSITY)
+ context.input.setCursorPos(317.0 * DENSITY, 189.0 * DENSITY)
context.waitTicks(2)
context.dragBy(0.0, -60.0)
context.takeScreenshot("gui-2j-extended")
@@ -213,12 +223,12 @@ object GuiTest : FabricClientGameTest {
context.takeScreenshot("gui-2k-extended-to-the-bar")
// Folding the category away takes the settings hanging off it along
- context.click(dpX = 110.0, dpY = 101.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 150.0, dpY = 101.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.takeScreenshot("gui-2f-category-folded")
- context.click(dpX = 110.0, dpY = 101.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 150.0, dpY = 101.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
// The settings of the Style module hold the colour pickers
- context.click(dpX = 830.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.takeScreenshot("gui-2b-style-settings")
// The first of the buttons opens a menu, which Escape closes without closing the GUI
@@ -278,13 +288,13 @@ object GuiTest : FabricClientGameTest {
context.waitTicks(10)
context.input.pressKey(GLFW.GLFW_KEY_ENTER)
context.waitTicks(15)
- context.click(dpX = 110.0, dpY = 219.5, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 150.0, dpY = 219.5, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.takeScreenshot("gui-4c-block-settings")
- context.click(dpX = 320.0, dpY = 242.0)
+ context.click(dpX = 350.0, dpY = 242.0)
context.takeScreenshot("gui-4d-block-list")
// Lists that scroll have a scrollbar on their right, like every other
- context.input.setCursorPos(370.0 * DENSITY, 346.0 * DENSITY)
+ context.input.setCursorPos(400.0 * DENSITY, 346.0 * DENSITY)
context.waitTicks(2)
context.input.scroll(-5.0)
context.waitTicks(15)
@@ -332,7 +342,7 @@ object GuiTest : FabricClientGameTest {
// A tooltip that is up when the GUI closes goes with it, and is not back when it reopens
context.input.setCursorPos(300.0 * DENSITY, 400.0 * DENSITY)
context.waitTicks(2)
- context.input.setCursorPos(110.0 * DENSITY, 115.0 * DENSITY)
+ context.input.setCursorPos(150.0 * DENSITY, 115.0 * DENSITY)
context.waitTicks(40)
context.takeScreenshot("gui-6a-tooltip")
context.input.pressKey(GLFW.GLFW_KEY_Y)
@@ -443,9 +453,9 @@ object GuiTest : FabricClientGameTest {
// A panel closed with a menu open on one of its settings takes the menu with it as it folds
context.openClickGui()
- context.click(dpX = 110.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.waitTicks(10)
- context.click(dpX = 290.0, dpY = 273.0)
+ context.click(dpX = 320.0, dpY = 273.0)
context.waitTicks(10)
context.takeScreenshot("gui-10a-panel-with-menu")
context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY)
@@ -461,7 +471,7 @@ object GuiTest : FabricClientGameTest {
// Settings kept open come back once the categories have unfolded, not riding their row down
context.runOnClient { GuiConfig.keepSettingsOpen = true }
- context.click(dpX = 110.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.waitTicks(10)
context.closeGui()
context.runOnClient { LambdaGui.open(LambdaGui.Screen.ClickGui) }
@@ -476,29 +486,43 @@ object GuiTest : FabricClientGameTest {
// The light theme, picked the way a player picks it, in the settings of Style
context.openClickGui()
- context.click(dpX = 830.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.waitTicks(10)
- context.click(dpX = 760.0, dpY = 201.0)
+ context.click(dpX = 730.0, dpY = 201.0)
context.waitTicks(10)
- context.click(dpX = 760.0, dpY = 243.0)
+ context.click(dpX = 730.0, dpY = 243.0)
context.waitTicks(10)
context.takeScreenshot("gui-12a-light-theme")
- context.click(dpX = 110.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.waitTicks(10)
context.takeScreenshot("gui-12b-light-theme-settings")
context.closeGui()
// Another font, picked the same way: the interface keeps its proportions
context.openClickGui()
- context.click(dpX = 830.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
context.waitTicks(10)
- context.click(dpX = 760.0, dpY = 215.0)
+ context.click(dpX = 730.0, dpY = 215.0)
context.waitTicks(10)
- context.click(dpX = 760.0, dpY = 243.0)
+ context.click(dpX = 730.0, dpY = 243.0)
context.waitTicks(10)
context.takeScreenshot("gui-13-fira-sans")
context.closeGui()
+ // Smaller text and taller modules, set on their sliders: the rows follow both
+ context.openClickGui()
+ context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT)
+ context.waitTicks(10)
+ context.input.setCursorPos(700.0 * DENSITY, 243.0 * DENSITY)
+ context.waitTicks(2)
+ context.dragBy(-30.0, 0.0)
+ context.input.setCursorPos(680.0 * DENSITY, 257.0 * DENSITY)
+ context.waitTicks(2)
+ context.dragBy(40.0, 0.0)
+ context.waitTicks(10)
+ context.takeScreenshot("gui-14-font-size-and-module-height")
+ context.closeGui()
+
singleplayer.close()
}
diff --git a/src/main/kotlin/com/lambda/config/entries/Setting.kt b/src/main/kotlin/com/lambda/config/entries/Setting.kt
index 9f367d26f..dc9dcecbf 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
@@ -142,6 +143,16 @@ abstract class Setting(
core = originalCore
}
+ /**
+ * The setting's editor in the GUI: what its row in a list of settings holds, its name
+ * included. The row around it, which shows the description as a tooltip and is lit when
+ * the search points at it, is [com.lambda.gui.settings.SettingRow]'s.
+ *
+ * A setting that draws nothing here can only be changed with the config command.
+ */
+ @Composable
+ open fun compose() {}
+
open fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(string("value as JSON")) { value ->
executeWithResult {
diff --git a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt
index c2962b58a..3326afff1 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,6 +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.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
@@ -40,6 +48,15 @@ class CharSetting(
defaultValue: Char,
visibility: () -> Boolean
) : Setting(name, description, defaultValue, layer, config, visibility) {
+ /** A field one character wide: whatever is typed last replaces what it holds */
+ @Composable
+ override fun compose() {
+ 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 ->
executeWithResult {
diff --git a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt
index 9dc2a42f0..c5bdec965 100644
--- a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt
@@ -17,9 +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.component.Button
+import com.lambda.gui.component.RowHeight
class FunctionSetting R, R>(
name: String,
@@ -29,4 +35,7 @@ class FunctionSetting R, R>(
layer: SettingEntryLayer, T>,
visibility: () -> Boolean
) : Setting(name, description, defaultValue, layer, config, visibility) {
+ /** A button that calls the function */
+ @Composable
+ override fun compose() = Button(name, Modifier.fillMaxWidth().height(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 e2d4a9d4d..690dbe1c5 100644
--- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt
+++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt
@@ -17,13 +17,42 @@
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.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.Size
+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.component.NumberInput
+import com.lambda.gui.component.RowHeight
+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.Radius
+import com.lambda.gui.theme.Text
import java.text.NumberFormat
import java.util.*
+import kotlin.math.roundToInt
+import kotlin.math.roundToLong
/**
* @see [com.lambda.config.Config]
@@ -50,9 +79,56 @@ abstract class NumericSetting(
override fun toString() = "${formatter.format(value)}$unit"
/**
- * Subclasses must implement this to provide their specific slider widget.
- */
+ * A bar filled up to the value. Dragging anywhere on it sets the value; clicking the number
+ * swaps the bar for a text field to type an exact one, for ranges with more steps than pixels.
+ */
+ @Composable
+ override fun compose() {
+ val colors = LambdaTheme.colors
+ val value by observe { value }
+ val label by observe { toString() }
+ var typing by remember { mutableStateOf(false) }
+ if (typing) {
+ NumberInput(value, { this.value = convert(it) }, Modifier.fillMaxWidth(), focused = true) {
+ typing = false
+ }
+ return
+ }
+
+ val min = range.start.toDouble()
+ val max = range.endInclusive.toDouble()
+ // The value moves in steps; the bar glides from one to the next
+ val fraction by animateFloatAsState(((value.toDouble() - min) / (max - min)).toFloat().coerceIn(0f, 1f))
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .heightIn(min = RowHeight)
+ .clip(RoundedCornerShape(Radius.Small))
+ .background(colors.track)
+ .drawBehind { drawRect(colors.primary, size = Size(size.width * fraction, size.height)) }
+ .scrubbable { position, size ->
+ val steps = ((position.x / size.width).coerceIn(0f, 1f) * (max - min) / step.toDouble()).roundToLong()
+ this.value = convert(min + steps * step.toDouble())
+ }
+ .padding(horizontal = 3.dp)
+ ) {
+ Text(name, Modifier.weight(1f), colors.onControl, maxLines = 1)
+ Text(label, Modifier.mouseClickable { typing = true }, colors.onControl, maxLines = 1)
+ }
+ }
+
+ /** A double as the setting's own number type; setting it clamps it to the range */
+ @Suppress("UNCHECKED_CAST")
+ private fun convert(number: Double): T =
+ when (value) {
+ is Int -> number.roundToInt()
+ is Long -> number.roundToLong()
+ is Float -> number.toFloat()
+ else -> number
+ } as T
}
@Suppress("unchecked_cast")
diff --git a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt
index 3d8920ac6..f47bd69e1 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,6 +37,11 @@ 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.component.TextInput
+import com.lambda.gui.core.observe
+import com.lambda.gui.settings.Labeled
+import com.lambda.gui.settings.TextFieldWidth
+import com.lambda.gui.theme.Text
import com.lambda.util.extension.CommandBuilder
import net.minecraft.command.CommandRegistryAccess
@@ -44,6 +58,20 @@ class StringSetting(
var multiline: Boolean = false,
) : Setting(name, description, defaultValue, layer, config, visibility) {
+ /** A field to type into beside the name, or under it for text of several lines */
+ @Composable
+ override fun compose() {
+ val value by observe { value }
+ // Text that runs over several lines is the one editor that cannot keep to a row
+ if (multiline) Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ Text(name, Modifier.padding(start = 3.dp, 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(TextFieldWidth))
+ }
+ }
+
override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) {
required(greedyString(name)) { parameter ->
execute {
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 98399ec4b..7d196209b 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,6 +27,7 @@ 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.settings.CollectionButton
import com.lambda.threading.runSafe
import net.minecraft.item.ItemStack
import tools.jackson.databind.JavaType
@@ -67,6 +69,10 @@ open class CollectionSetting