From 4f3b7a790cb13dd4abf18b1212939122ebfb1b84 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:02:34 +0000 Subject: [PATCH 01/34] rewrite --- README.md | 2 +- build.gradle.kts | 32 +- gradle.properties | 4 +- src/gametest/kotlin/com/lambda/GuiTest.kt | 517 ++++ src/gametest/resources/fabric.mod.json | 4 + .../lambda/mixin/MinecraftClientMixin.java | 10 +- .../com/lambda/mixin/input/KeyboardMixin.java | 5 +- .../mixin/render/ComposeDelayMixin.java | 46 + .../mixin/render/GameRendererMixin.java | 8 +- .../lambda/mixin/render/GuiRendererMixin.java | 59 + .../render/InactivityFpsLimiterMixin.java | 49 + .../com/lambda/mixin/render/ScreenMixin.java | 26 - src/main/kotlin/com/lambda/Lambda.kt | 11 +- src/main/kotlin/com/lambda/config/Config.kt | 4 +- .../com/lambda/config/entries/Setting.kt | 3 - .../com/lambda/config/settings/CharSetting.kt | 3 - .../lambda/config/settings/FunctionSetting.kt | 5 - .../lambda/config/settings/NumericSetting.kt | 41 - .../lambda/config/settings/StringSetting.kt | 17 - .../collections/BlockCollectionSetting.kt | 8 +- .../collections/ClassCollectionSetting.kt | 5 +- .../settings/collections/CollectionSetting.kt | 127 +- .../collections/FluidCollectionSetting.kt | 5 +- .../collections/ItemCollectionSetting.kt | 7 +- .../config/settings/collections/MapSetting.kt | 2 - .../settings/comparable/BooleanSetting.kt | 6 - .../config/settings/comparable/EnumSetting.kt | 23 - .../settings/complex/BlockPosSetting.kt | 19 - .../config/settings/complex/BlockSetting.kt | 3 - .../config/settings/complex/ColorSetting.kt | 6 - .../config/settings/complex/KeybindSetting.kt | 80 - .../config/settings/complex/Vec3dSetting.kt | 6 - .../config/settings/numeric/DoubleSetting.kt | 16 - .../config/settings/numeric/FloatSetting.kt | 15 - .../config/settings/numeric/IntegerSetting.kt | 5 - .../config/settings/numeric/LongSetting.kt | 12 - .../com/lambda/event/events/GuiEvent.kt | 14 - .../graphics/mc/LambdaRenderPipelines.kt | 59 + src/main/kotlin/com/lambda/gui/DearImGui.kt | 152 -- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 118 + src/main/kotlin/com/lambda/gui/GuiScreen.kt | 198 ++ src/main/kotlin/com/lambda/gui/LambdaGui.kt | 290 +++ .../kotlin/com/lambda/gui/LambdaScreen.kt | 72 - src/main/kotlin/com/lambda/gui/MenuBar.kt | 534 ----- .../com/lambda/gui/OverlayBackgroundScreen.kt | 2 +- src/main/kotlin/com/lambda/gui/Snap.kt | 123 + .../com/lambda/gui/clickgui/CategoryWindow.kt | 255 ++ .../com/lambda/gui/clickgui/ClickGui.kt | 194 ++ .../kotlin/com/lambda/gui/clickgui/Reveal.kt | 89 + .../com/lambda/gui/clickgui/SettingsPanel.kt | 446 ++++ .../com/lambda/gui/component/Controls.kt | 494 ++++ .../gui/{Layout.kt => component/Images.kt} | 16 +- .../com/lambda/gui/component/Pointer.kt | 267 +++ .../kotlin/com/lambda/gui/component/Popups.kt | 694 ++++++ .../com/lambda/gui/component/SlidingText.kt | 119 + .../com/lambda/gui/component/Surface.kt | 162 ++ .../lambda/gui/components/ClickGuiLayout.kt | 558 ----- .../com/lambda/gui/components/HudGuiLayout.kt | 298 --- .../com/lambda/gui/components/ModuleEntry.kt | 55 - .../com/lambda/gui/components/QuickSearch.kt | 342 --- .../lambda/gui/components/SettingsWidget.kt | 147 -- .../gui/{snap/Guide.kt => core/Frames.kt} | 20 +- .../kotlin/com/lambda/gui/core/GlState.kt | 188 ++ .../kotlin/com/lambda/gui/core/Observe.kt | 81 + .../kotlin/com/lambda/gui/core/Retained.kt | 52 + .../kotlin/com/lambda/gui/core/SceneHost.kt | 164 ++ .../kotlin/com/lambda/gui/core/SceneInput.kt | 168 ++ .../com/lambda/gui/core/ScenePlatform.kt | 119 + .../kotlin/com/lambda/gui/dsl/ImGuiBuilder.kt | 2078 ----------------- .../kotlin/com/lambda/gui/dsl/ImStorageDsl.kt | 59 - src/main/kotlin/com/lambda/gui/hud/Hud.kt | 169 ++ .../kotlin/com/lambda/gui/hud/HudEditor.kt | 412 ++++ .../kotlin/com/lambda/gui/menu/Dialogs.kt | 211 ++ .../kotlin/com/lambda/gui/menu/MenuBar.kt | 384 +++ src/main/kotlin/com/lambda/gui/menu/Search.kt | 117 + .../com/lambda/gui/render/BlurPyramid.kt | 128 + .../com/lambda/gui/render/GuiCompositor.kt | 129 + .../kotlin/com/lambda/gui/render/ItemAtlas.kt | 255 ++ .../lambda/gui/settings/CollectionEditor.kt | 185 ++ .../com/lambda/gui/settings/ColorPicker.kt | 218 ++ .../com/lambda/gui/settings/SettingRow.kt | 374 +++ .../com/lambda/gui/settings/SettingsList.kt | 204 ++ src/main/kotlin/com/lambda/gui/snap/RectF.kt | 27 - .../kotlin/com/lambda/gui/snap/SnapHandler.kt | 308 --- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 251 ++ .../kotlin/com/lambda/module/HudModule.kt | 27 +- src/main/kotlin/com/lambda/module/Module.kt | 17 +- .../module/modules/client/AutoUpdater.kt | 181 +- .../lambda/module/modules/client/Client.kt | 2 +- .../com/lambda/module/modules/client/Style.kt | 212 ++ .../combat/autodisconnect/AutoDisconnect.kt | 10 +- .../autodisconnect/DisconnectDetailsWidget.kt | 12 +- .../lambda/module/modules/hud/AccountName.kt | 12 +- .../com/lambda/module/modules/hud/Armor.kt | 70 + .../com/lambda/module/modules/hud/Baritone.kt | 28 +- .../lambda/module/modules/hud/Coordinates.kt | 43 +- .../com/lambda/module/modules/hud/Fps.kt | 11 +- .../lambda/module/modules/hud/ModuleList.kt | 43 +- .../com/lambda/module/modules/hud/Rotation.kt | 15 +- .../lambda/module/modules/hud/Speedometer.kt | 11 +- .../lambda/module/modules/hud/TaskFlowHud.kt | 11 +- .../com/lambda/module/modules/hud/Tps.kt | 63 +- .../lambda/module/modules/hud/Watermark.kt | 22 +- .../module/modules/movement/BackTrack.kt | 4 +- .../lambda/module/modules/movement/Blink.kt | 4 +- .../module/modules/player/InventoryMove.kt | 5 +- .../lambda/module/modules/player/Replay.kt | 74 +- .../com/lambda/util/CommunicationUtils.kt | 8 +- src/main/kotlin/com/lambda/util/InputUtils.kt | 82 +- .../kotlin/com/lambda/util/WindowUtils.kt | 2 +- .../lambda/shaders/core/gui_blur_down.fsh | 26 + .../lambda/shaders/core/gui_blur_up.fsh | 30 + .../lambda/shaders/core/gui_composite.fsh | 41 + src/main/resources/lambda.accesswidener | 1 + src/main/resources/lambda.mixins.json | 3 + 115 files changed, 8789 insertions(+), 5471 deletions(-) create mode 100644 src/gametest/kotlin/com/lambda/GuiTest.kt create mode 100644 src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java create mode 100644 src/main/java/com/lambda/mixin/render/GuiRendererMixin.java create mode 100644 src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java delete mode 100644 src/main/kotlin/com/lambda/gui/DearImGui.kt create mode 100644 src/main/kotlin/com/lambda/gui/GuiConfig.kt create mode 100644 src/main/kotlin/com/lambda/gui/GuiScreen.kt create mode 100644 src/main/kotlin/com/lambda/gui/LambdaGui.kt delete mode 100644 src/main/kotlin/com/lambda/gui/LambdaScreen.kt delete mode 100644 src/main/kotlin/com/lambda/gui/MenuBar.kt create mode 100644 src/main/kotlin/com/lambda/gui/Snap.kt create mode 100644 src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt create mode 100644 src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt create mode 100644 src/main/kotlin/com/lambda/gui/clickgui/Reveal.kt create mode 100644 src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt create mode 100644 src/main/kotlin/com/lambda/gui/component/Controls.kt rename src/main/kotlin/com/lambda/gui/{Layout.kt => component/Images.kt} (56%) create mode 100644 src/main/kotlin/com/lambda/gui/component/Pointer.kt create mode 100644 src/main/kotlin/com/lambda/gui/component/Popups.kt create mode 100644 src/main/kotlin/com/lambda/gui/component/SlidingText.kt create mode 100644 src/main/kotlin/com/lambda/gui/component/Surface.kt delete mode 100644 src/main/kotlin/com/lambda/gui/components/ClickGuiLayout.kt delete mode 100644 src/main/kotlin/com/lambda/gui/components/HudGuiLayout.kt delete mode 100644 src/main/kotlin/com/lambda/gui/components/ModuleEntry.kt delete mode 100644 src/main/kotlin/com/lambda/gui/components/QuickSearch.kt delete mode 100644 src/main/kotlin/com/lambda/gui/components/SettingsWidget.kt rename src/main/kotlin/com/lambda/gui/{snap/Guide.kt => core/Frames.kt} (58%) create mode 100644 src/main/kotlin/com/lambda/gui/core/GlState.kt create mode 100644 src/main/kotlin/com/lambda/gui/core/Observe.kt create mode 100644 src/main/kotlin/com/lambda/gui/core/Retained.kt create mode 100644 src/main/kotlin/com/lambda/gui/core/SceneHost.kt create mode 100644 src/main/kotlin/com/lambda/gui/core/SceneInput.kt create mode 100644 src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt delete mode 100644 src/main/kotlin/com/lambda/gui/dsl/ImGuiBuilder.kt delete mode 100644 src/main/kotlin/com/lambda/gui/dsl/ImStorageDsl.kt create mode 100644 src/main/kotlin/com/lambda/gui/hud/Hud.kt create mode 100644 src/main/kotlin/com/lambda/gui/hud/HudEditor.kt create mode 100644 src/main/kotlin/com/lambda/gui/menu/Dialogs.kt create mode 100644 src/main/kotlin/com/lambda/gui/menu/MenuBar.kt create mode 100644 src/main/kotlin/com/lambda/gui/menu/Search.kt create mode 100644 src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt create mode 100644 src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt create mode 100644 src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt create mode 100644 src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt create mode 100644 src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt create mode 100644 src/main/kotlin/com/lambda/gui/settings/SettingRow.kt create mode 100644 src/main/kotlin/com/lambda/gui/settings/SettingsList.kt delete mode 100644 src/main/kotlin/com/lambda/gui/snap/RectF.kt delete mode 100644 src/main/kotlin/com/lambda/gui/snap/SnapHandler.kt create mode 100644 src/main/kotlin/com/lambda/gui/theme/Theme.kt create mode 100644 src/main/kotlin/com/lambda/module/modules/client/Style.kt create mode 100644 src/main/kotlin/com/lambda/module/modules/hud/Armor.kt create mode 100644 src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh create mode 100644 src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh create mode 100644 src/main/resources/assets/lambda/shaders/core/gui_composite.fsh diff --git a/README.md b/README.md index 5100a22c6..3e2c92e7e 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Find our backup matrix space at [\#lambda-client:matrix.org](https://app.element ### Sophisticated User Experience * **Fine-Grained Control:** Access over **1000+ settings**, allowing you to tune every aspect of the client to your exact needs. -* **Advanced GUI:** The **Dear ImGui** interface is designed for clarity and depth, featuring quick search, context menus, and easy keybind editing. +* **Advanced GUI:** The **Jetpack Compose** interface is designed for clarity and depth, featuring quick search, context menus, and easy keybind editing. * **Automation Profiles:** Use linkable configs to apply complex configurations across multiple modules instantly. ### Stability & Safety diff --git a/build.gradle.kts b/build.gradle.kts index f96218fba..970799b46 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -32,11 +32,16 @@ val kotlinVersion: String by project val ktorVersion: String by project val jacksonVersion: String by project val mockkVersion: String by project -val spairVersion: String by project val lwjglVersion: String by project val sodiumVersion: String by project val litematicaVersion: String by project val maLiLibVersion: String by project +val composeVersion: String by project +val skikoVersion: String by project + +// Skiko (the Skia binding Compose draws with) ships its native library in one artifact per platform. +// Every platform is bundled so a single jar runs everywhere; skiko loads the one matching the host. +val skikoPlatforms = listOf("windows-x64", "windows-arm64", "linux-x64", "linux-arm64", "macos-x64", "macos-arm64") val libs = file("libs") val targets = listOf("fabric.mod.json") @@ -46,6 +51,7 @@ val replacements = file("gradle.properties").inputStream().use { stream -> plugins { kotlin("jvm") version "2.3.21" + kotlin("plugin.compose") version "2.3.21" id("org.jetbrains.dokka") version "2.1.0" id("fabric-loom") version "1.17-SNAPSHOT" id("com.gradleup.shadow") version "9.3.0" @@ -72,6 +78,10 @@ configurations.all { if (requested.group == "org.lwjgl") { useVersion(lwjglVersion) } + // The natives must be the exact build the skiko classes Compose pulls in were compiled against + if (requested.group == "org.jetbrains.skiko") { + useVersion(skikoVersion) + } } } @@ -81,6 +91,7 @@ repositories { maven("https://maven.2b2t.vc/releases") // Baritone maven("https://jitpack.io") // KDiscordIPC maven("https://api.modrinth.com/maven") + google() // AndroidX libraries Compose depends on mavenCentral() // Allow the use of local libraries @@ -169,11 +180,20 @@ dependencies { includeLib("com.github.beanbag44:KDiscordIPC:$discordIPCVersion") includeLib("com.pngencoder:pngencoder:$pngEncoderVersion") - includeLib("com.lambda:lambda-imgui-java-binding:$spairVersion") - includeLib("com.lambda:lambda-imgui-java-lwjgl3:$spairVersion") - includeLib("com.lambda:lambda-imgui-java-natives-windows:$spairVersion") - includeLib("com.lambda:lambda-imgui-java-natives-linux:$spairVersion") - includeLib("com.lambda:lambda-imgui-java-natives-macos:$spairVersion") + + // Compose. Kotlin and kotlinx are left out because fabric-language-kotlin already provides them + listOf("runtime:runtime", "ui:ui", "foundation:foundation").forEach { module -> + shadowLib("org.jetbrains.compose.$module-desktop:$composeVersion") { + exclude(group = "org.jetbrains.kotlin") + exclude(group = "org.jetbrains.kotlinx") + } + } + skikoPlatforms.forEach { platform -> + shadowLib("org.jetbrains.skiko:skiko-awt-runtime-$platform:$skikoVersion") { + exclude(group = "org.jetbrains.kotlin") + exclude(group = "org.jetbrains.kotlinx") + } + } // Ktor includeLib("io.ktor:ktor-client-core:$ktorVersion") diff --git a/gradle.properties b/gradle.properties index df5d67332..3c1beccc6 100644 --- a/gradle.properties +++ b/gradle.properties @@ -37,7 +37,9 @@ classGraphVersion=4.8.184 ktorVersion=3.3.3 jacksonVersion=3.1.4 mockkVersion=1.14.7 -spairVersion=1.90.0 +composeVersion=1.12.2 +# Must be the skiko version the Compose version above depends on +skikoVersion=0.150.2 # Fabric https://fabricmc.net/develop/ fabricLoaderVersion=0.19.5 diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt new file mode 100644 index 000000000..e6f4e967c --- /dev/null +++ b/src/gametest/kotlin/com/lambda/GuiTest.kt @@ -0,0 +1,517 @@ +/* + * 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 + +import com.lambda.gui.GuiConfig +import com.lambda.gui.LambdaGui +import com.lambda.module.ModuleRegistry +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 + +/** + * Walks through the interface the way a user would and takes a screenshot at every stop, so a + * change to the GUI can be looked at without playing through it by hand. It fails if the + * interface throws along the way, since that closes the screen the next step expects. + */ +@Suppress("UnstableApiUsage") +object GuiTest : FabricClientGameTest { + private const val WIDTH = 1920 + private const val HEIGHT = 1080 + + /** The interface is laid out for a screen 540 dp tall, see [LambdaGui] */ + private const val DENSITY = HEIGHT / 540.0 + + override fun runTest(context: ClientGameTestContext) { + context.input.resizeWindow(WIDTH, HEIGHT) + context.waitTicks(5) + + // Over the title screen, where there is no world to draw a HUD for. The first time the + // click GUI opens it offers the loader, which has to be answered before anything else. + context.openClickGui() + context.takeScreenshot("gui-0-loader-prompt") + context.runOnClient { AutoUpdater.answerPrompt(accepted = false) } + context.waitTicks(10) + context.takeScreenshot("gui-1-title-screen") + + // 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) + 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) + + // 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.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) + + // 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.waitTicks(30) + context.takeScreenshot("gui-1a-long-name-hovered") + context.input.setCursorPos(210.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.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" } + + // ...and with the snap key held it lines up with its neighbours instead + context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) + context.waitTicks(2) + 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" } + + // Resetting the layout forgets every placement, which puts the windows back in their row + context.runOnClient { GuiConfig.resetWindows() } + context.waitTicks(2) + 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.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.pressMouse(GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.waitTicks(1) + context.takeScreenshot("gui-2a-switching-settings") + context.waitTicks(10) + + // 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) + + // 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.takeScreenshot("gui-2c2-module-page") + context.input.setCursorPos(330.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.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) + + // 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.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.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.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.takeScreenshot("gui-2g0-dropdown-unfolding") + context.waitTicks(10) + context.takeScreenshot("gui-2g-dropdown") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(1) + context.takeScreenshot("gui-2g1-dropdown-folding") + context.waitTicks(2) + context.takeScreenshot("gui-2g2-dropdown-folded-in") + context.waitTicks(3) + context.input.setCursorPos(266.0 * DENSITY, 216.0 * DENSITY) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.takeScreenshot("gui-2d-tab-changing") + context.waitTicks(10) + 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.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.takeScreenshot("gui-2h0-collection-unfolding") + context.waitTicks(10) + context.takeScreenshot("gui-2h-collection") + context.input.typeChars("stone") + context.waitTicks(5) + context.takeScreenshot("gui-2h2-collection-searched") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(1) + context.takeScreenshot("gui-2h1-collection-folding") + context.waitTicks(2) + context.takeScreenshot("gui-2h3-collection-folded-in") + context.waitTicks(3) + + // 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) + // 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) + 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.waitTicks(2) + context.input.scroll(-2.0) + context.waitTicks(1) + context.takeScreenshot("gui-2i1-wheel-gliding") + context.waitTicks(15) + context.takeScreenshot("gui-2i2-wheel-settled") + context.input.scroll(10.0) + context.waitTicks(15) + context.input.setCursorPos(287.0 * DENSITY, 189.0 * DENSITY) + context.waitTicks(2) + context.dragBy(0.0, -60.0) + context.takeScreenshot("gui-2j-extended") + + // However far it is dragged, the panel stops under the menu bar, its grip still in reach + context.dragBy(0.0, -300.0) + 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.takeScreenshot("gui-2f-category-folded") + context.click(dpX = 110.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.takeScreenshot("gui-2b-style-settings") + + // The first of the buttons opens a menu, which Escape closes without closing the GUI + context.click(dpX = 20.0, dpY = 7.0) + context.takeScreenshot("gui-3-menu") + + // With a menu and one nested in it open, a single click on another entry of the bar + // closes both and opens that entry's menu + context.click(dpX = 30.0, dpY = 39.0) + context.click(dpX = 190.0, dpY = 7.0) + context.takeScreenshot("gui-3b-menu-to-menu") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + + // A menu closed with one nested in it open takes that one with it as it folds + context.click(dpX = 20.0, dpY = 7.0) + context.click(dpX = 30.0, dpY = 39.0) + context.waitTicks(10) + context.takeScreenshot("gui-3c-submenu") + context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.takeScreenshot("gui-3d-submenu-swallowed") + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.takeScreenshot("gui-3e-submenu-swallowed") + context.waitTicks(10) + + // Closed with a menu open, the GUI comes back as it was left, minus the menu + context.click(dpX = 20.0, dpY = 7.0) + context.closeGui() + context.openClickGui() + context.takeScreenshot("gui-3a-reopened") + + // The search in the menu bar lists what matches as it is typed... + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("scaff") + context.waitTicks(10) + context.takeScreenshot("gui-4-search") + + // ...and Enter shows where the first result is: the module is lit in its window + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(8) + context.takeScreenshot("gui-4a-search-module") + context.waitTicks(40) + + // A setting has the settings of its module opened on its tab, and is lit there + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("targeting range") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(15) + context.takeScreenshot("gui-4b-search-setting") + + // A list of blocks shows each with its icon, drawn by Minecraft + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("surround") + 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.takeScreenshot("gui-4c-block-settings") + context.click(dpX = 320.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.waitTicks(2) + context.input.scroll(-5.0) + context.waitTicks(15) + context.takeScreenshot("gui-4e-block-list-scrolled") + + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + context.takeScreenshot("gui-4f-block-list-shut") + + // A setting that is one block shows it on a chip, with its icon + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("pavement material") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(15) + context.takeScreenshot("gui-4g-block-setting") + context.closeGui() + + val singleplayer = context.worldBuilder() + .adjustSettings { it.gameMode = WorldCreator.Mode.CREATIVE } + .create() + singleplayer.clientWorld.waitForChunksDownload() + // A stack, a worn piece and an enchanted one: the count, the damage bar and the glint are Minecraft's + singleplayer.server.runCommand("/item replace entity @p armor.head with minecraft:stone 32") + singleplayer.server.runCommand("/item replace entity @p armor.chest with minecraft:netherite_chestplate[minecraft:damage=500]") + singleplayer.server.runCommand("/item replace entity @p armor.legs with minecraft:diamond_leggings[minecraft:enchantments={protection:4}]") + singleplayer.server.runCommand("/item replace entity @p armor.feet with minecraft:golden_boots[minecraft:damage=40]") + + context.runOnClient { + Armor.enable() + Coordinates.enable() + Fps.enable() + } + context.waitTicks(20) + context.takeScreenshot("gui-5-hud-in-game") + + // In game the GUI is opened the way a player does, with its keybind + context.input.pressKey(GLFW.GLFW_KEY_Y) + context.waitTicks(2) + context.takeScreenshot("gui-6-0-click-gui-opening") + context.waitTicks(18) + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "The keybind did not open the click GUI" } + context.takeScreenshot("gui-6-click-gui-in-game") + + // 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.waitTicks(40) + context.takeScreenshot("gui-6a-tooltip") + context.input.pressKey(GLFW.GLFW_KEY_Y) + context.waitTicks(10) + context.takeScreenshot("gui-6b-closed-with-tooltip-up") + context.input.pressKey(GLFW.GLFW_KEY_Y) + context.waitTicks(10) + context.takeScreenshot("gui-6c-reopened") + + // While a text field has the keyboard, the GUI's keybind is a letter like any other + context.click(dpX = 480.0, dpY = 7.0) + context.input.pressKey(GLFW.GLFW_KEY_Y) + context.waitTicks(5) + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "Typing the keybind into a text field closed the GUI" } + check(context.computeOnClient { LambdaGui.isCapturingKeys }) { "A focused text field did not hold on to the keys" } + context.input.pressKey(GLFW.GLFW_KEY_BACKSPACE) + context.waitTicks(2) + + // The HUD editor is reached from the click GUI's button, and dragging an element moves it + context.click(dpX = 924.0, dpY = 528.0) + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.HudEditor }) { "The HUD Editor button did not open the editor" } + check(context.computeOnClient { !LambdaGui.isCapturingKeys }) { "Keys stayed captured after the focused text field went away" } + context.input.setCursorPos(20.0 * DENSITY, 44.0 * DENSITY) + context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(10) { + context.input.moveCursor(30.0 * DENSITY, 15.0 * DENSITY) + context.waitTick() + } + context.takeScreenshot("gui-7-hud-editor-dragging") + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(2) + + // Dragged with the snap key held, the element lines up with the screen and its neighbours + context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) + context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(10) { + context.input.moveCursor(-29.0 * DENSITY, 2.0 * DENSITY) + context.waitTick() + } + context.takeScreenshot("gui-7a-hud-editor-snapping") + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) + context.waitTicks(2) + + // Right click on the empty screen offers the hidden elements, on an element its own menu. + // The second right click comes while the first menu is still open: it closes that one + // and opens its own, in one go. + context.click(dpX = 700.0, dpY = 400.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.takeScreenshot("gui-8-hud-editor-menu") + + // A right click elsewhere with the menu open unfolds a new one there + context.input.setCursorPos(500.0 * DENSITY, 300.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.waitTicks(1) + context.takeScreenshot("gui-8a-hud-editor-menu-reopening") + context.waitTicks(10) + context.takeScreenshot("gui-8b-hud-editor-menu-reopened") + + // How the editor is used is told by an entry of that menu, to whoever rests the pointer on it + context.input.setCursorPos(513.0 * DENSITY, 427.5 * DENSITY) + context.waitTicks(20) + context.takeScreenshot("gui-8c-hud-editor-help") + context.click(dpX = 150.0, dpY = 108.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.takeScreenshot("gui-9-hud-element-menu") + // Pressed and let go a few frames apart, the way a hand does it + context.input.setCursorPos(175.0 * DENSITY, 129.0 * DENSITY) + context.waitTicks(2) + context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(3) + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(10) + context.takeScreenshot("gui-9a-hud-element-settings") + + // What opens out of that panel in turn: a colour picker and a list of options + context.click(dpX = 342.0, dpY = 135.0) + context.takeScreenshot("gui-9b-hud-element-colour") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + context.click(dpX = 312.0, dpY = 208.5) + context.takeScreenshot("gui-9c-hud-element-options") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + + // The panel is dragged by any part of it that is not a control, here the room beside its buttons + context.input.setCursorPos(170.0 * DENSITY, 268.0 * DENSITY) + context.waitTicks(2) + context.dragBy(150.0, 60.0) + context.takeScreenshot("gui-9d-hud-settings-dragged") + + // A click off the panel closes it, shrinking into its middle, and the editor stays + context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.takeScreenshot("gui-9e-hud-settings-closing") + context.waitTicks(10) + context.takeScreenshot("gui-9f-hud-settings-closed") + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.HudEditor }) { "Closing the settings panel left the HUD editor" } + + // Escape leaves the editor for the click GUI, and the click GUI for the game + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "Escape did not return from the HUD editor to the click GUI" } + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + check(context.computeOnClient { LambdaGui.screen == null }) { "Escape did not close the click GUI" } + + // 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.waitTicks(10) + context.click(dpX = 290.0, dpY = 273.0) + context.waitTicks(10) + context.takeScreenshot("gui-10a-panel-with-menu") + context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.takeScreenshot("gui-10b-menu-folding-in-panel") + context.waitTicks(1) + context.takeScreenshot("gui-10c-menu-folding-in-panel") + context.waitTicks(15) + context.takeScreenshot("gui-10d-panel-closed") + + // 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.waitTicks(10) + context.closeGui() + context.runOnClient { LambdaGui.open(LambdaGui.Screen.ClickGui) } + context.waitTicks(2) + context.takeScreenshot("gui-11a-kept-settings-categories-unfolding") + context.waitTicks(4) + context.takeScreenshot("gui-11b-kept-settings-unfolding") + context.waitTicks(15) + context.takeScreenshot("gui-11c-kept-settings-open") + context.runOnClient { GuiConfig.keepSettingsOpen = false } + context.closeGui() + + singleplayer.close() + } + + private fun ClientGameTestContext.openClickGui() { + runOnClient { LambdaGui.open(LambdaGui.Screen.ClickGui) } + waitTicks(20) + check(computeOnClient { LambdaGui.screen != null }) { "The click GUI did not open" } + } + + private fun ClientGameTestContext.closeGui() { + check(computeOnClient { LambdaGui.screen != null }) { "The interface closed itself, see the log" } + runOnClient { it.setScreen(null) } + waitTicks(5) + } + + private fun ClientGameTestContext.click(dpX: Double, dpY: Double, button: Int = GLFW.GLFW_MOUSE_BUTTON_LEFT) { + input.setCursorPos(dpX * DENSITY, dpY * DENSITY) + waitTicks(2) + input.pressMouse(button) + waitTicks(10) + } + + /** Drags from where the pointer is, by a distance in dp, in steps a frame apart as a hand would */ + private fun ClientGameTestContext.dragBy(dpX: Double, dpY: Double) { + input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(5) { + input.moveCursor(dpX / 5 * DENSITY, dpY / 5 * DENSITY) + waitTick() + } + input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + waitTicks(2) + } + + private fun ClientGameTestContext.windowPlacement(category: String): GuiConfig.WindowPlacement = + computeOnClient { + checkNotNull(GuiConfig.windows[category]) { "The $category window was never moved" } + } + + private fun ClientGameTestContext.enabledModules(): Int = + computeOnClient { ModuleRegistry.modules.count { it.isEnabled } } +} diff --git a/src/gametest/resources/fabric.mod.json b/src/gametest/resources/fabric.mod.json index c9ff71449..3c966f713 100644 --- a/src/gametest/resources/fabric.mod.json +++ b/src/gametest/resources/fabric.mod.json @@ -9,6 +9,10 @@ { "adapter": "kotlin", "value": "com.lambda.LambdaTest" + }, + { + "adapter": "kotlin", + "value": "com.lambda.GuiTest" } ] } diff --git a/src/main/java/com/lambda/mixin/MinecraftClientMixin.java b/src/main/java/com/lambda/mixin/MinecraftClientMixin.java index d20a73c7a..d41043882 100644 --- a/src/main/java/com/lambda/mixin/MinecraftClientMixin.java +++ b/src/main/java/com/lambda/mixin/MinecraftClientMixin.java @@ -19,8 +19,7 @@ import com.lambda.event.EventFlow; import com.lambda.event.events.*; -import com.lambda.gui.DearImGui; -import com.lambda.gui.components.ClickGuiLayout; +import com.lambda.gui.GuiConfig; import com.lambda.interaction.handler.handlers.TimerHandler; import com.lambda.module.modules.movement.BetterFirework; import com.lambda.module.modules.player.Interact; @@ -65,11 +64,6 @@ public class MinecraftClientMixin { @Shadow public int itemUseCooldown; - @Inject(method = "close", at = @At("HEAD")) - void closeImGui(CallbackInfo ci) { - DearImGui.INSTANCE.destroy(); - } - @WrapMethod(method = "render") void onLoopTick(boolean tick, Operation original) { com.lambda.graphics.RenderMain.preRender(); @@ -201,7 +195,7 @@ float getTargetMillisPerTick(float millis, Operation original) { @Inject(method = "updateWindowTitle", at = @At("HEAD"), cancellable = true) void updateWindowTitle(CallbackInfo ci) { - if (!ClickGuiLayout.getSetLambdaWindowTitle()) return; + if (!GuiConfig.getSetLambdaWindowTitle()) return; WindowUtils.setLambdaTitle(); ci.cancel(); } diff --git a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java index 43a26f2cf..b2cdcbc1a 100644 --- a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java +++ b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java @@ -27,6 +27,7 @@ import net.minecraft.client.input.KeyInput; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; +import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Mixin; @Mixin(Keyboard.class) @@ -36,7 +37,9 @@ private void onKey(long window, int action, KeyInput input, Operation 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( value.size != defaultValue.size || defaultValue.any { !value.contains(it) } } + /** A chip with how much is selected, which opens the editor in a window of its own */ + @Composable + override fun compose() = CollectionButton(this) + /** How [item] is shown to the user */ open fun label(item: R): String = item.toString() 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 0341ce676..2982d44b3 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt @@ -17,6 +17,16 @@ package com.lambda.config.settings.comparable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp import com.lambda.brigadier.argument.boolean import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -24,6 +34,11 @@ 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.Checkmark +import com.lambda.gui.component.RowHeight +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.observe +import com.lambda.gui.theme.Text import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess @@ -35,6 +50,24 @@ class BooleanSetting( visibility: () -> Boolean, defaultValue: Boolean ) : Setting(name, description, defaultValue, layer, config, visibility) { + /** A tick box and the name: the whole row flips it */ + @Composable + override fun compose() { + val checked by observe { value } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = RowHeight) + .mouseClickable { value = !value } + .padding(horizontal = 3.dp) + ) { + Checkmark(checked) + Text(name, maxLines = 1) + } + } + 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 b7883b477..c6346831c 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt @@ -17,6 +17,11 @@ package com.lambda.config.settings.comparable +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import 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,8 +31,11 @@ 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.Dropdown +import com.lambda.gui.core.observe 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>( @@ -38,6 +46,19 @@ class EnumSetting>( visibility: () -> Boolean, defaultValue: T ) : Setting(name, description, defaultValue, layer, config, visibility) { + /** The name, and a chip that drops the options down under it */ + @Composable + override fun compose() { + val selected by observe { value } + Dropdown( + label = name, + options = selected.enumValues.asList(), + selected = selected, + optionLabel = { it.displayValue }, + modifier = Modifier.padding(start = 3.dp), + ) { value = it } + } + 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 f5f9fa4ef..531350e17 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt @@ -17,6 +17,12 @@ package com.lambda.config.settings.complex +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import com.lambda.Lambda.mc import com.lambda.brigadier.argument.integer import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -24,9 +30,19 @@ 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.Button +import com.lambda.gui.component.NumberInput +import com.lambda.gui.component.RowHeight +import com.lambda.gui.component.Tooltip +import com.lambda.gui.core.observe +import com.lambda.gui.settings.Labeled +import com.lambda.gui.settings.NumberFieldWidth +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 +import kotlin.math.roundToInt class BlockPosSetting( name: String, @@ -36,6 +52,23 @@ class BlockPosSetting( visibility: () -> Boolean, defaultValue: BlockPos ) : Setting(name, description, defaultValue, layer, config, visibility) { + /** A field for each coordinate, and a button that takes the block under the crosshair */ + @Composable + override fun compose() { + val pos by observe { value.toImmutable() } + Labeled(name) { + NumberInput(pos.x, { value = BlockPos(it.roundToInt(), pos.y, pos.z) }, Modifier.width(NumberFieldWidth)) + NumberInput(pos.y, { value = BlockPos(pos.x, it.roundToInt(), pos.z) }, Modifier.width(NumberFieldWidth)) + NumberInput(pos.z, { value = BlockPos(pos.x, pos.y, it.roundToInt()) }, Modifier.width(NumberFieldWidth)) + Tooltip("Use the block you are looking at") { + Button("Target", Modifier.height(RowHeight)) { + mc.crosshairTarget?.blockResult?.blockPos?.let { value = it } + ?: this@BlockPosSetting.info("No block under crosshair") + } + } + } + } + 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 eff9f5319..80f527555 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt @@ -17,6 +17,7 @@ package com.lambda.config.settings.complex +import androidx.compose.runtime.Composable import com.lambda.brigadier.argument.blockState import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -24,6 +25,7 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer +import com.lambda.gui.settings.BlockPicker import com.lambda.util.extension.CommandBuilder import net.minecraft.block.Block import net.minecraft.command.CommandRegistryAccess @@ -36,6 +38,10 @@ class BlockSetting( visibility: () -> Boolean, defaultValue: Block ) : Setting(name, description, defaultValue, layer, config, visibility) { + /** A chip with the block and its icon, which opens a window listing every block */ + @Composable + override fun compose() = BlockPicker(this) + 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 08c697b52..a2e34c034 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt @@ -17,6 +17,7 @@ package com.lambda.config.settings.complex +import androidx.compose.runtime.Composable import com.lambda.brigadier.argument.integer import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -25,6 +26,7 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer +import com.lambda.gui.settings.ColorPicker import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess import java.awt.Color @@ -37,6 +39,10 @@ class ColorSetting( visibility: () -> Boolean, defaultValue: Color ) : Setting(name, description, defaultValue, layer, config, visibility) { + /** A swatch of the colour, which opens the picker beside the row */ + @Composable + override fun compose() = ColorPicker(this) + 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 fe1a92e62..e204ab843 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -19,6 +19,21 @@ package com.lambda.config.settings.complex +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +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.fasterxml.jackson.annotation.JsonIncludeProperties import com.lambda.Lambda.mc import com.lambda.brigadier.CommandResult.Companion.failure @@ -37,6 +52,15 @@ import com.lambda.context.SafeContext import com.lambda.event.Muteable import com.lambda.event.events.ButtonEvent import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe +import com.lambda.gui.GuiScreen +import com.lambda.gui.component.RowHeight +import com.lambda.gui.component.Tooltip +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.observe +import com.lambda.gui.settings.Labeled +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Radius +import com.lambda.gui.theme.Text import com.lambda.threading.runSafe import com.lambda.util.KeyCode import com.lambda.util.Mouse @@ -107,6 +131,47 @@ class KeybindSetting( } } + /** + * 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 + override fun compose() { + val colors = LambdaTheme.colors + val bind by observe { value } + var recording by remember { mutableStateOf(false) } + DisposableEffect(Unit) { + onDispose { if (recording) GuiScreen.keybindRecorder = null } + } + + Labeled(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 { 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, + ) + } + } + } + } + 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 9a2506c8f..722e9b9a8 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt @@ -17,6 +17,10 @@ package com.lambda.config.settings.complex +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier import com.lambda.brigadier.argument.double import com.lambda.brigadier.argument.value import com.lambda.brigadier.execute @@ -24,6 +28,10 @@ import com.lambda.brigadier.required import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer +import com.lambda.gui.component.NumberInput +import com.lambda.gui.core.observe +import com.lambda.gui.settings.Labeled +import com.lambda.gui.settings.NumberFieldWidth import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess import net.minecraft.util.math.Vec3d @@ -36,6 +44,17 @@ class Vec3dSetting( visibility: () -> Boolean, defaultValue: Vec3d ) : Setting(name, description, defaultValue, layer, config, visibility) { + /** A field for each coordinate */ + @Composable + override fun compose() { + val vec by observe { value } + Labeled(name) { + NumberInput(vec.x, { value = Vec3d(it, vec.y, vec.z) }, Modifier.width(NumberFieldWidth)) + NumberInput(vec.y, { value = Vec3d(vec.x, it, vec.z) }, Modifier.width(NumberFieldWidth)) + NumberInput(vec.z, { value = Vec3d(vec.x, vec.y, it) }, Modifier.width(NumberFieldWidth)) + } + } + 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/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index f2fc8e1af..a0f287c48 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -70,9 +70,7 @@ import kotlin.concurrent.thread object LambdaGui : Loadable { enum class Screen { ClickGui, - - /** Reached from the click GUI, and returns to it */ - HudEditor, + HudEditor } /** The screen that is open, or null while only the HUD shows */ diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index e645be38c..938abe16e 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -45,10 +45,12 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType @@ -62,6 +64,7 @@ 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.RowHeight import com.lambda.gui.component.ScrollColumn import com.lambda.gui.component.SlidingText import com.lambda.gui.component.Tooltip @@ -79,13 +82,21 @@ import com.lambda.gui.theme.shadowed import com.lambda.module.Module import com.lambda.module.ModuleRegistry import com.lambda.module.ModuleTag +import com.lambda.module.modules.client.Style -internal val CategoryWindowWidth = 100.dp +internal val CategoryWindowWidth = 90.dp internal val CategoryWindowGap = 2.dp /** Room between the edge of a window and the text of its rows */ private val RowPadding = 4.dp +/** + * What makes a module a tile rather than a flat stripe, when the style asks for it: a trace of light along the top that is gone + * by the bottom, over whatever the tile is filled with. Only just there: it is felt more than seen. + * The tiles touch, as a gap would show the dark panel as a black line between two enabled ones. + */ +private val Emboss = Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05f), Color.Transparent)) + /** * 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. @@ -212,6 +223,7 @@ internal fun CategoryWindow( private fun ModuleRow(module: Module, isEdited: Boolean, panel: SettingsPanelState?, onEdit: () -> Unit) { val colors = LambdaTheme.colors val enabled by observe { module.isEnabled } + val embossed by observe { Style.emboss } 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()) @@ -227,6 +239,7 @@ private fun ModuleRow(module: Module, isEdited: Boolean, panel: SettingsPanelSta Tooltip(module.description, Modifier.fillMaxWidth()) { Box( + contentAlignment = Alignment.CenterStart, modifier = Modifier .fillMaxWidth() .then( @@ -234,14 +247,17 @@ private fun ModuleRow(module: Module, isEdited: Boolean, panel: SettingsPanelSta else Modifier.onGloballyPositioned { panel.row = Rect(it.positionInRoot(), it.size.toSize()) } ) .bringIntoViewRequester(intoView) + // One that is always enabled has nothing to toggle: either click opens its settings + .mouseClickable(onRightClick = onEdit) { if (module.alwaysEnabled) onEdit() else module.toggle() } .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) + .then(if (embossed) Modifier.background(Emboss) else Modifier) + // As tall as the style asks, or as its name needs if that is more + .heightIn(min = RowHeight) + .padding(horizontal = RowPadding) ) { // A name too long for the window slides along rather than being cut short SlidingText( diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt index 98e6a264c..90b0402aa 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -51,6 +51,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -84,17 +85,23 @@ import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.Dp import 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.LocalRowHeight 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 +/** + * How tall a module, a row of settings or a control is at least, so stacked ones line up. Set in + * the style as its element height; by default a line of text and a hair of room. + */ +val RowHeight: Dp + @Composable @ReadOnlyComposable get() = LocalRowHeight.current private const val TOGGLE_MILLIS = 150 @@ -379,6 +386,7 @@ fun Section( if (revealed) expanded = true } val turn by animateFloatAsState(if (expanded) 90f else 0f, tween(TOGGLE_MILLIS)) + val rowHeight = RowHeight Column( Modifier @@ -387,7 +395,7 @@ fun Section( .drawWithContent { drawContent() // Taller than its header, the section has something unfolded, or is unfolding - if (size.height > RowHeight.toPx() + 1f) { + if (size.height > rowHeight.toPx() + 1f) { drawRect(colors.primary, size = Size(SectionBar.toPx(), size.height)) } } diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 1b5ef07fe..717f11a6a 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -18,17 +18,13 @@ 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 @@ -37,67 +33,36 @@ 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.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.CommunicationUtils.info -import com.lambda.util.extension.displayValue -import com.lambda.util.world.raycast.RayCastUtils.blockResult -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 - * does nothing to a setting: in this interface it only ever opens and closes things. + * The row of one setting in a list, whatever its type: the description as its tooltip, the + * light the search puts on it, and the dimming of one that is disabled. What the row holds is + * the setting's own, see [Setting.compose]. 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, @@ -106,8 +71,6 @@ import kotlin.math.roundToLong * * 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 @@ -140,20 +103,7 @@ fun SettingRow(setting: Setting<*>) { ) { // 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) - } + setting.compose() } } } @@ -195,178 +145,8 @@ internal fun Labeled(name: String, modifier: Modifier = Modifier, editor: @Compo } } -@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, maxLines = 1) - 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), maxLines = 1) - 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 +internal val TextFieldWidth = 90.dp /** Width of each field of a position; longer numbers scroll inside it */ -private val NumberFieldWidth = 34.dp +internal val NumberFieldWidth = 34.dp diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index 2c948f03b..14344701d 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -150,7 +150,9 @@ class Typography(font: GuiFont, scale: Float = 1f) { fontFamily = font.family, fontWeight = weight, fontSize = size, - lineHeight = size, + // Only between the lines of text that wraps: the first and the last keep to the type. + // A pixel font fills its grid, an outline font needs air or its lines touch. + lineHeight = if (font == GuiFont.Minecraft) size else size * 1.25f, lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.Both), ) } @@ -185,6 +187,9 @@ val LocalBackdropBlur = staticCompositionLocalOf { 0.dp } */ val LocalUnderlay = staticCompositionLocalOf { 1f } +/** How tall rows and controls are at least, see [com.lambda.gui.component.RowHeight] */ +val LocalRowHeight = staticCompositionLocalOf { 12.dp } + /** Whether windows, panels and menus are drawn with a hairline border, see [com.lambda.gui.component.window] */ val LocalOutlines = staticCompositionLocalOf { true } @@ -202,12 +207,15 @@ fun LambdaTheme(content: @Composable () -> Unit) { // 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) + // On top of that comes the size the player asks for, which rows that hold text grow to fit. + val fontSize by observe { Style.fontSize } + val typography = remember(font, fontSize) { + if (font == GuiFont.Minecraft) return@remember Typography(font, fontSize) val line = measurer.measure("Ag", Typography(font).body, density = Density(1f)).size.height - Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f)) + Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f) * fontSize) } val underlay by observe { 1f - Style.layerFade } + val rowHeight by observe { Style.elementHeight.dp } CompositionLocalProvider( LocalPalette provides palette, LocalTypography provides typography, @@ -217,6 +225,7 @@ fun LambdaTheme(content: @Composable () -> Unit) { LocalBackdropBlur provides backdropBlur, LocalOutlines provides outlines, LocalUnderlay provides underlay, + LocalRowHeight provides rowHeight, content = content ) } 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 62a50005f..f51f404f9 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -48,6 +48,8 @@ object Style : Module( 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") + var fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") + var elementHeight by setting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") 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 } @@ -56,6 +58,7 @@ object Style : Module( 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 emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") val glow by setting("Glow", true, "Surrounds the click GUI with a glow") val glowRadius by setting("Glow Radius", 17f, 1f..100f, 1f) { glow } @@ -79,7 +82,7 @@ object Style : Module( 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), + moduleEnabled = Color(140, 0, 56), 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), @@ -108,7 +111,7 @@ object Style : Module( onSurfaceVariant = Color(128, 102, 108), header = Color(214, 55, 88, 242), onHeader = Color(255, 250, 251), - moduleEnabled = Color(226, 72, 104, 190), + moduleEnabled = Color(226, 72, 104), onModuleEnabled = Color(255, 250, 251), control = Color(214, 55, 88, 242), controlMenu = Color(246, 232, 235), From cf41459528a94611ce537b21b0e4d3c321f6e7f4 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:31:43 +0000 Subject: [PATCH 06/34] maximum settings menu width and dropdown tabs instead of buttons --- src/gametest/kotlin/com/lambda/GuiTest.kt | 24 +++- .../com/lambda/gui/clickgui/SettingsPanel.kt | 15 ++- .../lambda/gui/settings/CollectionEditor.kt | 18 ++- .../com/lambda/gui/settings/SettingsList.kt | 118 ++++++++++-------- 4 files changed, 107 insertions(+), 68 deletions(-) diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt index fda919ec8..d58ffe71c 100644 --- a/src/gametest/kotlin/com/lambda/GuiTest.kt +++ b/src/gametest/kotlin/com/lambda/GuiTest.kt @@ -128,7 +128,7 @@ object GuiTest : FabricClientGameTest { // What every module has is kept off its own settings, on pages the strip at the top turns to context.click(dpX = 298.5, dpY = 198.0) context.takeScreenshot("gui-2c2-module-page") - context.input.setCursorPos(360.0 * DENSITY, 198.0 * DENSITY) + context.input.setCursorPos(340.0 * DENSITY, 198.0 * DENSITY) context.waitTicks(2) context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) context.waitTicks(1) @@ -171,7 +171,12 @@ object GuiTest : FabricClientGameTest { context.waitTicks(2) context.takeScreenshot("gui-2g2-dropdown-folded-in") context.waitTicks(3) - context.input.setCursorPos(296.0 * DENSITY, 216.0 * DENSITY) + + // The pages a module sorts its settings into are picked from the band over them + context.click(dpX = 296.0, dpY = 216.0) + context.takeScreenshot("gui-2d0-tab-list") + context.input.setCursorPos(296.0 * DENSITY, 245.0 * DENSITY) + context.waitTicks(2) context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) context.waitTicks(1) context.takeScreenshot("gui-2d-tab-changing") @@ -198,7 +203,7 @@ 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 = 360.0, dpY = 198.0) + context.click(dpX = 340.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 = 261.0, dpY = y) context.takeScreenshot("gui-2i-scrolling") @@ -484,6 +489,19 @@ object GuiTest : FabricClientGameTest { context.runOnClient { GuiConfig.keepSettingsOpen = false } context.closeGui() + // However many pages a config has, the band that picks one is a single row + context.openClickGui() + context.click(dpX = 520.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.waitTicks(10) + context.takeScreenshot("gui-11d-settings-of-many-tabs") + context.click(dpX = 728.0, dpY = 185.0) + context.waitTicks(10) + context.click(dpX = 650.0, dpY = 216.0) + context.takeScreenshot("gui-11e-many-tabs-listed") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + context.closeGui() + // The light theme, picked the way a player picks it, in the settings of Style context.openClickGui() context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index c00edf1f3..7f3ff9cfb 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -118,8 +118,11 @@ 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 +/** + * ...nor wider than this, twice a category window. What is too long for it gives way rather + * than widening the panel: a value slides along under the pointer, tabs wrap onto another line. + */ +private val MaxWidth = 180.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) { @@ -363,8 +366,8 @@ private fun moduleSettings(module: Module): List> = listOfNotNull( ) /** - * 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 + * The strip along the top of a panel that turns its pages. It spans the panel, each page with + * a share to match its name, 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 @@ -377,7 +380,9 @@ private fun PageStrip(pages: List, selected: PanelPage, onSelect: (Pa Box( contentAlignment = Alignment.Center, modifier = Modifier - .weight(1f) + // By the length of its name and its padding: in equal parts a long name + // would be cut short in a narrow panel while a short one had room to spare + .weight(page.title.length + 2f) .height(RowHeight + 1.dp) .hoverHighlight(colors.raised) .mouseClickable { onSelect(page) } diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt index 828d4a507..f12bb6807 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -123,11 +123,19 @@ 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() + // The chip has what the name leaves: a block with a long name slides along under the pointer + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = RowHeight).padding(start = 3.dp) + ) { + Text(setting.name, maxLines = 1) + Box(Modifier.weight(1f), contentAlignment = Alignment.CenterEnd) { + Chip(onClick = { picking = true }) { + Box(Modifier.size(IconSize)) { ItemIcon(ItemStack(block.asItem()), IconSize) } + Text(BlockSerializer.stringify(block), Modifier.weight(1f, fill = false), maxLines = 1) + Ellipsis() + } } } if (!picking) return diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt index 9b80a8d07..f9b9a9d38 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -21,7 +21,6 @@ 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 @@ -29,12 +28,13 @@ import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.togetherWith import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow +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.layout.wrapContentWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -45,24 +45,32 @@ 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.layout.onSizeChanged import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import com.lambda.config.EntryLayer import com.lambda.config.MultipleLayerType import com.lambda.config.entries.Setting import com.lambda.gui.clickgui.Reveal +import com.lambda.gui.component.Chevron import com.lambda.gui.component.Expandable +import com.lambda.gui.component.Menu +import com.lambda.gui.component.MenuItem +import com.lambda.gui.component.MenuState +import com.lambda.gui.component.RowHeight import com.lambda.gui.component.Section +import com.lambda.gui.component.hoverHighlight import com.lambda.gui.component.mouseClickable import com.lambda.gui.core.observe +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 /** - * The settings of a config as they are organised in code: tabs become a strip that swaps the + * The settings of a config as they are organised in code: tabs become a band that picks 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. */ @@ -97,18 +105,17 @@ fun SettingsList(layer: EntryLayer>) { 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 pages a config sorts its settings into, and over them a band that says which one is shown + * and lists the others when clicked. * - * 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. + * What it picks decides everything under it, so the band is the strongest thing in a panel: as + * wide as it and filled like an enabled module, where the choice of a setting is a chip at the + * end of its row. It is one row however many pages there are, and no wider than its settings. + * Changing pages slides the new one in from the side it is on in the list, while the panel + * grows or shrinks to fit it. */ -@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) } @@ -119,54 +126,55 @@ private fun Tabs(tabs: List>>) { 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) - ) - } - } + TabPicker(shown.map { it.name }, selected.name) { selectedName = it } AnimatedContent( targetState = selected, modifier = Modifier.fillMaxWidth(), transitionSpec = { pageTurn(towardsEnd = shown.indexOf(targetState) > shown.indexOf(initialState)) }, ) { tab -> - Column( - Modifier - .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) } - } + Column(Modifier.fillMaxWidth().padding(vertical = 1.dp)) { Children(tab) } + } + } +} + +/** The band over a config's pages: the [selected] one of [names], and a menu of them all under it */ +@Composable +private fun TabPicker(names: List, selected: String, onSelect: (String) -> Unit) { + val colors = LambdaTheme.colors + val menu = remember { MenuState() } + var band by remember { mutableStateOf(IntSize.Zero) } + // The only page left, the others having nothing to show, is a heading rather than a choice of one + val choice = names.size > 1 + + Box(Modifier.fillMaxWidth().onSizeChanged { band = it }) { + ContentColor(colors.onModuleEnabled) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier .fillMaxWidth() - .padding(vertical = 1.dp) - ) { Children(tab) } + .heightIn(min = RowHeight + 2.dp) + .clip(RoundedCornerShape(Radius.Small)) + .background(colors.moduleEnabled) + .then( + if (!choice) Modifier + else Modifier.hoverHighlight(colors.onModuleEnabled.copy(alpha = 0.12f)).mouseClickable(onClick = menu::toggle) + ) + .padding(horizontal = 6.dp) + ) { + Text(selected, Modifier.weight(1f), style = Type.title, maxLines = 1) + if (choice) Chevron(90f) + } + } + // Drops out from under the band, as wide as it + Menu(menu.isOpen, onDismiss = menu::dismiss, unfoldFrom = IntSize(band.width, 0)) { + names.forEach { name -> + MenuItem(name, selected = name == selected) { + if (name != selected) onSelect(name) + } + } } } } From 47cf525aacbc280eee5af138b29149640a4c8cd2 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:37:16 +0000 Subject: [PATCH 07/34] experimental new colours and small fixes --- src/gametest/kotlin/com/lambda/GuiTest.kt | 90 ++++++++++++++ .../lambda/config/settings/NumericSetting.kt | 39 +++++- src/main/kotlin/com/lambda/gui/GuiScreen.kt | 6 + src/main/kotlin/com/lambda/gui/LambdaGui.kt | 2 + .../com/lambda/gui/clickgui/CategoryWindow.kt | 7 +- .../com/lambda/gui/clickgui/ClickGui.kt | 5 +- .../com/lambda/gui/clickgui/SettingsPanel.kt | 2 +- .../com/lambda/gui/component/Keyboard.kt | 105 ++++++++++++++++ .../com/lambda/gui/component/Pointer.kt | 14 ++- .../kotlin/com/lambda/gui/component/Popups.kt | 80 +++++++++---- .../kotlin/com/lambda/gui/core/SceneInput.kt | 37 +++++- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 91 +++++++++++--- .../com/lambda/gui/settings/SettingsList.kt | 19 +-- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 6 +- .../com/lambda/module/modules/client/Style.kt | 112 +++++++++++------- 15 files changed, 512 insertions(+), 103 deletions(-) create mode 100644 src/main/kotlin/com/lambda/gui/component/Keyboard.kt diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt index d58ffe71c..2f5fdec4e 100644 --- a/src/gametest/kotlin/com/lambda/GuiTest.kt +++ b/src/gametest/kotlin/com/lambda/GuiTest.kt @@ -18,6 +18,7 @@ package com.lambda import com.lambda.gui.GuiConfig +import com.lambda.gui.GuiScreen import com.lambda.gui.LambdaGui import com.lambda.module.ModuleRegistry import com.lambda.module.modules.client.AutoUpdater @@ -28,6 +29,7 @@ import com.lambda.module.modules.hud.Fps 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 net.minecraft.client.input.KeyInput import org.lwjgl.glfw.GLFW import kotlin.math.abs @@ -279,6 +281,24 @@ object GuiTest : FabricClientGameTest { context.takeScreenshot("gui-4a-search-module") context.waitTicks(40) + // The arrow keys and Tab move the mark through the results, and Enter takes the marked one + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("auto") + context.waitTicks(1) + context.takeScreenshot("gui-4a1-search-unfolding") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.waitTicks(5) + context.takeScreenshot("gui-4a2-search-third-marked") + context.input.pressKey(GLFW.GLFW_KEY_UP) + context.waitTicks(5) + context.takeScreenshot("gui-4a3-search-second-marked") + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(8) + context.takeScreenshot("gui-4a4-search-marked-chosen") + context.waitTicks(40) + // A setting has the settings of its module opened on its tab, and is lit there context.click(dpX = 480.0, dpY = 7.0) context.input.typeChars("targeting range") @@ -502,6 +522,12 @@ object GuiTest : FabricClientGameTest { context.waitTicks(5) context.closeGui() + // The glow is in the colours of the theme in use: the dark one's here, the light one's below + context.runOnClient { Style.glow = true } + context.openClickGui() + context.takeScreenshot("gui-11f-glow-dark") + context.closeGui() + // The light theme, picked the way a player picks it, in the settings of Style context.openClickGui() context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) @@ -515,6 +541,7 @@ object GuiTest : FabricClientGameTest { context.waitTicks(10) context.takeScreenshot("gui-12b-light-theme-settings") context.closeGui() + context.runOnClient { Style.glow = false } // Another font, picked the same way: the interface keeps its proportions context.openClickGui() @@ -541,6 +568,60 @@ object GuiTest : FabricClientGameTest { context.takeScreenshot("gui-14-font-size-and-module-height") context.closeGui() + // The whole of it from the keyboard. Tab puts the focus on the first thing there is, the + // header of the first window, and the arrows take it across to the third and down its list + context.openClickGui() + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.waitTicks(5) + context.takeScreenshot("gui-15a-keyboard-first-focus") + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.waitTicks(5) + context.takeScreenshot("gui-15b-keyboard-on-module") + + // Enter is a click on it, and Shift with Enter a right click: its settings open beside it + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + context.takeScreenshot("gui-15c-keyboard-toggled") + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) + context.waitTicks(15) + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.waitTicks(5) + context.takeScreenshot("gui-15d-keyboard-into-settings") + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.waitTicks(5) + context.takeScreenshot("gui-15e-keyboard-down-settings") + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.waitTicks(5) + context.takeScreenshot("gui-15f-keyboard-right-twice") + + // A menu of the bar is its own layer of focus: Enter opens it, the arrows move inside it + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("zoo") + context.waitTicks(10) + context.takeScreenshot("gui-15g-keyboard-search") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + repeat(5) { context.pressKey(GLFW.GLFW_KEY_TAB, GLFW.GLFW_MOD_SHIFT) } + context.waitTicks(5) + context.takeScreenshot("gui-15h-keyboard-on-menu-bar") + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.waitTicks(5) + context.takeScreenshot("gui-15i-keyboard-in-menu") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(10) + context.takeScreenshot("gui-15j-keyboard-menu-closed") + context.closeGui() + singleplayer.close() } @@ -550,6 +631,15 @@ object GuiTest : FabricClientGameTest { check(computeOnClient { LambdaGui.screen != null }) { "The click GUI did not open" } } + /** A key pressed with modifiers held, which the test's own input leaves out of the key it sends */ + private fun ClientGameTestContext.pressKey(key: Int, modifiers: Int) { + runOnClient { + GuiScreen.keyPressed(KeyInput(key, 0, modifiers)) + GuiScreen.keyReleased(KeyInput(key, 0, modifiers)) + } + waitTicks(1) + } + private fun ClientGameTestContext.closeGui() { check(computeOnClient { LambdaGui.screen != null }) { "The interface closed itself, see the log" } runOnClient { it.setScreen(null) } diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index 690dbe1c5..f3e9247ca 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -26,6 +26,7 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -34,15 +35,22 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.geometry.Size +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.key import androidx.compose.ui.unit.dp import com.lambda.config.Config import com.lambda.config.ConfigEditorD5l import com.lambda.config.SettingEditBuilder import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer +import com.lambda.gui.component.KeyboardFocus import com.lambda.gui.component.NumberInput import com.lambda.gui.component.RowHeight +import com.lambda.gui.component.isActivation +import com.lambda.gui.component.keyboardFocusable import com.lambda.gui.component.mouseClickable import com.lambda.gui.component.scrubbable import com.lambda.gui.core.observe @@ -81,6 +89,9 @@ abstract class NumericSetting( /** * 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. + * + * With the keyboard focus on it, the left and right arrows take the value a step down and up, + * and Enter or Space opens the field to type in. Done typing, the focus is back on the bar. */ @Composable override fun compose() { @@ -88,16 +99,27 @@ abstract class NumericSetting( val value by observe { value } val label by observe { toString() } var typing by remember { mutableStateOf(false) } + // The bar is not there while its field is: it has to ask for the focus the field gave up + val bar = remember { FocusRequester() } + var refocus by remember { mutableStateOf(false) } if (typing) { NumberInput(value, { this.value = convert(it) }, Modifier.fillMaxWidth(), focused = true) { typing = false + refocus = KeyboardFocus.visible } return } + if (refocus) LaunchedEffect(Unit) { + bar.requestFocus() + refocus = false + } val min = range.start.toDouble() val max = range.endInclusive.toDouble() + /** The value [steps] of the setting's step up from the bottom of its range */ + fun at(steps: Long) = convert(min + steps * step.toDouble()) + fun stepsOf(value: Double) = ((value - min) / step.toDouble()).roundToLong() // 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( @@ -108,15 +130,24 @@ abstract class NumericSetting( .heightIn(min = RowHeight) .clip(RoundedCornerShape(Radius.Small)) .background(colors.track) - .drawBehind { drawRect(colors.primary, size = Size(size.width * fraction, size.height)) } + .drawBehind { drawRect(colors.trackFilled, 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()) + this.value = at(stepsOf(min + (position.x / size.width).coerceIn(0f, 1f) * (max - min))) + } + .focusRequester(bar) + .keyboardFocusable { event -> + when { + event.key == Key.DirectionLeft -> this.value = at(stepsOf(value.toDouble()) - 1) + event.key == Key.DirectionRight -> this.value = at(stepsOf(value.toDouble()) + 1) + event.isActivation -> typing = true + else -> return@keyboardFocusable false + } + true } .padding(horizontal = 3.dp) ) { Text(name, Modifier.weight(1f), colors.onControl, maxLines = 1) - Text(label, Modifier.mouseClickable { typing = true }, colors.onControl, maxLines = 1) + Text(label, Modifier.mouseClickable(keyboard = false) { typing = true }, colors.onControl, maxLines = 1) } } diff --git a/src/main/kotlin/com/lambda/gui/GuiScreen.kt b/src/main/kotlin/com/lambda/gui/GuiScreen.kt index 63fef2c52..1745941f1 100644 --- a/src/main/kotlin/com/lambda/gui/GuiScreen.kt +++ b/src/main/kotlin/com/lambda/gui/GuiScreen.kt @@ -21,6 +21,7 @@ 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.clickgui.ClickGuiState import com.lambda.gui.component.TextFocus import com.lambda.module.modules.client.Style import com.lambda.module.modules.combat.autodisconnect.AutoDisconnectScreen @@ -148,6 +149,11 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { 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 + // Where every program has its search: the field of the menu bar takes the keyboard + if (input.key() == GLFW.GLFW_KEY_F && input.modifiers() and GLFW.GLFW_MOD_CONTROL != 0) { + ClickGuiState.focusSearch = LambdaGui.screen == LambdaGui.Screen.ClickGui + return true + } if (input.isEscape && LambdaGui.onEscape?.invoke() != true) LambdaGui.back() return true } diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index a0f287c48..21d035a22 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -35,6 +35,7 @@ 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.KeyboardFocus import com.lambda.gui.component.TextFocus import com.lambda.gui.core.GameClipboard import com.lambda.gui.core.LocalObservations @@ -232,6 +233,7 @@ object LambdaGui : Loadable { private fun Content() { CompositionLocalProvider(LocalObservations provides observations, LocalClipboard provides GameClipboard) { LambdaTheme { + KeyboardFocus.Layer() // What the search pointed at is lit for a moment, wherever it is shown val revealed = Reveal.module ?: Reveal.setting LaunchedEffect(revealed) { diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index 938abe16e..3af4f7161 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -262,7 +262,12 @@ private fun ModuleRow(module: Module, isEdited: Boolean, panel: SettingsPanelSta // 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, + // The fill is for what is on: one that is only being edited is merely lit + color = when { + enabled -> colors.onModuleEnabled + isEdited -> colors.onSurface + else -> colors.onSurfaceVariant + }, style = Type.body.shadowed(), ) } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index 66f554772..e6e15e902 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -78,6 +78,9 @@ internal sealed interface ClickGuiDialog { internal object ClickGuiState { var dialog: ClickGuiDialog? by mutableStateOf(null) var developerMode by mutableStateOf(false) + + /** Set to have the search field of the menu bar take the keyboard, which then unsets it */ + var focusSearch by mutableStateOf(false) } /** @@ -128,7 +131,7 @@ internal fun ClickGui() { val bounds = remember { mutableStateMapOf() } val snapping by observe { Snap.isActive } - Box(Modifier.fillMaxSize().mouseClickable { edited = null }) { + Box(Modifier.fillMaxSize().mouseClickable(keyboard = false) { 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 } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index 7f3ff9cfb..b610e9a43 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -376,7 +376,7 @@ private fun PageStrip(pages: List, selected: PanelPage, onSelect: (Pa 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) + val line by animateColorAsState(if (isSelected) colors.secondary else colors.raised) Box( contentAlignment = Alignment.Center, modifier = Modifier diff --git a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt new file mode 100644 index 000000000..322b3c639 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt @@ -0,0 +1,105 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.focusable +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.focus.FocusDirection +import androidx.compose.ui.focus.FocusManager +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme + +/** + * How the interface is being driven. Everything that can be clicked can also be reached from + * the keyboard: Tab and Shift with Tab step through it in order, the arrow keys move to what + * lies in their direction, and Enter or Space is a click on whatever the focus is on, with + * Shift a right click. + * + * The focus is only marked, and only acted on, while it is the keyboard that moves it. A mouse + * press puts the mark away, and with it the chance of Enter toggling something that was left + * focused out of sight; the next Tab or arrow key brings it back. + */ +internal object KeyboardFocus { + var visible by mutableStateOf(false) + + /** The focus of the interface and of every window open over it that takes the keyboard, the innermost last */ + private val layers = ArrayList() + + /** Moves the focus of whatever has the keyboard, and returns whether there was anywhere to move it */ + fun move(direction: FocusDirection) = layers.lastOrNull()?.moveFocus(direction) == true + + /** + * Has the keys that move the focus move it here, among what this is called beside, for as + * long as it is on screen. For the interface itself and for what opens over it and takes + * the keyboard, a menu or a dialog: each of those has a focus of its own. + */ + @Composable + fun Layer() { + val manager = LocalFocusManager.current + DisposableEffect(manager) { + layers += manager + onDispose { layers -= manager } + } + } +} + +/** + * Makes the element a stop for the keyboard focus, outlined while it holds it. Every key that + * goes down while it does is offered to [onKey], which returns whether the key was for it. + */ +fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = composed { + var focused by remember { mutableStateOf(false) } + val handle by rememberUpdatedState(onKey) + val mark = LambdaTheme.colors.onSurface + onFocusChanged { focused = it.isFocused } + .onKeyEvent { it.type == KeyEventType.KeyDown && KeyboardFocus.visible && handle(it) } + // Brings what it is on into view as well, in a list that scrolls + .focusable() + // In the colour of text, as what the search points at is lit: nothing else is outlined in it + .drawWithContent { + drawContent() + if (!focused || !KeyboardFocus.visible) return@drawWithContent + val width = FocusMark.toPx() + drawRect(mark, Offset(width / 2, width / 2), Size(size.width - width, size.height - width), style = Stroke(width)) + } +} + +/** Whether the key is one that clicks what the focus is on */ +internal val KeyEvent.isActivation get() = key == Key.Enter || key == Key.NumPadEnter || key == Key.Spacebar + +private val FocusMark = 1.dp diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt index 4d0edd69b..5ad6db01b 100644 --- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -42,6 +42,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.isShiftPressed import androidx.compose.ui.input.pointer.PointerButton import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType @@ -68,10 +69,16 @@ import kotlinx.coroutines.launch * as the pointer is moved off before letting go. * * Handled clicks are consumed: an element underneath never sees them. + * + * What can be clicked can be reached from the [keyboard] too, see [KeyboardFocus]: with the + * focus on it, Enter or Space is a left click and Shift with either a right click. Where there + * is nothing for a left click to do, the plain keys do what the right click does. Turn it off + * for what is clicked as a backdrop rather than as a thing. */ @OptIn(ExperimentalComposeUiApi::class) fun Modifier.mouseClickable( enabled: Boolean = true, + keyboard: Boolean = true, onRightClick: (() -> Unit)? = null, onMiddleClick: (() -> Unit)? = null, onClick: (() -> Unit)? = null, @@ -87,7 +94,12 @@ fun Modifier.mouseClickable( else -> null } } - pointerInput(onRelease) { + val keys = if (!keyboard) Modifier else Modifier.keyboardFocusable { event -> + val action = if (event.isShiftPressed) onRightClick else onClick ?: onRightClick + if (event.isActivation) action?.invoke() + event.isActivation && action != null + } + keys.pointerInput(onRelease) { awaitPointerEventScope { while (true) { val press = awaitPointerEvent() diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 604c1458d..94c7a1629 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -22,8 +22,11 @@ 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.animateContentSize import androidx.compose.animation.expandIn +import androidx.compose.animation.expandVertically import androidx.compose.animation.shrinkOut +import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope @@ -55,6 +58,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.composed +import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect @@ -157,6 +161,8 @@ private val Floating = PopupProperties( * 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. * + * One that is [attached] continues an element with a square edge, and is square along it too. + * * ``` * val menu = remember { MenuState() } * Box { @@ -173,9 +179,10 @@ fun Menu( onDismiss: () -> Unit, placement: MenuPlacement = MenuPlacement.Below, unfoldFrom: IntSize = IntSize.Zero, + attached: Boolean = false, content: @Composable ColumnScope.() -> Unit, ) { - MenuPopup(open, remember(placement) { UnfoldingPosition(placement::place) }, onDismiss, unfoldFrom, content) + MenuPopup(open, remember(placement) { UnfoldingPosition(placement::place) }, onDismiss, unfoldFrom, attached, content) } private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize) = when (this) { @@ -207,7 +214,7 @@ fun Popout(open: Boolean, onDismiss: () -> Unit, content: @Composable ColumnScop /** 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) + MenuPopup(open, remember(position) { UnfoldingPosition { _, _, _ -> position } }, onDismiss, IntSize.Zero, false, content) /** * [value], or while that is null, what it last was: what a popup goes on showing while it folds @@ -236,12 +243,19 @@ private fun MenuPopup( position: UnfoldingPosition, onDismiss: () -> Unit, unfoldFrom: IntSize, + attached: Boolean, content: @Composable ColumnScope.() -> Unit, ) { val open = open && LocalMenuOpen.current val dismissAll = LocalMenuDismiss.current ?: onDismiss val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } - FloatingPanel(open, position, onDismiss, RoundedCornerShape(Radius.Medium), unfoldFrom) { panel -> + // One that is attached is of a piece with a square edge of its element: square there too, on whichever side it opened + val shape = when { + !attached -> RoundedCornerShape(Radius.Medium) + position.upwards -> RoundedCornerShape(topStart = Radius.Medium, topEnd = Radius.Medium) + else -> RoundedCornerShape(bottomStart = Radius.Medium, bottomEnd = Radius.Medium) + } + FloatingPanel(open, position, onDismiss, shape, unfoldFrom) { panel -> CompositionLocalProvider(LocalMenuDismiss provides dismissAll, LocalMenuOpen provides open) { ScrollColumn( modifier = Modifier @@ -251,7 +265,8 @@ private fun MenuPopup( // 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), + // Entries run right up to the outline on every side, cut to its corners + .clip(shape), content = content ) } @@ -365,6 +380,7 @@ private fun FloatingPanel( properties = Floating, onKeyEvent = { open && it.dismissOnEscape(onDismiss) }, ) { + if (open) KeyboardFocus.Layer() 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( @@ -400,7 +416,8 @@ private class UnfoldingPosition( private var leftwards by mutableStateOf(false) /** Whether it opened above its element, and so grows upwards */ - private var upwards by mutableStateOf(false) + var upwards by mutableStateOf(false) + private set /** The corner it grows out of */ val corner @@ -434,31 +451,49 @@ private class UnfoldingPosition( * 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]. + * + * It unfolds downwards while [open] and folds back up once it is not, and in between it grows + * and shrinks with what it lists rather than jumping from one length to the next. */ @Composable -fun Suggestions(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { +fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { + // Gone at once with the interface, which leaves nothing on screen to fold away if (!LocalShown.current) { - SideEffect(onDismiss) + if (open) SideEffect(onDismiss) return } + val visibility = remember { MutableTransitionState(false) } + visibility.targetState = open + if (!open && visibility.isIdle && !visibility.currentState) return + val colors = LambdaTheme.colors + val shape = RoundedCornerShape(Radius.Medium) 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, + onDismissRequest = { if (open) 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 - ) + // By size alone and with the shadow cast from outside the clip, as every floating panel unfolds + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier.dropShadow(shape), + enter = expandVertically(Unfold, Alignment.Top), + exit = shrinkVertically(Unfold, Alignment.Top), + ) { + ScrollColumn( + modifier = Modifier + .heightIn(max = screenHeight * 0.6f) + .width(IntrinsicSize.Max) + .window(colors.panel, colors.border, shape) + .animateContentSize(Unfold) + .clip(shape), + content = content + ) + } } } } @@ -482,11 +517,11 @@ fun MenuItem( 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) + // The chosen one is lifted and named in the second accent, so it stands out from the rest at a glance + .background(if (selected) colors.controlSelected else Color.Transparent) .then( if (!enabled) Modifier - else Modifier.hoverHighlight(colors.header).mouseClickable { + else Modifier.hoverHighlight(colors.controlSelected).mouseClickable { onClick() if (checked == null) dismiss?.invoke() } @@ -496,7 +531,7 @@ fun MenuItem( if (checked != null) Checkmark(checked, Modifier.padding(end = 3.dp)) val color = when { !enabled -> colors.onSurfaceVariant - selected -> colors.onControl + selected -> colors.secondary else -> colors.onSurface } Text(label, Modifier.weight(1f), color, maxLines = 1) @@ -514,7 +549,7 @@ fun Submenu(label: String, enabled: Boolean = true, content: @Composable ColumnS verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() - .then(if (enabled) Modifier.hoverHighlight(colors.header).mouseClickable(onClick = menu::toggle) else Modifier) + .then(if (enabled) Modifier.hoverHighlight(colors.controlSelected).mouseClickable(onClick = menu::toggle) else Modifier) .padding(horizontal = 5.dp, vertical = 1.dp) ) { Text(label, Modifier.weight(1f), if (enabled) colors.onSurface else colors.onSurfaceVariant, maxLines = 1) @@ -576,12 +611,13 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { properties = PopupProperties(focusable = true), onKeyEvent = { onDismiss != null && it.dismissOnEscape(onDismiss) }, ) { + KeyboardFocus.Layer() Box( contentAlignment = Alignment.Center, modifier = Modifier .fillMaxSize() .glass(Color.Black.copy(alpha = 0.35f), RectangleShape) - .mouseClickable { onDismiss?.invoke() } + .mouseClickable(keyboard = false) { onDismiss?.invoke() } ) { ContentColor(colors.onSurface) { Box( diff --git a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt index ad609b7ca..3b98676e8 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt @@ -18,6 +18,7 @@ package com.lambda.gui.core import androidx.compose.ui.InternalComposeUiApi +import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent @@ -27,6 +28,7 @@ import androidx.compose.ui.input.pointer.PointerButtons import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.PointerKeyboardModifiers import androidx.compose.ui.scene.ComposeScene +import com.lambda.gui.component.KeyboardFocus import org.lwjgl.glfw.GLFW import java.awt.Component import java.awt.event.KeyEvent as AwtKeyEvent @@ -48,6 +50,7 @@ internal class SceneInput(private val scene: ComposeScene) { fun button(button: Int, pressed: Boolean, modifiers: Int) { val mask = 1 shl button pressedButtons = if (pressed) pressedButtons or mask else pressedButtons and mask.inv() + if (pressed) KeyboardFocus.visible = false pointer(if (pressed) PointerEventType.Press else PointerEventType.Release, button.toPointerButton(), modifiers) } @@ -56,18 +59,42 @@ internal class SceneInput(private val scene: ComposeScene) { 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( + /** + * Returns whether something in the scene handled the key. + * + * A Tab or an arrow key that nothing in the scene wanted for itself moves the keyboard focus, + * see [KeyboardFocus]. An arrow with nothing lying in its direction steps on in order as Tab + * would, which is also how the focus first gets onto something. + */ + fun key(key: Int, pressed: Boolean, modifiers: Int): Boolean { + val shift = modifiers and GLFW.GLFW_MOD_SHIFT != 0 + val direction = when (key.takeIf { pressed }) { + GLFW.GLFW_KEY_TAB -> if (shift) FocusDirection.Previous else FocusDirection.Next + GLFW.GLFW_KEY_UP -> FocusDirection.Up + GLFW.GLFW_KEY_DOWN -> FocusDirection.Down + GLFW.GLFW_KEY_LEFT -> FocusDirection.Left + GLFW.GLFW_KEY_RIGHT -> FocusDirection.Right + else -> null + } + if (direction != null) KeyboardFocus.visible = true + + val handled = scene.sendKeyEvent( KeyEvent( key = Key(key.toAwtKeyCode()), type = if (pressed) KeyEventType.KeyDown else KeyEventType.KeyUp, isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, - isShiftPressed = modifiers and GLFW.GLFW_MOD_SHIFT != 0, + isShiftPressed = shift, ) ) + if (handled || direction == null) return handled + val inOrder = when (direction) { + FocusDirection.Up, FocusDirection.Left -> FocusDirection.Previous + else -> FocusDirection.Next + } + return KeyboardFocus.move(direction) || direction != inOrder && KeyboardFocus.move(inOrder) + } /** * Sends a typed character. Compose's desktop text fields only accept text from an AWT @@ -93,6 +120,7 @@ internal class SceneInput(private val scene: ComposeScene) { pointer(PointerEventType.Exit) scene.cancelPointerInput() scene.focusManager.releaseFocus() + KeyboardFocus.visible = false } private fun pointer( @@ -145,6 +173,7 @@ internal class SceneInput(private val scene: ComposeScene) { GLFW.GLFW_KEY_ESCAPE -> AwtKeyEvent.VK_ESCAPE GLFW.GLFW_KEY_ENTER, GLFW.GLFW_KEY_KP_ENTER -> AwtKeyEvent.VK_ENTER GLFW.GLFW_KEY_TAB -> AwtKeyEvent.VK_TAB + GLFW.GLFW_KEY_SPACE -> AwtKeyEvent.VK_SPACE GLFW.GLFW_KEY_BACKSPACE -> AwtKeyEvent.VK_BACK_SPACE GLFW.GLFW_KEY_INSERT -> AwtKeyEvent.VK_INSERT GLFW.GLFW_KEY_DELETE -> AwtKeyEvent.VK_DELETE diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index 71220a4e0..cd3f35418 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -17,6 +17,10 @@ package com.lambda.gui.menu +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row @@ -27,19 +31,29 @@ 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.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.isShiftPressed import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.unit.dp import com.lambda.Lambda.REPO_URL @@ -65,6 +79,7 @@ import com.lambda.gui.component.consumeClicks import com.lambda.gui.component.glass import com.lambda.gui.component.hoverHighlight import com.lambda.gui.component.mouseClickable +import com.lambda.gui.component.rememberLast import com.lambda.gui.core.observe import com.lambda.gui.core.observeSafe import com.lambda.gui.hud.HudConfig @@ -125,7 +140,7 @@ private fun BarMenu(label: String, content: @Composable ColumnScope.() -> Unit) contentAlignment = Alignment.Center, modifier = Modifier .fillMaxHeight() - .hoverHighlight(LambdaTheme.colors.header) + .hoverHighlight(LambdaTheme.colors.controlSelected) .mouseClickable(onClick = menu::toggle) .padding(horizontal = 6.dp) ) { @@ -135,16 +150,31 @@ private fun BarMenu(label: String, content: @Composable ColumnScope.() -> Unit) } /** - * 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. + * The search field of the bar. Results drop down under it as the query is typed, and one of + * them is always marked, the first to begin with. The arrow keys, or Tab and Shift with Tab, + * move the mark up and down the list and round its ends, and so does the pointer; Enter takes + * the marked one, a click any, and Escape empties the field. Nothing in it needs a mouse: + * Control with F puts the cursor in the field. */ @Composable private fun SearchField(modifier: Modifier = Modifier) { val focus = LocalFocusManager.current + // Control with F puts the cursor in the field from anywhere in the click GUI + val field = remember { FocusRequester() } + val asked = ClickGuiState.focusSearch + LaunchedEffect(asked) { + if (asked) field.requestFocus() + ClickGuiState.focusSearch = false + } 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()) } + val open = listed && query.isNotBlank() + // What was listed stays to be seen while the list folds away + val shown = rememberLast(results.takeIf { open }).orEmpty() + // Which result is marked. Every keystroke lists anew, with the best match first and marked. + var marked by remember(results) { mutableStateOf(0) } fun choose(result: Search.Result) { query = "" @@ -157,16 +187,26 @@ private fun SearchField(modifier: Modifier = Modifier) { 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 } + event.key == Key.Enter -> { + results.getOrNull(marked)?.let(::choose) + true + } + // Without a list to move through, Tab is left to go where it goes anywhere else + !open || results.isEmpty() -> false + event.key == Key.DirectionDown || event.key == Key.Tab && !event.isShiftPressed -> { + marked = (marked + 1).mod(results.size) + true + } + event.key == Key.DirectionUp || event.key == Key.Tab -> { + marked = (marked - 1).mod(results.size) + true + } else -> false } } @@ -177,26 +217,49 @@ private fun SearchField(modifier: Modifier = Modifier) { query = it listed = true }, - modifier = Modifier.width(SearchWidth), + modifier = Modifier.width(SearchWidth).focusRequester(field), 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) } } + Suggestions(open, onDismiss = { listed = false }) { + if (shown.isEmpty()) MenuLabel("Nothing found") + shown.forEachIndexed { index, result -> + ResultRow(result, marked = index == marked, onPoint = { marked = index }) { choose(result) } + } } } } +/** + * One result of the search. The [marked] one is lit and kept in view, and the light passes from + * one to the next rather than jumping. Moving the pointer over a row marks it, [onPoint]; a + * pointer that merely lies where the list happens to open does not, or it would take the mark + * from the keyboard with every letter typed. + */ +@OptIn(ExperimentalFoundationApi::class) @Composable -private fun ResultRow(result: Search.Result, onClick: () -> Unit) { +private fun ResultRow(result: Search.Result, marked: Boolean, onPoint: () -> Unit, onClick: () -> Unit) { val colors = LambdaTheme.colors + val lit by animateColorAsState(if (marked) colors.controlSelected else Color.Transparent, tween(90)) + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(marked) { + if (marked) intoView.bringIntoView() + } + val point by rememberUpdatedState(onPoint) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .widthIn(min = SearchWidth) - .hoverHighlight(colors.header) - .mouseClickable(onClick = onClick) + .bringIntoViewRequester(intoView) + .background(lit) + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + if (awaitPointerEvent().type == PointerEventType.Move) point() + } + } + } + .mouseClickable(keyboard = false, onClick = onClick) .padding(horizontal = 5.dp, vertical = 1.dp) ) { Text(result.name, maxLines = 1) diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt index f9b9a9d38..adf9f2268 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -108,9 +108,9 @@ private fun Children(layer: EntryLayer.Multiple>) = layer.layers.forE * The pages a config sorts its settings into, and over them a band that says which one is shown * and lists the others when clicked. * - * What it picks decides everything under it, so the band is the strongest thing in a panel: as - * wide as it and filled like an enabled module, where the choice of a setting is a chip at the - * end of its row. It is one row however many pages there are, and no wider than its settings. + * What it picks decides everything under it, as a category does its modules, so the band is the + * header of a category over again: as wide as the panel, filled in its colour and rounded at the + * top alone, where the choice of a setting is a chip at the end of its row. It is one row however many pages there are, and no wider than its settings. * Changing pages slides the new one in from the side it is on in the list, while the panel * grows or shrinks to fit it. */ @@ -149,18 +149,19 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) val choice = names.size > 1 Box(Modifier.fillMaxWidth().onSizeChanged { band = it }) { - ContentColor(colors.onModuleEnabled) { + ContentColor(colors.onHeader) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier .fillMaxWidth() .heightIn(min = RowHeight + 2.dp) - .clip(RoundedCornerShape(Radius.Small)) - .background(colors.moduleEnabled) + // Square underneath, where its page hangs off it as the modules do off their category + .clip(RoundedCornerShape(topStart = Radius.Medium, topEnd = Radius.Medium)) + .background(colors.header) .then( if (!choice) Modifier - else Modifier.hoverHighlight(colors.onModuleEnabled.copy(alpha = 0.12f)).mouseClickable(onClick = menu::toggle) + else Modifier.hoverHighlight(colors.onHeader.copy(alpha = 0.12f)).mouseClickable(onClick = menu::toggle) ) .padding(horizontal = 6.dp) ) { @@ -168,8 +169,8 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) if (choice) Chevron(90f) } } - // Drops out from under the band, as wide as it - Menu(menu.isOpen, onDismiss = menu::dismiss, unfoldFrom = IntSize(band.width, 0)) { + // Drops out from under the band, as wide as it and square where the two meet + Menu(menu.isOpen, onDismiss = menu::dismiss, unfoldFrom = IntSize(band.width, 0), attached = true) { names.forEach { name -> MenuItem(name, selected = name == selected) { if (name != selected) onSelect(name) diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index 14344701d..47610307a 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -57,8 +57,9 @@ import com.lambda.util.stream */ @Immutable data class Palette( - /** Accent: sliders, checked boxes, the selected tab, the outline of the module being edited */ + /** Accent, for what is on or filled: sliders, checked boxes, the bar of an open group */ val primary: Color, + /** Second accent, a hue apart, for what is chosen among options: an entry of a menu, the page of a panel */ val secondary: Color, /** Fill of windows, tinted over the frosted game */ val surface: Color, @@ -88,6 +89,9 @@ data class Palette( /** Text drawn on [primary]: whichever of dark and white stands out */ val onPrimary: Color = if (primary.luminance() > 0.35f) Color(0xFF1B1024) else Color.White + /** The filled part of a slider: the accent held back, as it covers far more than a tick does and has text over it */ + val trackFilled: Color = primary.copy(alpha = 0.6f) + /** 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) 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 f51f404f9..0b00afa35 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -60,76 +60,94 @@ object Style : Module( val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") val emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") - val glow by setting("Glow", true, "Surrounds the click GUI with a glow") + var glow by setting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") 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. + /** The colours the glow runs between, which are the theme's: what suits dark glass is lost around light */ + val glowColorA: Color get() = theme.glowA + val glowColorB: Color get() = theme.glowB + + // Both themes are Lambda's rose and nothing else, structured the way Catppuccin structures + // its own. Most of what is on screen is a neutral warmed with a tenth of rose, stepped + // in tiers: wells, panels, windows, controls, borders. Kept that light and well clear of + // black it reads as a warm grey, where a darker one with as much rose in it turns to wine. + // + // Over it the rose comes in a few pastel variants, each with one job, which shift in hue as + // they do in lightness, the way a colour does in light: deeper ones lean to crimson, paler + // ones to salmon. The deepest fills a header, a softer tone of it an enabled module. The + // pale rose marks what is on or filled in a control, and the salmon what is chosen among + // options. Fills of rose are opaque, as glass in a hue takes on whatever is behind it. @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), + primary = Color(250, 140, 164), + secondary = Color(255, 168, 158), + surface = Color(60, 48, 52, 175), + panel = Color(48, 38, 42, 225), 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(140, 0, 56), - 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), + onSurface = Color(246, 236, 239), + onSurfaceVariant = Color(172, 152, 159), + header = Color(190, 62, 98), + onHeader = Color(255, 246, 248), + // A tone of the header, greyer and a step down: the name of a category stays the strongest thing in its window + moduleEnabled = Color(160, 76, 102), + onModuleEnabled = Color(255, 240, 244), + // Controls are a tier above anything they sit on, and say what they hold in plain text + control = Color(92, 75, 81), + controlMenu = Color(48, 38, 42), + controlSelected = Color(81, 65, 71), + onControl = Color(246, 236, 239), // 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), + track = Color(34, 27, 30, 230), + input = Color(29, 23, 25, 230), + border = Color(114, 93, 100, 235), + textShadow = Color(0, 0, 0, 150), + // From the rose of the headers to the salmon, the two ends of the theme's range + glowA = Color(190, 62, 98), + glowB = Color(255, 168, 158), ) ) // 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 + // cannot be read, and a shadow under dark text only smears it. Its tiers run the other way, + // darker for what is deeper, and its rose is the crimson of the logo, which holds on white. @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, 135), - panel = Color(247, 244, 245, 175), + secondary = Color(196, 58, 52), + surface = Color(246, 240, 243, 200), + panel = Color(240, 233, 237, 225), inset = Color(120, 0, 40, 34), - onSurface = Color(40, 14, 20), - onSurfaceVariant = Color(128, 102, 108), + onSurface = Color(64, 44, 54), + onSurfaceVariant = Color(128, 108, 117), header = Color(214, 55, 88, 242), onHeader = Color(255, 250, 251), - moduleEnabled = Color(226, 72, 104), - 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, 200), + moduleEnabled = Color(243, 217, 225), + onModuleEnabled = Color(176, 0, 70), + control = Color(216, 202, 209), + controlMenu = Color(240, 233, 237), + controlSelected = Color(228, 210, 218), + onControl = Color(64, 44, 54), + track = Color(214, 203, 208, 220), input = Color(255, 255, 255, 200), - border = Color(216, 134, 150, 238), + border = Color(190, 172, 180, 238), textShadow = Color(0, 0, 0, 0), + // From the rose of the headers to a paler one: around light glass a glow has to stay light itself + glowA = Color(214, 55, 88), + glowB = Color(255, 150, 172), ) ) - val palette: Palette + private val theme: PaletteSettings get() = when (themeMode) { ThemeMode.Dark -> darkTheme ThemeMode.Light -> lightTheme ThemeMode.Auto -> if (SystemAppearance.isDark) darkTheme else lightTheme - }.toPalette() + } + + val palette: Palette get() = theme.toPalette() /** Asking the operating system is not free, so the answer is reused for a moment */ private object SystemAppearance { @@ -171,9 +189,11 @@ class PaletteSettings( input: Color, border: Color, textShadow: Color, + glowA: Color, + glowB: 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 primary by c.setting("Primary", primary, "Accent colour: the fill of sliders, ticked boxes, what is chosen") + private val secondary by c.setting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") private val surface by c.setting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") private val panel by c.setting("Panel", panel, "Fill of settings panels, menus and dialogs") private val inset by c.setting("Inset", inset, "Shade over the module whose settings are open, which looks pressed in") @@ -185,12 +205,14 @@ class PaletteSettings( 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 controlSelected by c.setting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") private val onControl by c.setting("On Control", onControl) private val track by c.setting("Slider Track", track) private val input by c.setting("Text Field", input) private val border by c.setting("Border", border) private val textShadow by c.setting("Text Shadow", textShadow) + val glowA by c.setting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { Style.glow } + val glowB by c.setting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { Style.glow } fun toPalette() = Palette( primary = primary.toCompose(), From ea8ad5f023095d8a2fa85d4f034d5984a02478af Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:43:20 +0000 Subject: [PATCH 08/34] colours, config --- src/gametest/kotlin/com/lambda/GuiTest.kt | 4 +++ .../lambda/config/settings/NumericSetting.kt | 35 ++++++++++++++++++- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 7 ++-- .../com/lambda/module/modules/client/Style.kt | 21 ++++------- 4 files changed, 49 insertions(+), 18 deletions(-) diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt index 2f5fdec4e..dda44a1a1 100644 --- a/src/gametest/kotlin/com/lambda/GuiTest.kt +++ b/src/gametest/kotlin/com/lambda/GuiTest.kt @@ -599,6 +599,10 @@ object GuiTest : FabricClientGameTest { context.input.pressKey(GLFW.GLFW_KEY_RIGHT) context.waitTicks(5) context.takeScreenshot("gui-15f-keyboard-right-twice") + // Stepped back down, the value is the default again and not a rounding error beside it + context.input.pressKey(GLFW.GLFW_KEY_LEFT) + context.input.pressKey(GLFW.GLFW_KEY_LEFT) + context.waitTicks(5) // A menu of the bar is its own layer of focus: Enter opens it, the arrows move inside it context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index f3e9247ca..c16756219 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -57,8 +57,11 @@ 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.math.BigDecimal +import java.math.RoundingMode import java.text.NumberFormat import java.util.* +import kotlin.math.abs import kotlin.math.roundToInt import kotlin.math.roundToLong @@ -118,7 +121,7 @@ abstract class NumericSetting( val min = range.start.toDouble() val max = range.endInclusive.toDouble() /** The value [steps] of the setting's step up from the bottom of its range */ - fun at(steps: Long) = convert(min + steps * step.toDouble()) + fun at(steps: Long) = convert(range.start.decimal + step.decimal * BigDecimal.valueOf(steps)) fun stepsOf(value: Double) = ((value - min) / step.toDouble()).roundToLong() // 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)) @@ -151,6 +154,33 @@ abstract class NumericSetting( } } + /** + * A value is only saved once it is other than the default. One that is a rounding error + * away from it is not: files written while sliders still counted in binary hold such values, + * 0.14999999 for a default of 0.15, and they are the default. + */ + override val isModified + get() = abs(originalCore.value.toDouble() - originalCore.defaultValue.toDouble()) > step.toDouble() * SAME + + /** + * The number as the decimal it is written as. A slider counts its steps in these, because a + * step of 0.01 is not 0.01 in binary and thirty of them do not add up to 0.3: counted in + * binary, a bar dragged back to its default arrives a hair beside it, which shows the same + * and is saved as a change. Counted in decimal, every stop of the bar is exactly the number + * the code would write for it, however fine the step and however long the range. + */ + private val Number.decimal get() = BigDecimal(toString()) + + /** A decimal as the setting's own number type: the float or double nearest to it, as a literal of it would be */ + @Suppress("UNCHECKED_CAST") + private fun convert(number: BigDecimal): T = + when (value) { + is Int -> number.setScale(0, RoundingMode.HALF_UP).toInt() + is Long -> number.setScale(0, RoundingMode.HALF_UP).toLong() + is Float -> number.toPlainString().toFloat() + else -> number.toPlainString().toDouble() + } as T + /** 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 = @@ -162,6 +192,9 @@ abstract class NumericSetting( } as T } +/** How far from its default, as a share of its step, a number may be and still be the default: a rounding error, never a step */ +private const val SAME = 1e-4 + @Suppress("unchecked_cast") @ConfigEditorD5l fun SettingEditBuilder.range(range: ClosedRange) where T : Number, T : Comparable { diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index 47610307a..d9adc9782 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -86,8 +86,11 @@ data class Palette( 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 + /** + * Text drawn on [primary], the tick of a box among it: dark on all but a deep accent. Dark + * is the quieter of the two and reads on a rose of middling lightness as well as on a pale one. + */ + val onPrimary: Color = if (primary.luminance() > 0.2f) Color(0xFF1B1024) else Color.White /** The filled part of a slider: the accent held back, as it covers far more than a tick does and has text over it */ val trackFilled: Color = primary.copy(alpha = 0.6f) 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 0b00afa35..4896e5b2e 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -68,30 +68,21 @@ object Style : Module( val glowColorA: Color get() = theme.glowA val glowColorB: Color get() = theme.glowB - // Both themes are Lambda's rose and nothing else, structured the way Catppuccin structures - // its own. Most of what is on screen is a neutral warmed with a tenth of rose, stepped - // in tiers: wells, panels, windows, controls, borders. Kept that light and well clear of - // black it reads as a warm grey, where a darker one with as much rose in it turns to wine. - // - // Over it the rose comes in a few pastel variants, each with one job, which shift in hue as - // they do in lightness, the way a colour does in light: deeper ones lean to crimson, paler - // ones to salmon. The deepest fills a header, a softer tone of it an enabled module. The - // pale rose marks what is on or filled in a control, and the salmon what is chosen among - // options. Fills of rose are opaque, as glass in a hue takes on whatever is behind it. @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( PaletteSettings( this, - primary = Color(250, 140, 164), + // A brighter rose than the header rather than a paler one: pale, it is a pastel pink + primary = Color(226, 88, 120), secondary = Color(255, 168, 158), - surface = Color(60, 48, 52, 175), - panel = Color(48, 38, 42, 225), + surface = Color(60, 48, 52, 165), + panel = Color(48, 38, 42, 200), inset = Color(0, 0, 0, 90), onSurface = Color(246, 236, 239), onSurfaceVariant = Color(172, 152, 159), header = Color(190, 62, 98), onHeader = Color(255, 246, 248), - // A tone of the header, greyer and a step down: the name of a category stays the strongest thing in its window - moduleEnabled = Color(160, 76, 102), + // A shade of the header, as strong and a good step darker: greyed and left as light it turns to a dusty pink + moduleEnabled = Color(138, 46, 72), onModuleEnabled = Color(255, 240, 244), // Controls are a tier above anything they sit on, and say what they hold in plain text control = Color(92, 75, 81), From 813be337f36bfad3b64adabfb8302957fdd0a825 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:54:28 +0000 Subject: [PATCH 09/34] more style customisation settings and colour tweaks --- src/gametest/kotlin/com/lambda/GuiTest.kt | 138 +++++++++++++++++- .../lambda/config/settings/NumericSetting.kt | 2 +- .../config/settings/complex/KeybindSetting.kt | 7 +- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 17 ++- src/main/kotlin/com/lambda/gui/LambdaGui.kt | 2 + .../com/lambda/gui/clickgui/CategoryWindow.kt | 33 ++++- .../com/lambda/gui/clickgui/ClickGui.kt | 9 +- .../com/lambda/gui/clickgui/SettingsPanel.kt | 24 +-- .../com/lambda/gui/component/Controls.kt | 26 ++-- .../com/lambda/gui/component/Keyboard.kt | 8 + .../com/lambda/gui/component/Pointer.kt | 8 +- .../kotlin/com/lambda/gui/component/Popups.kt | 26 ++-- .../com/lambda/gui/component/SlidingText.kt | 25 ++-- .../com/lambda/gui/component/Surface.kt | 2 + .../kotlin/com/lambda/gui/core/SceneHost.kt | 4 +- .../kotlin/com/lambda/gui/hud/HudEditor.kt | 2 +- .../lambda/gui/settings/CollectionEditor.kt | 2 +- .../com/lambda/gui/settings/ColorPicker.kt | 6 +- .../com/lambda/gui/settings/SettingRow.kt | 13 +- .../com/lambda/gui/settings/SettingsList.kt | 13 +- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 137 +++++++++++++++-- .../com/lambda/module/modules/client/Style.kt | 47 +++++- 22 files changed, 446 insertions(+), 105 deletions(-) diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt index dda44a1a1..9a216a5ab 100644 --- a/src/gametest/kotlin/com/lambda/GuiTest.kt +++ b/src/gametest/kotlin/com/lambda/GuiTest.kt @@ -17,6 +17,8 @@ package com.lambda +import com.lambda.config.entries.Setting +import com.lambda.context.Automated import com.lambda.gui.GuiConfig import com.lambda.gui.GuiScreen import com.lambda.gui.LambdaGui @@ -105,7 +107,8 @@ 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 - 573f) < 0.1f) { "A window dragged with the snap key held did not snap back between its neighbours: $snapped" } + // Back in its place in the row, it is kept as being in the row rather than at the spot + check(snapped.inRow) { "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() } @@ -626,6 +629,131 @@ object GuiTest : FabricClientGameTest { context.takeScreenshot("gui-15j-keyboard-menu-closed") context.closeGui() + // The shape, the spacing and the motion of it all are the style's, each kind of thing by + // itself: round windows over a square panel here, thicker in outline, wider and roomier, + // and a panel that is all there the moment it is opened while the rest still animates + context.runOnClient { + Style.windowRounding = 9f + Style.panelRounding = 0f + Style.outlineWidth = 1.5f + Style.windowWidth = 110f + Style.windowGap = 8f + Style.modulePadding = 10f + Style.panelPadding = 10f + Style.settingSpacing = 4f + Style.panelAnimations = false + } + context.openClickGui() + context.takeScreenshot("gui-16a-restyled") + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) + context.waitTicks(1) + context.takeScreenshot("gui-16b-no-panel-animation") + context.closeGui() + context.runOnClient { + Style.windowRounding = 3f + Style.panelRounding = 5f + Style.outlineWidth = 0.5f + Style.windowWidth = 90f + Style.windowGap = 2f + Style.modulePadding = 4f + Style.panelPadding = 4f + Style.settingSpacing = 1f + Style.panelAnimations = true + } + + // Each spacing setting changed while the interface is open, with a module's settings out + // and a group in them unfolded: every one of them has to show at once + // ...windows put back in their row by hand or folded away among them: left where the + // row has them, they are in the row, and go where it goes + context.runOnClient { + GuiConfig.windows = mapOf( + "Movement" to GuiConfig.WindowPlacement(204.6f, 94.3f, false), + "Render" to GuiConfig.WindowPlacement(297f, 94f, true), + "World" to GuiConfig.WindowPlacement(500f, 200f, false), + ) + } + context.openClickGui() + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("window gap") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(60) + context.takeScreenshot("gui-17a-spacing-default") + context.runOnClient { Style.windowGap = 12f } + context.waitTicks(10) + context.takeScreenshot("gui-17b-window-gap") + context.runOnClient { Style.windowGap = 2f; Style.windowTop = 40f } + context.waitTicks(10) + context.takeScreenshot("gui-17c-window-top") + context.runOnClient { Style.windowTop = 94f; Style.modulePadding = 12f } + context.waitTicks(10) + context.takeScreenshot("gui-17d-module-padding") + context.runOnClient { Style.modulePadding = 4f; Style.panelPadding = 12f } + context.waitTicks(10) + context.takeScreenshot("gui-17e-panel-padding") + context.runOnClient { Style.panelPadding = 4f; Style.settingSpacing = 6f } + context.waitTicks(10) + context.takeScreenshot("gui-17f-setting-spacing") + context.runOnClient { Style.settingSpacing = 1f; Style.groupIndent = 12f } + context.waitTicks(10) + context.takeScreenshot("gui-17g-group-indent") + context.runOnClient { Style.groupIndent = 5f; Style.windowWidth = 120f } + context.waitTicks(10) + context.takeScreenshot("gui-17h-window-width") + context.runOnClient { Style.windowWidth = 90f } + context.waitTicks(10) + context.takeScreenshot("gui-17i-spacing-restored") + context.closeGui() + + // A setting that shows or hides others does so the moment it changes, with the panel + // open: the rows under Glow come and go with it, with animations and without them + context.runOnClient { GuiConfig.resetWindows() } + context.openClickGui() + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("emboss") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(60) + context.takeScreenshot("gui-18a-dependent-hidden") + context.runOnClient { Style.glow = true } + context.waitTicks(15) + context.takeScreenshot("gui-18b-dependent-shown") + context.runOnClient { Style.glow = false } + context.waitTicks(15) + context.takeScreenshot("gui-18c-dependent-hidden-again") + context.runOnClient { Style.animations = false } + context.waitTicks(5) + context.runOnClient { Style.glow = true } + context.waitTicks(15) + context.takeScreenshot("gui-18d-dependent-shown-unanimated") + context.runOnClient { Style.glow = false } + context.waitTicks(15) + context.takeScreenshot("gui-18e-dependent-hidden-unanimated") + context.runOnClient { Style.animations = true } + context.closeGui() + + // A setting that another one disables is dimmed the moment that one is switched off, + // wherever it is switched: here PacketMine's Rebreak Mode, by Rebreak in its automation + context.openClickGui() + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("rebreak mode") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(60) + context.takeScreenshot("gui-19a-dependent-enabled") + context.setRebreak(false) + context.waitTicks(15) + context.takeScreenshot("gui-19b-dependent-disabled") + context.setRebreak(true) + context.waitTicks(15) + context.takeScreenshot("gui-19c-dependent-enabled-again") + context.closeGui() + singleplayer.close() } @@ -644,6 +772,14 @@ object GuiTest : FabricClientGameTest { waitTicks(1) } + /** Sets Rebreak in the automation config PacketMine is linked to, a setting the module only reads */ + @Suppress("UNCHECKED_CAST") + private fun ClientGameTestContext.setRebreak(to: Boolean) = runOnClient { + val config = (ModuleRegistry.modules.first { it.name == "PacketMine" } as Automated).breakConfig + val delegate = config.javaClass.getDeclaredField("rebreak\$delegate").apply { isAccessible = true } + (delegate.get(config) as Setting).value = to + } + private fun ClientGameTestContext.closeGui() { check(computeOnClient { LambdaGui.screen != null }) { "The interface closed itself, see the log" } runOnClient { it.setScreen(null) } diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index c16756219..d7848d1bf 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -131,7 +131,7 @@ abstract class NumericSetting( modifier = Modifier .fillMaxWidth() .heightIn(min = RowHeight) - .clip(RoundedCornerShape(Radius.Small)) + .clip(RoundedCornerShape(Radius.Control)) .background(colors.track) .drawBehind { drawRect(colors.trackFilled, size = Size(size.width * fraction, size.height)) } .scrubbable { position, size -> 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 e204ab843..678084b29 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -151,8 +151,9 @@ class KeybindSetting( contentAlignment = Alignment.Center, modifier = Modifier .height(RowHeight) - .clip(RoundedCornerShape(Radius.Small)) - .background(if (recording) colors.primary else colors.track) + .clip(RoundedCornerShape(Radius.Control)) + // Filled as every control is, and in the second accent while it waits for a key + .background(if (recording) colors.secondary else colors.control) .mouseClickable { recording = true GuiScreen.keybindRecorder = { recorded -> @@ -164,7 +165,7 @@ class KeybindSetting( ) { Text( text = if (recording) "Press a key" else bind.name, - color = if (recording) colors.onPrimary else colors.onSurface, + color = if (recording) colors.onSecondary else colors.onControl, maxLines = 1, ) } diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index a3566502d..4dfc68ab4 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -80,15 +80,26 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @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) + /** + * A category window's position, in dp from the top left of the screen, and whether it is + * collapsed. One that is [inRow] has no position of its own: it is wherever the row puts it, + * and moves with the row when the style spaces or sizes the windows differently. + */ + data class WindowPlacement(val x: Float, val y: Float, val collapsed: Boolean) { + val inRow get() = x.isNaN() || y.isNaN() + + companion object { + /** A window in its place in the row, folded away or not */ + fun inRow(collapsed: Boolean) = WindowPlacement(Float.NaN, Float.NaN, collapsed) + } + } // 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. */ + /** Where the user left each category window, by tag name. Windows never moved or folded away are absent. */ var windows: Map get() { val saved = windowPlacements diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index 21d035a22..c2f4b2be2 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -51,6 +51,7 @@ 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.gui.theme.Look import com.lambda.module.modules.client.AutoUpdater import com.lambda.module.modules.client.Client import com.lambda.module.modules.client.Style @@ -182,6 +183,7 @@ object LambdaGui : Loadable { settled = true observations.refresh() + Look.refresh() if (screen == Screen.ClickGui) clickGuiObservations.refresh() val sceneChanged = host.advance(size, density) val itemsChanged = ItemAtlas.render() diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index 3af4f7161..8c1649d2c 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -75,6 +75,8 @@ 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.Look +import com.lambda.gui.theme.Motion import com.lambda.gui.theme.Radius import com.lambda.gui.theme.Text import com.lambda.gui.theme.Type @@ -83,12 +85,16 @@ import com.lambda.module.Module import com.lambda.module.ModuleRegistry import com.lambda.module.ModuleTag import com.lambda.module.modules.client.Style +import kotlin.math.absoluteValue -internal val CategoryWindowWidth = 90.dp -internal val CategoryWindowGap = 2.dp +internal val CategoryWindowWidth get() = Look.windowWidth +internal val CategoryWindowGap get() = Look.windowGap /** Room between the edge of a window and the text of its rows */ -private val RowPadding = 4.dp +private val RowPadding get() = Look.modulePadding + +/** How far from its place in the row, in dp either way, a window may be left and still count as in it */ +private const val InRow = 1.5f /** * What makes a module a tile rather than a flat stripe, when the style asks for it: a trace of light along the top that is gone @@ -129,7 +135,7 @@ internal fun CategoryWindow( // 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 position = placement?.takeUnless { it.inRow }?.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. @@ -147,8 +153,19 @@ internal fun CategoryWindow( onDispose { bounds -= tag } } + // A window left in its place in the row, or put back there, is kept as being in the row + // rather than at the spot: it then follows the row when the style spaces, sizes or moves it, + // where a spot would pin it under the windows that do fun place(at: DpOffset, collapsed: Boolean) { - GuiConfig.windows += tag.name to GuiConfig.WindowPlacement(at.x.value, at.y.value, collapsed) + val inRow = (at.x - defaultPosition.x).value.absoluteValue < InRow && (at.y - defaultPosition.y).value.absoluteValue < InRow + GuiConfig.windows += tag.name to + if (inRow) GuiConfig.WindowPlacement.inRow(collapsed) + else GuiConfig.WindowPlacement(at.x.value, at.y.value, collapsed) + } + // One that comes as a spot from elsewhere, a config saved before that distinction was made + // or loaded just now, is looked at the same way as it is found + LaunchedEffect(placement) { + position?.let { place(it, collapsed) } } Column( @@ -164,7 +181,7 @@ internal fun CategoryWindow( } } } - .window(colors.surface, colors.border, RoundedCornerShape(Radius.Medium)) + .window(colors.surface, colors.border, RoundedCornerShape(Radius.Window)) ) { Text( text = tag.name, @@ -199,8 +216,8 @@ internal fun CategoryWindow( SideEffect { panels.forEach { if (it.module in modules) it.settled = settled } } AnimatedVisibility( visibleState = unfolded, - enter = expandVertically(spring()), - exit = shrinkVertically(spring()), + enter = expandVertically(Motion.windows), + exit = shrinkVertically(Motion.windows), ) { // 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))) { diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index e6e15e902..f8eae0667 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -53,13 +53,14 @@ import com.lambda.gui.menu.ConfigDialog import com.lambda.gui.menu.LoaderPromptDialog import com.lambda.gui.menu.MenuBar import com.lambda.gui.menu.NewAutomationConfigDialog +import com.lambda.gui.theme.Look import com.lambda.module.HudModule import com.lambda.module.Module 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 +private val WindowRowTop get() = Look.windowTop /** * The categories the click GUI has a window for. HUD elements are not among them: they are @@ -136,7 +137,8 @@ internal fun ClickGui() { // 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 + // A row too wide for the screen starts at its edge and runs off the far side, rather than off both + val rowStart = ((with(density) { screen.width.toDp() } - rowWidth) / 2).coerceAtLeast(0.dp) tags.forEachIndexed { index, tag -> key(tag) { @@ -183,7 +185,8 @@ internal fun ClickGui() { ) Button( label = "HUD Editor", - modifier = Modifier.align(Alignment.BottomEnd).padding(4.dp).zIndex(stacking.size + 1f) + modifier = Modifier.align(Alignment.BottomEnd).padding(4.dp).zIndex(stacking.size + 1f), + prominent = true, ) { LambdaGui.open(LambdaGui.Screen.HudEditor) } } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index b610e9a43..b451e98e6 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -100,11 +100,13 @@ 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.Look 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.Style import com.lambda.module.modules.client.AutoUpdater import kotlinx.coroutines.launch import kotlin.math.roundToInt @@ -113,16 +115,11 @@ import kotlin.math.roundToInt 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 +private val Padding get() = Look.panelPadding /** 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, twice a category window. What is too long for it gives way rather - * than widening the panel: a value slides along under the pointer, tabs wrap onto another line. - */ -private val MaxWidth = 180.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) { @@ -192,10 +189,10 @@ internal fun SettingsPanel(panel: SettingsPanelState, open: Boolean, onClosed: ( // 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, + topStart = if (flipped || lift > 0f) Radius.Panel else 0.dp, + topEnd = if (!flipped || lift > 0f) Radius.Panel else 0.dp, + bottomEnd = Radius.Panel, + bottomStart = Radius.Panel, ) val seam = if (flipped) Alignment.TopEnd else Alignment.TopStart @@ -219,14 +216,17 @@ internal fun SettingsPanel(panel: SettingsPanelState, open: Boolean, onClosed: ( modifier = Modifier .onSizeChanged { unfolded = it.height } .onGloballyPositioned { popups.place(it.boundsInWindow()) } - .dropShadow(RoundedCornerShape(Radius.Large)), + .dropShadow(RoundedCornerShape(Radius.Panel)), enter = expandIn(Unfold, seam), exit = shrinkOut(Unfold, seam), ) { val colors = LambdaTheme.colors + // ...nor wider than the style allows. What is too long for it gives way rather than + // widening the panel: a value slides along under the pointer. + val maxWidth by observe { Style.settingsWidth.dp } Box( Modifier - .widthIn(MinWidth, MaxWidth) + .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) diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt index 90b0402aa..02fd4d15f 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -92,6 +92,7 @@ import com.lambda.gui.theme.ContentColor import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.LocalContentColor import com.lambda.gui.theme.LocalRowHeight +import com.lambda.gui.theme.Look import com.lambda.gui.theme.Radius import com.lambda.gui.theme.Text import com.lambda.gui.theme.Type @@ -105,25 +106,32 @@ val RowHeight: Dp private const val TOGGLE_MILLIS = 150 +/** + * A button. One that is [prominent] is filled like the header of a category rather than like a + * control: for the one that leads somewhere else, of which a screen has one at most. + */ @Composable fun Button( label: String, modifier: Modifier = Modifier, enabled: Boolean = true, + prominent: Boolean = false, onClick: () -> Unit, ) { val colors = LambdaTheme.colors + val fill = if (prominent) colors.header else colors.control + val text = if (prominent) colors.onHeader else colors.onControl Box( contentAlignment = Alignment.Center, modifier = modifier .heightIn(min = RowHeight + 2.dp) - .clip(RoundedCornerShape(Radius.Small)) - .background(colors.control) - .hoverHighlight(colors.onControl.copy(alpha = if (enabled) 0.12f else 0f)) + .clip(RoundedCornerShape(Radius.Control)) + .background(fill) + .hoverHighlight(text.copy(alpha = if (enabled) 0.12f else 0f)) .mouseClickable(enabled, onClick = onClick) .padding(horizontal = 5.dp, vertical = 1.dp) ) { - Text(label, color = if (enabled) colors.onControl else colors.onSurfaceVariant, maxLines = 1) + Text(label, color = if (enabled) text else colors.onSurfaceVariant, maxLines = 1) } } @@ -134,7 +142,7 @@ fun Checkmark(checked: Boolean, modifier: Modifier = Modifier) { Canvas( modifier .size(9.dp) - .clip(RoundedCornerShape(Radius.ExtraSmall)) + .clip(RoundedCornerShape(Radius.Box)) // 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) ) { @@ -256,7 +264,7 @@ fun TextInput( cursorBrush = SolidColor(colors.onControl), modifier = modifier .heightIn(min = RowHeight) - .clip(RoundedCornerShape(Radius.Small)) + .clip(RoundedCornerShape(Radius.Control)) .background(colors.input) .onGloballyPositioned { typing.bounds = it.boundsInWindow() } .focusRequester(focus) @@ -407,7 +415,7 @@ fun Section( modifier = Modifier .fillMaxWidth() .heightIn(min = RowHeight) - .clip(RoundedCornerShape(Radius.Small)) + .clip(RoundedCornerShape(Radius.Control)) .background(colors.raised) .mouseClickable { expanded = !expanded } .padding(horizontal = 4.dp) @@ -426,7 +434,7 @@ fun Section( private val SectionBar = 1.dp /** How far what a section holds is set in, clear of the bar */ -private val SectionIndent = 5.dp +private val SectionIndent get() = Look.groupIndent /** * A value shown at the end of a setting's row as something to click: the chosen option of a @@ -441,7 +449,7 @@ fun Chip(onClick: () -> Unit, modifier: Modifier = Modifier, content: @Composabl horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = modifier .height(RowHeight) - .clip(RoundedCornerShape(Radius.Small)) + .clip(RoundedCornerShape(Radius.Control)) .background(colors.control) .hoverHighlight(colors.onControl.copy(alpha = 0.12f)) .mouseClickable(onClick = onClick) diff --git a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt index 322b3c639..e23214e65 100644 --- a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt +++ b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt @@ -20,6 +20,7 @@ package com.lambda.gui.component import androidx.compose.foundation.focusable import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -83,6 +84,7 @@ internal object KeyboardFocus { * goes down while it does is offered to [onKey], which returns whether the key was for it. */ fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = composed { + if (!LocalKeyboardReachable.current) return@composed Modifier var focused by remember { mutableStateOf(false) } val handle by rememberUpdatedState(onKey) val mark = LambdaTheme.colors.onSurface @@ -99,6 +101,12 @@ fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = compose } } +/** + * Whether the keyboard focus stops on what is inside. Off for what the pointer cannot reach + * either, a setting that is disabled: the focus passes it by, so no key can change it. + */ +val LocalKeyboardReachable = compositionLocalOf { true } + /** Whether the key is one that clicks what the focus is on */ internal val KeyEvent.isActivation get() = key == Key.Enter || key == Key.NumPadEnter || key == Key.Spacebar diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt index 5ad6db01b..3e8c95316 100644 --- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -50,6 +50,8 @@ 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 com.lambda.gui.theme.Motion +import com.lambda.module.modules.client.Style import kotlinx.coroutines.Job import kotlinx.coroutines.launch @@ -234,7 +236,7 @@ fun Modifier.wheelScrollable(state: ScrollableState): Modifier = composed { val event = awaitPointerEvent(PointerEventPass.Initial) if (event.type != PointerEventType.Scroll) continue val change = event.changes.first() - val distance = change.scrollDelta.y * notch + val distance = change.scrollDelta.y * notch * Style.scrollSpeed val canFollow = if (distance > 0) state.canScrollForward else state.canScrollBackward if (distance == 0f || !canFollow || change.isConsumed) continue change.consume() @@ -242,7 +244,7 @@ fun Modifier.wheelScrollable(state: ScrollableState): Modifier = composed { // 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 { + glide.job = scope.launch(Motion.Scroll) { var travelled = 0f glide.remaining = total state.scroll(MutatePriority.UserInput) { @@ -265,7 +267,7 @@ private class WheelGlide { var job: Job? = null } -/** How far one line of the wheel takes a list; a notch is three lines, so three rows */ +/** How far one line of the wheel takes a list, before the scroll speed of the style: 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 */ diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 94c7a1629..ec90f1736 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -19,9 +19,6 @@ 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.animateContentSize import androidx.compose.animation.expandIn import androidx.compose.animation.expandVertically @@ -95,9 +92,11 @@ 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.Motion import com.lambda.gui.theme.Radius import com.lambda.gui.theme.Text import com.lambda.gui.theme.Type +import com.lambda.module.modules.client.Style import kotlin.math.max /** Where a [Menu] opens relative to the element it is declared in */ @@ -206,7 +205,7 @@ private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize @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 -> + FloatingPanel(open, position, onDismiss, RoundedCornerShape(Radius.Panel)) { panel -> Column(panel.padding(3.dp), content = content) } } @@ -251,9 +250,9 @@ private fun MenuPopup( val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } // One that is attached is of a piece with a square edge of its element: square there too, on whichever side it opened val shape = when { - !attached -> RoundedCornerShape(Radius.Medium) - position.upwards -> RoundedCornerShape(topStart = Radius.Medium, topEnd = Radius.Medium) - else -> RoundedCornerShape(bottomStart = Radius.Medium, bottomEnd = Radius.Medium) + !attached -> RoundedCornerShape(Radius.Menu) + position.upwards -> RoundedCornerShape(topStart = Radius.Menu, topEnd = Radius.Menu) + else -> RoundedCornerShape(bottomStart = Radius.Menu, bottomEnd = Radius.Menu) } FloatingPanel(open, position, onDismiss, shape, unfoldFrom) { panel -> CompositionLocalProvider(LocalMenuDismiss provides dismissAll, LocalMenuOpen provides open) { @@ -277,7 +276,7 @@ private fun MenuPopup( * 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) +val Unfold get() = Motion.panels /** * The part of the interface some floating panels are open on behalf of: the settings panel @@ -467,7 +466,7 @@ fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable Colum if (!open && visibility.isIdle && !visibility.currentState) return val colors = LambdaTheme.colors - val shape = RoundedCornerShape(Radius.Medium) + val shape = RoundedCornerShape(Radius.Menu) val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } Popup( popupPositionProvider = remember { @@ -622,7 +621,7 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { ContentColor(colors.onSurface) { Box( modifier = Modifier - .window(colors.panel, colors.border, RoundedCornerShape(Radius.Large), floating = true) + .window(colors.panel, colors.border, RoundedCornerShape(Radius.Panel), floating = true) .padding(6.dp), content = content ) @@ -653,7 +652,7 @@ fun Tooltip(text: String, modifier: Modifier = Modifier, content: @Composable () var bounds by remember { mutableStateOf(Rect.Zero) } LaunchedEffect(hovered) { if (!hovered) return@LaunchedEffect - awaitFrames(TOOLTIP_DELAY_MILLIS) + awaitFrames(Style.tooltipDelay.toLong()) visible = true } @@ -697,7 +696,7 @@ fun Tooltip(text: String, modifier: Modifier = Modifier, content: @Composable () style = Type.label, modifier = Modifier .widthIn(max = 220.dp) - .window(colors.panel, colors.border, RoundedCornerShape(Radius.Medium)) + .window(colors.panel, colors.border, RoundedCornerShape(Radius.Menu)) .padding(horizontal = 4.dp, vertical = 2.dp) ) } @@ -705,9 +704,6 @@ fun Tooltip(text: String, modifier: Modifier = Modifier, content: @Composable () } } -/** 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() diff --git a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt index ca410c54c..69700540a 100644 --- a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt +++ b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt @@ -40,9 +40,11 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp import com.lambda.gui.theme.LocalContentColor +import com.lambda.gui.theme.Motion import com.lambda.gui.theme.Text import com.lambda.gui.theme.Type import kotlin.math.roundToInt +import kotlinx.coroutines.withContext /** * A single line of text. When it is too long for the room it is given it is cut off, and @@ -74,17 +76,20 @@ fun SlidingText( 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 - } + // At the pace it is read at, whatever the style makes of the animations + withContext(Motion.Unscaled) { + slide.animateTo( + targetValue = 0f, + animationSpec = infiniteRepeatable( + keyframes { + durationMillis = REST_MILLIS + outMillis + END_REST_MILLIS + BACK_MILLIS + 0f at REST_MILLIS using LinearEasing + 1f at REST_MILLIS + outMillis + 1f at REST_MILLIS + outMillis + END_REST_MILLIS + } + ) ) - ) + } } Text( diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt index 5781fe682..301815734 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -39,6 +39,7 @@ 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.Look import com.lambda.gui.theme.LocalBackdropBlur import com.lambda.gui.theme.LocalOutlines import com.lambda.gui.theme.LocalUnderlay @@ -126,6 +127,7 @@ fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = drawWi maskFilter = MaskFilter.makeBlur(FilterBlurMode.NORMAL, blur) } onDrawBehind { + if (!Look.shadows) return@onDrawBehind clipPath(body, ClipOp.Difference) { clipRect(-reach, drop - reach, size.width + reach, size.height + drop + reach) { drawIntoCanvas { canvas -> diff --git a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt index 5fc77d616..84446bc37 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt @@ -29,6 +29,7 @@ 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 com.lambda.gui.theme.Motion import kotlinx.coroutines.Dispatchers import net.minecraft.client.texture.GlTexture import org.jetbrains.skia.BackendRenderTarget @@ -66,7 +67,8 @@ import org.lwjgl.opengl.GL30.glRenderbufferStorage internal class SceneHost(content: @Composable () -> Unit) : AutoCloseable { val platform = ScenePlatform() - private val recomposer = FrameRecomposer(Dispatchers.Unconfined) + // With the pace of every animation in the scene, which the style sets + private val recomposer = FrameRecomposer(Dispatchers.Unconfined + Motion) private var invalidated = true private val scene: ComposeScene = CanvasLayersComposeScene( diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt index 505936005..39d974f02 100644 --- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -310,7 +310,7 @@ private fun SettingsPanel(config: Config, open: Boolean, editor: HudEditorState) verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier .onSizeChanged { size = it } - .window(colors.panel, colors.border, RoundedCornerShape(Radius.Large), floating = true) + .window(colors.panel, colors.border, RoundedCornerShape(Radius.Panel), floating = true) // Dragged by any part of it that is not a control: those take their presses first .pointerInput(Unit) { awaitEachGesture { diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt index f12bb6807..14cc9f3dd 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -165,7 +165,7 @@ private fun Pane(title: String, entries: List>, modifier: Modifier, 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)) { + Box(Modifier.fillMaxSize().clip(RoundedCornerShape(Radius.Control)).background(colors.input)) { LazyColumn(state = list, modifier = Modifier.fillMaxSize().wheelScrollable(list)) { items(entries) { entry -> Row( diff --git a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt index 07b3747bd..21c7156e5 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt @@ -79,7 +79,7 @@ internal fun ColorPicker(setting: ColorSetting) { Spacer( Modifier .size(20.dp, 9.dp) - .clip(RoundedCornerShape(Radius.ExtraSmall)) + .clip(RoundedCornerShape(Radius.Box)) .drawBehind { drawCheckerboard() drawRect(color.toCompose()) @@ -121,7 +121,7 @@ private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { Modifier .fillMaxWidth() .aspectRatio(1.4f) - .clip(RoundedCornerShape(Radius.ExtraSmall)) + .clip(RoundedCornerShape(Radius.Box)) .drawBehind { drawRect(Color.hsv(hsb[0] * 360f, 1f, 1f)) drawRect(Brush.horizontalGradient(listOf(Color.White, Color.Transparent))) @@ -165,7 +165,7 @@ private fun Bar(fraction: Float, onChange: (Float) -> Unit, background: DrawScop Modifier .fillMaxWidth() .height(10.dp) - .clip(RoundedCornerShape(Radius.ExtraSmall)) + .clip(RoundedCornerShape(Radius.Box)) .drawBehind { background() val thumb = Size(4.dp.toPx(), size.height) diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 717f11a6a..727703c19 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -27,7 +27,6 @@ import androidx.compose.foundation.layout.RowScope 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.foundation.relocation.BringIntoViewRequester import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.shape.RoundedCornerShape @@ -49,12 +48,14 @@ import androidx.compose.ui.unit.dp import com.lambda.config.entries.Setting import com.lambda.gui.clickgui.Reveal import com.lambda.gui.component.LocalClickOnRelease +import com.lambda.gui.component.LocalKeyboardReachable import com.lambda.gui.component.RowHeight import com.lambda.gui.component.Tooltip import com.lambda.gui.component.hoverHighlight import com.lambda.gui.core.awaitFrames import com.lambda.gui.core.observe import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look import com.lambda.gui.theme.Radius import com.lambda.gui.theme.Text @@ -101,8 +102,9 @@ fun SettingRow(setting: Setting<*>) { } .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) { + // A setting is changed when the button is let go, so a slip of the hand can be taken back. + // One that is disabled is out of the keyboard's reach as it is out of the pointer's. + CompositionLocalProvider(LocalClickOnRelease provides true, LocalKeyboardReachable provides !disabled) { setting.compose() } } @@ -115,8 +117,9 @@ fun SettingRow(setting: Setting<*>) { */ internal fun Modifier.settingCell(): Modifier = composed { fillMaxWidth() - .padding(vertical = 0.5.dp) - .clip(RoundedCornerShape(Radius.Small)) + // Half above and half below, so the first and the last keep their distance from the edges too + .padding(vertical = Look.settingSpacing / 2) + .clip(RoundedCornerShape(Radius.Control)) .hoverHighlight(LambdaTheme.colors.hover) } diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt index adf9f2268..62ac4b9f1 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -65,6 +65,7 @@ import com.lambda.gui.component.mouseClickable import com.lambda.gui.core.observe import com.lambda.gui.theme.ContentColor import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Motion import com.lambda.gui.theme.Radius import com.lambda.gui.theme.Text import com.lambda.gui.theme.Type @@ -157,7 +158,7 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) .fillMaxWidth() .heightIn(min = RowHeight + 2.dp) // Square underneath, where its page hangs off it as the modules do off their category - .clip(RoundedCornerShape(topStart = Radius.Medium, topEnd = Radius.Medium)) + .clip(RoundedCornerShape(topStart = Radius.Window, topEnd = Radius.Window)) .background(colors.header) .then( if (!choice) Modifier @@ -180,7 +181,6 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) } } -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 @@ -188,10 +188,11 @@ private const val TAB_MILLIS = 160 * 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) }) + val millis = Motion.pageMillis + val slide = tween(millis) + return (fadeIn(tween(millis)) + slideInHorizontally(slide) { if (towardsEnd) it / 5 else -it / 5 }) + .togetherWith(fadeOut(tween(millis / 2)) + slideOutHorizontally(slide) { if (towardsEnd) -it / 5 else it / 5 }) + .using(SizeTransform(clip = true) { _, _ -> tween(millis) }) } /** Whether [setting] is somewhere in the layer, at any depth */ diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index d9adc9782..34ee9c160 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -17,6 +17,11 @@ package com.lambda.gui.theme +import androidx.compose.animation.core.FiniteAnimationSpec +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.VisibilityThreshold +import androidx.compose.animation.core.snap +import androidx.compose.animation.core.spring import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.text.selection.LocalTextSelectionColors import androidx.compose.foundation.text.selection.TextSelectionColors @@ -28,9 +33,12 @@ import androidx.compose.runtime.Immutable import androidx.compose.runtime.ReadOnlyComposable 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.Modifier +import androidx.compose.ui.MotionDurationScale import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow @@ -42,6 +50,8 @@ 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.Dp +import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -92,8 +102,14 @@ data class Palette( */ val onPrimary: Color = if (primary.luminance() > 0.2f) Color(0xFF1B1024) else Color.White - /** The filled part of a slider: the accent held back, as it covers far more than a tick does and has text over it */ - val trackFilled: Color = primary.copy(alpha = 0.6f) + /** Text drawn on [secondary], by the same rule */ + val onSecondary: Color = if (secondary.luminance() > 0.2f) Color(0xFF1B1024) else Color.White + + /** + * The filled part of a slider: the accent of a ticked box as it is under the light text of a + * dark theme, and thinned under the dark text of a light one, which could not be read on it. + */ + val trackFilled: Color = if (onControl.luminance() > 0.5f) primary else primary.copy(alpha = 0.6f) /** 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) @@ -103,24 +119,119 @@ data class Palette( } /** - * 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. + * What the [Style] module sets about the shape and the spacing of things, kept as state. A + * radius or a gap is asked for wherever a shape is built, a line drawn or a row padded, in a + * composable or out of one, and whatever asked follows the setting the moment it is changed. + * + * It is brought up to the settings once a frame with [refresh], before anything is composed. + * Setting a state to what it already is costs a comparison and wakes nothing. */ -val Hairline = 0.5.dp +internal object Look { + var windowRounding by mutableStateOf(3.dp) + private set + var panelRounding by mutableStateOf(5.dp) + private set + var menuRounding by mutableStateOf(3.dp) + private set + var controlRounding by mutableStateOf(2.dp) + private set + var outline by mutableStateOf(0.5.dp) + private set + var shadows by mutableStateOf(true) + private set + var windowWidth by mutableStateOf(90.dp) + private set + var windowGap by mutableStateOf(2.dp) + private set + var windowTop by mutableStateOf(94.dp) + private set + var modulePadding by mutableStateOf(4.dp) + private set + var panelPadding by mutableStateOf(4.dp) + private set + var settingSpacing by mutableStateOf(1.dp) + private set + var groupIndent by mutableStateOf(5.dp) + private set + + fun refresh() { + windowRounding = Style.windowRounding.dp + panelRounding = Style.panelRounding.dp + menuRounding = Style.menuRounding.dp + controlRounding = Style.controlRounding.dp + outline = Style.outlineWidth.dp + shadows = Style.shadows + windowWidth = Style.windowWidth.dp + windowGap = Style.windowGap.dp + windowTop = Style.windowTop.dp + modulePadding = Style.modulePadding.dp + panelPadding = Style.panelPadding.dp + settingSpacing = Style.settingSpacing.dp + groupIndent = Style.groupIndent.dp + } +} -/** Corner radii, by how much room the component has */ +/** + * How thick outlines are: one pixel at 1080p unless the style asks for more, and never less + * than one anywhere. Outlines are there to finish an edge, not to be looked at. + */ +val Hairline: Dp get() = Look.outline + +/** Corner radii, by what kind of thing has the corner. Each kind is rounded as the style asks for it. */ object Radius { - /** Checkboxes, colour swatches, the small parts inside a control */ - val ExtraSmall = 1.dp + /** Category windows, and the band of tabs that is made like their headers */ + val Window get() = Look.windowRounding + + /** The panels that pop out of a window, and dialogs */ + val Panel get() = Look.panelRounding + + /** Menus, dropdowns, search results and tooltips */ + val Menu get() = Look.menuRounding /** Controls and the blocks settings are grouped in */ - val Small = 2.dp + val Control get() = Look.controlRounding - /** Windows, menus and tooltips */ - val Medium = 3.dp + /** Checkboxes, colour swatches, the small parts inside a control */ + val Box get() = Look.controlRounding / 2 +} - /** The panels that pop out of a window, and dialogs */ - val Large = 5.dp +/** + * How fast the interface animates, for every animation in it at once: Compose asks this of the + * scene before it starts one. The durations they are written with are divided by the speed the + * style asks for, and with animations off they are over the moment they begin. + * + * A kind of animation the style switches off by itself is not scaled but replaced where it is + * asked for, by [windows], [panels] or [pageMillis]: an unfolding that snaps, a page that turns + * in no time. + */ +internal object Motion : MotionDurationScale { + override val scaleFactor get() = if (Style.animations) 1f / Style.animationSpeed else 0f + + /** How a category window unfolds out of its header */ + val windows: FiniteAnimationSpec get() = if (Style.windowAnimations) spring() else snap() + + /** + * How a panel, a menu or anything else that floats unfolds out of what opened it: on a + * spring quick enough to keep up with fast clicking. Nothing waits for it, a press is acted + * on at once. + */ + val panels: FiniteAnimationSpec + get() = if (Style.panelAnimations) Unfolding else snap() + + private val Unfolding = spring(stiffness = Spring.StiffnessMedium, visibilityThreshold = IntSize.VisibilityThreshold) + + /** How long one page of settings takes to give way to another */ + val pageMillis get() = if (Style.pageAnimations) 160 else 0 + + /** For the glide of a list after the wheel, which is the style's to have with or without the rest */ + val Scroll = object : MotionDurationScale { + override val scaleFactor get() = if (Style.smoothScrolling) 1f else 0f + } + + /** For what moves in order to be read rather than to look well, which keeps its own pace */ + val Unscaled = object : MotionDurationScale { + override val scaleFactor get() = 1f + } } /** 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 4896e5b2e..c60747d27 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -38,6 +38,9 @@ object Style : Module( ) { private const val DARK_THEME_GROUP = "Dark Theme" private const val LIGHT_THEME_GROUP = "Light Theme" + private const val SHAPE_GROUP = "Shape" + private const val MOTION_GROUP = "Motion" + private const val SPACING_GROUP = "Spacing" private enum class ThemeMode(override val displayName: String) : NamedEnum { Auto("Auto"), @@ -64,6 +67,31 @@ object Style : Module( 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 } + @Group(SHAPE_GROUP) var windowRounding by setting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") + @Group(SHAPE_GROUP) var panelRounding by setting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") + @Group(SHAPE_GROUP) val menuRounding by setting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") + @Group(SHAPE_GROUP) val controlRounding by setting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") + @Group(SHAPE_GROUP) var outlineWidth by setting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } + @Group(SHAPE_GROUP) val shadows by setting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") + @Group(SHAPE_GROUP) var windowWidth by setting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") + @Group(SHAPE_GROUP) val settingsWidth by setting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") + + @Group(SPACING_GROUP) var windowGap by setting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") + @Group(SPACING_GROUP) var windowTop by setting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") + @Group(SPACING_GROUP) var modulePadding by setting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") + @Group(SPACING_GROUP) var panelPadding by setting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") + @Group(SPACING_GROUP) var settingSpacing by setting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") + @Group(SPACING_GROUP) var groupIndent by setting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") + + @Group(MOTION_GROUP) var animations by setting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") + @Group(MOTION_GROUP) val animationSpeed by setting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } + @Group(MOTION_GROUP) val windowAnimations by setting("Window Animations", true, "Category windows unfold out of their headers") { animations } + @Group(MOTION_GROUP) var panelAnimations by setting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } + @Group(MOTION_GROUP) val pageAnimations by setting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } + @Group(MOTION_GROUP) val smoothScrolling by setting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") + @Group(MOTION_GROUP) val scrollSpeed by setting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") + @Group(MOTION_GROUP) val tooltipDelay by setting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") + /** The colours the glow runs between, which are the theme's: what suits dark glass is lost around light */ val glowColorA: Color get() = theme.glowA val glowColorB: Color get() = theme.glowB @@ -71,8 +99,9 @@ object Style : Module( @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( PaletteSettings( this, - // A brighter rose than the header rather than a paler one: pale, it is a pastel pink - primary = Color(226, 88, 120), + // A shade lighter than the header and a shade less full, so it is plain to see without being loud: a panel is + // read by its band of tabs, and what is set in it is not to be taken for a module that is on + primary = Color(194, 86, 114), secondary = Color(255, 168, 158), surface = Color(60, 48, 52, 165), panel = Color(48, 38, 42, 200), @@ -84,8 +113,9 @@ object Style : Module( // A shade of the header, as strong and a good step darker: greyed and left as light it turns to a dusty pink moduleEnabled = Color(138, 46, 72), onModuleEnabled = Color(255, 240, 244), - // Controls are a tier above anything they sit on, and say what they hold in plain text - control = Color(92, 75, 81), + // Every control is the one rose: a chip, a button and a key cap are filled as a slider + // and a ticked box are, so that whatever can be set looks like one kind of thing + control = Color(194, 86, 114), controlMenu = Color(48, 38, 42), controlSelected = Color(81, 65, 71), onControl = Color(246, 236, 239), @@ -115,9 +145,12 @@ object Style : Module( onSurfaceVariant = Color(128, 108, 117), header = Color(214, 55, 88, 242), onHeader = Color(255, 250, 251), - moduleEnabled = Color(243, 217, 225), - onModuleEnabled = Color(176, 0, 70), - control = Color(216, 202, 209), + // Filled a step under the header with its text in white, as in the dark theme: a tint of + // pink under crimson text was too faint to pick the enabled out of a list at a glance + moduleEnabled = Color(226, 104, 130), + onModuleEnabled = Color(255, 250, 251), + // The rose of the fill of a slider, which is the accent thinned for the dark text over it + control = Color(214, 114, 136), controlMenu = Color(240, 233, 237), controlSelected = Color(228, 210, 218), onControl = Color(64, 44, 54), From 680f42475c032cff0af25a931c15d2a29ee68269 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:19:39 +0000 Subject: [PATCH 10/34] optional inline settings, colour tweaks, multiple setting menus open at once --- src/gametest/kotlin/com/lambda/GuiTest.kt | 85 +++++++++++ .../lambda/config/settings/NumericSetting.kt | 33 +++- .../settings/complex/BlockPosSetting.kt | 6 +- .../config/settings/complex/Vec3dSetting.kt | 6 +- .../com/lambda/gui/clickgui/CategoryWindow.kt | 36 ++++- .../com/lambda/gui/clickgui/ClickGui.kt | 74 +++++++-- .../com/lambda/gui/clickgui/SettingsPanel.kt | 142 +++++++++++++----- .../com/lambda/gui/component/Controls.kt | 75 ++++++--- .../com/lambda/gui/component/Pointer.kt | 5 +- .../kotlin/com/lambda/gui/component/Popups.kt | 9 +- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 41 ++++- src/main/kotlin/com/lambda/gui/menu/Search.kt | 13 +- .../lambda/gui/settings/CollectionEditor.kt | 21 +-- .../com/lambda/gui/settings/SettingRow.kt | 19 +-- .../com/lambda/module/modules/client/Style.kt | 12 +- 15 files changed, 439 insertions(+), 138 deletions(-) diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt index 9a216a5ab..443bfd92c 100644 --- a/src/gametest/kotlin/com/lambda/GuiTest.kt +++ b/src/gametest/kotlin/com/lambda/GuiTest.kt @@ -525,6 +525,55 @@ object GuiTest : FabricClientGameTest { context.waitTicks(5) context.closeGui() + // Where the style has them inline, a module's settings drop down under it instead: as + // wide as its window, pushing the modules under it down, whatever they hold + context.runOnClient { + Style.inlineSettings = true + GuiConfig.resetWindows() + } + context.openClickGui() + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) + context.waitTicks(3) + context.takeScreenshot("gui-11g-inline-settings-dropping") + context.waitTicks(15) + context.takeScreenshot("gui-11h-inline-settings") + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("targeting range") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(40) + context.takeScreenshot("gui-11i-inline-settings-with-tabs") + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("window gap") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(40) + context.takeScreenshot("gui-11j-inline-settings-with-groups") + + // Several can be open at once where the style allows it: the one the search turns to + // next opens beside the last instead of in its place... + context.runOnClient { Style.multipleSettings = true } + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("targeting range") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(40) + context.takeScreenshot("gui-11k-inline-settings-of-two") + // ...and with settings no longer inline, the ones that are open are out as panels + context.runOnClient { Style.inlineSettings = false } + context.waitTicks(20) + context.takeScreenshot("gui-11l-panels-of-two") + // Held to one at a time again, the last one opened is the one that stays + context.runOnClient { Style.multipleSettings = false } + context.waitTicks(20) + context.takeScreenshot("gui-11m-panel-of-one") + context.closeGui() + // The glow is in the colours of the theme in use: the dark one's here, the light one's below context.runOnClient { Style.glow = true } context.openClickGui() @@ -561,6 +610,30 @@ object GuiTest : FabricClientGameTest { context.openClickGui() context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) context.waitTicks(10) + // The scale of the interface is the one bar that waits for the button to be let go: held, + // it shows what the scale is about to be and nothing moves, least of all the bar itself + context.input.setCursorPos(700.0 * DENSITY, 229.0 * DENSITY) + context.waitTicks(2) + context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(5) { + context.input.moveCursor(3.0 * DENSITY, 0.0) + context.waitTick() + } + context.waitTicks(5) + context.takeScreenshot("gui-14a-scale-held") + check(context.computeOnClient { Style.scale } == 1f) { "The scale changed while its bar was still held" } + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(10) + context.takeScreenshot("gui-14b-scale-applied") + check(context.computeOnClient { Style.scale } > 1f) { "The scale was not applied when its bar was let go" } + // At the largest scale there is, nothing is off the screen: the windows close up to fit, + // the search field clears the menus, and the settings that would undo it are in reach + context.runOnClient { Style.scale = 1.5f } + context.waitTicks(15) + context.takeScreenshot("gui-14c-scale-largest") + context.runOnClient { Style.scale = 1f } + context.waitTicks(10) + context.input.setCursorPos(700.0 * DENSITY, 243.0 * DENSITY) context.waitTicks(2) context.dragBy(-30.0, 0.0) @@ -754,6 +827,18 @@ object GuiTest : FabricClientGameTest { context.takeScreenshot("gui-19c-dependent-enabled-again") context.closeGui() + // Settings of one name in many configs are told apart by where each is: its config, and + // the tab and group it is under + context.openClickGui() + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("airplace") + context.waitTicks(15) + context.takeScreenshot("gui-20-search-same-name") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + context.closeGui() + singleplayer.close() } diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index d7848d1bf..a0f2b6b18 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -87,6 +87,12 @@ abstract class NumericSetting( private val formatter = NumberFormat.getNumberInstance(Locale.getDefault()) + /** + * Whether dragging the bar only sets the value once the button is let go, see [appliedOnRelease]. + * Until then the bar and its number show what the value is about to be. + */ + var appliedOnRelease = false + override fun toString() = "${formatter.format(value)}$unit" /** @@ -124,7 +130,10 @@ abstract class NumericSetting( fun at(steps: Long) = convert(range.start.decimal + step.decimal * BigDecimal.valueOf(steps)) fun stepsOf(value: Double) = ((value - min) / step.toDouble()).roundToLong() // 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)) + // What the bar has been dragged to but not let go at, for a setting that waits for that + var held by remember { mutableStateOf(null) } + val shown = held ?: value + val fraction by animateFloatAsState(((shown.toDouble() - min) / (max - min)).toFloat().coerceIn(0f, 1f)) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), @@ -134,8 +143,12 @@ abstract class NumericSetting( .clip(RoundedCornerShape(Radius.Control)) .background(colors.track) .drawBehind { drawRect(colors.trackFilled, size = Size(size.width * fraction, size.height)) } - .scrubbable { position, size -> - this.value = at(stepsOf(min + (position.x / size.width).coerceIn(0f, 1f) * (max - min))) + .scrubbable(onEnd = { + held?.let { this.value = it } + held = null + }) { position, size -> + val dragged = at(stepsOf(min + (position.x / size.width).coerceIn(0f, 1f) * (max - min))) + if (appliedOnRelease) held = dragged.coerceIn(range) else this.value = dragged } .focusRequester(bar) .keyboardFocusable { event -> @@ -150,7 +163,12 @@ abstract class NumericSetting( .padding(horizontal = 3.dp) ) { Text(name, Modifier.weight(1f), colors.onControl, maxLines = 1) - Text(label, Modifier.mouseClickable(keyboard = false) { typing = true }, colors.onControl, maxLines = 1) + Text( + text = held?.let { "${formatter.format(it)}$unit" } ?: label, + modifier = Modifier.mouseClickable(keyboard = false) { typing = true }, + color = colors.onControl, + maxLines = 1, + ) } } @@ -195,6 +213,13 @@ abstract class NumericSetting( /** How far from its default, as a share of its step, a number may be and still be the default: a rounding error, never a step */ private const val SAME = 1e-4 +/** + * Has dragging the bar set the value only when the button is let go, where it otherwise follows + * the pointer. For a value that moves the bar it is set on, the scale of the interface: applied + * as it is dragged, the bar would shift and resize under the pointer that is setting it. + */ +fun > S.appliedOnRelease() = apply { appliedOnRelease = true } + @Suppress("unchecked_cast") @ConfigEditorD5l fun SettingEditBuilder.range(range: ClosedRange) where T : Number, T : Comparable { diff --git a/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt index 531350e17..f7479874a 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt @@ -57,9 +57,9 @@ class BlockPosSetting( override fun compose() { val pos by observe { value.toImmutable() } Labeled(name) { - NumberInput(pos.x, { value = BlockPos(it.roundToInt(), pos.y, pos.z) }, Modifier.width(NumberFieldWidth)) - NumberInput(pos.y, { value = BlockPos(pos.x, it.roundToInt(), pos.z) }, Modifier.width(NumberFieldWidth)) - NumberInput(pos.z, { value = BlockPos(pos.x, pos.y, it.roundToInt()) }, Modifier.width(NumberFieldWidth)) + NumberInput(pos.x, { value = BlockPos(it.roundToInt(), pos.y, pos.z) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) + NumberInput(pos.y, { value = BlockPos(pos.x, it.roundToInt(), pos.z) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) + NumberInput(pos.z, { value = BlockPos(pos.x, pos.y, it.roundToInt()) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) Tooltip("Use the block you are looking at") { Button("Target", Modifier.height(RowHeight)) { mc.crosshairTarget?.blockResult?.blockPos?.let { value = it } 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 722e9b9a8..777323fae 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt @@ -49,9 +49,9 @@ class Vec3dSetting( override fun compose() { val vec by observe { value } Labeled(name) { - NumberInput(vec.x, { value = Vec3d(it, vec.y, vec.z) }, Modifier.width(NumberFieldWidth)) - NumberInput(vec.y, { value = Vec3d(vec.x, it, vec.z) }, Modifier.width(NumberFieldWidth)) - NumberInput(vec.z, { value = Vec3d(vec.x, vec.y, it) }, Modifier.width(NumberFieldWidth)) + NumberInput(vec.x, { value = Vec3d(it, vec.y, vec.z) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) + NumberInput(vec.y, { value = Vec3d(vec.x, it, vec.z) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) + NumberInput(vec.z, { value = Vec3d(vec.x, vec.y, it) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) } } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index 8c1649d2c..bbfb3ae95 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -93,6 +93,9 @@ internal val CategoryWindowGap get() = Look.windowGap /** Room between the edge of a window and the text of its rows */ private val RowPadding get() = Look.modulePadding +/** How much of a window is always kept on the screen from its top: its header and a module or two */ +private val Reach = 40.dp + /** How far from its place in the row, in dp either way, a window may be left and still count as in it */ private const val InRow = 1.5f @@ -105,7 +108,8 @@ private val Emboss = Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05 /** * 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. + * opens its settings; right click on the header folds the window away. The settings are a panel + * beside the module, one of [panels], unless the style has them [inline], under the module. * * 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, @@ -118,8 +122,9 @@ internal fun CategoryWindow( defaultPosition: DpOffset, bounds: MutableMap, snapping: Boolean, - edited: Module?, + edited: List, panels: List, + inline: ((Module) -> SettingsPanelState)?, onEdit: (Module) -> Unit, onFocus: () -> Unit, modifier: Modifier = Modifier, @@ -147,7 +152,15 @@ internal fun CategoryWindow( 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 + } ?: (position ?: defaultPosition).let { at -> + // Never off the screen, wherever it was left: a screen made smaller since, by a larger + // scale or a smaller window, would otherwise put it out of reach + val screenWidth = with(density) { screen.width.toDp() } + DpOffset( + at.x.coerceIn(0.dp, (screenWidth - CategoryWindowWidth).coerceAtLeast(0.dp)), + at.y.coerceIn(0.dp, (screenHeight - Reach).coerceAtLeast(0.dp)), + ) + } val currentPosition by rememberUpdatedState(shownPosition) DisposableEffect(tag) { onDispose { bounds -= tag } @@ -200,7 +213,7 @@ internal fun CategoryWindow( ) { 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) + if (!collapsed) edited.filter { it in modules }.forEach(onEdit) place(currentPosition, !collapsed) }) .padding(horizontal = RowPadding, vertical = 2.dp) @@ -213,7 +226,9 @@ internal fun CategoryWindow( 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 } } + // Looked up here, where a panel being added to the list has this run again to tell it + val hanging = panels.filter { it.module in modules } + SideEffect { hanging.forEach { it.settled = settled } } AnimatedVisibility( visibleState = unfolded, enter = expandVertically(Motion.windows), @@ -224,10 +239,15 @@ internal fun CategoryWindow( modules.forEach { module -> ModuleRow( module = module, - isEdited = module == edited, + isEdited = module in edited, + // Settings under the module are plainly its own: it is only pressed in + // for ones that are out beside it, to show which row they hang off + pressedIn = inline == null, panel = panels.find { it.module == module }, onEdit = { onEdit(module) }, ) + // Where the style has settings drop down under their module instead + if (inline != null) InlineSettings(inline(module), open = module in edited) } } } @@ -237,13 +257,13 @@ internal fun CategoryWindow( /** 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) { +private fun ModuleRow(module: Module, isEdited: Boolean, pressedIn: Boolean, panel: SettingsPanelState?, onEdit: () -> Unit) { val colors = LambdaTheme.colors val enabled by observe { module.isEnabled } val embossed by observe { Style.emboss } 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()) + val pressed by animateColorAsState(if (isEdited && pressedIn) colors.inset.copy(alpha = colors.inset.alpha / 2) 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 diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index f8eae0667..b5b75b5c6 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -22,6 +22,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateListOf @@ -37,6 +38,7 @@ import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex @@ -58,6 +60,7 @@ import com.lambda.module.HudModule import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.module.modules.client.AutoUpdater +import com.lambda.module.modules.client.Style /** 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 get() = Look.windowTop @@ -68,6 +71,9 @@ private val WindowRowTop get() = Look.windowTop */ internal val ClickGuiCategories = ModuleTag.defaults - ModuleTag.HUD +/** What the row of windows was last laid out with, and whether the interface was open then */ +private class RowLayout(var row: Triple, var shown: Boolean = false) + /** A window the click GUI shows over everything else until it is dismissed */ internal sealed interface ClickGuiDialog { data object About : ClickGuiDialog @@ -98,16 +104,30 @@ internal fun ClickGui() { 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) } + // The modules whose settings are open, the last opened last: one of them, unless the style + // lets several be open at once. A 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 + val edited = remember { mutableStateListOf() } 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 stateOf(module: Module) = panelStates.getOrPut(module) { SettingsPanelState(module) } + // Beside the module as a panel, or where the style asks for it, dropped down under it + val inline by observe { Style.inlineSettings } + val several by observe { Style.multipleSettings } fun edit(module: Module) { - edited = module - val panel = panelStates.getOrPut(module) { SettingsPanelState(module) } - if (panel !in panels) panels += panel + if (!several) edited.clear() + if (module !in edited) edited += module + val panel = stateOf(module) + if (!inline && panel !in panels) panels += panel + } + // What a press beside the settings does: puts them away, all of them where several are open + fun dismiss() = edited.clear() + // The style changed with settings open: held to one at a time again, the last opened is the + // one that stays, and no longer under their modules, they are out beside them as panels + LaunchedEffect(inline, several) { + if (!several && edited.size > 1) edited.removeRange(0, edited.size - 1) + if (!inline) edited.forEach { module -> stateOf(module).let { if (it !in panels) panels += it } } } // A setting the search points at is shown in the settings of its module @@ -121,35 +141,58 @@ internal fun ClickGui() { val shown = LocalShown.current LaunchedEffect(shown) { if (!shown && !GuiConfig.keepSettingsOpen) { - edited = null + edited.clear() panels.clear() } } + // The row is laid out anew when the style changes what it is made of, the width of a window, + // the gap between two or how far down they start: every window goes back to its place in it. + // A row spaced or sized differently around windows left where they were would not be one, and + // which of those were meant to be elsewhere is not something their places can tell. Only while + // the interface is open, which is when the style is being set: what it was changed to in the + // meantime, by a config being loaded, moves nothing. + val row = Triple(CategoryWindowWidth, CategoryWindowGap, WindowRowTop) + val laidOut = remember { RowLayout(row) } + SideEffect { + if (row != laidOut.row && shown && laidOut.shown) { + GuiConfig.windows = GuiConfig.windows.mapValues { GuiConfig.WindowPlacement.inRow(it.value.collapsed) } + } + laidOut.row = row + laidOut.shown = shown + } + // 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(keyboard = false) { edited = null }) { + Box(Modifier.fillMaxSize().mouseClickable(keyboard = false, onClick = ::dismiss)) { // 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) - // A row too wide for the screen starts at its edge and runs off the far side, rather than off both - val rowStart = ((with(density) { screen.width.toDp() } - rowWidth) / 2).coerceAtLeast(0.dp) + // On a screen too narrow for the row, which a large scale makes of any screen, the windows + // close up and overlap like a hand of cards rather than run off its edge: every one of + // them keeps a strip that can be pressed, which brings it to the front + val screenWidth = with(density) { screen.width.toDp() } + val pitch = (CategoryWindowWidth + CategoryWindowGap) + .coerceAtMost((screenWidth - CategoryWindowWidth) / (inRow - 1).coerceAtLeast(1)) + .coerceAtLeast(0.dp) + val rowWidth = CategoryWindowWidth + pitch * (inRow - 1) + val rowStart = ((screenWidth - rowWidth) / 2).coerceAtLeast(0.dp) tags.forEachIndexed { index, tag -> key(tag) { CategoryWindow( tag = tag, - defaultPosition = DpOffset(rowStart + (CategoryWindowWidth + CategoryWindowGap) * index, WindowRowTop), + defaultPosition = DpOffset(rowStart + pitch * index, WindowRowTop), bounds = bounds, snapping = snapping, edited = edited, panels = panels, - onEdit = { module -> if (module == edited) edited = null else edit(module) }, + inline = if (inline) ::stateOf else null, + onEdit = { module -> if (module in edited) edited -= module else edit(module) }, onFocus = { stacking.remove(tag) stacking.add(tag) @@ -163,7 +206,8 @@ internal fun ClickGui() { key(panel.module) { SettingsPanel( panel = panel, - open = panel.module == edited, + // One left open when the style is changed to have them inline folds away + open = panel.module in edited && !inline, onClosed = { panels -= panel }, modifier = Modifier.zIndex(stacking.size.toFloat()) ) @@ -178,7 +222,7 @@ internal fun ClickGui() { .pointerInput(Unit) { awaitPointerEventScope { while (true) { - if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) edited = null + if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) dismiss() } } } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index b451e98e6..bd16657f1 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -27,9 +27,12 @@ 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.ExperimentalFoundationApi +import androidx.compose.foundation.ScrollState import androidx.compose.foundation.background 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.Spacer import androidx.compose.foundation.layout.fillMaxWidth @@ -40,6 +43,8 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable @@ -56,9 +61,12 @@ 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.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerHoverIcon import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.layout @@ -77,6 +85,7 @@ 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.Expandable import com.lambda.gui.component.LocalClickOnRelease import com.lambda.gui.component.LocalPopupHost import com.lambda.gui.component.PopupHost @@ -91,6 +100,7 @@ import com.lambda.gui.component.mouseDraggable import com.lambda.gui.component.window import com.lambda.gui.core.LocalShown import com.lambda.gui.core.ResizeVerticalIcon +import com.lambda.gui.core.awaitFrames import com.lambda.gui.core.observe import com.lambda.gui.menu.MenuBarHeight import com.lambda.gui.settings.SettingRow @@ -106,10 +116,10 @@ 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.Style import com.lambda.module.modules.client.AutoUpdater -import kotlinx.coroutines.launch +import com.lambda.module.modules.client.Style 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 @@ -234,42 +244,8 @@ internal fun SettingsPanel(panel: SettingsPanelState, open: Boolean, onClosed: ( .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) - } - } - } - } - } - } + Column(Modifier.padding(Padding)) { Pages(panel, scroll) } } // Only there while there is something to gain from it, or to take back if (scroll.maxValue > 0 || lift > 0f) { @@ -290,6 +266,98 @@ internal fun SettingsPanel(panel: SettingsPanelState, open: Boolean, onClosed: ( } } +/** + * A module's settings dropped down under its row, inside its window: what the style can have in + * place of the panel beside it. They are as wide as the window, whatever they hold, and push the + * modules under them down while [open]; a name or a value too long for the room slides along + * under the pointer, as it does anywhere. They scroll with the list they are in, and come into + * view when they open. + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(open) { + if (open) { + awaitFrames(SETTLE_MILLIS) + intoView.bringIntoView() + } + } + Expandable(open) { + val colors = LambdaTheme.colors + Column( + Modifier + .fillMaxWidth() + .bringIntoViewRequester(intoView) + // Filled as a panel beside the module would be and then shaded a little, a quarter + // as far as what is pressed in: inside a window the fill alone is too close to it + .background(colors.panel) + .background(colors.inset.copy(alpha = colors.inset.alpha / 4)) + // And darker at its top and bottom edges, as what is set into a surface is where + // the surface overhangs it + .drawWithCache { + val depth = InsetShadow.toPx().coerceAtMost(size.height / 2) + val dark = colors.inset.copy(alpha = colors.inset.alpha / 2) + val top = Brush.verticalGradient(listOf(dark, Color.Transparent), 0f, depth) + val bottom = Brush.verticalGradient(listOf(Color.Transparent, dark), size.height - depth, size.height) + onDrawBehind { + drawRect(top, size = Size(size.width, depth)) + drawRect(bottom, Offset(0f, size.height - depth), Size(size.width, depth)) + } + } + .padding(Padding / 2) + ) { Pages(panel, scroll = null) } + } +} + +/** How far the shade at the top and bottom of settings under their module reaches into them */ +private val InsetShadow = 5.dp + +/** How long settings take to drop down, before they are where they will stay */ +private const val SETTLE_MILLIS = 200L + +/** + * What a module's settings are made of, in a panel or dropped down under its row: the strip + * that turns their pages, and under it the page turned to. In a panel the page scrolls by + * itself, on [scroll], under a strip that stays put; without one it is as long as it is. + */ +@Composable +private fun ColumnScope.Pages(panel: SettingsPanelState, scroll: ScrollState?) { + 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() + + SoftTextShadow { + if (pages.size > 1) PageStrip(pages, page) { + panel.page = it + // A page turned to by hand starts at its top + if (scroll != null) scope.launch { scroll.scrollTo(0) } + } + // Turned like the tabs a module's settings bring + val turned = @Composable { + 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) + } + } + } + } + if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } else turned() + } +} + /** * 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. diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt index 02fd4d15f..09c8a86a6 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -78,6 +78,7 @@ 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.Layout import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged @@ -85,6 +86,7 @@ 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.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp @@ -474,26 +476,18 @@ fun Dropdown( ) { 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) - } + LabeledRow(label, modifier) { + Box(Modifier.onSizeChanged { chip = it }) { + // A choice too long for the room the chip is given slides along under the pointer + 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) } } } @@ -501,6 +495,47 @@ fun Dropdown( } } +/** + * A row with [label] at its start and, at its end, whatever edits the value it names. + * + * With room for both, each is as wide as it likes and the room left over lies between them. + * Without, as in the width of a window when settings drop down under their module, neither is + * let crowd the other out: the editor gives way first, down to three fifths of the row, and the + * label has what is left. What does not fit of either slides along under the pointer. + */ +@Composable +fun LabeledRow(label: String, modifier: Modifier = Modifier, editor: @Composable RowScope.() -> Unit) { + Layout( + content = { + Text(label, maxLines = 1) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(LabelGap), content = editor) + }, + modifier = modifier.fillMaxWidth().heightIn(min = RowHeight), + ) { (name, edited), constraints -> + val gap = LabelGap.roundToPx() + val loose = constraints.copy(minWidth = 0, minHeight = 0) + val room = constraints.maxWidth + val wanted = edited.maxIntrinsicWidth(constraints.maxHeight) + // Asked how wide it would like to be, which is what sizes a panel: as wide as both + val editorWidth = + if (!constraints.hasBoundedWidth) wanted + else wanted.coerceAtMost(maxOf(room - name.maxIntrinsicWidth(constraints.maxHeight) - gap, room * 3 / 5)) + val editor = edited.measure(loose.copy(maxWidth = editorWidth.coerceAtLeast(0))) + val nameRoom = if (constraints.hasBoundedWidth) (room - editor.width - gap).coerceAtLeast(0) else Constraints.Infinity + val text = name.measure(loose.copy(maxWidth = nameRoom)) + + val width = if (constraints.hasBoundedWidth) room else text.width + gap + editor.width + val height = maxOf(text.height, editor.height, constraints.minHeight) + layout(width, height) { + text.place(0, (height - text.height) / 2) + editor.place(width - editor.width, (height - editor.height) / 2) + } + } +} + +/** Room between a label and what edits its value, and between the parts of that */ +private val LabelGap = 3.dp + /** 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) { diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt index 3e8c95316..82be906b2 100644 --- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -200,9 +200,11 @@ fun Modifier.mouseDraggable( /** * 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. + * [onEnd] is called once it has been. */ -fun Modifier.scrubbable(onScrub: (position: Offset, size: IntSize) -> Unit): Modifier = composed { +fun Modifier.scrubbable(onEnd: () -> Unit = {}, onScrub: (position: Offset, size: IntSize) -> Unit): Modifier = composed { val currentOnScrub by rememberUpdatedState(onScrub) + val currentOnEnd by rememberUpdatedState(onEnd) pointerInput(Unit) { awaitEachGesture { // On a desktop only the left button counts as the first down of a gesture @@ -213,6 +215,7 @@ fun Modifier.scrubbable(onScrub: (position: Offset, size: IntSize) -> Unit): Mod change.consume() currentOnScrub(change.position, size) } + currentOnEnd() } } } diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index ec90f1736..b3837b2dd 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -448,8 +448,8 @@ private class UnfoldingPosition( /** * 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]. + * keyboard: what a search field shows its results in. It is centred under the element, however + * much wider than it the results make it. A press outside of it calls [onDismiss]. * * It unfolds downwards while [open] and folds back up once it is not, and in between it grows * and shrinks with what it lists rather than jumping from one length to the next. @@ -470,7 +470,10 @@ fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable Colum 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) } + positionProvider { anchor, window, popup -> + val centred = anchor.left + (anchor.width - popup.width) / 2 + IntOffset(centred.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), anchor.bottom) + } }, onDismissRequest = { if (open) onDismiss() }, properties = PopupProperties(focusable = false), diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index cd3f35418..80562a215 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -20,7 +20,9 @@ package com.lambda.gui.menu import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row @@ -28,7 +30,9 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.relocation.BringIntoViewRequester @@ -45,6 +49,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType @@ -54,7 +59,10 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import com.lambda.Lambda.REPO_URL import com.lambda.Lambda.mc @@ -80,6 +88,7 @@ import com.lambda.gui.component.glass import com.lambda.gui.component.hoverHighlight import com.lambda.gui.component.mouseClickable import com.lambda.gui.component.rememberLast +import com.lambda.gui.component.rememberTexture import com.lambda.gui.core.observe import com.lambda.gui.core.observeSafe import com.lambda.gui.hud.HudConfig @@ -112,29 +121,40 @@ internal val MenuBarHeight = 15.dp @Composable internal fun MenuBar(modifier: Modifier = Modifier) { val colors = LambdaTheme.colors + // The search field is in the middle of the bar for as long as the menus leave the middle + // free. On a bar too short for that, a large scale on a narrow screen, it moves over just + // far enough to clear them. + var bar by remember { mutableStateOf(IntSize.Zero) } + var menus by remember { mutableStateOf(IntSize.Zero) } + var search by remember { mutableStateOf(IntSize.Zero) } Box( contentAlignment = Alignment.Center, modifier = modifier .fillMaxWidth() .height(MenuBarHeight) + .onSizeChanged { bar = it } // 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() } + Row(Modifier.align(Alignment.CenterStart).fillMaxHeight().onSizeChanged { menus = it }, verticalAlignment = Alignment.CenterVertically) { + BarMenu("Lambda", icon = "textures/lambda.png") { LambdaMenu() } BarMenu("Modules") { ModulesMenu() } BarMenu("Automation") { AutomationMenu() } BarMenu("Minecraft") { MinecraftMenu() } BarMenu("Help") { HelpMenu() } } - SearchField() + SearchField( + Modifier + .onSizeChanged { search = it } + .offset { IntOffset((menus.width - (bar.width - search.width) / 2).coerceAtLeast(0), 0) } + ) } } -/** An entry of the bar that drops a menu down underneath itself */ +/** An entry of the bar that drops a menu down underneath itself, with the texture at [icon] before its [label] if it has one */ @Composable -private fun BarMenu(label: String, content: @Composable ColumnScope.() -> Unit) { +private fun BarMenu(label: String, icon: String? = null, content: @Composable ColumnScope.() -> Unit) { val menu = remember { MenuState() } Box( contentAlignment = Alignment.Center, @@ -144,11 +164,20 @@ private fun BarMenu(label: String, content: @Composable ColumnScope.() -> Unit) .mouseClickable(onClick = menu::toggle) .padding(horizontal = 6.dp) ) { - Text(label, maxLines = 1) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { + // Drawn far smaller than it is made, which only looks clean when it is filtered well + if (icon != null) Image(rememberTexture(icon), contentDescription = null, Modifier.size(IconSize), filterQuality = FilterQuality.High) + Text(label, maxLines = 1) + } + // Beside the label and not after it in its row, where the menu, once open, would be + // one more thing for the row to space out and the entry would grow by a gap Menu(menu.isOpen, onDismiss = menu::dismiss, content = content) } } +/** Edge length of the logo in the bar: the height of a capital of the Minecraft font and a little over */ +private val IconSize = 9.dp + /** * The search field of the bar. Results drop down under it as the query is typed, and one of * them is always marked, the first to begin with. The arrow keys, or Tab and Shift with Tab, diff --git a/src/main/kotlin/com/lambda/gui/menu/Search.kt b/src/main/kotlin/com/lambda/gui/menu/Search.kt index 646950e99..d570cdf42 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Search.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt @@ -51,9 +51,14 @@ internal object Search { override fun choose() = Reveal.show(module) } - class OfSetting(val setting: Setting<*>, val config: Config) : Result { + /** + * A setting of [config], under the tabs and groups of [path] from the outermost in. Its + * origin spells all of that out: settings of one name are in many configs, every module + * that builds has an Air Place, and the origin is all that tells them apart in a list. + */ + class OfSetting(val setting: Setting<*>, val config: Config, path: List) : Result { override val name get() = setting.name - override val origin = (listOf(config.name) + setting.getConfigCommandPath()).dropLast(1).joinToString(" \u00bb ") + override val origin = (listOf(config.name) + path).joinToString(" \u00bb ") override fun choose() = Reveal.show(config, setting) } @@ -101,9 +106,9 @@ internal object Search { ConfigLoader.configCategories.forEach { category -> category.configs.forEach { config -> if (hidden(config)) return@forEach - config.settingLayers.forEachEntry { _, single -> + config.settingLayers.forEachEntry { path, single -> val setting = single.entry - if (setting.visibility()) consider({ Result.OfSetting(setting, config) }, 0, setting.name) + if (setting.visibility()) consider({ Result.OfSetting(setting, config, path.map { it.name }) }, 0, setting.name) } } } diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt index 14cc9f3dd..ba9aed782 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -77,7 +77,7 @@ internal fun CollectionButton(setting: CollectionSetting) { Labeled(setting.name) { Chip(onClick = { editing = true }) { - Text("$count selected", maxLines = 1) + Text("$count selected", Modifier.weight(1f, fill = false), maxLines = 1) Ellipsis() } } @@ -123,19 +123,12 @@ internal fun BlockPicker(setting: BlockSetting) { val block by observe { setting.value } var picking by remember { mutableStateOf(false) } - // The chip has what the name leaves: a block with a long name slides along under the pointer - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(3.dp), - modifier = Modifier.fillMaxWidth().heightIn(min = RowHeight).padding(start = 3.dp) - ) { - Text(setting.name, maxLines = 1) - Box(Modifier.weight(1f), contentAlignment = Alignment.CenterEnd) { - Chip(onClick = { picking = true }) { - Box(Modifier.size(IconSize)) { ItemIcon(ItemStack(block.asItem()), IconSize) } - Text(BlockSerializer.stringify(block), Modifier.weight(1f, fill = false), maxLines = 1) - Ellipsis() - } + // A block with a long name slides along under the pointer in the room its chip is given + Labeled(setting.name) { + Chip(onClick = { picking = true }) { + Box(Modifier.size(IconSize)) { ItemIcon(ItemStack(block.asItem()), IconSize) } + Text(BlockSerializer.stringify(block), Modifier.weight(1f, fill = false), maxLines = 1) + Ellipsis() } } if (!picking) return diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 727703c19..2790ce160 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -20,12 +20,9 @@ package com.lambda.gui.settings import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.relocation.BringIntoViewRequester import androidx.compose.foundation.relocation.bringIntoViewRequester @@ -35,7 +32,6 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.draw.alpha @@ -47,9 +43,9 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import com.lambda.config.entries.Setting import com.lambda.gui.clickgui.Reveal +import com.lambda.gui.component.LabeledRow import com.lambda.gui.component.LocalClickOnRelease import com.lambda.gui.component.LocalKeyboardReachable -import com.lambda.gui.component.RowHeight import com.lambda.gui.component.Tooltip import com.lambda.gui.component.hoverHighlight import com.lambda.gui.core.awaitFrames @@ -57,7 +53,6 @@ import com.lambda.gui.core.observe import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look import com.lambda.gui.theme.Radius -import com.lambda.gui.theme.Text /** * The row of one setting in a list, whatever its type: the description as its tooltip, the @@ -137,16 +132,8 @@ private fun Modifier.enabled(enabled: Boolean): Modifier = /** 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() - } -} +internal fun Labeled(name: String, modifier: Modifier = Modifier, editor: @Composable RowScope.() -> Unit) = + LabeledRow(name, modifier.padding(start = 3.dp), editor) /** Width of the field a line of text is typed into, beside its name */ internal val TextFieldWidth = 90.dp 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 c60747d27..6cf3b1b84 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -20,6 +20,7 @@ package com.lambda.module.modules.client import com.lambda.config.Config import com.lambda.config.ConfigBlock import com.lambda.config.Group +import com.lambda.config.settings.appliedOnRelease import com.lambda.gui.theme.GuiFont import com.lambda.gui.theme.Palette import com.lambda.gui.theme.toCompose @@ -50,7 +51,7 @@ object Style : Module( 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") + var scale by setting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() var fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") var elementHeight by setting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") val dimBackground by setting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") @@ -63,6 +64,9 @@ object Style : Module( val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") val emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") + var inlineSettings by setting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") + var multipleSettings by setting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") + var glow by setting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") 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 } @@ -105,7 +109,7 @@ object Style : Module( secondary = Color(255, 168, 158), surface = Color(60, 48, 52, 165), panel = Color(48, 38, 42, 200), - inset = Color(0, 0, 0, 90), + inset = Color(0, 0, 0, 190), onSurface = Color(246, 236, 239), onSurfaceVariant = Color(172, 152, 159), header = Color(190, 62, 98), @@ -140,7 +144,7 @@ object Style : Module( secondary = Color(196, 58, 52), surface = Color(246, 240, 243, 200), panel = Color(240, 233, 237, 225), - inset = Color(120, 0, 40, 34), + inset = Color(120, 0, 40, 68), onSurface = Color(64, 44, 54), onSurfaceVariant = Color(128, 108, 117), header = Color(214, 55, 88, 242), @@ -220,7 +224,7 @@ class PaletteSettings( private val secondary by c.setting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") private val surface by c.setting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") private val panel by c.setting("Panel", panel, "Fill of settings panels, menus and dialogs") - private val inset by c.setting("Inset", inset, "Shade over the module whose settings are open, which looks pressed in") + private val inset by c.setting("Inset", inset, "Shade behind settings that open under their module, and over the module whose settings are open beside it") private val onSurface by c.setting("On Surface", onSurface, "Text on windows") private val onSurfaceVariant by c.setting("On Surface Variant", onSurfaceVariant, "Subdued text on windows") private val header by c.setting("Header", header) From 6c99c0f48939eefac2831b1ad3e8dba32e4e5bd7 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:55:05 +0000 Subject: [PATCH 11/34] brighter colours --- .../com/lambda/module/modules/client/Style.kt | 83 ++++++++++--------- 1 file changed, 44 insertions(+), 39 deletions(-) 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 6cf3b1b84..b41a1c81e 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -105,66 +105,71 @@ object Style : Module( this, // A shade lighter than the header and a shade less full, so it is plain to see without being loud: a panel is // read by its band of tabs, and what is set in it is not to be taken for a module that is on - primary = Color(194, 86, 114), - secondary = Color(255, 168, 158), - surface = Color(60, 48, 52, 165), - panel = Color(48, 38, 42, 200), + primary = Color(214, 77, 113), + secondary = Color(255, 141, 128), + surface = Color(69, 48, 55, 165), + panel = Color(55, 38, 45, 200), inset = Color(0, 0, 0, 190), onSurface = Color(246, 236, 239), - onSurfaceVariant = Color(172, 152, 159), - header = Color(190, 62, 98), + onSurfaceVariant = Color(184, 156, 166), + header = Color(222, 53, 101), onHeader = Color(255, 246, 248), // A shade of the header, as strong and a good step darker: greyed and left as light it turns to a dusty pink - moduleEnabled = Color(138, 46, 72), + moduleEnabled = Color(161, 42, 75), onModuleEnabled = Color(255, 240, 244), // Every control is the one rose: a chip, a button and a key cap are filled as a slider // and a ticked box are, so that whatever can be set looks like one kind of thing - control = Color(194, 86, 114), - controlMenu = Color(48, 38, 42), - controlSelected = Color(81, 65, 71), + control = Color(214, 77, 113), + controlMenu = Color(55, 38, 45), + controlSelected = Color(92, 64, 75), onControl = Color(246, 236, 239), // Wells cut into the panel, darker than any glass they sit on so they never blend into it - track = Color(34, 27, 30, 230), - input = Color(29, 23, 25, 230), - border = Color(114, 93, 100, 235), + track = Color(38, 28, 32, 230), + input = Color(32, 23, 26, 230), + border = Color(128, 92, 104, 235), textShadow = Color(0, 0, 0, 150), // From the rose of the headers to the salmon, the two ends of the theme's range - glowA = Color(190, 62, 98), - glowB = Color(255, 168, 158), + glowA = Color(222, 53, 101), + glowB = Color(255, 141, 128), ) ) - // 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. Its tiers run the other way, - // darker for what is deeper, and its rose is the crimson of the logo, which holds on white. + // The dark theme turned over: the same rose, salmon and rose-tinted backing at the same hues, + // with the tiers running the other way, darker for what is deeper. Light glass has to be + // nearly solid, as dark text over whatever the game shows through it cannot be read, and it + // takes no text shadow, which only smears dark text. @Group(LIGHT_THEME_GROUP) private val lightTheme by configBlock( PaletteSettings( this, - primary = Color(214, 55, 88), - secondary = Color(196, 58, 52), - surface = Color(246, 240, 243, 200), - panel = Color(240, 233, 237, 225), + // The rose of the headers: it fills a slider thinned, under the dark text over it + primary = Color(222, 53, 101), + // The salmon, deepened until it reads as text on a light panel + secondary = Color(209, 74, 59), + surface = Color(250, 236, 241, 228), + panel = Color(244, 226, 232, 240), inset = Color(120, 0, 40, 68), - onSurface = Color(64, 44, 54), - onSurfaceVariant = Color(128, 108, 117), - header = Color(214, 55, 88, 242), + onSurface = Color(61, 40, 47), + onSurfaceVariant = Color(110, 86, 95), + // The same as on dark glass, so a window is known by the one colour in either theme + header = Color(222, 53, 101), onHeader = Color(255, 250, 251), - // Filled a step under the header with its text in white, as in the dark theme: a tint of - // pink under crimson text was too faint to pick the enabled out of a list at a glance - moduleEnabled = Color(226, 104, 130), + // A step under the header, which on light glass is a step lighter, with its text in white: + // a tint of pink under dark text was too faint to pick the enabled out of a list at a glance + moduleEnabled = Color(232, 84, 126), onModuleEnabled = Color(255, 250, 251), - // The rose of the fill of a slider, which is the accent thinned for the dark text over it - control = Color(214, 114, 136), - controlMenu = Color(240, 233, 237), - controlSelected = Color(228, 210, 218), - onControl = Color(64, 44, 54), - track = Color(214, 203, 208, 220), - input = Color(255, 255, 255, 200), - border = Color(190, 172, 180, 238), + // The same rose paler again, so what is set in a panel is not taken for a module that is on + control = Color(240, 139, 166), + controlMenu = Color(244, 226, 232), + controlSelected = Color(224, 197, 206), + onControl = Color(61, 40, 47), + // Wells cut into the panel: a track is darker than it, a text field is paper + track = Color(209, 192, 199, 220), + input = Color(255, 250, 252, 210), + border = Color(184, 154, 164, 238), textShadow = Color(0, 0, 0, 0), - // From the rose of the headers to a paler one: around light glass a glow has to stay light itself - glowA = Color(214, 55, 88), - glowB = Color(255, 150, 172), + // The two ends of the theme's range, as in the dark theme: both are light enough to glow around light glass + glowA = Color(222, 53, 101), + glowB = Color(255, 141, 128), ) ) From aba77cbf1230fb87939289cb4b78841a08c0737a Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:51:35 +0000 Subject: [PATCH 12/34] cleanup --- build.gradle.kts | 6 +- src/gametest/kotlin/com/lambda/GuiTest.kt | 899 ------------------ src/gametest/resources/fabric.mod.json | 4 - .../com/lambda/mixin/input/KeyboardMixin.java | 1 - .../mixin/render/ComposeDelayMixin.java | 23 +- .../mixin/render/GameRendererMixin.java | 2 - .../lambda/mixin/render/GuiRendererMixin.java | 13 +- .../render/InactivityFpsLimiterMixin.java | 7 - .../kotlin/com/lambda/config/EntryLayer.kt | 17 +- .../config/automation/UserAutomationConfig.kt | 7 + .../com/lambda/config/entries/Setting.kt | 9 +- .../com/lambda/config/settings/CharSetting.kt | 3 +- .../lambda/config/settings/FunctionSetting.kt | 5 +- .../lambda/config/settings/NumericSetting.kt | 141 ++- .../lambda/config/settings/StringSetting.kt | 13 +- .../collections/BlockCollectionSetting.kt | 1 - .../settings/collections/CollectionSetting.kt | 6 +- .../settings/comparable/BooleanSetting.kt | 12 +- .../config/settings/comparable/EnumSetting.kt | 7 +- .../settings/complex/BlockPosSetting.kt | 16 +- .../config/settings/complex/BlockSetting.kt | 3 +- .../config/settings/complex/ColorSetting.kt | 3 +- .../config/settings/complex/KeybindSetting.kt | 17 +- .../config/settings/complex/Vec3dSetting.kt | 12 +- .../config/settings/numeric/DoubleSetting.kt | 3 + .../config/settings/numeric/FloatSetting.kt | 3 + .../config/settings/numeric/IntegerSetting.kt | 4 + .../config/settings/numeric/LongSetting.kt | 4 + .../graphics/mc/LambdaRenderPipelines.kt | 6 - src/main/kotlin/com/lambda/gui/GuiConfig.kt | 27 +- src/main/kotlin/com/lambda/gui/GuiScreen.kt | 26 - src/main/kotlin/com/lambda/gui/LambdaGui.kt | 119 +-- .../com/lambda/gui/{clickgui => }/Reveal.kt | 52 +- src/main/kotlin/com/lambda/gui/Snap.kt | 136 +-- .../com/lambda/gui/clickgui/CategoryWindow.kt | 124 +-- .../com/lambda/gui/clickgui/ClickGui.kt | 116 +-- .../com/lambda/gui/clickgui/OpenSettings.kt | 76 ++ .../com/lambda/gui/clickgui/SettingsPanel.kt | 351 +------ .../com/lambda/gui/component/Controls.kt | 326 +------ .../kotlin/com/lambda/gui/component/Images.kt | 29 +- .../com/lambda/gui/component/Keyboard.kt | 36 +- .../com/lambda/gui/component/Pointer.kt | 123 --- .../kotlin/com/lambda/gui/component/Popups.kt | 222 +---- .../kotlin/com/lambda/gui/component/Scroll.kt | 132 +++ .../com/lambda/gui/component/SlidingText.kt | 35 +- .../com/lambda/gui/component/Surface.kt | 113 +-- .../kotlin/com/lambda/gui/component/Text.kt | 77 ++ .../com/lambda/gui/component/TextInput.kt | 171 ++++ src/main/kotlin/com/lambda/gui/core/Frames.kt | 5 - .../kotlin/com/lambda/gui/core/GlState.kt | 13 - .../kotlin/com/lambda/gui/core/Observe.kt | 23 - .../com/lambda/gui/core/RenderThread.kt | 41 + .../kotlin/com/lambda/gui/core/Retained.kt | 13 - .../kotlin/com/lambda/gui/core/SceneHost.kt | 88 +- .../kotlin/com/lambda/gui/core/SceneInput.kt | 40 +- .../com/lambda/gui/core/ScenePlatform.kt | 11 - src/main/kotlin/com/lambda/gui/hud/Hud.kt | 69 +- .../kotlin/com/lambda/gui/hud/HudEditor.kt | 144 +-- .../kotlin/com/lambda/gui/menu/Dialogs.kt | 39 +- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 59 +- src/main/kotlin/com/lambda/gui/menu/Search.kt | 18 +- .../com/lambda/gui/render/BlurPyramid.kt | 16 - .../com/lambda/gui/render/GuiCompositor.kt | 18 - .../kotlin/com/lambda/gui/render/ItemAtlas.kt | 51 +- .../lambda/gui/settings/CollectionEditor.kt | 39 +- .../com/lambda/gui/settings/ColorPicker.kt | 37 +- .../com/lambda/gui/settings/ConfigSettings.kt | 72 ++ .../com/lambda/gui/settings/ModuleSettings.kt | 194 ++++ .../com/lambda/gui/settings/SettingRow.kt | 50 +- .../com/lambda/gui/settings/SettingsList.kt | 60 +- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 305 ++---- .../kotlin/com/lambda/module/HudModule.kt | 10 - src/main/kotlin/com/lambda/module/Module.kt | 4 - .../module/modules/client/AutoUpdater.kt | 4 - .../com/lambda/module/modules/client/Style.kt | 111 +-- .../combat/autodisconnect/AutoDisconnect.kt | 11 +- .../autodisconnect/DisconnectDetailsWidget.kt | 16 +- .../com/lambda/module/modules/hud/Armor.kt | 4 +- .../lambda/module/modules/hud/Coordinates.kt | 2 +- .../lambda/module/modules/hud/ModuleList.kt | 2 - .../com/lambda/module/modules/hud/Tps.kt | 3 +- .../lambda/module/modules/hud/Watermark.kt | 1 - .../module/modules/movement/BackTrack.kt | 5 +- .../lambda/module/modules/movement/Blink.kt | 6 +- .../lambda/module/modules/player/Replay.kt | 77 +- .../com/lambda/util/CommunicationUtils.kt | 9 +- src/main/kotlin/com/lambda/util/InputUtils.kt | 1 - src/main/kotlin/com/lambda/util/math/Color.kt | 5 + .../lambda/shaders/core/gui_blur_down.fsh | 3 - .../lambda/shaders/core/gui_blur_up.fsh | 3 - .../lambda/shaders/core/gui_composite.fsh | 12 +- 91 files changed, 1624 insertions(+), 3608 deletions(-) delete mode 100644 src/gametest/kotlin/com/lambda/GuiTest.kt rename src/main/kotlin/com/lambda/gui/{clickgui => }/Reveal.kt (61%) create mode 100644 src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt create mode 100644 src/main/kotlin/com/lambda/gui/component/Scroll.kt create mode 100644 src/main/kotlin/com/lambda/gui/component/Text.kt create mode 100644 src/main/kotlin/com/lambda/gui/component/TextInput.kt create mode 100644 src/main/kotlin/com/lambda/gui/core/RenderThread.kt create mode 100644 src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt create mode 100644 src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt diff --git a/build.gradle.kts b/build.gradle.kts index 970799b46..648e8c584 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -39,8 +39,6 @@ val maLiLibVersion: String by project val composeVersion: String by project val skikoVersion: String by project -// Skiko (the Skia binding Compose draws with) ships its native library in one artifact per platform. -// Every platform is bundled so a single jar runs everywhere; skiko loads the one matching the host. val skikoPlatforms = listOf("windows-x64", "windows-arm64", "linux-x64", "linux-arm64", "macos-x64", "macos-arm64") val libs = file("libs") @@ -78,7 +76,6 @@ configurations.all { if (requested.group == "org.lwjgl") { useVersion(lwjglVersion) } - // The natives must be the exact build the skiko classes Compose pulls in were compiled against if (requested.group == "org.jetbrains.skiko") { useVersion(skikoVersion) } @@ -91,7 +88,7 @@ repositories { maven("https://maven.2b2t.vc/releases") // Baritone maven("https://jitpack.io") // KDiscordIPC maven("https://api.modrinth.com/maven") - google() // AndroidX libraries Compose depends on + google() mavenCentral() // Allow the use of local libraries @@ -181,7 +178,6 @@ dependencies { includeLib("com.pngencoder:pngencoder:$pngEncoderVersion") - // Compose. Kotlin and kotlinx are left out because fabric-language-kotlin already provides them listOf("runtime:runtime", "ui:ui", "foundation:foundation").forEach { module -> shadowLib("org.jetbrains.compose.$module-desktop:$composeVersion") { exclude(group = "org.jetbrains.kotlin") diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt deleted file mode 100644 index 443bfd92c..000000000 --- a/src/gametest/kotlin/com/lambda/GuiTest.kt +++ /dev/null @@ -1,899 +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 - -import com.lambda.config.entries.Setting -import com.lambda.context.Automated -import com.lambda.gui.GuiConfig -import com.lambda.gui.GuiScreen -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 -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 net.minecraft.client.input.KeyInput -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 - * change to the GUI can be looked at without playing through it by hand. It fails if the - * interface throws along the way, since that closes the screen the next step expects. - */ -@Suppress("UnstableApiUsage") -object GuiTest : FabricClientGameTest { - private const val WIDTH = 1920 - private const val HEIGHT = 1080 - - /** The interface is laid out for a screen 540 dp tall, see [LambdaGui] */ - private const val DENSITY = HEIGHT / 540.0 - - override fun runTest(context: ClientGameTestContext) { - context.input.resizeWindow(WIDTH, HEIGHT) - context.waitTicks(5) - - // Over the title screen, where there is no world to draw a HUD for. The first time the - // click GUI opens it offers the loader, which has to be answered before anything else. - context.openClickGui() - context.takeScreenshot("gui-0-loader-prompt") - context.runOnClient { AutoUpdater.answerPrompt(accepted = false) } - 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 = 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 = 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(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 = 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(240.0 * DENSITY, 193.0 * DENSITY) - context.waitTicks(30) - context.takeScreenshot("gui-1a-long-name-hovered") - 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(620.0 * DENSITY, 101.0 * DENSITY) - context.dragBy(3.5, 7.5) - val free = context.windowPlacement("Network") - 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) - context.waitTicks(2) - context.dragBy(2.0, 2.0) - context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) - val snapped = context.windowPlacement("Network") - // Back in its place in the row, it is kept as being in the row rather than at the spot - check(snapped.inRow) { "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() } - context.waitTicks(2) - 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 = 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(150.0 * DENSITY, 128.0 * DENSITY) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(1) - context.takeScreenshot("gui-2a-switching-settings") - context.waitTicks(10) - - // 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 = 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 = 298.5, dpY = 198.0) - context.takeScreenshot("gui-2c2-module-page") - context.input.setCursorPos(340.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(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 = 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(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(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(320.0 * DENSITY, 273.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.takeScreenshot("gui-2g0-dropdown-unfolding") - context.waitTicks(10) - context.takeScreenshot("gui-2g-dropdown") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(1) - context.takeScreenshot("gui-2g1-dropdown-folding") - context.waitTicks(2) - context.takeScreenshot("gui-2g2-dropdown-folded-in") - context.waitTicks(3) - - // The pages a module sorts its settings into are picked from the band over them - context.click(dpX = 296.0, dpY = 216.0) - context.takeScreenshot("gui-2d0-tab-list") - context.input.setCursorPos(296.0 * DENSITY, 245.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.takeScreenshot("gui-2d-tab-changing") - context.waitTicks(10) - context.takeScreenshot("gui-2e-tab-changed") - - // A collection is edited in a window of its own, each entry with its icon - context.input.setCursorPos(360.0 * DENSITY, 260.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.takeScreenshot("gui-2h0-collection-unfolding") - context.waitTicks(10) - context.takeScreenshot("gui-2h-collection") - context.input.typeChars("stone") - context.waitTicks(5) - context.takeScreenshot("gui-2h2-collection-searched") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(1) - context.takeScreenshot("gui-2h1-collection-folding") - context.waitTicks(2) - context.takeScreenshot("gui-2h3-collection-folded-in") - context.waitTicks(3) - - // 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 = 340.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 = 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(290.0 * DENSITY, 400.0 * DENSITY) - context.waitTicks(2) - context.input.scroll(-2.0) - context.waitTicks(1) - context.takeScreenshot("gui-2i1-wheel-gliding") - context.waitTicks(15) - context.takeScreenshot("gui-2i2-wheel-settled") - context.input.scroll(10.0) - context.waitTicks(15) - context.input.setCursorPos(317.0 * DENSITY, 189.0 * DENSITY) - context.waitTicks(2) - context.dragBy(0.0, -60.0) - context.takeScreenshot("gui-2j-extended") - - // However far it is dragged, the panel stops under the menu bar, its grip still in reach - context.dragBy(0.0, -300.0) - context.takeScreenshot("gui-2k-extended-to-the-bar") - - // Folding the category away takes the settings hanging off it along - context.click(dpX = 150.0, dpY = 101.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-2f-category-folded") - 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 = 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 - context.click(dpX = 20.0, dpY = 7.0) - context.takeScreenshot("gui-3-menu") - - // With a menu and one nested in it open, a single click on another entry of the bar - // closes both and opens that entry's menu - context.click(dpX = 30.0, dpY = 39.0) - context.click(dpX = 190.0, dpY = 7.0) - context.takeScreenshot("gui-3b-menu-to-menu") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - - // A menu closed with one nested in it open takes that one with it as it folds - context.click(dpX = 20.0, dpY = 7.0) - context.click(dpX = 30.0, dpY = 39.0) - context.waitTicks(10) - context.takeScreenshot("gui-3c-submenu") - context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.takeScreenshot("gui-3d-submenu-swallowed") - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.takeScreenshot("gui-3e-submenu-swallowed") - context.waitTicks(10) - - // Closed with a menu open, the GUI comes back as it was left, minus the menu - context.click(dpX = 20.0, dpY = 7.0) - context.closeGui() - context.openClickGui() - context.takeScreenshot("gui-3a-reopened") - - // The search in the menu bar lists what matches as it is typed... - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("scaff") - context.waitTicks(10) - context.takeScreenshot("gui-4-search") - - // ...and Enter shows where the first result is: the module is lit in its window - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(8) - context.takeScreenshot("gui-4a-search-module") - context.waitTicks(40) - - // The arrow keys and Tab move the mark through the results, and Enter takes the marked one - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("auto") - context.waitTicks(1) - context.takeScreenshot("gui-4a1-search-unfolding") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.waitTicks(5) - context.takeScreenshot("gui-4a2-search-third-marked") - context.input.pressKey(GLFW.GLFW_KEY_UP) - context.waitTicks(5) - context.takeScreenshot("gui-4a3-search-second-marked") - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(8) - context.takeScreenshot("gui-4a4-search-marked-chosen") - context.waitTicks(40) - - // A setting has the settings of its module opened on its tab, and is lit there - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("targeting range") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(15) - context.takeScreenshot("gui-4b-search-setting") - - // A list of blocks shows each with its icon, drawn by Minecraft - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("surround") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(15) - context.click(dpX = 150.0, dpY = 219.5, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-4c-block-settings") - 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(400.0 * DENSITY, 346.0 * DENSITY) - context.waitTicks(2) - context.input.scroll(-5.0) - context.waitTicks(15) - context.takeScreenshot("gui-4e-block-list-scrolled") - - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - context.takeScreenshot("gui-4f-block-list-shut") - - // A setting that is one block shows it on a chip, with its icon - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("pavement material") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(15) - context.takeScreenshot("gui-4g-block-setting") - context.closeGui() - - val singleplayer = context.worldBuilder() - .adjustSettings { it.gameMode = WorldCreator.Mode.CREATIVE } - .create() - singleplayer.clientWorld.waitForChunksDownload() - // A stack, a worn piece and an enchanted one: the count, the damage bar and the glint are Minecraft's - singleplayer.server.runCommand("/item replace entity @p armor.head with minecraft:stone 32") - singleplayer.server.runCommand("/item replace entity @p armor.chest with minecraft:netherite_chestplate[minecraft:damage=500]") - singleplayer.server.runCommand("/item replace entity @p armor.legs with minecraft:diamond_leggings[minecraft:enchantments={protection:4}]") - singleplayer.server.runCommand("/item replace entity @p armor.feet with minecraft:golden_boots[minecraft:damage=40]") - - context.runOnClient { - Armor.enable() - Coordinates.enable() - Fps.enable() - } - context.waitTicks(20) - context.takeScreenshot("gui-5-hud-in-game") - - // In game the GUI is opened the way a player does, with its keybind - context.input.pressKey(GLFW.GLFW_KEY_Y) - context.waitTicks(2) - context.takeScreenshot("gui-6-0-click-gui-opening") - context.waitTicks(18) - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "The keybind did not open the click GUI" } - context.takeScreenshot("gui-6-click-gui-in-game") - - // 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(150.0 * DENSITY, 115.0 * DENSITY) - context.waitTicks(40) - context.takeScreenshot("gui-6a-tooltip") - context.input.pressKey(GLFW.GLFW_KEY_Y) - context.waitTicks(10) - context.takeScreenshot("gui-6b-closed-with-tooltip-up") - context.input.pressKey(GLFW.GLFW_KEY_Y) - context.waitTicks(10) - context.takeScreenshot("gui-6c-reopened") - - // While a text field has the keyboard, the GUI's keybind is a letter like any other - context.click(dpX = 480.0, dpY = 7.0) - context.input.pressKey(GLFW.GLFW_KEY_Y) - context.waitTicks(5) - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "Typing the keybind into a text field closed the GUI" } - check(context.computeOnClient { LambdaGui.isCapturingKeys }) { "A focused text field did not hold on to the keys" } - context.input.pressKey(GLFW.GLFW_KEY_BACKSPACE) - context.waitTicks(2) - - // The HUD editor is reached from the click GUI's button, and dragging an element moves it - context.click(dpX = 924.0, dpY = 528.0) - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.HudEditor }) { "The HUD Editor button did not open the editor" } - check(context.computeOnClient { !LambdaGui.isCapturingKeys }) { "Keys stayed captured after the focused text field went away" } - context.input.setCursorPos(20.0 * DENSITY, 44.0 * DENSITY) - context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(10) { - context.input.moveCursor(30.0 * DENSITY, 15.0 * DENSITY) - context.waitTick() - } - context.takeScreenshot("gui-7-hud-editor-dragging") - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(2) - - // Dragged with the snap key held, the element lines up with the screen and its neighbours - context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) - context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(10) { - context.input.moveCursor(-29.0 * DENSITY, 2.0 * DENSITY) - context.waitTick() - } - context.takeScreenshot("gui-7a-hud-editor-snapping") - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) - context.waitTicks(2) - - // Right click on the empty screen offers the hidden elements, on an element its own menu. - // The second right click comes while the first menu is still open: it closes that one - // and opens its own, in one go. - context.click(dpX = 700.0, dpY = 400.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-8-hud-editor-menu") - - // A right click elsewhere with the menu open unfolds a new one there - context.input.setCursorPos(500.0 * DENSITY, 300.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(1) - context.takeScreenshot("gui-8a-hud-editor-menu-reopening") - context.waitTicks(10) - context.takeScreenshot("gui-8b-hud-editor-menu-reopened") - - // How the editor is used is told by an entry of that menu, to whoever rests the pointer on it - context.input.setCursorPos(513.0 * DENSITY, 427.5 * DENSITY) - context.waitTicks(20) - context.takeScreenshot("gui-8c-hud-editor-help") - context.click(dpX = 150.0, dpY = 108.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-9-hud-element-menu") - // Pressed and let go a few frames apart, the way a hand does it - context.input.setCursorPos(175.0 * DENSITY, 129.0 * DENSITY) - context.waitTicks(2) - context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(3) - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(10) - context.takeScreenshot("gui-9a-hud-element-settings") - - // What opens out of that panel in turn: a colour picker and a list of options - context.click(dpX = 342.0, dpY = 135.0) - context.takeScreenshot("gui-9b-hud-element-colour") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - context.click(dpX = 312.0, dpY = 208.5) - context.takeScreenshot("gui-9c-hud-element-options") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - - // The panel is dragged by any part of it that is not a control, here the room beside its buttons - context.input.setCursorPos(170.0 * DENSITY, 268.0 * DENSITY) - context.waitTicks(2) - context.dragBy(150.0, 60.0) - context.takeScreenshot("gui-9d-hud-settings-dragged") - - // A click off the panel closes it, shrinking into its middle, and the editor stays - context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.takeScreenshot("gui-9e-hud-settings-closing") - context.waitTicks(10) - context.takeScreenshot("gui-9f-hud-settings-closed") - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.HudEditor }) { "Closing the settings panel left the HUD editor" } - - // Escape leaves the editor for the click GUI, and the click GUI for the game - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "Escape did not return from the HUD editor to the click GUI" } - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - check(context.computeOnClient { LambdaGui.screen == null }) { "Escape did not close the click GUI" } - - // 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 = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(10) - 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) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.takeScreenshot("gui-10b-menu-folding-in-panel") - context.waitTicks(1) - context.takeScreenshot("gui-10c-menu-folding-in-panel") - context.waitTicks(15) - context.takeScreenshot("gui-10d-panel-closed") - - // Settings kept open come back once the categories have unfolded, not riding their row down - context.runOnClient { GuiConfig.keepSettingsOpen = true } - 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) } - context.waitTicks(2) - context.takeScreenshot("gui-11a-kept-settings-categories-unfolding") - context.waitTicks(4) - context.takeScreenshot("gui-11b-kept-settings-unfolding") - context.waitTicks(15) - context.takeScreenshot("gui-11c-kept-settings-open") - context.runOnClient { GuiConfig.keepSettingsOpen = false } - context.closeGui() - - // However many pages a config has, the band that picks one is a single row - context.openClickGui() - context.click(dpX = 520.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(10) - context.takeScreenshot("gui-11d-settings-of-many-tabs") - context.click(dpX = 728.0, dpY = 185.0) - context.waitTicks(10) - context.click(dpX = 650.0, dpY = 216.0) - context.takeScreenshot("gui-11e-many-tabs-listed") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - context.closeGui() - - // Where the style has them inline, a module's settings drop down under it instead: as - // wide as its window, pushing the modules under it down, whatever they hold - context.runOnClient { - Style.inlineSettings = true - GuiConfig.resetWindows() - } - context.openClickGui() - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) - context.waitTicks(3) - context.takeScreenshot("gui-11g-inline-settings-dropping") - context.waitTicks(15) - context.takeScreenshot("gui-11h-inline-settings") - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("targeting range") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(40) - context.takeScreenshot("gui-11i-inline-settings-with-tabs") - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("window gap") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(40) - context.takeScreenshot("gui-11j-inline-settings-with-groups") - - // Several can be open at once where the style allows it: the one the search turns to - // next opens beside the last instead of in its place... - context.runOnClient { Style.multipleSettings = true } - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("targeting range") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(40) - context.takeScreenshot("gui-11k-inline-settings-of-two") - // ...and with settings no longer inline, the ones that are open are out as panels - context.runOnClient { Style.inlineSettings = false } - context.waitTicks(20) - context.takeScreenshot("gui-11l-panels-of-two") - // Held to one at a time again, the last one opened is the one that stays - context.runOnClient { Style.multipleSettings = false } - context.waitTicks(20) - context.takeScreenshot("gui-11m-panel-of-one") - context.closeGui() - - // The glow is in the colours of the theme in use: the dark one's here, the light one's below - context.runOnClient { Style.glow = true } - context.openClickGui() - context.takeScreenshot("gui-11f-glow-dark") - context.closeGui() - - // The light theme, picked the way a player picks it, in the settings of Style - context.openClickGui() - context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(10) - context.click(dpX = 730.0, dpY = 201.0) - context.waitTicks(10) - context.click(dpX = 730.0, dpY = 243.0) - context.waitTicks(10) - context.takeScreenshot("gui-12a-light-theme") - 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() - context.runOnClient { Style.glow = false } - - // Another font, picked the same way: the interface keeps its proportions - context.openClickGui() - context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(10) - context.click(dpX = 730.0, dpY = 215.0) - context.waitTicks(10) - 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) - // The scale of the interface is the one bar that waits for the button to be let go: held, - // it shows what the scale is about to be and nothing moves, least of all the bar itself - context.input.setCursorPos(700.0 * DENSITY, 229.0 * DENSITY) - context.waitTicks(2) - context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(5) { - context.input.moveCursor(3.0 * DENSITY, 0.0) - context.waitTick() - } - context.waitTicks(5) - context.takeScreenshot("gui-14a-scale-held") - check(context.computeOnClient { Style.scale } == 1f) { "The scale changed while its bar was still held" } - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(10) - context.takeScreenshot("gui-14b-scale-applied") - check(context.computeOnClient { Style.scale } > 1f) { "The scale was not applied when its bar was let go" } - // At the largest scale there is, nothing is off the screen: the windows close up to fit, - // the search field clears the menus, and the settings that would undo it are in reach - context.runOnClient { Style.scale = 1.5f } - context.waitTicks(15) - context.takeScreenshot("gui-14c-scale-largest") - context.runOnClient { Style.scale = 1f } - 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() - - // The whole of it from the keyboard. Tab puts the focus on the first thing there is, the - // header of the first window, and the arrows take it across to the third and down its list - context.openClickGui() - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.waitTicks(5) - context.takeScreenshot("gui-15a-keyboard-first-focus") - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.waitTicks(5) - context.takeScreenshot("gui-15b-keyboard-on-module") - - // Enter is a click on it, and Shift with Enter a right click: its settings open beside it - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - context.takeScreenshot("gui-15c-keyboard-toggled") - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) - context.waitTicks(15) - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.waitTicks(5) - context.takeScreenshot("gui-15d-keyboard-into-settings") - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.waitTicks(5) - context.takeScreenshot("gui-15e-keyboard-down-settings") - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.waitTicks(5) - context.takeScreenshot("gui-15f-keyboard-right-twice") - // Stepped back down, the value is the default again and not a rounding error beside it - context.input.pressKey(GLFW.GLFW_KEY_LEFT) - context.input.pressKey(GLFW.GLFW_KEY_LEFT) - context.waitTicks(5) - - // A menu of the bar is its own layer of focus: Enter opens it, the arrows move inside it - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("zoo") - context.waitTicks(10) - context.takeScreenshot("gui-15g-keyboard-search") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - repeat(5) { context.pressKey(GLFW.GLFW_KEY_TAB, GLFW.GLFW_MOD_SHIFT) } - context.waitTicks(5) - context.takeScreenshot("gui-15h-keyboard-on-menu-bar") - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.waitTicks(5) - context.takeScreenshot("gui-15i-keyboard-in-menu") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(10) - context.takeScreenshot("gui-15j-keyboard-menu-closed") - context.closeGui() - - // The shape, the spacing and the motion of it all are the style's, each kind of thing by - // itself: round windows over a square panel here, thicker in outline, wider and roomier, - // and a panel that is all there the moment it is opened while the rest still animates - context.runOnClient { - Style.windowRounding = 9f - Style.panelRounding = 0f - Style.outlineWidth = 1.5f - Style.windowWidth = 110f - Style.windowGap = 8f - Style.modulePadding = 10f - Style.panelPadding = 10f - Style.settingSpacing = 4f - Style.panelAnimations = false - } - context.openClickGui() - context.takeScreenshot("gui-16a-restyled") - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) - context.waitTicks(1) - context.takeScreenshot("gui-16b-no-panel-animation") - context.closeGui() - context.runOnClient { - Style.windowRounding = 3f - Style.panelRounding = 5f - Style.outlineWidth = 0.5f - Style.windowWidth = 90f - Style.windowGap = 2f - Style.modulePadding = 4f - Style.panelPadding = 4f - Style.settingSpacing = 1f - Style.panelAnimations = true - } - - // Each spacing setting changed while the interface is open, with a module's settings out - // and a group in them unfolded: every one of them has to show at once - // ...windows put back in their row by hand or folded away among them: left where the - // row has them, they are in the row, and go where it goes - context.runOnClient { - GuiConfig.windows = mapOf( - "Movement" to GuiConfig.WindowPlacement(204.6f, 94.3f, false), - "Render" to GuiConfig.WindowPlacement(297f, 94f, true), - "World" to GuiConfig.WindowPlacement(500f, 200f, false), - ) - } - context.openClickGui() - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("window gap") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(60) - context.takeScreenshot("gui-17a-spacing-default") - context.runOnClient { Style.windowGap = 12f } - context.waitTicks(10) - context.takeScreenshot("gui-17b-window-gap") - context.runOnClient { Style.windowGap = 2f; Style.windowTop = 40f } - context.waitTicks(10) - context.takeScreenshot("gui-17c-window-top") - context.runOnClient { Style.windowTop = 94f; Style.modulePadding = 12f } - context.waitTicks(10) - context.takeScreenshot("gui-17d-module-padding") - context.runOnClient { Style.modulePadding = 4f; Style.panelPadding = 12f } - context.waitTicks(10) - context.takeScreenshot("gui-17e-panel-padding") - context.runOnClient { Style.panelPadding = 4f; Style.settingSpacing = 6f } - context.waitTicks(10) - context.takeScreenshot("gui-17f-setting-spacing") - context.runOnClient { Style.settingSpacing = 1f; Style.groupIndent = 12f } - context.waitTicks(10) - context.takeScreenshot("gui-17g-group-indent") - context.runOnClient { Style.groupIndent = 5f; Style.windowWidth = 120f } - context.waitTicks(10) - context.takeScreenshot("gui-17h-window-width") - context.runOnClient { Style.windowWidth = 90f } - context.waitTicks(10) - context.takeScreenshot("gui-17i-spacing-restored") - context.closeGui() - - // A setting that shows or hides others does so the moment it changes, with the panel - // open: the rows under Glow come and go with it, with animations and without them - context.runOnClient { GuiConfig.resetWindows() } - context.openClickGui() - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("emboss") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(60) - context.takeScreenshot("gui-18a-dependent-hidden") - context.runOnClient { Style.glow = true } - context.waitTicks(15) - context.takeScreenshot("gui-18b-dependent-shown") - context.runOnClient { Style.glow = false } - context.waitTicks(15) - context.takeScreenshot("gui-18c-dependent-hidden-again") - context.runOnClient { Style.animations = false } - context.waitTicks(5) - context.runOnClient { Style.glow = true } - context.waitTicks(15) - context.takeScreenshot("gui-18d-dependent-shown-unanimated") - context.runOnClient { Style.glow = false } - context.waitTicks(15) - context.takeScreenshot("gui-18e-dependent-hidden-unanimated") - context.runOnClient { Style.animations = true } - context.closeGui() - - // A setting that another one disables is dimmed the moment that one is switched off, - // wherever it is switched: here PacketMine's Rebreak Mode, by Rebreak in its automation - context.openClickGui() - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("rebreak mode") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(60) - context.takeScreenshot("gui-19a-dependent-enabled") - context.setRebreak(false) - context.waitTicks(15) - context.takeScreenshot("gui-19b-dependent-disabled") - context.setRebreak(true) - context.waitTicks(15) - context.takeScreenshot("gui-19c-dependent-enabled-again") - context.closeGui() - - // Settings of one name in many configs are told apart by where each is: its config, and - // the tab and group it is under - context.openClickGui() - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("airplace") - context.waitTicks(15) - context.takeScreenshot("gui-20-search-same-name") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - context.closeGui() - - singleplayer.close() - } - - private fun ClientGameTestContext.openClickGui() { - runOnClient { LambdaGui.open(LambdaGui.Screen.ClickGui) } - waitTicks(20) - check(computeOnClient { LambdaGui.screen != null }) { "The click GUI did not open" } - } - - /** A key pressed with modifiers held, which the test's own input leaves out of the key it sends */ - private fun ClientGameTestContext.pressKey(key: Int, modifiers: Int) { - runOnClient { - GuiScreen.keyPressed(KeyInput(key, 0, modifiers)) - GuiScreen.keyReleased(KeyInput(key, 0, modifiers)) - } - waitTicks(1) - } - - /** Sets Rebreak in the automation config PacketMine is linked to, a setting the module only reads */ - @Suppress("UNCHECKED_CAST") - private fun ClientGameTestContext.setRebreak(to: Boolean) = runOnClient { - val config = (ModuleRegistry.modules.first { it.name == "PacketMine" } as Automated).breakConfig - val delegate = config.javaClass.getDeclaredField("rebreak\$delegate").apply { isAccessible = true } - (delegate.get(config) as Setting).value = to - } - - private fun ClientGameTestContext.closeGui() { - check(computeOnClient { LambdaGui.screen != null }) { "The interface closed itself, see the log" } - runOnClient { it.setScreen(null) } - waitTicks(5) - } - - private fun ClientGameTestContext.click(dpX: Double, dpY: Double, button: Int = GLFW.GLFW_MOUSE_BUTTON_LEFT) { - input.setCursorPos(dpX * DENSITY, dpY * DENSITY) - waitTicks(2) - input.pressMouse(button) - waitTicks(10) - } - - /** Drags from where the pointer is, by a distance in dp, in steps a frame apart as a hand would */ - private fun ClientGameTestContext.dragBy(dpX: Double, dpY: Double) { - input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(5) { - input.moveCursor(dpX / 5 * DENSITY, dpY / 5 * DENSITY) - waitTick() - } - input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - waitTicks(2) - } - - private fun ClientGameTestContext.windowPlacement(category: String): GuiConfig.WindowPlacement = - computeOnClient { - checkNotNull(GuiConfig.windows[category]) { "The $category window was never moved" } - } - - private fun ClientGameTestContext.enabledModules(): Int = - computeOnClient { ModuleRegistry.modules.count { it.isEnabled } } -} diff --git a/src/gametest/resources/fabric.mod.json b/src/gametest/resources/fabric.mod.json index 3c966f713..c9ff71449 100644 --- a/src/gametest/resources/fabric.mod.json +++ b/src/gametest/resources/fabric.mod.json @@ -9,10 +9,6 @@ { "adapter": "kotlin", "value": "com.lambda.LambdaTest" - }, - { - "adapter": "kotlin", - "value": "com.lambda.GuiTest" } ] } diff --git a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java index b2cdcbc1a..49e94071a 100644 --- a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java +++ b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java @@ -38,7 +38,6 @@ private void onKey(long window, int action, KeyInput input, Operation orig original.call(window, action, input); int key = input.key(); 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 index 8fe497385..52469a732 100644 --- a/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java +++ b/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java @@ -18,29 +18,18 @@ package com.lambda.mixin.render; import androidx.compose.ui.Actuals_skikoKt; +import com.lambda.gui.core.RenderThread; import kotlin.Unit; import kotlin.jvm.functions.Function0; -import net.minecraft.client.MinecraftClient; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -/** - * 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; - }; + @Inject(method = "postDelayed", at = @At("HEAD"), cancellable = true, require = 1) + private static void delayOnRenderThread(long delayMillis, Function0 block, CallbackInfoReturnable cir) { + cir.setReturnValue(RenderThread.after(delayMillis, block)); } } diff --git a/src/main/java/com/lambda/mixin/render/GameRendererMixin.java b/src/main/java/com/lambda/mixin/render/GameRendererMixin.java index a2ea9f39a..cf4304a15 100644 --- a/src/main/java/com/lambda/mixin/render/GameRendererMixin.java +++ b/src/main/java/com/lambda/mixin/render/GameRendererMixin.java @@ -102,8 +102,6 @@ private void applyCursorOverride(DrawContext context, Window window, 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")) + @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferWidth()I"), require = 1) private int itemAtlasWidth(Window window, Operation original) { Framebuffer atlas = ItemAtlas.getTarget(); return atlas != null ? atlas.textureWidth : original.call(window); } - @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferHeight()I")) + @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferHeight()I"), require = 1) private int itemAtlasHeight(Window window, Operation original) { Framebuffer atlas = ItemAtlas.getTarget(); return atlas != null ? atlas.textureHeight : original.call(window); } - @WrapOperation(method = {"renderPreparedDraws", "getWindowScaleFactor"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getScaleFactor()I")) + @WrapOperation(method = {"renderPreparedDraws", "getWindowScaleFactor"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getScaleFactor()I"), require = 1) private int itemAtlasScale(Window window, Operation original) { return ItemAtlas.getTarget() != null ? ItemAtlas.getScale() : original.call(window); } diff --git a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java index 926b8cfaf..40ba23482 100644 --- a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java +++ b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java @@ -26,13 +26,6 @@ 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 diff --git a/src/main/kotlin/com/lambda/config/EntryLayer.kt b/src/main/kotlin/com/lambda/config/EntryLayer.kt index 1539307f7..a2bd1267b 100644 --- a/src/main/kotlin/com/lambda/config/EntryLayer.kt +++ b/src/main/kotlin/com/lambda/config/EntryLayer.kt @@ -103,4 +103,19 @@ sealed class ConfigBlockLayer { } internalForEach(this, emptyList()) } -} \ No newline at end of file +} + +fun EntryLayer>.holds(setting: Setting<*>): Boolean = when (this) { + is EntryLayer.Single -> entry === setting + is EntryLayer.Multiple -> layers.any { it.holds(setting) } + else -> false +} + +fun EntryLayer.Multiple>.hasVisibleSettings(): Boolean = + layers.any { + when (it) { + is EntryLayer.Single -> it.entry.visibility() + is EntryLayer.Multiple -> it.hasVisibleSettings() + else -> false + } + } diff --git a/src/main/kotlin/com/lambda/config/automation/UserAutomationConfig.kt b/src/main/kotlin/com/lambda/config/automation/UserAutomationConfig.kt index e19d5ddc3..976678ea2 100644 --- a/src/main/kotlin/com/lambda/config/automation/UserAutomationConfig.kt +++ b/src/main/kotlin/com/lambda/config/automation/UserAutomationConfig.kt @@ -37,6 +37,13 @@ class UserAutomationConfig(name: String) : AutomationConfig(name, UserAutomation } } + fun delete() { + linkedModules.value.forEach { name -> + moduleNameMap[name]?.let { it.automationConfig = it.defaultAutomationConfig } + } + UserAutomationCategory.configs.remove(this) + } + private fun Module.removeLink() { (automationConfig as? UserAutomationConfig)?.linkedModules?.value?.remove(name) } diff --git a/src/main/kotlin/com/lambda/config/entries/Setting.kt b/src/main/kotlin/com/lambda/config/entries/Setting.kt index dc9dcecbf..e1cd1d2e8 100644 --- a/src/main/kotlin/com/lambda/config/entries/Setting.kt +++ b/src/main/kotlin/com/lambda/config/entries/Setting.kt @@ -143,15 +143,8 @@ 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 Editor() {} open fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(string("value as JSON")) { value -> diff --git a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt index 3326afff1..61d9279e5 100644 --- a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt @@ -48,9 +48,8 @@ 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() { + override fun Editor() { val value by observe { value } Labeled(name) { TextInput(value.toString(), { text -> text.lastOrNull()?.let { this@CharSetting.value = it } }, Modifier.width(18.dp)) diff --git a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt index c5bdec965..020636a24 100644 --- a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt @@ -25,7 +25,7 @@ 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 +import com.lambda.gui.theme.Look class FunctionSetting R, R>( name: String, @@ -35,7 +35,6 @@ 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() } + override fun Editor() = Button(name, Modifier.fillMaxWidth().height(Look.rowHeight)) { value() } } diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index a0f2b6b18..f3ee50cca 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -48,22 +48,22 @@ import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer import com.lambda.gui.component.KeyboardFocus import com.lambda.gui.component.NumberInput -import com.lambda.gui.component.RowHeight +import com.lambda.gui.component.Text import com.lambda.gui.component.isActivation import com.lambda.gui.component.keyboardFocusable import com.lambda.gui.component.mouseClickable import com.lambda.gui.component.scrubbable import com.lambda.gui.core.observe +import com.lambda.gui.settings.ROW_INSET import com.lambda.gui.theme.LambdaTheme -import com.lambda.gui.theme.Radius -import com.lambda.gui.theme.Text +import com.lambda.gui.theme.Look import java.math.BigDecimal import java.math.RoundingMode import java.text.NumberFormat import java.util.* import kotlin.math.abs -import kotlin.math.roundToInt -import kotlin.math.roundToLong + +private const val SAME = 1e-4 /** * @see [com.lambda.config.Config] @@ -86,34 +86,56 @@ abstract class NumericSetting( } private val formatter = NumberFormat.getNumberInstance(Locale.getDefault()) + private val lowest get() = range.start.decimal + private val highest get() = range.endInclusive.decimal + private val Number.decimal get() = BigDecimal(toString()) - /** - * Whether dragging the bar only sets the value once the button is let go, see [appliedOnRelease]. - * Until then the bar and its number show what the value is about to be. - */ var appliedOnRelease = false - override fun toString() = "${formatter.format(value)}$unit" + override val isModified + get() = abs(originalCore.value.toDouble() - originalCore.defaultValue.toDouble()) > step.toDouble() * SAME + + protected abstract fun convert(number: BigDecimal): T + + override fun toString() = format(value) + + private fun format(value: T) = "${formatter.format(value)}$unit" + + private fun parse(text: String): T? = + text.replace(',', '.').toBigDecimalOrNull()?.let { convert(it.coerceIn(lowest, highest)) } + + private fun fractionOf(value: T): Float { + val span = range.endInclusive.toDouble() - range.start.toDouble() + val fraction = ((value.toDouble() - range.start.toDouble()) / span).toFloat() + return if (span > 0 && !fraction.isNaN()) fraction.coerceIn(0f, 1f) else 0f + } + + private fun at(fraction: Float): T = when { + fraction <= 0f -> range.start + fraction >= 1f -> range.endInclusive + else -> onGrid(lowest + (highest - lowest) * fraction.toBigDecimal(), RoundingMode.HALF_UP) + } + + private fun stepped(by: Int): T = + onGrid(value.decimal, if (by < 0) RoundingMode.CEILING else RoundingMode.FLOOR, by) + + private fun onGrid(target: BigDecimal, rounding: RoundingMode, offset: Int = 0): T { + val step = step.decimal + if (step.signum() <= 0) return convert(target.coerceIn(lowest, highest)) + val steps = (target - lowest).divide(step, 0, rounding) + offset.toBigDecimal() + return convert((lowest + step * steps).coerceIn(lowest, highest)) + } - /** - * 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. - * - * With the keyboard focus on it, the left and right arrows take the value a step down and up, - * and Enter or Space opens the field to type in. Done typing, the focus is back on the bar. - */ @Composable - override fun compose() { + override fun Editor() { val colors = LambdaTheme.colors - val value by observe { value } - val label by observe { toString() } + val current by observe { value } var typing by remember { mutableStateOf(false) } - // The bar is not there while its field is: it has to ask for the focus the field gave up val bar = remember { FocusRequester() } var refocus by remember { mutableStateOf(false) } if (typing) { - NumberInput(value, { this.value = convert(it) }, Modifier.fillMaxWidth(), focused = true) { + NumberInput(current, ::parse, { value = it }, Modifier.fillMaxWidth(), focused = true) { typing = false refocus = KeyboardFocus.visible } @@ -124,100 +146,49 @@ abstract class NumericSetting( refocus = false } - val min = range.start.toDouble() - val max = range.endInclusive.toDouble() - /** The value [steps] of the setting's step up from the bottom of its range */ - fun at(steps: Long) = convert(range.start.decimal + step.decimal * BigDecimal.valueOf(steps)) - fun stepsOf(value: Double) = ((value - min) / step.toDouble()).roundToLong() - // The value moves in steps; the bar glides from one to the next - // What the bar has been dragged to but not let go at, for a setting that waits for that var held by remember { mutableStateOf(null) } - val shown = held ?: value - val fraction by animateFloatAsState(((shown.toDouble() - min) / (max - min)).toFloat().coerceIn(0f, 1f)) + val shown = held ?: current + val label = remember(shown, unit) { format(shown) } + val fraction by animateFloatAsState(fractionOf(shown)) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier .fillMaxWidth() - .heightIn(min = RowHeight) - .clip(RoundedCornerShape(Radius.Control)) + .heightIn(min = Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) .background(colors.track) .drawBehind { drawRect(colors.trackFilled, size = Size(size.width * fraction, size.height)) } .scrubbable(onEnd = { - held?.let { this.value = it } + held?.let { value = it } held = null }) { position, size -> - val dragged = at(stepsOf(min + (position.x / size.width).coerceIn(0f, 1f) * (max - min))) - if (appliedOnRelease) held = dragged.coerceIn(range) else this.value = dragged + val dragged = at(position.x / size.width) + if (appliedOnRelease) held = dragged else value = dragged } .focusRequester(bar) .keyboardFocusable { event -> when { - event.key == Key.DirectionLeft -> this.value = at(stepsOf(value.toDouble()) - 1) - event.key == Key.DirectionRight -> this.value = at(stepsOf(value.toDouble()) + 1) + event.key == Key.DirectionLeft -> value = stepped(-1) + event.key == Key.DirectionRight -> value = stepped(1) event.isActivation -> typing = true else -> return@keyboardFocusable false } true } - .padding(horizontal = 3.dp) + .padding(horizontal = ROW_INSET) ) { Text(name, Modifier.weight(1f), colors.onControl, maxLines = 1) Text( - text = held?.let { "${formatter.format(it)}$unit" } ?: label, + text = label, modifier = Modifier.mouseClickable(keyboard = false) { typing = true }, color = colors.onControl, maxLines = 1, ) } } - - /** - * A value is only saved once it is other than the default. One that is a rounding error - * away from it is not: files written while sliders still counted in binary hold such values, - * 0.14999999 for a default of 0.15, and they are the default. - */ - override val isModified - get() = abs(originalCore.value.toDouble() - originalCore.defaultValue.toDouble()) > step.toDouble() * SAME - - /** - * The number as the decimal it is written as. A slider counts its steps in these, because a - * step of 0.01 is not 0.01 in binary and thirty of them do not add up to 0.3: counted in - * binary, a bar dragged back to its default arrives a hair beside it, which shows the same - * and is saved as a change. Counted in decimal, every stop of the bar is exactly the number - * the code would write for it, however fine the step and however long the range. - */ - private val Number.decimal get() = BigDecimal(toString()) - - /** A decimal as the setting's own number type: the float or double nearest to it, as a literal of it would be */ - @Suppress("UNCHECKED_CAST") - private fun convert(number: BigDecimal): T = - when (value) { - is Int -> number.setScale(0, RoundingMode.HALF_UP).toInt() - is Long -> number.setScale(0, RoundingMode.HALF_UP).toLong() - is Float -> number.toPlainString().toFloat() - else -> number.toPlainString().toDouble() - } as T - - /** 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 } -/** How far from its default, as a share of its step, a number may be and still be the default: a rounding error, never a step */ -private const val SAME = 1e-4 - -/** - * Has dragging the bar set the value only when the button is let go, where it otherwise follows - * the pointer. For a value that moves the bar it is set on, the scale of the interface: applied - * as it is dragged, the bar would shift and resize under the pointer that is setting it. - */ fun > S.appliedOnRelease() = apply { appliedOnRelease = true } @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 f47bd69e1..46c115af5 100644 --- a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt @@ -37,11 +37,12 @@ import com.lambda.config.ConfigEditorD5l import com.lambda.config.SettingEditBuilder import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer +import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput import com.lambda.gui.core.observe import com.lambda.gui.settings.Labeled -import com.lambda.gui.settings.TextFieldWidth -import com.lambda.gui.theme.Text +import com.lambda.gui.settings.ROW_INSET +import com.lambda.gui.settings.TEXT_FIELD_WIDTH import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess @@ -58,17 +59,15 @@ 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() { + override fun Editor() { 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) + Text(name, Modifier.padding(start = ROW_INSET, top = 1.dp), maxLines = 1) TextInput(value, { this@StringSetting.value = it }, Modifier.fillMaxWidth(), singleLine = false) } else Labeled(name) { - TextInput(value, { this@StringSetting.value = it }, Modifier.width(TextFieldWidth)) + TextInput(value, { this@StringSetting.value = it }, Modifier.width(TEXT_FIELD_WIDTH)) } } 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 b6717f62a..c3356a650 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/BlockCollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/BlockCollectionSetting.kt @@ -44,6 +44,5 @@ class BlockCollectionSetting( serialize = true, ) { 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/CollectionSetting.kt b/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt index 7d196209b..114722580 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt @@ -69,14 +69,11 @@ open class CollectionSetting( value.size != defaultValue.size || defaultValue.any { !value.contains(it) } } - /** A chip with how much is selected, which opens the editor in a window of its own */ @Composable - override fun compose() = CollectionButton(this) + override fun Editor() = CollectionButton(this) - /** How [item] is shown to the user */ open fun label(item: R): String = item.toString() - /** What Minecraft shows [item] as in an inventory, for settings of game content; null for the rest */ open fun icon(item: R): ItemStack? = null fun select(item: R) { @@ -92,7 +89,6 @@ open class CollectionSetting( 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/comparable/BooleanSetting.kt b/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt index 2982d44b3..3898ee845 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt @@ -35,10 +35,11 @@ import com.lambda.config.Config import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer import com.lambda.gui.component.Checkmark -import com.lambda.gui.component.RowHeight +import com.lambda.gui.component.Text import com.lambda.gui.component.mouseClickable import com.lambda.gui.core.observe -import com.lambda.gui.theme.Text +import com.lambda.gui.settings.ROW_INSET +import com.lambda.gui.theme.Look import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess @@ -50,18 +51,17 @@ class BooleanSetting( visibility: () -> Boolean, defaultValue: Boolean ) : Setting(name, description, defaultValue, layer, config, visibility) { - /** A tick box and the name: the whole row flips it */ @Composable - override fun compose() { + override fun Editor() { val checked by observe { value } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier .fillMaxWidth() - .heightIn(min = RowHeight) + .heightIn(min = Look.rowHeight) .mouseClickable { value = !value } - .padding(horizontal = 3.dp) + .padding(horizontal = ROW_INSET) ) { Checkmark(checked) Text(name, maxLines = 1) 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 c6346831c..c3fa309db 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt @@ -21,7 +21,6 @@ import androidx.compose.foundation.layout.padding 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 @@ -33,6 +32,7 @@ import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer import com.lambda.gui.component.Dropdown import com.lambda.gui.core.observe +import com.lambda.gui.settings.ROW_INSET import com.lambda.util.StringUtils.capitalize import com.lambda.util.extension.CommandBuilder import com.lambda.util.extension.displayValue @@ -46,16 +46,15 @@ class EnumSetting>( visibility: () -> Boolean, defaultValue: T ) : Setting(name, description, defaultValue, layer, config, visibility) { - /** The name, and a chip that drops the options down under it */ @Composable - override fun compose() { + override fun Editor() { val selected by observe { value } Dropdown( label = name, options = selected.enumValues.asList(), selected = selected, optionLabel = { it.displayValue }, - modifier = Modifier.padding(start = 3.dp), + modifier = Modifier.padding(start = ROW_INSET), ) { value = it } } 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 f7479874a..3f88d24a7 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt @@ -32,17 +32,16 @@ import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer import com.lambda.gui.component.Button import com.lambda.gui.component.NumberInput -import com.lambda.gui.component.RowHeight import com.lambda.gui.component.Tooltip import com.lambda.gui.core.observe import com.lambda.gui.settings.Labeled -import com.lambda.gui.settings.NumberFieldWidth +import com.lambda.gui.settings.NUMBER_FIELD_WIDTH +import com.lambda.gui.theme.Look import com.lambda.util.CommunicationUtils.info import com.lambda.util.extension.CommandBuilder import com.lambda.util.world.raycast.RayCastUtils.blockResult import net.minecraft.command.CommandRegistryAccess import net.minecraft.util.math.BlockPos -import kotlin.math.roundToInt class BlockPosSetting( name: String, @@ -52,16 +51,15 @@ class BlockPosSetting( visibility: () -> Boolean, defaultValue: BlockPos ) : Setting(name, description, defaultValue, layer, config, visibility) { - /** A field for each coordinate, and a button that takes the block under the crosshair */ @Composable - override fun compose() { + override fun Editor() { val pos by observe { value.toImmutable() } Labeled(name) { - NumberInput(pos.x, { value = BlockPos(it.roundToInt(), pos.y, pos.z) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) - NumberInput(pos.y, { value = BlockPos(pos.x, it.roundToInt(), pos.z) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) - NumberInput(pos.z, { value = BlockPos(pos.x, pos.y, it.roundToInt()) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) + NumberInput(pos.x, String::toIntOrNull, { value = BlockPos(it, pos.y, pos.z) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) + NumberInput(pos.y, String::toIntOrNull, { value = BlockPos(pos.x, it, pos.z) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) + NumberInput(pos.z, String::toIntOrNull, { value = BlockPos(pos.x, pos.y, it) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) Tooltip("Use the block you are looking at") { - Button("Target", Modifier.height(RowHeight)) { + Button("Target", Modifier.height(Look.rowHeight)) { mc.crosshairTarget?.blockResult?.blockPos?.let { value = it } ?: this@BlockPosSetting.info("No block under crosshair") } 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 80f527555..ffb3c143d 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt @@ -38,9 +38,8 @@ class BlockSetting( visibility: () -> Boolean, defaultValue: Block ) : Setting(name, description, defaultValue, layer, config, visibility) { - /** A chip with the block and its icon, which opens a window listing every block */ @Composable - override fun compose() = BlockPicker(this) + override fun Editor() = BlockPicker(this) override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(blockState(name, registry)) { argument -> diff --git a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt index a2e34c034..4ad2bedeb 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt @@ -39,9 +39,8 @@ class ColorSetting( visibility: () -> Boolean, defaultValue: Color ) : Setting(name, description, defaultValue, layer, config, visibility) { - /** A swatch of the colour, which opens the picker beside the row */ @Composable - override fun compose() = ColorPicker(this) + override fun Editor() = ColorPicker(this) override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(integer("Red", 0, 255)) { red -> diff --git a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt index 678084b29..c27214579 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -53,14 +53,13 @@ import com.lambda.event.Muteable import com.lambda.event.events.ButtonEvent import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe import com.lambda.gui.GuiScreen -import com.lambda.gui.component.RowHeight +import com.lambda.gui.component.Text import com.lambda.gui.component.Tooltip import com.lambda.gui.component.mouseClickable import com.lambda.gui.core.observe import com.lambda.gui.settings.Labeled import com.lambda.gui.theme.LambdaTheme -import com.lambda.gui.theme.Radius -import com.lambda.gui.theme.Text +import com.lambda.gui.theme.Look import com.lambda.threading.runSafe import com.lambda.util.KeyCode import com.lambda.util.Mouse @@ -131,13 +130,8 @@ class KeybindSetting( } } - /** - * 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 - override fun compose() { + override fun Editor() { val colors = LambdaTheme.colors val bind by observe { value } var recording by remember { mutableStateOf(false) } @@ -150,9 +144,8 @@ class KeybindSetting( Box( contentAlignment = Alignment.Center, modifier = Modifier - .height(RowHeight) - .clip(RoundedCornerShape(Radius.Control)) - // Filled as every control is, and in the second accent while it waits for a key + .height(Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) .background(if (recording) colors.secondary else colors.control) .mouseClickable { recording = true 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 777323fae..a77473fe8 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt @@ -31,7 +31,7 @@ import com.lambda.config.entries.SettingEntryLayer import com.lambda.gui.component.NumberInput import com.lambda.gui.core.observe import com.lambda.gui.settings.Labeled -import com.lambda.gui.settings.NumberFieldWidth +import com.lambda.gui.settings.NUMBER_FIELD_WIDTH import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess import net.minecraft.util.math.Vec3d @@ -44,14 +44,14 @@ class Vec3dSetting( visibility: () -> Boolean, defaultValue: Vec3d ) : Setting(name, description, defaultValue, layer, config, visibility) { - /** A field for each coordinate */ @Composable - override fun compose() { + override fun Editor() { val vec by observe { value } Labeled(name) { - NumberInput(vec.x, { value = Vec3d(it, vec.y, vec.z) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) - NumberInput(vec.y, { value = Vec3d(vec.x, it, vec.z) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) - NumberInput(vec.z, { value = Vec3d(vec.x, vec.y, it) }, Modifier.weight(1f, fill = false).width(NumberFieldWidth)) + val parse = { text: String -> text.toDoubleOrNull()?.takeIf(Double::isFinite) } + NumberInput(vec.x, parse, { value = Vec3d(it, vec.y, vec.z) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) + NumberInput(vec.y, parse, { value = Vec3d(vec.x, it, vec.z) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) + NumberInput(vec.z, parse, { value = Vec3d(vec.x, vec.y, it) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) } } 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 5c72d8a87..2528eb8d7 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/DoubleSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/DoubleSetting.kt @@ -26,6 +26,7 @@ import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.settings.NumericSetting import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess +import java.math.BigDecimal /** * @see [com.lambda.config.Config] @@ -41,6 +42,8 @@ class DoubleSetting( override var step: Double, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { + override fun convert(number: BigDecimal) = number.toDouble() + 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 2e749b9a9..e17cf2bd2 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/FloatSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/FloatSetting.kt @@ -26,6 +26,7 @@ import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.settings.NumericSetting import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess +import java.math.BigDecimal /** * @see [com.lambda.config.Config] @@ -41,6 +42,8 @@ class FloatSetting( override var step: Float = 1f, unit: String, ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { + override fun convert(number: BigDecimal) = number.toFloat() + 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 7aa14e4b2..764d9039b 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt @@ -26,6 +26,8 @@ import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.settings.NumericSetting import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess +import java.math.BigDecimal +import java.math.RoundingMode /** * @see [com.lambda.config.Config] @@ -41,6 +43,8 @@ class IntegerSetting( override var step: Int = 1, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { + override fun convert(number: BigDecimal) = number.setScale(0, RoundingMode.HALF_UP).toInt() + override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(integer(name, range.start, range.endInclusive)) { parameter -> 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 462b6221f..bfbb72325 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt @@ -26,6 +26,8 @@ import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.settings.NumericSetting import com.lambda.util.extension.CommandBuilder import net.minecraft.command.CommandRegistryAccess +import java.math.BigDecimal +import java.math.RoundingMode /** * @see [com.lambda.config.Config] @@ -41,6 +43,8 @@ class LongSetting( override var step: Long = 1, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { + override fun convert(number: BigDecimal) = number.setScale(0, RoundingMode.HALF_UP).toLong() + override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(long(name, range.start, range.endInclusive)) { parameter -> execute { diff --git a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt index ad2c0aee1..09d8a0552 100644 --- a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt +++ b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt @@ -301,10 +301,6 @@ 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, @@ -329,7 +325,6 @@ object LambdaRenderPipelines : Loadable { .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"), @@ -337,7 +332,6 @@ object LambdaRenderPipelines : Loadable { 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"), diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index 4dfc68ab4..76a267a08 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -28,17 +28,11 @@ 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, - * 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) @@ -54,10 +48,9 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { .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 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 } @@ -71,35 +64,18 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @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. One that is [inRow] has no position of its own: it is wherever the row puts it, - * and moves with the row when the style spaces or sizes the windows differently. - */ data class WindowPlacement(val x: Float, val y: Float, val collapsed: Boolean) { val inRow get() = x.isNaN() || y.isNaN() companion object { - /** A window in its place in the row, folded away or not */ fun inRow(collapsed: Boolean) = WindowPlacement(Float.NaN, Float.NaN, collapsed) } } - // 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 or folded away are absent. */ var windows: Map get() { val saved = windowPlacements @@ -115,7 +91,6 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { } } - /** Forgets where the category windows were moved to, which puts them back in their row */ fun resetWindows() { windows = emptyMap() } diff --git a/src/main/kotlin/com/lambda/gui/GuiScreen.kt b/src/main/kotlin/com/lambda/gui/GuiScreen.kt index 1745941f1..2d2f24c01 100644 --- a/src/main/kotlin/com/lambda/gui/GuiScreen.kt +++ b/src/main/kotlin/com/lambda/gui/GuiScreen.kt @@ -38,21 +38,11 @@ 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, @@ -63,7 +53,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { 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) } @@ -82,20 +71,15 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { 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) @@ -120,11 +104,9 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { 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) @@ -149,7 +131,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { 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 - // Where every program has its search: the field of the menu bar takes the keyboard if (input.key() == GLFW.GLFW_KEY_F && input.modifiers() and GLFW.GLFW_MOD_CONTROL != 0) { ClickGuiState.focusSearch = LambdaGui.screen == LambdaGui.Screen.ClickGui return true @@ -169,10 +150,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { 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( @@ -185,7 +162,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { 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) } ) @@ -193,12 +169,10 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { 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 index c2f4b2be2..871a14e30 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -19,7 +19,6 @@ 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 @@ -30,11 +29,7 @@ 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.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.KeyboardFocus import com.lambda.gui.component.TextFocus import com.lambda.gui.core.GameClipboard @@ -43,7 +38,6 @@ import com.lambda.gui.core.Observations import com.lambda.gui.core.Retained import com.lambda.gui.core.SceneHost import com.lambda.gui.core.SceneInput -import com.lambda.gui.core.awaitFrames import com.lambda.gui.hud.Hud import com.lambda.gui.hud.HudEditor import com.lambda.gui.hud.HudLayer @@ -52,6 +46,7 @@ import com.lambda.gui.render.ItemAtlas import com.lambda.gui.settings.SettingsList import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Motion import com.lambda.module.modules.client.AutoUpdater import com.lambda.module.modules.client.Client import com.lambda.module.modules.client.Style @@ -63,43 +58,35 @@ 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. - * - * 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 { + private const val REFERENCE_HEIGHT = 540f + private const val MAX_FAILURES = 3 + private const val FAILURE_WINDOW_NANOS = 60_000_000_000L + enum class Screen { ClickGui, HudEditor } - /** 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 failures = 0 + private var failedAt = 0L 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 + private val observations = Observations() + private val clickGuiObservations = Observations() - /** Cursor the element under the pointer wants, or null for the default */ + internal val input: SceneInput? get() = host?.input internal val cursor: Cursor? get() = host?.platform?.cursor + internal var onEscape: (() -> Boolean)? = null - /** 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 { @@ -107,8 +94,6 @@ object LambdaGui : Loadable { } 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() @@ -116,9 +101,6 @@ object LambdaGui : Loadable { 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" } @@ -129,7 +111,7 @@ object LambdaGui : Loadable { 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.") + warn("Lambda's interface stopped after repeated errors. Check the log, and restart the game to bring it back.") return } if (this.screen == null) { @@ -141,18 +123,10 @@ object LambdaGui : Loadable { 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() @@ -162,10 +136,6 @@ object LambdaGui : Loadable { 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) @@ -192,21 +162,31 @@ object LambdaGui : Loadable { 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() + if (e is OutOfMemoryError) throw e + fail(e) } } - /** - * 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 fail(error: Throwable) { + val now = System.nanoTime() + if (now - failedAt > FAILURE_WINDOW_NANOS) failures = 0 + failedAt = now + broken = ++failures >= MAX_FAILURES + LOG.error(if (broken) "Lambda's interface failed again and was switched off" else "Lambda's interface failed and is being rebuilt", error) + + val failed = host + host = null + ItemAtlas.release() + runCatching { failed?.closeAndFree() }.onFailure { LOG.warn("Could not free the failed interface", it) } + observations.active.clear() + clickGuiObservations.active.clear() + if (screen != null) GuiScreen.close() + warn( + if (broken) "Lambda's interface stopped after repeated errors. Check the log, and restart the game to bring it back." + else "Lambda's interface hit an error and was restarted. Check the log for what went wrong." + ) + } + private fun warmUp(size: IntSize, density: Float) { val start = System.nanoTime() try { @@ -218,17 +198,18 @@ object LambdaGui : Loadable { 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() } + val failed = host host = null + ItemAtlas.release() + runCatching { failed?.closeAndFree() } } } private fun createHost(): SceneHost { prepareSkiko() - return SceneHost { Content() }.also { host = it } + return SceneHost(Motion) { Content() }.also { host = it } } @Composable @@ -236,39 +217,24 @@ object LambdaGui : Loadable { CompositionLocalProvider(LocalObservations provides observations, LocalClipboard provides GameClipboard) { LambdaTheme { KeyboardFocus.Layer() - // 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() - } - } + Reveal.Expiry() - // 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() } } } - /** 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( @@ -285,16 +251,9 @@ object LambdaGui : Loadable { 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/clickgui/Reveal.kt b/src/main/kotlin/com/lambda/gui/Reveal.kt similarity index 61% rename from src/main/kotlin/com/lambda/gui/clickgui/Reveal.kt rename to src/main/kotlin/com/lambda/gui/Reveal.kt index eef7fd68f..5a310b521 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/Reveal.kt +++ b/src/main/kotlin/com/lambda/gui/Reveal.kt @@ -15,69 +15,59 @@ * along with this program. If not, see . */ -package com.lambda.gui.clickgui +package com.lambda.gui +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.lambda.config.Config import com.lambda.config.automation.AutomationConfig import com.lambda.config.entries.Setting -import com.lambda.gui.GuiConfig -import com.lambda.gui.LambdaGui +import com.lambda.gui.clickgui.ClickGuiDialog +import com.lambda.gui.clickgui.ClickGuiState +import com.lambda.gui.core.awaitFrames import com.lambda.module.HudModule import com.lambda.module.Module import com.lambda.module.ModuleRegistry import com.lambda.module.ModuleTag -/** - * 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 { + private const val MILLIS = 1800L + 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<*>?) { + fun show(config: Config, setting: Setting<*>? = null) { 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" - */ + @Composable + fun Expiry() { + val module = module + val setting = setting + LaunchedEffect(module, setting) { + if (module == null && setting == null) return@LaunchedEffect + awaitFrames(MILLIS) + this@Reveal.module = null + this@Reveal.setting = null + } + } + private fun owner(config: Config): Module? = config as? Module ?: config.takeIf { it !== AutomationConfig.DEFAULT } ?.let { ModuleRegistry.modules.firstOrNull { module -> module.automationConfig === config } } - 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 diff --git a/src/main/kotlin/com/lambda/gui/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt index 982fb78e3..71dce0277 100644 --- a/src/main/kotlin/com/lambda/gui/Snap.kt +++ b/src/main/kotlin/com/lambda/gui/Snap.kt @@ -17,29 +17,27 @@ package com.lambda.gui +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp import com.lambda.config.settings.complex.Bind import com.lambda.util.InputUtils.isSatisfied +import com.lambda.util.math.toCompose import kotlin.math.abs import kotlin.math.max import kotlin.math.roundToInt -/** - * 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. */ + private const val MIN_GRID_STEP = 4f + private val GRID_COLOR = Color.White.copy(alpha = 0.11f) + data class Guides(val x: Float?, val y: Float?) { companion object { val NONE = Guides(null, null) @@ -48,76 +46,82 @@ internal object Snap { 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 */ + private class Target(val shift: Float, val guide: Float?) + 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 gridStep(density: Density) = with(density) { max(MIN_GRID_STEP, GuiConfig.gridSize.dp.toPx()) } + + fun free(element: Rect, area: Rect) = Result(element.topLeft.keptIn(area, element.size), Guides.NONE) + + fun snap(element: Rect, others: Collection, area: Rect, density: Density, spacing: Float = 0f): Result = with(density) { + fun axis(start: (Rect) -> Float, end: (Rect) -> Float): Target { fun center(rect: Rect) = (start(rect) + end(rect)) / 2 - val lines = listOf(start(element), center(element), end(element)) + val from = start(element) + val size = end(element) - from + fun startAt(at: Float, guide: Float? = at) = Target(at - from, guide) + fun endAt(at: Float, guide: Float? = at) = Target(at - size - from, guide) + fun centerAt(at: Float, guide: Float? = at) = Target(at - size / 2 - from, guide) - // 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 { + val neighbours = buildList { if (GuiConfig.snapToEdges) { - add(-half) - add(extent + half) - others.forEach { - add(start(it) - half) - add(end(it) + half) + add(startAt(start(area))) + add(endAt(end(area))) + others.forEach { other -> + add(startAt(start(other))) + add(endAt(end(other))) + add(startAt(end(other) + spacing, end(other) + spacing / 2)) + add(endAt(start(other) - spacing, start(other) - spacing / 2)) } } - if (GuiConfig.snapToCenters) others.forEach { add(center(it)) } + if (GuiConfig.snapToCenters) others.forEach { add(centerAt(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 middle = center(area) + val screenCenter = listOf(startAt(middle), centerAt(middle), endAt(middle)).takeIf { GuiConfig.snapToScreenCenter }.orEmpty() + val step = gridStep(density) + fun onGrid(line: Float) = (line / step).roundToInt() * step + val grid = listOf( + startAt(onGrid(from), null), + centerAt(onGrid(from + size / 2), null), + endAt(onGrid(from + size), null), + ).takeIf { GuiConfig.snapToGrid }.orEmpty() + + return listOf( + neighbours to GuiConfig.snapDistanceElement.dp.toPx(), + screenCenter to GuiConfig.snapDistanceScreen.dp.toPx(), + grid to GuiConfig.snapDistanceGrid.dp.toPx(), + ).firstNotNullOfOrNull { (targets, reach) -> + targets.minByOrNull { abs(it.shift) }?.takeIf { abs(it.shift) <= reach } + } ?: Target(0f, null) } - val (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)) + val x = axis({ it.left }, { it.right }) + val y = axis({ it.top }, { it.bottom }) + Result((element.topLeft + Offset(x.shift, y.shift)).keptIn(area, element.size), Guides(x.guide, y.guide)) } - /** 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 } + fun Modifier.snapLines(drop: () -> Result?): Modifier = drawWithContent { + val guides = drop()?.guides.takeIf { GuiConfig.showSnapLines } + if (guides != null && isActive && GuiConfig.snapToGrid) drawGrid() + drawContent() + if (guides != null) { + val color = GuiConfig.snapLineColor.toCompose() + guides.x?.let { drawLine(color, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } + guides.y?.let { drawLine(color, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } } - 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)) + private fun DrawScope.drawGrid() { + val step = gridStep(this) + generateSequence(0f) { it + step }.takeWhile { it <= size.width } + .forEach { drawLine(GRID_COLOR, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } + generateSequence(0f) { it + step }.takeWhile { it <= size.height } + .forEach { drawLine(GRID_COLOR, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } + } + + private fun Offset.keptIn(area: Rect, element: Size) = Offset( + x.coerceIn(area.left, max(area.left, area.right - element.width)), + y.coerceIn(area.top, max(area.top, area.bottom - element.height)) ) } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index bbfb3ae95..8ec881334 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -63,69 +63,42 @@ 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.Reveal import com.lambda.gui.Snap -import com.lambda.gui.component.RowHeight import com.lambda.gui.component.ScrollColumn import com.lambda.gui.component.SlidingText +import com.lambda.gui.component.Text import com.lambda.gui.component.Tooltip import com.lambda.gui.component.hoverHighlight import com.lambda.gui.component.mouseClickable import com.lambda.gui.component.mouseDraggable +import com.lambda.gui.component.shadowed import com.lambda.gui.component.window import com.lambda.gui.core.LocalShown import com.lambda.gui.core.observe +import com.lambda.gui.menu.MENU_BAR_HEIGHT import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look import com.lambda.gui.theme.Motion -import com.lambda.gui.theme.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 -import com.lambda.module.modules.client.Style import kotlin.math.absoluteValue -internal val CategoryWindowWidth get() = Look.windowWidth -internal val CategoryWindowGap get() = Look.windowGap +private val REACH = 40.dp +private const val IN_ROW = 1.5f +private val EMBOSS = Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05f), Color.Transparent)) -/** Room between the edge of a window and the text of its rows */ -private val RowPadding get() = Look.modulePadding - -/** How much of a window is always kept on the screen from its top: its header and a module or two */ -private val Reach = 40.dp - -/** How far from its place in the row, in dp either way, a window may be left and still count as in it */ -private const val InRow = 1.5f - -/** - * What makes a module a tile rather than a flat stripe, when the style asks for it: a trace of light along the top that is gone - * by the bottom, over whatever the tile is filled with. Only just there: it is felt more than seen. - * The tiles touch, as a gap would show the dark panel as a black line between two enabled ones. - */ -private val Emboss = Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05f), Color.Transparent)) - -/** - * 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. The settings are a panel - * beside the module, one of [panels], unless the style has them [inline], under the module. - * - * 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: List, - panels: List, - inline: ((Module) -> SettingsPanelState)?, - onEdit: (Module) -> Unit, + onDrop: (Snap.Result?) -> Unit, + settings: OpenSettings, + inline: Boolean, onFocus: () -> Unit, modifier: Modifier = Modifier, ) { @@ -136,29 +109,26 @@ internal fun CategoryWindow( val density = LocalDensity.current val screen = LocalWindowInfo.current.containerSize.toSize() val screenHeight = with(density) { screen.height.toDp() } + val area = Rect(0f, with(density) { MENU_BAR_HEIGHT.toPx() }, screen.width, screen.height) - // 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?.takeUnless { it.inRow }?.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 drop = 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()) } + if (snapping) Snap.snap(window, bounds.filterKeys { it != tag }.values, area, density, with(density) { Look.windowGap.toPx() }) + else Snap.free(window, area) + } + if (drop != null) SideEffect { onDrop(drop) } + val shownPosition = drop?.let { + with(density) { DpOffset(it.position.x.toDp(), it.position.y.toDp()) } } ?: (position ?: defaultPosition).let { at -> - // Never off the screen, wherever it was left: a screen made smaller since, by a larger - // scale or a smaller window, would otherwise put it out of reach val screenWidth = with(density) { screen.width.toDp() } DpOffset( - at.x.coerceIn(0.dp, (screenWidth - CategoryWindowWidth).coerceAtLeast(0.dp)), - at.y.coerceIn(0.dp, (screenHeight - Reach).coerceAtLeast(0.dp)), + at.x.coerceIn(0.dp, (screenWidth - Look.windowWidth).coerceAtLeast(0.dp)), + at.y.coerceIn(MENU_BAR_HEIGHT, (screenHeight - REACH).coerceAtLeast(MENU_BAR_HEIGHT)), ) } val currentPosition by rememberUpdatedState(shownPosition) @@ -166,17 +136,12 @@ internal fun CategoryWindow( onDispose { bounds -= tag } } - // A window left in its place in the row, or put back there, is kept as being in the row - // rather than at the spot: it then follows the row when the style spaces, sizes or moves it, - // where a spot would pin it under the windows that do fun place(at: DpOffset, collapsed: Boolean) { - val inRow = (at.x - defaultPosition.x).value.absoluteValue < InRow && (at.y - defaultPosition.y).value.absoluteValue < InRow + val inRow = (at.x - defaultPosition.x).value.absoluteValue < IN_ROW && (at.y - defaultPosition.y).value.absoluteValue < IN_ROW GuiConfig.windows += tag.name to if (inRow) GuiConfig.WindowPlacement.inRow(collapsed) else GuiConfig.WindowPlacement(at.x.value, at.y.value, collapsed) } - // One that comes as a spot from elsewhere, a config saved before that distinction was made - // or loaded just now, is looked at the same way as it is found LaunchedEffect(placement) { position?.let { place(it, collapsed) } } @@ -184,17 +149,16 @@ internal fun CategoryWindow( Column( modifier = modifier .offset(shownPosition.x, shownPosition.y) - .width(CategoryWindowWidth) + .width(Look.windowWidth) .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.Window)) + .window(colors.surface, colors.border, RoundedCornerShape(Look.windowRounding)) ) { Text( text = tag.name, @@ -209,65 +173,52 @@ internal fun CategoryWindow( onDragEnd = { if (dragged != null) place(currentPosition, collapsed) dragged = null + onDrop(null) }, ) { delta -> dragged = dragged?.plus(delta) } .mouseClickable(onRightClick = { - // Settings hang off a row of the list, and go with it - if (!collapsed) edited.filter { it in modules }.forEach(onEdit) + if (!collapsed) settings.close(modules) place(currentPosition, !collapsed) }) - .padding(horizontal = RowPadding, vertical = 2.dp) + .padding(horizontal = Look.modulePadding, 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 - // Looked up here, where a panel being added to the list has this run again to tell it - val hanging = panels.filter { it.module in modules } + val hanging = modules.mapNotNull(settings::panelOf) SideEffect { hanging.forEach { it.settled = settled } } AnimatedVisibility( visibleState = unfolded, enter = expandVertically(Motion.windows), exit = shrinkVertically(Motion.windows), ) { - // 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 in edited, - // Settings under the module are plainly its own: it is only pressed in - // for ones that are out beside it, to show which row they hang off - pressedIn = inline == null, - panel = panels.find { it.module == module }, - onEdit = { onEdit(module) }, + isEdited = settings.isOpen(module), + pressedIn = !inline, + panel = settings.panelOf(module).takeUnless { inline }, + onEdit = { settings.toggle(module) }, ) - // Where the style has settings drop down under their module instead - if (inline != null) InlineSettings(inline(module), open = module in edited) + if (inline) InlineSettings(settings.stateOf(module), open = settings.isOpen(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, pressedIn: Boolean, panel: SettingsPanelState?, onEdit: () -> Unit) { val colors = LambdaTheme.colors val enabled by observe { module.isEnabled } - val embossed by observe { Style.emboss } 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 && pressedIn) colors.inset.copy(alpha = colors.inset.alpha / 2) 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) { @@ -284,22 +235,17 @@ private fun ModuleRow(module: Module, isEdited: Boolean, pressedIn: Boolean, pan else Modifier.onGloballyPositioned { panel.row = Rect(it.positionInRoot(), it.size.toSize()) } ) .bringIntoViewRequester(intoView) - // One that is always enabled has nothing to toggle: either click opens its settings .mouseClickable(onRightClick = onEdit) { if (module.alwaysEnabled) onEdit() else module.toggle() } .background(fill) .background(pressed) .background(lit) - // A shade lighter under the pointer, or darker in the light theme .hoverHighlight(colors.raised) - .then(if (embossed) Modifier.background(Emboss) else Modifier) - // As tall as the style asks, or as its name needs if that is more - .heightIn(min = RowHeight) - .padding(horizontal = RowPadding) + .then(if (Look.emboss) Modifier.background(EMBOSS) else Modifier) + .heightIn(min = Look.rowHeight) + .padding(horizontal = Look.modulePadding) ) { - // A name too long for the window slides along rather than being cut short SlidingText( text = module.name, - // The fill is for what is on: one that is only being edited is merely lit color = when { enabled -> colors.onModuleEnabled isEdited -> colors.onSurface diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index b5b75b5c6..9a2b65162 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -45,7 +45,9 @@ import androidx.compose.ui.zIndex import com.lambda.config.Config import com.lambda.gui.GuiConfig import com.lambda.gui.LambdaGui +import com.lambda.gui.Reveal import com.lambda.gui.Snap +import com.lambda.gui.Snap.snapLines import com.lambda.gui.component.Button import com.lambda.gui.component.mouseClickable import com.lambda.gui.core.LocalShown @@ -57,102 +59,50 @@ import com.lambda.gui.menu.MenuBar import com.lambda.gui.menu.NewAutomationConfigDialog import com.lambda.gui.theme.Look import com.lambda.module.HudModule -import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.module.modules.client.AutoUpdater import com.lambda.module.modules.client.Style -/** 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 get() = Look.windowTop +internal val CLICK_GUI_CATEGORIES = ModuleTag.defaults - ModuleTag.HUD -/** - * 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 - -/** What the row of windows was last laid out with, and whether the interface was open then */ private class RowLayout(var row: Triple, var shown: Boolean = false) -/** 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) - - /** Set to have the search field of the menu bar take the keyboard, which then unsets it */ var focusSearch 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 }) + CLICK_GUI_CATEGORIES.filter(ModuleTag::isTagShown) + listOfNotNull(ModuleTag.DEBUG.takeIf { developerMode }) } - // The modules whose settings are open, the last opened last: one of them, unless the style - // lets several be open at once. A 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 - val edited = remember { mutableStateListOf() } - 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 stateOf(module: Module) = panelStates.getOrPut(module) { SettingsPanelState(module) } - // Beside the module as a panel, or where the style asks for it, dropped down under it + val settings = remember { OpenSettings() } val inline by observe { Style.inlineSettings } - val several by observe { Style.multipleSettings } - fun edit(module: Module) { - if (!several) edited.clear() - if (module !in edited) edited += module - val panel = stateOf(module) - if (!inline && panel !in panels) panels += panel - } - // What a press beside the settings does: puts them away, all of them where several are open - fun dismiss() = edited.clear() - // The style changed with settings open: held to one at a time again, the last opened is the - // one that stays, and no longer under their modules, they are out beside them as panels - LaunchedEffect(inline, several) { - if (!several && edited.size > 1) edited.removeRange(0, edited.size - 1) - if (!inline) edited.forEach { module -> stateOf(module).let { if (it !in panels) panels += it } } - } - // 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) + if (revealedModule != null && revealedModule !is HudModule && revealedSetting != null) settings.open(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.clear() - panels.clear() - } + if (!shown && !GuiConfig.keepSettingsOpen) settings.forget() } - // The row is laid out anew when the style changes what it is made of, the width of a window, - // the gap between two or how far down they start: every window goes back to its place in it. - // A row spaced or sized differently around windows left where they were would not be one, and - // which of those were meant to be elsewhere is not something their places can tell. Only while - // the interface is open, which is when the style is being set: what it was changed to in the - // meantime, by a config being loaded, moves nothing. - val row = Triple(CategoryWindowWidth, CategoryWindowGap, WindowRowTop) + val row = Triple(Look.windowWidth, Look.windowGap, Look.windowTop) val laidOut = remember { RowLayout(row) } SideEffect { if (row != laidOut.row && shown && laidOut.shown) { @@ -162,37 +112,30 @@ internal fun ClickGui() { laidOut.shown = shown } - // 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 } + var drop by remember { mutableStateOf(null) } - Box(Modifier.fillMaxSize().mouseClickable(keyboard = false, onClick = ::dismiss)) { - // 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 + Box(Modifier.fillMaxSize().mouseClickable(keyboard = false, onClick = settings::closeAll).snapLines { drop }) { val inRow = tags.count { it != ModuleTag.DEBUG } - // On a screen too narrow for the row, which a large scale makes of any screen, the windows - // close up and overlap like a hand of cards rather than run off its edge: every one of - // them keeps a strip that can be pressed, which brings it to the front val screenWidth = with(density) { screen.width.toDp() } - val pitch = (CategoryWindowWidth + CategoryWindowGap) - .coerceAtMost((screenWidth - CategoryWindowWidth) / (inRow - 1).coerceAtLeast(1)) + val pitch = (Look.windowWidth + Look.windowGap) + .coerceAtMost((screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1)) .coerceAtLeast(0.dp) - val rowWidth = CategoryWindowWidth + pitch * (inRow - 1) + val rowWidth = Look.windowWidth + pitch * (inRow - 1) val rowStart = ((screenWidth - rowWidth) / 2).coerceAtLeast(0.dp) tags.forEachIndexed { index, tag -> key(tag) { CategoryWindow( tag = tag, - defaultPosition = DpOffset(rowStart + pitch * index, WindowRowTop), + defaultPosition = DpOffset(rowStart + pitch * index, Look.windowTop), bounds = bounds, snapping = snapping, - edited = edited, - panels = panels, - inline = if (inline) ::stateOf else null, - onEdit = { module -> if (module in edited) edited -= module else edit(module) }, + onDrop = { drop = it }, + settings = settings, + inline = inline, onFocus = { stacking.remove(tag) stacking.add(tag) @@ -202,13 +145,13 @@ internal fun ClickGui() { } } - panels.forEach { panel -> + settings.panels.forEach { panel -> key(panel.module) { SettingsPanel( panel = panel, - // One left open when the style is changed to have them inline folds away - open = panel.module in edited && !inline, - onClosed = { panels -= panel }, + open = settings.isOpen(panel.module) && !inline, + windows = bounds, + onClosed = { settings.closed(panel.module) }, modifier = Modifier.zIndex(stacking.size.toFloat()) ) } @@ -218,11 +161,10 @@ internal fun ClickGui() { 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) dismiss() + if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) settings.closeAll() } } } @@ -234,11 +176,13 @@ internal fun ClickGui() { ) { 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 + val prompt = observe { AutoUpdater.prompt }.value + val closeDialog = { ClickGuiState.dialog = null } + val dialog = ClickGuiState.dialog + when { + prompt != null -> LoaderPromptDialog(prompt) + dialog is ClickGuiDialog.About -> AboutDialog(closeDialog) + dialog is ClickGuiDialog.NewAutomationConfig -> NewAutomationConfigDialog(closeDialog) + dialog is ClickGuiDialog.Settings -> ConfigDialog(dialog.config, closeDialog) } } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt new file mode 100644 index 000000000..50be533d5 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt @@ -0,0 +1,76 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.clickgui + +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.unit.dp +import com.lambda.gui.settings.PanelPage +import com.lambda.module.Module +import com.lambda.module.modules.client.Style + +internal class SettingsPanelState(val module: Module) { + var page by mutableStateOf(PanelPage.Settings) + var extension by mutableStateOf(0.dp) + var row by mutableStateOf(Rect.Zero) + var settled by mutableStateOf(false) +} + +@Stable +internal class OpenSettings { + private val states = HashMap() + private val open = mutableStateListOf() + private val closing = mutableStateListOf() + + val panels: List get() = (open + closing).map(::stateOf) + + fun stateOf(module: Module) = states.getOrPut(module) { SettingsPanelState(module) } + + fun panelOf(module: Module) = if (module in open || module in closing) stateOf(module) else null + + fun isOpen(module: Module) = module in open + + fun open(module: Module) { + if (!Style.multipleSettings) closeAll() + closing -= module + if (module !in open) open += module + } + + fun toggle(module: Module) = if (isOpen(module)) close(module) else open(module) + + fun close(module: Module) { + if (open.remove(module)) closing += module + } + + fun close(modules: Collection) = open.filter { it in modules }.forEach(::close) + + fun closeAll() = open.toList().forEach(::close) + + fun closed(module: Module) { + closing -= module + } + + fun forget() { + open.clear() + closing.clear() + } +} diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index bd16657f1..1c58cb9e4 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -17,9 +17,7 @@ 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 @@ -28,12 +26,9 @@ import androidx.compose.animation.core.spring import androidx.compose.animation.expandIn import androidx.compose.animation.shrinkOut import androidx.compose.foundation.ExperimentalFoundationApi -import androidx.compose.foundation.ScrollState import androidx.compose.foundation.background 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.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -52,7 +47,6 @@ 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 @@ -60,7 +54,6 @@ 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.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect @@ -79,95 +72,42 @@ 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.Expandable -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.awaitFrames -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.menu.MENU_BAR_HEIGHT +import com.lambda.gui.settings.ModuleSettings import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look -import com.lambda.gui.theme.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 com.lambda.module.modules.client.Style +import com.lambda.gui.theme.Motion +import com.lambda.module.ModuleTag 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 get() = Look.panelPadding - -/** A panel is given at least this much height, even under a module at the bottom of the screen */ -private val MinHeight = 120.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) -} +private val MIN_WIDTH = 130.dp +private val MIN_HEIGHT = 120.dp +private val MIN_GRIP_HEIGHT = 3.dp +private val INSET_SHADOW = 5.dp +private const val SETTLE_MILLIS = 200L +private val WIDTH_CHANGE = spring(stiffness = Spring.StiffnessMedium) -/** - * 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) { +internal fun SettingsPanel( + panel: SettingsPanelState, + open: Boolean, + windows: Map, + 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 wanted = open && panel.settled && !row.isEmpty val popups = remember { PopupHost() } SideEffect { popups.closing = !wanted } visibility.targetState = wanted @@ -175,83 +115,74 @@ internal fun SettingsPanel(panel: SettingsPanelState, open: Boolean, onClosed: ( SideEffect(onClosed) return } + if (row.isEmpty) 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 barBottom = with(density) { MENU_BAR_HEIGHT.toPx() } + val window = windows[panel.module.tag] + val top = (if (window == null) row.top else row.top.coerceIn(window.top, (window.bottom - row.height).coerceAtLeast(window.top))) + .coerceAtLeast(barBottom) + val below = with(density) { (screen.height - top).toDp() }.coerceAtLeast(MIN_HEIGHT) + val highest = screenHeight - MENU_BAR_HEIGHT val maxHeight = (below + panel.extension).coerceAtMost(highest) - // 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)) + val fitsRight = row.right - overlap + size.width <= screen.width + val fitsLeft = row.left + overlap - size.width >= 0 + val flipped = !fitsRight && (fitsLeft || row.left > screen.width - row.right) + val lift = (top + unfolded - screen.height).coerceIn(0f, top - barBottom) - // 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.Panel else 0.dp, - topEnd = if (!flipped || lift > 0f) Radius.Panel else 0.dp, - bottomEnd = Radius.Panel, - bottomStart = Radius.Panel, + topStart = if (flipped || lift > 0f) Look.panelRounding else 0.dp, + topEnd = if (!flipped || lift > 0f) Look.panelRounding else 0.dp, + bottomEnd = Look.panelRounding, + bottomStart = Look.panelRounding, ) val seam = if (flipped) Alignment.TopEnd else Alignment.TopStart Box( modifier .offset { + val room = (screen.width - size.width).coerceAtLeast(0) IntOffset( - (if (flipped) row.left + overlap else row.right - overlap).roundToInt(), - (row.top - lift).roundToInt() + if (flipped) (row.left + overlap).roundToInt().coerceIn(screen.width - room, screen.width) + else (row.right - overlap).roundToInt().coerceIn(0, room), + (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.Panel)), - enter = expandIn(Unfold, seam), - exit = shrinkOut(Unfold, seam), + .dropShadow(RoundedCornerShape(Look.panelRounding)), + enter = expandIn(Motion.panels, seam), + exit = shrinkOut(Motion.panels, seam), ) { val colors = LambdaTheme.colors - // ...nor wider than the style allows. What is too long for it gives way rather than - // widening the panel: a value slides along under the pointer. - val maxWidth by observe { Style.settingsWidth.dp } 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 + .widthIn(MIN_WIDTH, Look.settingsWidth) .heightIn(max = maxHeight) .widthOfContent() .onSizeChanged { size = it } .window(colors.panel, colors.border, shape) ) { CompositionLocalProvider(LocalPopupHost provides popups) { - Column(Modifier.padding(Padding)) { Pages(panel, scroll) } + Column(Modifier.padding(Look.panelPadding)) { ModuleSettings(panel.module, panel.page, { panel.page = it }, scroll) } } - // 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 -> @@ -266,13 +197,6 @@ internal fun SettingsPanel(panel: SettingsPanelState, open: Boolean, onClosed: ( } } -/** - * A module's settings dropped down under its row, inside its window: what the style can have in - * place of the panel beside it. They are as wide as the window, whatever they hold, and push the - * modules under them down while [open]; a name or a value too long for the room slides along - * under the pointer, as it does anywhere. They scroll with the list they are in, and come into - * view when they open. - */ @OptIn(ExperimentalFoundationApi::class) @Composable internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { @@ -289,14 +213,10 @@ internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { Modifier .fillMaxWidth() .bringIntoViewRequester(intoView) - // Filled as a panel beside the module would be and then shaded a little, a quarter - // as far as what is pressed in: inside a window the fill alone is too close to it .background(colors.panel) .background(colors.inset.copy(alpha = colors.inset.alpha / 4)) - // And darker at its top and bottom edges, as what is set into a surface is where - // the surface overhangs it .drawWithCache { - val depth = InsetShadow.toPx().coerceAtMost(size.height / 2) + val depth = INSET_SHADOW.toPx().coerceAtMost(size.height / 2) val dark = colors.inset.copy(alpha = colors.inset.alpha / 2) val top = Brush.verticalGradient(listOf(dark, Color.Transparent), 0f, depth) val bottom = Brush.verticalGradient(listOf(Color.Transparent, dark), size.height - depth, size.height) @@ -305,84 +225,25 @@ internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { drawRect(bottom, Offset(0f, size.height - depth), Size(size.width, depth)) } } - .padding(Padding / 2) - ) { Pages(panel, scroll = null) } + .padding(Look.panelPadding / 2) + ) { ModuleSettings(panel.module, panel.page, { panel.page = it }, scroll = null) } } } -/** How far the shade at the top and bottom of settings under their module reaches into them */ -private val InsetShadow = 5.dp - -/** How long settings take to drop down, before they are where they will stay */ -private const val SETTLE_MILLIS = 200L - -/** - * What a module's settings are made of, in a panel or dropped down under its row: the strip - * that turns their pages, and under it the page turned to. In a panel the page scrolls by - * itself, on [scroll], under a strip that stays put; without one it is as long as it is. - */ -@Composable -private fun ColumnScope.Pages(panel: SettingsPanelState, scroll: ScrollState?) { - 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() - - SoftTextShadow { - if (pages.size > 1) PageStrip(pages, page) { - panel.page = it - // A page turned to by hand starts at its top - if (scroll != null) scope.launch { scroll.scrollTo(0) } - } - // Turned like the tabs a module's settings bring - val turned = @Composable { - 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) - } - } - } - } - if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } else turned() - } -} - -/** - * 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) } + if (current.targetValue != wanted) scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } val placeable = measurable.measure(Constraints.fixedWidth(current.value.roundToInt()).copy(maxHeight = constraints.maxHeight)) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } } -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 @@ -391,128 +252,10 @@ private fun Grip(onDragStart: () -> Unit, onDrag: (up: Dp) -> Unit, modifier: Mo contentAlignment = Alignment.Center, modifier = modifier .fillMaxWidth() - .height(Padding) + .height(Look.panelPadding.coerceAtLeast(MIN_GRIP_HEIGHT)) .pointerHoverIcon(ResizeVerticalIcon) .mouseDraggable(onDragStart = onDragStart) { delta -> onDrag(with(density) { -delta.y.toDp() }) } ) { Spacer(Modifier.size(16.dp, 1.dp).background(color, RoundedCornerShape(50))) } } - -/** - * 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, each page with - * a share to match its name, 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.secondary else colors.raised) - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - // By the length of its name and its padding: in equal parts a long name - // would be cut short in a narrow panel while a short one had room to spare - .weight(page.title.length + 2f) - .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 index 09c8a86a6..5344534a4 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -25,9 +25,6 @@ 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 @@ -35,23 +32,14 @@ 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.ReadOnlyComposable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -61,57 +49,26 @@ 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.Layout -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.Constraints -import androidx.compose.ui.unit.Dp 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.LocalRowHeight import com.lambda.gui.theme.Look -import com.lambda.gui.theme.Radius -import com.lambda.gui.theme.Text -import com.lambda.gui.theme.Type - -/** - * How tall a module, a row of settings or a control is at least, so stacked ones line up. Set in - * the style as its element height; by default a line of text and a hair of room. - */ -val RowHeight: Dp - @Composable @ReadOnlyComposable get() = LocalRowHeight.current private const val TOGGLE_MILLIS = 150 +private val SECTION_BAR = 1.dp +private val LABEL_GAP = 3.dp -/** - * A button. One that is [prominent] is filled like the header of a category rather than like a - * control: for the one that leads somewhere else, of which a screen has one at most. - */ @Composable fun Button( label: String, @@ -126,8 +83,8 @@ fun Button( Box( contentAlignment = Alignment.Center, modifier = modifier - .heightIn(min = RowHeight + 2.dp) - .clip(RoundedCornerShape(Radius.Control)) + .heightIn(min = Look.rowHeight + 2.dp) + .clip(RoundedCornerShape(Look.controlRounding)) .background(fill) .hoverHighlight(text.copy(alpha = if (enabled) 0.12f else 0f)) .mouseClickable(enabled, onClick = onClick) @@ -137,15 +94,13 @@ fun Button( } } -/** 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.Box)) - // Empty, it is the grey of a slider's track, which stands out on a panel without an outline + .clip(RoundedCornerShape(Look.boxRounding)) .background(if (checked) colors.primary else colors.track) ) { if (!checked) return@Canvas @@ -162,10 +117,6 @@ fun Checkmark(checked: Boolean, modifier: Modifier = Modifier) { } } -/** - * 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)) { @@ -175,7 +126,6 @@ fun Ellipsis(modifier: Modifier = Modifier, color: Color = LocalContentColor.cur } } -/** 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)) { @@ -191,177 +141,6 @@ fun Chevron(degrees: Float, modifier: Modifier = Modifier, color: Color = LocalC } } -/** - * 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.Control)) - .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( @@ -372,31 +151,19 @@ fun Expandable(visible: Boolean, modifier: Modifier = Modifier, content: @Compos ) { 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) } + var expanded by remember { mutableStateOf(false) } LaunchedEffect(revealed) { if (revealed) expanded = true } val turn by animateFloatAsState(if (expanded) 90f else 0f, tween(TOGGLE_MILLIS)) - val rowHeight = RowHeight + val rowHeight = Look.rowHeight Column( Modifier @@ -404,44 +171,31 @@ fun Section( .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)) + drawRect(colors.primary, size = Size(SECTION_BAR.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.Control)) - .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) - } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.raised) + .mouseClickable { expanded = !expanded } + .padding(horizontal = 4.dp) + ) { + Chevron(turn, color = colors.onSurface) + Text(title, color = colors.onSurface, maxLines = 1) } Expandable(expanded) { - Column(Modifier.fillMaxWidth().padding(start = SectionIndent, top = 1.dp), content = content) + Column(Modifier.fillMaxWidth().padding(start = Look.groupIndent, 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 get() = Look.groupIndent - -/** - * 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 @@ -450,8 +204,8 @@ fun Chip(onClick: () -> Unit, modifier: Modifier = Modifier, content: @Composabl verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = modifier - .height(RowHeight) - .clip(RoundedCornerShape(Radius.Control)) + .height(Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) .background(colors.control) .hoverHighlight(colors.onControl.copy(alpha = 0.12f)) .mouseClickable(onClick = onClick) @@ -461,10 +215,6 @@ fun Chip(onClick: () -> Unit, modifier: Modifier = Modifier, content: @Composabl } } -/** - * 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, @@ -478,12 +228,10 @@ fun Dropdown( var chip by remember { mutableStateOf(IntSize.Zero) } LabeledRow(label, modifier) { Box(Modifier.onSizeChanged { chip = it }) { - // A choice too long for the room the chip is given slides along under the pointer 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) { @@ -495,28 +243,19 @@ fun Dropdown( } } -/** - * A row with [label] at its start and, at its end, whatever edits the value it names. - * - * With room for both, each is as wide as it likes and the room left over lies between them. - * Without, as in the width of a window when settings drop down under their module, neither is - * let crowd the other out: the editor gives way first, down to three fifths of the row, and the - * label has what is left. What does not fit of either slides along under the pointer. - */ @Composable fun LabeledRow(label: String, modifier: Modifier = Modifier, editor: @Composable RowScope.() -> Unit) { Layout( content = { Text(label, maxLines = 1) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(LabelGap), content = editor) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(LABEL_GAP), content = editor) }, - modifier = modifier.fillMaxWidth().heightIn(min = RowHeight), + modifier = modifier.fillMaxWidth().heightIn(min = Look.rowHeight), ) { (name, edited), constraints -> - val gap = LabelGap.roundToPx() + val gap = LABEL_GAP.roundToPx() val loose = constraints.copy(minWidth = 0, minHeight = 0) val room = constraints.maxWidth val wanted = edited.maxIntrinsicWidth(constraints.maxHeight) - // Asked how wide it would like to be, which is what sizes a panel: as wide as both val editorWidth = if (!constraints.hasBoundedWidth) wanted else wanted.coerceAtMost(maxOf(room - name.maxIntrinsicWidth(constraints.maxHeight) - gap, room * 3 / 5)) @@ -532,14 +271,3 @@ fun LabeledRow(label: String, modifier: Modifier = Modifier, editor: @Composable } } } - -/** Room between a label and what edits its value, and between the parts of that */ -private val LabelGap = 3.dp - -/** 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/component/Images.kt b/src/main/kotlin/com/lambda/gui/component/Images.kt index cd5cd07dd..b68555340 100644 --- a/src/main/kotlin/com/lambda/gui/component/Images.kt +++ b/src/main/kotlin/com/lambda/gui/component/Images.kt @@ -17,14 +17,41 @@ package com.lambda.gui.component +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.toComposeImageBitmap +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Dp +import com.lambda.gui.render.ItemAtlas +import com.lambda.gui.render.ItemAtlas.drawItem import com.lambda.util.stream +import net.minecraft.item.ItemStack import org.jetbrains.skia.Image +import kotlin.math.roundToInt -/** 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() } + +@Composable +fun ItemIcon(stack: ItemStack, size: Dp, modifier: Modifier = Modifier) { + val slot = remember { ItemAtlas.Slot() } + val density = LocalDensity.current + val pixels = with(density) { ItemAtlas.ITEM * (size.toPx() / ItemAtlas.ITEM).roundToInt().coerceAtLeast(1) } + SideEffect { + slot.stack = stack + slot.size = pixels + } + DisposableEffect(slot) { + ItemAtlas.add(slot) + onDispose { ItemAtlas.remove(slot) } + } + Spacer(modifier.size(with(density) { pixels.toDp() }).drawBehind { drawItem(slot) }) +} diff --git a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt index e23214e65..5441d4b7b 100644 --- a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt +++ b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt @@ -45,30 +45,15 @@ import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.unit.dp import com.lambda.gui.theme.LambdaTheme -/** - * How the interface is being driven. Everything that can be clicked can also be reached from - * the keyboard: Tab and Shift with Tab step through it in order, the arrow keys move to what - * lies in their direction, and Enter or Space is a click on whatever the focus is on, with - * Shift a right click. - * - * The focus is only marked, and only acted on, while it is the keyboard that moves it. A mouse - * press puts the mark away, and with it the chance of Enter toggling something that was left - * focused out of sight; the next Tab or arrow key brings it back. - */ +private val FOCUS_MARK = 1.dp + internal object KeyboardFocus { var visible by mutableStateOf(false) - /** The focus of the interface and of every window open over it that takes the keyboard, the innermost last */ private val layers = ArrayList() - /** Moves the focus of whatever has the keyboard, and returns whether there was anywhere to move it */ fun move(direction: FocusDirection) = layers.lastOrNull()?.moveFocus(direction) == true - /** - * Has the keys that move the focus move it here, among what this is called beside, for as - * long as it is on screen. For the interface itself and for what opens over it and takes - * the keyboard, a menu or a dialog: each of those has a focus of its own. - */ @Composable fun Layer() { val manager = LocalFocusManager.current @@ -79,10 +64,6 @@ internal object KeyboardFocus { } } -/** - * Makes the element a stop for the keyboard focus, outlined while it holds it. Every key that - * goes down while it does is offered to [onKey], which returns whether the key was for it. - */ fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = composed { if (!LocalKeyboardReachable.current) return@composed Modifier var focused by remember { mutableStateOf(false) } @@ -90,24 +71,15 @@ fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = compose val mark = LambdaTheme.colors.onSurface onFocusChanged { focused = it.isFocused } .onKeyEvent { it.type == KeyEventType.KeyDown && KeyboardFocus.visible && handle(it) } - // Brings what it is on into view as well, in a list that scrolls .focusable() - // In the colour of text, as what the search points at is lit: nothing else is outlined in it .drawWithContent { drawContent() if (!focused || !KeyboardFocus.visible) return@drawWithContent - val width = FocusMark.toPx() + val width = FOCUS_MARK.toPx() drawRect(mark, Offset(width / 2, width / 2), Size(size.width - width, size.height - width), style = Stroke(width)) } } -/** - * Whether the keyboard focus stops on what is inside. Off for what the pointer cannot reach - * either, a setting that is disabled: the focus passes it by, so no key can change it. - */ val LocalKeyboardReachable = compositionLocalOf { true } -/** Whether the key is one that clicks what the focus is on */ -internal val KeyEvent.isActivation get() = key == Key.Enter || key == Key.NumPadEnter || key == Key.Spacebar - -private val FocusMark = 1.dp +internal val KeyEvent.isActivation get() = key == Key.Enter || key == Key.Spacebar diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt index 82be906b2..a5f8fa3a5 100644 --- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -17,14 +17,9 @@ 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.ScrollableState import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.drag @@ -35,7 +30,6 @@ 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 @@ -44,45 +38,15 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.isShiftPressed import androidx.compose.ui.input.pointer.PointerButton -import androidx.compose.ui.input.pointer.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 com.lambda.gui.theme.Motion -import com.lambda.module.modules.client.Style -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. - * - * What can be clicked can be reached from the [keyboard] too, see [KeyboardFocus]: with the - * focus on it, Enter or Space is a left click and Shift with either a right click. Where there - * is nothing for a left click to do, the plain keys do what the right click does. Turn it off - * for what is clicked as a backdrop rather than as a thing. - */ @OptIn(ExperimentalComposeUiApi::class) fun Modifier.mouseClickable( enabled: Boolean = true, keyboard: Boolean = true, onRightClick: (() -> Unit)? = null, - onMiddleClick: (() -> Unit)? = null, onClick: (() -> Unit)? = null, ): Modifier = if (!enabled) this @@ -92,7 +56,6 @@ fun Modifier.mouseClickable( when (button) { PointerButton.Primary -> onClick PointerButton.Secondary -> onRightClick - PointerButton.Tertiary -> onMiddleClick else -> null } } @@ -109,17 +72,14 @@ fun Modifier.mouseClickable( 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() @@ -132,29 +92,14 @@ fun Modifier.mouseClickable( } } -/** 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) @@ -170,10 +115,6 @@ private fun Modifier.onPress(handle: (button: PointerButton?, position: Offset) } } -/** - * 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) { @@ -183,7 +124,6 @@ fun Modifier.consumeClicks(): Modifier = pointerInput(Unit) { } } -/** 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 = {}, @@ -197,17 +137,11 @@ fun Modifier.mouseDraggable( 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. - * [onEnd] is called once it has been. - */ fun Modifier.scrubbable(onEnd: () -> Unit = {}, onScrub: (position: Offset, size: IntSize) -> Unit): Modifier = composed { val currentOnScrub by rememberUpdatedState(onScrub) val currentOnEnd by rememberUpdatedState(onEnd) pointerInput(Unit) { awaitEachGesture { - // On a desktop only the left button counts as the first down of a gesture val down = awaitFirstDown() down.consume() currentOnScrub(down.position, size) @@ -220,63 +154,6 @@ fun Modifier.scrubbable(onEnd: () -> Unit = {}, onScrub: (position: Offset, 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 * Style.scrollSpeed - 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(Motion.Scroll) { - 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, before the scroll speed of the style: 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() diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index b3837b2dd..04e73c311 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -77,6 +77,7 @@ import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.layout.positionInWindow +import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalWindowInfo import androidx.compose.ui.unit.IntOffset @@ -88,90 +89,63 @@ import androidx.compose.ui.unit.round import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupPositionProvider import androidx.compose.ui.window.PopupProperties +import com.lambda.gui.core.GameClipboard import com.lambda.gui.core.LocalShown +import com.lambda.gui.core.Press import com.lambda.gui.core.awaitFrames -import com.lambda.gui.theme.ContentColor import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look import com.lambda.gui.theme.Motion -import com.lambda.gui.theme.Radius -import com.lambda.gui.theme.Text import com.lambda.gui.theme.Type import com.lambda.module.modules.client.Style import kotlin.math.max -/** Where a [Menu] opens relative to the element it is declared in */ +@OptIn(ExperimentalComposeUiApi::class) +private val FLOATING = PopupProperties( + focusable = true, + dismissOnBackPress = true, + dismissOnClickOutside = true, + clippingEnabled = true, + usePlatformDefaultWidth = false, + usePlatformInsets = true, + consumePointerInputOutside = false, +) + +private val SLACK = 4.dp + +@Composable +private fun ScenePopup( + popupPositionProvider: PopupPositionProvider, + onDismissRequest: (() -> Unit)? = null, + properties: PopupProperties = PopupProperties(), + onKeyEvent: ((KeyEvent) -> Boolean)? = null, + content: @Composable () -> Unit, +) = Popup(popupPositionProvider, onDismissRequest, properties, onKeyEvent = onKeyEvent) { + CompositionLocalProvider(LocalClipboard provides GameClipboard, content = content) +} + enum class MenuPlacement { - /** 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 + private var dismissedBy = -1L fun dismiss() { isOpen = false - dismissedAt = System.nanoTime() + dismissedBy = Press.id } 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 + if (dismissedBy != Press.id) isOpen = true } } -/** - * 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. - * - * One that is [attached] continues an element with a square edge, and is square along it too. - * - * ``` - * val menu = remember { MenuState() } - * Box { - * Button("File", onClick = menu::toggle) - * Menu(menu.isOpen, onDismiss = menu::dismiss) { - * MenuItem("Save") { save() } - * } - * } - * ``` - */ @Composable fun Menu( open: Boolean, @@ -189,36 +163,24 @@ private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize 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.Panel)) { panel -> + FloatingPanel(open, position, onDismiss, RoundedCornerShape(Look.panelRounding)) { 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, false, 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() } @@ -230,10 +192,8 @@ 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 @@ -248,23 +208,19 @@ private fun MenuPopup( val open = open && LocalMenuOpen.current val dismissAll = LocalMenuDismiss.current ?: onDismiss val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } - // One that is attached is of a piece with a square edge of its element: square there too, on whichever side it opened val shape = when { - !attached -> RoundedCornerShape(Radius.Menu) - position.upwards -> RoundedCornerShape(topStart = Radius.Menu, topEnd = Radius.Menu) - else -> RoundedCornerShape(bottomStart = Radius.Menu, bottomEnd = Radius.Menu) + !attached -> RoundedCornerShape(Look.menuRounding) + position.upwards -> RoundedCornerShape(topStart = Look.menuRounding, topEnd = Look.menuRounding) + else -> RoundedCornerShape(bottomStart = Look.menuRounding, bottomEnd = Look.menuRounding) } FloatingPanel(open, position, onDismiss, shape, unfoldFrom) { panel -> CompositionLocalProvider(LocalMenuDismiss provides dismissAll, LocalMenuOpen provides open) { ScrollColumn( modifier = Modifier - // 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) - // Entries run right up to the outline on every side, cut to its corners .clip(shape), content = content ) @@ -272,27 +228,12 @@ private fun MenuPopup( } } -/** - * 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 get() = Motion.panels - -/** - * 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 @@ -302,18 +243,15 @@ class PopupHost { } } -/** 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 slack = SLACK.toPx() val dx = when { origin.x >= full.right - slack -> left.right - full.right origin.x + size.width <= full.left + slack -> left.left - full.left @@ -324,7 +262,6 @@ private fun Modifier.swallowedBy(host: PopupHost?): Modifier = if (host == null) 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, @@ -337,17 +274,6 @@ private fun Modifier.swallowedBy(host: PopupHost?): Modifier = if (host == null) } } -/** 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, @@ -357,7 +283,6 @@ private fun FloatingPanel( 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 @@ -366,31 +291,28 @@ private fun FloatingPanel( 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( + ScenePopup( popupPositionProvider = position, onDismissRequest = { if (open) onDismiss() }, - properties = Floating, + properties = FLOATING, onKeyEvent = { open && it.dismissOnEscape(onDismiss) }, ) { if (open) KeyboardFocus.Layer() 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) }, + enter = expandIn(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, + exit = shrinkOut(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, ) { CompositionLocalProvider(LocalPopupHost provides own) { content(Modifier.onSizeChanged { position.unfolded = it }.window(colors.panel, colors.border, shape)) @@ -400,25 +322,16 @@ private fun FloatingPanel( } } -/** - * 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 */ var upwards by mutableStateOf(false) private set - /** The corner it grows out of */ val corner get() = when { upwards -> if (leftwards) Alignment.BottomEnd else Alignment.BottomStart @@ -435,10 +348,8 @@ private class UnfoldingPosition( 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 @@ -446,17 +357,8 @@ private class UnfoldingPosition( } } -/** - * 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. It is centred under the element, however - * much wider than it the results make it. A press outside of it calls [onDismiss]. - * - * It unfolds downwards while [open] and folds back up once it is not, and in between it grows - * and shrinks with what it lists rather than jumping from one length to the next. - */ @Composable fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { - // Gone at once with the interface, which leaves nothing on screen to fold away if (!LocalShown.current) { if (open) SideEffect(onDismiss) return @@ -466,9 +368,9 @@ fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable Colum if (!open && visibility.isIdle && !visibility.currentState) return val colors = LambdaTheme.colors - val shape = RoundedCornerShape(Radius.Menu) + val shape = RoundedCornerShape(Look.menuRounding) val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } - Popup( + ScenePopup( popupPositionProvider = remember { positionProvider { anchor, window, popup -> val centred = anchor.left + (anchor.width - popup.width) / 2 @@ -479,19 +381,18 @@ fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable Colum properties = PopupProperties(focusable = false), ) { ContentColor(colors.onSurface) { - // By size alone and with the shadow cast from outside the clip, as every floating panel unfolds AnimatedVisibility( visibleState = visibility, modifier = Modifier.dropShadow(shape), - enter = expandVertically(Unfold, Alignment.Top), - exit = shrinkVertically(Unfold, Alignment.Top), + enter = expandVertically(Motion.panels, Alignment.Top), + exit = shrinkVertically(Motion.panels, Alignment.Top), ) { ScrollColumn( modifier = Modifier .heightIn(max = screenHeight * 0.6f) .width(IntrinsicSize.Max) .window(colors.panel, colors.border, shape) - .animateContentSize(Unfold) + .animateContentSize(Motion.panels) .clip(shape), content = content ) @@ -500,10 +401,6 @@ fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable Colum } } -/** - * 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, @@ -519,7 +416,6 @@ fun MenuItem( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() - // The chosen one is lifted and named in the second accent, so it stands out from the rest at a glance .background(if (selected) colors.controlSelected else Color.Transparent) .then( if (!enabled) Modifier @@ -541,7 +437,6 @@ fun MenuItem( } } -/** 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 @@ -565,10 +460,6 @@ fun Submenu(label: String, enabled: Boolean = true, content: @Composable ColumnS 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 @@ -595,20 +486,14 @@ fun MenuDivider() = Spacer( .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( + ScenePopup( popupPositionProvider = remember { positionProvider { _, _, _ -> IntOffset.Zero } }, properties = PopupProperties(focusable = true), onKeyEvent = { onDismiss != null && it.dismissOnEscape(onDismiss) }, @@ -624,7 +509,7 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { ContentColor(colors.onSurface) { Box( modifier = Modifier - .window(colors.panel, colors.border, RoundedCornerShape(Radius.Panel), floating = true) + .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) .padding(6.dp), content = content ) @@ -633,15 +518,6 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { } } -/** - * 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()) { @@ -681,7 +557,7 @@ fun Tooltip(text: String, modifier: Modifier = Modifier, content: @Composable () content() if (visible && hovered) { val below = with(LocalDensity.current) { 16.dp.roundToPx() } - Popup( + ScenePopup( popupPositionProvider = remember(pointer, bounds) { positionProvider { _, window, popup -> val at = (bounds.topLeft + pointer).round() + IntOffset(0, below) @@ -699,7 +575,7 @@ fun Tooltip(text: String, modifier: Modifier = Modifier, content: @Composable () style = Type.label, modifier = Modifier .widthIn(max = 220.dp) - .window(colors.panel, colors.border, RoundedCornerShape(Radius.Menu)) + .window(colors.panel, colors.border, RoundedCornerShape(Look.menuRounding)) .padding(horizontal = 4.dp, vertical = 2.dp) ) } diff --git a/src/main/kotlin/com/lambda/gui/component/Scroll.kt b/src/main/kotlin/com/lambda/gui/component/Scroll.kt new file mode 100644 index 000000000..608b73c85 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Scroll.kt @@ -0,0 +1,132 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.animation.core.EaseOutQuint +import androidx.compose.animation.core.animate +import androidx.compose.animation.core.tween +import androidx.compose.foundation.MutatePriority +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.ScrollbarStyle +import androidx.compose.foundation.VerticalScrollbar +import androidx.compose.foundation.gestures.ScrollableState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.rememberScrollbarAdapter +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.v2.ScrollbarAdapter +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +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.input.key.type +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Motion +import com.lambda.module.modules.client.Style +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch + +private val WHEEL_STEP = 14.dp +private val GLIDE = tween(durationMillis = 520, easing = EaseOutQuint) +private const val SCROLLBAR_FADE_MILLIS = 150 + +@Composable +fun ScrollColumn( + modifier: Modifier = Modifier, + scroll: ScrollState = rememberScrollState(), + content: @Composable ColumnScope.() -> Unit, +) { + Box(modifier.wheelScrollable(scroll)) { + Column(Modifier.verticalScroll(scroll), content = content) + if (scroll.maxValue > 0) Scrollbar(rememberScrollbarAdapter(scroll), Modifier.matchParentSize()) + } +} + +@Composable +fun Scrollbar(adapter: ScrollbarAdapter, modifier: Modifier) { + val colors = LambdaTheme.colors + Box(modifier) { + VerticalScrollbar( + adapter = adapter, + modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), + style = ScrollbarStyle( + minimalHeight = 12.dp, + thickness = 2.dp, + shape = RoundedCornerShape(1.dp), + hoverDurationMillis = SCROLLBAR_FADE_MILLIS, + unhoverColor = colors.onSurfaceVariant.copy(alpha = 0.5f), + hoverColor = colors.onSurface + ) + ) + } +} + +fun Modifier.wheelScrollable(state: ScrollableState): Modifier = composed { + val scope = rememberCoroutineScope() + val notch = with(LocalDensity.current) { WHEEL_STEP.toPx() } + val glide = remember { WheelGlide() } + pointerInput(state, notch) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type != PointerEventType.Scroll) continue + val change = event.changes.first() + val distance = change.scrollDelta.y * notch * Style.scrollSpeed + val canFollow = if (distance > 0) state.canScrollForward else state.canScrollBackward + if (distance == 0f || !canFollow || change.isConsumed) continue + change.consume() + + val total = distance + if (glide.remaining * distance > 0) glide.remaining else 0f + glide.job?.cancel() + glide.job = scope.launch(Motion.SCROLL) { + var travelled = 0f + glide.remaining = total + try { + state.scroll(MutatePriority.UserInput) { + animate(0f, total, animationSpec = GLIDE) { value, _ -> + scrollBy(value - travelled) + travelled = value + glide.remaining = total - value + } + } + } finally { + if (glide.job === coroutineContext[Job]) glide.remaining = 0f + } + } + } + } + } +} + +private class WheelGlide { + var remaining = 0f + var job: Job? = null +} diff --git a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt index 69700540a..b0553283f 100644 --- a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt +++ b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt @@ -41,20 +41,15 @@ import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp import com.lambda.gui.theme.LocalContentColor import com.lambda.gui.theme.Motion -import com.lambda.gui.theme.Text import com.lambda.gui.theme.Type import kotlin.math.roundToInt import kotlinx.coroutines.withContext -/** - * 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. - */ +private val SLIDE_SPEED = 28.dp +private const val REST_MILLIS = 350 +private const val END_REST_MILLIS = 900 +private const val BACK_MILLIS = 250 + @Composable fun SlidingText( text: String, @@ -62,13 +57,11 @@ fun SlidingText( 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() } + val pixelsPerSecond = with(LocalDensity.current) { SLIDE_SPEED.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) { @@ -76,8 +69,7 @@ fun SlidingText( return@LaunchedEffect } val outMillis = (overflow / pixelsPerSecond * 1000).roundToInt().coerceAtLeast(BACK_MILLIS) - // At the pace it is read at, whatever the style makes of the animations - withContext(Motion.Unscaled) { + withContext(Motion.UNSCALED) { slide.animateTo( targetValue = 0f, animationSpec = infiniteRepeatable( @@ -104,21 +96,8 @@ fun SlidingText( 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 index 301815734..6370ffa4f 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -38,11 +38,7 @@ 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.Look -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 @@ -53,29 +49,35 @@ 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. - * - * 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. - */ +private val SHADOW_COLOR = Color.Black.copy(alpha = 0.55f) +private val SHADOW_BLUR = 5.dp +private val SHADOW_DROP = 2.dp +private val CLOSE_SHADOW_COLOR = Color.Black.copy(alpha = 0.85f) +private val CLOSE_SHADOW_BLUR = 3.dp +private val CLOSE_SHADOW_DROP = 2.dp + +private val DRAWN = ImageFilter.makeColorFilter( + ColorFilter.makeMatrix( + ColorMatrix( + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 64f, 0f, + ) + ), + null, + null +) + +private val REPLACE = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC } +private val WITHIN = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC_IN } + fun Modifier.glass(color: Color, shape: Shape): Modifier = clip(shape).composed { - val sigma = with(LocalDensity.current) { LocalBackdropBlur.current.toPx() } - val underlay = LocalUnderlay.current + val sigma = with(LocalDensity.current) { Look.backdropBlur.toPx() } + val underlay = Look.underlay val blur = remember(sigma, underlay) { if (sigma <= 0f) return@remember null val blurred = ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) - // 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 { @@ -84,46 +86,26 @@ fun Modifier.glass(color: Color, shape: Shape): Modifier = clip(shape).composed 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.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 } + .then(if (Look.outlines) Modifier.border(Look.outlineWidth, 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 drop = (if (close) CLOSE_SHADOW_DROP else SHADOW_DROP).toPx() + val blur = (if (close) CLOSE_SHADOW_BLUR else SHADOW_BLUR).toPx() val reach = blur * 3 val shadow = Paint().apply { - color = (if (close) CloseShadowColor else ShadowColor).toArgb() + color = (if (close) CLOSE_SHADOW_COLOR else SHADOW_COLOR).toArgb() maskFilter = MaskFilter.makeBlur(FilterBlurMode.NORMAL, blur) } onDrawBehind { @@ -132,11 +114,8 @@ fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = drawWi 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.saveLayer(Canvas.SaveLayerRec(null, null, DRAWN)) + skia.saveLayer(null, WITHIN) skia.translate(0f, drop) skia.drawPath(body.asSkiaPath(), shadow) skia.restore() @@ -147,31 +126,6 @@ fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = drawWi } } -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 -) - -/** Scales the opacity of what it is applied to by [fraction] */ private fun faded(fraction: Float) = ColorFilter.makeMatrix( ColorMatrix( 1f, 0f, 0f, 0f, 0f, @@ -180,6 +134,3 @@ private fun faded(fraction: Float) = ColorFilter.makeMatrix( 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/component/Text.kt b/src/main/kotlin/com/lambda/gui/component/Text.kt new file mode 100644 index 000000000..b5d50736e --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Text.kt @@ -0,0 +1,77 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.text.BasicText +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shadow +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.LocalContentColor +import com.lambda.gui.theme.Type + +private val LocalTextShadow = compositionLocalOf { null } + +@Composable +fun Text( + text: String, + modifier: Modifier = Modifier, + color: Color = LocalContentColor.current, + style: TextStyle = Type.body, + maxLines: Int = Int.MAX_VALUE, + softWrap: Boolean = true, +) { + if (maxLines == 1) return SlidingText(text, modifier, color, style) + BasicText( + text = text, + modifier = modifier, + style = style.copy(color = color, shadow = style.shadow ?: LocalTextShadow.current), + maxLines = maxLines, + softWrap = softWrap, + overflow = if (maxLines == Int.MAX_VALUE) TextOverflow.Clip else TextOverflow.Ellipsis, + ) +} + +@Composable +fun ContentColor(color: Color, content: @Composable () -> Unit) = + CompositionLocalProvider(LocalContentColor provides color, content = content) + +@Composable +fun SoftTextShadow(content: @Composable () -> Unit) { + val density = LocalDensity.current + val color = LambdaTheme.colors.textShadow + val shadow = remember(density, color) { + with(density) { Shadow(color, Offset(0f, 0.5.dp.toPx()), blurRadius = 1.5.dp.toPx()) } + } + CompositionLocalProvider(LocalTextShadow provides shadow, content = content) +} + +@Composable +fun TextStyle.shadowed(color: Color = LambdaTheme.colors.textShadow): TextStyle { + val offset = with(LocalDensity.current) { 1.dp.toPx() } + return copy(shadow = Shadow(color, Offset(offset, offset))) +} diff --git a/src/main/kotlin/com/lambda/gui/component/TextInput.kt b/src/main/kotlin/com/lambda/gui/component/TextInput.kt new file mode 100644 index 000000000..7aaa8dcab --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/TextInput.kt @@ -0,0 +1,171 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.component + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.dp +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Type + +internal object TextFocus { + private val fields = mutableListOf() + + val isTyping get() = fields.isNotEmpty() + + fun press(position: Offset) = fields.filter { position !in it.bounds }.forEach { it.release() } + + fun add(field: Field) = fields.add(field) + fun remove(field: Field) = fields.remove(field) + + class Field(val release: () -> Unit) { + var bounds = Rect.Zero + } +} + +@Composable +fun TextInput( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + singleLine: Boolean = true, + placeholder: String = "", + style: TextStyle = Type.body, + focused: Boolean = false, + onDone: (() -> Unit)? = null, +) { + val colors = LambdaTheme.colors + var field by remember { mutableStateOf(TextFieldValue(value, TextRange(value.length))) } + var adopted by remember { mutableStateOf(value) } + if (value != adopted) { + adopted = value + if (value != field.text) field = TextFieldValue(value, TextRange(value.length)) + } + + val focus = remember { FocusRequester() } + var hadFocus by remember { mutableStateOf(false) } + var hasFocus by remember { mutableStateOf(false) } + if (focused) LaunchedEffect(Unit) { focus.requestFocus() } + val focusManager = LocalFocusManager.current + val typing = remember(focusManager) { TextFocus.Field { focusManager.clearFocus() } } + if (hasFocus) DisposableEffect(typing) { + TextFocus.add(typing) + onDispose { TextFocus.remove(typing) } + } + + BasicTextField( + value = field, + onValueChange = { + val edited = it.text != field.text + field = it + if (edited) onValueChange(it.text) + }, + enabled = LocalKeyboardReachable.current, + singleLine = singleLine, + textStyle = style.copy(color = colors.onControl), + cursorBrush = SolidColor(colors.onControl), + modifier = modifier + .heightIn(min = Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.input) + .onGloballyPositioned { typing.bounds = it.boundsInWindow() } + .focusRequester(focus) + .onFocusChanged { + hasFocus = it.isFocused + if (it.isFocused) hadFocus = true + else if (hadFocus) onDone?.invoke() + } + .onPreviewKeyEvent { event -> + if (onDone == null || (event.key != Key.Enter && event.key != Key.Escape)) false + else { + if (event.type == KeyEventType.KeyDown) onDone() + true + } + } + .padding(horizontal = 3.dp, vertical = 1.dp), + decorationBox = { innerTextField -> + Box(contentAlignment = Alignment.CenterStart) { + if (field.text.isEmpty()) Text(placeholder, color = colors.onSurfaceVariant, style = style, maxLines = 1) + innerTextField() + } + } + ) +} + +@Composable +fun NumberInput( + value: T, + parse: (String) -> T?, + onCommit: (T) -> Unit, + modifier: Modifier = Modifier, + focused: Boolean = false, + onDone: () -> Unit = {}, +) { + var draft by remember { mutableStateOf(null) } + fun finish(commit: Boolean) { + val typed = draft + draft = null + if (commit && typed != null) parse(typed.trim())?.takeIf { it != value }?.let(onCommit) + onDone() + } + TextInput( + value = draft ?: value.toString(), + onValueChange = { draft = it }, + modifier = modifier.onPreviewKeyEvent { event -> + if (event.key != Key.Escape) false + else { + if (event.type == KeyEventType.KeyDown) finish(commit = false) + true + } + }, + focused = focused, + onDone = { finish(commit = true) }, + ) +} diff --git a/src/main/kotlin/com/lambda/gui/core/Frames.kt b/src/main/kotlin/com/lambda/gui/core/Frames.kt index 6517a4203..dcb2c69f5 100644 --- a/src/main/kotlin/com/lambda/gui/core/Frames.kt +++ b/src/main/kotlin/com/lambda/gui/core/Frames.kt @@ -19,11 +19,6 @@ package com.lambda.gui.core 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 index c66c59806..93a6018f1 100644 --- a/src/main/kotlin/com/lambda/gui/core/GlState.kt +++ b/src/main/kotlin/com/lambda/gui/core/GlState.kt @@ -80,15 +80,7 @@ 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( @@ -115,17 +107,12 @@ internal object GlState { } } - /** - * 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) { diff --git a/src/main/kotlin/com/lambda/gui/core/Observe.kt b/src/main/kotlin/com/lambda/gui/core/Observe.kt index 910393c8e..ebea6223b 100644 --- a/src/main/kotlin/com/lambda/gui/core/Observe.kt +++ b/src/main/kotlin/com/lambda/gui/core/Observe.kt @@ -26,22 +26,6 @@ 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 @@ -54,7 +38,6 @@ fun observe(read: () -> T): State { 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) } @@ -66,16 +49,10 @@ internal class Observation(var read: () -> T) { } } -/** - * 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/RenderThread.kt b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt new file mode 100644 index 000000000..09f9f55c7 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt @@ -0,0 +1,41 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import com.lambda.Lambda.mc +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlin.coroutines.CoroutineContext + +object RenderThread : CoroutineDispatcher() { + private val scope = CoroutineScope(this + SupervisorJob()) + + override fun isDispatchNeeded(context: CoroutineContext) = !mc.isOnThread + + override fun dispatch(context: CoroutineContext, block: Runnable) = mc.send(block) + + @JvmStatic + fun after(millis: Long, block: () -> Unit): Job = scope.launch { + delay(millis) + block() + } +} diff --git a/src/main/kotlin/com/lambda/gui/core/Retained.kt b/src/main/kotlin/com/lambda/gui/core/Retained.kt index 4498d2bab..b51dce578 100644 --- a/src/main/kotlin/com/lambda/gui/core/Retained.kt +++ b/src/main/kotlin/com/lambda/gui/core/Retained.kt @@ -24,21 +24,8 @@ 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) { diff --git a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt index 84446bc37..4da505506 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt @@ -29,8 +29,6 @@ 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 com.lambda.gui.theme.Motion -import kotlinx.coroutines.Dispatchers import net.minecraft.client.texture.GlTexture import org.jetbrains.skia.BackendRenderTarget import org.jetbrains.skia.Color @@ -55,20 +53,13 @@ import org.lwjgl.opengl.GL30.glFramebufferTexture2D import org.lwjgl.opengl.GL30.glGenFramebuffers import org.lwjgl.opengl.GL30.glGenRenderbuffers import org.lwjgl.opengl.GL30.glRenderbufferStorage +import kotlin.coroutines.CoroutineContext -/** - * 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 { +internal class SceneHost(context: CoroutineContext, content: @Composable () -> Unit) : AutoCloseable { val platform = ScenePlatform() - // With the pace of every animation in the scene, which the style sets - private val recomposer = FrameRecomposer(Dispatchers.Unconfined + Motion) + private val recomposer = FrameRecomposer(RenderThread + context) private var invalidated = true private val scene: ComposeScene = CanvasLayersComposeScene( @@ -82,10 +73,8 @@ internal class SceneHost(content: @Composable () -> Unit) : AutoCloseable { 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) @@ -98,37 +87,44 @@ internal class SceneHost(content: @Composable () -> Unit) : AutoCloseable { 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 + val outgrown = target?.takeIf { it.size != size } + val target = target?.takeIf { it.size == size } ?: SkiaTarget(size).also { target = it } 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 + outgrown?.detach() + val surface = target.attach(skia) skia.resetGLAll() beforeScene(skia) - target.surface.canvas.clear(Color.TRANSPARENT) - scene.draw(target.surface.canvas.asComposeCanvas()) - target.surface.flushAndSubmit() + surface.canvas.clear(Color.TRANSPARENT) + scene.draw(surface.canvas.asComposeCanvas()) + surface.flushAndSubmit() } + outgrown?.close() 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() } + + fun closeAndFree() { + runCatching { scene.close() } + runCatching { recomposer.close() } + val freed = target + target = null + GlState.borrow { + freed?.detach() + skia?.close() + } + skia = null + freed?.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 class SkiaTarget(val size: IntSize) : AutoCloseable { private val texture: GpuTexture = RenderSystem.getDevice().createTexture( { "Lambda GUI" }, GpuTexture.USAGE_RENDER_ATTACHMENT or GpuTexture.USAGE_TEXTURE_BINDING, @@ -137,29 +133,39 @@ private class SkiaTarget(skia: DirectContext, val size: IntSize) : AutoCloseable ) val view: GpuTextureView = RenderSystem.getDevice().createTextureView(texture) - private val framebuffer = glGenFramebuffers() - private val stencil = glGenRenderbuffers() - private val renderTarget: BackendRenderTarget - val surface: Surface + private var framebuffer = 0 + private var stencil = 0 + private var renderTarget: BackendRenderTarget? = null + private var surface: Surface? = null - init { + fun attach(skia: DirectContext): Surface = surface ?: run { + framebuffer = glGenFramebuffers() + stencil = glGenRenderbuffers() glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, (texture as GlTexture).glId, 0) glBindRenderbuffer(GL_RENDERBUFFER, stencil) glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, size.width, size.height) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, stencil) - renderTarget = BackendRenderTarget.makeGL(size.width, size.height, 0, 8, framebuffer, FramebufferFormat.GR_GL_RGBA8) - surface = Surface.makeFromBackendRenderTarget( + val renderTarget = BackendRenderTarget.makeGL(size.width, size.height, 0, 8, framebuffer, FramebufferFormat.GR_GL_RGBA8) + .also { renderTarget = it } + Surface.makeFromBackendRenderTarget( skia, renderTarget, SurfaceOrigin.BOTTOM_LEFT, SurfaceColorFormat.RGBA_8888, ColorSpace.sRGB - ) ?: error("Skia rejected the GUI render target") + )?.also { surface = it } ?: error("Skia rejected the GUI render target") + } + + fun detach() { + surface?.close() + surface = null + renderTarget?.close() + renderTarget = null + if (framebuffer != 0) glDeleteFramebuffers(framebuffer) + if (stencil != 0) glDeleteRenderbuffers(stencil) + framebuffer = 0 + stencil = 0 } override fun close() { - 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 index 3b98676e8..a30dc0901 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt @@ -33,10 +33,15 @@ import org.lwjgl.glfw.GLFW import java.awt.Component import java.awt.event.KeyEvent as AwtKeyEvent -/** - * 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. - */ +internal object Press { + var id = 0L + private set + + fun begin() { + id++ + } +} + @OptIn(InternalComposeUiApi::class) internal class SceneInput(private val scene: ComposeScene) { private var position = Offset.Zero @@ -50,23 +55,19 @@ internal class SceneInput(private val scene: ComposeScene) { fun button(button: Int, pressed: Boolean, modifiers: Int) { val mask = 1 shl button pressedButtons = if (pressed) pressedButtons or mask else pressedButtons and mask.inv() - if (pressed) KeyboardFocus.visible = false + if (pressed) { + Press.begin() + KeyboardFocus.visible = false + } 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. - * - * A Tab or an arrow key that nothing in the scene wanted for itself moves the keyboard focus, - * see [KeyboardFocus]. An arrow with nothing lying in its direction steps on in order as Tab - * would, which is also how the focus first gets onto something. - */ fun key(key: Int, pressed: Boolean, modifiers: Int): Boolean { + if (pressed) Press.begin() val shift = modifiers and GLFW.GLFW_MOD_SHIFT != 0 val direction = when (key.takeIf { pressed }) { GLFW.GLFW_KEY_TAB -> if (shift) FocusDirection.Previous else FocusDirection.Next @@ -96,10 +97,6 @@ internal class SceneInput(private val scene: ComposeScene) { return KeyboardFocus.move(direction) || direction != inOrder && KeyboardFocus.move(inOrder) } - /** - * 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( @@ -110,12 +107,8 @@ internal class SceneInput(private val scene: ComposeScene) { ) || 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() @@ -151,10 +144,8 @@ internal class SceneInput(private val scene: ComposeScene) { } 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() {} @@ -168,7 +159,6 @@ internal class SceneInput(private val scene: ComposeScene) { 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 @@ -189,7 +179,7 @@ internal class SceneInput(private val scene: ComposeScene) { 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_A..GLFW.GLFW_KEY_Z, in GLFW.GLFW_KEY_0..GLFW.GLFW_KEY_9 -> this in GLFW.GLFW_KEY_F1..GLFW.GLFW_KEY_F12 -> AwtKeyEvent.VK_F1 + (this - GLFW.GLFW_KEY_F1) else -> AwtKeyEvent.VK_UNDEFINED } diff --git a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt index 52829a1d1..aed222c81 100644 --- a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt +++ b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt @@ -44,10 +44,6 @@ 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 - * 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 { @@ -55,7 +51,6 @@ internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { 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 @@ -75,7 +70,6 @@ internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { } } - // 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") @@ -95,13 +89,8 @@ internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { } } -/** 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 diff --git a/src/main/kotlin/com/lambda/gui/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt index d6b44ab25..1550a6293 100644 --- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -19,43 +19,36 @@ 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.component.Text +import com.lambda.gui.component.shadowed 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 net.minecraft.item.ItemStack +import com.lambda.util.math.toCompose import kotlin.math.roundToInt -/** Settings shared by every HUD element, and by the editor that arranges them */ +private val HUD_TEXT_SHADOW = Color.Black.copy(alpha = 0.75f) +private val ELEMENT_PADDING = 1.dp + object HudConfig : Loadable, Config("HUD", HudCategory) { val showInScreens by setting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The Lambda GUI always shows them.") val textColor by setting("Text Color", java.awt.Color.WHITE, "Colour of HUD text") @@ -65,10 +58,6 @@ object HudConfig : Loadable, Config("HUD", HudCategory) { 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 @@ -77,19 +66,6 @@ internal object Hud { } } -/** 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 } @@ -110,10 +86,6 @@ private fun HudElement(hud: HudModule, editor: HudEditorState?) { 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) @@ -127,43 +99,18 @@ private fun HudElement(hud: HudModule, editor: HudEditorState?) { } } .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) + .padding(ELEMENT_PADDING) ) { 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) }) + Text(text, modifier, color ?: hudColor, Type.body.copy(fontSize = size, lineHeight = size * 1.25f).shadowed(HUD_TEXT_SHADOW)) } diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt index 39d974f02..6de2d6342 100644 --- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -26,14 +26,8 @@ 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 @@ -52,12 +46,10 @@ 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.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 @@ -78,51 +70,36 @@ import com.lambda.config.Config import com.lambda.config.settings.complex.Bind import com.lambda.gui.GuiConfig import com.lambda.gui.LambdaGui +import com.lambda.gui.Reveal import com.lambda.gui.Snap -import com.lambda.gui.clickgui.Reveal -import com.lambda.gui.component.Button +import com.lambda.gui.Snap.snapLines import com.lambda.gui.component.ContextMenu import com.lambda.gui.component.MenuDivider import com.lambda.gui.component.MenuHelp import com.lambda.gui.component.MenuItem import com.lambda.gui.component.MenuLabel -import com.lambda.gui.component.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.settings.ConfigSettings 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.gui.theme.Look 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 - */ +private val PANEL_SCALE = spring(stiffness = Spring.StiffnessMedium) + 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 @@ -135,44 +112,31 @@ internal class HudEditorState(snapping: State) { 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) + if (this.snapping) Snap.snap(element, bounds.filterKeys { it != hud }.values, Rect(Offset.Zero, screen), density) + else Snap.free(element, Rect(Offset.Zero, screen)) } fun shownPosition(hud: HudModule) = drop?.position.takeIf { dragged == hud } } -/** - * 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 } @@ -180,24 +144,17 @@ internal fun HudEditor() { 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) @@ -206,22 +163,13 @@ internal fun HudEditor() { } } } - .drawWithContent { - val guides = editor.drop?.guides.takeIf { showSnapLines } - if (guides != null && editor.snapping) drawGrid() - drawContent() - if (guides != null) drawGuides(guides, snapLineColor) - } + .snapLines { editor.drop } ) { 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) } } + rememberLast(editor.configuring)?.let { config -> key(config) { ElementSettings(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) @@ -239,7 +187,6 @@ private fun ElementMenu(hud: HudModule, editor: HudEditorState) { 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 { @@ -261,7 +208,6 @@ private fun ScreenMenu(position: Offset, editor: HudEditorState) { 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() @@ -274,44 +220,36 @@ private fun ScreenMenu(position: Offset, editor: HudEditorState) { 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) { +private fun ElementSettings(config: Config, open: Boolean, editor: HudEditorState) { val colors = LambdaTheme.colors val density = LocalDensity.current val maxHeight = with(density) { editor.screen.height.toDp() } * 0.6f var size by remember { mutableStateOf(IntSize.Zero) } - // 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), + enter = scaleIn(PANEL_SCALE), + exit = scaleOut(PANEL_SCALE), ) { - Column( - verticalArrangement = Arrangement.spacedBy(4.dp), + ConfigSettings( + config = config, + maxHeight = maxHeight, + onDone = { editor.configure(null) }, modifier = Modifier .onSizeChanged { size = it } - .window(colors.panel, colors.border, RoundedCornerShape(Radius.Panel), floating = true) - // Dragged by any part of it that is not a control: those take their presses first + .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) .pointerInput(Unit) { awaitEachGesture { val down = awaitFirstDown() @@ -325,27 +263,10 @@ private fun SettingsPanel(config: Config, open: Boolean, editor: HudEditorState) } .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 -> @@ -365,7 +286,6 @@ internal fun Modifier.hudEditable(hud: HudModule, editor: HudEditorState): Modif 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 @@ -375,8 +295,7 @@ internal fun Modifier.hudEditable(hud: HudModule, editor: HudEditorState): Modif } } .drawBehind { - // Half of the element's padding, so the outline never touches what it is drawn around - val width = Hairline.toPx() + val width = Look.outlineWidth.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), @@ -385,27 +304,4 @@ internal fun Modifier.hudEditable(hud: HudModule, editor: HudEditorState): Modif ) } -/** 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 index 696c3c3c3..a8abfff4f 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -23,7 +23,6 @@ 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 @@ -43,57 +42,26 @@ 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.Text 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.settings.ConfigSettings 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) - } - } - } + Dialog(onDismiss) { ConfigSettings(config, maxHeight, onDismiss, Modifier.width(240.dp)) } } @Composable @@ -170,7 +138,6 @@ internal fun AboutDialog(onDismiss: () -> Unit) { } } -/** 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 diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index 80562a215..1a514101d 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -72,7 +72,7 @@ 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.CLICK_GUI_CATEGORIES import com.lambda.gui.clickgui.ClickGuiDialog import com.lambda.gui.clickgui.ClickGuiState import com.lambda.gui.component.Menu @@ -82,6 +82,7 @@ import com.lambda.gui.component.MenuLabel import com.lambda.gui.component.MenuState import com.lambda.gui.component.Submenu import com.lambda.gui.component.Suggestions +import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput import com.lambda.gui.component.consumeClicks import com.lambda.gui.component.glass @@ -93,7 +94,6 @@ 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 @@ -112,18 +112,13 @@ import net.minecraft.world.GameMode import java.nio.file.Path import java.util.* -internal val MenuBarHeight = 15.dp +internal val MENU_BAR_HEIGHT = 15.dp +private val ICON_SIZE = 9.dp +private val SEARCH_WIDTH = 150.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 - // The search field is in the middle of the bar for as long as the menus leave the middle - // free. On a bar too short for that, a large scale on a narrow screen, it moves over just - // far enough to clear them. var bar by remember { mutableStateOf(IntSize.Zero) } var menus by remember { mutableStateOf(IntSize.Zero) } var search by remember { mutableStateOf(IntSize.Zero) } @@ -131,9 +126,8 @@ internal fun MenuBar(modifier: Modifier = Modifier) { contentAlignment = Alignment.Center, modifier = modifier .fillMaxWidth() - .height(MenuBarHeight) + .height(MENU_BAR_HEIGHT) .onSizeChanged { bar = it } - // Glass like a window, but running from edge to edge it needs no outline .glass(colors.surface, RectangleShape) .consumeClicks() ) { @@ -152,7 +146,6 @@ internal fun MenuBar(modifier: Modifier = Modifier) { } } -/** An entry of the bar that drops a menu down underneath itself, with the texture at [icon] before its [label] if it has one */ @Composable private fun BarMenu(label: String, icon: String? = null, content: @Composable ColumnScope.() -> Unit) { val menu = remember { MenuState() } @@ -165,30 +158,16 @@ private fun BarMenu(label: String, icon: String? = null, content: @Composable Co .padding(horizontal = 6.dp) ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { - // Drawn far smaller than it is made, which only looks clean when it is filtered well - if (icon != null) Image(rememberTexture(icon), contentDescription = null, Modifier.size(IconSize), filterQuality = FilterQuality.High) + if (icon != null) Image(rememberTexture(icon), contentDescription = null, Modifier.size(ICON_SIZE), filterQuality = FilterQuality.High) Text(label, maxLines = 1) } - // Beside the label and not after it in its row, where the menu, once open, would be - // one more thing for the row to space out and the entry would grow by a gap Menu(menu.isOpen, onDismiss = menu::dismiss, content = content) } } -/** Edge length of the logo in the bar: the height of a capital of the Minecraft font and a little over */ -private val IconSize = 9.dp - -/** - * The search field of the bar. Results drop down under it as the query is typed, and one of - * them is always marked, the first to begin with. The arrow keys, or Tab and Shift with Tab, - * move the mark up and down the list and round its ends, and so does the pointer; Enter takes - * the marked one, a click any, and Escape empties the field. Nothing in it needs a mouse: - * Control with F puts the cursor in the field. - */ @Composable private fun SearchField(modifier: Modifier = Modifier) { val focus = LocalFocusManager.current - // Control with F puts the cursor in the field from anywhere in the click GUI val field = remember { FocusRequester() } val asked = ClickGuiState.focusSearch LaunchedEffect(asked) { @@ -196,13 +175,10 @@ private fun SearchField(modifier: Modifier = Modifier) { ClickGuiState.focusSearch = false } 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()) } val open = listed && query.isNotBlank() - // What was listed stays to be seen while the list folds away val shown = rememberLast(results.takeIf { open }).orEmpty() - // Which result is marked. Every keystroke lists anew, with the best match first and marked. var marked by remember(results) { mutableStateOf(0) } fun choose(result: Search.Result) { @@ -216,17 +192,15 @@ private fun SearchField(modifier: Modifier = Modifier) { modifier.onPreviewKeyEvent { event -> when { event.type != KeyEventType.KeyDown -> false - // 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 } event.key == Key.Enter -> { - results.getOrNull(marked)?.let(::choose) + if (open) results.getOrNull(marked)?.let(::choose) true } - // Without a list to move through, Tab is left to go where it goes anywhere else !open || results.isEmpty() -> false event.key == Key.DirectionDown || event.key == Key.Tab && !event.isShiftPressed -> { marked = (marked + 1).mod(results.size) @@ -246,7 +220,7 @@ private fun SearchField(modifier: Modifier = Modifier) { query = it listed = true }, - modifier = Modifier.width(SearchWidth).focusRequester(field), + modifier = Modifier.width(SEARCH_WIDTH).focusRequester(field), placeholder = "Search modules and settings", ) Suggestions(open, onDismiss = { listed = false }) { @@ -258,12 +232,6 @@ private fun SearchField(modifier: Modifier = Modifier) { } } -/** - * One result of the search. The [marked] one is lit and kept in view, and the light passes from - * one to the next rather than jumping. Moving the pointer over a row marks it, [onPoint]; a - * pointer that merely lies where the list happens to open does not, or it would take the mark - * from the keyboard with every letter typed. - */ @OptIn(ExperimentalFoundationApi::class) @Composable private fun ResultRow(result: Search.Result, marked: Boolean, onPoint: () -> Unit, onClick: () -> Unit) { @@ -278,7 +246,7 @@ private fun ResultRow(result: Search.Result, marked: Boolean, onPoint: () -> Uni verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() - .widthIn(min = SearchWidth) + .widthIn(min = SEARCH_WIDTH) .bringIntoViewRequester(intoView) .background(lit) .pointerInput(Unit) { @@ -297,8 +265,6 @@ private fun ResultRow(result: Search.Result, marked: Boolean, onPoint: () -> Uni } } -private val SearchWidth = 150.dp - @Composable private fun LambdaMenu() { Submenu("Save Config") { @@ -354,17 +320,16 @@ private fun LambdaMenu() { 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 -> + CLICK_GUI_CATEGORIES.forEach { tag -> val shown by observe { ModuleTag.isTagShown(tag) } MenuItem(tag.name, checked = shown) { ModuleTag.toggleTag(tag) } } } MenuDivider() - ClickGuiCategories.forEach { tag -> + CLICK_GUI_CATEGORIES.forEach { tag -> Submenu(tag.name) { ModuleRegistry.modules.filter { it.tag == tag }.forEach { module -> val shown by observe { module.showInClickGui.value } diff --git a/src/main/kotlin/com/lambda/gui/menu/Search.kt b/src/main/kotlin/com/lambda/gui/menu/Search.kt index d570cdf42..8c3f68092 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Search.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt @@ -23,8 +23,8 @@ import com.lambda.command.LambdaCommand import com.lambda.config.Config import com.lambda.config.ConfigLoader import com.lambda.config.entries.Setting +import com.lambda.gui.Reveal import com.lambda.gui.clickgui.ClickGuiState -import com.lambda.gui.clickgui.Reveal import com.lambda.module.HudModule import com.lambda.module.Module import com.lambda.module.ModuleRegistry @@ -32,15 +32,10 @@ import com.lambda.module.ModuleTag 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() @@ -51,11 +46,6 @@ internal object Search { override fun choose() = Reveal.show(module) } - /** - * A setting of [config], under the tabs and groups of [path] from the outermost in. Its - * origin spells all of that out: settings of one name are in many configs, every module - * that builds has an Air Place, and the origin is all that tells them apart in a list. - */ class OfSetting(val setting: Setting<*>, val config: Config, path: List) : Result { override val name get() = setting.name override val origin = (listOf(config.name) + path).joinToString(" \u00bb ") @@ -71,12 +61,10 @@ internal object Search { 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() @@ -92,8 +80,6 @@ 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 -> @@ -114,14 +100,12 @@ internal object Search { } } - /** 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 index df7baf876..652fa9a80 100644 --- a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt +++ b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt @@ -31,17 +31,6 @@ import java.util.* import kotlin.math.ceil import kotlin.math.log2 -/** - * 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 @@ -52,10 +41,8 @@ internal class BlurPyramid(private val name: String) { ) 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)) @@ -115,14 +102,11 @@ internal class BlurPyramid(private val name: String) { } 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 index 453f1ffc1..d84ee8e1f 100644 --- a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt +++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt @@ -29,18 +29,7 @@ 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. - * - * 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, @@ -58,7 +47,6 @@ internal object GuiCompositor { 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( @@ -66,11 +54,6 @@ internal object GuiCompositor { ) } - /** - * 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) @@ -124,6 +107,5 @@ internal object GuiCompositor { 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 index 6385ff783..753ac37c8 100644 --- a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt +++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt @@ -50,41 +50,19 @@ 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: - * 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 @@ -105,11 +83,9 @@ object ItemAtlas { ) } - /** 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) { @@ -120,7 +96,6 @@ object ItemAtlas { 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) @@ -138,7 +113,6 @@ object ItemAtlas { } } - /** 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 @@ -150,8 +124,6 @@ object ItemAtlas { 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) @@ -164,8 +136,6 @@ object ItemAtlas { } 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() @@ -187,17 +157,24 @@ object ItemAtlas { return true } - /** Copies what [render] drew into [image]. Runs while Skia holds the GL context. */ + fun release() { + slots.clear() + image?.close() + image = null + strip?.close() + strip = null + pendingImport = false + renderedModels = emptyList() + } + fun import(skia: DirectContext) { if (!pendingImport) return pendingImport = false val previous = image image = strip?.snapshot(skia) - // 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) @@ -206,7 +183,6 @@ object ItemAtlas { 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 { @@ -215,11 +191,9 @@ object ItemAtlas { } } - /** 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 @@ -233,8 +207,6 @@ object ItemAtlas { 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() } @@ -246,12 +218,9 @@ object ItemAtlas { } } - /** 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 index ba9aed782..922131849 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -51,25 +51,22 @@ import com.lambda.gui.component.Button import com.lambda.gui.component.Chip import com.lambda.gui.component.Dialog import com.lambda.gui.component.Ellipsis -import com.lambda.gui.component.RowHeight +import com.lambda.gui.component.ItemIcon import com.lambda.gui.component.Scrollbar +import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput import com.lambda.gui.component.hoverHighlight import com.lambda.gui.component.mouseClickable import com.lambda.gui.component.wheelScrollable import com.lambda.gui.core.observe -import com.lambda.gui.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.Look 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. - */ +private val ICON_SIZE = 8.dp + @Composable internal fun CollectionButton(setting: CollectionSetting) { val count by observe { setting.value.size } @@ -84,13 +81,8 @@ internal fun CollectionButton(setting: CollectionSetting) { 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)) } @@ -104,7 +96,7 @@ private fun CollectionWindow(setting: CollectionSetting, onDismiss: 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() } + Button("Invert", Modifier.height(Look.rowHeight)) { setting.invertSelection() } } Row(Modifier.height(220.dp), horizontalArrangement = Arrangement.spacedBy(3.dp)) { Pane("Available (${available.size})", available, Modifier.weight(1f)) { setting.select(it) } @@ -114,19 +106,14 @@ private fun CollectionWindow(setting: CollectionSetting, onDismiss: } } -/** - * 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) } - // A block with a long name slides along under the pointer in the room its chip is given Labeled(setting.name) { Chip(onClick = { picking = true }) { - Box(Modifier.size(IconSize)) { ItemIcon(ItemStack(block.asItem()), IconSize) } + Box(Modifier.size(ICON_SIZE)) { ItemIcon(ItemStack(block.asItem()), ICON_SIZE) } Text(BlockSerializer.stringify(block), Modifier.weight(1f, fill = false), maxLines = 1) Ellipsis() } @@ -148,7 +135,6 @@ internal fun BlockPicker(setting: BlockSetting) { } } -/** 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 @@ -156,9 +142,8 @@ private fun Pane(title: String, entries: List>, modifier: Modifier, 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.Control)).background(colors.input)) { + Box(Modifier.fillMaxSize().clip(RoundedCornerShape(Look.controlRounding)).background(colors.input)) { LazyColumn(state = list, modifier = Modifier.fillMaxSize().wheelScrollable(list)) { items(entries) { entry -> Row( @@ -166,13 +151,12 @@ private fun Pane(title: String, entries: List>, modifier: Modifier, horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier .fillMaxWidth() - .heightIn(min = RowHeight) + .heightIn(min = Look.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) } + if (entry.icon != null) Box(Modifier.size(ICON_SIZE)) { ItemIcon(entry.icon, ICON_SIZE) } Text(entry.label, color = colors.onControl, maxLines = 1) } } @@ -181,6 +165,3 @@ private fun Pane(title: String, entries: List>, modifier: Modifier, } } } - -/** 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 index 21c7156e5..56185c190 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt @@ -51,27 +51,24 @@ import com.lambda.config.settings.complex.ColorSetting import com.lambda.gui.component.MenuState import com.lambda.gui.component.NumberInput import com.lambda.gui.component.Popout +import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput import com.lambda.gui.component.mouseClickable import com.lambda.gui.component.scrubbable import com.lambda.gui.core.observe import com.lambda.gui.theme.LambdaTheme -import com.lambda.gui.theme.Radius -import com.lambda.gui.theme.Text +import com.lambda.gui.theme.Look import com.lambda.gui.theme.Type -import com.lambda.gui.theme.toCompose +import com.lambda.util.math.toCompose 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. - * The picker works in hue, saturation and brightness, and offers the channels and a hex code - * to type. - */ +private val PICKER_WIDTH = 130.dp +private val HUES = (0..6).map { Color.hsv(it * 60f % 360f, 1f, 1f) } + @Composable internal fun ColorPicker(setting: ColorSetting) { val color by observe { setting.value } - // 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)) { @@ -79,27 +76,23 @@ internal fun ColorPicker(setting: ColorSetting) { Spacer( Modifier .size(20.dp, 9.dp) - .clip(RoundedCornerShape(Radius.Box)) + .clip(RoundedCornerShape(Look.boxRounding)) .drawBehind { drawCheckerboard() drawRect(color.toCompose()) } ) Popout(picker.isOpen, onDismiss = picker::dismiss) { - Column(Modifier.width(PickerWidth)) { Picker(color) { setting.value = it } } + Column(Modifier.width(PICKER_WIDTH)) { 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) { @@ -116,12 +109,11 @@ private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { } Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { - // Saturation across, brightness up Spacer( Modifier .fillMaxWidth() .aspectRatio(1.4f) - .clip(RoundedCornerShape(Radius.Box)) + .clip(RoundedCornerShape(Look.boxRounding)) .drawBehind { drawRect(Color.hsv(hsb[0] * 360f, 1f, 1f)) drawRect(Brush.horizontalGradient(listOf(Color.White, Color.Transparent))) @@ -158,14 +150,13 @@ private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { } } -/** 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.Box)) + .clip(RoundedCornerShape(Look.boxRounding)) .drawBehind { background() val thumb = Size(4.dp.toPx(), size.height) @@ -182,11 +173,10 @@ private fun Bar(fraction: Float, onChange: (Float) -> Unit, background: DrawScop 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()) + NumberInput(value, { it.toIntOrNull()?.coerceIn(0, 255) }, onChange, Modifier.fillMaxWidth()) } } -/** The grey chequers a translucent colour is shown over */ private fun DrawScope.drawCheckerboard() { val cell = 4.dp.toPx() drawRect(Color(0xFFCCCCCC)) @@ -205,12 +195,9 @@ 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 + if (digits.length != 6 && digits.length != 8 || digits.any { it.digitToIntOrNull(16) == null }) return null val channels = digits.chunked(2).map { it.toIntOrNull(16) ?: return null } return AwtColor(channels[0], channels[1], channels[2], channels.getOrElse(3) { 255 }) } - -private val HUES = (0..6).map { Color.hsv(it * 60f % 360f, 1f, 1f) } diff --git a/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt new file mode 100644 index 000000000..92ae4bab2 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt @@ -0,0 +1,72 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.lambda.config.Config +import com.lambda.config.automation.UserAutomationConfig +import com.lambda.gui.component.Button +import com.lambda.gui.component.ScrollColumn +import com.lambda.gui.component.SoftTextShadow +import com.lambda.gui.component.Text +import com.lambda.gui.theme.Type +import com.lambda.module.Module + +@Composable +internal fun ConfigSettings(config: Config, maxHeight: Dp, onDone: () -> Unit, modifier: Modifier = Modifier) { + Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("${config.name} Settings", Modifier.fillMaxWidth().padding(horizontal = 4.dp), style = Type.title) + if (config is Module) { + var page by remember(config) { mutableStateOf(PanelPage.Settings) } + Column(Modifier.heightIn(max = maxHeight)) { ModuleSettings(config, page, { page = it }, rememberScrollState()) } + } else { + ScrollColumn(Modifier.heightIn(max = maxHeight)) { + SoftTextShadow { + if (config is UserAutomationConfig) SettingRow(config.linkedModules) + SettingsList(config.settingLayers) + } + } + } + Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + if (config is UserAutomationConfig) { + Button("Delete") { + config.delete() + onDone() + } + } + Spacer(Modifier.weight(1f)) + if (config !is Module) Button("Reset") { config.resetSettings() } + Button("Done", onClick = onDone) + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt new file mode 100644 index 000000000..9993cece9 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.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.settings + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.unit.dp +import com.lambda.config.automation.AutomationConfig +import com.lambda.config.automation.UserAutomationConfig +import com.lambda.config.categories.UserAutomationCategory +import com.lambda.config.entries.Setting +import com.lambda.config.hasVisibleSettings +import com.lambda.config.holds +import com.lambda.gui.Reveal +import com.lambda.gui.component.Button +import com.lambda.gui.component.Dropdown +import com.lambda.gui.component.LocalClickOnRelease +import com.lambda.gui.component.ScrollColumn +import com.lambda.gui.component.SoftTextShadow +import com.lambda.gui.component.Text +import com.lambda.gui.component.Tooltip +import com.lambda.gui.component.hoverHighlight +import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.observe +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.module.Module +import com.lambda.module.modules.client.AutoUpdater +import kotlinx.coroutines.launch + +internal enum class PanelPage(val title: String) { + Settings("Settings"), + Module("Module"), + Automation("Automation"), +} + +@Composable +internal fun ColumnScope.ModuleSettings(module: Module, selected: PanelPage, onSelect: (PanelPage) -> Unit, scroll: ScrollState?) { + val pages = pagesOf(module) + val page = selected.takeIf { it in pages } ?: PanelPage.Settings + val revealed = Reveal.setting.takeIf { Reveal.module === module } + LaunchedEffect(revealed) { + if (revealed != null) onSelect(pageOf(module, revealed)) + } + val scope = rememberCoroutineScope() + + SoftTextShadow { + if (pages.size > 1) PageStrip(pages, page) { + onSelect(it) + if (scroll != null) scope.launch { scroll.scrollTo(0) } + } + val turned = @Composable { + AnimatedContent( + targetState = page, + modifier = Modifier.fillMaxWidth(), + transitionSpec = { pageTurn(towardsEnd = targetState > initialState) }, + ) { shown -> + Column(Modifier.fillMaxWidth()) { + when (shown) { + PanelPage.Settings -> SettingsPage(module) + PanelPage.Module -> ModulePage(module) + PanelPage.Automation -> AutomationPage(module) + } + } + } + } + if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } else turned() + } +} + +private fun pagesOf(module: Module): List = when { + module == AutoUpdater -> listOf(PanelPage.Settings) + module.automationConfig === AutomationConfig.DEFAULT -> listOf(PanelPage.Settings, PanelPage.Module) + else -> PanelPage.entries +} + +private fun pageOf(module: Module, setting: Setting<*>): PanelPage = when { + module.automationConfig !== AutomationConfig.DEFAULT && module.automationConfig.settingLayers.holds(setting) -> PanelPage.Automation + setting in moduleSettings(module) -> PanelPage.Module + else -> PanelPage.Settings +} + +private fun moduleSettings(module: Module): List> = listOfNotNull( + module.keybindSetting.takeUnless { module.alwaysEnabled }, + module.prioritySetting, + module.disableOnReleaseSetting.takeUnless { module.alwaysEnabled }, + module.drawSetting.takeUnless { module.alwaysEnabled }, +) + +@Composable +private fun PageStrip(pages: List, selected: PanelPage, onSelect: (PanelPage) -> Unit) { + val colors = LambdaTheme.colors + Row(Modifier.fillMaxWidth().padding(bottom = 2.dp)) { + pages.forEach { page -> + val isSelected = page == selected + val line by animateColorAsState(if (isSelected) colors.secondary else colors.raised) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .weight(page.title.length + 2f) + .height(Look.rowHeight + 1.dp) + .hoverHighlight(colors.raised) + .mouseClickable { onSelect(page) } + .drawBehind { + val thickness = 1.dp.toPx() + drawRect(line, Offset(0f, size.height - thickness), Size(size.width, thickness)) + } + .padding(horizontal = 4.dp) + ) { + Text(page.title, color = if (isSelected) colors.onSurface else colors.onSurfaceVariant, maxLines = 1, softWrap = false) + } + } + } +} + +@Composable +private fun SettingsPage(module: Module) { + val any by observe { module.settingLayers.hasVisibleSettings() } + if (any) SettingsList(module.settingLayers) + else Box(Modifier.fillMaxWidth().padding(vertical = 4.dp), contentAlignment = Alignment.Center) { + Text("No settings", color = LambdaTheme.colors.onSurfaceVariant) + } +} + +@Composable +private fun AutomationPage(module: Module) { + val linked by observe { module.backingAutomationConfig } + CompositionLocalProvider(LocalClickOnRelease provides true) { AutomationConfigSelector(module, linked) } + key(linked) { SettingsList(module.automationConfig.settingLayers) } +} + +@Composable +private fun ModulePage(module: Module) { + moduleSettings(module).forEach { SettingRow(it) } + Tooltip("Resets all settings for this module to their default values", Modifier.fillMaxWidth()) { + CompositionLocalProvider(LocalClickOnRelease provides true) { + Button("Reset", Modifier.settingCell().height(Look.rowHeight)) { module.resetSettings() } + } + } +} + +@Composable +private fun AutomationConfigSelector(module: Module, linked: AutomationConfig) { + val options by observe { + listOf(module.defaultAutomationConfig) + UserAutomationCategory.configs.filterIsInstance() + } + Dropdown( + label = "Linked Config", + options = options, + selected = linked, + optionLabel = { it.name }, + modifier = Modifier.settingCell().padding(start = ROW_INSET), + ) { selected -> + (module.backingAutomationConfig as? UserAutomationConfig)?.linkedModules?.value?.remove(module.name) + (selected as? UserAutomationConfig)?.linkedModules?.value?.add(module.name) + module.automationConfig = selected + } +} diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 2790ce160..4362b95d8 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -31,6 +31,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.composed @@ -42,7 +43,7 @@ import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import com.lambda.config.entries.Setting -import com.lambda.gui.clickgui.Reveal +import com.lambda.gui.Reveal import com.lambda.gui.component.LabeledRow import com.lambda.gui.component.LocalClickOnRelease import com.lambda.gui.component.LocalKeyboardReachable @@ -52,29 +53,17 @@ import com.lambda.gui.core.awaitFrames import com.lambda.gui.core.observe import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look -import com.lambda.gui.theme.Radius -/** - * The row of one setting in a list, whatever its type: the description as its tooltip, the - * light the search puts on it, and the dimming of one that is disabled. What the row holds is - * the setting's own, see [Setting.compose]. 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. - */ +private const val SETTLE_MILLIS = 250L +internal val TEXT_FIELD_WIDTH = 90.dp +internal val NUMBER_FIELD_WIDTH = 34.dp +internal val ROW_INSET = 3.dp + @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() } @@ -90,38 +79,26 @@ fun SettingRow(setting: Setting<*>) { 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. - // One that is disabled is out of the keyboard's reach as it is out of the pointer's. CompositionLocalProvider(LocalClickOnRelease provides true, LocalKeyboardReachable provides !disabled) { - setting.compose() + key(setting) { setting.Editor() } } } } } -/** - * 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() - // Half above and half below, so the first and the last keep their distance from the edges too .padding(vertical = Look.settingSpacing / 2) - .clip(RoundedCornerShape(Radius.Control)) + .clip(RoundedCornerShape(Look.controlRounding)) .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) { @@ -130,13 +107,6 @@ private fun Modifier.enabled(enabled: Boolean): Modifier = } } -/** 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) = - LabeledRow(name, modifier.padding(start = 3.dp), editor) - -/** Width of the field a line of text is typed into, beside its name */ -internal val TextFieldWidth = 90.dp - -/** Width of each field of a position; longer numbers scroll inside it */ -internal val NumberFieldWidth = 34.dp + LabeledRow(name, modifier.padding(start = ROW_INSET), editor) diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt index 62ac4b9f1..977993f06 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -52,29 +52,25 @@ 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.config.hasVisibleSettings +import com.lambda.config.holds +import com.lambda.gui.Reveal import com.lambda.gui.component.Chevron +import com.lambda.gui.component.ContentColor import com.lambda.gui.component.Expandable import com.lambda.gui.component.Menu import com.lambda.gui.component.MenuItem import com.lambda.gui.component.MenuState -import com.lambda.gui.component.RowHeight import com.lambda.gui.component.Section +import com.lambda.gui.component.Text import com.lambda.gui.component.hoverHighlight import com.lambda.gui.component.mouseClickable import com.lambda.gui.core.observe -import com.lambda.gui.theme.ContentColor import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look import com.lambda.gui.theme.Motion -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 band that picks 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) { @@ -93,7 +89,6 @@ fun SettingsList(layer: EntryLayer>) { 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) } @@ -105,24 +100,12 @@ fun SettingsList(layer: EntryLayer>) { @Composable private fun Children(layer: EntryLayer.Multiple>) = layer.layers.forEach { SettingsList(it) } -/** - * The pages a config sorts its settings into, and over them a band that says which one is shown - * and lists the others when clicked. - * - * What it picks decides everything under it, as a category does its modules, so the band is the - * header of a category over again: as wide as the panel, filled in its colour and rounded at the - * top alone, where the choice of a setting is a chip at the end of its row. It is one row however many pages there are, and no wider than its settings. - * Changing pages slides the new one in from the side it is on in the list, while the panel - * grows or shrinks to fit it. - */ @Composable private fun Tabs(tabs: List>>) { val shown by observe { tabs.filter { it.hasVisibleSettings() } } if (shown.isEmpty()) return var selectedName by remember { mutableStateOf(shown.first().name) } - // 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 } @@ -140,13 +123,11 @@ private fun Tabs(tabs: List>>) { } } -/** The band over a config's pages: the [selected] one of [names], and a menu of them all under it */ @Composable private fun TabPicker(names: List, selected: String, onSelect: (String) -> Unit) { val colors = LambdaTheme.colors val menu = remember { MenuState() } var band by remember { mutableStateOf(IntSize.Zero) } - // The only page left, the others having nothing to show, is a heading rather than a choice of one val choice = names.size > 1 Box(Modifier.fillMaxWidth().onSizeChanged { band = it }) { @@ -156,9 +137,8 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) horizontalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier .fillMaxWidth() - .heightIn(min = RowHeight + 2.dp) - // Square underneath, where its page hangs off it as the modules do off their category - .clip(RoundedCornerShape(topStart = Radius.Window, topEnd = Radius.Window)) + .heightIn(min = Look.rowHeight + 2.dp) + .clip(RoundedCornerShape(topStart = Look.windowRounding, topEnd = Look.windowRounding)) .background(colors.header) .then( if (!choice) Modifier @@ -170,7 +150,6 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) if (choice) Chevron(90f) } } - // Drops out from under the band, as wide as it and square where the two meet Menu(menu.isOpen, onDismiss = menu::dismiss, unfoldFrom = IntSize(band.width, 0), attached = true) { names.forEach { name -> MenuItem(name, selected = name == selected) { @@ -181,12 +160,6 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) } } - -/** - * 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 millis = Motion.pageMillis val slide = tween(millis) @@ -194,20 +167,3 @@ internal fun AnimatedContentTransitionScope<*>.pageTurn(towardsEnd: Boolean): Co .togetherWith(fadeOut(tween(millis / 2)) + slideOutHorizontally(slide) { if (towardsEnd) -it / 5 else it / 5 }) .using(SizeTransform(clip = true) { _, _ -> tween(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/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index 34ee9c160..7c00e2fed 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -22,60 +22,48 @@ import androidx.compose.animation.core.Spring import androidx.compose.animation.core.VisibilityThreshold import androidx.compose.animation.core.snap import androidx.compose.animation.core.spring -import androidx.compose.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 +import androidx.compose.runtime.State 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.Modifier import androidx.compose.ui.MotionDurationScale -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.rememberTextMeasurer import androidx.compose.ui.text.style.LineHeightStyle -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import com.lambda.gui.component.SlidingText +import com.lambda.gui.core.Observation +import com.lambda.gui.core.Observations import com.lambda.gui.core.observe import com.lambda.module.modules.client.Style import com.lambda.util.NamedEnum import com.lambda.util.stream -/** - * 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. - */ +private const val LINE_HEIGHT = 10.95f + +private val ON_LIGHT_ACCENT = Color(0xFF1B1024) + @Immutable data class Palette( - /** Accent, for what is on or filled: sliders, checked boxes, the bar of an open group */ val primary: Color, - /** Second accent, a hue apart, for what is chosen among options: an entry of a menu, the page of a panel */ 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, @@ -83,162 +71,73 @@ data class Palette( 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], the tick of a box among it: dark on all but a deep accent. Dark - * is the quieter of the two and reads on a rose of middling lightness as well as on a pale one. - */ - val onPrimary: Color = if (primary.luminance() > 0.2f) Color(0xFF1B1024) else Color.White - - /** Text drawn on [secondary], by the same rule */ - val onSecondary: Color = if (secondary.luminance() > 0.2f) Color(0xFF1B1024) else Color.White + val onPrimary = primary.contrast() + val onSecondary = secondary.contrast() + val trackFilled = if (onControl.luminance() > 0.5f) primary else primary.copy(alpha = 0.6f) + val raised = onSurface.copy(alpha = 0.11f) + val hover = onSurface.copy(alpha = 0.06f) - /** - * The filled part of a slider: the accent of a ticked box as it is under the light text of a - * dark theme, and thinned under the dark text of a light one, which could not be read on it. - */ - val trackFilled: Color = if (onControl.luminance() > 0.5f) primary else primary.copy(alpha = 0.6f) - - /** 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) + private fun Color.contrast() = if (luminance() > 0.2f) ON_LIGHT_ACCENT else Color.White } -/** - * What the [Style] module sets about the shape and the spacing of things, kept as state. A - * radius or a gap is asked for wherever a shape is built, a line drawn or a row padded, in a - * composable or out of one, and whatever asked follows the setting the moment it is changed. - * - * It is brought up to the settings once a frame with [refresh], before anything is composed. - * Setting a state to what it already is costs a comparison and wakes nothing. - */ internal object Look { - var windowRounding by mutableStateOf(3.dp) - private set - var panelRounding by mutableStateOf(5.dp) - private set - var menuRounding by mutableStateOf(3.dp) - private set - var controlRounding by mutableStateOf(2.dp) - private set - var outline by mutableStateOf(0.5.dp) - private set - var shadows by mutableStateOf(true) - private set - var windowWidth by mutableStateOf(90.dp) - private set - var windowGap by mutableStateOf(2.dp) - private set - var windowTop by mutableStateOf(94.dp) - private set - var modulePadding by mutableStateOf(4.dp) - private set - var panelPadding by mutableStateOf(4.dp) - private set - var settingSpacing by mutableStateOf(1.dp) - private set - var groupIndent by mutableStateOf(5.dp) - private set - - fun refresh() { - windowRounding = Style.windowRounding.dp - panelRounding = Style.panelRounding.dp - menuRounding = Style.menuRounding.dp - controlRounding = Style.controlRounding.dp - outline = Style.outlineWidth.dp - shadows = Style.shadows - windowWidth = Style.windowWidth.dp - windowGap = Style.windowGap.dp - windowTop = Style.windowTop.dp - modulePadding = Style.modulePadding.dp - panelPadding = Style.panelPadding.dp - settingSpacing = Style.settingSpacing.dp - groupIndent = Style.groupIndent.dp - } + private val observations = Observations() + + val windowRounding by style { Style.windowRounding.dp } + val panelRounding by style { Style.panelRounding.dp } + val menuRounding by style { Style.menuRounding.dp } + val controlRounding by style { Style.controlRounding.dp } + val boxRounding get() = controlRounding / 2 + + val outlines by style { Style.outlines } + val outlineWidth by style { Style.outlineWidth.dp } + val shadows by style { Style.shadows } + val emboss by style { Style.emboss } + val backdropBlur by style { if (Style.blur) (Style.blurRadius / 2f).dp else 0.dp } + val underlay by style { 1f - Style.layerFade } + + val rowHeight by style { Style.elementHeight.dp } + val windowWidth by style { Style.windowWidth.dp } + val settingsWidth by style { Style.settingsWidth.dp } + val windowGap by style { Style.windowGap.dp } + val windowTop by style { Style.windowTop.dp } + val modulePadding by style { Style.modulePadding.dp } + val panelPadding by style { Style.panelPadding.dp } + val settingSpacing by style { Style.settingSpacing.dp } + val groupIndent by style { Style.groupIndent.dp } + + fun refresh() = observations.refresh() + + private fun style(read: () -> T): State = Observation(read).also { observations.active += it }.state } -/** - * How thick outlines are: one pixel at 1080p unless the style asks for more, and never less - * than one anywhere. Outlines are there to finish an edge, not to be looked at. - */ -val Hairline: Dp get() = Look.outline - -/** Corner radii, by what kind of thing has the corner. Each kind is rounded as the style asks for it. */ -object Radius { - /** Category windows, and the band of tabs that is made like their headers */ - val Window get() = Look.windowRounding - - /** The panels that pop out of a window, and dialogs */ - val Panel get() = Look.panelRounding - - /** Menus, dropdowns, search results and tooltips */ - val Menu get() = Look.menuRounding - - /** Controls and the blocks settings are grouped in */ - val Control get() = Look.controlRounding - - /** Checkboxes, colour swatches, the small parts inside a control */ - val Box get() = Look.controlRounding / 2 -} - -/** - * How fast the interface animates, for every animation in it at once: Compose asks this of the - * scene before it starts one. The durations they are written with are divided by the speed the - * style asks for, and with animations off they are over the moment they begin. - * - * A kind of animation the style switches off by itself is not scaled but replaced where it is - * asked for, by [windows], [panels] or [pageMillis]: an unfolding that snaps, a page that turns - * in no time. - */ internal object Motion : MotionDurationScale { - override val scaleFactor get() = if (Style.animations) 1f / Style.animationSpeed else 0f - - /** How a category window unfolds out of its header */ - val windows: FiniteAnimationSpec get() = if (Style.windowAnimations) spring() else snap() - - /** - * How a panel, a menu or anything else that floats unfolds out of what opened it: on a - * spring quick enough to keep up with fast clicking. Nothing waits for it, a press is acted - * on at once. - */ - val panels: FiniteAnimationSpec - get() = if (Style.panelAnimations) Unfolding else snap() + private const val PAGE_MILLIS = 160 + private val UNFOLDING = spring(stiffness = Spring.StiffnessMedium, visibilityThreshold = IntSize.VisibilityThreshold) - private val Unfolding = spring(stiffness = Spring.StiffnessMedium, visibilityThreshold = IntSize.VisibilityThreshold) - - /** How long one page of settings takes to give way to another */ - val pageMillis get() = if (Style.pageAnimations) 160 else 0 - - /** For the glide of a list after the wheel, which is the style's to have with or without the rest */ - val Scroll = object : MotionDurationScale { + val SCROLL = object : MotionDurationScale { override val scaleFactor get() = if (Style.smoothScrolling) 1f else 0f } - /** For what moves in order to be read rather than to look well, which keeps its own pace */ - val Unscaled = object : MotionDurationScale { + val UNSCALED = object : MotionDurationScale { override val scaleFactor get() = 1f } + + override val scaleFactor get() = if (Style.animations) 1f / Style.animationSpeed else 0f + + val windows: FiniteAnimationSpec get() = if (Style.windowAnimations) spring() else snap() + val panels: FiniteAnimationSpec get() = if (Style.panelAnimations) UNFOLDING else snap() + val pageMillis get() = if (Style.pageAnimations) PAGE_MILLIS else 0 } -/** - * 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), @@ -255,27 +154,21 @@ 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, 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 * scale) private fun compact(font: GuiFont, size: TextUnit, weight: FontWeight = FontWeight.Normal) = TextStyle( fontFamily = font.family, fontWeight = weight, fontSize = size, - // Only between the lines of text that wraps: the first and the last keep to the type. - // A pixel font fills its grid, an outline font needs air or its lines touch. lineHeight = if (font == GuiFont.Minecraft) size else size * 1.25f, 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 @@ -290,114 +183,24 @@ object LambdaTheme { 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 } - -/** - * 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 } - -/** How tall rows and controls are at least, see [com.lambda.gui.component.RowHeight] */ -val LocalRowHeight = staticCompositionLocalOf { 12.dp } - -/** 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 } - // 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 } - // 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() - // On top of that comes the size the player asks for, which rows that hold text grow to fit. val fontSize by observe { Style.fontSize } + val measurer = rememberTextMeasurer() val typography = remember(font, fontSize) { if (font == GuiFont.Minecraft) return@remember Typography(font, fontSize) val line = measurer.measure("Ag", Typography(font).body, density = Density(1f)).size.height Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f) * fontSize) } - val underlay by observe { 1f - Style.layerFade } - val rowHeight by observe { Style.elementHeight.dp } CompositionLocalProvider( LocalPalette provides palette, 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, - LocalBackdropBlur provides backdropBlur, - LocalOutlines provides outlines, - LocalUnderlay provides underlay, - LocalRowHeight provides rowHeight, 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, -) { - // 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, - 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 f05ac8671..60f2e9945 100644 --- a/src/main/kotlin/com/lambda/module/HudModule.kt +++ b/src/main/kotlin/com/lambda/module/HudModule.kt @@ -31,25 +31,15 @@ abstract class HudModule( ) : 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 4d0762f6c..2f73164a5 100644 --- a/src/main/kotlin/com/lambda/module/Module.kt +++ b/src/main/kotlin/com/lambda/module/Module.kt @@ -126,10 +126,6 @@ abstract class Module( modulePriority: Int = 0, defaultKeybind: Bind = Bind.EMPTY, 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() 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 4bd4ed871..fa5737dc8 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt @@ -42,7 +42,6 @@ object AutoUpdater : Module( private var loaderPromptHandled by property(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 @@ -61,13 +60,10 @@ object AutoUpdater : Module( } init { - // 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 } } } - /** Called when the click GUI opens, the first of which decides whether to offer the loader */ fun onGuiOpened() { if (firstLaunchStateInitialized) return firstLaunchStateInitialized = true 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 b41a1c81e..aefccbca3 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -23,10 +23,10 @@ import com.lambda.config.Group import com.lambda.config.settings.appliedOnRelease 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 com.lambda.util.math.toCompose import org.jetbrains.skiko.SystemTheme import org.jetbrains.skiko.currentSystemTheme import java.awt.Color @@ -37,11 +37,12 @@ object Style : Module( tag = ModuleTag.CLIENT, alwaysEnabled = true, ) { - private const val DARK_THEME_GROUP = "Dark Theme" - private const val LIGHT_THEME_GROUP = "Light Theme" + private const val BACKDROP_GROUP = "Backdrop" private const val SHAPE_GROUP = "Shape" + private const val LAYOUT_GROUP = "Layout" private const val MOTION_GROUP = "Motion" - private const val SPACING_GROUP = "Spacing" + 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"), @@ -51,60 +52,51 @@ object Style : Module( 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") - var scale by setting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() - var fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") - var elementHeight by setting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") - 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 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 emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") - - var inlineSettings by setting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") - var multipleSettings by setting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") - - var glow by setting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") - 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 } - - @Group(SHAPE_GROUP) var windowRounding by setting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") - @Group(SHAPE_GROUP) var panelRounding by setting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") + val fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") + val scale by setting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() + + @Group(BACKDROP_GROUP) val dimBackground by setting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") + @Group(BACKDROP_GROUP) val dimStrength by setting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } + @Group(BACKDROP_GROUP) val blur by setting("Blur", true, "Blurs what is behind windows for a frosted glass look") + @Group(BACKDROP_GROUP) val blurRadius by setting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } + @Group(BACKDROP_GROUP) val layerFade by setting("Layer Fade", 0.5f, 0f..1f, 0.05f, "How far the interface fades out underneath a panel, menu or window opened over it, letting the game show there instead so the two do not run together") { blur } + @Group(BACKDROP_GROUP) val glow by setting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") + @Group(BACKDROP_GROUP) val glowRadius by setting("Glow Radius", 17f, 1f..100f, 1f) { glow } + @Group(BACKDROP_GROUP) val glowIntensity by setting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } + + @Group(SHAPE_GROUP) val windowRounding by setting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") + @Group(SHAPE_GROUP) val panelRounding by setting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") @Group(SHAPE_GROUP) val menuRounding by setting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") @Group(SHAPE_GROUP) val controlRounding by setting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") - @Group(SHAPE_GROUP) var outlineWidth by setting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } + @Group(SHAPE_GROUP) val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") + @Group(SHAPE_GROUP) val outlineWidth by setting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } @Group(SHAPE_GROUP) val shadows by setting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") - @Group(SHAPE_GROUP) var windowWidth by setting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") - @Group(SHAPE_GROUP) val settingsWidth by setting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") - - @Group(SPACING_GROUP) var windowGap by setting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") - @Group(SPACING_GROUP) var windowTop by setting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") - @Group(SPACING_GROUP) var modulePadding by setting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") - @Group(SPACING_GROUP) var panelPadding by setting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") - @Group(SPACING_GROUP) var settingSpacing by setting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") - @Group(SPACING_GROUP) var groupIndent by setting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") - - @Group(MOTION_GROUP) var animations by setting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") + @Group(SHAPE_GROUP) val emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") + + @Group(LAYOUT_GROUP) val elementHeight by setting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") + @Group(LAYOUT_GROUP) val windowWidth by setting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") + @Group(LAYOUT_GROUP) val settingsWidth by setting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") + @Group(LAYOUT_GROUP) val windowGap by setting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") + @Group(LAYOUT_GROUP) val windowTop by setting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") + @Group(LAYOUT_GROUP) val modulePadding by setting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") + @Group(LAYOUT_GROUP) val panelPadding by setting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") + @Group(LAYOUT_GROUP) val settingSpacing by setting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") + @Group(LAYOUT_GROUP) val groupIndent by setting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") + @Group(LAYOUT_GROUP) val inlineSettings by setting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") + @Group(LAYOUT_GROUP) val multipleSettings by setting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") + + @Group(MOTION_GROUP) val animations by setting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") @Group(MOTION_GROUP) val animationSpeed by setting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } @Group(MOTION_GROUP) val windowAnimations by setting("Window Animations", true, "Category windows unfold out of their headers") { animations } - @Group(MOTION_GROUP) var panelAnimations by setting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } + @Group(MOTION_GROUP) val panelAnimations by setting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } @Group(MOTION_GROUP) val pageAnimations by setting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } @Group(MOTION_GROUP) val smoothScrolling by setting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") @Group(MOTION_GROUP) val scrollSpeed by setting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") @Group(MOTION_GROUP) val tooltipDelay by setting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") - /** The colours the glow runs between, which are the theme's: what suits dark glass is lost around light */ - val glowColorA: Color get() = theme.glowA - val glowColorB: Color get() = theme.glowB - @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( PaletteSettings( this, - // A shade lighter than the header and a shade less full, so it is plain to see without being loud: a panel is - // read by its band of tabs, and what is set in it is not to be taken for a module that is on primary = Color(214, 77, 113), secondary = Color(255, 141, 128), surface = Color(69, 48, 55, 165), @@ -114,60 +106,41 @@ object Style : Module( onSurfaceVariant = Color(184, 156, 166), header = Color(222, 53, 101), onHeader = Color(255, 246, 248), - // A shade of the header, as strong and a good step darker: greyed and left as light it turns to a dusty pink moduleEnabled = Color(161, 42, 75), onModuleEnabled = Color(255, 240, 244), - // Every control is the one rose: a chip, a button and a key cap are filled as a slider - // and a ticked box are, so that whatever can be set looks like one kind of thing control = Color(214, 77, 113), - controlMenu = Color(55, 38, 45), controlSelected = Color(92, 64, 75), onControl = Color(246, 236, 239), - // Wells cut into the panel, darker than any glass they sit on so they never blend into it track = Color(38, 28, 32, 230), input = Color(32, 23, 26, 230), border = Color(128, 92, 104, 235), textShadow = Color(0, 0, 0, 150), - // From the rose of the headers to the salmon, the two ends of the theme's range glowA = Color(222, 53, 101), glowB = Color(255, 141, 128), ) ) - // The dark theme turned over: the same rose, salmon and rose-tinted backing at the same hues, - // with the tiers running the other way, darker for what is deeper. Light glass has to be - // nearly solid, as dark text over whatever the game shows through it cannot be read, and it - // takes no text shadow, which only smears dark text. @Group(LIGHT_THEME_GROUP) private val lightTheme by configBlock( PaletteSettings( this, - // The rose of the headers: it fills a slider thinned, under the dark text over it primary = Color(222, 53, 101), - // The salmon, deepened until it reads as text on a light panel secondary = Color(209, 74, 59), surface = Color(250, 236, 241, 228), panel = Color(244, 226, 232, 240), inset = Color(120, 0, 40, 68), onSurface = Color(61, 40, 47), onSurfaceVariant = Color(110, 86, 95), - // The same as on dark glass, so a window is known by the one colour in either theme header = Color(222, 53, 101), onHeader = Color(255, 250, 251), - // A step under the header, which on light glass is a step lighter, with its text in white: - // a tint of pink under dark text was too faint to pick the enabled out of a list at a glance moduleEnabled = Color(232, 84, 126), onModuleEnabled = Color(255, 250, 251), - // The same rose paler again, so what is set in a panel is not taken for a module that is on control = Color(240, 139, 166), - controlMenu = Color(244, 226, 232), controlSelected = Color(224, 197, 206), onControl = Color(61, 40, 47), - // Wells cut into the panel: a track is darker than it, a text field is paper track = Color(209, 192, 199, 220), input = Color(255, 250, 252, 210), border = Color(184, 154, 164, 238), textShadow = Color(0, 0, 0, 0), - // The two ends of the theme's range, as in the dark theme: both are light enough to glow around light glass glowA = Color(222, 53, 101), glowB = Color(255, 141, 128), ) @@ -181,8 +154,9 @@ object Style : Module( } val palette: Palette get() = theme.toPalette() + val glowColorA: Color get() = theme.glowA + val glowColorB: Color get() = theme.glowB - /** Asking the operating system is not free, so the answer is reused for a moment */ private object SystemAppearance { private const val REFRESH_MILLIS = 1000L @@ -215,7 +189,6 @@ class PaletteSettings( moduleEnabled: Color, onModuleEnabled: Color, control: Color, - controlMenu: Color, controlSelected: Color, onControl: Color, track: Color, @@ -225,7 +198,7 @@ class PaletteSettings( glowA: Color, glowB: Color, ) : ConfigBlock { - private val primary by c.setting("Primary", primary, "Accent colour: the fill of sliders, ticked boxes, what is chosen") + private val primary by c.setting("Primary", primary, "Accent colour: the fill of sliders and ticked boxes") private val secondary by c.setting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") private val surface by c.setting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") private val panel by c.setting("Panel", panel, "Fill of settings panels, menus and dialogs") @@ -236,8 +209,7 @@ class PaletteSettings( 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 control by c.setting("Control", control, "Fill of dropdowns, buttons and key caps") private val controlSelected by c.setting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") private val onControl by c.setting("On Control", onControl) private val track by c.setting("Slider Track", track) @@ -260,7 +232,6 @@ class PaletteSettings( moduleEnabled = moduleEnabled.toCompose(), onModuleEnabled = onModuleEnabled.toCompose(), control = control.toCompose(), - controlMenu = controlMenu.toCompose(), controlSelected = controlSelected.toCompose(), onControl = onControl.toCompose(), track = track.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 1e3c4c127..99269f7e3 100644 --- a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt +++ b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt @@ -25,10 +25,10 @@ import com.lambda.event.events.PlayerEvent import com.lambda.event.events.TickEvent import com.lambda.event.events.WorldEvent import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.GuiConfig import com.lambda.interaction.handler.handlers.FriendHandler import com.lambda.module.Module import com.lambda.module.ModuleTag +import com.lambda.module.modules.client.Style import com.lambda.module.modules.network.AutoReconnect import com.lambda.sound.SoundHandler.playSound import com.lambda.util.CommunicationUtils @@ -44,6 +44,7 @@ import com.lambda.util.extension.fullHealth import com.lambda.util.extension.tickDeltaF import com.lambda.util.item.ItemStackUtils.bundleStacks import com.lambda.util.item.ItemStackUtils.shulkerBoxStacks +import com.lambda.util.math.toAwt import com.lambda.util.player.MovementUtils.moveDelta import com.lambda.util.player.PlayerUtils.isIn2b2tQueue import com.lambda.util.player.SlotUtils.allStacks @@ -654,7 +655,7 @@ object AutoDisconnect : Module( buildText { text(effect.effectType.value().name) if (effect.amplifier > 0) literal(" ${effect.amplifier + 1}") - color(GuiConfig.textDisabled) { literal(" (${effectDuration(effect)})") } + color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (${effectDuration(effect)})") } } ) } @@ -741,7 +742,7 @@ object AutoDisconnect : Module( val customName = stack.get(DataComponentTypes.CUSTOM_NAME) if (customName != null) { text(stack.itemName) - color(GuiConfig.textDisabled) { + color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (") text(customName) literal(")") @@ -751,11 +752,11 @@ object AutoDisconnect : Module( } if (stack.isDamageable) { - color(GuiConfig.textDisabled) { literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") } + color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") } } if (stack.maxCount > 1) { - color(GuiConfig.textDisabled) { literal(" (${stack.count})") } + color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.count})") } } if (selected) { diff --git a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt index 4b6d6ca43..e9196fbff 100644 --- a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt +++ b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt @@ -17,7 +17,8 @@ package com.lambda.module.modules.combat.autodisconnect -import com.lambda.gui.GuiConfig +import androidx.compose.ui.graphics.toArgb +import com.lambda.module.modules.client.Style import com.lambda.util.text.buildText import com.lambda.util.text.highlighted import com.lambda.util.text.text @@ -267,13 +268,10 @@ class DisconnectDetailsWidget( const val HOVER_PADDING = 2 const val HOVER_RADIUS = 1 - // Pulled live from the click GUI theme so the panel matches the user's colors. - val COLOR_TEXT get() = 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() = GuiConfig.text.rgb//composite(COLOR_TEXT, COLOR_HOVER_BACKGROUND) + val COLOR_TEXT get() = Style.palette.onSurface.toArgb() + val COLOR_BACKGROUND get() = Style.palette.panel.toArgb() + val COLOR_BORDER get() = Style.palette.border.toArgb() + val COLOR_HOVER_BACKGROUND get() = Style.palette.controlSelected.toArgb() + val COLOR_HEADER get() = COLOR_TEXT } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt index 0b32ec44a..287269c1b 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt @@ -23,10 +23,10 @@ import androidx.compose.foundation.layout.Row import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.unit.dp +import com.lambda.gui.component.ItemIcon import com.lambda.gui.core.observe import com.lambda.gui.core.observeSafe import com.lambda.gui.hud.HudText -import com.lambda.gui.hud.ItemIcon import com.lambda.module.HudModule import com.lambda.module.ModuleTag import com.lambda.util.NamedEnum @@ -50,7 +50,6 @@ object Armor : HudModule( @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 } @@ -60,7 +59,6 @@ object Armor : HudModule( 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) } } 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 5c521d6ed..9118257ab 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt @@ -62,7 +62,7 @@ object Coordinates : HudModule( 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. + val otherDimensionPos = if (world.isNether) player.overworldCoord.let { Vec2d(it.x, it.z) }.format(formatter.locale, formatter.separator, "[", "]", formatter.precision) else player.netherCoord.let { Vec2d(it.x, it.z) }.format(formatter.locale, formatter.separator, "[", "]", formatter.precision) 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 3c97ac908..8b55e11d4 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt @@ -43,10 +43,8 @@ object ModuleList : HudModule( @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 } 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 417510ac7..1544ebd0b 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt @@ -33,12 +33,12 @@ 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 import com.lambda.util.ServerTPSUtils import com.lambda.util.ServerTPSUtils.recentData +import com.lambda.util.math.toCompose @Suppress("unused") object Tps : HudModule( @@ -75,7 +75,6 @@ object Tps : HudModule( } } - /** 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 } 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 ee48d37d4..6f7600180 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt @@ -40,7 +40,6 @@ object Watermark : HudModule( 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 cefa3e41e..c23a860d0 100644 --- a/src/main/kotlin/com/lambda/module/modules/movement/BackTrack.kt +++ b/src/main/kotlin/com/lambda/module/modules/movement/BackTrack.kt @@ -25,7 +25,6 @@ import com.lambda.event.events.TickEvent import com.lambda.event.listener.SafeListener.Companion.listen import com.lambda.graphics.mc.renderer.ImmediateRenderer.Companion.immediateRenderer import com.lambda.graphics.util.DynamicAABB -import com.lambda.gui.GuiConfig import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.module.modules.combat.KillAura @@ -60,6 +59,8 @@ object BackTrack : Module( description = "Gives reach advantage by delaying your packets", tag = ModuleTag.MOVEMENT, ) { + private val BOX_COLOR = Color(130, 200, 255) + private val outbound by setting("Outbound", true) private val mode by setting("Mode", Mode.Fixed) private val delay by setting("Delay", 500, 100..2000) { mode == Mode.Fixed } @@ -172,7 +173,7 @@ object BackTrack : Module( immediateRenderer("BackTrack Immediate Renderer") { val target = target ?: return@immediateRenderer - val c1 = GuiConfig.primaryColor + val c1 = BOX_COLOR val c2 = Color.RED val p = target.hurtTime / 10.0 val c = lerp(p, c1, c2) diff --git a/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt b/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt index c14c669f2..4b2d12a48 100644 --- a/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt +++ b/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt @@ -24,7 +24,6 @@ import com.lambda.event.listener.SafeListener.Companion.listen import com.lambda.graphics.mc.renderer.ImmediateRenderer.Companion.immediateRenderer import com.lambda.graphics.mc.renderer.TickedRenderer.Companion.tickedRenderer import com.lambda.graphics.util.DynamicAABB -import com.lambda.gui.GuiConfig import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.module.modules.combat.KillAura @@ -40,6 +39,7 @@ import net.minecraft.network.packet.s2c.play.EntityVelocityUpdateS2CPacket import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Box import net.minecraft.util.math.Vec3d +import java.awt.Color import java.util.concurrent.ConcurrentLinkedDeque object Blink : Module( @@ -47,6 +47,8 @@ object Blink : Module( description = "Holds packets", tag = ModuleTag.MOVEMENT, ) { + private val BOX_COLOR = Color(130, 200, 255) + private var delay by setting("Delay", 500, 50..10000, 10) private val shiftVelocity by setting("Shift velocity", true) private val requiresAura by setting("Requires Aura", false) @@ -71,7 +73,7 @@ object Blink : Module( } immediateRenderer("Blink Immediate Renderer") { - val color = GuiConfig.primaryColor + val color = BOX_COLOR box(box.update(lastBox).box(mc.tickDelta) ?: return@immediateRenderer) { colors(color.setAlpha(0.3), color) } diff --git a/src/main/kotlin/com/lambda/module/modules/player/Replay.kt b/src/main/kotlin/com/lambda/module/modules/player/Replay.kt index b614c817c..27137b50d 100644 --- a/src/main/kotlin/com/lambda/module/modules/player/Replay.kt +++ b/src/main/kotlin/com/lambda/module/modules/player/Replay.kt @@ -32,7 +32,6 @@ import com.lambda.event.EventFlow.lambdaScope import com.lambda.event.events.MovementEvent import com.lambda.event.events.TickEvent import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.gui.GuiConfig import com.lambda.interaction.handler.handlers.TimerHandler import com.lambda.interaction.manager.managers.rotating.Rotation import com.lambda.interaction.manager.managers.rotating.RotationMode @@ -67,6 +66,7 @@ import net.minecraft.client.input.Input import net.minecraft.sound.SoundEvents import net.minecraft.util.PlayerInput import net.minecraft.util.math.Vec3d +import java.awt.Color import java.io.File import java.lang.reflect.Type import java.time.format.DateTimeFormatter @@ -87,6 +87,9 @@ object Replay : Module( tag = ModuleTag.PLAYER, autoDisable = true ) { + private val HIGHLIGHT_COLOR = Color(130, 200, 255) + private val ACTION_COLOR = Color(225, 130, 225) + private val record by setting("Record", KeyCode.R) .onPress { handleRecord() } private val play by setting("Play / Stop", KeyCode.C) @@ -197,11 +200,11 @@ object Replay : Module( val index = recordings.indexOf(saving) this@Replay.info(buildText { literal("Auto saved #") - color(GuiConfig.primaryColor) { literal("$index") } + color(HIGHLIGHT_COLOR) { literal("$index") } literal(" of ") - color(GuiConfig.primaryColor) { literal(saving.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(saving.duration.toString()) } literal(" at ") - color(GuiConfig.primaryColor) { literal(saving.endPos.format(precision = 1)) } + color(HIGHLIGHT_COLOR) { literal(saving.endPos.format(precision = 1)) } playMessage(saving) saveMessage(saving) pruneMessage(saving) @@ -219,9 +222,9 @@ object Replay : Module( buffer = playback?.duplicate() this@Replay.info(buildText { if (repeats > 0) { - color(GuiConfig.primaryColor) { literal("[$repeats / $loops]") } + color(HIGHLIGHT_COLOR) { literal("[$repeats / $loops]") } } else { - color(GuiConfig.primaryColor) { literal("[$repeats/∞]") } + color(HIGHLIGHT_COLOR) { literal("[$repeats/∞]") } } literal(" Replay looped.") }) @@ -232,7 +235,7 @@ object Replay : Module( state = State.Inactive this@Replay.info(buildText { literal("Replay finished after ") - color(GuiConfig.primaryColor) { literal(playback?.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(playback?.duration.toString()) } literal(".") }) return@listen @@ -257,9 +260,9 @@ object Replay : Module( info(buildText { literal("Recording #${recordings.indexOf(deserialized)} ") - color(GuiConfig.primaryColor) { literal(file.nameWithoutExtension) } + color(HIGHLIGHT_COLOR) { literal(file.nameWithoutExtension) } literal(" loaded. Duration: ") - color(GuiConfig.primaryColor) { literal(deserialized.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(deserialized.duration.toString()) } playMessage(deserialized) pruneMessage(deserialized) }) @@ -288,9 +291,9 @@ object Replay : Module( playback = recording info(buildText { literal("Replaying recording #") - color(GuiConfig.primaryColor) { literal(index.toString()) } + color(HIGHLIGHT_COLOR) { literal(index.toString()) } literal(" of ") - color(GuiConfig.primaryColor) { literal(recording.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(recording.duration.toString()) } }) return CommandResult.success() } @@ -304,13 +307,13 @@ object Replay : Module( recordings.add(pruned) info(buildText { literal("Shortened recording #") - color(GuiConfig.primaryColor) { literal(recordings.indexOf(toShorten).toString()) } + color(HIGHLIGHT_COLOR) { literal(recordings.indexOf(toShorten).toString()) } literal(" of ") - color(GuiConfig.primaryColor) { literal(toShorten.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(toShorten.duration.toString()) } literal(" to new recording #") - color(GuiConfig.primaryColor) { literal(recordings.indexOf(pruned).toString()) } + color(HIGHLIGHT_COLOR) { literal(recordings.indexOf(pruned).toString()) } literal(" of ") - color(GuiConfig.primaryColor) { literal(pruned.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(pruned.duration.toString()) } playMessage(pruned) saveMessage(pruned) }) @@ -326,7 +329,7 @@ object Replay : Module( buffer = it.duplicate() info(buildText { literal("Replaying most recent recording #${recordings.indexOf(it)}. Duration: ") - color(GuiConfig.primaryColor) { literal(it.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(it.duration.toString()) } }) } ?: run { this@Replay.warn("No recording to replay.") @@ -370,9 +373,9 @@ object Replay : Module( recordings.add(rec) this@Replay.info(buildText { literal("Stopped recording #") - color(GuiConfig.primaryColor) { literal("${recordings.indexOf(rec)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(rec)}") } literal(" of ") - color(GuiConfig.primaryColor) { literal(rec.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(rec.duration.toString()) } literal(".") playMessage(rec) saveMessage(rec) @@ -387,9 +390,9 @@ object Replay : Module( recordings.add(checkRec) this@Replay.info(buildText { literal("Checkpoint #") - color(GuiConfig.primaryColor) { literal("${recordings.indexOf(checkRec)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(checkRec)}") } literal(" created at ") - color(GuiConfig.primaryColor) { literal(checkRec.endPos.format(precision = 0)) } + color(HIGHLIGHT_COLOR) { literal(checkRec.endPos.format(precision = 0)) } literal(".") playMessage(checkRec) saveMessage(checkRec) @@ -408,9 +411,9 @@ object Replay : Module( playMode = PlayMode.entries[(playMode.ordinal + 1) % PlayMode.entries.size] info(buildText { literal("Set play mode to ") - color(GuiConfig.primaryColor) { literal(playMode.name) } + color(HIGHLIGHT_COLOR) { literal(playMode.name) } literal(" (previously ") - color(GuiConfig.primaryColor) { literal(oldMode.name) } + color(HIGHLIGHT_COLOR) { literal(oldMode.name) } literal(")") }) } @@ -430,30 +433,30 @@ object Replay : Module( this@Replay.info(buildText { literal("Saved recording #") - color(GuiConfig.primaryColor) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(" of ") - color(GuiConfig.primaryColor) { literal(recording.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(recording.duration.toString()) } literal(" in file ") - color(GuiConfig.primaryColor) { literal(name) } + color(HIGHLIGHT_COLOR) { literal(name) } val filePath = file.toPath().pathString hoverEvent(HoverEvents.showText(buildText { literal("Open file ") - color(GuiConfig.primaryColor) { literal(filePath) } + color(HIGHLIGHT_COLOR) { literal(filePath) } })) { clickEvent(ClickEvents.openFile(filePath)) { literal(" [") - color(GuiConfig.secondaryColor) { literal("OPEN FILE") } + color(ACTION_COLOR) { literal("OPEN FILE") } literal("]") } } val parentPath = file.parentFile.toPath().pathString hoverEvent(HoverEvents.showText(buildText { literal("Open folder ") - color(GuiConfig.primaryColor) { literal(parentPath) } + color(HIGHLIGHT_COLOR) { literal(parentPath) } })) { clickEvent(ClickEvents.openFile(parentPath)) { literal(" [") - color(GuiConfig.secondaryColor) { literal("OPEN FOLDER") } + color(ACTION_COLOR) { literal("OPEN FOLDER") } literal("]") } } @@ -464,12 +467,12 @@ object Replay : Module( private fun TextBuilder.playMessage(recording: Recording) { hoverEvent(HoverEvents.showText(buildText { literal("Click to replay recording #") - color(GuiConfig.primaryColor) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(".") })) { clickEvent(ClickEvents.suggestCommand(";replay play ${recordings.indexOf(recording)}")) { literal(" [") - color(GuiConfig.secondaryColor) { + color(ACTION_COLOR) { literal("PLAY") } literal("]") @@ -482,17 +485,17 @@ object Replay : Module( hoverEvent(HoverEvents.showText(buildText { literal(" Recording can be shortened by ") - color(GuiConfig.primaryColor) { + color(HIGHLIGHT_COLOR) { literal(recording.pruneTimesave.toString()) } literal(" by removing idles and cyclic paths.") })) { clickEvent(ClickEvents.suggestCommand(";replay prune ${recordings.indexOf(recording)}")) { literal(" [") - color(GuiConfig.secondaryColor) { + color(ACTION_COLOR) { literal("PRUNE ") } - color(GuiConfig.primaryColor) { + color(HIGHLIGHT_COLOR) { literal("${recording.pruneTimesave}") } literal("]") @@ -503,12 +506,12 @@ object Replay : Module( private fun TextBuilder.saveMessage(recording: Recording) { hoverEvent(HoverEvents.showText(buildText { literal("Click to save recording #") - color(GuiConfig.primaryColor) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(".") })) { clickEvent(ClickEvents.suggestCommand(";replay save ${recordings.indexOf(recording)} ${getTime(fileFormatter).sanitizeForFilename()}")) { literal(" [") - color(GuiConfig.secondaryColor) { literal("SAVE") } + color(ACTION_COLOR) { literal("SAVE") } literal("]") } } @@ -528,7 +531,7 @@ object Replay : Module( } this@Replay.info(buildText { literal("Postprocessing finished. Shortened recording by ") - color(GuiConfig.primaryColor) { literal((duration - pruned.duration).toString()) } + color(HIGHLIGHT_COLOR) { literal((duration - pruned.duration).toString()) } literal(".") }) return pruned diff --git a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt index 188cf2b90..b7b312d6f 100644 --- a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt +++ b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt @@ -24,12 +24,13 @@ import com.lambda.command.LambdaCommand import com.lambda.config.ConfigLoader import com.lambda.core.Loader import com.lambda.event.EventFlow -import com.lambda.gui.GuiConfig import com.lambda.module.Module import com.lambda.module.ModuleRegistry +import com.lambda.module.modules.client.Style import com.lambda.threading.runSafe import com.lambda.threading.runSafeGameScheduled import com.lambda.util.StringUtils.capitalize +import com.lambda.util.math.toAwt import com.lambda.util.text.HoverEvents import com.lambda.util.text.TextBuilder import com.lambda.util.text.buildText @@ -152,7 +153,7 @@ object CommunicationUtils { if (command.usage.isNotBlank()) { literal("\n") literal("Usage: ") - color(GuiConfig.primaryColor) { + color(Style.palette.primary.toAwt()) { literal(command.usage) } } @@ -160,7 +161,7 @@ object CommunicationUtils { literal("\n") literal("Aliases: ") joinToText(command.aliases) { - color(GuiConfig.primaryColor) { + color(Style.palette.primary.toAwt()) { literal(it) } } @@ -179,7 +180,7 @@ object CommunicationUtils { literal("\n") } literal("Keybind: ") - color(GuiConfig.primaryColor) { + color(Style.palette.primary.toAwt()) { if (module.keybind.key != 0 || module.keybind.mouse > -1) { literal(module.keybind.name) } else { diff --git a/src/main/kotlin/com/lambda/util/InputUtils.kt b/src/main/kotlin/com/lambda/util/InputUtils.kt index 24446de97..e51fef76c 100644 --- a/src/main/kotlin/com/lambda/util/InputUtils.kt +++ b/src/main/kotlin/com/lambda/util/InputUtils.kt @@ -32,7 +32,6 @@ object InputUtils { fun SafeContext.isKeyPressed(vararg keys: Int) = keys.any { glfwGetKey(mc.window.handle, it) >= GLFW_PRESS } - /** Whether everything the bind is made of is held down right now. Never true for an unbound one. */ fun Bind.isSatisfied(): Boolean = (isKeyBind || isMouseBind) && (!isKeyBind || InputUtil.isKeyPressed(mc.window, key)) && diff --git a/src/main/kotlin/com/lambda/util/math/Color.kt b/src/main/kotlin/com/lambda/util/math/Color.kt index 6c1eebdf5..8abe724f4 100644 --- a/src/main/kotlin/com/lambda/util/math/Color.kt +++ b/src/main/kotlin/com/lambda/util/math/Color.kt @@ -17,6 +17,7 @@ package com.lambda.util.math +import androidx.compose.ui.graphics.toArgb import net.minecraft.util.math.Vec3d import java.awt.Color @@ -35,3 +36,7 @@ val Color.b get() = blue / 255.0 val Color.a get() = alpha / 255.0 val Color.vec3d get() = Vec3d(r, g, b) + +fun Color.toCompose() = androidx.compose.ui.graphics.Color(red, green, blue, alpha) + +fun androidx.compose.ui.graphics.Color.toAwt() = Color(toArgb(), true) diff --git a/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh b/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh index 14700c833..0bc8370d2 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh @@ -1,8 +1,5 @@ #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 { 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 index 8e31793d2..a6034ef27 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh @@ -1,8 +1,5 @@ #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 { diff --git a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh index 2386c9206..e01bb5291 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh @@ -1,12 +1,8 @@ #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 +uniform sampler2D GuiSampler; +uniform sampler2D BackdropSampler; +uniform sampler2D HaloSampler; layout(std140) uniform GuiEffects { vec4 GlowColorA; @@ -23,14 +19,12 @@ 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); From 9ca44863076f731ba772348d5c8540cec9e86748 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:53:01 +0000 Subject: [PATCH 13/34] GuiTest --- src/gametest/kotlin/com/lambda/GuiTest.kt | 972 ++++++++++++++++++++++ src/gametest/resources/fabric.mod.json | 4 + 2 files changed, 976 insertions(+) create mode 100644 src/gametest/kotlin/com/lambda/GuiTest.kt diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt new file mode 100644 index 000000000..88666a979 --- /dev/null +++ b/src/gametest/kotlin/com/lambda/GuiTest.kt @@ -0,0 +1,972 @@ +/* + * 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 + +import com.lambda.config.entries.Setting +import com.lambda.context.Automated +import com.lambda.gui.GuiConfig +import com.lambda.gui.GuiScreen +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.render.Bobbing +import com.lambda.module.modules.hud.Armor +import com.lambda.module.modules.hud.Coordinates +import com.lambda.module.modules.hud.Fps +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 net.minecraft.client.input.KeyInput +import org.lwjgl.glfw.GLFW +import kotlin.math.abs + +@Suppress("UnstableApiUsage") +object GuiTest : FabricClientGameTest { + private const val WIDTH = 1920 + private const val HEIGHT = 1080 + + private const val DENSITY = HEIGHT / 540.0 + + override fun runTest(context: ClientGameTestContext) { + context.input.resizeWindow(WIDTH, HEIGHT) + context.waitTicks(5) + + context.openClickGui() + context.takeScreenshot("gui-0-loader-prompt") + context.runOnClient { AutoUpdater.answerPrompt(accepted = false) } + context.waitTicks(10) + context.takeScreenshot("gui-1-title-screen") + + context.runOnClient { + Style.set("fontSize", 1f) + Style.set("elementHeight", 13f) + } + context.waitTicks(5) + + val enabledBefore = context.enabledModules() + 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 = 150.0, dpY = 115.0) + + val enabledBeforePress = context.enabledModules() + 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 = 150.0, dpY = 115.0) + + context.input.setCursorPos(240.0 * DENSITY, 193.0 * DENSITY) + context.waitTicks(30) + context.takeScreenshot("gui-1a-long-name-hovered") + context.input.setCursorPos(240.0 * DENSITY, 60.0 * DENSITY) + context.waitTicks(10) + context.takeScreenshot("gui-1b-long-name-left") + + context.input.setCursorPos(620.0 * DENSITY, 101.0 * DENSITY) + context.dragBy(3.5, 7.5) + val free = context.windowPlacement("Network") + check(abs(free.x - 576.5f) < 0.6f && abs(free.y - 101.5f) < 0.6f) { "A dragged window did not follow the pointer: $free" } + + context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) + context.waitTicks(2) + context.dragBy(2.0, 2.0) + context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) + val snapped = context.windowPlacement("Network") + check(snapped.inRow) { "A window dragged with the snap key held did not snap back between its neighbours: $snapped" } + + context.runOnClient { GuiConfig.set("showSnapLines", true) } + context.input.setCursorPos(620.0 * DENSITY, 100.0 * DENSITY) + context.waitTicks(2) + context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) + context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(5) { + context.input.moveCursor(3.0 * DENSITY, 30.0 * DENSITY) + context.waitTick() + } + context.waitTicks(3) + context.takeScreenshot("gui-1b1-window-snap-lines") + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) + context.waitTicks(2) + val aligned = context.windowPlacement("Network") + check(abs(aligned.x - 573f) < 0.6f) { "A window dragged down beside its place in the row did not stay in line with it: $aligned" } + context.runOnClient { + GuiConfig.set("showSnapLines", false) + GuiConfig.resetWindows() + } + context.waitTicks(5) + + context.input.setCursorPos(620.0 * DENSITY, 100.0 * DENSITY) + context.waitTicks(2) + context.dragBy(0.0, -95.0) + val raised = context.windowPlacement("Network") + context.takeScreenshot("gui-1c-window-dragged-to-the-top") + check(abs(raised.y - 15f) < 0.6f) { "A window dragged to the top of the screen did not stop under the menu bar: $raised" } + + context.runOnClient { GuiConfig.resetWindows() } + context.waitTicks(2) + check(context.computeOnClient { GuiConfig.windows.isEmpty() }) { "Resetting the layout left a window placed" } + + context.click(dpX = 150.0, dpY = 115.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.takeScreenshot("gui-2-module-settings") + + 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") + context.waitTicks(10) + + context.click(dpX = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + + context.click(dpX = 298.5, dpY = 198.0) + context.takeScreenshot("gui-2c2-module-page") + context.input.setCursorPos(340.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(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 = 261.0, dpY = 247.0) + context.click(dpX = 236.5, dpY = 198.0) + + 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(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") + + context.input.setCursorPos(320.0 * DENSITY, 273.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.takeScreenshot("gui-2g0-dropdown-unfolding") + context.waitTicks(10) + context.takeScreenshot("gui-2g-dropdown") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(1) + context.takeScreenshot("gui-2g1-dropdown-folding") + context.waitTicks(2) + context.takeScreenshot("gui-2g2-dropdown-folded-in") + context.waitTicks(3) + + context.click(dpX = 296.0, dpY = 216.0) + context.takeScreenshot("gui-2d0-tab-list") + context.input.setCursorPos(296.0 * DENSITY, 245.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.takeScreenshot("gui-2d-tab-changing") + context.waitTicks(10) + context.takeScreenshot("gui-2e-tab-changed") + + context.input.setCursorPos(360.0 * DENSITY, 260.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.takeScreenshot("gui-2h0-collection-unfolding") + context.waitTicks(10) + context.takeScreenshot("gui-2h-collection") + context.input.typeChars("stone") + context.waitTicks(5) + context.takeScreenshot("gui-2h2-collection-searched") + + context.setClipboard("") + context.pressKey(GLFW.GLFW_KEY_A, GLFW.GLFW_MOD_CONTROL) + context.pressKey(GLFW.GLFW_KEY_C, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(3) + check(context.clipboard() == "stone") { "Copying from a text field in a dialog left the clipboard as '${context.clipboard()}'" } + context.setClipboard("glass") + context.pressKey(GLFW.GLFW_KEY_A, GLFW.GLFW_MOD_CONTROL) + context.pressKey(GLFW.GLFW_KEY_V, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(3) + context.setClipboard("") + context.pressKey(GLFW.GLFW_KEY_A, GLFW.GLFW_MOD_CONTROL) + context.pressKey(GLFW.GLFW_KEY_C, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(3) + check(context.clipboard() == "glass") { "Pasting into a text field in a dialog gave '${context.clipboard()}'" } + context.takeScreenshot("gui-2h4-collection-pasted") + + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(1) + context.takeScreenshot("gui-2h1-collection-folding") + context.waitTicks(2) + context.takeScreenshot("gui-2h3-collection-folded-in") + context.waitTicks(3) + + context.click(dpX = 340.0, dpY = 198.0) + for (y in listOf(289.0, 275.0, 261.0, 247.0)) context.click(dpX = 261.0, dpY = y) + context.takeScreenshot("gui-2i-scrolling") + + context.input.setCursorPos(290.0 * DENSITY, 400.0 * DENSITY) + context.waitTicks(2) + context.input.scroll(-2.0) + context.waitTicks(1) + context.takeScreenshot("gui-2i1-wheel-gliding") + context.waitTicks(15) + context.takeScreenshot("gui-2i2-wheel-settled") + context.input.scroll(10.0) + context.waitTicks(15) + context.input.setCursorPos(317.0 * DENSITY, 189.0 * DENSITY) + context.waitTicks(2) + context.dragBy(0.0, -60.0) + context.takeScreenshot("gui-2j-extended") + + context.dragBy(0.0, -300.0) + context.takeScreenshot("gui-2k-extended-to-the-bar") + + context.click(dpX = 150.0, dpY = 101.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.takeScreenshot("gui-2f-category-folded") + context.click(dpX = 150.0, dpY = 101.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") + + context.click(dpX = 20.0, dpY = 7.0) + context.takeScreenshot("gui-3-menu") + + context.click(dpX = 30.0, dpY = 39.0) + context.click(dpX = 190.0, dpY = 7.0) + context.takeScreenshot("gui-3b-menu-to-menu") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + + context.click(dpX = 20.0, dpY = 7.0) + context.click(dpX = 30.0, dpY = 39.0) + context.waitTicks(10) + context.takeScreenshot("gui-3c-submenu") + context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.takeScreenshot("gui-3d-submenu-swallowed") + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.takeScreenshot("gui-3e-submenu-swallowed") + context.waitTicks(10) + + context.click(dpX = 20.0, dpY = 7.0) + context.closeGui() + context.openClickGui() + context.takeScreenshot("gui-3a-reopened") + + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("scaff") + context.waitTicks(10) + context.takeScreenshot("gui-4-search") + + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(8) + context.takeScreenshot("gui-4a-search-module") + context.waitTicks(40) + + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("auto") + context.waitTicks(1) + context.takeScreenshot("gui-4a1-search-unfolding") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.waitTicks(5) + context.takeScreenshot("gui-4a2-search-third-marked") + context.input.pressKey(GLFW.GLFW_KEY_UP) + context.waitTicks(5) + context.takeScreenshot("gui-4a3-search-second-marked") + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(8) + context.takeScreenshot("gui-4a4-search-marked-chosen") + context.waitTicks(40) + + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("targeting range") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(15) + context.takeScreenshot("gui-4b-search-setting") + + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("surround") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(15) + context.click(dpX = 150.0, dpY = 219.5, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.takeScreenshot("gui-4c-block-settings") + context.click(dpX = 350.0, dpY = 242.0) + context.takeScreenshot("gui-4d-block-list") + + context.input.setCursorPos(400.0 * DENSITY, 346.0 * DENSITY) + context.waitTicks(2) + context.input.scroll(-5.0) + context.waitTicks(15) + context.takeScreenshot("gui-4e-block-list-scrolled") + + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + context.takeScreenshot("gui-4f-block-list-shut") + + context.click(dpX = 480.0, dpY = 7.0) + context.input.typeChars("pavement material") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(15) + context.takeScreenshot("gui-4g-block-setting") + context.closeGui() + + val singleplayer = context.worldBuilder() + .adjustSettings { it.gameMode = WorldCreator.Mode.CREATIVE } + .create() + singleplayer.clientWorld.waitForChunksDownload() + singleplayer.server.runCommand("/item replace entity @p armor.head with minecraft:stone 32") + singleplayer.server.runCommand("/item replace entity @p armor.chest with minecraft:netherite_chestplate[minecraft:damage=500]") + singleplayer.server.runCommand("/item replace entity @p armor.legs with minecraft:diamond_leggings[minecraft:enchantments={protection:4}]") + singleplayer.server.runCommand("/item replace entity @p armor.feet with minecraft:golden_boots[minecraft:damage=40]") + + context.runOnClient { + Armor.enable() + Coordinates.enable() + Fps.enable() + } + context.waitTicks(20) + context.takeScreenshot("gui-5-hud-in-game") + + context.input.pressKey(GLFW.GLFW_KEY_Y) + context.waitTicks(2) + context.takeScreenshot("gui-6-0-click-gui-opening") + context.waitTicks(18) + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "The keybind did not open the click GUI" } + context.takeScreenshot("gui-6-click-gui-in-game") + + context.input.setCursorPos(300.0 * DENSITY, 400.0 * DENSITY) + context.waitTicks(2) + context.input.setCursorPos(150.0 * DENSITY, 115.0 * DENSITY) + context.waitTicks(40) + context.takeScreenshot("gui-6a-tooltip") + context.input.pressKey(GLFW.GLFW_KEY_Y) + context.waitTicks(10) + context.takeScreenshot("gui-6b-closed-with-tooltip-up") + context.input.pressKey(GLFW.GLFW_KEY_Y) + context.waitTicks(10) + context.takeScreenshot("gui-6c-reopened") + + context.click(dpX = 480.0, dpY = 7.0) + context.input.pressKey(GLFW.GLFW_KEY_Y) + context.waitTicks(5) + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "Typing the keybind into a text field closed the GUI" } + check(context.computeOnClient { LambdaGui.isCapturingKeys }) { "A focused text field did not hold on to the keys" } + context.input.pressKey(GLFW.GLFW_KEY_BACKSPACE) + context.waitTicks(2) + + context.click(dpX = 924.0, dpY = 528.0) + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.HudEditor }) { "The HUD Editor button did not open the editor" } + check(context.computeOnClient { !LambdaGui.isCapturingKeys }) { "Keys stayed captured after the focused text field went away" } + context.input.setCursorPos(20.0 * DENSITY, 44.0 * DENSITY) + context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(10) { + context.input.moveCursor(30.0 * DENSITY, 15.0 * DENSITY) + context.waitTick() + } + context.takeScreenshot("gui-7-hud-editor-dragging") + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(2) + + context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) + context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(10) { + context.input.moveCursor(-29.0 * DENSITY, 2.0 * DENSITY) + context.waitTick() + } + context.takeScreenshot("gui-7a-hud-editor-snapping") + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) + context.waitTicks(2) + + context.click(dpX = 700.0, dpY = 400.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.takeScreenshot("gui-8-hud-editor-menu") + + context.input.setCursorPos(500.0 * DENSITY, 300.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.waitTicks(1) + context.takeScreenshot("gui-8a-hud-editor-menu-reopening") + context.waitTicks(10) + context.takeScreenshot("gui-8b-hud-editor-menu-reopened") + + context.input.setCursorPos(513.0 * DENSITY, 427.5 * DENSITY) + context.waitTicks(20) + context.takeScreenshot("gui-8c-hud-editor-help") + context.click(dpX = 150.0, dpY = 108.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.takeScreenshot("gui-9-hud-element-menu") + context.input.setCursorPos(175.0 * DENSITY, 129.0 * DENSITY) + context.waitTicks(2) + context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(3) + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(10) + context.takeScreenshot("gui-9a-hud-element-settings") + + context.click(dpX = 342.0, dpY = 151.0) + context.takeScreenshot("gui-9b-hud-element-colour") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + context.click(dpX = 312.0, dpY = 224.5) + context.takeScreenshot("gui-9c-hud-element-options") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + + context.click(dpX = 311.0, dpY = 135.0) + context.waitTicks(10) + context.takeScreenshot("gui-9c1-hud-element-module-page") + context.click(dpX = 200.0, dpY = 135.0) + context.waitTicks(10) + + context.input.setCursorPos(170.0 * DENSITY, 284.0 * DENSITY) + context.waitTicks(2) + context.dragBy(150.0, 60.0) + context.takeScreenshot("gui-9d-hud-settings-dragged") + + context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.takeScreenshot("gui-9e-hud-settings-closing") + context.waitTicks(10) + context.takeScreenshot("gui-9f-hud-settings-closed") + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.HudEditor }) { "Closing the settings panel left the HUD editor" } + + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "Escape did not return from the HUD editor to the click GUI" } + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + check(context.computeOnClient { LambdaGui.screen == null }) { "Escape did not close the click GUI" } + + context.openClickGui() + context.click(dpX = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.waitTicks(10) + 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) + context.waitTicks(2) + context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(1) + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.takeScreenshot("gui-10b-menu-folding-in-panel") + context.waitTicks(1) + context.takeScreenshot("gui-10c-menu-folding-in-panel") + context.waitTicks(15) + context.takeScreenshot("gui-10d-panel-closed") + + context.runOnClient { GuiConfig.set("keepSettingsOpen", true) } + 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) } + context.waitTicks(2) + context.takeScreenshot("gui-11a-kept-settings-categories-unfolding") + context.waitTicks(4) + context.takeScreenshot("gui-11b-kept-settings-unfolding") + context.waitTicks(15) + context.takeScreenshot("gui-11c-kept-settings-open") + context.runOnClient { GuiConfig.set("keepSettingsOpen", false) } + context.closeGui() + + context.openClickGui() + context.click(dpX = 520.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.waitTicks(10) + context.takeScreenshot("gui-11d-settings-of-many-tabs") + context.click(dpX = 728.0, dpY = 185.0) + context.waitTicks(10) + context.click(dpX = 650.0, dpY = 216.0) + context.takeScreenshot("gui-11e-many-tabs-listed") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + context.closeGui() + + context.runOnClient { + Style.set("inlineSettings", true) + GuiConfig.resetWindows() + } + context.openClickGui() + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) + context.waitTicks(3) + context.takeScreenshot("gui-11g-inline-settings-dropping") + context.waitTicks(15) + context.takeScreenshot("gui-11h-inline-settings") + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("targeting range") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(40) + context.takeScreenshot("gui-11i-inline-settings-with-tabs") + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("window gap") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(40) + context.takeScreenshot("gui-11j-inline-settings-with-groups") + + context.runOnClient { Style.set("multipleSettings", true) } + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("targeting range") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(40) + context.takeScreenshot("gui-11k-inline-settings-of-two") + context.runOnClient { Style.set("inlineSettings", false) } + context.waitTicks(20) + context.takeScreenshot("gui-11l-panels-of-two") + context.runOnClient { Style.set("multipleSettings", false) } + context.waitTicks(20) + context.takeScreenshot("gui-11m-multiple-off-both-stay") + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("magnitude") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(40) + context.takeScreenshot("gui-11n-opening-one-closes-the-rest") + context.closeGui() + + context.runOnClient { Style.set("glow", true) } + context.openClickGui() + context.takeScreenshot("gui-11f-glow-dark") + context.closeGui() + + context.openClickGui() + context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.waitTicks(10) + context.click(dpX = 730.0, dpY = 201.0) + context.waitTicks(10) + context.click(dpX = 730.0, dpY = 243.0) + context.waitTicks(10) + context.takeScreenshot("gui-12a-light-theme") + 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() + context.runOnClient { Style.set("glow", false) } + + context.openClickGui() + context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) + context.waitTicks(10) + context.click(dpX = 730.0, dpY = 215.0) + context.waitTicks(10) + context.click(dpX = 730.0, dpY = 243.0) + context.waitTicks(10) + context.takeScreenshot("gui-13-fira-sans") + context.closeGui() + + 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.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(5) { + context.input.moveCursor(3.0 * DENSITY, 0.0) + context.waitTick() + } + context.waitTicks(5) + context.takeScreenshot("gui-14a-scale-held") + check(context.computeOnClient { Style.scale } == 1f) { "The scale changed while its bar was still held" } + context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + context.waitTicks(10) + context.takeScreenshot("gui-14b-scale-applied") + check(context.computeOnClient { Style.scale } > 1f) { "The scale was not applied when its bar was let go" } + context.runOnClient { Style.set("scale", 1.5f) } + context.waitTicks(15) + context.takeScreenshot("gui-14c-scale-largest") + context.runOnClient { Style.set("scale", 1f) } + context.waitTicks(10) + + context.input.setCursorPos(700.0 * DENSITY, 229.0 * DENSITY) + context.waitTicks(2) + context.dragBy(-30.0, 0.0) + context.runOnClient { Style.set("elementHeight", 20f) } + context.waitTicks(10) + context.takeScreenshot("gui-14-font-size-and-module-height") + check(context.computeOnClient { Style.fontSize } < 0.85f) { "Dragging the font size bar did not make text smaller" } + check(context.computeOnClient { Style.scale } == 1f) { "The scale was left changed" } + + context.runOnClient { Style.set("scale", 1.5f) } + context.waitTicks(15) + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("magnitude") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(45) + context.takeScreenshot("gui-14d-panel-beside-row") + context.input.setCursorPos(200.0 * DENSITY * 1.5, 200.0 * DENSITY * 1.5) + context.waitTicks(2) + context.input.scroll(-30.0) + context.waitTicks(25) + context.takeScreenshot("gui-14e-panel-row-scrolled-away") + context.runOnClient { Style.set("scale", 1f) } + context.waitTicks(10) + context.closeGui() + + context.openClickGui() + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.waitTicks(5) + context.takeScreenshot("gui-15a-keyboard-first-focus") + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.waitTicks(5) + context.takeScreenshot("gui-15b-keyboard-on-module") + + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + context.takeScreenshot("gui-15c-keyboard-toggled") + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) + context.waitTicks(15) + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.waitTicks(5) + context.takeScreenshot("gui-15d-keyboard-into-settings") + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.waitTicks(5) + context.takeScreenshot("gui-15e-keyboard-down-settings") + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.waitTicks(5) + context.takeScreenshot("gui-15f-keyboard-right-twice") + check(context.bobbingSpeed() == 1.02) { "Two steps right did not take the slider from 1.0 to 1.02" } + context.input.pressKey(GLFW.GLFW_KEY_LEFT) + context.input.pressKey(GLFW.GLFW_KEY_LEFT) + context.waitTicks(5) + check(context.bobbingSpeed() == 1.0) { "Two steps left did not bring the slider back to exactly 1.0" } + + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + context.input.typeChars("5") + context.waitTicks(5) + context.takeScreenshot("gui-15f1-number-being-typed") + check(context.bobbingSpeed() == 1.0) { "A number was applied while it was still being typed" } + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + check(context.bobbingSpeed() == 1.05) { "A typed number was not applied on Enter" } + + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + context.input.typeChars("9") + context.waitTicks(5) + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + check(context.bobbingSpeed() == 1.05) { "Escape did not discard a typed number" } + check(context.computeOnClient { LambdaGui.screen != null }) { "Escape in a number field closed the interface" } + + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + repeat(4) { context.input.pressKey(GLFW.GLFW_KEY_BACKSPACE) } + context.input.typeChars("7") + context.waitTicks(5) + check(context.bobbingSpeed() == 1.05) { "Clearing a number field changed the setting before it was done" } + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + context.takeScreenshot("gui-15f2-number-clamped") + check(context.bobbingSpeed() == 2.0) { "A typed number beyond the range was not brought to its end" } + context.runOnClient { Bobbing.set("speed", 1.0) } + context.waitTicks(5) + + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("zoo") + context.waitTicks(10) + context.takeScreenshot("gui-15g-keyboard-search") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + repeat(5) { context.pressKey(GLFW.GLFW_KEY_TAB, GLFW.GLFW_MOD_SHIFT) } + context.waitTicks(5) + context.takeScreenshot("gui-15h-keyboard-on-menu-bar") + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.waitTicks(5) + context.takeScreenshot("gui-15i-keyboard-in-menu") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(10) + context.takeScreenshot("gui-15j-keyboard-menu-closed") + + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(10) + repeat(7) { context.input.pressKey(GLFW.GLFW_KEY_DOWN) } + context.waitTicks(5) + context.takeScreenshot("gui-15k-keyboard-menu-reopened") + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(10) + check(context.computeOnClient { LambdaGui.screen == null }) { + "A menu closed from the keyboard did not open again from it, to have its Close GUI chosen" + } + + context.runOnClient { + Style.set("windowRounding", 9f) + Style.set("panelRounding", 0f) + Style.set("outlineWidth", 1.5f) + Style.set("windowWidth", 110f) + Style.set("windowGap", 8f) + Style.set("modulePadding", 10f) + Style.set("panelPadding", 10f) + Style.set("settingSpacing", 4f) + Style.set("panelAnimations", false) + } + context.openClickGui() + context.takeScreenshot("gui-16a-restyled") + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) + context.waitTicks(1) + context.takeScreenshot("gui-16b-no-panel-animation") + context.closeGui() + context.runOnClient { + Style.set("windowRounding", 3f) + Style.set("panelRounding", 5f) + Style.set("outlineWidth", 0.5f) + Style.set("windowWidth", 90f) + Style.set("windowGap", 2f) + Style.set("modulePadding", 4f) + Style.set("panelPadding", 4f) + Style.set("settingSpacing", 1f) + Style.set("panelAnimations", true) + } + + context.runOnClient { + GuiConfig.windows = mapOf( + "Movement" to GuiConfig.WindowPlacement(204.6f, 94.3f, false), + "Render" to GuiConfig.WindowPlacement(297f, 94f, true), + "World" to GuiConfig.WindowPlacement(500f, 200f, false), + ) + } + context.openClickGui() + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("window gap") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(60) + context.takeScreenshot("gui-17a-spacing-default") + context.runOnClient { Style.set("windowGap", 12f) } + context.waitTicks(10) + context.takeScreenshot("gui-17b-window-gap") + context.runOnClient { Style.set("windowGap", 2f); Style.set("windowTop", 40f) } + context.waitTicks(10) + context.takeScreenshot("gui-17c-window-top") + context.runOnClient { Style.set("windowTop", 94f); Style.set("modulePadding", 12f) } + context.waitTicks(10) + context.takeScreenshot("gui-17d-module-padding") + context.runOnClient { Style.set("modulePadding", 4f); Style.set("panelPadding", 12f) } + context.waitTicks(10) + context.takeScreenshot("gui-17e-panel-padding") + context.runOnClient { Style.set("panelPadding", 4f); Style.set("settingSpacing", 6f) } + context.waitTicks(10) + context.takeScreenshot("gui-17f-setting-spacing") + context.runOnClient { Style.set("settingSpacing", 1f); Style.set("groupIndent", 12f) } + context.waitTicks(10) + context.takeScreenshot("gui-17g-group-indent") + context.runOnClient { Style.set("groupIndent", 5f); Style.set("windowWidth", 120f) } + context.waitTicks(10) + context.takeScreenshot("gui-17h-window-width") + context.runOnClient { Style.set("windowWidth", 90f) } + context.waitTicks(10) + context.takeScreenshot("gui-17i-spacing-restored") + context.closeGui() + + context.runOnClient { GuiConfig.resetWindows() } + context.openClickGui() + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("emboss") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(60) + context.takeScreenshot("gui-18a-dependent-hidden") + context.runOnClient { Style.set("glow", true) } + context.waitTicks(15) + context.takeScreenshot("gui-18b-dependent-shown") + context.runOnClient { Style.set("glow", false) } + context.waitTicks(15) + context.takeScreenshot("gui-18c-dependent-hidden-again") + context.runOnClient { Style.set("animations", false) } + context.waitTicks(5) + context.runOnClient { Style.set("glow", true) } + context.waitTicks(15) + context.takeScreenshot("gui-18d-dependent-shown-unanimated") + context.runOnClient { Style.set("glow", false) } + context.waitTicks(15) + context.takeScreenshot("gui-18e-dependent-hidden-unanimated") + context.runOnClient { Style.set("animations", true) } + context.closeGui() + + context.openClickGui() + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("rebreak mode") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(60) + context.takeScreenshot("gui-19a-dependent-enabled") + context.setRebreak(false) + context.waitTicks(15) + context.takeScreenshot("gui-19b-dependent-disabled") + context.setRebreak(true) + context.waitTicks(15) + context.takeScreenshot("gui-19c-dependent-enabled-again") + context.closeGui() + + context.openClickGui() + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("airplace") + context.waitTicks(15) + context.takeScreenshot("gui-20-search-same-name") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(5) + + context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) + context.waitTicks(5) + context.input.typeChars("keep settings open") + context.waitTicks(10) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(45) + context.takeScreenshot("gui-20a-config-dialog") + context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) + context.waitTicks(10) + context.closeGui() + + context.openClickGui() + context.failInterface() + context.waitTicks(10) + check(context.computeOnClient { LambdaGui.screen == null }) { "An error in the interface left its screen open" } + context.takeScreenshot("gui-21a-hud-after-an-error") + context.openClickGui() + val enabledAfterError = context.enabledModules() + context.input.pressKey(GLFW.GLFW_KEY_TAB) + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.input.pressKey(GLFW.GLFW_KEY_RIGHT) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.input.pressKey(GLFW.GLFW_KEY_DOWN) + context.waitTicks(5) + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + context.takeScreenshot("gui-21b-click-gui-after-an-error") + check(context.enabledModules() != enabledAfterError) { "The interface rebuilt after an error did not take input" } + context.input.pressKey(GLFW.GLFW_KEY_ENTER) + context.waitTicks(5) + context.closeGui() + + context.failInterface() + context.failInterface() + context.runOnClient { LambdaGui.open(LambdaGui.Screen.ClickGui) } + context.waitTicks(10) + check(context.computeOnClient { LambdaGui.screen == null }) { "The interface went on opening after failing three times in a row" } + + singleplayer.close() + } + + private fun ClientGameTestContext.openClickGui() { + runOnClient { LambdaGui.open(LambdaGui.Screen.ClickGui) } + waitTicks(20) + check(computeOnClient { LambdaGui.screen != null }) { "The click GUI did not open" } + } + + private fun ClientGameTestContext.pressKey(key: Int, modifiers: Int) { + runOnClient { + GuiScreen.keyPressed(KeyInput(key, 0, modifiers)) + GuiScreen.keyReleased(KeyInput(key, 0, modifiers)) + } + waitTicks(1) + } + + private fun ClientGameTestContext.setRebreak(to: Boolean) = runOnClient { + (ModuleRegistry.modules.first { it.name == "PacketMine" } as Automated).breakConfig.set("rebreak", to) + } + + private fun ClientGameTestContext.failInterface() = runOnClient { + LambdaGui.javaClass.getDeclaredMethod("fail", Throwable::class.java) + .apply { isAccessible = true } + .invoke(LambdaGui, IllegalStateException("An error made up by the GUI test")) + } + + private fun ClientGameTestContext.clipboard(): String = computeOnClient { it.keyboard.clipboard } + + private fun ClientGameTestContext.setClipboard(text: String) = runOnClient { it.keyboard.clipboard = text } + + private fun ClientGameTestContext.bobbingSpeed(): Double = computeOnClient { Bobbing.speed } + + @Suppress("UNCHECKED_CAST") + private fun Any.set(property: String, value: Any) { + val delegate = javaClass.getDeclaredField(property + "\$delegate").apply { isAccessible = true } + (delegate.get(this) as Setting).value = value + } + + private fun ClientGameTestContext.closeGui() { + check(computeOnClient { LambdaGui.screen != null }) { "The interface closed itself, see the log" } + runOnClient { it.setScreen(null) } + waitTicks(5) + } + + private fun ClientGameTestContext.click(dpX: Double, dpY: Double, button: Int = GLFW.GLFW_MOUSE_BUTTON_LEFT) { + input.setCursorPos(dpX * DENSITY, dpY * DENSITY) + waitTicks(2) + input.pressMouse(button) + waitTicks(10) + } + + private fun ClientGameTestContext.dragBy(dpX: Double, dpY: Double) { + input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + repeat(5) { + input.moveCursor(dpX / 5 * DENSITY, dpY / 5 * DENSITY) + waitTick() + } + input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) + waitTicks(2) + } + + private fun ClientGameTestContext.windowPlacement(category: String): GuiConfig.WindowPlacement = + computeOnClient { + checkNotNull(GuiConfig.windows[category]) { "The $category window was never moved" } + } + + private fun ClientGameTestContext.enabledModules(): Int = + computeOnClient { ModuleRegistry.modules.count { it.isEnabled } } +} diff --git a/src/gametest/resources/fabric.mod.json b/src/gametest/resources/fabric.mod.json index c9ff71449..3c966f713 100644 --- a/src/gametest/resources/fabric.mod.json +++ b/src/gametest/resources/fabric.mod.json @@ -9,6 +9,10 @@ { "adapter": "kotlin", "value": "com.lambda.LambdaTest" + }, + { + "adapter": "kotlin", + "value": "com.lambda.GuiTest" } ] } From 8414a6fde7d0397f2ba69bf2ecdbbe2d0f59a028 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:58:10 +0000 Subject: [PATCH 14/34] optimize imports --- src/gametest/kotlin/com/lambda/GuiTest.kt | 2 +- src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt | 2 +- src/main/kotlin/com/lambda/gui/component/Popups.kt | 2 +- src/main/kotlin/com/lambda/gui/component/Scroll.kt | 3 --- src/main/kotlin/com/lambda/gui/component/SlidingText.kt | 2 +- src/main/kotlin/com/lambda/gui/hud/Hud.kt | 1 - src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt | 2 -- src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt | 2 -- 8 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt index 88666a979..964f6d153 100644 --- a/src/gametest/kotlin/com/lambda/GuiTest.kt +++ b/src/gametest/kotlin/com/lambda/GuiTest.kt @@ -25,10 +25,10 @@ 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.render.Bobbing 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.render.Bobbing 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 diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index 1c58cb9e4..75070fc46 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -87,8 +87,8 @@ import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look import com.lambda.gui.theme.Motion import com.lambda.module.ModuleTag -import kotlin.math.roundToInt import kotlinx.coroutines.launch +import kotlin.math.roundToInt private val MIN_WIDTH = 130.dp private val MIN_HEIGHT = 120.dp diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 04e73c311..616442b4b 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -18,8 +18,8 @@ package com.lambda.gui.component import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.expandIn import androidx.compose.animation.expandVertically import androidx.compose.animation.shrinkOut diff --git a/src/main/kotlin/com/lambda/gui/component/Scroll.kt b/src/main/kotlin/com/lambda/gui/component/Scroll.kt index 608b73c85..a831d029a 100644 --- a/src/main/kotlin/com/lambda/gui/component/Scroll.kt +++ b/src/main/kotlin/com/lambda/gui/component/Scroll.kt @@ -35,14 +35,11 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.v2.ScrollbarAdapter import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue 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.input.key.type import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput diff --git a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt index b0553283f..7a7d155ce 100644 --- a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt +++ b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt @@ -42,8 +42,8 @@ import androidx.compose.ui.unit.dp import com.lambda.gui.theme.LocalContentColor import com.lambda.gui.theme.Motion import com.lambda.gui.theme.Type -import kotlin.math.roundToInt import kotlinx.coroutines.withContext +import kotlin.math.roundToInt private val SLIDE_SPEED = 28.dp private const val REST_MILLIS = 350 diff --git a/src/main/kotlin/com/lambda/gui/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt index 1550a6293..fde904155 100644 --- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -21,7 +21,6 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue diff --git a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt index 753ac37c8..656a3fec0 100644 --- a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt +++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt @@ -25,8 +25,6 @@ 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 net.minecraft.client.gl.Framebuffer import net.minecraft.client.gl.GlBackend diff --git a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt index 9993cece9..9b1dbd8ec 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt @@ -27,14 +27,12 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind From 1266a19fd1b1191644a8f89872ac6a765ed49886 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:31:57 +0000 Subject: [PATCH 15/34] remover GuiTest --- src/gametest/kotlin/com/lambda/GuiTest.kt | 972 ------------------ src/gametest/resources/fabric.mod.json | 4 - src/main/kotlin/com/lambda/gui/GuiConfig.kt | 8 +- src/main/kotlin/com/lambda/gui/Snap.kt | 2 +- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 2 +- .../module/modules/client/AutoUpdater.kt | 8 +- 6 files changed, 10 insertions(+), 986 deletions(-) delete mode 100644 src/gametest/kotlin/com/lambda/GuiTest.kt diff --git a/src/gametest/kotlin/com/lambda/GuiTest.kt b/src/gametest/kotlin/com/lambda/GuiTest.kt deleted file mode 100644 index 964f6d153..000000000 --- a/src/gametest/kotlin/com/lambda/GuiTest.kt +++ /dev/null @@ -1,972 +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 - -import com.lambda.config.entries.Setting -import com.lambda.context.Automated -import com.lambda.gui.GuiConfig -import com.lambda.gui.GuiScreen -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 -import com.lambda.module.modules.render.Bobbing -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 net.minecraft.client.input.KeyInput -import org.lwjgl.glfw.GLFW -import kotlin.math.abs - -@Suppress("UnstableApiUsage") -object GuiTest : FabricClientGameTest { - private const val WIDTH = 1920 - private const val HEIGHT = 1080 - - private const val DENSITY = HEIGHT / 540.0 - - override fun runTest(context: ClientGameTestContext) { - context.input.resizeWindow(WIDTH, HEIGHT) - context.waitTicks(5) - - context.openClickGui() - context.takeScreenshot("gui-0-loader-prompt") - context.runOnClient { AutoUpdater.answerPrompt(accepted = false) } - context.waitTicks(10) - context.takeScreenshot("gui-1-title-screen") - - context.runOnClient { - Style.set("fontSize", 1f) - Style.set("elementHeight", 13f) - } - context.waitTicks(5) - - val enabledBefore = context.enabledModules() - 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 = 150.0, dpY = 115.0) - - val enabledBeforePress = context.enabledModules() - 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 = 150.0, dpY = 115.0) - - context.input.setCursorPos(240.0 * DENSITY, 193.0 * DENSITY) - context.waitTicks(30) - context.takeScreenshot("gui-1a-long-name-hovered") - context.input.setCursorPos(240.0 * DENSITY, 60.0 * DENSITY) - context.waitTicks(10) - context.takeScreenshot("gui-1b-long-name-left") - - context.input.setCursorPos(620.0 * DENSITY, 101.0 * DENSITY) - context.dragBy(3.5, 7.5) - val free = context.windowPlacement("Network") - check(abs(free.x - 576.5f) < 0.6f && abs(free.y - 101.5f) < 0.6f) { "A dragged window did not follow the pointer: $free" } - - context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) - context.waitTicks(2) - context.dragBy(2.0, 2.0) - context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) - val snapped = context.windowPlacement("Network") - check(snapped.inRow) { "A window dragged with the snap key held did not snap back between its neighbours: $snapped" } - - context.runOnClient { GuiConfig.set("showSnapLines", true) } - context.input.setCursorPos(620.0 * DENSITY, 100.0 * DENSITY) - context.waitTicks(2) - context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) - context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(5) { - context.input.moveCursor(3.0 * DENSITY, 30.0 * DENSITY) - context.waitTick() - } - context.waitTicks(3) - context.takeScreenshot("gui-1b1-window-snap-lines") - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) - context.waitTicks(2) - val aligned = context.windowPlacement("Network") - check(abs(aligned.x - 573f) < 0.6f) { "A window dragged down beside its place in the row did not stay in line with it: $aligned" } - context.runOnClient { - GuiConfig.set("showSnapLines", false) - GuiConfig.resetWindows() - } - context.waitTicks(5) - - context.input.setCursorPos(620.0 * DENSITY, 100.0 * DENSITY) - context.waitTicks(2) - context.dragBy(0.0, -95.0) - val raised = context.windowPlacement("Network") - context.takeScreenshot("gui-1c-window-dragged-to-the-top") - check(abs(raised.y - 15f) < 0.6f) { "A window dragged to the top of the screen did not stop under the menu bar: $raised" } - - context.runOnClient { GuiConfig.resetWindows() } - context.waitTicks(2) - check(context.computeOnClient { GuiConfig.windows.isEmpty() }) { "Resetting the layout left a window placed" } - - context.click(dpX = 150.0, dpY = 115.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-2-module-settings") - - 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") - context.waitTicks(10) - - context.click(dpX = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - - context.click(dpX = 298.5, dpY = 198.0) - context.takeScreenshot("gui-2c2-module-page") - context.input.setCursorPos(340.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(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 = 261.0, dpY = 247.0) - context.click(dpX = 236.5, dpY = 198.0) - - 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(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") - - context.input.setCursorPos(320.0 * DENSITY, 273.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.takeScreenshot("gui-2g0-dropdown-unfolding") - context.waitTicks(10) - context.takeScreenshot("gui-2g-dropdown") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(1) - context.takeScreenshot("gui-2g1-dropdown-folding") - context.waitTicks(2) - context.takeScreenshot("gui-2g2-dropdown-folded-in") - context.waitTicks(3) - - context.click(dpX = 296.0, dpY = 216.0) - context.takeScreenshot("gui-2d0-tab-list") - context.input.setCursorPos(296.0 * DENSITY, 245.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.takeScreenshot("gui-2d-tab-changing") - context.waitTicks(10) - context.takeScreenshot("gui-2e-tab-changed") - - context.input.setCursorPos(360.0 * DENSITY, 260.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.takeScreenshot("gui-2h0-collection-unfolding") - context.waitTicks(10) - context.takeScreenshot("gui-2h-collection") - context.input.typeChars("stone") - context.waitTicks(5) - context.takeScreenshot("gui-2h2-collection-searched") - - context.setClipboard("") - context.pressKey(GLFW.GLFW_KEY_A, GLFW.GLFW_MOD_CONTROL) - context.pressKey(GLFW.GLFW_KEY_C, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(3) - check(context.clipboard() == "stone") { "Copying from a text field in a dialog left the clipboard as '${context.clipboard()}'" } - context.setClipboard("glass") - context.pressKey(GLFW.GLFW_KEY_A, GLFW.GLFW_MOD_CONTROL) - context.pressKey(GLFW.GLFW_KEY_V, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(3) - context.setClipboard("") - context.pressKey(GLFW.GLFW_KEY_A, GLFW.GLFW_MOD_CONTROL) - context.pressKey(GLFW.GLFW_KEY_C, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(3) - check(context.clipboard() == "glass") { "Pasting into a text field in a dialog gave '${context.clipboard()}'" } - context.takeScreenshot("gui-2h4-collection-pasted") - - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(1) - context.takeScreenshot("gui-2h1-collection-folding") - context.waitTicks(2) - context.takeScreenshot("gui-2h3-collection-folded-in") - context.waitTicks(3) - - context.click(dpX = 340.0, dpY = 198.0) - for (y in listOf(289.0, 275.0, 261.0, 247.0)) context.click(dpX = 261.0, dpY = y) - context.takeScreenshot("gui-2i-scrolling") - - context.input.setCursorPos(290.0 * DENSITY, 400.0 * DENSITY) - context.waitTicks(2) - context.input.scroll(-2.0) - context.waitTicks(1) - context.takeScreenshot("gui-2i1-wheel-gliding") - context.waitTicks(15) - context.takeScreenshot("gui-2i2-wheel-settled") - context.input.scroll(10.0) - context.waitTicks(15) - context.input.setCursorPos(317.0 * DENSITY, 189.0 * DENSITY) - context.waitTicks(2) - context.dragBy(0.0, -60.0) - context.takeScreenshot("gui-2j-extended") - - context.dragBy(0.0, -300.0) - context.takeScreenshot("gui-2k-extended-to-the-bar") - - context.click(dpX = 150.0, dpY = 101.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-2f-category-folded") - context.click(dpX = 150.0, dpY = 101.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") - - context.click(dpX = 20.0, dpY = 7.0) - context.takeScreenshot("gui-3-menu") - - context.click(dpX = 30.0, dpY = 39.0) - context.click(dpX = 190.0, dpY = 7.0) - context.takeScreenshot("gui-3b-menu-to-menu") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - - context.click(dpX = 20.0, dpY = 7.0) - context.click(dpX = 30.0, dpY = 39.0) - context.waitTicks(10) - context.takeScreenshot("gui-3c-submenu") - context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.takeScreenshot("gui-3d-submenu-swallowed") - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.takeScreenshot("gui-3e-submenu-swallowed") - context.waitTicks(10) - - context.click(dpX = 20.0, dpY = 7.0) - context.closeGui() - context.openClickGui() - context.takeScreenshot("gui-3a-reopened") - - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("scaff") - context.waitTicks(10) - context.takeScreenshot("gui-4-search") - - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(8) - context.takeScreenshot("gui-4a-search-module") - context.waitTicks(40) - - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("auto") - context.waitTicks(1) - context.takeScreenshot("gui-4a1-search-unfolding") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.waitTicks(5) - context.takeScreenshot("gui-4a2-search-third-marked") - context.input.pressKey(GLFW.GLFW_KEY_UP) - context.waitTicks(5) - context.takeScreenshot("gui-4a3-search-second-marked") - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(8) - context.takeScreenshot("gui-4a4-search-marked-chosen") - context.waitTicks(40) - - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("targeting range") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(15) - context.takeScreenshot("gui-4b-search-setting") - - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("surround") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(15) - context.click(dpX = 150.0, dpY = 219.5, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-4c-block-settings") - context.click(dpX = 350.0, dpY = 242.0) - context.takeScreenshot("gui-4d-block-list") - - context.input.setCursorPos(400.0 * DENSITY, 346.0 * DENSITY) - context.waitTicks(2) - context.input.scroll(-5.0) - context.waitTicks(15) - context.takeScreenshot("gui-4e-block-list-scrolled") - - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - context.takeScreenshot("gui-4f-block-list-shut") - - context.click(dpX = 480.0, dpY = 7.0) - context.input.typeChars("pavement material") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(15) - context.takeScreenshot("gui-4g-block-setting") - context.closeGui() - - val singleplayer = context.worldBuilder() - .adjustSettings { it.gameMode = WorldCreator.Mode.CREATIVE } - .create() - singleplayer.clientWorld.waitForChunksDownload() - singleplayer.server.runCommand("/item replace entity @p armor.head with minecraft:stone 32") - singleplayer.server.runCommand("/item replace entity @p armor.chest with minecraft:netherite_chestplate[minecraft:damage=500]") - singleplayer.server.runCommand("/item replace entity @p armor.legs with minecraft:diamond_leggings[minecraft:enchantments={protection:4}]") - singleplayer.server.runCommand("/item replace entity @p armor.feet with minecraft:golden_boots[minecraft:damage=40]") - - context.runOnClient { - Armor.enable() - Coordinates.enable() - Fps.enable() - } - context.waitTicks(20) - context.takeScreenshot("gui-5-hud-in-game") - - context.input.pressKey(GLFW.GLFW_KEY_Y) - context.waitTicks(2) - context.takeScreenshot("gui-6-0-click-gui-opening") - context.waitTicks(18) - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "The keybind did not open the click GUI" } - context.takeScreenshot("gui-6-click-gui-in-game") - - context.input.setCursorPos(300.0 * DENSITY, 400.0 * DENSITY) - context.waitTicks(2) - context.input.setCursorPos(150.0 * DENSITY, 115.0 * DENSITY) - context.waitTicks(40) - context.takeScreenshot("gui-6a-tooltip") - context.input.pressKey(GLFW.GLFW_KEY_Y) - context.waitTicks(10) - context.takeScreenshot("gui-6b-closed-with-tooltip-up") - context.input.pressKey(GLFW.GLFW_KEY_Y) - context.waitTicks(10) - context.takeScreenshot("gui-6c-reopened") - - context.click(dpX = 480.0, dpY = 7.0) - context.input.pressKey(GLFW.GLFW_KEY_Y) - context.waitTicks(5) - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "Typing the keybind into a text field closed the GUI" } - check(context.computeOnClient { LambdaGui.isCapturingKeys }) { "A focused text field did not hold on to the keys" } - context.input.pressKey(GLFW.GLFW_KEY_BACKSPACE) - context.waitTicks(2) - - context.click(dpX = 924.0, dpY = 528.0) - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.HudEditor }) { "The HUD Editor button did not open the editor" } - check(context.computeOnClient { !LambdaGui.isCapturingKeys }) { "Keys stayed captured after the focused text field went away" } - context.input.setCursorPos(20.0 * DENSITY, 44.0 * DENSITY) - context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(10) { - context.input.moveCursor(30.0 * DENSITY, 15.0 * DENSITY) - context.waitTick() - } - context.takeScreenshot("gui-7-hud-editor-dragging") - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(2) - - context.input.holdKey(GLFW.GLFW_KEY_LEFT_SHIFT) - context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(10) { - context.input.moveCursor(-29.0 * DENSITY, 2.0 * DENSITY) - context.waitTick() - } - context.takeScreenshot("gui-7a-hud-editor-snapping") - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.input.releaseKey(GLFW.GLFW_KEY_LEFT_SHIFT) - context.waitTicks(2) - - context.click(dpX = 700.0, dpY = 400.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-8-hud-editor-menu") - - context.input.setCursorPos(500.0 * DENSITY, 300.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(1) - context.takeScreenshot("gui-8a-hud-editor-menu-reopening") - context.waitTicks(10) - context.takeScreenshot("gui-8b-hud-editor-menu-reopened") - - context.input.setCursorPos(513.0 * DENSITY, 427.5 * DENSITY) - context.waitTicks(20) - context.takeScreenshot("gui-8c-hud-editor-help") - context.click(dpX = 150.0, dpY = 108.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.takeScreenshot("gui-9-hud-element-menu") - context.input.setCursorPos(175.0 * DENSITY, 129.0 * DENSITY) - context.waitTicks(2) - context.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(3) - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(10) - context.takeScreenshot("gui-9a-hud-element-settings") - - context.click(dpX = 342.0, dpY = 151.0) - context.takeScreenshot("gui-9b-hud-element-colour") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - context.click(dpX = 312.0, dpY = 224.5) - context.takeScreenshot("gui-9c-hud-element-options") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - - context.click(dpX = 311.0, dpY = 135.0) - context.waitTicks(10) - context.takeScreenshot("gui-9c1-hud-element-module-page") - context.click(dpX = 200.0, dpY = 135.0) - context.waitTicks(10) - - context.input.setCursorPos(170.0 * DENSITY, 284.0 * DENSITY) - context.waitTicks(2) - context.dragBy(150.0, 60.0) - context.takeScreenshot("gui-9d-hud-settings-dragged") - - context.input.setCursorPos(700.0 * DENSITY, 450.0 * DENSITY) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.takeScreenshot("gui-9e-hud-settings-closing") - context.waitTicks(10) - context.takeScreenshot("gui-9f-hud-settings-closed") - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.HudEditor }) { "Closing the settings panel left the HUD editor" } - - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - check(context.computeOnClient { LambdaGui.screen == LambdaGui.Screen.ClickGui }) { "Escape did not return from the HUD editor to the click GUI" } - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - check(context.computeOnClient { LambdaGui.screen == null }) { "Escape did not close the click GUI" } - - context.openClickGui() - context.click(dpX = 150.0, dpY = 193.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(10) - 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) - context.waitTicks(2) - context.input.pressMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(1) - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.takeScreenshot("gui-10b-menu-folding-in-panel") - context.waitTicks(1) - context.takeScreenshot("gui-10c-menu-folding-in-panel") - context.waitTicks(15) - context.takeScreenshot("gui-10d-panel-closed") - - context.runOnClient { GuiConfig.set("keepSettingsOpen", true) } - 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) } - context.waitTicks(2) - context.takeScreenshot("gui-11a-kept-settings-categories-unfolding") - context.waitTicks(4) - context.takeScreenshot("gui-11b-kept-settings-unfolding") - context.waitTicks(15) - context.takeScreenshot("gui-11c-kept-settings-open") - context.runOnClient { GuiConfig.set("keepSettingsOpen", false) } - context.closeGui() - - context.openClickGui() - context.click(dpX = 520.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(10) - context.takeScreenshot("gui-11d-settings-of-many-tabs") - context.click(dpX = 728.0, dpY = 185.0) - context.waitTicks(10) - context.click(dpX = 650.0, dpY = 216.0) - context.takeScreenshot("gui-11e-many-tabs-listed") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - context.closeGui() - - context.runOnClient { - Style.set("inlineSettings", true) - GuiConfig.resetWindows() - } - context.openClickGui() - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) - context.waitTicks(3) - context.takeScreenshot("gui-11g-inline-settings-dropping") - context.waitTicks(15) - context.takeScreenshot("gui-11h-inline-settings") - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("targeting range") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(40) - context.takeScreenshot("gui-11i-inline-settings-with-tabs") - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("window gap") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(40) - context.takeScreenshot("gui-11j-inline-settings-with-groups") - - context.runOnClient { Style.set("multipleSettings", true) } - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("targeting range") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(40) - context.takeScreenshot("gui-11k-inline-settings-of-two") - context.runOnClient { Style.set("inlineSettings", false) } - context.waitTicks(20) - context.takeScreenshot("gui-11l-panels-of-two") - context.runOnClient { Style.set("multipleSettings", false) } - context.waitTicks(20) - context.takeScreenshot("gui-11m-multiple-off-both-stay") - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("magnitude") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(40) - context.takeScreenshot("gui-11n-opening-one-closes-the-rest") - context.closeGui() - - context.runOnClient { Style.set("glow", true) } - context.openClickGui() - context.takeScreenshot("gui-11f-glow-dark") - context.closeGui() - - context.openClickGui() - context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(10) - context.click(dpX = 730.0, dpY = 201.0) - context.waitTicks(10) - context.click(dpX = 730.0, dpY = 243.0) - context.waitTicks(10) - context.takeScreenshot("gui-12a-light-theme") - 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() - context.runOnClient { Style.set("glow", false) } - - context.openClickGui() - context.click(dpX = 800.0, dpY = 180.0, button = GLFW.GLFW_MOUSE_BUTTON_RIGHT) - context.waitTicks(10) - context.click(dpX = 730.0, dpY = 215.0) - context.waitTicks(10) - context.click(dpX = 730.0, dpY = 243.0) - context.waitTicks(10) - context.takeScreenshot("gui-13-fira-sans") - context.closeGui() - - 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.input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(5) { - context.input.moveCursor(3.0 * DENSITY, 0.0) - context.waitTick() - } - context.waitTicks(5) - context.takeScreenshot("gui-14a-scale-held") - check(context.computeOnClient { Style.scale } == 1f) { "The scale changed while its bar was still held" } - context.input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - context.waitTicks(10) - context.takeScreenshot("gui-14b-scale-applied") - check(context.computeOnClient { Style.scale } > 1f) { "The scale was not applied when its bar was let go" } - context.runOnClient { Style.set("scale", 1.5f) } - context.waitTicks(15) - context.takeScreenshot("gui-14c-scale-largest") - context.runOnClient { Style.set("scale", 1f) } - context.waitTicks(10) - - context.input.setCursorPos(700.0 * DENSITY, 229.0 * DENSITY) - context.waitTicks(2) - context.dragBy(-30.0, 0.0) - context.runOnClient { Style.set("elementHeight", 20f) } - context.waitTicks(10) - context.takeScreenshot("gui-14-font-size-and-module-height") - check(context.computeOnClient { Style.fontSize } < 0.85f) { "Dragging the font size bar did not make text smaller" } - check(context.computeOnClient { Style.scale } == 1f) { "The scale was left changed" } - - context.runOnClient { Style.set("scale", 1.5f) } - context.waitTicks(15) - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("magnitude") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(45) - context.takeScreenshot("gui-14d-panel-beside-row") - context.input.setCursorPos(200.0 * DENSITY * 1.5, 200.0 * DENSITY * 1.5) - context.waitTicks(2) - context.input.scroll(-30.0) - context.waitTicks(25) - context.takeScreenshot("gui-14e-panel-row-scrolled-away") - context.runOnClient { Style.set("scale", 1f) } - context.waitTicks(10) - context.closeGui() - - context.openClickGui() - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.waitTicks(5) - context.takeScreenshot("gui-15a-keyboard-first-focus") - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.waitTicks(5) - context.takeScreenshot("gui-15b-keyboard-on-module") - - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - context.takeScreenshot("gui-15c-keyboard-toggled") - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) - context.waitTicks(15) - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.waitTicks(5) - context.takeScreenshot("gui-15d-keyboard-into-settings") - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.waitTicks(5) - context.takeScreenshot("gui-15e-keyboard-down-settings") - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.waitTicks(5) - context.takeScreenshot("gui-15f-keyboard-right-twice") - check(context.bobbingSpeed() == 1.02) { "Two steps right did not take the slider from 1.0 to 1.02" } - context.input.pressKey(GLFW.GLFW_KEY_LEFT) - context.input.pressKey(GLFW.GLFW_KEY_LEFT) - context.waitTicks(5) - check(context.bobbingSpeed() == 1.0) { "Two steps left did not bring the slider back to exactly 1.0" } - - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - context.input.typeChars("5") - context.waitTicks(5) - context.takeScreenshot("gui-15f1-number-being-typed") - check(context.bobbingSpeed() == 1.0) { "A number was applied while it was still being typed" } - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - check(context.bobbingSpeed() == 1.05) { "A typed number was not applied on Enter" } - - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - context.input.typeChars("9") - context.waitTicks(5) - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - check(context.bobbingSpeed() == 1.05) { "Escape did not discard a typed number" } - check(context.computeOnClient { LambdaGui.screen != null }) { "Escape in a number field closed the interface" } - - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - repeat(4) { context.input.pressKey(GLFW.GLFW_KEY_BACKSPACE) } - context.input.typeChars("7") - context.waitTicks(5) - check(context.bobbingSpeed() == 1.05) { "Clearing a number field changed the setting before it was done" } - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - context.takeScreenshot("gui-15f2-number-clamped") - check(context.bobbingSpeed() == 2.0) { "A typed number beyond the range was not brought to its end" } - context.runOnClient { Bobbing.set("speed", 1.0) } - context.waitTicks(5) - - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("zoo") - context.waitTicks(10) - context.takeScreenshot("gui-15g-keyboard-search") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - repeat(5) { context.pressKey(GLFW.GLFW_KEY_TAB, GLFW.GLFW_MOD_SHIFT) } - context.waitTicks(5) - context.takeScreenshot("gui-15h-keyboard-on-menu-bar") - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.waitTicks(5) - context.takeScreenshot("gui-15i-keyboard-in-menu") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(10) - context.takeScreenshot("gui-15j-keyboard-menu-closed") - - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(10) - repeat(7) { context.input.pressKey(GLFW.GLFW_KEY_DOWN) } - context.waitTicks(5) - context.takeScreenshot("gui-15k-keyboard-menu-reopened") - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(10) - check(context.computeOnClient { LambdaGui.screen == null }) { - "A menu closed from the keyboard did not open again from it, to have its Close GUI chosen" - } - - context.runOnClient { - Style.set("windowRounding", 9f) - Style.set("panelRounding", 0f) - Style.set("outlineWidth", 1.5f) - Style.set("windowWidth", 110f) - Style.set("windowGap", 8f) - Style.set("modulePadding", 10f) - Style.set("panelPadding", 10f) - Style.set("settingSpacing", 4f) - Style.set("panelAnimations", false) - } - context.openClickGui() - context.takeScreenshot("gui-16a-restyled") - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.pressKey(GLFW.GLFW_KEY_ENTER, GLFW.GLFW_MOD_SHIFT) - context.waitTicks(1) - context.takeScreenshot("gui-16b-no-panel-animation") - context.closeGui() - context.runOnClient { - Style.set("windowRounding", 3f) - Style.set("panelRounding", 5f) - Style.set("outlineWidth", 0.5f) - Style.set("windowWidth", 90f) - Style.set("windowGap", 2f) - Style.set("modulePadding", 4f) - Style.set("panelPadding", 4f) - Style.set("settingSpacing", 1f) - Style.set("panelAnimations", true) - } - - context.runOnClient { - GuiConfig.windows = mapOf( - "Movement" to GuiConfig.WindowPlacement(204.6f, 94.3f, false), - "Render" to GuiConfig.WindowPlacement(297f, 94f, true), - "World" to GuiConfig.WindowPlacement(500f, 200f, false), - ) - } - context.openClickGui() - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("window gap") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(60) - context.takeScreenshot("gui-17a-spacing-default") - context.runOnClient { Style.set("windowGap", 12f) } - context.waitTicks(10) - context.takeScreenshot("gui-17b-window-gap") - context.runOnClient { Style.set("windowGap", 2f); Style.set("windowTop", 40f) } - context.waitTicks(10) - context.takeScreenshot("gui-17c-window-top") - context.runOnClient { Style.set("windowTop", 94f); Style.set("modulePadding", 12f) } - context.waitTicks(10) - context.takeScreenshot("gui-17d-module-padding") - context.runOnClient { Style.set("modulePadding", 4f); Style.set("panelPadding", 12f) } - context.waitTicks(10) - context.takeScreenshot("gui-17e-panel-padding") - context.runOnClient { Style.set("panelPadding", 4f); Style.set("settingSpacing", 6f) } - context.waitTicks(10) - context.takeScreenshot("gui-17f-setting-spacing") - context.runOnClient { Style.set("settingSpacing", 1f); Style.set("groupIndent", 12f) } - context.waitTicks(10) - context.takeScreenshot("gui-17g-group-indent") - context.runOnClient { Style.set("groupIndent", 5f); Style.set("windowWidth", 120f) } - context.waitTicks(10) - context.takeScreenshot("gui-17h-window-width") - context.runOnClient { Style.set("windowWidth", 90f) } - context.waitTicks(10) - context.takeScreenshot("gui-17i-spacing-restored") - context.closeGui() - - context.runOnClient { GuiConfig.resetWindows() } - context.openClickGui() - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("emboss") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(60) - context.takeScreenshot("gui-18a-dependent-hidden") - context.runOnClient { Style.set("glow", true) } - context.waitTicks(15) - context.takeScreenshot("gui-18b-dependent-shown") - context.runOnClient { Style.set("glow", false) } - context.waitTicks(15) - context.takeScreenshot("gui-18c-dependent-hidden-again") - context.runOnClient { Style.set("animations", false) } - context.waitTicks(5) - context.runOnClient { Style.set("glow", true) } - context.waitTicks(15) - context.takeScreenshot("gui-18d-dependent-shown-unanimated") - context.runOnClient { Style.set("glow", false) } - context.waitTicks(15) - context.takeScreenshot("gui-18e-dependent-hidden-unanimated") - context.runOnClient { Style.set("animations", true) } - context.closeGui() - - context.openClickGui() - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("rebreak mode") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(60) - context.takeScreenshot("gui-19a-dependent-enabled") - context.setRebreak(false) - context.waitTicks(15) - context.takeScreenshot("gui-19b-dependent-disabled") - context.setRebreak(true) - context.waitTicks(15) - context.takeScreenshot("gui-19c-dependent-enabled-again") - context.closeGui() - - context.openClickGui() - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("airplace") - context.waitTicks(15) - context.takeScreenshot("gui-20-search-same-name") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(5) - - context.pressKey(GLFW.GLFW_KEY_F, GLFW.GLFW_MOD_CONTROL) - context.waitTicks(5) - context.input.typeChars("keep settings open") - context.waitTicks(10) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(45) - context.takeScreenshot("gui-20a-config-dialog") - context.input.pressKey(GLFW.GLFW_KEY_ESCAPE) - context.waitTicks(10) - context.closeGui() - - context.openClickGui() - context.failInterface() - context.waitTicks(10) - check(context.computeOnClient { LambdaGui.screen == null }) { "An error in the interface left its screen open" } - context.takeScreenshot("gui-21a-hud-after-an-error") - context.openClickGui() - val enabledAfterError = context.enabledModules() - context.input.pressKey(GLFW.GLFW_KEY_TAB) - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.input.pressKey(GLFW.GLFW_KEY_RIGHT) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.input.pressKey(GLFW.GLFW_KEY_DOWN) - context.waitTicks(5) - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - context.takeScreenshot("gui-21b-click-gui-after-an-error") - check(context.enabledModules() != enabledAfterError) { "The interface rebuilt after an error did not take input" } - context.input.pressKey(GLFW.GLFW_KEY_ENTER) - context.waitTicks(5) - context.closeGui() - - context.failInterface() - context.failInterface() - context.runOnClient { LambdaGui.open(LambdaGui.Screen.ClickGui) } - context.waitTicks(10) - check(context.computeOnClient { LambdaGui.screen == null }) { "The interface went on opening after failing three times in a row" } - - singleplayer.close() - } - - private fun ClientGameTestContext.openClickGui() { - runOnClient { LambdaGui.open(LambdaGui.Screen.ClickGui) } - waitTicks(20) - check(computeOnClient { LambdaGui.screen != null }) { "The click GUI did not open" } - } - - private fun ClientGameTestContext.pressKey(key: Int, modifiers: Int) { - runOnClient { - GuiScreen.keyPressed(KeyInput(key, 0, modifiers)) - GuiScreen.keyReleased(KeyInput(key, 0, modifiers)) - } - waitTicks(1) - } - - private fun ClientGameTestContext.setRebreak(to: Boolean) = runOnClient { - (ModuleRegistry.modules.first { it.name == "PacketMine" } as Automated).breakConfig.set("rebreak", to) - } - - private fun ClientGameTestContext.failInterface() = runOnClient { - LambdaGui.javaClass.getDeclaredMethod("fail", Throwable::class.java) - .apply { isAccessible = true } - .invoke(LambdaGui, IllegalStateException("An error made up by the GUI test")) - } - - private fun ClientGameTestContext.clipboard(): String = computeOnClient { it.keyboard.clipboard } - - private fun ClientGameTestContext.setClipboard(text: String) = runOnClient { it.keyboard.clipboard = text } - - private fun ClientGameTestContext.bobbingSpeed(): Double = computeOnClient { Bobbing.speed } - - @Suppress("UNCHECKED_CAST") - private fun Any.set(property: String, value: Any) { - val delegate = javaClass.getDeclaredField(property + "\$delegate").apply { isAccessible = true } - (delegate.get(this) as Setting).value = value - } - - private fun ClientGameTestContext.closeGui() { - check(computeOnClient { LambdaGui.screen != null }) { "The interface closed itself, see the log" } - runOnClient { it.setScreen(null) } - waitTicks(5) - } - - private fun ClientGameTestContext.click(dpX: Double, dpY: Double, button: Int = GLFW.GLFW_MOUSE_BUTTON_LEFT) { - input.setCursorPos(dpX * DENSITY, dpY * DENSITY) - waitTicks(2) - input.pressMouse(button) - waitTicks(10) - } - - private fun ClientGameTestContext.dragBy(dpX: Double, dpY: Double) { - input.holdMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - repeat(5) { - input.moveCursor(dpX / 5 * DENSITY, dpY / 5 * DENSITY) - waitTick() - } - input.releaseMouse(GLFW.GLFW_MOUSE_BUTTON_LEFT) - waitTicks(2) - } - - private fun ClientGameTestContext.windowPlacement(category: String): GuiConfig.WindowPlacement = - computeOnClient { - checkNotNull(GuiConfig.windows[category]) { "The $category window was never moved" } - } - - private fun ClientGameTestContext.enabledModules(): Int = - computeOnClient { ModuleRegistry.modules.count { it.isEnabled } } -} diff --git a/src/gametest/resources/fabric.mod.json b/src/gametest/resources/fabric.mod.json index 3c966f713..c9ff71449 100644 --- a/src/gametest/resources/fabric.mod.json +++ b/src/gametest/resources/fabric.mod.json @@ -9,10 +9,6 @@ { "adapter": "kotlin", "value": "com.lambda.LambdaTest" - }, - { - "adapter": "kotlin", - "value": "com.lambda.GuiTest" } ] } diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index 76a267a08..04143135f 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -49,7 +49,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @Tab(GENERAL_TAB) val lambdaTitleAppendixName by setting("Append Username", true) { setLambdaWindowTitle } .onValueChange { _, _ -> mc.updateWindowTitle() } @Tab(GENERAL_TAB) val keepSettingsOpen by setting("Keep Settings Open", false, "Leaves a module's settings open when the click GUI closes, so they are still there when it opens again") - @Tab(GENERAL_TAB) val resetWindowLayout by setting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded") + @Tab(GENERAL_TAB) private val resetWindowLayout by setting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded") @Tab(SNAPPING_TAB) val snapEnabled by setting("Enable Snapping", true, "Master toggle for snapping HUD elements and click GUI windows into line when they are dragged") @Tab(SNAPPING_TAB) val snapKey by setting("Snap Key", KeyCode.LeftShift, "What is dragged only snaps while this is held. Unbind it to snap all the time.") { snapEnabled } @@ -64,7 +64,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @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 } - data class WindowPlacement(val x: Float, val y: Float, val collapsed: Boolean) { + internal data class WindowPlacement(val x: Float, val y: Float, val collapsed: Boolean) { val inRow get() = x.isNaN() || y.isNaN() companion object { @@ -76,7 +76,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { private var decodedFrom: String? = null private var decoded = emptyMap() - var windows: Map + internal var windows: Map get() { val saved = windowPlacements if (saved != decodedFrom) { @@ -91,7 +91,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { } } - fun resetWindows() { + internal fun resetWindows() { windows = emptyMap() } diff --git a/src/main/kotlin/com/lambda/gui/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt index 71dce0277..cb4c6efc2 100644 --- a/src/main/kotlin/com/lambda/gui/Snap.kt +++ b/src/main/kotlin/com/lambda/gui/Snap.kt @@ -51,7 +51,7 @@ internal object Snap { val isActive: Boolean get() = GuiConfig.snapEnabled && (GuiConfig.snapKey == Bind.EMPTY || GuiConfig.snapKey.isSatisfied()) - fun gridStep(density: Density) = with(density) { max(MIN_GRID_STEP, GuiConfig.gridSize.dp.toPx()) } + private fun gridStep(density: Density) = with(density) { max(MIN_GRID_STEP, GuiConfig.gridSize.dp.toPx()) } fun free(element: Rect, area: Rect) = Result(element.topLeft.keptIn(area, element.size), Guides.NONE) diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index 7c00e2fed..d9caa8d7a 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -155,7 +155,7 @@ enum class GuiFont(override val displayName: String, val size: TextUnit, val sma } @Immutable -class Typography(font: GuiFont, scale: Float = 1f) { +private class Typography(font: GuiFont, scale: Float = 1f) { val title = compact(font, font.size * scale, font.titleWeight) val body = compact(font, font.size * scale) val label = compact(font, font.smallSize * scale) 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 fa5737dc8..67660199b 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt @@ -42,9 +42,9 @@ object AutoUpdater : Module( private var loaderPromptHandled by property(false) - enum class Prompt { FirstLaunch, Install, Uninstall } + internal enum class Prompt { FirstLaunch, Install, Uninstall } - var prompt: Prompt? = null + internal var prompt: Prompt? = null private set private var firstLaunchStateInitialized = false @@ -64,7 +64,7 @@ object AutoUpdater : Module( onDisableUnsafe { prompt = Prompt.Uninstall.takeIf { LambdaGui.screen != null && prompt != Prompt.Install } } } - fun onGuiOpened() { + internal fun onGuiOpened() { if (firstLaunchStateInitialized) return firstLaunchStateInitialized = true @@ -76,7 +76,7 @@ object AutoUpdater : Module( if (!loaderPromptHandled) prompt = Prompt.FirstLaunch } - fun answerPrompt(accepted: Boolean) { + internal fun answerPrompt(accepted: Boolean) { when (prompt) { Prompt.FirstLaunch -> { loaderPromptHandled = true From 094cb14831715837ffbf507e9777201d716ea4db Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:05:14 +0000 Subject: [PATCH 16/34] formatting --- .../com/lambda/mixin/input/KeyboardMixin.java | 2 +- src/main/kotlin/com/lambda/Lambda.kt | 7 +- .../kotlin/com/lambda/config/EntryLayer.kt | 11 +- .../lambda/config/settings/NumericSetting.kt | 11 +- .../config/settings/complex/KeybindSetting.kt | 58 ++++-- .../graphics/mc/LambdaRenderPipelines.kt | 54 +++--- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 7 +- src/main/kotlin/com/lambda/gui/GuiScreen.kt | 49 +---- src/main/kotlin/com/lambda/gui/LambdaGui.kt | 28 +-- src/main/kotlin/com/lambda/gui/Snap.kt | 115 ++++++------ .../com/lambda/gui/clickgui/CategoryWindow.kt | 30 ++-- .../com/lambda/gui/clickgui/ClickGui.kt | 7 +- .../com/lambda/gui/clickgui/SettingsPanel.kt | 42 +++-- .../com/lambda/gui/component/Keyboard.kt | 31 ++-- .../com/lambda/gui/component/Pointer.kt | 96 +++++----- .../kotlin/com/lambda/gui/component/Popups.kt | 167 ++++++++++-------- .../kotlin/com/lambda/gui/component/Scroll.kt | 60 ++++--- .../com/lambda/gui/component/Surface.kt | 124 ++++++------- .../kotlin/com/lambda/gui/component/Text.kt | 7 +- .../com/lambda/gui/component/TextInput.kt | 5 +- .../kotlin/com/lambda/gui/core/GlState.kt | 20 ++- .../com/lambda/gui/core/RenderThread.kt | 9 +- .../kotlin/com/lambda/gui/core/SceneHost.kt | 56 +++--- .../kotlin/com/lambda/gui/core/SceneInput.kt | 120 +++++++------ .../com/lambda/gui/core/ScenePlatform.kt | 60 ++++--- .../kotlin/com/lambda/gui/hud/HudEditor.kt | 65 +++---- .../kotlin/com/lambda/gui/menu/Dialogs.kt | 51 +++--- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 11 +- src/main/kotlin/com/lambda/gui/menu/Search.kt | 41 ++--- .../com/lambda/gui/render/BlurPyramid.kt | 20 ++- .../com/lambda/gui/render/GuiCompositor.kt | 26 +-- .../kotlin/com/lambda/gui/render/ItemAtlas.kt | 35 ++-- .../lambda/gui/settings/CollectionEditor.kt | 7 +- .../com/lambda/gui/settings/ModuleSettings.kt | 60 ++++--- .../com/lambda/gui/settings/SettingRow.kt | 13 +- .../com/lambda/gui/settings/SettingsList.kt | 9 +- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 40 +++-- .../module/modules/client/AutoUpdater.kt | 18 +- .../com/lambda/module/modules/client/Style.kt | 52 +++--- 39 files changed, 859 insertions(+), 765 deletions(-) diff --git a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java index 49e94071a..00da2bbe4 100644 --- a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java +++ b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java @@ -34,7 +34,7 @@ public class KeyboardMixin { @WrapMethod(method = "onKey") private void onKey(long window, int action, KeyInput input, Operation original) { - EventFlow.post(new ButtonEvent.Keyboard.Press(input.key(), input.scancode(), action, input.modifiers())); + if (EventFlow.post(new ButtonEvent.Keyboard.Press(input.key(), input.scancode(), action, input.modifiers())).isCanceled()) return; original.call(window, action, input); int key = input.key(); if (!InventoryMove.isKeyMovementRelated(key)) return; diff --git a/src/main/kotlin/com/lambda/Lambda.kt b/src/main/kotlin/com/lambda/Lambda.kt index b448ec2ce..69dd1e6c9 100644 --- a/src/main/kotlin/com/lambda/Lambda.kt +++ b/src/main/kotlin/com/lambda/Lambda.kt @@ -49,9 +49,10 @@ 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) diff --git a/src/main/kotlin/com/lambda/config/EntryLayer.kt b/src/main/kotlin/com/lambda/config/EntryLayer.kt index a2bd1267b..9fb7d6e4e 100644 --- a/src/main/kotlin/com/lambda/config/EntryLayer.kt +++ b/src/main/kotlin/com/lambda/config/EntryLayer.kt @@ -105,11 +105,12 @@ sealed class ConfigBlockLayer { } } -fun EntryLayer>.holds(setting: Setting<*>): Boolean = when (this) { - is EntryLayer.Single -> entry === setting - is EntryLayer.Multiple -> layers.any { it.holds(setting) } - else -> false -} +fun EntryLayer>.holds(setting: Setting<*>): Boolean = + when (this) { + is EntryLayer.Single -> entry === setting + is EntryLayer.Multiple -> layers.any { it.holds(setting) } + else -> false + } fun EntryLayer.Multiple>.hasVisibleSettings(): Boolean = layers.any { diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index f3ee50cca..cff1f9aff 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -110,11 +110,12 @@ abstract class NumericSetting( return if (span > 0 && !fraction.isNaN()) fraction.coerceIn(0f, 1f) else 0f } - private fun at(fraction: Float): T = when { - fraction <= 0f -> range.start - fraction >= 1f -> range.endInclusive - else -> onGrid(lowest + (highest - lowest) * fraction.toBigDecimal(), RoundingMode.HALF_UP) - } + private fun at(fraction: Float): T = + when { + fraction <= 0f -> range.start + fraction >= 1f -> range.endInclusive + else -> onGrid(lowest + (highest - lowest) * fraction.toBigDecimal(), RoundingMode.HALF_UP) + } private fun stepped(by: Int): T = onGrid(value.decimal, if (by < 0) RoundingMode.CEILING else RoundingMode.FLOOR, by) 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 c27214579..efc8633ae 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -25,10 +25,8 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect 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 @@ -52,7 +50,6 @@ 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.GuiScreen import com.lambda.gui.component.Text import com.lambda.gui.component.Tooltip import com.lambda.gui.component.mouseClickable @@ -66,12 +63,15 @@ 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 import org.lwjgl.glfw.GLFW.GLFW_MOD_NUM_LOCK import org.lwjgl.glfw.GLFW.GLFW_MOD_SHIFT import org.lwjgl.glfw.GLFW.GLFW_MOD_SUPER +import org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_LEFT class KeybindSetting( name: String, @@ -107,8 +107,12 @@ class KeybindSetting( get() = muteable?.isMuted == true && !alwaysListening init { - listenUnsafe { event -> onButtonEvent(event) } - listenUnsafe { event -> onButtonEvent(event) } + listenUnsafe(alwaysListen = true) { event -> + if (recorder === this) record(event) else if (!isMuted) onButtonEvent(event) + } + listenUnsafe(alwaysListen = true) { event -> + if (recorder === this) record(event) else if (!isMuted) onButtonEvent(event) + } } private fun onButtonEvent(event: ButtonEvent) { @@ -134,10 +138,7 @@ class KeybindSetting( override fun Editor() { val colors = LambdaTheme.colors val bind by observe { value } - var recording by remember { mutableStateOf(false) } - DisposableEffect(Unit) { - onDispose { if (recording) GuiScreen.keybindRecorder = null } - } + val recording = recorder === this Labeled(name) { Tooltip("Click, then press a key or mouse button. Backspace unbinds, Escape cancels.") { @@ -147,13 +148,7 @@ class KeybindSetting( .height(Look.rowHeight) .clip(RoundedCornerShape(Look.controlRounding)) .background(if (recording) colors.secondary else colors.control) - .mouseClickable { - recording = true - GuiScreen.keybindRecorder = { recorded -> - recorded?.let { value = it } - recording = false - } - } + .mouseClickable { recorder = this@KeybindSetting } .padding(horizontal = 4.dp) ) { Text( @@ -166,6 +161,37 @@ class KeybindSetting( } } + private fun record(event: ButtonEvent.Keyboard.Press) { + event.cancel() + val isModifier = event.keyCode in GLFW_KEY_LEFT_SHIFT..GLFW_KEY_RIGHT_SUPER + if (event.isRepeated || event.isPressed == isModifier) return + when (val key = event.translated) { + KeyCode.Unbound -> return + KeyCode.Escape -> Unit + KeyCode.Backspace, KeyCode.Delete -> value = Bind.EMPTY + else -> value = Bind(key.code, if (isModifier) 0 else event.modifiers, -1) + } + recorder = null + } + + private fun record(event: ButtonEvent.Mouse.Click) { + if (!event.isPressed) return + recorder = null + if (event.button == GLFW_MOUSE_BUTTON_LEFT) return + event.cancel() + value = Bind(0, event.modifiers, event.button) + } + + companion object { + private var recorder: KeybindSetting? by mutableStateOf(null) + + internal val isRecording get() = recorder != null + + internal fun stopRecording() { + recorder = null + } + } + override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(word(name)) { nameArg -> suggests { _, builder -> diff --git a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt index 09d8a0552..6eeff19c9 100644 --- a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt +++ b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt @@ -325,32 +325,36 @@ object LambdaRenderPipelines : Loadable { .build() ) - val GUI_BLIT = guiPass( - "gui_blit", - Identifier.ofVanilla("core/blit_screen"), - samplers = listOf("InSampler"), - blend = BlendFunction.TRANSLUCENT_PREMULTIPLIED_ALPHA - ) + val GUI_BLIT = + guiPass( + "gui_blit", + Identifier.ofVanilla("core/blit_screen"), + samplers = listOf("InSampler"), + blend = BlendFunction.TRANSLUCENT_PREMULTIPLIED_ALPHA + ) - val GUI_COMPOSITE = guiPass( - "gui_composite", - Identifier.of("lambda", "core/gui_composite"), - samplers = listOf("GuiSampler", "BackdropSampler", "HaloSampler"), - uniform = "GuiEffects", - blend = BlendFunction.TRANSLUCENT_PREMULTIPLIED_ALPHA - ) + val GUI_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_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" - ) + 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/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index 04143135f..a8e2097f4 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -86,9 +86,10 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { return decoded } set(value) { - windowPlacements = value.entries.joinToString(";") { (tag, window) -> - "$tag:${window.x},${window.y},${window.collapsed}" - } + windowPlacements = + value.entries.joinToString(";") { (tag, window) -> + "$tag:${window.x},${window.y},${window.collapsed}" + } } internal fun resetWindows() { diff --git a/src/main/kotlin/com/lambda/gui/GuiScreen.kt b/src/main/kotlin/com/lambda/gui/GuiScreen.kt index 2d2f24c01..3145c367c 100644 --- a/src/main/kotlin/com/lambda/gui/GuiScreen.kt +++ b/src/main/kotlin/com/lambda/gui/GuiScreen.kt @@ -19,13 +19,11 @@ 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.config.settings.complex.KeybindSetting import com.lambda.gui.clickgui.ClickGuiState 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 @@ -41,13 +39,12 @@ import org.lwjgl.glfw.GLFW object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { private var parent: Screen? = null - internal var keybindRecorder: ((Bind?) -> Unit)? = null - - private val backgroundScreens = listOf( - TitleScreen::class.java, - MultiplayerScreen::class.java, - AutoDisconnectScreen::class.java, - ) + private val backgroundScreens = + listOf( + TitleScreen::class.java, + MultiplayerScreen::class.java, + AutoDisconnectScreen::class.java, + ) fun canOpenOver(screen: Screen?) = screen == null || backgroundScreens.any { it.isInstance(screen) } @@ -64,8 +61,7 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { } override fun removed() { - keybindRecorder?.invoke(null) - keybindRecorder = null + KeybindSetting.stopRecording() LambdaGui.onScreenRemoved() } @@ -98,14 +94,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { } 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 - } - record(null) - } val position = scenePosition(click.x(), click.y()) TextFocus.press(position) LambdaGui.input?.run { @@ -129,7 +117,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { } 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.key() == GLFW.GLFW_KEY_F && input.modifiers() and GLFW.GLFW_MOD_CONTROL != 0) { ClickGuiState.focusSearch = LambdaGui.screen == LambdaGui.Screen.ClickGui @@ -140,7 +127,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { } override fun keyReleased(input: KeyInput): Boolean { - if (recordKey(input, pressed = false)) return true LambdaGui.input?.key(input.key(), false, input.modifiers()) return true } @@ -150,25 +136,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { return true } - 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 - else -> Bind(key.code, if (isModifier) 0 else input.modifiers(), -1) - } - ) - keybindRecorder = null - return true - } - private fun scenePosition(x: Double, y: Double): Offset { val scale = mc.window.scaleFactor return Offset((x * scale).toFloat(), (y * scale).toFloat()) diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index 871a14e30..c0c6ebd39 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -26,6 +26,7 @@ import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.unit.IntSize import com.lambda.Lambda.LOG import com.lambda.Lambda.mc +import com.lambda.config.settings.complex.KeybindSetting import com.lambda.core.Loadable import com.lambda.event.events.ClientEvent import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe @@ -87,7 +88,7 @@ object LambdaGui : Loadable { internal val cursor: Cursor? get() = host?.platform?.cursor internal var onEscape: (() -> Boolean)? = null - val isCapturingKeys get() = TextFocus.isTyping || GuiScreen.keybindRecorder != null + val isCapturingKeys get() = TextFocus.isTyping || KeybindSetting.isRecording init { listenUnsafe { close() } @@ -106,7 +107,8 @@ object LambdaGui : Loadable { fun toggle() { if (isCapturingKeys) return - if (screen == null) open(Screen.ClickGui) else GuiScreen.close() + if (screen == null) open(Screen.ClickGui) + else GuiScreen.close() } fun open(screen: Screen) { @@ -235,16 +237,18 @@ object LambdaGui : Loadable { SettingsList(Style.settingLayers) } - 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 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() diff --git a/src/main/kotlin/com/lambda/gui/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt index cb4c6efc2..f0ed2d349 100644 --- a/src/main/kotlin/com/lambda/gui/Snap.kt +++ b/src/main/kotlin/com/lambda/gui/Snap.kt @@ -55,62 +55,66 @@ internal object Snap { fun free(element: Rect, area: Rect) = Result(element.topLeft.keptIn(area, element.size), Guides.NONE) - fun snap(element: Rect, others: Collection, area: Rect, density: Density, spacing: Float = 0f): Result = with(density) { - fun axis(start: (Rect) -> Float, end: (Rect) -> Float): Target { - fun center(rect: Rect) = (start(rect) + end(rect)) / 2 - val from = start(element) - val size = end(element) - from - fun startAt(at: Float, guide: Float? = at) = Target(at - from, guide) - fun endAt(at: Float, guide: Float? = at) = Target(at - size - from, guide) - fun centerAt(at: Float, guide: Float? = at) = Target(at - size / 2 - from, guide) - - val neighbours = buildList { - if (GuiConfig.snapToEdges) { - add(startAt(start(area))) - add(endAt(end(area))) - others.forEach { other -> - add(startAt(start(other))) - add(endAt(end(other))) - add(startAt(end(other) + spacing, end(other) + spacing / 2)) - add(endAt(start(other) - spacing, start(other) - spacing / 2)) + fun snap(element: Rect, others: Collection, area: Rect, density: Density, spacing: Float = 0f): Result = + with(density) { + fun axis(start: (Rect) -> Float, end: (Rect) -> Float): Target { + fun center(rect: Rect) = (start(rect) + end(rect)) / 2 + val from = start(element) + val size = end(element) - from + fun startAt(at: Float, guide: Float? = at) = Target(at - from, guide) + fun endAt(at: Float, guide: Float? = at) = Target(at - size - from, guide) + fun centerAt(at: Float, guide: Float? = at) = Target(at - size / 2 - from, guide) + + val neighbours = + buildList { + if (GuiConfig.snapToEdges) { + add(startAt(start(area))) + add(endAt(end(area))) + others.forEach { other -> + add(startAt(start(other))) + add(endAt(end(other))) + add(startAt(end(other) + spacing, end(other) + spacing / 2)) + add(endAt(start(other) - spacing, start(other) - spacing / 2)) + } + } + if (GuiConfig.snapToCenters) others.forEach { add(centerAt(center(it))) } } - } - if (GuiConfig.snapToCenters) others.forEach { add(centerAt(center(it))) } + val middle = center(area) + val screenCenter = listOf(startAt(middle), centerAt(middle), endAt(middle)).takeIf { GuiConfig.snapToScreenCenter }.orEmpty() + val step = gridStep(density) + fun onGrid(line: Float) = (line / step).roundToInt() * step + val grid = + listOf( + startAt(onGrid(from), null), + centerAt(onGrid(from + size / 2), null), + endAt(onGrid(from + size), null), + ).takeIf { GuiConfig.snapToGrid }.orEmpty() + + return listOf( + neighbours to GuiConfig.snapDistanceElement.dp.toPx(), + screenCenter to GuiConfig.snapDistanceScreen.dp.toPx(), + grid to GuiConfig.snapDistanceGrid.dp.toPx(), + ).firstNotNullOfOrNull { (targets, reach) -> + targets.minByOrNull { abs(it.shift) }?.takeIf { abs(it.shift) <= reach } + } ?: Target(0f, null) } - val middle = center(area) - val screenCenter = listOf(startAt(middle), centerAt(middle), endAt(middle)).takeIf { GuiConfig.snapToScreenCenter }.orEmpty() - val step = gridStep(density) - fun onGrid(line: Float) = (line / step).roundToInt() * step - val grid = listOf( - startAt(onGrid(from), null), - centerAt(onGrid(from + size / 2), null), - endAt(onGrid(from + size), null), - ).takeIf { GuiConfig.snapToGrid }.orEmpty() - - return listOf( - neighbours to GuiConfig.snapDistanceElement.dp.toPx(), - screenCenter to GuiConfig.snapDistanceScreen.dp.toPx(), - grid to GuiConfig.snapDistanceGrid.dp.toPx(), - ).firstNotNullOfOrNull { (targets, reach) -> - targets.minByOrNull { abs(it.shift) }?.takeIf { abs(it.shift) <= reach } - } ?: Target(0f, null) - } - val x = axis({ it.left }, { it.right }) - val y = axis({ it.top }, { it.bottom }) - Result((element.topLeft + Offset(x.shift, y.shift)).keptIn(area, element.size), Guides(x.guide, y.guide)) - } + val x = axis({ it.left }, { it.right }) + val y = axis({ it.top }, { it.bottom }) + Result((element.topLeft + Offset(x.shift, y.shift)).keptIn(area, element.size), Guides(x.guide, y.guide)) + } - fun Modifier.snapLines(drop: () -> Result?): Modifier = drawWithContent { - val guides = drop()?.guides.takeIf { GuiConfig.showSnapLines } - if (guides != null && isActive && GuiConfig.snapToGrid) drawGrid() - drawContent() - if (guides != null) { - val color = GuiConfig.snapLineColor.toCompose() - guides.x?.let { drawLine(color, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } - guides.y?.let { drawLine(color, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } + fun Modifier.snapLines(drop: () -> Result?): Modifier = + drawWithContent { + val guides = drop()?.guides.takeIf { GuiConfig.showSnapLines } + if (guides != null && isActive && GuiConfig.snapToGrid) drawGrid() + drawContent() + if (guides != null) { + val color = GuiConfig.snapLineColor.toCompose() + guides.x?.let { drawLine(color, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } + guides.y?.let { drawLine(color, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } + } } - } private fun DrawScope.drawGrid() { val step = gridStep(this) @@ -120,8 +124,9 @@ internal object Snap { .forEach { drawLine(GRID_COLOR, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } } - private fun Offset.keptIn(area: Rect, element: Size) = Offset( - x.coerceIn(area.left, max(area.left, area.right - element.width)), - y.coerceIn(area.top, max(area.top, area.bottom - element.height)) - ) + private fun Offset.keptIn(area: Rect, element: Size) = + Offset( + x.coerceIn(area.left, max(area.left, area.right - element.width)), + y.coerceIn(area.top, max(area.top, area.bottom - element.height)) + ) } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index 8ec881334..fb4c6478b 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -116,21 +116,23 @@ internal fun CategoryWindow( val collapsed = placement?.collapsed ?: false var dragged by remember { mutableStateOf(null) } - val drop = dragged?.let { corner -> - val window = Rect(corner, bounds[tag]?.size ?: Size.Zero) - if (snapping) Snap.snap(window, bounds.filterKeys { it != tag }.values, area, density, with(density) { Look.windowGap.toPx() }) - else Snap.free(window, area) - } + val drop = + dragged?.let { corner -> + val window = Rect(corner, bounds[tag]?.size ?: Size.Zero) + if (snapping) Snap.snap(window, bounds.filterKeys { it != tag }.values, area, density, with(density) { Look.windowGap.toPx() }) + else Snap.free(window, area) + } if (drop != null) SideEffect { onDrop(drop) } - val shownPosition = drop?.let { - with(density) { DpOffset(it.position.x.toDp(), it.position.y.toDp()) } - } ?: (position ?: defaultPosition).let { at -> - val screenWidth = with(density) { screen.width.toDp() } - DpOffset( - at.x.coerceIn(0.dp, (screenWidth - Look.windowWidth).coerceAtLeast(0.dp)), - at.y.coerceIn(MENU_BAR_HEIGHT, (screenHeight - REACH).coerceAtLeast(MENU_BAR_HEIGHT)), - ) - } + val shownPosition = + drop?.let { + with(density) { DpOffset(it.position.x.toDp(), it.position.y.toDp()) } + } ?: (position ?: defaultPosition).let { at -> + val screenWidth = with(density) { screen.width.toDp() } + DpOffset( + at.x.coerceIn(0.dp, (screenWidth - Look.windowWidth).coerceAtLeast(0.dp)), + at.y.coerceIn(MENU_BAR_HEIGHT, (screenHeight - REACH).coerceAtLeast(MENU_BAR_HEIGHT)), + ) + } val currentPosition by rememberUpdatedState(shownPosition) DisposableEffect(tag) { onDispose { bounds -= tag } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index 9a2b65162..f270e1d02 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -120,9 +120,10 @@ internal fun ClickGui() { Box(Modifier.fillMaxSize().mouseClickable(keyboard = false, onClick = settings::closeAll).snapLines { drop }) { val inRow = tags.count { it != ModuleTag.DEBUG } val screenWidth = with(density) { screen.width.toDp() } - val pitch = (Look.windowWidth + Look.windowGap) - .coerceAtMost((screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1)) - .coerceAtLeast(0.dp) + val pitch = + (Look.windowWidth + Look.windowGap) + .coerceAtMost((screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1)) + .coerceAtLeast(0.dp) val rowWidth = Look.windowWidth + pitch * (inRow - 1) val rowStart = ((screenWidth - rowWidth) / 2).coerceAtLeast(0.dp) diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index 75070fc46..d3c15f71b 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -126,8 +126,9 @@ internal fun SettingsPanel( val screenHeight = with(density) { screen.height.toDp() } val barBottom = with(density) { MENU_BAR_HEIGHT.toPx() } val window = windows[panel.module.tag] - val top = (if (window == null) row.top else row.top.coerceIn(window.top, (window.bottom - row.height).coerceAtLeast(window.top))) - .coerceAtLeast(barBottom) + val top = + (if (window == null) row.top else row.top.coerceIn(window.top, (window.bottom - row.height).coerceAtLeast(window.top))) + .coerceAtLeast(barBottom) val below = with(density) { (screen.height - top).toDp() }.coerceAtLeast(MIN_HEIGHT) val highest = screenHeight - MENU_BAR_HEIGHT val maxHeight = (below + panel.extension).coerceAtMost(highest) @@ -138,12 +139,13 @@ internal fun SettingsPanel( val flipped = !fitsRight && (fitsLeft || row.left > screen.width - row.right) val lift = (top + unfolded - screen.height).coerceIn(0f, top - barBottom) - val shape = RoundedCornerShape( - topStart = if (flipped || lift > 0f) Look.panelRounding else 0.dp, - topEnd = if (!flipped || lift > 0f) Look.panelRounding else 0.dp, - bottomEnd = Look.panelRounding, - bottomStart = Look.panelRounding, - ) + val shape = + RoundedCornerShape( + topStart = if (flipped || lift > 0f) Look.panelRounding else 0.dp, + topEnd = if (!flipped || lift > 0f) Look.panelRounding else 0.dp, + bottomEnd = Look.panelRounding, + bottomStart = Look.panelRounding, + ) val seam = if (flipped) Alignment.TopEnd else Alignment.TopStart Box( @@ -230,19 +232,21 @@ internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { } } -private fun Modifier.widthOfContent(): Modifier = composed { - val scope = rememberCoroutineScope() - var width by remember { mutableStateOf?>(null) } - layout { measurable, constraints -> - val wanted = measurable.maxIntrinsicWidth(constraints.maxHeight) - .coerceIn(constraints.minWidth, constraints.maxWidth).toFloat() - val current = width ?: Animatable(wanted).also { width = it } - if (current.targetValue != wanted) scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } +private fun Modifier.widthOfContent(): Modifier = + composed { + val scope = rememberCoroutineScope() + var width by remember { mutableStateOf?>(null) } + layout { measurable, constraints -> + val wanted = + measurable.maxIntrinsicWidth(constraints.maxHeight) + .coerceIn(constraints.minWidth, constraints.maxWidth).toFloat() + val current = width ?: Animatable(wanted).also { width = it } + if (current.targetValue != wanted) scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } - val placeable = measurable.measure(Constraints.fixedWidth(current.value.roundToInt()).copy(maxHeight = constraints.maxHeight)) - layout(placeable.width, placeable.height) { placeable.place(0, 0) } + val placeable = measurable.measure(Constraints.fixedWidth(current.value.roundToInt()).copy(maxHeight = constraints.maxHeight)) + layout(placeable.width, placeable.height) { placeable.place(0, 0) } + } } -} @Composable private fun Grip(onDragStart: () -> Unit, onDrag: (up: Dp) -> Unit, modifier: Modifier = Modifier) { diff --git a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt index 5441d4b7b..fab65bc8c 100644 --- a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt +++ b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt @@ -64,21 +64,22 @@ internal object KeyboardFocus { } } -fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = composed { - if (!LocalKeyboardReachable.current) return@composed Modifier - var focused by remember { mutableStateOf(false) } - val handle by rememberUpdatedState(onKey) - val mark = LambdaTheme.colors.onSurface - onFocusChanged { focused = it.isFocused } - .onKeyEvent { it.type == KeyEventType.KeyDown && KeyboardFocus.visible && handle(it) } - .focusable() - .drawWithContent { - drawContent() - if (!focused || !KeyboardFocus.visible) return@drawWithContent - val width = FOCUS_MARK.toPx() - drawRect(mark, Offset(width / 2, width / 2), Size(size.width - width, size.height - width), style = Stroke(width)) - } -} +fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = + composed { + if (!LocalKeyboardReachable.current) return@composed Modifier + var focused by remember { mutableStateOf(false) } + val handle by rememberUpdatedState(onKey) + val mark = LambdaTheme.colors.onSurface + onFocusChanged { focused = it.isFocused } + .onKeyEvent { it.type == KeyEventType.KeyDown && KeyboardFocus.visible && handle(it) } + .focusable() + .drawWithContent { + drawContent() + if (!focused || !KeyboardFocus.visible) return@drawWithContent + val width = FOCUS_MARK.toPx() + drawRect(mark, Offset(width / 2, width / 2), Size(size.width - width, size.height - width), style = Stroke(width)) + } + } val LocalKeyboardReachable = compositionLocalOf { true } diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt index a5f8fa3a5..7f1aa9479 100644 --- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -59,11 +59,12 @@ fun Modifier.mouseClickable( else -> null } } - val keys = if (!keyboard) Modifier else Modifier.keyboardFocusable { event -> - val action = if (event.isShiftPressed) onRightClick else onClick ?: onRightClick - if (event.isActivation) action?.invoke() - event.isActivation && action != null - } + val keys = + if (!keyboard) Modifier else Modifier.keyboardFocusable { event -> + val action = if (event.isShiftPressed) onRightClick else onClick ?: onRightClick + if (event.isActivation) action?.invoke() + event.isActivation && action != null + } keys.pointerInput(onRelease) { awaitPointerEventScope { while (true) { @@ -101,61 +102,66 @@ fun Modifier.onMousePress(button: PointerButton, onPress: (position: Offset) -> } @OptIn(ExperimentalComposeUiApi::class) -private fun Modifier.onPress(handle: (button: PointerButton?, position: Offset) -> Boolean): Modifier = composed { - val currentHandle by rememberUpdatedState(handle) +private fun Modifier.onPress(handle: (button: PointerButton?, position: Offset) -> Boolean): Modifier = + composed { + val currentHandle by rememberUpdatedState(handle) + pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.first() + if (event.type != PointerEventType.Press || change.isConsumed) continue + if (currentHandle(event.button, change.position)) change.consume() + } + } + } + } + +fun Modifier.consumeClicks(): Modifier = pointerInput(Unit) { awaitPointerEventScope { while (true) { val event = awaitPointerEvent() - val change = event.changes.first() - if (event.type != PointerEventType.Press || change.isConsumed) continue - if (currentHandle(event.button, change.position)) change.consume() + if (event.type == PointerEventType.Press) event.changes.forEach { it.consume() } } } } -} - -fun Modifier.consumeClicks(): Modifier = pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent() - if (event.type == PointerEventType.Press) event.changes.forEach { it.consume() } - } - } -} @OptIn(ExperimentalFoundationApi::class) fun Modifier.mouseDraggable( onDragStart: () -> Unit = {}, onDragEnd: () -> Unit = {}, onDrag: (Offset) -> Unit, -): Modifier = onDrag( - matcher = PointerMatcher.mouse(PointerButton.Primary), - onDragStart = { onDragStart() }, - onDragCancel = onDragEnd, - onDragEnd = onDragEnd, - onDrag = onDrag, -) +): Modifier = + onDrag( + matcher = PointerMatcher.mouse(PointerButton.Primary), + onDragStart = { onDragStart() }, + onDragCancel = onDragEnd, + onDragEnd = onDragEnd, + onDrag = onDrag, + ) -fun Modifier.scrubbable(onEnd: () -> Unit = {}, onScrub: (position: Offset, size: IntSize) -> Unit): Modifier = composed { - val currentOnScrub by rememberUpdatedState(onScrub) - val currentOnEnd by rememberUpdatedState(onEnd) - pointerInput(Unit) { - awaitEachGesture { - val down = awaitFirstDown() - down.consume() - currentOnScrub(down.position, size) - drag(down.id) { change -> - change.consume() - currentOnScrub(change.position, size) +fun Modifier.scrubbable(onEnd: () -> Unit = {}, onScrub: (position: Offset, size: IntSize) -> Unit): Modifier = + composed { + val currentOnScrub by rememberUpdatedState(onScrub) + val currentOnEnd by rememberUpdatedState(onEnd) + pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown() + down.consume() + currentOnScrub(down.position, size) + drag(down.id) { change -> + change.consume() + currentOnScrub(change.position, size) + } + currentOnEnd() } - currentOnEnd() } } -} -fun Modifier.hoverHighlight(color: Color): Modifier = composed { - val interactions = remember { MutableInteractionSource() } - val hovered by interactions.collectIsHoveredAsState() - hoverable(interactions).background(if (hovered) color else Color.Transparent) -} +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 index 616442b4b..11e308a06 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -101,15 +101,16 @@ import com.lambda.module.modules.client.Style import kotlin.math.max @OptIn(ExperimentalComposeUiApi::class) -private val FLOATING = PopupProperties( - focusable = true, - dismissOnBackPress = true, - dismissOnClickOutside = true, - clippingEnabled = true, - usePlatformDefaultWidth = false, - usePlatformInsets = true, - consumePointerInputOutside = false, -) +private val FLOATING = + PopupProperties( + focusable = true, + dismissOnBackPress = true, + dismissOnClickOutside = true, + clippingEnabled = true, + usePlatformDefaultWidth = false, + usePlatformInsets = true, + consumePointerInputOutside = false, + ) private val SLACK = 4.dp @@ -120,9 +121,10 @@ private fun ScenePopup( properties: PopupProperties = PopupProperties(), onKeyEvent: ((KeyEvent) -> Boolean)? = null, content: @Composable () -> Unit, -) = Popup(popupPositionProvider, onDismissRequest, properties, onKeyEvent = onKeyEvent) { - CompositionLocalProvider(LocalClipboard provides GameClipboard, content = content) -} +) = + Popup(popupPositionProvider, onDismissRequest, properties, onKeyEvent = onKeyEvent) { + CompositionLocalProvider(LocalClipboard provides GameClipboard, content = content) + } enum class MenuPlacement { Below, @@ -158,16 +160,19 @@ fun Menu( MenuPopup(open, remember(placement) { UnfoldingPosition(placement::place) }, onDismiss, unfoldFrom, attached, content) } -private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize) = when (this) { - MenuPlacement.Below -> IntOffset( - anchor.left, - if (anchor.bottom + popup.height <= window.height || anchor.top - popup.height < 0) anchor.bottom else anchor.top - popup.height - ) - MenuPlacement.Beside -> IntOffset( - if (anchor.right + popup.width <= window.width) anchor.right else anchor.left - popup.width, - anchor.top - ) -} +private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize) = + when (this) { + MenuPlacement.Below -> + IntOffset( + anchor.left, + if (anchor.bottom + popup.height <= window.height || anchor.top - popup.height < 0) anchor.bottom else anchor.top - popup.height + ) + MenuPlacement.Beside -> + IntOffset( + if (anchor.right + popup.width <= window.width) anchor.right else anchor.left - popup.width, + anchor.top + ) + } @Composable fun Popout(open: Boolean, onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { @@ -208,11 +213,12 @@ private fun MenuPopup( val open = open && LocalMenuOpen.current val dismissAll = LocalMenuDismiss.current ?: onDismiss val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } - val shape = when { - !attached -> RoundedCornerShape(Look.menuRounding) - position.upwards -> RoundedCornerShape(topStart = Look.menuRounding, topEnd = Look.menuRounding) - else -> RoundedCornerShape(bottomStart = Look.menuRounding, bottomEnd = Look.menuRounding) - } + val shape = + when { + !attached -> RoundedCornerShape(Look.menuRounding) + position.upwards -> RoundedCornerShape(topStart = Look.menuRounding, topEnd = Look.menuRounding) + else -> RoundedCornerShape(bottomStart = Look.menuRounding, bottomEnd = Look.menuRounding) + } FloatingPanel(open, position, onDismiss, shape, unfoldFrom) { panel -> CompositionLocalProvider(LocalMenuDismiss provides dismissAll, LocalMenuOpen provides open) { ScrollColumn( @@ -245,34 +251,37 @@ class PopupHost { val LocalPopupHost = compositionLocalOf { null } -private fun Modifier.swallowedBy(host: PopupHost?): Modifier = if (host == null) this else composed { - var origin by remember { mutableStateOf(Offset.Zero) } - onGloballyPositioned { origin = it.positionInWindow() }.drawWithContent { - if (!host.closing) return@drawWithContent drawContent() - val full = host.full - val left = host.bounds - val slack = SLACK.toPx() - val dx = when { - origin.x >= full.right - slack -> left.right - full.right - origin.x + size.width <= full.left + slack -> left.left - full.left - else -> null - } - val dy = when { - origin.y >= full.bottom - slack -> left.bottom - full.bottom - origin.y + size.height <= full.top + slack -> left.top - full.top - else -> null - } - val far = 10_000f - clipRect( - if (dx == null) left.left - origin.x else -far, - if (dy == null) left.top - origin.y else -far, - if (dx == null) left.right - origin.x else far, - if (dy == null) left.bottom - origin.y else far, - ) { - translate(dx ?: 0f, dy ?: 0f) { this@drawWithContent.drawContent() } +private fun Modifier.swallowedBy(host: PopupHost?): Modifier = + if (host == null) this else composed { + var origin by remember { mutableStateOf(Offset.Zero) } + onGloballyPositioned { origin = it.positionInWindow() }.drawWithContent { + if (!host.closing) return@drawWithContent drawContent() + val full = host.full + val left = host.bounds + val slack = SLACK.toPx() + val dx = + when { + origin.x >= full.right - slack -> left.right - full.right + origin.x + size.width <= full.left + slack -> left.left - full.left + else -> null + } + val dy = + when { + origin.y >= full.bottom - slack -> left.bottom - full.bottom + origin.y + size.height <= full.top + slack -> left.top - full.top + else -> null + } + val far = 10_000f + clipRect( + if (dx == null) left.left - origin.x else -far, + if (dy == null) left.top - origin.y else -far, + if (dx == null) left.right - origin.x else far, + if (dy == null) left.bottom - origin.y else far, + ) { + translate(dx ?: 0f, dy ?: 0f) { this@drawWithContent.drawContent() } + } } } -} @Composable private fun FloatingPanel( @@ -333,10 +342,11 @@ private class UnfoldingPosition( private set val corner - get() = when { - upwards -> if (leftwards) Alignment.BottomEnd else Alignment.BottomStart - else -> if (leftwards) Alignment.TopEnd else Alignment.TopStart - } + get() = + when { + upwards -> if (leftwards) Alignment.BottomEnd else Alignment.BottomStart + else -> if (leftwards) Alignment.TopEnd else Alignment.TopStart + } override fun calculatePosition( anchorBounds: IntRect, @@ -427,11 +437,12 @@ fun MenuItem( .padding(horizontal = 5.dp, vertical = 1.dp) ) { if (checked != null) Checkmark(checked, Modifier.padding(end = 3.dp)) - val color = when { - !enabled -> colors.onSurfaceVariant - selected -> colors.secondary - else -> colors.onSurface - } + val color = + when { + !enabled -> colors.onSurfaceVariant + selected -> colors.secondary + else -> colors.onSurface + } Text(label, Modifier.weight(1f), color, maxLines = 1) if (hint != null) Text(hint, Modifier.padding(start = 12.dp), colors.onSurfaceVariant, Type.label, maxLines = 1) } @@ -478,13 +489,14 @@ fun MenuHelp(text: String, label: String = "Help") { } @Composable -fun MenuDivider() = Spacer( - Modifier - .fillMaxWidth() - .padding(horizontal = 3.dp, vertical = 1.dp) - .height(1.dp) - .background(LambdaTheme.colors.border) -) +fun MenuDivider() = + Spacer( + Modifier + .fillMaxWidth() + .padding(horizontal = 3.dp, vertical = 1.dp) + .height(1.dp) + .background(LambdaTheme.colors.border) + ) @Composable fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { @@ -591,13 +603,14 @@ private fun KeyEvent.dismissOnEscape(onDismiss: () -> Unit): Boolean { 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) -} +) = + object : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ) = position(anchorBounds, windowSize, popupContentSize) + } private fun IntSize.coerceAtMost(other: IntSize) = IntSize(minOf(width, other.width), minOf(height, other.height)) diff --git a/src/main/kotlin/com/lambda/gui/component/Scroll.kt b/src/main/kotlin/com/lambda/gui/component/Scroll.kt index a831d029a..a52b87a4f 100644 --- a/src/main/kotlin/com/lambda/gui/component/Scroll.kt +++ b/src/main/kotlin/com/lambda/gui/component/Scroll.kt @@ -86,42 +86,44 @@ fun Scrollbar(adapter: ScrollbarAdapter, modifier: Modifier) { } } -fun Modifier.wheelScrollable(state: ScrollableState): Modifier = composed { - val scope = rememberCoroutineScope() - val notch = with(LocalDensity.current) { WHEEL_STEP.toPx() } - val glide = remember { WheelGlide() } - pointerInput(state, notch) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent(PointerEventPass.Initial) - if (event.type != PointerEventType.Scroll) continue - val change = event.changes.first() - val distance = change.scrollDelta.y * notch * Style.scrollSpeed - val canFollow = if (distance > 0) state.canScrollForward else state.canScrollBackward - if (distance == 0f || !canFollow || change.isConsumed) continue - change.consume() +fun Modifier.wheelScrollable(state: ScrollableState): Modifier = + composed { + val scope = rememberCoroutineScope() + val notch = with(LocalDensity.current) { WHEEL_STEP.toPx() } + val glide = remember { WheelGlide() } + pointerInput(state, notch) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type != PointerEventType.Scroll) continue + val change = event.changes.first() + val distance = change.scrollDelta.y * notch * Style.scrollSpeed + val canFollow = if (distance > 0) state.canScrollForward else state.canScrollBackward + if (distance == 0f || !canFollow || change.isConsumed) continue + change.consume() - val total = distance + if (glide.remaining * distance > 0) glide.remaining else 0f - glide.job?.cancel() - glide.job = scope.launch(Motion.SCROLL) { - var travelled = 0f - glide.remaining = total - try { - state.scroll(MutatePriority.UserInput) { - animate(0f, total, animationSpec = GLIDE) { value, _ -> - scrollBy(value - travelled) - travelled = value - glide.remaining = total - value + val total = distance + if (glide.remaining * distance > 0) glide.remaining else 0f + glide.job?.cancel() + glide.job = + scope.launch(Motion.SCROLL) { + var travelled = 0f + glide.remaining = total + try { + state.scroll(MutatePriority.UserInput) { + animate(0f, total, animationSpec = GLIDE) { value, _ -> + scrollBy(value - travelled) + travelled = value + glide.remaining = total - value + } + } + } finally { + if (glide.job === coroutineContext[Job]) glide.remaining = 0f } } - } finally { - if (glide.job === coroutineContext[Job]) glide.remaining = 0f - } } } } } -} private class WheelGlide { var remaining = 0f diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt index 6370ffa4f..b39a6cbe2 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -56,42 +56,45 @@ private val CLOSE_SHADOW_COLOR = Color.Black.copy(alpha = 0.85f) private val CLOSE_SHADOW_BLUR = 3.dp private val CLOSE_SHADOW_DROP = 2.dp -private val DRAWN = ImageFilter.makeColorFilter( - ColorFilter.makeMatrix( - ColorMatrix( - 0f, 0f, 0f, 0f, 0f, - 0f, 0f, 0f, 0f, 0f, - 0f, 0f, 0f, 0f, 0f, - 0f, 0f, 0f, 64f, 0f, - ) - ), - null, - null -) +private val DRAWN = + ImageFilter.makeColorFilter( + ColorFilter.makeMatrix( + ColorMatrix( + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 64f, 0f, + ) + ), + null, + null + ) private val REPLACE = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC } private val WITHIN = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC_IN } -fun Modifier.glass(color: Color, shape: Shape): Modifier = clip(shape).composed { - val sigma = with(LocalDensity.current) { Look.backdropBlur.toPx() } - val underlay = Look.underlay - val blur = remember(sigma, underlay) { - if (sigma <= 0f) return@remember null - val blurred = ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) - if (underlay >= 1f) blurred else ImageFilter.makeColorFilter(faded(underlay), blurred, null) - } - drawBehind { - if (blur == null) { - drawRect(color, blendMode = BlendMode.Src) - return@drawBehind - } - drawIntoCanvas { canvas -> - canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), REPLACE, blur)) - canvas.skiaCanvas.restore() +fun Modifier.glass(color: Color, shape: Shape): Modifier = + clip(shape).composed { + val sigma = with(LocalDensity.current) { Look.backdropBlur.toPx() } + val underlay = Look.underlay + val blur = + remember(sigma, underlay) { + if (sigma <= 0f) return@remember null + val blurred = ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) + if (underlay >= 1f) blurred else ImageFilter.makeColorFilter(faded(underlay), blurred, null) + } + drawBehind { + if (blur == null) { + drawRect(color, blendMode = BlendMode.Src) + return@drawBehind + } + drawIntoCanvas { canvas -> + canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), REPLACE, blur)) + canvas.skiaCanvas.restore() + } + drawRect(color) } - drawRect(color) } -} fun Modifier.window(color: Color, border: Color, shape: Shape, floating: Boolean = false): Modifier = (if (floating) dropShadow(shape) else this) @@ -99,38 +102,41 @@ fun Modifier.window(color: Color, border: Color, shape: Shape, floating: Boolean .then(if (Look.outlines) Modifier.border(Look.outlineWidth, border, shape) else Modifier) .consumeClicks() -fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = drawWithCache { - val body = Path().apply { addOutline(shape.createOutline(size, layoutDirection, this@drawWithCache)) } - val drop = (if (close) CLOSE_SHADOW_DROP else SHADOW_DROP).toPx() - val blur = (if (close) CLOSE_SHADOW_BLUR else SHADOW_BLUR).toPx() - val reach = blur * 3 - val shadow = Paint().apply { - color = (if (close) CLOSE_SHADOW_COLOR else SHADOW_COLOR).toArgb() - maskFilter = MaskFilter.makeBlur(FilterBlurMode.NORMAL, blur) - } - onDrawBehind { - if (!Look.shadows) return@onDrawBehind - clipPath(body, ClipOp.Difference) { - clipRect(-reach, drop - reach, size.width + reach, size.height + drop + reach) { - drawIntoCanvas { canvas -> - val skia = canvas.skiaCanvas - skia.saveLayer(Canvas.SaveLayerRec(null, null, DRAWN)) - skia.saveLayer(null, WITHIN) - skia.translate(0f, drop) - skia.drawPath(body.asSkiaPath(), shadow) - skia.restore() - skia.restore() +fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = + drawWithCache { + val body = Path().apply { addOutline(shape.createOutline(size, layoutDirection, this@drawWithCache)) } + val drop = (if (close) CLOSE_SHADOW_DROP else SHADOW_DROP).toPx() + val blur = (if (close) CLOSE_SHADOW_BLUR else SHADOW_BLUR).toPx() + val reach = blur * 3 + val shadow = + Paint().apply { + color = (if (close) CLOSE_SHADOW_COLOR else SHADOW_COLOR).toArgb() + maskFilter = MaskFilter.makeBlur(FilterBlurMode.NORMAL, blur) + } + onDrawBehind { + if (!Look.shadows) return@onDrawBehind + clipPath(body, ClipOp.Difference) { + clipRect(-reach, drop - reach, size.width + reach, size.height + drop + reach) { + drawIntoCanvas { canvas -> + val skia = canvas.skiaCanvas + skia.saveLayer(Canvas.SaveLayerRec(null, null, DRAWN)) + skia.saveLayer(null, WITHIN) + skia.translate(0f, drop) + skia.drawPath(body.asSkiaPath(), shadow) + skia.restore() + skia.restore() + } } } } } -} -private fun faded(fraction: Float) = ColorFilter.makeMatrix( - ColorMatrix( - 1f, 0f, 0f, 0f, 0f, - 0f, 1f, 0f, 0f, 0f, - 0f, 0f, 1f, 0f, 0f, - 0f, 0f, 0f, fraction, 0f, +private fun faded(fraction: Float) = + ColorFilter.makeMatrix( + ColorMatrix( + 1f, 0f, 0f, 0f, 0f, + 0f, 1f, 0f, 0f, 0f, + 0f, 0f, 1f, 0f, 0f, + 0f, 0f, 0f, fraction, 0f, + ) ) -) diff --git a/src/main/kotlin/com/lambda/gui/component/Text.kt b/src/main/kotlin/com/lambda/gui/component/Text.kt index b5d50736e..ba8385a78 100644 --- a/src/main/kotlin/com/lambda/gui/component/Text.kt +++ b/src/main/kotlin/com/lambda/gui/component/Text.kt @@ -64,9 +64,10 @@ fun ContentColor(color: Color, content: @Composable () -> Unit) = 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()) } - } + 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) } diff --git a/src/main/kotlin/com/lambda/gui/component/TextInput.kt b/src/main/kotlin/com/lambda/gui/component/TextInput.kt index 7aaa8dcab..09c3914e9 100644 --- a/src/main/kotlin/com/lambda/gui/component/TextInput.kt +++ b/src/main/kotlin/com/lambda/gui/component/TextInput.kt @@ -119,8 +119,9 @@ fun TextInput( .focusRequester(focus) .onFocusChanged { hasFocus = it.isFocused - if (it.isFocused) hadFocus = true - else if (hadFocus) onDone?.invoke() + if (it.isFocused) hadFocus = + true + else if (hadFocus) onDone?.invoke() } .onPreviewKeyEvent { event -> if (onDone == null || (event.key != Key.Enter && event.key != Key.Escape)) false diff --git a/src/main/kotlin/com/lambda/gui/core/GlState.kt b/src/main/kotlin/com/lambda/gui/core/GlState.kt index 93a6018f1..fc43946f1 100644 --- a/src/main/kotlin/com/lambda/gui/core/GlState.kt +++ b/src/main/kotlin/com/lambda/gui/core/GlState.kt @@ -83,10 +83,11 @@ import org.lwjgl.system.MemoryStack internal object GlState { private const val TEXTURE_UNITS = 12 - private val UNPACK_PARAMETERS = intArrayOf( - GL_UNPACK_SWAP_BYTES, GL_UNPACK_LSB_FIRST, GL_UNPACK_ROW_LENGTH, GL_UNPACK_IMAGE_HEIGHT, - GL_UNPACK_SKIP_ROWS, GL_UNPACK_SKIP_PIXELS, GL_UNPACK_SKIP_IMAGES, GL_UNPACK_ALIGNMENT - ) + private val UNPACK_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) @@ -136,11 +137,12 @@ internal object GlState { 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 } - } + 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) } diff --git a/src/main/kotlin/com/lambda/gui/core/RenderThread.kt b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt index 09f9f55c7..1f0d3a8bd 100644 --- a/src/main/kotlin/com/lambda/gui/core/RenderThread.kt +++ b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt @@ -34,8 +34,9 @@ object RenderThread : CoroutineDispatcher() { override fun dispatch(context: CoroutineContext, block: Runnable) = mc.send(block) @JvmStatic - fun after(millis: Long, block: () -> Unit): Job = scope.launch { - delay(millis) - block() - } + fun after(millis: Long, block: () -> Unit): Job = + scope.launch { + delay(millis) + block() + } } diff --git a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt index 4da505506..5e4dd293e 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt @@ -62,11 +62,12 @@ internal class SceneHost(context: CoroutineContext, content: @Composable () -> U private val recomposer = FrameRecomposer(RenderThread + context) private var invalidated = true - private val scene: ComposeScene = CanvasLayersComposeScene( - frameRecomposer = recomposer, - platformContext = platform, - invalidateDraw = { invalidated = true }, - ).also { it.setContent(content = content) } + private val scene: ComposeScene = + CanvasLayersComposeScene( + frameRecomposer = recomposer, + platformContext = platform, + invalidateDraw = { invalidated = true }, + ).also { it.setContent(content = content) } val input = SceneInput(scene) @@ -125,12 +126,13 @@ internal class SceneHost(context: CoroutineContext, content: @Composable () -> U } private class SkiaTarget(val size: IntSize) : AutoCloseable { - private val texture: GpuTexture = RenderSystem.getDevice().createTexture( - { "Lambda GUI" }, - GpuTexture.USAGE_RENDER_ATTACHMENT or GpuTexture.USAGE_TEXTURE_BINDING, - TextureFormat.RGBA8, - size.width, size.height, 1, 1 - ) + private val texture: GpuTexture = + RenderSystem.getDevice().createTexture( + { "Lambda GUI" }, + GpuTexture.USAGE_RENDER_ATTACHMENT or GpuTexture.USAGE_TEXTURE_BINDING, + TextureFormat.RGBA8, + size.width, size.height, 1, 1 + ) val view: GpuTextureView = RenderSystem.getDevice().createTextureView(texture) private var framebuffer = 0 @@ -138,21 +140,23 @@ private class SkiaTarget(val size: IntSize) : AutoCloseable { private var renderTarget: BackendRenderTarget? = null private var surface: Surface? = null - fun attach(skia: DirectContext): Surface = surface ?: run { - framebuffer = glGenFramebuffers() - stencil = glGenRenderbuffers() - glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, (texture as GlTexture).glId, 0) - glBindRenderbuffer(GL_RENDERBUFFER, stencil) - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, size.width, size.height) - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, stencil) - - val renderTarget = BackendRenderTarget.makeGL(size.width, size.height, 0, 8, framebuffer, FramebufferFormat.GR_GL_RGBA8) - .also { renderTarget = it } - Surface.makeFromBackendRenderTarget( - skia, renderTarget, SurfaceOrigin.BOTTOM_LEFT, SurfaceColorFormat.RGBA_8888, ColorSpace.sRGB - )?.also { surface = it } ?: error("Skia rejected the GUI render target") - } + fun attach(skia: DirectContext): Surface = + surface ?: run { + framebuffer = glGenFramebuffers() + stencil = glGenRenderbuffers() + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, (texture as GlTexture).glId, 0) + glBindRenderbuffer(GL_RENDERBUFFER, stencil) + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, size.width, size.height) + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, stencil) + + val renderTarget = + BackendRenderTarget.makeGL(size.width, size.height, 0, 8, framebuffer, FramebufferFormat.GR_GL_RGBA8) + .also { renderTarget = it } + Surface.makeFromBackendRenderTarget( + skia, renderTarget, SurfaceOrigin.BOTTOM_LEFT, SurfaceColorFormat.RGBA_8888, ColorSpace.sRGB + )?.also { surface = it } ?: error("Skia rejected the GUI render target") + } fun detach() { surface?.close() diff --git a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt index a30dc0901..dac51cebb 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt @@ -69,39 +69,43 @@ internal class SceneInput(private val scene: ComposeScene) { fun key(key: Int, pressed: Boolean, modifiers: Int): Boolean { if (pressed) Press.begin() val shift = modifiers and GLFW.GLFW_MOD_SHIFT != 0 - val direction = when (key.takeIf { pressed }) { - GLFW.GLFW_KEY_TAB -> if (shift) FocusDirection.Previous else FocusDirection.Next - GLFW.GLFW_KEY_UP -> FocusDirection.Up - GLFW.GLFW_KEY_DOWN -> FocusDirection.Down - GLFW.GLFW_KEY_LEFT -> FocusDirection.Left - GLFW.GLFW_KEY_RIGHT -> FocusDirection.Right - else -> null - } + val direction = + when (key.takeIf { pressed }) { + GLFW.GLFW_KEY_TAB -> if (shift) FocusDirection.Previous else FocusDirection.Next + GLFW.GLFW_KEY_UP -> FocusDirection.Up + GLFW.GLFW_KEY_DOWN -> FocusDirection.Down + GLFW.GLFW_KEY_LEFT -> FocusDirection.Left + GLFW.GLFW_KEY_RIGHT -> FocusDirection.Right + else -> null + } if (direction != null) KeyboardFocus.visible = true - val handled = scene.sendKeyEvent( - KeyEvent( - key = Key(key.toAwtKeyCode()), - type = if (pressed) KeyEventType.KeyDown else KeyEventType.KeyUp, - isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, - isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, - isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, - isShiftPressed = shift, + val handled = + scene.sendKeyEvent( + KeyEvent( + key = Key(key.toAwtKeyCode()), + type = if (pressed) KeyEventType.KeyDown else KeyEventType.KeyUp, + isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, + isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, + isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, + isShiftPressed = shift, + ) ) - ) if (handled || direction == null) return handled - val inOrder = when (direction) { - FocusDirection.Up, FocusDirection.Left -> FocusDirection.Previous - else -> FocusDirection.Next - } + val inOrder = + when (direction) { + FocusDirection.Up, FocusDirection.Left -> FocusDirection.Previous + else -> FocusDirection.Next + } return KeyboardFocus.move(direction) || direction != inOrder && KeyboardFocus.move(inOrder) } fun type(codePoint: Int): Boolean = Character.toChars(codePoint).fold(false) { handled, char -> - val typed = AwtKeyEvent( - awtSource, AwtKeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, AwtKeyEvent.VK_UNDEFINED, char - ) + 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 @@ -150,38 +154,40 @@ internal class SceneInput(private val scene: ComposeScene) { val awtSource = object : Component() {} - fun Int.toPointerButton() = when (this) { - GLFW.GLFW_MOUSE_BUTTON_LEFT -> PointerButton.Primary - GLFW.GLFW_MOUSE_BUTTON_RIGHT -> PointerButton.Secondary - GLFW.GLFW_MOUSE_BUTTON_MIDDLE -> PointerButton.Tertiary - GLFW.GLFW_MOUSE_BUTTON_4 -> PointerButton.Back - GLFW.GLFW_MOUSE_BUTTON_5 -> PointerButton.Forward - else -> null - } - - fun Int.toAwtKeyCode() = when (this) { - GLFW.GLFW_KEY_ESCAPE -> AwtKeyEvent.VK_ESCAPE - GLFW.GLFW_KEY_ENTER, GLFW.GLFW_KEY_KP_ENTER -> AwtKeyEvent.VK_ENTER - GLFW.GLFW_KEY_TAB -> AwtKeyEvent.VK_TAB - GLFW.GLFW_KEY_SPACE -> AwtKeyEvent.VK_SPACE - GLFW.GLFW_KEY_BACKSPACE -> AwtKeyEvent.VK_BACK_SPACE - GLFW.GLFW_KEY_INSERT -> AwtKeyEvent.VK_INSERT - GLFW.GLFW_KEY_DELETE -> AwtKeyEvent.VK_DELETE - GLFW.GLFW_KEY_RIGHT -> AwtKeyEvent.VK_RIGHT - GLFW.GLFW_KEY_LEFT -> AwtKeyEvent.VK_LEFT - GLFW.GLFW_KEY_DOWN -> AwtKeyEvent.VK_DOWN - GLFW.GLFW_KEY_UP -> AwtKeyEvent.VK_UP - GLFW.GLFW_KEY_PAGE_UP -> AwtKeyEvent.VK_PAGE_UP - GLFW.GLFW_KEY_PAGE_DOWN -> AwtKeyEvent.VK_PAGE_DOWN - GLFW.GLFW_KEY_HOME -> AwtKeyEvent.VK_HOME - GLFW.GLFW_KEY_END -> AwtKeyEvent.VK_END - GLFW.GLFW_KEY_LEFT_SHIFT, GLFW.GLFW_KEY_RIGHT_SHIFT -> AwtKeyEvent.VK_SHIFT - GLFW.GLFW_KEY_LEFT_CONTROL, GLFW.GLFW_KEY_RIGHT_CONTROL -> AwtKeyEvent.VK_CONTROL - GLFW.GLFW_KEY_LEFT_ALT, GLFW.GLFW_KEY_RIGHT_ALT -> AwtKeyEvent.VK_ALT - GLFW.GLFW_KEY_LEFT_SUPER, GLFW.GLFW_KEY_RIGHT_SUPER -> AwtKeyEvent.VK_META - in GLFW.GLFW_KEY_A..GLFW.GLFW_KEY_Z, in GLFW.GLFW_KEY_0..GLFW.GLFW_KEY_9 -> this - in GLFW.GLFW_KEY_F1..GLFW.GLFW_KEY_F12 -> AwtKeyEvent.VK_F1 + (this - GLFW.GLFW_KEY_F1) - else -> AwtKeyEvent.VK_UNDEFINED - } + fun Int.toPointerButton() = + when (this) { + GLFW.GLFW_MOUSE_BUTTON_LEFT -> PointerButton.Primary + GLFW.GLFW_MOUSE_BUTTON_RIGHT -> PointerButton.Secondary + GLFW.GLFW_MOUSE_BUTTON_MIDDLE -> PointerButton.Tertiary + GLFW.GLFW_MOUSE_BUTTON_4 -> PointerButton.Back + GLFW.GLFW_MOUSE_BUTTON_5 -> PointerButton.Forward + else -> null + } + + fun Int.toAwtKeyCode() = + when (this) { + GLFW.GLFW_KEY_ESCAPE -> AwtKeyEvent.VK_ESCAPE + GLFW.GLFW_KEY_ENTER, GLFW.GLFW_KEY_KP_ENTER -> AwtKeyEvent.VK_ENTER + GLFW.GLFW_KEY_TAB -> AwtKeyEvent.VK_TAB + GLFW.GLFW_KEY_SPACE -> AwtKeyEvent.VK_SPACE + GLFW.GLFW_KEY_BACKSPACE -> AwtKeyEvent.VK_BACK_SPACE + GLFW.GLFW_KEY_INSERT -> AwtKeyEvent.VK_INSERT + GLFW.GLFW_KEY_DELETE -> AwtKeyEvent.VK_DELETE + GLFW.GLFW_KEY_RIGHT -> AwtKeyEvent.VK_RIGHT + GLFW.GLFW_KEY_LEFT -> AwtKeyEvent.VK_LEFT + GLFW.GLFW_KEY_DOWN -> AwtKeyEvent.VK_DOWN + GLFW.GLFW_KEY_UP -> AwtKeyEvent.VK_UP + GLFW.GLFW_KEY_PAGE_UP -> AwtKeyEvent.VK_PAGE_UP + GLFW.GLFW_KEY_PAGE_DOWN -> AwtKeyEvent.VK_PAGE_DOWN + GLFW.GLFW_KEY_HOME -> AwtKeyEvent.VK_HOME + GLFW.GLFW_KEY_END -> AwtKeyEvent.VK_END + GLFW.GLFW_KEY_LEFT_SHIFT, GLFW.GLFW_KEY_RIGHT_SHIFT -> AwtKeyEvent.VK_SHIFT + GLFW.GLFW_KEY_LEFT_CONTROL, GLFW.GLFW_KEY_RIGHT_CONTROL -> AwtKeyEvent.VK_CONTROL + GLFW.GLFW_KEY_LEFT_ALT, GLFW.GLFW_KEY_RIGHT_ALT -> AwtKeyEvent.VK_ALT + GLFW.GLFW_KEY_LEFT_SUPER, GLFW.GLFW_KEY_RIGHT_SUPER -> AwtKeyEvent.VK_META + in GLFW.GLFW_KEY_A..GLFW.GLFW_KEY_Z, in GLFW.GLFW_KEY_0..GLFW.GLFW_KEY_9 -> this + in GLFW.GLFW_KEY_F1..GLFW.GLFW_KEY_F12 -> AwtKeyEvent.VK_F1 + (this - GLFW.GLFW_KEY_F1) + else -> AwtKeyEvent.VK_UNDEFINED + } } } diff --git a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt index aed222c81..e4c18fdcc 100644 --- a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt +++ b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt @@ -46,11 +46,12 @@ import java.awt.datatransfer.Transferable @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) - } + private val window = + object : WindowInfo { + override val isWindowFocused get() = true + override var containerSize by mutableStateOf(IntSize.Zero) + override var containerDpSize by mutableStateOf(DpSize.Zero) + } var cursor: Cursor? = null override val windowInfo: WindowInfo get() = window @@ -61,32 +62,34 @@ internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { } 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 - } + cursor = + when (pointerIcon) { + PointerIcon.Text -> StandardCursors.IBEAM + PointerIcon.Hand -> StandardCursors.POINTING_HAND + PointerIcon.Crosshair -> StandardCursors.CROSSHAIR + ResizeVerticalIcon -> StandardCursors.RESIZE_NS + else -> null + } } 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 val textInputService = + object : PlatformTextInputService { + override fun startInput( + value: TextFieldValue, + imeOptions: ImeOptions, + onEditCommand: (List) -> Unit, + onImeActionPerformed: (ImeAction) -> Unit, + ) = Unit - override fun stopInput() = Unit + override fun stopInput() = Unit - override fun showSoftwareKeyboard() = Unit - override fun hideSoftwareKeyboard() = Unit - override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) = Unit - } + override fun showSoftwareKeyboard() = Unit + override fun hideSoftwareKeyboard() = Unit + override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) = Unit + } } object ResizeVerticalIcon : PointerIcon @@ -100,9 +103,10 @@ internal object GameClipboard : Clipboard { 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 - ?: "" + mc.keyboard.clipboard = + transferable + ?.takeIf { it.isDataFlavorSupported(DataFlavor.stringFlavor) } + ?.getTransferData(DataFlavor.stringFlavor) as? String + ?: "" } } diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt index 6de2d6342..3a2d5afc9 100644 --- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -267,41 +267,42 @@ private fun ElementSettings(config: Config, open: Boolean, editor: HudEditorStat } } -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() +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() + editor.draggedTo = origin.topLeft + editor.dragged = hud + try { + drag(down.id) { change -> + editor.draggedTo += change.positionChange() + change.consume() + } + } finally { + val dropped = editor.drop?.position ?: origin.topLeft + val room = editor.screen - origin.size + hud.anchorX = if (room.width > 0f) (dropped.x / room.width).coerceIn(0f, 1f) else 0f + hud.anchorY = if (room.height > 0f) (dropped.y / room.height).coerceIn(0f, 1f) else 0f + editor.dragged = null } - } finally { - val dropped = editor.drop?.position ?: origin.topLeft - val room = editor.screen - origin.size - hud.anchorX = if (room.width > 0f) (dropped.x / room.width).coerceIn(0f, 1f) else 0f - hud.anchorY = if (room.height > 0f) (dropped.y / room.height).coerceIn(0f, 1f) else 0f - editor.dragged = null } } - } - .drawBehind { - val width = Look.outlineWidth.toPx() - 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) - ) - } + .drawBehind { + val width = Look.outlineWidth.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) + ) + } 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 index a8abfff4f..f468c4242 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -91,31 +91,34 @@ internal fun NewAutomationConfigDialog(onDismiss: () -> Unit) { @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 - } + 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() } } - 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)) { diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index 1a514101d..9be33ff63 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -400,11 +400,12 @@ private fun MinecraftMenu() { 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 - ) + 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.") } } diff --git a/src/main/kotlin/com/lambda/gui/menu/Search.kt b/src/main/kotlin/com/lambda/gui/menu/Search.kt index 8c3f68092..0c840373d 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Search.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt @@ -74,31 +74,32 @@ internal object Search { .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) - } + private fun rank(query: String, lenient: Boolean): List> = + buildList { + fun consider(result: () -> Result, bonus: Int, vararg names: String) { + val score = names.maxOf { score(query, it.lowercase(), lenient) } + if (score > 0) add(result() to score + bonus) + } - fun hidden(config: Any) = config is Module && config.tag == ModuleTag.DEBUG && !ClickGuiState.developerMode + fun hidden(config: Any) = config is Module && config.tag == ModuleTag.DEBUG && !ClickGuiState.developerMode - ModuleRegistry.modules.forEach { module -> - if (hidden(module)) return@forEach - consider({ Result.OfModule(module) }, if (module is HudModule) HUD_MODULE_BONUS else MODULE_BONUS, module.name, module.tag.name) - } - CommandRegistry.commands.forEach { command -> - consider({ Result.OfCommand(command) }, COMMAND_BONUS, command.name, *command.aliases.toTypedArray()) - } - ConfigLoader.configCategories.forEach { category -> - category.configs.forEach { config -> - if (hidden(config)) return@forEach - config.settingLayers.forEachEntry { path, single -> - val setting = single.entry - if (setting.visibility()) consider({ Result.OfSetting(setting, config, path.map { it.name }) }, 0, setting.name) + ModuleRegistry.modules.forEach { module -> + if (hidden(module)) return@forEach + consider({ Result.OfModule(module) }, if (module is HudModule) HUD_MODULE_BONUS else MODULE_BONUS, module.name, module.tag.name) + } + CommandRegistry.commands.forEach { command -> + consider({ Result.OfCommand(command) }, COMMAND_BONUS, command.name, *command.aliases.toTypedArray()) + } + ConfigLoader.configCategories.forEach { category -> + category.configs.forEach { config -> + if (hidden(config)) return@forEach + config.settingLayers.forEachEntry { path, single -> + val setting = single.entry + if (setting.visibility()) consider({ Result.OfSetting(setting, config, path.map { it.name }) }, 0, setting.name) + } } } } - } private fun score(query: String, target: String, lenient: Boolean): Int { if (target.isEmpty()) return 0 diff --git a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt index 652fa9a80..b98efd0dc 100644 --- a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt +++ b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt @@ -36,9 +36,10 @@ internal class BlurPyramid(private val name: String) { 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 val spreadUniform: GpuBuffer = + RenderSystem.getDevice().createBuffer( + { "$name spread" }, GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, SPREAD_UNIFORM_SIZE + ) private var spread = Float.NaN fun blur(source: GpuTextureView, width: Int, height: Int, radius: Float): GpuTextureView { @@ -87,12 +88,13 @@ internal class BlurPyramid(private val name: String) { } 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 - ) + 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() { diff --git a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt index d84ee8e1f..1a1ecf56f 100644 --- a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt +++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt @@ -72,11 +72,12 @@ internal object GuiCompositor { } 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 - } + 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() @@ -93,13 +94,14 @@ internal object GuiCompositor { 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() + 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) } } diff --git a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt index 656a3fec0..f4c7699ad 100644 --- a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt +++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt @@ -132,8 +132,9 @@ object ItemAtlas { models += it.state().modelKey moving = moving || it.state().isAnimated } - val changed = scale != this.scale || models != renderedModels || - slots.any { !ItemStack.areEqual(it.stack, it.rendered) } + val changed = + scale != this.scale || models != renderedModels || + slots.any { !ItemStack.areEqual(it.stack, it.rendered) } val now = System.nanoTime() if (!changed && !(moving && now - renderedAt >= ANIMATION_INTERVAL)) { state.clear() @@ -143,10 +144,11 @@ object ItemAtlas { 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 } - } + 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() } @@ -192,19 +194,22 @@ object ItemAtlas { private class Strip(val width: Int, val height: Int) : AutoCloseable { val framebuffer = SimpleFramebuffer("Lambda GUI items", width, height, true) - private val glFramebuffer = (framebuffer.colorAttachment as GlTexture) - .getOrCreateFramebuffer((RenderSystem.getDevice() as GlBackend).bufferManager, null) + private 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 + val surface = + surface ?: run { + val renderTarget = + BackendRenderTarget.makeGL(width, height, 0, 0, glFramebuffer, FramebufferFormat.GR_GL_RGBA8) + .also { renderTarget = it } + Surface.makeFromBackendRenderTarget( + skia, renderTarget, SurfaceOrigin.BOTTOM_LEFT, SurfaceColorFormat.RGBA_8888, ColorSpace.sRGB + ).also { surface = it } + } ?: return null surface.notifyContentWillChange(ContentChangeMode.DISCARD) return surface.makeImageSnapshot() } diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt index 922131849..f6eaf03de 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -84,9 +84,10 @@ internal fun CollectionButton(setting: CollectionSetting) { @Composable private fun CollectionWindow(setting: CollectionSetting, onDismiss: () -> Unit) { val selected by observe { setting.value.toSet() } - val entries = remember(setting.immutableCollection) { - setting.immutableCollection.map { Entry(it, setting.label(it), setting.icon(it)) } - } + 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 } } diff --git a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt index 9b1dbd8ec..acbc88116 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt @@ -83,43 +83,47 @@ internal fun ColumnScope.ModuleSettings(module: Module, selected: PanelPage, onS onSelect(it) if (scroll != null) scope.launch { scroll.scrollTo(0) } } - val turned = @Composable { - AnimatedContent( - targetState = page, - modifier = Modifier.fillMaxWidth(), - transitionSpec = { pageTurn(towardsEnd = targetState > initialState) }, - ) { shown -> - Column(Modifier.fillMaxWidth()) { - when (shown) { - PanelPage.Settings -> SettingsPage(module) - PanelPage.Module -> ModulePage(module) - PanelPage.Automation -> AutomationPage(module) + val turned = + @Composable { + AnimatedContent( + targetState = page, + modifier = Modifier.fillMaxWidth(), + transitionSpec = { pageTurn(towardsEnd = targetState > initialState) }, + ) { shown -> + Column(Modifier.fillMaxWidth()) { + when (shown) { + PanelPage.Settings -> SettingsPage(module) + PanelPage.Module -> ModulePage(module) + PanelPage.Automation -> AutomationPage(module) + } } } } - } if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } else turned() } } -private fun pagesOf(module: Module): List = when { - module == AutoUpdater -> listOf(PanelPage.Settings) - module.automationConfig === AutomationConfig.DEFAULT -> listOf(PanelPage.Settings, PanelPage.Module) - else -> PanelPage.entries -} +private fun pagesOf(module: Module): List = + when { + module == AutoUpdater -> listOf(PanelPage.Settings) + module.automationConfig === AutomationConfig.DEFAULT -> listOf(PanelPage.Settings, PanelPage.Module) + else -> PanelPage.entries + } -private fun pageOf(module: Module, setting: Setting<*>): PanelPage = when { - module.automationConfig !== AutomationConfig.DEFAULT && module.automationConfig.settingLayers.holds(setting) -> PanelPage.Automation - setting in moduleSettings(module) -> PanelPage.Module - else -> PanelPage.Settings -} +private fun pageOf(module: Module, setting: Setting<*>): PanelPage = + when { + module.automationConfig !== AutomationConfig.DEFAULT && module.automationConfig.settingLayers.holds(setting) -> PanelPage.Automation + setting in moduleSettings(module) -> PanelPage.Module + else -> PanelPage.Settings + } -private fun moduleSettings(module: Module): List> = listOfNotNull( - module.keybindSetting.takeUnless { module.alwaysEnabled }, - module.prioritySetting, - module.disableOnReleaseSetting.takeUnless { module.alwaysEnabled }, - module.drawSetting.takeUnless { module.alwaysEnabled }, -) +private fun moduleSettings(module: Module): List> = + listOfNotNull( + module.keybindSetting.takeUnless { module.alwaysEnabled }, + module.prioritySetting, + module.disableOnReleaseSetting.takeUnless { module.alwaysEnabled }, + module.drawSetting.takeUnless { module.alwaysEnabled }, + ) @Composable private fun PageStrip(pages: List, selected: PanelPage, onSelect: (PanelPage) -> Unit) { diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 4362b95d8..f32f34935 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -92,12 +92,13 @@ fun SettingRow(setting: Setting<*>) { } } -internal fun Modifier.settingCell(): Modifier = composed { - fillMaxWidth() - .padding(vertical = Look.settingSpacing / 2) - .clip(RoundedCornerShape(Look.controlRounding)) - .hoverHighlight(LambdaTheme.colors.hover) -} +internal fun Modifier.settingCell(): Modifier = + composed { + fillMaxWidth() + .padding(vertical = Look.settingSpacing / 2) + .clip(RoundedCornerShape(Look.controlRounding)) + .hoverHighlight(LambdaTheme.colors.hover) + } private fun Modifier.enabled(enabled: Boolean): Modifier = if (enabled) this diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt index 977993f06..aabbdc389 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -88,10 +88,11 @@ fun SettingsList(layer: EntryLayer>) { when { layer.multipleType == MultipleLayerType.Group -> Section(layer.name, revealed = Reveal.setting?.let(layer::holds) == true) { Children(layer) } - else -> Column(Modifier.fillMaxWidth()) { - layer.layers.filter { it !is EntryLayer.Tab }.forEach { SettingsList(it) } - if (tabs.isNotEmpty()) Tabs(tabs) - } + else -> + Column(Modifier.fillMaxWidth()) { + layer.layers.filter { it !is EntryLayer.Tab }.forEach { SettingsList(it) } + if (tabs.isNotEmpty()) Tabs(tabs) + } } } } diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index d9caa8d7a..23dd03b75 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -123,13 +123,15 @@ internal object Motion : MotionDurationScale { private const val PAGE_MILLIS = 160 private val UNFOLDING = spring(stiffness = Spring.StiffnessMedium, visibilityThreshold = IntSize.VisibilityThreshold) - val SCROLL = object : MotionDurationScale { - override val scaleFactor get() = if (Style.smoothScrolling) 1f else 0f - } + val SCROLL = + object : MotionDurationScale { + override val scaleFactor get() = if (Style.smoothScrolling) 1f else 0f + } - val UNSCALED = object : MotionDurationScale { - override val scaleFactor get() = 1f - } + val UNSCALED = + object : MotionDurationScale { + override val scaleFactor get() = 1f + } override val scaleFactor get() = if (Style.animations) 1f / Style.animationSpeed else 0f @@ -160,13 +162,14 @@ private class Typography(font: GuiFont, scale: Float = 1f) { val body = compact(font, font.size * scale) val label = compact(font, font.smallSize * scale) - private fun compact(font: GuiFont, size: TextUnit, weight: FontWeight = FontWeight.Normal) = TextStyle( - fontFamily = font.family, - fontWeight = weight, - fontSize = size, - lineHeight = if (font == GuiFont.Minecraft) size else size * 1.25f, - lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.Both), - ) + private fun compact(font: GuiFont, size: TextUnit, weight: FontWeight = FontWeight.Normal) = + TextStyle( + fontFamily = font.family, + fontWeight = weight, + fontSize = size, + lineHeight = if (font == GuiFont.Minecraft) size else size * 1.25f, + lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.Both), + ) } object Type { @@ -191,11 +194,12 @@ fun LambdaTheme(content: @Composable () -> Unit) { val font by observe { Style.font } val fontSize by observe { Style.fontSize } val measurer = rememberTextMeasurer() - val typography = remember(font, fontSize) { - if (font == GuiFont.Minecraft) return@remember Typography(font, fontSize) - val line = measurer.measure("Ag", Typography(font).body, density = Density(1f)).size.height - Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f) * fontSize) - } + val typography = + remember(font, fontSize) { + if (font == GuiFont.Minecraft) return@remember Typography(font, fontSize) + val line = measurer.measure("Ag", Typography(font).body, density = Density(1f)).size.height + Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f) * fontSize) + } CompositionLocalProvider( LocalPalette provides palette, LocalTypography provides typography, 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 67660199b..7e41ea5b4 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt @@ -83,14 +83,16 @@ object AutoUpdater : Module( prompt = null if (accepted) installLoader() } - Prompt.Install -> if (accepted) { - prompt = null - installLoader() - } else disable() - Prompt.Uninstall -> if (accepted) { - prompt = null - installClient() - } else enable() + Prompt.Install -> + if (accepted) { + prompt = null + installLoader() + } else disable() + Prompt.Uninstall -> + if (accepted) { + prompt = null + installClient() + } else enable() null -> Unit } } 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 aefccbca3..289ca01a1 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -147,11 +147,12 @@ object Style : Module( ) private val theme: PaletteSettings - get() = when (themeMode) { - ThemeMode.Dark -> darkTheme - ThemeMode.Light -> lightTheme - ThemeMode.Auto -> if (SystemAppearance.isDark) darkTheme else lightTheme - } + get() = + when (themeMode) { + ThemeMode.Dark -> darkTheme + ThemeMode.Light -> lightTheme + ThemeMode.Auto -> if (SystemAppearance.isDark) darkTheme else lightTheme + } val palette: Palette get() = theme.toPalette() val glowColorA: Color get() = theme.glowA @@ -219,24 +220,25 @@ class PaletteSettings( val glowA by c.setting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { Style.glow } val glowB by c.setting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { Style.glow } - fun toPalette() = Palette( - primary = primary.toCompose(), - secondary = secondary.toCompose(), - surface = surface.toCompose(), - panel = panel.toCompose(), - inset = inset.toCompose(), - onSurface = onSurface.toCompose(), - onSurfaceVariant = onSurfaceVariant.toCompose(), - header = header.toCompose(), - onHeader = onHeader.toCompose(), - moduleEnabled = moduleEnabled.toCompose(), - onModuleEnabled = onModuleEnabled.toCompose(), - control = control.toCompose(), - controlSelected = controlSelected.toCompose(), - onControl = onControl.toCompose(), - track = track.toCompose(), - input = input.toCompose(), - border = border.toCompose(), - textShadow = textShadow.toCompose(), - ) + fun toPalette() = + Palette( + primary = primary.toCompose(), + secondary = secondary.toCompose(), + surface = surface.toCompose(), + panel = panel.toCompose(), + inset = inset.toCompose(), + onSurface = onSurface.toCompose(), + onSurfaceVariant = onSurfaceVariant.toCompose(), + header = header.toCompose(), + onHeader = onHeader.toCompose(), + moduleEnabled = moduleEnabled.toCompose(), + onModuleEnabled = onModuleEnabled.toCompose(), + control = control.toCompose(), + controlSelected = controlSelected.toCompose(), + onControl = onControl.toCompose(), + track = track.toCompose(), + input = input.toCompose(), + border = border.toCompose(), + textShadow = textShadow.toCompose(), + ) } From 809b17246951405ec8e4f25151e03442914fbc1a Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:57:35 +0000 Subject: [PATCH 17/34] formatting --- .../com/lambda/config/entries/Setting.kt | 2 +- .../com/lambda/config/settings/CharSetting.kt | 8 +- .../lambda/config/settings/FunctionSetting.kt | 2 +- .../lambda/config/settings/NumericSetting.kt | 20 +- .../lambda/config/settings/StringSetting.kt | 20 +- .../settings/collections/CollectionSetting.kt | 2 +- .../settings/comparable/BooleanSetting.kt | 2 +- .../config/settings/comparable/EnumSetting.kt | 2 +- .../settings/complex/BlockPosSetting.kt | 23 ++- .../config/settings/complex/BlockSetting.kt | 2 +- .../config/settings/complex/ColorSetting.kt | 2 +- .../config/settings/complex/KeybindSetting.kt | 34 ++-- .../config/settings/complex/Vec3dSetting.kt | 26 ++- .../config/settings/numeric/IntegerSetting.kt | 3 +- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 16 +- src/main/kotlin/com/lambda/gui/GuiScreen.kt | 26 ++- src/main/kotlin/com/lambda/gui/LambdaGui.kt | 32 +++- src/main/kotlin/com/lambda/gui/Reveal.kt | 13 +- src/main/kotlin/com/lambda/gui/Snap.kt | 31 +++- .../com/lambda/gui/clickgui/CategoryWindow.kt | 92 +++++++-- .../com/lambda/gui/clickgui/ClickGui.kt | 41 +++- .../com/lambda/gui/clickgui/OpenSettings.kt | 11 +- .../com/lambda/gui/clickgui/SettingsPanel.kt | 76 ++++++-- .../com/lambda/gui/component/Controls.kt | 70 +++++-- .../kotlin/com/lambda/gui/component/Images.kt | 11 +- .../com/lambda/gui/component/Keyboard.kt | 7 +- .../com/lambda/gui/component/Pointer.kt | 24 ++- .../kotlin/com/lambda/gui/component/Popups.kt | 150 ++++++++++++--- .../kotlin/com/lambda/gui/component/Scroll.kt | 19 +- .../com/lambda/gui/component/SlidingText.kt | 4 +- .../com/lambda/gui/component/Surface.kt | 17 +- .../com/lambda/gui/component/TextInput.kt | 25 ++- .../kotlin/com/lambda/gui/core/GlState.kt | 39 +++- .../com/lambda/gui/core/RenderThread.kt | 3 +- .../kotlin/com/lambda/gui/core/Retained.kt | 15 +- .../kotlin/com/lambda/gui/core/SceneHost.kt | 47 ++++- .../kotlin/com/lambda/gui/core/SceneInput.kt | 45 ++++- .../com/lambda/gui/core/ScenePlatform.kt | 33 +--- src/main/kotlin/com/lambda/gui/hud/Hud.kt | 24 ++- .../kotlin/com/lambda/gui/hud/HudEditor.kt | 53 +++++- .../kotlin/com/lambda/gui/menu/Dialogs.kt | 45 ++++- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 175 ++++++++++++++---- src/main/kotlin/com/lambda/gui/menu/Search.kt | 50 ++++- .../com/lambda/gui/render/BlurPyramid.kt | 50 ++++- .../com/lambda/gui/render/GuiCompositor.kt | 49 +++-- .../kotlin/com/lambda/gui/render/ItemAtlas.kt | 36 +++- .../lambda/gui/settings/CollectionEditor.kt | 104 +++++++++-- .../com/lambda/gui/settings/ColorPicker.kt | 105 +++++++++-- .../com/lambda/gui/settings/ConfigSettings.kt | 22 ++- .../com/lambda/gui/settings/ModuleSettings.kt | 62 +++++-- .../com/lambda/gui/settings/SettingRow.kt | 27 ++- .../com/lambda/gui/settings/SettingsList.kt | 27 ++- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 80 ++++++-- .../kotlin/com/lambda/module/HudModule.kt | 9 +- .../com/lambda/module/modules/client/Style.kt | 6 +- .../combat/autodisconnect/AutoDisconnect.kt | 8 +- .../com/lambda/module/modules/hud/Armor.kt | 18 +- .../lambda/module/modules/hud/Coordinates.kt | 20 +- .../lambda/module/modules/hud/ModuleList.kt | 9 +- .../com/lambda/module/modules/hud/Tps.kt | 5 +- .../lambda/module/modules/hud/Watermark.kt | 6 +- 61 files changed, 1552 insertions(+), 433 deletions(-) diff --git a/src/main/kotlin/com/lambda/config/entries/Setting.kt b/src/main/kotlin/com/lambda/config/entries/Setting.kt index e1cd1d2e8..691c1a505 100644 --- a/src/main/kotlin/com/lambda/config/entries/Setting.kt +++ b/src/main/kotlin/com/lambda/config/entries/Setting.kt @@ -144,7 +144,7 @@ abstract class Setting( } @Composable - open fun Editor() {} + open fun Gui() {} open fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(string("value as JSON")) { value -> diff --git a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt index 61d9279e5..86416a816 100644 --- a/src/main/kotlin/com/lambda/config/settings/CharSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/CharSetting.kt @@ -49,10 +49,14 @@ class CharSetting( visibility: () -> Boolean ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() { + override fun Gui() { val value by observe { value } Labeled(name) { - TextInput(value.toString(), { text -> text.lastOrNull()?.let { this@CharSetting.value = it } }, Modifier.width(18.dp)) + TextInput( + value.toString(), + { text -> text.lastOrNull()?.let { this@CharSetting.value = it } }, + Modifier.width(18.dp) + ) } } diff --git a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt index 020636a24..d23326fdd 100644 --- a/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/FunctionSetting.kt @@ -36,5 +36,5 @@ class FunctionSetting R, R>( visibility: () -> Boolean ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() = Button(name, Modifier.fillMaxWidth().height(Look.rowHeight)) { value() } + override fun Gui() = Button(name, Modifier.fillMaxWidth().height(Look.rowHeight)) { value() } } diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index cff1f9aff..64f395d32 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -107,7 +107,8 @@ abstract class NumericSetting( private fun fractionOf(value: T): Float { val span = range.endInclusive.toDouble() - range.start.toDouble() val fraction = ((value.toDouble() - range.start.toDouble()) / span).toFloat() - return if (span > 0 && !fraction.isNaN()) fraction.coerceIn(0f, 1f) else 0f + return if (span > 0 && !fraction.isNaN()) fraction.coerceIn(0f, 1f) + else 0f } private fun at(fraction: Float): T = @@ -128,7 +129,7 @@ abstract class NumericSetting( } @Composable - override fun Editor() { + override fun Gui() { val colors = LambdaTheme.colors val current by observe { value } var typing by remember { mutableStateOf(false) } @@ -136,7 +137,13 @@ abstract class NumericSetting( var refocus by remember { mutableStateOf(false) } if (typing) { - NumberInput(current, ::parse, { value = it }, Modifier.fillMaxWidth(), focused = true) { + NumberInput( + current, + ::parse, + { value = it }, + Modifier.fillMaxWidth(), + focused = true + ) { typing = false refocus = KeyboardFocus.visible } @@ -159,7 +166,12 @@ abstract class NumericSetting( .heightIn(min = Look.rowHeight) .clip(RoundedCornerShape(Look.controlRounding)) .background(colors.track) - .drawBehind { drawRect(colors.trackFilled, size = Size(size.width * fraction, size.height)) } + .drawBehind { + drawRect( + colors.trackFilled, + size = Size(size.width * fraction, size.height) + ) + } .scrubbable(onEnd = { held?.let { value = it } held = null diff --git a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt index 46c115af5..1a187531c 100644 --- a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt @@ -60,14 +60,26 @@ class StringSetting( ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() { + override fun Gui() { val value by observe { value } - if (multiline) Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(1.dp)) { + if (multiline) Column( + Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(1.dp) + ) { Text(name, Modifier.padding(start = ROW_INSET, top = 1.dp), maxLines = 1) - TextInput(value, { this@StringSetting.value = it }, Modifier.fillMaxWidth(), singleLine = false) + TextInput( + value, + { this@StringSetting.value = it }, + Modifier.fillMaxWidth(), + singleLine = false + ) } else Labeled(name) { - TextInput(value, { this@StringSetting.value = it }, Modifier.width(TEXT_FIELD_WIDTH)) + TextInput( + value, + { this@StringSetting.value = it }, + Modifier.width(TEXT_FIELD_WIDTH) + ) } } 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 114722580..0dbded7a6 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt @@ -70,7 +70,7 @@ open class CollectionSetting( } @Composable - override fun Editor() = CollectionButton(this) + override fun Gui() = CollectionButton(this) open fun label(item: R): String = item.toString() 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 3898ee845..64ebbe729 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt @@ -52,7 +52,7 @@ class BooleanSetting( defaultValue: Boolean ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() { + override fun Gui() { val checked by observe { value } Row( verticalAlignment = Alignment.CenterVertically, 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 c3fa309db..ab05a32d7 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt @@ -47,7 +47,7 @@ class EnumSetting>( defaultValue: T ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() { + override fun Gui() { val selected by observe { value } Dropdown( label = name, 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 3f88d24a7..3940101f5 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockPosSetting.kt @@ -52,12 +52,27 @@ class BlockPosSetting( defaultValue: BlockPos ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() { + override fun Gui() { val pos by observe { value.toImmutable() } Labeled(name) { - NumberInput(pos.x, String::toIntOrNull, { value = BlockPos(it, pos.y, pos.z) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) - NumberInput(pos.y, String::toIntOrNull, { value = BlockPos(pos.x, it, pos.z) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) - NumberInput(pos.z, String::toIntOrNull, { value = BlockPos(pos.x, pos.y, it) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) + NumberInput( + pos.x, + String::toIntOrNull, + { value = BlockPos(it, pos.y, pos.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + pos.y, + String::toIntOrNull, + { value = BlockPos(pos.x, it, pos.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + pos.z, + String::toIntOrNull, + { value = BlockPos(pos.x, pos.y, it) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) Tooltip("Use the block you are looking at") { Button("Target", Modifier.height(Look.rowHeight)) { mc.crosshairTarget?.blockResult?.blockPos?.let { value = it } 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 ffb3c143d..542b72bff 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/BlockSetting.kt @@ -39,7 +39,7 @@ class BlockSetting( defaultValue: Block ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() = BlockPicker(this) + override fun Gui() = BlockPicker(this) override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(blockState(name, registry)) { argument -> diff --git a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt index 4ad2bedeb..e631564f5 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt @@ -40,7 +40,7 @@ class ColorSetting( defaultValue: Color ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() = ColorPicker(this) + override fun Gui() = ColorPicker(this) override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(integer("Red", 0, 255)) { red -> diff --git a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt index efc8633ae..2cab99179 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -135,7 +135,7 @@ class KeybindSetting( } @Composable - override fun Editor() { + override fun Gui() { val colors = LambdaTheme.colors val bind by observe { value } val recording = recorder === this @@ -201,22 +201,23 @@ class KeybindSetting( } optional(boolean("mouse button")) { isMouseButton -> executeWithResult { - val isMouse = if (isMouseButton != null) isMouseButton().value() else false - var bind = Bind.EMPTY - if (isMouse) { - val num = try { - nameArg().value().toInt() - } catch (_: NumberFormatException) { - return@executeWithResult failure("${nameArg().value()} doesn't match with a mouse button") + val isMouse = isMouseButton != null && isMouseButton().value() + val bind = + if (isMouse) { + val num = + try { + nameArg().value().toInt() + } catch (_: NumberFormatException) { + return@executeWithResult failure("${nameArg().value()} doesn't match with a mouse button") + } + Bind(0, 0, mouse = num) + } else { + try { + Bind(KeyCode.valueOf(nameArg().value()).code, 0) + } catch (_: IllegalArgumentException) { + return@executeWithResult failure("${nameArg().value()} doesn't match with a bind") + } } - bind = Bind(0, 0, mouse = num) - } else { - bind = try { - Bind(KeyCode.valueOf(nameArg().value()).code, 0) - } catch (_: IllegalArgumentException) { - return@executeWithResult failure("${nameArg().value()} doesn't match with a bind") - } - } trySetValue(bind) return@executeWithResult success() @@ -244,7 +245,6 @@ class KeybindSetting( fun onReleaseUnsafe(block: (ButtonEvent) -> Unit) = apply { unsafeReleaseListeners.add(block) } } -@Suppress("unused") @JsonIncludeProperties("key", "modifiers", "mouse") data class Bind( val key: Int, diff --git a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt index a77473fe8..c55a370c5 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt @@ -45,13 +45,29 @@ class Vec3dSetting( defaultValue: Vec3d ) : Setting(name, description, defaultValue, layer, config, visibility) { @Composable - override fun Editor() { + override fun Gui() { val vec by observe { value } Labeled(name) { - val parse = { text: String -> text.toDoubleOrNull()?.takeIf(Double::isFinite) } - NumberInput(vec.x, parse, { value = Vec3d(it, vec.y, vec.z) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) - NumberInput(vec.y, parse, { value = Vec3d(vec.x, it, vec.z) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) - NumberInput(vec.z, parse, { value = Vec3d(vec.x, vec.y, it) }, Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH)) + val parse = + { text: String -> text.toDoubleOrNull()?.takeIf(Double::isFinite) } + NumberInput( + vec.x, + parse, + { value = Vec3d(it, vec.y, vec.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + vec.y, + parse, + { value = Vec3d(vec.x, it, vec.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + vec.z, + parse, + { value = Vec3d(vec.x, vec.y, it) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) } } 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 764d9039b..4c61ff945 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt @@ -43,7 +43,8 @@ class IntegerSetting( override var step: Int = 1, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { - override fun convert(number: BigDecimal) = number.setScale(0, RoundingMode.HALF_UP).toInt() + override fun convert(number: BigDecimal) = + number.setScale(0, RoundingMode.HALF_UP).toInt() override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(integer(name, range.start, range.endInclusive)) { parameter -> diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index a8e2097f4..486fbee9c 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -39,7 +39,9 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { .onValueChange { _, to -> if (to) setLambdaWindowIcon() else { - val icon = if (SharedConstants.getGameVersion().stable()) Icons.RELEASE else Icons.SNAPSHOT + val icon = + if (SharedConstants.getGameVersion().stable()) Icons.RELEASE + else Icons.SNAPSHOT mc.window.setIcon(mc.defaultResourcePack, icon) } } @@ -64,7 +66,11 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @Tab(SNAPPING_TAB) val snapDistanceGrid by setting("Snap Distance (Grid)", 12f, 1f..48f, 1f) { snapEnabled } @Tab(SNAPPING_TAB) val snapLineColor by setting("Snap Line Color", Color(255, 160, 0, 220)) { snapEnabled && showSnapLines } - internal data class WindowPlacement(val x: Float, val y: Float, val collapsed: Boolean) { + internal data class WindowPlacement( + val x: Float, + val y: Float, + val collapsed: Boolean + ) { val inRow get() = x.isNaN() || y.isNaN() companion object { @@ -99,6 +105,10 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { 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()) + 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 index 3145c367c..412590ce8 100644 --- a/src/main/kotlin/com/lambda/gui/GuiScreen.kt +++ b/src/main/kotlin/com/lambda/gui/GuiScreen.kt @@ -46,7 +46,8 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { AutoDisconnectScreen::class.java, ) - fun canOpenOver(screen: Screen?) = screen == null || backgroundScreens.any { it.isInstance(screen) } + fun canOpenOver(screen: Screen?) = + screen == null || backgroundScreens.any { it.isInstance(screen) } internal fun show() { parent = mc.currentScreen @@ -67,9 +68,19 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { override fun shouldPause() = false - override fun render(context: DrawContext, mouseX: Int, mouseY: Int, deltaTicks: Float) = Unit - - override fun renderBackground(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { + override fun render( + context: DrawContext, + mouseX: Int, + mouseY: Int, + deltaTicks: Float + ) = Unit + + override fun renderBackground( + context: DrawContext, + mouseX: Int, + mouseY: Int, + delta: Float + ) { val parent = parent if (parent != null) { parent.renderBackground(context, -1, -1, delta) @@ -111,7 +122,12 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { return true } - override fun mouseScrolled(mouseX: Double, mouseY: Double, horizontalAmount: Double, verticalAmount: Double): Boolean { + override fun mouseScrolled( + mouseX: Double, + mouseY: Double, + horizontalAmount: Double, + verticalAmount: Double + ): Boolean { LambdaGui.input?.scroll(horizontalAmount, verticalAmount) return true } diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index c0c6ebd39..ed9020614 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -113,7 +113,7 @@ object LambdaGui : Loadable { fun open(screen: Screen) { if (broken) { - warn("Lambda's interface stopped after repeated errors. Check the log, and restart the game to bring it back.") + warn("Lambda's GUI stopped after repeated errors. Restart the game to bring it back.") return } if (this.screen == null) { @@ -162,7 +162,13 @@ object LambdaGui : Loadable { val redraw = sceneChanged || itemsChanged if (redraw) host.draw(beforeScene = ItemAtlas::import) - GuiCompositor.composite(host.texture ?: return, size.width, size.height, redraw, effects(density)) + GuiCompositor.composite( + host.texture ?: return, + size.width, + size.height, + redraw, + effects(density) + ) } catch (e: Throwable) { if (e is OutOfMemoryError) throw e fail(e) @@ -174,7 +180,11 @@ object LambdaGui : Loadable { if (now - failedAt > FAILURE_WINDOW_NANOS) failures = 0 failedAt = now broken = ++failures >= MAX_FAILURES - LOG.error(if (broken) "Lambda's interface failed again and was switched off" else "Lambda's interface failed and is being rebuilt", error) + LOG.error( + if (broken) "Lambda's interface failed again and was switched off" + else "Lambda's interface failed and is being rebuilt", + error + ) val failed = host host = null @@ -216,7 +226,10 @@ object LambdaGui : Loadable { @Composable private fun Content() { - CompositionLocalProvider(LocalObservations provides observations, LocalClipboard provides GameClipboard) { + CompositionLocalProvider( + LocalObservations provides observations, + LocalClipboard provides GameClipboard + ) { LambdaTheme { KeyboardFocus.Layer() Reveal.Expiry() @@ -226,7 +239,12 @@ object LambdaGui : Loadable { Screen.ClickGui -> Unit null -> HudLayer() } - Retained(shown = screen == Screen.ClickGui || warmingUp, clickGuiObservations) { ClickGui() } + Retained( + shown = screen == Screen.ClickGui || warmingUp, + clickGuiObservations + ) { + ClickGui() + } if (warmingUp) WarmUp() } } @@ -243,7 +261,9 @@ object LambdaGui : Loadable { else -> GuiCompositor.Effects( frost = if (Style.blur) Style.blurRadius * density else 0f, - glow = if (Style.glow && screen == Screen.ClickGui) Style.glowRadius * density else 0f, + glow = + if (Style.glow && screen == Screen.ClickGui) Style.glowRadius * density + else 0f, glowIntensity = Style.glowIntensity, glowColorA = Style.glowColorA, glowColorB = Style.glowColorB, diff --git a/src/main/kotlin/com/lambda/gui/Reveal.kt b/src/main/kotlin/com/lambda/gui/Reveal.kt index 5a310b521..2b1cccd47 100644 --- a/src/main/kotlin/com/lambda/gui/Reveal.kt +++ b/src/main/kotlin/com/lambda/gui/Reveal.kt @@ -64,13 +64,18 @@ internal object Reveal { } } - private fun owner(config: Config): Module? = - config as? Module ?: config.takeIf { it !== AutomationConfig.DEFAULT } - ?.let { ModuleRegistry.modules.firstOrNull { module -> module.automationConfig === config } } + private fun owner(config: Config): Module? = config as? Module + ?: config.takeIf { it !== AutomationConfig.DEFAULT } + ?.let { + ModuleRegistry.modules.firstOrNull { module -> + module.automationConfig === config + } + } private fun uncover(module: Module) { val tag = module.tag - if (tag == ModuleTag.DEBUG) ClickGuiState.developerMode = true else ModuleTag.shownTags += tag + if (tag == ModuleTag.DEBUG) ClickGuiState.developerMode = + true else ModuleTag.shownTags += tag module.showInClickGui.value = true GuiConfig.windows[tag.name]?.takeIf { it.collapsed }?.let { GuiConfig.windows += tag.name to it.copy(collapsed = false) diff --git a/src/main/kotlin/com/lambda/gui/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt index f0ed2d349..8e924d63f 100644 --- a/src/main/kotlin/com/lambda/gui/Snap.kt +++ b/src/main/kotlin/com/lambda/gui/Snap.kt @@ -49,13 +49,23 @@ internal object Snap { private class Target(val shift: Float, val guide: Float?) val isActive: Boolean - get() = GuiConfig.snapEnabled && (GuiConfig.snapKey == Bind.EMPTY || GuiConfig.snapKey.isSatisfied()) - - private fun gridStep(density: Density) = with(density) { max(MIN_GRID_STEP, GuiConfig.gridSize.dp.toPx()) } - - fun free(element: Rect, area: Rect) = Result(element.topLeft.keptIn(area, element.size), Guides.NONE) - - fun snap(element: Rect, others: Collection, area: Rect, density: Density, spacing: Float = 0f): Result = + get() = + GuiConfig.snapEnabled && + (GuiConfig.snapKey == Bind.EMPTY || GuiConfig.snapKey.isSatisfied()) + + private fun gridStep(density: Density) = + with(density) { max(MIN_GRID_STEP, GuiConfig.gridSize.dp.toPx()) } + + fun free(element: Rect, area: Rect) = + Result(element.topLeft.keptIn(area, element.size), Guides.NONE) + + fun snap( + element: Rect, + others: Collection, + area: Rect, + density: Density, + spacing: Float = 0f + ): Result = with(density) { fun axis(start: (Rect) -> Float, end: (Rect) -> Float): Target { fun center(rect: Rect) = (start(rect) + end(rect)) / 2 @@ -80,7 +90,12 @@ internal object Snap { if (GuiConfig.snapToCenters) others.forEach { add(centerAt(center(it))) } } val middle = center(area) - val screenCenter = listOf(startAt(middle), centerAt(middle), endAt(middle)).takeIf { GuiConfig.snapToScreenCenter }.orEmpty() + val screenCenter = + listOf( + startAt(middle), + centerAt(middle), + endAt(middle) + ).takeIf { GuiConfig.snapToScreenCenter }.orEmpty() val step = gridStep(density) fun onGrid(line: Float) = (line / step).roundToInt() * step val grid = diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index fb4c6478b..4c3a0a1df 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -24,7 +24,6 @@ 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 @@ -88,7 +87,8 @@ import kotlin.math.absoluteValue private val REACH = 40.dp private const val IN_ROW = 1.5f -private val EMBOSS = Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05f), Color.Transparent)) +private val EMBOSS = + Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05f), Color.Transparent)) @Composable internal fun CategoryWindow( @@ -102,14 +102,23 @@ internal fun CategoryWindow( onFocus: () -> Unit, modifier: Modifier = Modifier, ) { - val modules by observe { ModuleRegistry.modules.filter { it.tag == tag && it.showInClickGui.value } } + val modules by + observe { + ModuleRegistry.modules.filter { it.tag == tag && it.showInClickGui.value } + } if (modules.isEmpty()) return val colors = LambdaTheme.colors val density = LocalDensity.current val screen = LocalWindowInfo.current.containerSize.toSize() val screenHeight = with(density) { screen.height.toDp() } - val area = Rect(0f, with(density) { MENU_BAR_HEIGHT.toPx() }, screen.width, screen.height) + val area = + Rect( + 0f, + with(density) { MENU_BAR_HEIGHT.toPx() }, + screen.width, + screen.height + ) val placement by observe { GuiConfig.windows[tag.name] } val position = placement?.takeUnless { it.inRow }?.let { DpOffset(it.x.dp, it.y.dp) } @@ -119,7 +128,15 @@ internal fun CategoryWindow( val drop = dragged?.let { corner -> val window = Rect(corner, bounds[tag]?.size ?: Size.Zero) - if (snapping) Snap.snap(window, bounds.filterKeys { it != tag }.values, area, density, with(density) { Look.windowGap.toPx() }) + if (snapping) { + Snap.snap( + window, + bounds.filterKeys { it != tag }.values, + area, + density, + with(density) { Look.windowGap.toPx() } + ) + } else Snap.free(window, area) } if (drop != null) SideEffect { onDrop(drop) } @@ -129,8 +146,14 @@ internal fun CategoryWindow( } ?: (position ?: defaultPosition).let { at -> val screenWidth = with(density) { screen.width.toDp() } DpOffset( - at.x.coerceIn(0.dp, (screenWidth - Look.windowWidth).coerceAtLeast(0.dp)), - at.y.coerceIn(MENU_BAR_HEIGHT, (screenHeight - REACH).coerceAtLeast(MENU_BAR_HEIGHT)), + at.x.coerceIn( + 0.dp, + (screenWidth - Look.windowWidth).coerceAtLeast(0.dp) + ), + at.y.coerceIn( + MENU_BAR_HEIGHT, + (screenHeight - REACH).coerceAtLeast(MENU_BAR_HEIGHT) + ), ) } val currentPosition by rememberUpdatedState(shownPosition) @@ -139,7 +162,8 @@ internal fun CategoryWindow( } fun place(at: DpOffset, collapsed: Boolean) { - val inRow = (at.x - defaultPosition.x).value.absoluteValue < IN_ROW && (at.y - defaultPosition.y).value.absoluteValue < IN_ROW + val inRow = (at.x - defaultPosition.x).value.absoluteValue < IN_ROW && + (at.y - defaultPosition.y).value.absoluteValue < IN_ROW GuiConfig.windows += tag.name to if (inRow) GuiConfig.WindowPlacement.inRow(collapsed) else GuiConfig.WindowPlacement(at.x.value, at.y.value, collapsed) @@ -156,7 +180,8 @@ internal fun CategoryWindow( .pointerInput(Unit) { awaitPointerEventScope { while (true) { - if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) onFocus() + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Press) onFocus() } } } @@ -196,7 +221,11 @@ internal fun CategoryWindow( enter = expandVertically(Motion.windows), exit = shrinkVertically(Motion.windows), ) { - ScrollColumn(Modifier.heightIn(max = (screenHeight - shownPosition.y - 24.dp).coerceAtLeast(48.dp))) { + ScrollColumn( + Modifier.heightIn( + max = (screenHeight - shownPosition.y - 24.dp).coerceAtLeast(48.dp) + ) + ) { modules.forEach { module -> ModuleRow( module = module, @@ -205,23 +234,46 @@ internal fun CategoryWindow( panel = settings.panelOf(module).takeUnless { inline }, onEdit = { settings.toggle(module) }, ) - if (inline) InlineSettings(settings.stateOf(module), open = settings.isOpen(module)) + if (inline) { + InlineSettings( + settings.stateOf(module), + open = settings.isOpen(module) + ) + } } } } } } -@OptIn(ExperimentalFoundationApi::class) @Composable -private fun ModuleRow(module: Module, isEdited: Boolean, pressedIn: Boolean, panel: SettingsPanelState?, onEdit: () -> Unit) { +private fun ModuleRow( + module: Module, + isEdited: Boolean, + pressedIn: Boolean, + panel: SettingsPanelState?, + onEdit: () -> Unit +) { val colors = LambdaTheme.colors val enabled by observe { module.isEnabled } - val fill by animateColorAsState(if (enabled) colors.moduleEnabled else Color.Transparent, spring()) - val pressed by animateColorAsState(if (isEdited && pressedIn) colors.inset.copy(alpha = colors.inset.alpha / 2) else Color.Transparent, spring()) + val fill by + animateColorAsState( + if (enabled) colors.moduleEnabled else Color.Transparent, + spring() + ) + val pressed by + animateColorAsState( + if (isEdited && pressedIn) colors.inset.copy(alpha = colors.inset.alpha / 2) + else Color.Transparent, + spring() + ) val revealed = Reveal.module === module && Reveal.setting == null - val lit by animateColorAsState(if (revealed) colors.onSurface.copy(alpha = 0.4f) else Color.Transparent, tween(250)) + val 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() @@ -234,10 +286,14 @@ private fun ModuleRow(module: Module, isEdited: Boolean, pressedIn: Boolean, pan .fillMaxWidth() .then( if (panel == null) Modifier - else Modifier.onGloballyPositioned { panel.row = Rect(it.positionInRoot(), it.size.toSize()) } + else Modifier.onGloballyPositioned { + panel.row = Rect(it.positionInRoot(), it.size.toSize()) + } ) .bringIntoViewRequester(intoView) - .mouseClickable(onRightClick = onEdit) { if (module.alwaysEnabled) onEdit() else module.toggle() } + .mouseClickable(onRightClick = onEdit) { + if (module.alwaysEnabled) onEdit() else module.toggle() + } .background(fill) .background(pressed) .background(lit) diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index f270e1d02..ef5cb2f98 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -85,7 +85,9 @@ internal fun ClickGui() { val screen = LocalWindowInfo.current.containerSize val developerMode = ClickGuiState.developerMode val tags by observe { - CLICK_GUI_CATEGORIES.filter(ModuleTag::isTagShown) + listOfNotNull(ModuleTag.DEBUG.takeIf { developerMode }) + CLICK_GUI_CATEGORIES.filter(ModuleTag::isTagShown) + listOfNotNull( + ModuleTag.DEBUG.takeIf { developerMode } + ) } val settings = remember { OpenSettings() } @@ -94,7 +96,13 @@ internal fun ClickGui() { val revealedModule = Reveal.module val revealedSetting = Reveal.setting LaunchedEffect(revealedModule, revealedSetting) { - if (revealedModule != null && revealedModule !is HudModule && revealedSetting != null) settings.open(revealedModule) + if ( + revealedModule != null && + revealedModule !is HudModule && + revealedSetting != null + ) { + settings.open(revealedModule) + } } val shown = LocalShown.current @@ -106,7 +114,10 @@ internal fun ClickGui() { val laidOut = remember { RowLayout(row) } SideEffect { if (row != laidOut.row && shown && laidOut.shown) { - GuiConfig.windows = GuiConfig.windows.mapValues { GuiConfig.WindowPlacement.inRow(it.value.collapsed) } + GuiConfig.windows = + GuiConfig.windows.mapValues { + GuiConfig.WindowPlacement.inRow(it.value.collapsed) + } } laidOut.row = row laidOut.shown = shown @@ -117,12 +128,21 @@ internal fun ClickGui() { val snapping by observe { Snap.isActive } var drop by remember { mutableStateOf(null) } - Box(Modifier.fillMaxSize().mouseClickable(keyboard = false, onClick = settings::closeAll).snapLines { drop }) { + Box( + Modifier.fillMaxSize().mouseClickable( + keyboard = false, + onClick = settings::closeAll + ).snapLines { + drop + } + ) { val inRow = tags.count { it != ModuleTag.DEBUG } val screenWidth = with(density) { screen.width.toDp() } val pitch = (Look.windowWidth + Look.windowGap) - .coerceAtMost((screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1)) + .coerceAtMost( + (screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1) + ) .coerceAtLeast(0.dp) val rowWidth = Look.windowWidth + pitch * (inRow - 1) val rowStart = ((screenWidth - rowWidth) / 2).coerceAtLeast(0.dp) @@ -165,14 +185,18 @@ internal fun ClickGui() { .pointerInput(Unit) { awaitPointerEventScope { while (true) { - if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) settings.closeAll() + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Press) settings.closeAll() } } } ) Button( label = "HUD Editor", - modifier = Modifier.align(Alignment.BottomEnd).padding(4.dp).zIndex(stacking.size + 1f), + modifier = Modifier + .align(Alignment.BottomEnd) + .padding(4.dp) + .zIndex(stacking.size + 1f), prominent = true, ) { LambdaGui.open(LambdaGui.Screen.HudEditor) } } @@ -183,7 +207,8 @@ internal fun ClickGui() { when { prompt != null -> LoaderPromptDialog(prompt) dialog is ClickGuiDialog.About -> AboutDialog(closeDialog) - dialog is ClickGuiDialog.NewAutomationConfig -> NewAutomationConfigDialog(closeDialog) + dialog is ClickGuiDialog.NewAutomationConfig -> + NewAutomationConfigDialog(closeDialog) dialog is ClickGuiDialog.Settings -> ConfigDialog(dialog.config, closeDialog) } } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt index 50be533d5..79a51a955 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt @@ -45,7 +45,9 @@ internal class OpenSettings { fun stateOf(module: Module) = states.getOrPut(module) { SettingsPanelState(module) } - fun panelOf(module: Module) = if (module in open || module in closing) stateOf(module) else null + fun panelOf(module: Module) = + if (module in open || module in closing) stateOf(module) + else null fun isOpen(module: Module) = module in open @@ -55,13 +57,16 @@ internal class OpenSettings { if (module !in open) open += module } - fun toggle(module: Module) = if (isOpen(module)) close(module) else open(module) + fun toggle(module: Module) = + if (isOpen(module)) close(module) + else open(module) fun close(module: Module) { if (open.remove(module)) closing += module } - fun close(modules: Collection) = open.filter { it in modules }.forEach(::close) + fun close(modules: Collection) = + open.filter { it in modules }.forEach(::close) fun closeAll() = open.toList().forEach(::close) diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index d3c15f71b..333fe1c7a 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -25,7 +25,6 @@ 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.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -127,8 +126,15 @@ internal fun SettingsPanel( val barBottom = with(density) { MENU_BAR_HEIGHT.toPx() } val window = windows[panel.module.tag] val top = - (if (window == null) row.top else row.top.coerceIn(window.top, (window.bottom - row.height).coerceAtLeast(window.top))) - .coerceAtLeast(barBottom) + ( + if (window == null) row.top + else { + row.top.coerceIn( + window.top, + (window.bottom - row.height).coerceAtLeast(window.top) + ) + } + ).coerceAtLeast(barBottom) val below = with(density) { (screen.height - top).toDp() }.coerceAtLeast(MIN_HEIGHT) val highest = screenHeight - MENU_BAR_HEIGHT val maxHeight = (below + panel.extension).coerceAtMost(highest) @@ -146,7 +152,9 @@ internal fun SettingsPanel( bottomEnd = Look.panelRounding, bottomStart = Look.panelRounding, ) - val seam = if (flipped) Alignment.TopEnd else Alignment.TopStart + val seam = + if (flipped) Alignment.TopEnd + else Alignment.TopStart Box( modifier @@ -180,16 +188,33 @@ internal fun SettingsPanel( .window(colors.panel, colors.border, shape) ) { CompositionLocalProvider(LocalPopupHost provides popups) { - Column(Modifier.padding(Look.panelPadding)) { ModuleSettings(panel.module, panel.page, { panel.page = it }, scroll) } + Column(Modifier.padding(Look.panelPadding)) { + ModuleSettings( + panel.module, + panel.page, + { panel.page = it }, + scroll + ) + } } if (scroll.maxValue > 0 || lift > 0f) { Grip( onDragStart = { - panel.extension = panel.extension.coerceAtMost(with(density) { lift.toDp() }) + 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)) + 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) ) @@ -199,7 +224,6 @@ internal fun SettingsPanel( } } -@OptIn(ExperimentalFoundationApi::class) @Composable internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { val intoView = remember { BringIntoViewRequester() } @@ -221,10 +245,19 @@ internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { val depth = INSET_SHADOW.toPx().coerceAtMost(size.height / 2) val dark = colors.inset.copy(alpha = colors.inset.alpha / 2) val top = Brush.verticalGradient(listOf(dark, Color.Transparent), 0f, depth) - val bottom = Brush.verticalGradient(listOf(Color.Transparent, dark), size.height - depth, size.height) + val bottom = + Brush.verticalGradient( + listOf(Color.Transparent, dark), + size.height - depth, + size.height + ) onDrawBehind { drawRect(top, size = Size(size.width, depth)) - drawRect(bottom, Offset(0f, size.height - depth), Size(size.width, depth)) + drawRect( + bottom, + Offset(0f, size.height - depth), + Size(size.width, depth) + ) } } .padding(Look.panelPadding / 2) @@ -241,15 +274,26 @@ private fun Modifier.widthOfContent(): Modifier = measurable.maxIntrinsicWidth(constraints.maxHeight) .coerceIn(constraints.minWidth, constraints.maxWidth).toFloat() val current = width ?: Animatable(wanted).also { width = it } - if (current.targetValue != wanted) scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } + if (current.targetValue != wanted) { + scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } + } - val placeable = measurable.measure(Constraints.fixedWidth(current.value.roundToInt()).copy(maxHeight = constraints.maxHeight)) + val placeable = + measurable.measure( + Constraints.fixedWidth(current.value.roundToInt()).copy( + maxHeight = constraints.maxHeight + ) + ) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } } @Composable -private fun Grip(onDragStart: () -> Unit, onDrag: (up: Dp) -> Unit, modifier: Modifier = Modifier) { +private fun Grip( + onDragStart: () -> Unit, + onDrag: (up: Dp) -> Unit, + modifier: Modifier = Modifier +) { val density = LocalDensity.current val color = LambdaTheme.colors.onSurfaceVariant Box( @@ -258,7 +302,9 @@ private fun Grip(onDragStart: () -> Unit, onDrag: (up: Dp) -> Unit, modifier: Mo .fillMaxWidth() .height(Look.panelPadding.coerceAtLeast(MIN_GRIP_HEIGHT)) .pointerHoverIcon(ResizeVerticalIcon) - .mouseDraggable(onDragStart = onDragStart) { delta -> onDrag(with(density) { -delta.y.toDp() }) } + .mouseDraggable(onDragStart = onDragStart) { delta -> + onDrag(with(density) { -delta.y.toDp() }) + } ) { Spacer(Modifier.size(16.dp, 1.dp).background(color, RoundedCornerShape(50))) } diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt index 5344534a4..ee9ef830b 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -78,8 +78,12 @@ fun Button( onClick: () -> Unit, ) { val colors = LambdaTheme.colors - val fill = if (prominent) colors.header else colors.control - val text = if (prominent) colors.onHeader else colors.onControl + val fill = + if (prominent) colors.header + else colors.control + val text = + if (prominent) colors.onHeader + else colors.onControl Box( contentAlignment = Alignment.Center, modifier = modifier @@ -122,12 +126,18 @@ fun Ellipsis(modifier: Modifier = Modifier, color: Color = LocalContentColor.cur 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)) } + repeat(3) { + drawRect(color, Offset(it * (size.width - dot) / 2, top), Size(dot, dot)) + } } } @Composable -fun Chevron(degrees: Float, modifier: Modifier = Modifier, color: Color = LocalContentColor.current) { +fun Chevron( + degrees: Float, + modifier: Modifier = Modifier, + color: Color = LocalContentColor.current +) { Canvas(modifier.size(5.dp).rotate(degrees)) { drawPath( path = Path().apply { @@ -142,7 +152,11 @@ fun Chevron(degrees: Float, modifier: Modifier = Modifier, color: Color = LocalC } @Composable -fun Expandable(visible: Boolean, modifier: Modifier = Modifier, content: @Composable () -> Unit) { +fun Expandable( + visible: Boolean, + modifier: Modifier = Modifier, + content: @Composable () -> Unit +) { AnimatedVisibility( visible = visible, modifier = modifier, @@ -191,13 +205,20 @@ fun Section( Text(title, color = colors.onSurface, maxLines = 1) } Expandable(expanded) { - Column(Modifier.fillMaxWidth().padding(start = Look.groupIndent, top = 1.dp), content = content) + Column( + Modifier.fillMaxWidth().padding(start = Look.groupIndent, top = 1.dp), + content = content + ) } } } @Composable -fun Chip(onClick: () -> Unit, modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) { +fun Chip( + onClick: () -> Unit, + modifier: Modifier = Modifier, + content: @Composable RowScope.() -> Unit +) { val colors = LambdaTheme.colors ContentColor(colors.onControl) { Row( @@ -232,7 +253,11 @@ fun Dropdown( SlidingText(optionLabel(selected), Modifier.weight(1f, fill = false)) Chevron(90f) } - Menu(menu.isOpen, onDismiss = menu::dismiss, unfoldFrom = IntSize(chip.width, 0)) { + 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) @@ -244,11 +269,19 @@ fun Dropdown( } @Composable -fun LabeledRow(label: String, modifier: Modifier = Modifier, editor: @Composable RowScope.() -> Unit) { +fun LabeledRow( + label: String, + modifier: Modifier = Modifier, + editor: @Composable RowScope.() -> Unit +) { Layout( content = { Text(label, maxLines = 1) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(LABEL_GAP), content = editor) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(LABEL_GAP), + content = editor + ) }, modifier = modifier.fillMaxWidth().heightIn(min = Look.rowHeight), ) { (name, edited), constraints -> @@ -258,12 +291,23 @@ fun LabeledRow(label: String, modifier: Modifier = Modifier, editor: @Composable val wanted = edited.maxIntrinsicWidth(constraints.maxHeight) val editorWidth = if (!constraints.hasBoundedWidth) wanted - else wanted.coerceAtMost(maxOf(room - name.maxIntrinsicWidth(constraints.maxHeight) - gap, room * 3 / 5)) + else { + wanted.coerceAtMost( + maxOf( + room - name.maxIntrinsicWidth(constraints.maxHeight) - gap, + room * 3 / 5 + ) + ) + } val editor = edited.measure(loose.copy(maxWidth = editorWidth.coerceAtLeast(0))) - val nameRoom = if (constraints.hasBoundedWidth) (room - editor.width - gap).coerceAtLeast(0) else Constraints.Infinity + val nameRoom = + if (constraints.hasBoundedWidth) (room - editor.width - gap).coerceAtLeast(0) + else Constraints.Infinity val text = name.measure(loose.copy(maxWidth = nameRoom)) - val width = if (constraints.hasBoundedWidth) room else text.width + gap + editor.width + val width = + if (constraints.hasBoundedWidth) room + else text.width + gap + editor.width val height = maxOf(text.height, editor.height, constraints.minHeight) layout(width, height) { text.place(0, (height - text.height) / 2) diff --git a/src/main/kotlin/com/lambda/gui/component/Images.kt b/src/main/kotlin/com/lambda/gui/component/Images.kt index b68555340..558852697 100644 --- a/src/main/kotlin/com/lambda/gui/component/Images.kt +++ b/src/main/kotlin/com/lambda/gui/component/Images.kt @@ -38,13 +38,20 @@ import kotlin.math.roundToInt @Composable fun rememberTexture(path: String): ImageBitmap = - remember(path) { path.stream.use { Image.makeFromEncoded(it.readAllBytes()) }.toComposeImageBitmap() } + remember(path) { + path.stream + .use { Image.makeFromEncoded(it.readAllBytes()) } + .toComposeImageBitmap() + } @Composable fun ItemIcon(stack: ItemStack, size: Dp, modifier: Modifier = Modifier) { val slot = remember { ItemAtlas.Slot() } val density = LocalDensity.current - val pixels = with(density) { ItemAtlas.ITEM * (size.toPx() / ItemAtlas.ITEM).roundToInt().coerceAtLeast(1) } + val pixels = + with(density) { + ItemAtlas.ITEM * (size.toPx() / ItemAtlas.ITEM).roundToInt().coerceAtLeast(1) + } SideEffect { slot.stack = stack slot.size = pixels diff --git a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt index fab65bc8c..58c89c7b4 100644 --- a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt +++ b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt @@ -77,7 +77,12 @@ fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = drawContent() if (!focused || !KeyboardFocus.visible) return@drawWithContent val width = FOCUS_MARK.toPx() - drawRect(mark, Offset(width / 2, width / 2), Size(size.width - width, size.height - width), style = Stroke(width)) + drawRect( + mark, + Offset(width / 2, width / 2), + Size(size.width - width, size.height - width), + style = Stroke(width) + ) } } diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt index 7f1aa9479..9ed115f65 100644 --- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -60,8 +60,11 @@ fun Modifier.mouseClickable( } } val keys = - if (!keyboard) Modifier else Modifier.keyboardFocusable { event -> - val action = if (event.isShiftPressed) onRightClick else onClick ?: onRightClick + if (!keyboard) Modifier + else Modifier.keyboardFocusable { event -> + val action = + if (event.isShiftPressed) onRightClick + else onClick ?: onRightClick if (event.isActivation) action?.invoke() event.isActivation && action != null } @@ -84,7 +87,8 @@ fun Modifier.mouseClickable( 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() + val inside = change.position.x in 0f..size.width.toFloat() && + change.position.y in 0f..size.height.toFloat() if (inside) actionFor(button)?.invoke() break } @@ -95,14 +99,19 @@ fun Modifier.mouseClickable( val LocalClickOnRelease = compositionLocalOf { false } -fun Modifier.onMousePress(button: PointerButton, onPress: (position: Offset) -> Unit): Modifier = +fun Modifier.onMousePress( + button: PointerButton, + onPress: (position: Offset) -> Unit +): Modifier = onPress { pressed, position -> if (pressed == button) onPress(position) pressed == button } @OptIn(ExperimentalComposeUiApi::class) -private fun Modifier.onPress(handle: (button: PointerButton?, position: Offset) -> Boolean): Modifier = +private fun Modifier.onPress( + handle: (button: PointerButton?, position: Offset) -> Boolean +): Modifier = composed { val currentHandle by rememberUpdatedState(handle) pointerInput(Unit) { @@ -141,7 +150,10 @@ fun Modifier.mouseDraggable( onDrag = onDrag, ) -fun Modifier.scrubbable(onEnd: () -> Unit = {}, onScrub: (position: Offset, size: IntSize) -> Unit): Modifier = +fun Modifier.scrubbable( + onEnd: () -> Unit = {}, + onScrub: (position: Offset, size: IntSize) -> Unit +): Modifier = composed { val currentOnScrub by rememberUpdatedState(onScrub) val currentOnEnd by rememberUpdatedState(onEnd) diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 11e308a06..21f612d24 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -157,7 +157,14 @@ fun Menu( attached: Boolean = false, content: @Composable ColumnScope.() -> Unit, ) { - MenuPopup(open, remember(placement) { UnfoldingPosition(placement::place) }, onDismiss, unfoldFrom, attached, content) + MenuPopup( + open, + remember(placement) { UnfoldingPosition(placement::place) }, + onDismiss, + unfoldFrom, + attached, + content + ) } private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize) = @@ -165,26 +172,53 @@ private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize MenuPlacement.Below -> IntOffset( anchor.left, - if (anchor.bottom + popup.height <= window.height || anchor.top - popup.height < 0) anchor.bottom else anchor.top - popup.height + if (anchor.bottom + popup.height <= window.height || + anchor.top - popup.height < 0 + ) { + anchor.bottom + } + else anchor.top - popup.height ) MenuPlacement.Beside -> IntOffset( - if (anchor.right + popup.width <= window.width) anchor.right else anchor.left - popup.width, + if (anchor.right + popup.width <= window.width) anchor.right + else anchor.left - popup.width, anchor.top ) } @Composable -fun Popout(open: Boolean, onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { +fun Popout( + open: Boolean, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit +) { val position = remember { UnfoldingPosition(MenuPlacement.Beside::place) } - FloatingPanel(open, position, onDismiss, RoundedCornerShape(Look.panelRounding)) { panel -> + FloatingPanel( + open, + position, + onDismiss, + RoundedCornerShape(Look.panelRounding) + ) { panel -> Column(panel.padding(3.dp), content = content) } } @Composable -fun ContextMenu(open: Boolean, position: IntOffset, onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) = - MenuPopup(open, remember(position) { UnfoldingPosition { _, _, _ -> position } }, onDismiss, IntSize.Zero, false, content) +fun ContextMenu( + open: Boolean, + position: IntOffset, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit +) = + MenuPopup( + open, + remember(position) { UnfoldingPosition { _, _, _ -> position } }, + onDismiss, + IntSize.Zero, + false, + content + ) @Composable fun rememberLast(value: T?): T? { @@ -252,7 +286,8 @@ class PopupHost { val LocalPopupHost = compositionLocalOf { null } private fun Modifier.swallowedBy(host: PopupHost?): Modifier = - if (host == null) this else composed { + if (host == null) this + else composed { var origin by remember { mutableStateOf(Offset.Zero) } onGloballyPositioned { origin = it.positionInWindow() }.drawWithContent { if (!host.closing) return@drawWithContent drawContent() @@ -344,8 +379,12 @@ private class UnfoldingPosition( val corner get() = when { - upwards -> if (leftwards) Alignment.BottomEnd else Alignment.BottomStart - else -> if (leftwards) Alignment.TopEnd else Alignment.TopStart + upwards -> + if (leftwards) Alignment.BottomEnd + else Alignment.BottomStart + else -> + if (leftwards) Alignment.TopEnd + else Alignment.TopStart } override fun calculatePosition( @@ -354,7 +393,11 @@ private class UnfoldingPosition( layoutDirection: LayoutDirection, popupContentSize: IntSize, ): IntOffset { - val full = IntSize(max(unfolded.width, popupContentSize.width), max(unfolded.height, popupContentSize.height)) + 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 @@ -368,7 +411,11 @@ private class UnfoldingPosition( } @Composable -fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { +fun Suggestions( + open: Boolean, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit +) { if (!LocalShown.current) { if (open) SideEffect(onDismiss) return @@ -379,12 +426,16 @@ fun Suggestions(open: Boolean, onDismiss: () -> Unit, content: @Composable Colum val colors = LambdaTheme.colors val shape = RoundedCornerShape(Look.menuRounding) - val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } + val screenHeight = + with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } ScenePopup( popupPositionProvider = remember { positionProvider { anchor, window, popup -> val centred = anchor.left + (anchor.width - popup.width) / 2 - IntOffset(centred.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), anchor.bottom) + IntOffset( + centred.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), + anchor.bottom + ) } }, onDismissRequest = { if (open) onDismiss() }, @@ -444,12 +495,24 @@ fun MenuItem( 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) + if (hint != null) { + Text( + hint, + Modifier.padding(start = 12.dp), + colors.onSurfaceVariant, + Type.label, + maxLines = 1 + ) + } } } @Composable -fun Submenu(label: String, enabled: Boolean = true, content: @Composable ColumnScope.() -> Unit) { +fun Submenu( + label: String, + enabled: Boolean = true, + content: @Composable ColumnScope.() -> Unit +) { val colors = LambdaTheme.colors val menu = remember { MenuState() } Box { @@ -457,19 +520,41 @@ fun Submenu(label: String, enabled: Boolean = true, content: @Composable ColumnS verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() - .then(if (enabled) Modifier.hoverHighlight(colors.controlSelected).mouseClickable(onClick = menu::toggle) else Modifier) + .then( + if (enabled) { + Modifier + .hoverHighlight(colors.controlSelected) + .mouseClickable(onClick = menu::toggle) + } + else Modifier + ) .padding(horizontal = 5.dp, vertical = 1.dp) ) { - Text(label, Modifier.weight(1f), if (enabled) colors.onSurface else colors.onSurfaceVariant, maxLines = 1) + 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) + 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) + Text( + label, + Modifier.padding(horizontal = 5.dp, vertical = 1.dp), + LambdaTheme.colors.onSurfaceVariant, + maxLines = 1 + ) @Composable fun MenuHelp(text: String, label: String = "Help") { @@ -483,7 +568,13 @@ fun MenuHelp(text: String, label: String = "Help") { .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) + Text( + "?", + Modifier.padding(start = 12.dp), + colors.onSurfaceVariant, + Type.label, + maxLines = 1 + ) } } } @@ -506,7 +597,9 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { } val colors = LambdaTheme.colors ScenePopup( - popupPositionProvider = remember { positionProvider { _, _, _ -> IntOffset.Zero } }, + popupPositionProvider = remember { + positionProvider { _, _, _ -> IntOffset.Zero } + }, properties = PopupProperties(focusable = true), onKeyEvent = { onDismiss != null && it.dismissOnEscape(onDismiss) }, ) { @@ -521,7 +614,12 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { ContentColor(colors.onSurface) { Box( modifier = Modifier - .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) + .window( + colors.panel, + colors.border, + RoundedCornerShape(Look.panelRounding), + floating = true + ) .padding(6.dp), content = content ) @@ -531,7 +629,11 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { } @Composable -fun Tooltip(text: String, modifier: Modifier = Modifier, content: @Composable () -> Unit) { +fun Tooltip( + text: String, + modifier: Modifier = Modifier, + content: @Composable () -> Unit +) { if (text.isBlank()) { Box(modifier) { content() } return diff --git a/src/main/kotlin/com/lambda/gui/component/Scroll.kt b/src/main/kotlin/com/lambda/gui/component/Scroll.kt index a52b87a4f..784bf7c3a 100644 --- a/src/main/kotlin/com/lambda/gui/component/Scroll.kt +++ b/src/main/kotlin/com/lambda/gui/component/Scroll.kt @@ -98,11 +98,16 @@ fun Modifier.wheelScrollable(state: ScrollableState): Modifier = if (event.type != PointerEventType.Scroll) continue val change = event.changes.first() val distance = change.scrollDelta.y * notch * Style.scrollSpeed - val canFollow = if (distance > 0) state.canScrollForward else state.canScrollBackward + val canFollow = + if (distance > 0) state.canScrollForward + else state.canScrollBackward if (distance == 0f || !canFollow || change.isConsumed) continue change.consume() - val total = distance + if (glide.remaining * distance > 0) glide.remaining else 0f + val total = + distance + + if (glide.remaining * distance > 0) glide.remaining + else 0f glide.job?.cancel() glide.job = scope.launch(Motion.SCROLL) { @@ -110,14 +115,20 @@ fun Modifier.wheelScrollable(state: ScrollableState): Modifier = glide.remaining = total try { state.scroll(MutatePriority.UserInput) { - animate(0f, total, animationSpec = GLIDE) { value, _ -> + animate( + 0f, + total, + animationSpec = GLIDE + ) { value, _ -> scrollBy(value - travelled) travelled = value glide.remaining = total - value } } } finally { - if (glide.job === coroutineContext[Job]) glide.remaining = 0f + if (glide.job === coroutineContext[Job]) { + glide.remaining = 0f + } } } } diff --git a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt index 7a7d155ce..479c3a07d 100644 --- a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt +++ b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt @@ -94,7 +94,9 @@ fun SlidingText( .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 + overflow = + if (constraints.hasBoundedWidth) (placeable.width - constraints.maxWidth).coerceAtLeast(0) + else 0 layout(placeable.width - overflow, placeable.height) { placeable.place(-(slide.value * overflow).roundToInt(), 0) } diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt index b39a6cbe2..12e8cfb8e 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -81,7 +81,8 @@ fun Modifier.glass(color: Color, shape: Shape): Modifier = remember(sigma, underlay) { if (sigma <= 0f) return@remember null val blurred = ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) - if (underlay >= 1f) blurred else ImageFilter.makeColorFilter(faded(underlay), blurred, null) + if (underlay >= 1f) blurred + else ImageFilter.makeColorFilter(faded(underlay), blurred, null) } drawBehind { if (blur == null) { @@ -96,7 +97,12 @@ fun Modifier.glass(color: Color, shape: Shape): Modifier = } } -fun Modifier.window(color: Color, border: Color, shape: Shape, floating: Boolean = false): Modifier = +fun Modifier.window( + color: Color, + border: Color, + shape: Shape, + floating: Boolean = false +): Modifier = (if (floating) dropShadow(shape) else this) .glass(color, shape) .then(if (Look.outlines) Modifier.border(Look.outlineWidth, border, shape) else Modifier) @@ -116,7 +122,12 @@ fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = onDrawBehind { if (!Look.shadows) return@onDrawBehind clipPath(body, ClipOp.Difference) { - clipRect(-reach, drop - reach, size.width + reach, size.height + drop + reach) { + clipRect( + -reach, + drop - reach, + size.width + reach, + size.height + drop + reach + ) { drawIntoCanvas { canvas -> val skia = canvas.skiaCanvas skia.saveLayer(Canvas.SaveLayerRec(null, null, DRAWN)) diff --git a/src/main/kotlin/com/lambda/gui/component/TextInput.kt b/src/main/kotlin/com/lambda/gui/component/TextInput.kt index 09c3914e9..ea13cd7b4 100644 --- a/src/main/kotlin/com/lambda/gui/component/TextInput.kt +++ b/src/main/kotlin/com/lambda/gui/component/TextInput.kt @@ -119,12 +119,16 @@ fun TextInput( .focusRequester(focus) .onFocusChanged { hasFocus = it.isFocused - if (it.isFocused) hadFocus = - true - else if (hadFocus) onDone?.invoke() + if (it.isFocused) hadFocus = true + else if (hadFocus) onDone?.invoke() } .onPreviewKeyEvent { event -> - if (onDone == null || (event.key != Key.Enter && event.key != Key.Escape)) false + if ( + onDone == null || + (event.key != Key.Enter && event.key != Key.Escape) + ) { + false + } else { if (event.type == KeyEventType.KeyDown) onDone() true @@ -133,7 +137,14 @@ fun TextInput( .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) + if (field.text.isEmpty()) { + Text( + placeholder, + color = colors.onSurfaceVariant, + style = style, + maxLines = 1 + ) + } innerTextField() } } @@ -153,7 +164,9 @@ fun NumberInput( fun finish(commit: Boolean) { val typed = draft draft = null - if (commit && typed != null) parse(typed.trim())?.takeIf { it != value }?.let(onCommit) + if (commit && typed != null) { + parse(typed.trim())?.takeIf { it != value }?.let(onCommit) + } onDone() } TextInput( diff --git a/src/main/kotlin/com/lambda/gui/core/GlState.kt b/src/main/kotlin/com/lambda/gui/core/GlState.kt index fc43946f1..ef8382c87 100644 --- a/src/main/kotlin/com/lambda/gui/core/GlState.kt +++ b/src/main/kotlin/com/lambda/gui/core/GlState.kt @@ -85,11 +85,24 @@ internal object GlState { 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 + 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 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) @@ -111,12 +124,14 @@ internal object GlState { fun prepare() { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) glBindBuffer(GL_PIXEL_PACK_BUFFER, 0) - UNPACK_PARAMETERS.forEachIndexed { index, parameter -> glPixelStorei(parameter, UNPACK_DEFAULTS[index]) } + UNPACK_PARAMETERS.forEachIndexed { index, parameter -> + glPixelStorei(parameter, UNPACK_DEFAULTS[index]) + } } fun capture(): () -> Unit { val activeTexture = glGetInteger(GL_ACTIVE_TEXTURE) - for (unit in 0 until TEXTURE_UNITS) { + repeat(TEXTURE_UNITS) { unit -> glActiveTexture(GL_TEXTURE0 + unit) textures[unit] = glGetInteger(GL_TEXTURE_BINDING_2D) samplers[unit] = glGetInteger(GL_SAMPLER_BINDING) @@ -145,12 +160,16 @@ internal object GlState { } 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) } + 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) { + repeat(TEXTURE_UNITS) { unit -> glActiveTexture(GL_TEXTURE0 + unit) glBindTexture(GL_TEXTURE_2D, textures[unit]) glBindSampler(unit, samplers[unit]) @@ -171,7 +190,9 @@ internal object GlState { CAPABILITIES.forEachIndexed { index, capability -> if (capabilities[index]) glEnable(capability) else glDisable(capability) } - UNPACK_PARAMETERS.forEachIndexed { index, parameter -> glPixelStorei(parameter, unpack[index]) } + UNPACK_PARAMETERS.forEachIndexed { index, parameter -> + glPixelStorei(parameter, unpack[index]) + } } } } diff --git a/src/main/kotlin/com/lambda/gui/core/RenderThread.kt b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt index 1f0d3a8bd..b6dacb820 100644 --- a/src/main/kotlin/com/lambda/gui/core/RenderThread.kt +++ b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt @@ -25,6 +25,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext +import kotlin.time.Duration.Companion.milliseconds object RenderThread : CoroutineDispatcher() { private val scope = CoroutineScope(this + SupervisorJob()) @@ -36,7 +37,7 @@ object RenderThread : CoroutineDispatcher() { @JvmStatic fun after(millis: Long, block: () -> Unit): Job = scope.launch { - delay(millis) + delay(millis.milliseconds) block() } } diff --git a/src/main/kotlin/com/lambda/gui/core/Retained.kt b/src/main/kotlin/com/lambda/gui/core/Retained.kt index b51dce578..b6f37f4e7 100644 --- a/src/main/kotlin/com/lambda/gui/core/Retained.kt +++ b/src/main/kotlin/com/lambda/gui/core/Retained.kt @@ -27,12 +27,21 @@ import androidx.compose.ui.layout.layout val LocalShown = compositionLocalOf { true } @Composable -internal fun Retained(shown: Boolean, observations: Observations, content: @Composable () -> Unit) { - CompositionLocalProvider(LocalShown provides shown, LocalObservations provides observations) { +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) } + 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 index 5e4dd293e..7a0e66483 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt @@ -56,7 +56,10 @@ import org.lwjgl.opengl.GL30.glRenderbufferStorage import kotlin.coroutines.CoroutineContext @OptIn(InternalComposeUiApi::class) -internal class SceneHost(context: CoroutineContext, content: @Composable () -> Unit) : AutoCloseable { +internal class SceneHost( + context: CoroutineContext, + content: @Composable () -> Unit +) : AutoCloseable { val platform = ScenePlatform() private val recomposer = FrameRecomposer(RenderThread + context) @@ -140,21 +143,47 @@ private class SkiaTarget(val size: IntSize) : AutoCloseable { private var renderTarget: BackendRenderTarget? = null private var surface: Surface? = null - fun attach(skia: DirectContext): Surface = - surface ?: run { + fun attach(skia: DirectContext): Surface = surface + ?: run { framebuffer = glGenFramebuffers() stencil = glGenRenderbuffers() glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, (texture as GlTexture).glId, 0) + 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) + glRenderbufferStorage( + GL_RENDERBUFFER, + GL_DEPTH24_STENCIL8, + size.width, + size.height + ) + glFramebufferRenderbuffer( + GL_FRAMEBUFFER, + GL_DEPTH_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, + stencil + ) val renderTarget = - BackendRenderTarget.makeGL(size.width, size.height, 0, 8, framebuffer, FramebufferFormat.GR_GL_RGBA8) - .also { renderTarget = it } + BackendRenderTarget.makeGL( + size.width, + size.height, + 0, + 8, + framebuffer, + FramebufferFormat.GR_GL_RGBA8 + ).also { renderTarget = it } Surface.makeFromBackendRenderTarget( - skia, renderTarget, SurfaceOrigin.BOTTOM_LEFT, SurfaceColorFormat.RGBA_8888, ColorSpace.sRGB + skia, + renderTarget, + SurfaceOrigin.BOTTOM_LEFT, + SurfaceColorFormat.RGBA_8888, + ColorSpace.sRGB )?.also { surface = it } ?: error("Skia rejected the GUI render target") } diff --git a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt index dac51cebb..858774b77 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt @@ -54,16 +54,25 @@ internal class SceneInput(private val scene: ComposeScene) { fun button(button: Int, pressed: Boolean, modifiers: Int) { val mask = 1 shl button - pressedButtons = if (pressed) pressedButtons or mask else pressedButtons and mask.inv() + pressedButtons = + if (pressed) pressedButtons or mask + else pressedButtons and mask.inv() if (pressed) { Press.begin() KeyboardFocus.visible = false } - pointer(if (pressed) PointerEventType.Press else PointerEventType.Release, button.toPointerButton(), modifiers) + pointer( + if (pressed) PointerEventType.Press else PointerEventType.Release, + button.toPointerButton(), + modifiers + ) } fun scroll(horizontal: Double, vertical: Double) { - pointer(PointerEventType.Scroll, scroll = Offset(horizontal.toFloat(), -vertical.toFloat()) * LINES_PER_NOTCH) + pointer( + PointerEventType.Scroll, + scroll = Offset(horizontal.toFloat(), -vertical.toFloat()) * LINES_PER_NOTCH + ) } fun key(key: Int, pressed: Boolean, modifiers: Int): Boolean { @@ -71,7 +80,9 @@ internal class SceneInput(private val scene: ComposeScene) { val shift = modifiers and GLFW.GLFW_MOD_SHIFT != 0 val direction = when (key.takeIf { pressed }) { - GLFW.GLFW_KEY_TAB -> if (shift) FocusDirection.Previous else FocusDirection.Next + GLFW.GLFW_KEY_TAB -> + if (shift) FocusDirection.Previous + else FocusDirection.Next GLFW.GLFW_KEY_UP -> FocusDirection.Up GLFW.GLFW_KEY_DOWN -> FocusDirection.Down GLFW.GLFW_KEY_LEFT -> FocusDirection.Left @@ -104,10 +115,20 @@ internal class SceneInput(private val scene: ComposeScene) { Character.toChars(codePoint).fold(false) { handled, char -> val typed = AwtKeyEvent( - awtSource, AwtKeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, AwtKeyEvent.VK_UNDEFINED, char + 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) + KeyEvent( + key = Key.Unknown, + type = KeyEventType.Unknown, + codePoint = char.code, + nativeEvent = typed + ) ) || handled } @@ -181,12 +202,16 @@ internal class SceneInput(private val scene: ComposeScene) { 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_SHIFT, GLFW.GLFW_KEY_RIGHT_SHIFT -> + AwtKeyEvent.VK_SHIFT + GLFW.GLFW_KEY_LEFT_CONTROL, GLFW.GLFW_KEY_RIGHT_CONTROL -> + AwtKeyEvent.VK_CONTROL GLFW.GLFW_KEY_LEFT_ALT, GLFW.GLFW_KEY_RIGHT_ALT -> AwtKeyEvent.VK_ALT GLFW.GLFW_KEY_LEFT_SUPER, GLFW.GLFW_KEY_RIGHT_SUPER -> AwtKeyEvent.VK_META - in GLFW.GLFW_KEY_A..GLFW.GLFW_KEY_Z, in GLFW.GLFW_KEY_0..GLFW.GLFW_KEY_9 -> this - in GLFW.GLFW_KEY_F1..GLFW.GLFW_KEY_F12 -> AwtKeyEvent.VK_F1 + (this - GLFW.GLFW_KEY_F1) + in GLFW.GLFW_KEY_A..GLFW.GLFW_KEY_Z, + in GLFW.GLFW_KEY_0..GLFW.GLFW_KEY_9 -> this + in GLFW.GLFW_KEY_F1..GLFW.GLFW_KEY_F12 -> + AwtKeyEvent.VK_F1 + (this - GLFW.GLFW_KEY_F1) else -> AwtKeyEvent.VK_UNDEFINED } } diff --git a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt index e4c18fdcc..579123235 100644 --- a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt +++ b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt @@ -26,25 +26,18 @@ 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 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 -@OptIn(InternalComposeUiApi::class, ExperimentalComposeUiApi::class) +@OptIn(InternalComposeUiApi::class) internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { private val window = object : WindowInfo { @@ -71,35 +64,19 @@ internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { else -> null } } - - 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 - } } object ResizeVerticalIcon : PointerIcon @OptIn(ExperimentalComposeUiApi::class) internal object GameClipboard : Clipboard { + @Suppress("OVERRIDE_DEPRECATION") override val nativeClipboard: Any get() = this override suspend fun getClipEntry(): ClipEntry? = - mc.keyboard.clipboard.takeIf { it.isNotEmpty() }?.let { ClipEntry(StringSelection(it)) } + mc.keyboard.clipboard.takeIf { it.isNotEmpty() }?.let { + ClipEntry(StringSelection(it)) + } override suspend fun setClipEntry(clipEntry: ClipEntry?) { val transferable = clipEntry?.nativeClipEntry as? Transferable diff --git a/src/main/kotlin/com/lambda/gui/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt index fde904155..9b8bc038e 100644 --- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -61,7 +61,8 @@ internal object Hud { 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 } + return if (mc.world == null || mc.options.hudHidden || covered) emptyList() + else modules.filter { it.isEnabled } } } @@ -86,14 +87,19 @@ private fun HudElement(hud: HudModule, editor: HudEditorState?) { Box( Modifier .layout { measurable, constraints -> - val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) + 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) + (dragged?.x ?: (roomX * anchor.x)) + .roundToInt() + .coerceIn(0, roomX), + (dragged?.y ?: (roomY * anchor.y)) + .roundToInt() + .coerceIn(0, roomY) ) } } @@ -111,5 +117,13 @@ fun HudText(text: String, modifier: Modifier = Modifier, color: Color? = null) { val hudColor by observe { HudConfig.textColor.toCompose() } val scale by observe { HudConfig.scale } val size = Type.body.fontSize * scale - Text(text, modifier, color ?: hudColor, Type.body.copy(fontSize = size, lineHeight = size * 1.25f).shadowed(HUD_TEXT_SHADOW)) + Text( + text, + modifier, + color ?: hudColor, + Type.body.copy( + fontSize = size, + lineHeight = size * 1.25f + ).shadowed(HUD_TEXT_SHADOW) + ) } diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt index 3a2d5afc9..df0335e07 100644 --- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -121,7 +121,11 @@ internal class HudEditorState(snapping: State) { 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) + if (config != null) panelPosition = position + ?: Offset( + screen.width / 2 - 120 * density.density, + screen.height * 0.15f + ) } var screen = Size.Zero @@ -130,7 +134,14 @@ internal class HudEditorState(snapping: State) { val drop: Snap.Result? by derivedStateOf { val hud = dragged ?: return@derivedStateOf null val element = Rect(draggedTo, bounds[hud]?.size ?: return@derivedStateOf null) - if (this.snapping) Snap.snap(element, bounds.filterKeys { it != hud }.values, Rect(Offset.Zero, screen), density) + if (this.snapping) { + Snap.snap( + element, + bounds.filterKeys { it != hud }.values, + Rect(Offset.Zero, screen), + density + ) + } else Snap.free(element, Rect(Offset.Zero, screen)) } @@ -166,13 +177,20 @@ internal fun HudEditor() { .snapLines { editor.drop } ) { HudLayer(editor) - rememberLast(editor.configuring)?.let { config -> key(config) { ElementSettings(config, editor.configuring === config, editor) } } + rememberLast(editor.configuring)?.let { config -> + key(config) { ElementSettings(config, editor.configuring === config, editor) } + } } rememberLast(editor.menu)?.let { (position, hud) -> key(editor.menusOpened) { - ContextMenu(editor.menu != null, position.round(), onDismiss = editor::closeMenu) { - if (hud != null) ElementMenu(hud, editor) else ScreenMenu(position, editor) + ContextMenu( + editor.menu != null, + position.round(), + onDismiss = editor::closeMenu + ) { + if (hud != null) ElementMenu(hud, editor) + else ScreenMenu(position, editor) } } } @@ -226,8 +244,16 @@ private fun ElementSettings(config: Config, open: Boolean, editor: HudEditorStat val density = LocalDensity.current val maxHeight = with(density) { editor.screen.height.toDp() } * 0.6f var size by remember { mutableStateOf(IntSize.Zero) } - val room = Offset((editor.screen.width - size.width).coerceAtLeast(0f), (editor.screen.height - size.height).coerceAtLeast(0f)) - val position = Offset(editor.panelPosition.x.coerceIn(0f, room.x), editor.panelPosition.y.coerceIn(0f, room.y)) + val room = + Offset( + (editor.screen.width - size.width).coerceAtLeast(0f), + (editor.screen.height - size.height).coerceAtLeast(0f) + ) + val position = + Offset( + editor.panelPosition.x.coerceIn(0f, room.x), + editor.panelPosition.y.coerceIn(0f, room.y) + ) val shownAt by rememberUpdatedState(position) if (open) editor.panelBounds = Rect(position, size.toSize()) DisposableEffect(Unit) { @@ -289,16 +315,23 @@ internal fun Modifier.hudEditable(hud: HudModule, editor: HudEditorState): Modif } finally { val dropped = editor.drop?.position ?: origin.topLeft val room = editor.screen - origin.size - hud.anchorX = if (room.width > 0f) (dropped.x / room.width).coerceIn(0f, 1f) else 0f - hud.anchorY = if (room.height > 0f) (dropped.y / room.height).coerceIn(0f, 1f) else 0f + hud.anchorX = + if (room.width > 0f) (dropped.x / room.width).coerceIn(0f, 1f) + else 0f + hud.anchorY = + if (room.height > 0f) (dropped.y / room.height).coerceIn(0f, 1f) + else 0f editor.dragged = null } } } .drawBehind { val width = Look.outlineWidth.toPx() + val alpha = + if (editor.dragged == hud || Reveal.module === hud) 0.9f + else 0.35f drawRect( - color = Color.White.copy(alpha = if (editor.dragged == hud || Reveal.module === hud) 0.9f else 0.35f), + color = Color.White.copy(alpha = alpha), topLeft = Offset(width / 2, width / 2), size = Size(size.width - width, size.height - width), style = Stroke(width) diff --git a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt index f468c4242..5cbb2960f 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -60,8 +60,13 @@ import net.minecraft.util.Util @Composable internal fun ConfigDialog(config: Config, onDismiss: () -> Unit) { - val maxHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } * 0.7f - Dialog(onDismiss) { ConfigSettings(config, maxHeight, onDismiss, Modifier.width(240.dp)) } + val maxHeight = + with(LocalDensity.current) { + LocalWindowInfo.current.containerSize.height.toDp() + } * 0.7f + Dialog(onDismiss) { + ConfigSettings(config, maxHeight, onDismiss, Modifier.width(240.dp)) + } } @Composable @@ -78,7 +83,13 @@ internal fun NewAutomationConfigDialog(onDismiss: () -> Unit) { 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) + TextInput( + name, + { name = it }, + Modifier.fillMaxWidth(), + placeholder = "Name", + focused = true + ) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { Spacer(Modifier.weight(1f)) Button("Cancel", onClick = onDismiss) @@ -114,7 +125,9 @@ internal fun AboutDialog(onDismiss: () -> Unit) { } val authors = remember { - FabricLoader.getInstance().getModContainer("lambda").orElseThrow().metadata.authors + FabricLoader.getInstance() + .getModContainer("lambda") + .orElseThrow().metadata.authors .flatMap { it.name.split(",") } .map { it.trim() } .filter { it.isNotEmpty() } @@ -130,10 +143,19 @@ internal fun AboutDialog(onDismiss: () -> Unit) { 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)) { + 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") } + Button("View License") { + Util.getOperatingSystem().open("$REPO_URL/blob/master/LICENSE.md") + } Spacer(Modifier.weight(1f)) Button("Close", onClick = onDismiss) } @@ -156,7 +178,10 @@ internal fun LoaderPromptDialog(prompt: AutoUpdater.Prompt) { 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) + Text( + "You can change this later from the AutoUpdater module.", + color = colors.onSurfaceVariant + ) } } Row( @@ -172,7 +197,9 @@ internal fun LoaderPromptDialog(prompt: AutoUpdater.Prompt) { modifier = Modifier.weight(1f) ) { AutoUpdater.answerPrompt(accepted = false) } Button( - label = if (prompt == AutoUpdater.Prompt.Uninstall) "Uninstall" else "Switch To Loader", + 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 index 9be33ff63..cdda54cff 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -19,7 +19,6 @@ package com.lambda.gui.menu import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.tween -import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement @@ -131,7 +130,13 @@ internal fun MenuBar(modifier: Modifier = Modifier) { .glass(colors.surface, RectangleShape) .consumeClicks() ) { - Row(Modifier.align(Alignment.CenterStart).fillMaxHeight().onSizeChanged { menus = it }, verticalAlignment = Alignment.CenterVertically) { + Row( + Modifier + .align(Alignment.CenterStart) + .fillMaxHeight() + .onSizeChanged { menus = it }, + verticalAlignment = Alignment.CenterVertically + ) { BarMenu("Lambda", icon = "textures/lambda.png") { LambdaMenu() } BarMenu("Modules") { ModulesMenu() } BarMenu("Automation") { AutomationMenu() } @@ -141,13 +146,22 @@ internal fun MenuBar(modifier: Modifier = Modifier) { SearchField( Modifier .onSizeChanged { search = it } - .offset { IntOffset((menus.width - (bar.width - search.width) / 2).coerceAtLeast(0), 0) } + .offset { + IntOffset( + (menus.width - (bar.width - search.width) / 2).coerceAtLeast(0), + 0 + ) + } ) } } @Composable -private fun BarMenu(label: String, icon: String? = null, content: @Composable ColumnScope.() -> Unit) { +private fun BarMenu( + label: String, + icon: String? = null, + content: @Composable ColumnScope.() -> Unit +) { val menu = remember { MenuState() } Box( contentAlignment = Alignment.Center, @@ -157,8 +171,18 @@ private fun BarMenu(label: String, icon: String? = null, content: @Composable Co .mouseClickable(onClick = menu::toggle) .padding(horizontal = 6.dp) ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { - if (icon != null) Image(rememberTexture(icon), contentDescription = null, Modifier.size(ICON_SIZE), filterQuality = FilterQuality.High) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + if (icon != null) { + Image( + rememberTexture(icon), + contentDescription = null, + Modifier.size(ICON_SIZE), + filterQuality = FilterQuality.High + ) + } Text(label, maxLines = 1) } Menu(menu.isOpen, onDismiss = menu::dismiss, content = content) @@ -202,7 +226,8 @@ private fun SearchField(modifier: Modifier = Modifier) { true } !open || results.isEmpty() -> false - event.key == Key.DirectionDown || event.key == Key.Tab && !event.isShiftPressed -> { + event.key == Key.DirectionDown || + event.key == Key.Tab && !event.isShiftPressed -> { marked = (marked + 1).mod(results.size) true } @@ -226,17 +251,31 @@ private fun SearchField(modifier: Modifier = Modifier) { Suggestions(open, onDismiss = { listed = false }) { if (shown.isEmpty()) MenuLabel("Nothing found") shown.forEachIndexed { index, result -> - ResultRow(result, marked = index == marked, onPoint = { marked = index }) { choose(result) } + ResultRow( + result, + marked = index == marked, + onPoint = { marked = index } + ) { + choose(result) + } } } } } -@OptIn(ExperimentalFoundationApi::class) @Composable -private fun ResultRow(result: Search.Result, marked: Boolean, onPoint: () -> Unit, onClick: () -> Unit) { +private fun ResultRow( + result: Search.Result, + marked: Boolean, + onPoint: () -> Unit, + onClick: () -> Unit +) { val colors = LambdaTheme.colors - val lit by animateColorAsState(if (marked) colors.controlSelected else Color.Transparent, tween(90)) + val lit by + animateColorAsState( + if (marked) colors.controlSelected else Color.Transparent, + tween(90) + ) val intoView = remember { BringIntoViewRequester() } LaunchedEffect(marked) { if (marked) intoView.bringIntoView() @@ -261,7 +300,12 @@ private fun ResultRow(result: Search.Result, marked: Boolean, onPoint: () -> Uni ) { Text(result.name, maxLines = 1) Spacer(Modifier.weight(1f).widthIn(min = 10.dp)) - Text(result.origin, color = colors.onSurfaceVariant, style = Type.label, maxLines = 1) + Text( + result.origin, + color = colors.onSurfaceVariant, + style = Type.label, + maxLines = 1 + ) } } @@ -270,7 +314,9 @@ private fun LambdaMenu() { Submenu("Save Config") { MenuItem("Save All Configs") { ConfigLoader.configCategories.forEach { it.trySaveToFile(true) } - GuiConfig.info("Saved ${ConfigLoader.configCategories.size} configuration files.") + GuiConfig.info( + "Saved ${ConfigLoader.configCategories.size} configuration files." + ) } ConfigLoader.configCategories.forEach { category -> MenuItem("Save ${category.name}") { @@ -282,7 +328,9 @@ private fun LambdaMenu() { Submenu("Load Config") { MenuItem("Load All Configs") { ConfigLoader.configCategories.forEach { it.tryLoadFromFile() } - GuiConfig.info("Loaded ${ConfigLoader.configCategories.size} configuration files.") + GuiConfig.info( + "Loaded ${ConfigLoader.configCategories.size} configuration files." + ) } ConfigLoader.configCategories.forEach { category -> MenuItem("Load ${category.name}") { @@ -293,10 +341,18 @@ private fun LambdaMenu() { } 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) } + 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() } } @@ -333,7 +389,9 @@ private fun ModulesMenu() { 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 } + MenuItem(module.name, checked = shown) { + module.showInClickGui.value = !shown + } } } } @@ -341,13 +399,22 @@ private fun ModulesMenu() { @Composable private fun AutomationMenu() { - val configs by observe { UserAutomationCategory.configs.filterIsInstance() } - MenuItem("New Config...") { ClickGuiState.dialog = ClickGuiDialog.NewAutomationConfig } + 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("${config.name}...") { + ClickGuiState.dialog = ClickGuiDialog.Settings(config) + } + } + MenuItem("${AutomationConfig.DEFAULT.name}...") { + ClickGuiState.dialog = ClickGuiDialog.Settings(AutomationConfig.DEFAULT) } - MenuItem("${AutomationConfig.DEFAULT.name}...") { ClickGuiState.dialog = ClickGuiDialog.Settings(AutomationConfig.DEFAULT) } } @Composable @@ -363,38 +430,66 @@ private fun MinecraftMenu() { MenuDivider() val gameMode by observeSafe { interaction.gameMode } - val mayChangeGameMode by observeSafe { GameModeCommand.PERMISSION_CHECK.allows(player.permissions) } + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + MenuItem( + "Packet Size & Ping Charts", + hint = "F3+3", + checked = observe { mc.debugHud.packetSizeAndPingChartsVisible }.value + ) { mc.debugHud.togglePacketSizeAndPingCharts() } MenuDivider() @@ -404,7 +499,12 @@ private fun MinecraftMenu() { 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 + world.registryKey.value, + player.x, + player.y, + player.z, + player.yaw, + player.pitch ) GuiConfig.info("Copied location command to clipboard.") } @@ -417,11 +517,15 @@ private fun MinecraftMenu() { mc.reloadResources() } MenuItem("Reload Chunks", hint = "F3+A") { mc.worldRenderer.reload() } - MenuItem("Start/Stop Profiler", hint = "F3+L") { mc.toggleDebugProfiler { GuiConfig.info(it) } } + 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)}") + GuiConfig.info( + "Dumped dynamic textures to: ${gameDirectory.relativize(output)}" + ) } } } @@ -439,4 +543,5 @@ private fun HelpMenu() { } @Composable -private fun FolderItem(label: String, folder: Path) = MenuItem("Open $label") { Util.getOperatingSystem().open(folder) } +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 index 0c840373d..5dd745eb8 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Search.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt @@ -42,11 +42,17 @@ internal object Search { 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 val origin = + if (module is HudModule) "HUD element" + else "${module.tag.name} module" override fun choose() = Reveal.show(module) } - class OfSetting(val setting: Setting<*>, val config: Config, path: List) : Result { + class OfSetting( + val setting: Setting<*>, + val config: Config, + path: List + ) : Result { override val name get() = setting.name override val origin = (listOf(config.name) + path).joinToString(" \u00bb ") override fun choose() = Reveal.show(config, setting) @@ -81,21 +87,46 @@ internal object Search { if (score > 0) add(result() to score + bonus) } - fun hidden(config: Any) = config is Module && config.tag == ModuleTag.DEBUG && !ClickGuiState.developerMode + 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) + 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()) + consider( + { Result.OfCommand(command) }, + COMMAND_BONUS, + command.name, + *command.aliases.toTypedArray() + ) } ConfigLoader.configCategories.forEach { category -> category.configs.forEach { config -> if (hidden(config)) return@forEach config.settingLayers.forEachEntry { path, single -> val setting = single.entry - if (setting.visibility()) consider({ Result.OfSetting(setting, config, path.map { it.name }) }, 0, setting.name) + if (setting.visibility()) { + consider( + { + Result.OfSetting( + setting, + config, + path.map { it.name } + ) + }, + 0, + setting.name + ) + } } } } @@ -108,7 +139,10 @@ internal object Search { if (target.contains(query)) return 50 + query.length * 40 / target.length val distance = query.levenshteinDistance(target) - val allowed = if (lenient) (query.length / 2).coerceIn(2, 6) else (query.length / 3).coerceIn(1, 4) - return if (distance <= allowed) (50 - distance * 10).coerceAtLeast(1) else 0 + 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 index b98efd0dc..0caddf426 100644 --- a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt +++ b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt @@ -38,33 +38,49 @@ internal class BlurPyramid(private val name: String) { private val spreadUniform: GpuBuffer = RenderSystem.getDevice().createBuffer( - { "$name spread" }, GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, SPREAD_UNIFORM_SIZE + { "$name spread" }, + GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, + SPREAD_UNIFORM_SIZE ) private var spread = Float.NaN - fun blur(source: GpuTextureView, width: Int, height: Int, radius: Float): GpuTextureView { + fun blur( + source: GpuTextureView, + width: Int, + height: Int, + radius: Float + ): GpuTextureView { resize(width, height) - val depth = (ceil(log2(radius.coerceAtLeast(1f))).toInt() - 1).coerceIn(1, levels.size) + 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) { + repeat(depth) { index -> pass(LambdaRenderPipelines.GUI_BLUR_DOWN, input, levels[index].view) input = levels[index].view } - for (index in depth - 2 downTo 0) { + (depth - 2 downTo 0).forEach { index -> pass(LambdaRenderPipelines.GUI_BLUR_UP, input, levels[index].view) input = levels[index].view } return input } - private fun pass(pipeline: RenderPipeline, input: GpuTextureView, output: GpuTextureView) { + 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.bindTexture( + "InSampler", + input, + RenderSystem.getSamplerCache().get(FilterMode.LINEAR) + ) pass.setUniform("BlurSpread", spreadUniform) pass.draw(0, 3) } @@ -74,15 +90,29 @@ internal class BlurPyramid(private val name: String) { 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) + 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)) } + 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 } diff --git a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt index 1a1ecf56f..eb6267329 100644 --- a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt +++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt @@ -47,14 +47,30 @@ internal object GuiCompositor { private var haloView: GpuTextureView? = null private var haloRadius = 0f - private val uniformSize = Std140SizeCalculator().putVec4().putVec4().putFloat().putFloat().putFloat().align(16).get() + 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() + { "Lambda GUI effects" }, + GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, + uniformSize.toLong() ) } - fun composite(gui: GpuTextureView, width: Int, height: Int, guiChanged: Boolean, effects: Effects) { + 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) @@ -71,13 +87,14 @@ internal object GuiCompositor { 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 - } + 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() @@ -102,12 +119,20 @@ internal object GuiCompositor { .putFloat(if (effects.frost > 0f) 1f else 0f) .putFloat((System.currentTimeMillis() % GLOW_CYCLE_MILLIS) / 1000f) .get() - RenderSystem.getDevice().createCommandEncoder().writeToBuffer(uniforms.slice(), data) + 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) + putVec4( + color.red / 255f, + color.green / 255f, + color.blue / 255f, + color.alpha / 255f + ) private const val GLOW_CYCLE_MILLIS = 3_141_592L } diff --git a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt index f4c7699ad..9d678abd4 100644 --- a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt +++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt @@ -127,7 +127,10 @@ object ItemAtlas { 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 } + 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 @@ -144,8 +147,8 @@ object ItemAtlas { val width = slots.size * CELL * scale val height = CELL * scale - val strip = - strip?.takeIf { it.width == width && it.height == height } ?: run { + val strip = strip?.takeIf { it.width == width && it.height == height } + ?: run { strip?.close() Strip(width, height).also { strip = it } } @@ -177,7 +180,12 @@ object ItemAtlas { private fun draw(framebuffer: Framebuffer) { RenderSystem.getDevice().createCommandEncoder() - .clearColorAndDepthTextures(framebuffer.colorAttachment, 0, framebuffer.depthAttachment, 1.0) + .clearColorAndDepthTextures( + framebuffer.colorAttachment, + 0, + framebuffer.depthAttachment, + 1.0 + ) val projection = RenderSystem.getProjectionMatrixBuffer() val projectionType = RenderSystem.getProjectionType() @@ -201,13 +209,23 @@ object ItemAtlas { private var surface: Surface? = null fun snapshot(skia: DirectContext): Image? { - val surface = - surface ?: run { + val surface = surface + ?: run { val renderTarget = - BackendRenderTarget.makeGL(width, height, 0, 0, glFramebuffer, FramebufferFormat.GR_GL_RGBA8) - .also { renderTarget = it } + 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 + skia, + renderTarget, + SurfaceOrigin.BOTTOM_LEFT, + SurfaceColorFormat.RGBA_8888, + ColorSpace.sRGB ).also { surface = it } } ?: return null surface.notifyContentWillChange(ContentChangeMode.DISCARD) diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt index f6eaf03de..b4382e18f 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -82,26 +82,53 @@ internal fun CollectionButton(setting: CollectionSetting) { } @Composable -private fun CollectionWindow(setting: CollectionSetting, onDismiss: () -> Unit) { +private fun CollectionWindow( + setting: CollectionSetting, + onDismiss: () -> Unit +) { val selected by observe { setting.value.toSet() } val entries = remember(setting.immutableCollection) { - setting.immutableCollection.map { Entry(it, setting.label(it), setting.icon(it)) } + 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 } } + val matching = + remember(entries, query) { + entries.filter { it.label.contains(query.trim(), ignoreCase = true) } + } + val (chosen, available) = + remember(matching, selected) { matching.partition { it.item in selected } } Dialog(onDismiss) { Column(Modifier.width(360.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { Text(setting.name) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { - TextInput(query, { query = it }, Modifier.weight(1f), placeholder = "Search ${setting.name}", focused = true) - Button("Invert", Modifier.height(Look.rowHeight)) { setting.invertSelection() } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + TextInput( + query, + { query = it }, + Modifier.weight(1f), + placeholder = "Search ${setting.name}", + focused = true + ) + Button("Invert", Modifier.height(Look.rowHeight)) { + setting.invertSelection() + } } - Row(Modifier.height(220.dp), horizontalArrangement = Arrangement.spacedBy(3.dp)) { - Pane("Available (${available.size})", available, Modifier.weight(1f)) { setting.select(it) } - Pane("Selected (${chosen.size})", chosen, Modifier.weight(1f)) { setting.deselect(it) } + 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) + } } } } @@ -114,20 +141,40 @@ internal fun BlockPicker(setting: BlockSetting) { Labeled(setting.name) { Chip(onClick = { picking = true }) { - Box(Modifier.size(ICON_SIZE)) { ItemIcon(ItemStack(block.asItem()), ICON_SIZE) } - Text(BlockSerializer.stringify(block), Modifier.weight(1f, fill = false), maxLines = 1) + Box(Modifier.size(ICON_SIZE)) { + ItemIcon(ItemStack(block.asItem()), ICON_SIZE) + } + Text( + BlockSerializer.stringify(block), + Modifier.weight(1f, fill = false), + maxLines = 1 + ) Ellipsis() } } if (!picking) return - val entries = remember { Registries.BLOCK.map { Entry(it, BlockSerializer.stringify(it), ItemStack(it.asItem())) } } + 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) } } + 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) + 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 @@ -139,13 +186,26 @@ internal fun BlockPicker(setting: BlockSetting) { 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) { +private fun Pane( + title: String, + entries: List>, + modifier: Modifier, + onClick: (R) -> Unit +) { val colors = LambdaTheme.colors Column(modifier.fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(title, color = colors.onSurfaceVariant, style = Type.label) val list = rememberLazyListState() - Box(Modifier.fillMaxSize().clip(RoundedCornerShape(Look.controlRounding)).background(colors.input)) { - LazyColumn(state = list, modifier = Modifier.fillMaxSize().wheelScrollable(list)) { + Box( + Modifier + .fillMaxSize() + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.input) + ) { + LazyColumn( + state = list, + modifier = Modifier.fillMaxSize().wheelScrollable(list) + ) { items(entries) { entry -> Row( verticalAlignment = Alignment.CenterVertically, @@ -157,12 +217,16 @@ private fun Pane(title: String, entries: List>, modifier: Modifier, .mouseClickable { onClick(entry.item) } .padding(horizontal = 4.dp) ) { - if (entry.icon != null) Box(Modifier.size(ICON_SIZE)) { ItemIcon(entry.icon, ICON_SIZE) } + if (entry.icon != null) Box(Modifier.size(ICON_SIZE)) { + ItemIcon(entry.icon, ICON_SIZE) + } Text(entry.label, color = colors.onControl, maxLines = 1) } } } - if (list.canScrollForward || list.canScrollBackward) Scrollbar(rememberScrollbarAdapter(list), Modifier.matchParentSize()) + if (list.canScrollForward || list.canScrollBackward) { + Scrollbar(rememberScrollbarAdapter(list), Modifier.matchParentSize()) + } } } } diff --git a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt index 56185c190..869c99f04 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt @@ -83,7 +83,9 @@ internal fun ColorPicker(setting: ColorSetting) { } ) Popout(picker.isOpen, onDismiss = picker::dismiss) { - Column(Modifier.width(PICKER_WIDTH)) { Picker(color) { setting.value = it } } + Column(Modifier.width(PICKER_WIDTH)) { + Picker(color) { setting.value = it } + } } } } @@ -93,16 +95,25 @@ internal fun ColorPicker(setting: ColorSetting) { private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { val colors = LambdaTheme.colors - var hsb by remember { mutableStateOf(AwtColor.RGBtoHSB(color.red, color.green, color.blue, null)) } + var 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) { + val shown = AwtColor.HSBtoRGB(hsb[0], hsb[1], hsb[2]) and 0xFFFFFF + if (shown != color.rgb and 0xFFFFFF) { hsb = AwtColor.RGBtoHSB(color.red, color.green, color.blue, null) } } - fun pick(hue: Float = hsb[0], saturation: Float = hsb[1], brightness: Float = hsb[2], alpha: Int = color.alpha) { + 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)) @@ -119,8 +130,18 @@ private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { 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())) + 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( @@ -134,24 +155,48 @@ private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { } Bar(color.alpha / 255f, onChange = { pick(alpha = (it * 255).roundToInt()) }) { drawCheckerboard() - drawRect(Brush.horizontalGradient(listOf(Color.Transparent, color.toCompose().copy(alpha = 1f)))) + 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)) } + 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)) { + 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) + TextInput( + color.toHex(), + { text -> parseHex(text)?.let(onColorChange) }, + Modifier.weight(1f), + style = Type.label + ) } } } @Composable -private fun Bar(fraction: Float, onChange: (Float) -> Unit, background: DrawScope.() -> Unit) { +private fun Bar( + fraction: Float, + onChange: (Float) -> Unit, + background: DrawScope.() -> Unit +) { Spacer( Modifier .fillMaxWidth() @@ -163,9 +208,17 @@ private fun Bar(fraction: Float, onChange: (Float) -> Unit, background: DrawScop 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())) + drawRoundRect( + Color.Black, + left, + thumb, + corner, + style = Stroke(0.5.dp.toPx()) + ) + } + .scrubbable { position, size -> + onChange((position.x / size.width).coerceIn(0f, 1f)) } - .scrubbable { position, size -> onChange((position.x / size.width).coerceIn(0f, 1f)) } ) } @@ -173,7 +226,12 @@ private fun Bar(fraction: Float, onChange: (Float) -> Unit, background: DrawScop private fun RowScope.Channel(label: String, value: Int, onChange: (Int) -> Unit) { Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) { Text(label, color = LambdaTheme.colors.onSurfaceVariant, style = Type.label) - NumberInput(value, { it.toIntOrNull()?.coerceIn(0, 255) }, onChange, Modifier.fillMaxWidth()) + NumberInput( + value, + { it.toIntOrNull()?.coerceIn(0, 255) }, + onChange, + Modifier.fillMaxWidth() + ) } } @@ -184,7 +242,11 @@ private fun DrawScope.drawCheckerboard() { 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)) + drawRect( + Color(0xFF999999), + Offset(column * cell, row * cell), + Size(cell, cell) + ) column += 2 } row++ @@ -197,7 +259,12 @@ private fun AwtColor.toHex() = private fun parseHex(text: String): AwtColor? { val digits = text.removePrefix("#") - if (digits.length != 6 && digits.length != 8 || digits.any { it.digitToIntOrNull(16) == null }) return null + if ( + digits.length != 6 && digits.length != 8 || + digits.any { it.digitToIntOrNull(16) == null } + ) { + return null + } val channels = digits.chunked(2).map { it.toIntOrNull(16) ?: return null } return AwtColor(channels[0], channels[1], channels[2], channels.getOrElse(3) { 255 }) } diff --git a/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt index 92ae4bab2..217a10d04 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt @@ -43,12 +43,23 @@ import com.lambda.gui.theme.Type import com.lambda.module.Module @Composable -internal fun ConfigSettings(config: Config, maxHeight: Dp, onDone: () -> Unit, modifier: Modifier = Modifier) { +internal fun ConfigSettings( + config: Config, + maxHeight: Dp, + onDone: () -> Unit, + modifier: Modifier = Modifier +) { Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text("${config.name} Settings", Modifier.fillMaxWidth().padding(horizontal = 4.dp), style = Type.title) + Text( + "${config.name} Settings", + Modifier.fillMaxWidth().padding(horizontal = 4.dp), + style = Type.title + ) if (config is Module) { var page by remember(config) { mutableStateOf(PanelPage.Settings) } - Column(Modifier.heightIn(max = maxHeight)) { ModuleSettings(config, page, { page = it }, rememberScrollState()) } + Column(Modifier.heightIn(max = maxHeight)) { + ModuleSettings(config, page, { page = it }, rememberScrollState()) + } } else { ScrollColumn(Modifier.heightIn(max = maxHeight)) { SoftTextShadow { @@ -57,7 +68,10 @@ internal fun ConfigSettings(config: Config, maxHeight: Dp, onDone: () -> Unit, m } } } - Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Row( + Modifier.fillMaxWidth().padding(horizontal = 4.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { if (config is UserAutomationConfig) { Button("Delete") { config.delete() diff --git a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt index acbc88116..99d7731ed 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt @@ -69,7 +69,12 @@ internal enum class PanelPage(val title: String) { } @Composable -internal fun ColumnScope.ModuleSettings(module: Module, selected: PanelPage, onSelect: (PanelPage) -> Unit, scroll: ScrollState?) { +internal fun ColumnScope.ModuleSettings( + module: Module, + selected: PanelPage, + onSelect: (PanelPage) -> Unit, + scroll: ScrollState? +) { val pages = pagesOf(module) val page = selected.takeIf { it in pages } ?: PanelPage.Settings val revealed = Reveal.setting.takeIf { Reveal.module === module } @@ -88,7 +93,7 @@ internal fun ColumnScope.ModuleSettings(module: Module, selected: PanelPage, onS AnimatedContent( targetState = page, modifier = Modifier.fillMaxWidth(), - transitionSpec = { pageTurn(towardsEnd = targetState > initialState) }, + transitionSpec = { pageTurn(towardsEnd = targetState > initialState) } ) { shown -> Column(Modifier.fillMaxWidth()) { when (shown) { @@ -99,20 +104,23 @@ internal fun ColumnScope.ModuleSettings(module: Module, selected: PanelPage, onS } } } - if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } else turned() + if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } + else turned() } } private fun pagesOf(module: Module): List = when { module == AutoUpdater -> listOf(PanelPage.Settings) - module.automationConfig === AutomationConfig.DEFAULT -> listOf(PanelPage.Settings, PanelPage.Module) + module.automationConfig === AutomationConfig.DEFAULT -> + listOf(PanelPage.Settings, PanelPage.Module) else -> PanelPage.entries } private fun pageOf(module: Module, setting: Setting<*>): PanelPage = when { - module.automationConfig !== AutomationConfig.DEFAULT && module.automationConfig.settingLayers.holds(setting) -> PanelPage.Automation + module.automationConfig !== AutomationConfig.DEFAULT && + module.automationConfig.settingLayers.holds(setting) -> PanelPage.Automation setting in moduleSettings(module) -> PanelPage.Module else -> PanelPage.Settings } @@ -126,7 +134,11 @@ private fun moduleSettings(module: Module): List> = ) @Composable -private fun PageStrip(pages: List, selected: PanelPage, onSelect: (PanelPage) -> Unit) { +private fun PageStrip( + pages: List, + selected: PanelPage, + onSelect: (PanelPage) -> Unit +) { val colors = LambdaTheme.colors Row(Modifier.fillMaxWidth().padding(bottom = 2.dp)) { pages.forEach { page -> @@ -141,11 +153,20 @@ private fun PageStrip(pages: List, selected: PanelPage, onSelect: (Pa .mouseClickable { onSelect(page) } .drawBehind { val thickness = 1.dp.toPx() - drawRect(line, Offset(0f, size.height - thickness), Size(size.width, thickness)) + 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) + Text( + page.title, + color = if (isSelected) colors.onSurface else colors.onSurfaceVariant, + maxLines = 1, + softWrap = false + ) } } } @@ -155,24 +176,36 @@ private fun PageStrip(pages: List, selected: PanelPage, onSelect: (Pa 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) + else { + Box( + Modifier.fillMaxWidth().padding(vertical = 4.dp), + contentAlignment = Alignment.Center + ) { + Text("No settings", color = LambdaTheme.colors.onSurfaceVariant) + } } } @Composable private fun AutomationPage(module: Module) { val linked by observe { module.backingAutomationConfig } - CompositionLocalProvider(LocalClickOnRelease provides true) { AutomationConfigSelector(module, linked) } + CompositionLocalProvider(LocalClickOnRelease provides true) { + AutomationConfigSelector(module, linked) + } key(linked) { SettingsList(module.automationConfig.settingLayers) } } @Composable private fun ModulePage(module: Module) { moduleSettings(module).forEach { SettingRow(it) } - Tooltip("Resets all settings for this module to their default values", Modifier.fillMaxWidth()) { + Tooltip( + "Resets all settings for this module to their default values", + Modifier.fillMaxWidth() + ) { CompositionLocalProvider(LocalClickOnRelease provides true) { - Button("Reset", Modifier.settingCell().height(Look.rowHeight)) { module.resetSettings() } + Button("Reset", Modifier.settingCell().height(Look.rowHeight)) { + module.resetSettings() + } } } } @@ -180,7 +213,8 @@ private fun ModulePage(module: Module) { @Composable private fun AutomationConfigSelector(module: Module, linked: AutomationConfig) { val options by observe { - listOf(module.defaultAutomationConfig) + UserAutomationCategory.configs.filterIsInstance() + listOf(module.defaultAutomationConfig) + + UserAutomationCategory.configs.filterIsInstance() } Dropdown( label = "Linked Config", diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index f32f34935..6ae14cd30 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -19,7 +19,6 @@ package com.lambda.gui.settings import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.tween -import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxWidth @@ -59,13 +58,17 @@ internal val TEXT_FIELD_WIDTH = 90.dp internal val NUMBER_FIELD_WIDTH = 34.dp internal val ROW_INSET = 3.dp -@OptIn(ExperimentalFoundationApi::class) @Composable fun SettingRow(setting: Setting<*>) { val disabled by observe { setting.disabled() } val revealed = Reveal.setting === setting - val lit by animateColorAsState(if (revealed) LambdaTheme.colors.onSurface.copy(alpha = 0.35f) else Color.Transparent, tween(250)) + val 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) { @@ -85,8 +88,11 @@ fun SettingRow(setting: Setting<*>) { } .enabled(!disabled) ) { - CompositionLocalProvider(LocalClickOnRelease provides true, LocalKeyboardReachable provides !disabled) { - key(setting) { setting.Editor() } + CompositionLocalProvider( + LocalClickOnRelease provides true, + LocalKeyboardReachable provides !disabled + ) { + key(setting) { setting.Gui() } } } } @@ -104,10 +110,15 @@ 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() } + while (true) awaitPointerEvent(PointerEventPass.Initial).changes.forEach { + it.consume() + } } } @Composable -internal fun Labeled(name: String, modifier: Modifier = Modifier, editor: @Composable RowScope.() -> Unit) = - LabeledRow(name, modifier.padding(start = ROW_INSET), editor) +internal fun Labeled( + name: String, + modifier: Modifier = Modifier, + editor: @Composable RowScope.() -> Unit +) = LabeledRow(name, modifier.padding(start = ROW_INSET), editor) diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt index aabbdc389..0a17882c9 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -87,7 +87,12 @@ fun SettingsList(layer: EntryLayer>) { val tabs = layer.layers.filterIsInstance>>() when { layer.multipleType == MultipleLayerType.Group -> - Section(layer.name, revealed = Reveal.setting?.let(layer::holds) == true) { Children(layer) } + Section( + layer.name, + revealed = Reveal.setting?.let(layer::holds) == true + ) { + Children(layer) + } else -> Column(Modifier.fillMaxWidth()) { layer.layers.filter { it !is EntryLayer.Tab }.forEach { SettingsList(it) } @@ -99,7 +104,8 @@ fun SettingsList(layer: EntryLayer>) { } @Composable -private fun Children(layer: EntryLayer.Multiple>) = layer.layers.forEach { SettingsList(it) } +private fun Children(layer: EntryLayer.Multiple>) = + layer.layers.forEach { SettingsList(it) } @Composable private fun Tabs(tabs: List>>) { @@ -109,7 +115,9 @@ private fun Tabs(tabs: List>>) { val selected = shown.firstOrNull { it.name == selectedName } ?: shown.first() val revealed = Reveal.setting LaunchedEffect(revealed) { - if (revealed != null) shown.firstOrNull { it.holds(revealed) }?.let { selectedName = it.name } + if (revealed != null) { + shown.firstOrNull { it.holds(revealed) }?.let { selectedName = it.name } + } } Column(Modifier.fillMaxWidth().padding(top = 1.dp)) { @@ -143,7 +151,11 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) .background(colors.header) .then( if (!choice) Modifier - else Modifier.hoverHighlight(colors.onHeader.copy(alpha = 0.12f)).mouseClickable(onClick = menu::toggle) + else { + Modifier + .hoverHighlight(colors.onHeader.copy(alpha = 0.12f)) + .mouseClickable(onClick = menu::toggle) + } ) .padding(horizontal = 6.dp) ) { @@ -151,7 +163,12 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) if (choice) Chevron(90f) } } - Menu(menu.isOpen, onDismiss = menu::dismiss, unfoldFrom = IntSize(band.width, 0), attached = true) { + Menu( + menu.isOpen, + onDismiss = menu::dismiss, + unfoldFrom = IntSize(band.width, 0), + attached = true + ) { names.forEach { name -> MenuItem(name, selected = name == selected) { if (name != selected) onSelect(name) diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index 23dd03b75..f4f5affd9 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -81,11 +81,15 @@ data class Palette( ) { val onPrimary = primary.contrast() val onSecondary = secondary.contrast() - val trackFilled = if (onControl.luminance() > 0.5f) primary else primary.copy(alpha = 0.6f) + val trackFilled = + if (onControl.luminance() > 0.5f) primary + else primary.copy(alpha = 0.6f) val raised = onSurface.copy(alpha = 0.11f) val hover = onSurface.copy(alpha = 0.06f) - private fun Color.contrast() = if (luminance() > 0.2f) ON_LIGHT_ACCENT else Color.White + private fun Color.contrast() = + if (luminance() > 0.2f) ON_LIGHT_ACCENT + else Color.White } internal object Look { @@ -116,16 +120,23 @@ internal object Look { fun refresh() = observations.refresh() - private fun style(read: () -> T): State = Observation(read).also { observations.active += it }.state + private fun style(read: () -> T): State = + Observation(read).also { observations.active += it }.state } internal object Motion : MotionDurationScale { private const val PAGE_MILLIS = 160 - private val UNFOLDING = spring(stiffness = Spring.StiffnessMedium, visibilityThreshold = IntSize.VisibilityThreshold) + private val UNFOLDING = + spring( + stiffness = Spring.StiffnessMedium, + visibilityThreshold = IntSize.VisibilityThreshold + ) val SCROLL = object : MotionDurationScale { - override val scaleFactor get() = if (Style.smoothScrolling) 1f else 0f + override val scaleFactor get() = + if (Style.smoothScrolling) 1f + else 0f } val UNSCALED = @@ -133,14 +144,24 @@ internal object Motion : MotionDurationScale { override val scaleFactor get() = 1f } - override val scaleFactor get() = if (Style.animations) 1f / Style.animationSpeed else 0f + override val scaleFactor get() = + if (Style.animations) 1f / Style.animationSpeed + else 0f - val windows: FiniteAnimationSpec get() = if (Style.windowAnimations) spring() else snap() - val panels: FiniteAnimationSpec get() = if (Style.panelAnimations) UNFOLDING else snap() - val pageMillis get() = if (Style.pageAnimations) PAGE_MILLIS else 0 + val windows: FiniteAnimationSpec + get() = if (Style.windowAnimations) spring() else snap() + val panels: FiniteAnimationSpec + get() = if (Style.panelAnimations) UNFOLDING else snap() + val pageMillis + get() = if (Style.pageAnimations) PAGE_MILLIS else 0 } -enum class GuiFont(override val displayName: String, val size: TextUnit, val smallSize: TextUnit, val titleWeight: FontWeight) : NamedEnum { +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); @@ -149,8 +170,13 @@ enum class GuiFont(override val displayName: String, val size: TextUnit, val sma 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)) + 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 } } @@ -162,13 +188,20 @@ private class Typography(font: GuiFont, scale: Float = 1f) { val body = compact(font, font.size * scale) val label = compact(font, font.smallSize * scale) - private fun compact(font: GuiFont, size: TextUnit, weight: FontWeight = FontWeight.Normal) = + private fun compact( + font: GuiFont, + size: TextUnit, + weight: FontWeight = FontWeight.Normal + ) = TextStyle( fontFamily = font.family, fontWeight = weight, fontSize = size, lineHeight = if (font == GuiFont.Minecraft) size else size * 1.25f, - lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.Both), + lineHeightStyle = LineHeightStyle( + LineHeightStyle.Alignment.Center, + LineHeightStyle.Trim.Both + ), ) } @@ -183,8 +216,10 @@ object LambdaTheme { @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") } +private val LocalPalette = + staticCompositionLocalOf { error("No LambdaTheme in this composition") } +private val LocalTypography = + staticCompositionLocalOf { error("No LambdaTheme in this composition") } val LocalContentColor = compositionLocalOf { Color.White } @@ -197,13 +232,22 @@ fun LambdaTheme(content: @Composable () -> Unit) { val typography = remember(font, fontSize) { if (font == GuiFont.Minecraft) return@remember Typography(font, fontSize) - val line = measurer.measure("Ag", Typography(font).body, density = Density(1f)).size.height + val line = + measurer.measure( + "Ag", + Typography(font).body, + density = Density(1f) + ).size.height Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f) * fontSize) } CompositionLocalProvider( LocalPalette provides palette, LocalTypography provides typography, - LocalTextSelectionColors provides TextSelectionColors(palette.primary, palette.primary.copy(alpha = 0.4f)), + LocalTextSelectionColors provides + TextSelectionColors( + palette.primary, + palette.primary.copy(alpha = 0.4f) + ), LocalContentColor provides palette.onSurface, content = content ) diff --git a/src/main/kotlin/com/lambda/module/HudModule.kt b/src/main/kotlin/com/lambda/module/HudModule.kt index 60f2e9945..330d1f82a 100644 --- a/src/main/kotlin/com/lambda/module/HudModule.kt +++ b/src/main/kotlin/com/lambda/module/HudModule.kt @@ -28,7 +28,14 @@ abstract class HudModule( alwaysListening: Boolean = false, enabledByDefault: Boolean = false, defaultKeybind: Bind = Bind.EMPTY, -) : Module(name, description, tag, alwaysListening, enabledByDefault, defaultKeybind = defaultKeybind) { +) : Module( + name, + description, + tag, + alwaysListening, + enabledByDefault, + defaultKeybind = defaultKeybind +) { val backgroundColor = setting("Background Color", Color(0, 0, 0, 0)) var anchorX by setting("HUD X", DEFAULT_ANCHOR, 0f..1f, 0.001f) { false } 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 289ca01a1..75531583e 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -50,7 +50,7 @@ object Style : Module( Light("Light"), } - private val themeMode by setting("Theme", ThemeMode.Auto, "Auto follows the theme of your operating system") + private val themeMode by setting("Theme", ThemeMode.Dark, "Auto follows the theme of your operating system") val font by setting("Font", GuiFont.Minecraft, "The Minecraft font is sharpest where the interface is a whole number of times its natural size: at 1080p and 2160p with a scale of 1") val fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") val scale by setting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() @@ -151,7 +151,9 @@ object Style : Module( when (themeMode) { ThemeMode.Dark -> darkTheme ThemeMode.Light -> lightTheme - ThemeMode.Auto -> if (SystemAppearance.isDark) darkTheme else lightTheme + ThemeMode.Auto -> + if (SystemAppearance.isDark) darkTheme + else lightTheme } val palette: Palette get() = theme.toPalette() 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 99269f7e3..66129f462 100644 --- a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt +++ b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt @@ -655,7 +655,9 @@ object AutoDisconnect : Module( buildText { text(effect.effectType.value().name) if (effect.amplifier > 0) literal(" ${effect.amplifier + 1}") - color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (${effectDuration(effect)})") } + color(Style.palette.onSurfaceVariant.toAwt()) { + literal(" (${effectDuration(effect)})") + } } ) } @@ -752,7 +754,9 @@ object AutoDisconnect : Module( } if (stack.isDamageable) { - color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") } + color(Style.palette.onSurfaceVariant.toAwt()) { + literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") + } } if (stack.maxCount > 1) { diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt index 287269c1b..d65f8cd53 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt @@ -46,7 +46,13 @@ object Armor : HudModule( 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) + private val slots = + listOf( + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + ) @Composable override fun Content() { @@ -61,8 +67,14 @@ object Armor : HudModule( } 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) } } + 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/Coordinates.kt b/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt index 9118257ab..b06deaf31 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Coordinates.kt @@ -63,8 +63,24 @@ object Coordinates : HudModule( private fun SafeContext.coordinates(): String { val position = player.pos.format(formatter) val otherDimensionPos = - if (world.isNether) player.overworldCoord.let { Vec2d(it.x, it.z) }.format(formatter.locale, formatter.separator, "[", "]", formatter.precision) - else player.netherCoord.let { Vec2d(it.x, it.z) }.format(formatter.locale, formatter.separator, "[", "]", formatter.precision) + 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 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 8b55e11d4..c4c7683da 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt @@ -54,7 +54,14 @@ object ModuleList : HudModule( entries.forEach { (name, bind) -> Row { HudText(name) - if (showKeybind) HudText(" [${(bind ?: Bind.EMPTY).name}]", color = if (bind != null) Color.Green else Color.Red) + 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/Tps.kt b/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt index 1544ebd0b..c36621201 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt @@ -70,7 +70,10 @@ object Tps : HudModule( 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) { + Box( + Modifier.size(size).drawBehind { drawGraph(data, stride, lineColor) }, + Alignment.TopCenter + ) { HudText("cur ${data.last().format()}${format.unit} | avg ${average.format()}${format.unit}") } } 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 6f7600180..748d17b05 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt @@ -40,6 +40,10 @@ object Watermark : HudModule( override fun Content() { val logo = rememberTexture("textures/lambda.png") val scale by observe { scale } - Image(logo, "Lambda", Modifier.size((logo.width * scale).dp, (logo.height * scale).dp)) + Image( + logo, + "Lambda", + Modifier.size((logo.width * scale).dp, (logo.height * scale).dp) + ) } } From be84af798026504d8e17430df74af3d58d215637 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:56:33 +0000 Subject: [PATCH 18/34] close animation and more options for animations as a whole, with the ability to stack them --- .../render/InactivityFpsLimiterMixin.java | 4 +- src/main/kotlin/com/lambda/gui/GuiScreen.kt | 6 - src/main/kotlin/com/lambda/gui/LambdaGui.kt | 131 +++++++++++++++--- .../com/lambda/gui/clickgui/CategoryWindow.kt | 17 ++- .../com/lambda/gui/clickgui/ClickGui.kt | 16 +++ .../com/lambda/gui/clickgui/SettingsPanel.kt | 13 +- .../kotlin/com/lambda/gui/component/Popups.kt | 13 +- .../com/lambda/gui/render/GuiCompositor.kt | 5 +- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 19 +++ .../com/lambda/module/modules/client/Style.kt | 7 + .../lambda/shaders/core/gui_composite.fsh | 9 +- 11 files changed, 191 insertions(+), 49 deletions(-) diff --git a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java index 40ba23482..54ea7aab9 100644 --- a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java +++ b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java @@ -18,6 +18,7 @@ package com.lambda.mixin.render; import com.lambda.gui.GuiScreen; +import com.lambda.gui.LambdaGui; import com.llamalad7.mixinextras.injector.ModifyReturnValue; import net.minecraft.client.MinecraftClient; import net.minecraft.client.option.InactivityFpsLimiter; @@ -34,7 +35,8 @@ public class InactivityFpsLimiterMixin { @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) { + boolean shown = client.currentScreen == GuiScreen.INSTANCE || LambdaGui.INSTANCE.getLeaving(); + if (reason == InactivityFpsLimiter.LimitReason.OUT_OF_LEVEL_MENU && shown) { return InactivityFpsLimiter.LimitReason.NONE; } return reason; diff --git a/src/main/kotlin/com/lambda/gui/GuiScreen.kt b/src/main/kotlin/com/lambda/gui/GuiScreen.kt index 412590ce8..f0ee54200 100644 --- a/src/main/kotlin/com/lambda/gui/GuiScreen.kt +++ b/src/main/kotlin/com/lambda/gui/GuiScreen.kt @@ -22,7 +22,6 @@ import com.lambda.Lambda.mc import com.lambda.config.settings.complex.KeybindSetting import com.lambda.gui.clickgui.ClickGuiState import com.lambda.gui.component.TextFocus -import com.lambda.module.modules.client.Style import com.lambda.module.modules.combat.autodisconnect.AutoDisconnectScreen import com.lambda.util.render.CursorOverrideProvider import net.minecraft.client.gui.Click @@ -87,10 +86,6 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { parent.render(context, -1, -1, delta) context.drawDeferredElements() } - 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) { @@ -157,5 +152,4 @@ object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { return Offset((x * scale).toFloat(), (y * scale).toFloat()) } - 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 index ed9020614..2c3605a25 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -17,9 +17,13 @@ package com.lambda.gui +import androidx.compose.animation.core.animate import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalClipboard @@ -45,6 +49,8 @@ import com.lambda.gui.hud.HudLayer import com.lambda.gui.render.GuiCompositor import com.lambda.gui.render.ItemAtlas import com.lambda.gui.settings.SettingsList +import com.lambda.gui.theme.GuiInterrupt +import com.lambda.gui.theme.GuiTransition import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look import com.lambda.gui.theme.Motion @@ -54,10 +60,12 @@ import com.lambda.module.modules.client.Style import com.lambda.sound.LambdaSound import com.lambda.sound.SoundHandler.play import com.lambda.util.CommunicationUtils.warn +import kotlinx.coroutines.Job import net.minecraft.client.gui.cursor.Cursor import org.jetbrains.skia.FontMgr import org.jetbrains.skia.impl.Library import kotlin.concurrent.thread +import kotlin.math.abs object LambdaGui : Loadable { private const val REFERENCE_HEIGHT = 540f @@ -81,6 +89,30 @@ object LambdaGui : Loadable { private var warmingUp by mutableStateOf(false) private var warmedUp = false + private var shownPresence by mutableFloatStateOf(0f) + private var animation: Job? = null + var leaving by mutableStateOf(false) + private set + internal var restarts by mutableIntStateOf(0) + private set + internal val presence + get() = + if (warmingUp) 1f + else shownPresence + internal val transitions: Collection + get() = + if (leaving) Style.closeStyle + else Style.openStyle + internal val unfoldsOpen + get() = + Style.animations && + Style.openAnimation && + GuiTransition.Unfold in Style.openStyle + private val showsClickGui + get() = screen == Screen.ClickGui || leaving + internal val foldsClosed + get() = leaving && GuiTransition.Unfold in Style.closeStyle + private val observations = Observations() private val clickGuiObservations = Observations() @@ -91,7 +123,7 @@ object LambdaGui : Loadable { val isCapturingKeys get() = TextFocus.isTyping || KeybindSetting.isRecording init { - listenUnsafe { close() } + listenUnsafe { shutDown() } } override fun load(): String { @@ -108,7 +140,28 @@ object LambdaGui : Loadable { fun toggle() { if (isCapturingKeys) return if (screen == null) open(Screen.ClickGui) - else GuiScreen.close() + else close() + } + + fun close() { + val animated = + Style.animations && Style.closeAnimation && Style.closeStyle.isNotEmpty() + if (screen == Screen.ClickGui && animated) { + if (shownPresence < 1f) skipTo(1f) + leaving = true + } + GuiScreen.close() + } + + private fun skipTo(end: Float) { + if (Style.interruptedAnimation != GuiInterrupt.Finish) return + jumpTo(end) + restarts++ + } + + private fun jumpTo(value: Float) { + animation?.cancel() + shownPresence = value } fun open(screen: Screen) { @@ -118,21 +171,26 @@ object LambdaGui : Loadable { } if (this.screen == null) { if (!GuiScreen.canOpenOver(mc.currentScreen)) return + if (leaving) skipTo(0f) + else jumpTo(0f) if (Client.clientSounds) LambdaSound.ModuleOn.play() GuiScreen.show() AutoUpdater.onGuiOpened() } + leaving = false this.screen = screen } fun back() { - if (screen == Screen.HudEditor) screen = Screen.ClickGui else GuiScreen.close() + if (screen == Screen.HudEditor) screen = Screen.ClickGui + else close() } internal fun onScreenRemoved() { if (screen == null) return if (Client.clientSounds) LambdaSound.ModuleOff.play() screen = null + if (!leaving) jumpTo(0f) settled = false input?.release() host?.platform?.cursor = null @@ -148,7 +206,7 @@ object LambdaGui : Loadable { warmedUp = true warmUp(size, density) } - if (screen == null && Hud.shown.isEmpty() && settled) return + if (screen == null && !leaving && Hud.shown.isEmpty() && settled) return try { val host = host ?: createHost() @@ -189,7 +247,9 @@ object LambdaGui : Loadable { val failed = host host = null ItemAtlas.release() - runCatching { failed?.closeAndFree() }.onFailure { LOG.warn("Could not free the failed interface", it) } + runCatching { failed?.closeAndFree() }.onFailure { + LOG.warn("Could not free the failed interface", it) + } observations.active.clear() clickGuiObservations.active.clear() if (screen != null) GuiScreen.close() @@ -233,6 +293,7 @@ object LambdaGui : Loadable { LambdaTheme { KeyboardFocus.Layer() Reveal.Expiry() + Presence() when (screen) { Screen.HudEditor -> HudEditor() @@ -240,7 +301,7 @@ object LambdaGui : Loadable { null -> HudLayer() } Retained( - shown = screen == Screen.ClickGui || warmingUp, + shown = showsClickGui || warmingUp, clickGuiObservations ) { ClickGui() @@ -250,27 +311,55 @@ object LambdaGui : Loadable { } } + @Composable + private fun Presence() { + val present = screen == Screen.ClickGui + LaunchedEffect(present) { + animation = coroutineContext[Job] + val target = + if (present) 1f + else 0f + val animated = + if (present) Style.openAnimation && Style.openStyle.isNotEmpty() + else leaving + if (animated) { + val spec = Motion.gui(abs(target - shownPresence)) + animate(shownPresence, target, animationSpec = spec) { value, _ -> + shownPresence = value + } + } + else shownPresence = target + if (!present) leaving = false + } + } + @Composable private fun WarmUp() { SettingsList(Style.settingLayers) } - private fun effects(density: Float) = - 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 effects(density: Float): GuiCompositor.Effects { + if (screen == null && !leaving) return GuiCompositor.Effects.NONE + val strength = + if (showsClickGui) presence + else 1f + return GuiCompositor.Effects( + frost = + if (Style.blur) Style.blurRadius * density * strength + else 0f, + glow = + if (Style.glow && showsClickGui) Style.glowRadius * density + else 0f, + glowIntensity = Style.glowIntensity * strength, + glowColorA = Style.glowColorA, + glowColorB = Style.glowColorB, + dim = + if (Style.dimBackground && showsClickGui) Style.dimStrength * presence + else 0f, + ) + } - private fun close() { + private fun shutDown() { host?.close() host = null } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index 4c3a0a1df..8c6e068de 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -62,6 +62,7 @@ import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.toSize import com.lambda.gui.GuiConfig +import com.lambda.gui.LambdaGui import com.lambda.gui.Reveal import com.lambda.gui.Snap import com.lambda.gui.component.ScrollColumn @@ -211,15 +212,25 @@ internal fun CategoryWindow( ) val shown = LocalShown.current - val unfolded = remember(shown) { MutableTransitionState(false) } - unfolded.targetState = shown && !collapsed + val folding = LambdaGui.foldsClosed + val unfolded = + remember(shown, LambdaGui.restarts) { + MutableTransitionState( + (folding || !LambdaGui.unfoldsOpen) && shown && !collapsed + ) + } + unfolded.targetState = shown && !folding && !collapsed val settled = unfolded.isIdle && unfolded.currentState val hanging = modules.mapNotNull(settings::panelOf) SideEffect { hanging.forEach { it.settled = settled } } AnimatedVisibility( visibleState = unfolded, enter = expandVertically(Motion.windows), - exit = shrinkVertically(Motion.windows), + exit = + shrinkVertically( + if (folding) Motion.guiFold + else Motion.windows + ), ) { ScrollColumn( Modifier.heightIn( diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index ef5cb2f98..3a60767b1 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -33,6 +33,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput @@ -57,12 +58,16 @@ import com.lambda.gui.menu.ConfigDialog import com.lambda.gui.menu.LoaderPromptDialog import com.lambda.gui.menu.MenuBar import com.lambda.gui.menu.NewAutomationConfigDialog +import com.lambda.gui.theme.GuiTransition import com.lambda.gui.theme.Look import com.lambda.module.HudModule import com.lambda.module.ModuleTag import com.lambda.module.modules.client.AutoUpdater import com.lambda.module.modules.client.Style +private val SLIDE = 24.dp +private const val ZOOM = 0.92f + internal val CLICK_GUI_CATEGORIES = ModuleTag.defaults - ModuleTag.HUD private class RowLayout(var row: Triple, var shown: Boolean = false) @@ -134,6 +139,17 @@ internal fun ClickGui() { onClick = settings::closeAll ).snapLines { drop + }.graphicsLayer { + val presence = LambdaGui.presence + val styles = LambdaGui.transitions + if (GuiTransition.Fade in styles) alpha = presence + if (GuiTransition.Slide in styles) { + translationY = (presence - 1f) * SLIDE.toPx() + } + if (GuiTransition.Zoom in styles) { + scaleX = ZOOM + (1f - ZOOM) * presence + scaleY = scaleX + } } ) { val inRow = tags.count { it != ModuleTag.DEBUG } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index 333fe1c7a..f98cd5698 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -174,18 +174,17 @@ internal fun SettingsPanel( modifier = Modifier .onSizeChanged { unfolded = it.height } .onGloballyPositioned { popups.place(it.boundsInWindow()) } - .dropShadow(RoundedCornerShape(Look.panelRounding)), + .dropShadow(RoundedCornerShape(Look.panelRounding)) + .window(LambdaTheme.colors.panel, LambdaTheme.colors.border, shape), enter = expandIn(Motion.panels, seam), exit = shrinkOut(Motion.panels, seam), ) { - val colors = LambdaTheme.colors Box( Modifier .widthIn(MIN_WIDTH, Look.settingsWidth) .heightIn(max = maxHeight) .widthOfContent() .onSizeChanged { size = it } - .window(colors.panel, colors.border, shape) ) { CompositionLocalProvider(LocalPopupHost provides popups) { Column(Modifier.padding(Look.panelPadding)) { @@ -200,14 +199,10 @@ internal fun SettingsPanel( if (scroll.maxValue > 0 || lift > 0f) { Grip( onDragStart = { - panel.extension = - panel.extension.coerceAtMost( - with(density) { lift.toDp() } - ) + panel.extension = panel.extension.coerceAtMost(with(density) { lift.toDp() }) }, onDrag = { up -> - val needed = - panel.extension + with(density) { scroll.maxValue.toDp() } + val needed = panel.extension + with(density) { scroll.maxValue.toDp() } panel.extension = (panel.extension + up).coerceIn( 0.dp, diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 21f612d24..911f4956d 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -354,12 +354,13 @@ private fun FloatingPanel( modifier = Modifier .swallowedBy(host) .onGloballyPositioned { own.place(it.boundsInWindow()) } - .dropShadow(shape, close = true), + .dropShadow(shape, close = true) + .window(colors.panel, colors.border, shape), enter = expandIn(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, exit = shrinkOut(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, ) { CompositionLocalProvider(LocalPopupHost provides own) { - content(Modifier.onSizeChanged { position.unfolded = it }.window(colors.panel, colors.border, shape)) + content(Modifier.onSizeChanged { position.unfolded = it }) } } } @@ -444,7 +445,9 @@ fun Suggestions( ContentColor(colors.onSurface) { AnimatedVisibility( visibleState = visibility, - modifier = Modifier.dropShadow(shape), + modifier = Modifier + .dropShadow(shape) + .window(colors.panel, colors.border, shape), enter = expandVertically(Motion.panels, Alignment.Top), exit = shrinkVertically(Motion.panels, Alignment.Top), ) { @@ -452,9 +455,7 @@ fun Suggestions( modifier = Modifier .heightIn(max = screenHeight * 0.6f) .width(IntrinsicSize.Max) - .window(colors.panel, colors.border, shape) - .animateContentSize(Motion.panels) - .clip(shape), + .animateContentSize(Motion.panels), content = content ) } diff --git a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt index eb6267329..aef3e80d3 100644 --- a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt +++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt @@ -36,6 +36,7 @@ internal object GuiCompositor { val glowIntensity: Float = 0f, val glowColorA: Color = Color.WHITE, val glowColorB: Color = Color.WHITE, + val dim: Float = 0f, ) { companion object { val NONE = Effects() @@ -54,6 +55,7 @@ internal object GuiCompositor { .putFloat() .putFloat() .putFloat() + .putFloat() .align(16) .get() private val uniforms: GpuBuffer by lazy { @@ -75,7 +77,7 @@ internal object GuiCompositor { val linear = RenderSystem.getSamplerCache().get(FilterMode.LINEAR) val nearest = RenderSystem.getSamplerCache().get(FilterMode.NEAREST) - if (effects.frost <= 0f && effects.glow <= 0f) { + if (effects.frost <= 0f && effects.glow <= 0f && effects.dim <= 0f) { haloView = null RenderSystem.getDevice().createCommandEncoder() .createRenderPass({ "Lambda GUI" }, screen, OptionalInt.empty()) @@ -118,6 +120,7 @@ internal object GuiCompositor { .putFloat(if (effects.glow > 0f) effects.glowIntensity else 0f) .putFloat(if (effects.frost > 0f) 1f else 0f) .putFloat((System.currentTimeMillis() % GLOW_CYCLE_MILLIS) / 1000f) + .putFloat(effects.dim) .get() RenderSystem.getDevice().createCommandEncoder().writeToBuffer( uniforms.slice(), diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index f4f5affd9..d66a55876 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -22,6 +22,7 @@ import androidx.compose.animation.core.Spring import androidx.compose.animation.core.VisibilityThreshold import androidx.compose.animation.core.snap import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween import androidx.compose.foundation.text.selection.LocalTextSelectionColors import androidx.compose.foundation.text.selection.TextSelectionColors import androidx.compose.runtime.Composable @@ -53,6 +54,7 @@ import com.lambda.gui.core.observe import com.lambda.module.modules.client.Style import com.lambda.util.NamedEnum import com.lambda.util.stream +import kotlin.math.roundToInt private const val LINE_HEIGHT = 10.95f @@ -126,6 +128,7 @@ internal object Look { internal object Motion : MotionDurationScale { private const val PAGE_MILLIS = 160 + private const val GUI_MILLIS = 180 private val UNFOLDING = spring( stiffness = Spring.StiffnessMedium, @@ -154,6 +157,22 @@ internal object Motion : MotionDurationScale { get() = if (Style.panelAnimations) UNFOLDING else snap() val pageMillis get() = if (Style.pageAnimations) PAGE_MILLIS else 0 + fun gui(distance: Float): FiniteAnimationSpec = + tween((GUI_MILLIS * distance).roundToInt()) + val guiFold: FiniteAnimationSpec + get() = tween(GUI_MILLIS) +} + +enum class GuiTransition(override val displayName: String) : NamedEnum { + Unfold("Unfold"), + Fade("Fade"), + Slide("Slide"), + Zoom("Zoom"), +} + +enum class GuiInterrupt(override val displayName: String) : NamedEnum { + Reverse("Reverse"), + Finish("Skip To End"), } enum class GuiFont( 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 75531583e..8f81273d8 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -22,6 +22,8 @@ import com.lambda.config.ConfigBlock import com.lambda.config.Group import com.lambda.config.settings.appliedOnRelease import com.lambda.gui.theme.GuiFont +import com.lambda.gui.theme.GuiInterrupt +import com.lambda.gui.theme.GuiTransition import com.lambda.gui.theme.Palette import com.lambda.module.Module import com.lambda.module.ModuleTag @@ -87,6 +89,11 @@ object Style : Module( @Group(MOTION_GROUP) val animations by setting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") @Group(MOTION_GROUP) val animationSpeed by setting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } + @Group(MOTION_GROUP) val openAnimation by setting("Open Animation", true, "Animates the click GUI in when it opens") { animations } + @Group(MOTION_GROUP) val openStyle by setting("Open Style", setOf(GuiTransition.Unfold), GuiTransition.entries.toSet(), "What the click GUI does as it comes in, any of them together: its windows unfold out of their headers, and all of it fades, slides down or zooms in") { animations && openAnimation } + @Group(MOTION_GROUP) val closeAnimation by setting("Close Animation", true, "Animates the click GUI out when it closes. The game has the mouse and keyboard back at once: the animation only plays over it") { animations } + @Group(MOTION_GROUP) val closeStyle by setting("Close Style", setOf(GuiTransition.Unfold, GuiTransition.Fade), GuiTransition.entries.toSet(), "What the click GUI does as it goes out, any of them together: its windows fold into their headers, and all of it fades, slides up or zooms out") { animations && closeAnimation } + @Group(MOTION_GROUP) val interruptedAnimation by setting("Interrupted Animation", GuiInterrupt.Reverse, "What happens when the click GUI is opened or closed again before its animation is done: it turns around from where it is, or skips to the end and plays the other one in full") { animations && (openAnimation || closeAnimation) } @Group(MOTION_GROUP) val windowAnimations by setting("Window Animations", true, "Category windows unfold out of their headers") { animations } @Group(MOTION_GROUP) val panelAnimations by setting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } @Group(MOTION_GROUP) val pageAnimations by setting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } diff --git a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh index e01bb5291..b7d4f8130 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh @@ -10,8 +10,11 @@ layout(std140) uniform GuiEffects { float GlowIntensity; float Frost; float Time; + float Dim; }; +const vec3 DIM_COLOR = vec3(16.0 / 255.0); + in vec2 texCoord; out vec4 fragColor; @@ -22,7 +25,8 @@ void main() { 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; + vec3 backdrop = mix(texture(BackdropSampler, texCoord).rgb, DIM_COLOR, Dim); + vec4 under = vec4(backdrop, 1.0) * frost; if (GlowIntensity > 0.0) { float halo = clamp(texture(HaloSampler, texCoord).a * 2.0, 0.0, 1.0); @@ -31,5 +35,6 @@ void main() { under += vec4(mix(GlowColorA.rgb, GlowColorB.rgb, wave), 1.0) * glow * (1.0 - frost); } - fragColor = gui + under * (1.0 - gui.a); + vec4 over = gui + under * (1.0 - gui.a); + fragColor = over + vec4(DIM_COLOR, 1.0) * Dim * (1.0 - over.a); } From 4fa2c849adfdb4d237a126109c94a5c67046ee4a Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:36:40 +0000 Subject: [PATCH 19/34] notifications --- .../config/settings/complex/KeybindSetting.kt | 10 +- .../com/lambda/event/events/ComposeEvent.kt | 40 +++++ src/main/kotlin/com/lambda/gui/LambdaGui.kt | 54 +++++- .../kotlin/com/lambda/gui/Notifications.kt | 155 ++++++++++++++++++ .../com/lambda/gui/component/Surface.kt | 28 +++- .../kotlin/com/lambda/gui/core/ComposeSlot.kt | 40 +++++ .../kotlin/com/lambda/gui/core/SceneHost.kt | 43 ++++- src/main/kotlin/com/lambda/gui/hud/Hud.kt | 21 ++- .../kotlin/com/lambda/gui/hud/HudEditor.kt | 25 +-- .../kotlin/com/lambda/gui/menu/Dialogs.kt | 2 + .../kotlin/com/lambda/gui/menu/MenuBar.kt | 9 +- .../com/lambda/gui/render/GuiCompositor.kt | 21 ++- .../kotlin/com/lambda/gui/render/ItemAtlas.kt | 6 +- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 5 + .../handler/handlers/NotificationHandler.kt | 68 ++++++++ .../module/modules/client/ModuleNotifier.kt | 15 +- .../com/lambda/module/modules/client/Style.kt | 6 + 17 files changed, 494 insertions(+), 54 deletions(-) create mode 100644 src/main/kotlin/com/lambda/event/events/ComposeEvent.kt create mode 100644 src/main/kotlin/com/lambda/gui/Notifications.kt create mode 100644 src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt create mode 100644 src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt 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 2cab99179..907ff2083 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -53,6 +53,7 @@ import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe import com.lambda.gui.component.Text import com.lambda.gui.component.Tooltip import com.lambda.gui.component.mouseClickable +import com.lambda.gui.core.Press import com.lambda.gui.core.observe import com.lambda.gui.settings.Labeled import com.lambda.gui.theme.LambdaTheme @@ -148,7 +149,10 @@ class KeybindSetting( .height(Look.rowHeight) .clip(RoundedCornerShape(Look.controlRounding)) .background(if (recording) colors.secondary else colors.control) - .mouseClickable { recorder = this@KeybindSetting } + .mouseClickable { + val stoppedHere = stopped === this@KeybindSetting && stoppedBy == Press.id + if (!stoppedHere) recorder = this@KeybindSetting + } .padding(horizontal = 4.dp) ) { Text( @@ -177,6 +181,8 @@ class KeybindSetting( private fun record(event: ButtonEvent.Mouse.Click) { if (!event.isPressed) return recorder = null + stopped = this + stoppedBy = Press.id + 1 if (event.button == GLFW_MOUSE_BUTTON_LEFT) return event.cancel() value = Bind(0, event.modifiers, event.button) @@ -184,6 +190,8 @@ class KeybindSetting( companion object { private var recorder: KeybindSetting? by mutableStateOf(null) + private var stopped: KeybindSetting? = null + private var stoppedBy = 0L internal val isRecording get() = recorder != null diff --git a/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt b/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt new file mode 100644 index 000000000..e45fdfb11 --- /dev/null +++ b/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt @@ -0,0 +1,40 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.event.events + +import androidx.compose.runtime.Composable +import com.lambda.event.Event + +sealed class ComposeEvent : Event { + private val added = mutableListOf<@Composable () -> Unit>() + val contents: List<@Composable () -> Unit> get() = added + + fun content(content: @Composable () -> Unit) { + added += content + } + + sealed class Hud : ComposeEvent() { + class Pre : Hud() + class Post : Hud() + } + + sealed class Gui : ComposeEvent() { + class Pre : Gui() + class Post : Gui() + } +} diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index 2c3605a25..8f025534a 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -18,14 +18,21 @@ package com.lambda.gui import androidx.compose.animation.core.animate +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.graphics.layer.GraphicsLayer +import androidx.compose.ui.graphics.rememberGraphicsLayer import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.unit.IntSize import com.lambda.Lambda.LOG @@ -33,10 +40,12 @@ import com.lambda.Lambda.mc import com.lambda.config.settings.complex.KeybindSetting import com.lambda.core.Loadable import com.lambda.event.events.ClientEvent +import com.lambda.event.events.ComposeEvent import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe import com.lambda.gui.clickgui.ClickGui import com.lambda.gui.component.KeyboardFocus import com.lambda.gui.component.TextFocus +import com.lambda.gui.core.ComposeSlot import com.lambda.gui.core.GameClipboard import com.lambda.gui.core.LocalObservations import com.lambda.gui.core.Observations @@ -85,6 +94,13 @@ object LambdaGui : Loadable { private var failedAt = 0L private var broken = false + private val beneathHud = ComposeSlot { ComposeEvent.Hud.Pre() } + private val aboveHud = ComposeSlot { ComposeEvent.Hud.Post() } + private val beneathGui = ComposeSlot { ComposeEvent.Gui.Pre() } + private val aboveGui = ComposeSlot { ComposeEvent.Gui.Post() } + private var underlay: GraphicsLayer? = null + private var layered by mutableStateOf(false) + private var settled = true private var warmingUp by mutableStateOf(false) private var warmedUp = false @@ -206,7 +222,14 @@ object LambdaGui : Loadable { warmedUp = true warmUp(size, density) } - if (screen == null && !leaving && Hud.shown.isEmpty() && settled) return + val showsGui = screen != null || leaving + beneathHud.collect() + aboveHud.collect() + beneathGui.collect(showsGui) + aboveGui.collect(showsGui) + val showsHud = !beneathHud.isEmpty || !aboveHud.isEmpty || screen == null && Hud.shown.isNotEmpty() + if (!showsGui && !showsHud && settled) return + layered = showsGui && showsHud try { val host = host ?: createHost() @@ -218,8 +241,9 @@ object LambdaGui : Loadable { val sceneChanged = host.advance(size, density) val itemsChanged = ItemAtlas.render() val redraw = sceneChanged || itemsChanged - if (redraw) host.draw(beforeScene = ItemAtlas::import) + if (redraw) host.draw(underlay.takeIf { layered }, ItemAtlas::import) + if (layered) host.underlayTexture?.let(GuiCompositor::blit) GuiCompositor.composite( host.texture ?: return, size.width, @@ -246,6 +270,7 @@ object LambdaGui : Loadable { val failed = host host = null + underlay = null ItemAtlas.release() runCatching { failed?.closeAndFree() }.onFailure { LOG.warn("Could not free the failed interface", it) @@ -295,22 +320,39 @@ object LambdaGui : Loadable { Reveal.Expiry() Presence() - when (screen) { - Screen.HudEditor -> HudEditor() - Screen.ClickGui -> Unit - null -> HudLayer() + Underlay { + beneathHud.Content() + if (screen == null) HudLayer() + aboveHud.Content() } + beneathGui.Content() + if (screen == Screen.HudEditor) HudEditor() Retained( shown = showsClickGui || warmingUp, clickGuiObservations ) { ClickGui() } + aboveGui.Content() if (warmingUp) WarmUp() } } } + @Composable + private fun Underlay(content: @Composable () -> Unit) { + val layer = rememberGraphicsLayer() + SideEffect { underlay = layer } + Box( + modifier = Modifier + .fillMaxSize() + .drawWithContent { + if (layered) layer.record { this@drawWithContent.drawContent() } + else drawContent() + }, + ) { content() } + } + @Composable private fun Presence() { val present = screen == Screen.ClickGui diff --git a/src/main/kotlin/com/lambda/gui/Notifications.kt b/src/main/kotlin/com/lambda/gui/Notifications.kt new file mode 100644 index 000000000..a550701f6 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/Notifications.kt @@ -0,0 +1,155 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui + +import androidx.compose.animation.core.Animatable +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import com.lambda.gui.component.ContentColor +import com.lambda.gui.component.Text +import com.lambda.gui.component.window +import com.lambda.gui.theme.LambdaTheme +import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Motion +import com.lambda.gui.theme.Type +import com.lambda.interaction.handler.handlers.NotificationHandler +import com.lambda.interaction.handler.handlers.NotificationHandler.Notification +import com.lambda.util.math.toCompose +import kotlin.math.roundToInt + +private val MARGIN = 6.dp +private val GAP = 4.dp +private val STRIPE = 2.dp + +@Composable +internal fun Notifications() { + val notifications = NotificationHandler.notifications + if (notifications.isEmpty()) return + val heights = remember { mutableStateMapOf() } + val density = LocalDensity.current + val scaled = Density(density.density * Look.notificationScale, density.fontScale) + CompositionLocalProvider(LocalDensity provides scaled) { + Stack(notifications, heights) + } +} + +@Composable +private fun Stack(notifications: List, heights: MutableMap) { + Box(Modifier.fillMaxSize()) { + notifications.forEach { notification -> + key(notification) { + val stacked = + notifications + .takeWhile { it !== notification } + .filterNot { it.dismissed } + .sumOf { heights[it] ?: 0 } + val beneath = notifications.takeWhile { it !== notification }.count { !it.dismissed } + Toast( + notification = notification, + stacked = stacked, + beneath = beneath, + height = heights[notification] ?: 0, + onMeasured = { heights[notification] = it }, + onGone = { + heights -= notification + NotificationHandler.remove(notification) + }, + modifier = Modifier.align(Alignment.BottomEnd) + ) + } + } + } +} + +@Composable +private fun Toast( + notification: Notification, + stacked: Int, + beneath: Int, + height: Int, + onMeasured: (height: Int) -> Unit, + onGone: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = LambdaTheme.colors + val density = LocalDensity.current + val reach = with(density) { (Look.notificationWidth + MARGIN * 4).toPx() } + val rise = + if (notification.dismissed) -height - with(density) { (MARGIN * 4).toPx() } + else with(density) { (MARGIN + GAP * beneath).toPx() } + stacked + val entered = remember { Animatable(0f) } + val risen = remember { Animatable(rise) } + LaunchedEffect(Unit) { entered.animateTo(1f, Motion.NOTIFICATIONS) } + LaunchedEffect(rise) { + risen.animateTo(rise, Motion.NOTIFICATIONS) + if (notification.dismissed) onGone() + } + + val shape = RoundedCornerShape(Look.panelRounding) + Row( + modifier + .offset { + IntOffset( + ((1f - entered.value) * reach).roundToInt() - MARGIN.roundToPx(), + -risen.value.roundToInt() + ) + } + .onSizeChanged { onMeasured(it.height) } + .width(Look.notificationWidth) + .height(IntrinsicSize.Min) + .window(colors.panel, colors.border, shape, floating = true) + ) { + Box( + Modifier + .width(STRIPE) + .fillMaxHeight() + .background(notification.accent?.toCompose() ?: colors.primary) + ) + ContentColor(colors.onSurface) { + Column(Modifier.padding(Look.panelPadding, Look.panelPadding / 2)) { + Text(notification.title, style = Type.label, maxLines = 1) + if (notification.message.isNotEmpty()) { + Text(notification.message, color = colors.onSurfaceVariant) + } + } + } + } +} diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt index 12e8cfb8e..f619825ea 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -24,10 +24,14 @@ import androidx.compose.ui.composed import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.drawWithCache +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.ClipOp import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.addOutline import androidx.compose.ui.graphics.asSkiaPath @@ -37,6 +41,9 @@ import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.skiaCanvas import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.lambda.gui.theme.Look import org.jetbrains.skia.Canvas @@ -104,10 +111,29 @@ fun Modifier.window( floating: Boolean = false ): Modifier = (if (floating) dropShadow(shape) else this) + .border(Look.outlineWidth, if (Look.outlines) border else Color.Transparent, shape) .glass(color, shape) - .then(if (Look.outlines) Modifier.border(Look.outlineWidth, border, shape) else Modifier) + .clip(if (Look.outlines) Inset(shape, Look.outlineWidth / 2) else RectangleShape) .consumeClicks() +private data class Inset(private val shape: Shape, private val inset: Dp) : Shape { + override fun createOutline( + size: Size, + layoutDirection: LayoutDirection, + density: Density + ): Outline { + val edge = with(density) { inset.toPx() } + val inner = + Size( + (size.width - edge * 2).coerceAtLeast(0f), + (size.height - edge * 2).coerceAtLeast(0f) + ) + val path = Path().apply { addOutline(shape.createOutline(inner, layoutDirection, density)) } + path.translate(Offset(edge, edge)) + return Outline.Generic(path) + } +} + fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = drawWithCache { val body = Path().apply { addOutline(shape.createOutline(size, layoutDirection, this@drawWithCache)) } diff --git a/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt b/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt new file mode 100644 index 000000000..d44d114e7 --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt @@ -0,0 +1,40 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.gui.core + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.lambda.event.EventFlow.post +import com.lambda.event.events.ComposeEvent + +internal class ComposeSlot(private val event: () -> ComposeEvent) { + private var contents by mutableStateOf(emptyList<@Composable () -> Unit>()) + val isEmpty get() = contents.isEmpty() + + fun collect(active: Boolean = true) { + val collected = + if (active) event().post().contents + else emptyList() + if (collected != contents) contents = collected + } + + @Composable + fun Content() = contents.forEach { it() } +} diff --git a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt index 7a0e66483..2f40b41fc 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt @@ -20,11 +20,16 @@ package com.lambda.gui.core import androidx.compose.runtime.Composable import androidx.compose.ui.InternalComposeUiApi import androidx.compose.ui.graphics.asComposeCanvas +import androidx.compose.ui.graphics.drawscope.CanvasDrawScope +import androidx.compose.ui.graphics.layer.GraphicsLayer +import androidx.compose.ui.graphics.layer.drawLayer import androidx.compose.ui.platform.FrameRecomposer import androidx.compose.ui.scene.CanvasLayersComposeScene import androidx.compose.ui.scene.ComposeScene import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.toSize import com.mojang.blaze3d.systems.RenderSystem import com.mojang.blaze3d.textures.GpuTexture import com.mojang.blaze3d.textures.GpuTextureView @@ -76,8 +81,10 @@ internal class SceneHost( private var skia: DirectContext? = null private var target: SkiaTarget? = null + private var underlayTarget: SkiaTarget? = null val texture: GpuTextureView? get() = target?.view + val underlayTexture: GpuTextureView? get() = underlayTarget?.view fun advance(size: IntSize, density: Float): Boolean { if (scene.size != size || scene.density.density != density) { @@ -91,21 +98,40 @@ internal class SceneHost( return invalidated || scene.hasPendingDraw || target == null } - fun draw(beforeScene: (DirectContext) -> Unit = {}) { + fun draw(underlay: GraphicsLayer? = null, beforeScene: (DirectContext) -> Unit = {}) { val size = scene.size ?: return - val outgrown = target?.takeIf { it.size != size } - val target = target?.takeIf { it.size == size } ?: SkiaTarget(size).also { target = it } + val outgrown = + listOfNotNull( + target?.takeIf { it.size != size }, + underlayTarget?.takeIf { it.size != size || underlay == null } + ) + val target = target?.takeIf { it !in outgrown } ?: SkiaTarget(size).also { target = it } + val underlayTarget = + if (underlay == null) null + else underlayTarget?.takeIf { it !in outgrown } ?: SkiaTarget(size) + this.underlayTarget = underlayTarget GlState.borrow { val skia = skia ?: DirectContext.makeGL().also { skia = it } - outgrown?.detach() + outgrown.forEach { it.detach() } val surface = target.attach(skia) + val underlaySurface = underlayTarget?.attach(skia) skia.resetGLAll() beforeScene(skia) surface.canvas.clear(Color.TRANSPARENT) scene.draw(surface.canvas.asComposeCanvas()) surface.flushAndSubmit() + if (underlay != null && underlaySurface != null) { + underlaySurface.canvas.clear(Color.TRANSPARENT) + CanvasDrawScope().draw( + scene.density, + LayoutDirection.Ltr, + underlaySurface.canvas.asComposeCanvas(), + size.toSize() + ) { drawLayer(underlay) } + underlaySurface.flushAndSubmit() + } } - outgrown?.close() + outgrown.forEach { it.close() } invalidated = false } @@ -117,14 +143,15 @@ internal class SceneHost( fun closeAndFree() { runCatching { scene.close() } runCatching { recomposer.close() } - val freed = target + val freed = listOfNotNull(target, underlayTarget) target = null + underlayTarget = null GlState.borrow { - freed?.detach() + freed.forEach { it.detach() } skia?.close() } skia = null - freed?.close() + freed.forEach { it.close() } } } diff --git a/src/main/kotlin/com/lambda/gui/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt index 9b8bc038e..ab09ddc2f 100644 --- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -25,11 +25,15 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layout +import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.unit.dp import com.lambda.Lambda.mc import com.lambda.config.Config @@ -39,6 +43,7 @@ import com.lambda.gui.GuiScreen import com.lambda.gui.component.Text import com.lambda.gui.component.shadowed import com.lambda.gui.core.observe +import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Type import com.lambda.module.HudModule import com.lambda.module.ModuleRegistry @@ -49,7 +54,7 @@ private val HUD_TEXT_SHADOW = Color.Black.copy(alpha = 0.75f) private val ELEMENT_PADDING = 1.dp object HudConfig : Loadable, Config("HUD", HudCategory) { - val showInScreens by setting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The Lambda GUI always shows them.") + val showInScreens by setting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The HUD editor always shows them.") val textColor by setting("Text Color", java.awt.Color.WHITE, "Colour of HUD text") val scale by setting("Scale", 1f, 0.5f..3f, 0.05f, "Size of HUD text") } @@ -57,18 +62,24 @@ object HudConfig : Loadable, Config("HUD", HudCategory) { internal object Hud { val modules: List by lazy { ModuleRegistry.modules.filterIsInstance() } + val enabled: List + get() = modules.filter { it.isEnabled } + val shown: List get() { val screen = mc.currentScreen val covered = screen != null && screen !is GuiScreen && !HudConfig.showInScreens return if (mc.world == null || mc.options.hudHidden || covered) emptyList() - else modules.filter { it.isEnabled } + else enabled } } @Composable internal fun HudLayer(editor: HudEditorState? = null) { - val shown by observe { Hud.shown } + val shown by observe { + if (editor != null) Hud.enabled + else Hud.shown + } Box(Modifier.fillMaxSize()) { shown.forEach { hud -> key(hud) { HudElement(hud, editor) } @@ -80,6 +91,7 @@ internal fun HudLayer(editor: HudEditorState? = null) { private fun HudElement(hud: HudModule, editor: HudEditorState?) { val anchor by observe { Offset(hud.anchorX, hud.anchorY) } val background by observe { hud.backgroundColor.value.toCompose() } + var empty by remember { mutableStateOf(false) } if (editor != null) DisposableEffect(hud) { onDispose { editor.bounds -= hud } } @@ -108,7 +120,8 @@ private fun HudElement(hud: HudModule, editor: HudEditorState?) { .background(background) .padding(ELEMENT_PADDING) ) { - hud.Content() + Box(Modifier.onSizeChanged { empty = it.width == 0 || it.height == 0 }) { hud.Content() } + if (editor != null && empty) HudText(hud.name, color = LambdaTheme.colors.onSurfaceVariant) } } diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt index df0335e07..71bac86e2 100644 --- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -131,19 +131,20 @@ internal class HudEditorState(snapping: State) { var screen = Size.Zero var density = Density(1f) - val drop: Snap.Result? by derivedStateOf { - val hud = dragged ?: return@derivedStateOf null - val element = Rect(draggedTo, bounds[hud]?.size ?: return@derivedStateOf null) - if (this.snapping) { - Snap.snap( - element, - bounds.filterKeys { it != hud }.values, - Rect(Offset.Zero, screen), - density - ) + val drop: Snap.Result? by + derivedStateOf { + val hud = dragged ?: return@derivedStateOf null + val element = Rect(draggedTo, bounds[hud]?.size ?: return@derivedStateOf null) + if (this.snapping) { + Snap.snap( + element, + bounds.filterKeys { it != hud }.values, + Rect(Offset.Zero, screen), + density + ) + } + else Snap.free(element, Rect(Offset.Zero, screen)) } - else Snap.free(element, Rect(Offset.Zero, screen)) - } fun shownPosition(hud: HudModule) = drop?.position.takeIf { dragged == hud } } diff --git a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt index 5cbb2960f..c1419279f 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -49,6 +49,7 @@ import com.lambda.gui.component.Dialog import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput import com.lambda.gui.component.rememberTexture +import com.lambda.gui.core.LocalShown import com.lambda.gui.settings.ConfigSettings import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Type @@ -165,6 +166,7 @@ internal fun AboutDialog(onDismiss: () -> Unit) { @Composable internal fun LoaderPromptDialog(prompt: AutoUpdater.Prompt) { + if (!LocalShown.current && prompt == AutoUpdater.Prompt.FirstLaunch) return val colors = LambdaTheme.colors Dialog(onDismiss = { AutoUpdater.answerPrompt(accepted = false) }) { Column(Modifier.width(260.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index cdda54cff..3cf0067d7 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -17,8 +17,6 @@ package com.lambda.gui.menu -import androidx.compose.animation.animateColorAsState -import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement @@ -271,11 +269,6 @@ private fun ResultRow( onClick: () -> Unit ) { val colors = LambdaTheme.colors - val lit by - animateColorAsState( - if (marked) colors.controlSelected else Color.Transparent, - tween(90) - ) val intoView = remember { BringIntoViewRequester() } LaunchedEffect(marked) { if (marked) intoView.bringIntoView() @@ -287,7 +280,7 @@ private fun ResultRow( .fillMaxWidth() .widthIn(min = SEARCH_WIDTH) .bringIntoViewRequester(intoView) - .background(lit) + .background(if (marked) colors.controlSelected else Color.Transparent) .pointerInput(Unit) { awaitPointerEventScope { while (true) { diff --git a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt index aef3e80d3..ccf13555a 100644 --- a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt +++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt @@ -79,14 +79,7 @@ internal object GuiCompositor { if (effects.frost <= 0f && effects.glow <= 0f && effects.dim <= 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 + return blit(gui) } val backdropView = @@ -111,6 +104,18 @@ internal object GuiCompositor { } } + fun blit(layer: GpuTextureView) { + val screen = mc.framebuffer.colorAttachmentView ?: return + val nearest = RenderSystem.getSamplerCache().get(FilterMode.NEAREST) + RenderSystem.getDevice().createCommandEncoder() + .createRenderPass({ "Lambda GUI" }, screen, OptionalInt.empty()) + .use { pass -> + pass.setPipeline(LambdaRenderPipelines.GUI_BLIT) + pass.bindTexture("InSampler", layer, nearest) + pass.draw(0, 3) + } + } + private fun writeUniforms(effects: Effects) { MemoryStack.stackPush().use { stack -> val data = diff --git a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt index 9d678abd4..25fa5739a 100644 --- a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt +++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt @@ -68,6 +68,7 @@ object ItemAtlas { private val slots = ArrayList() private var strip: Strip? = null private var pendingImport = false + private var rearranged = false private val state = GuiRenderState() private val context by lazy { DrawContext(mc, state, 0, 0) } @@ -88,10 +89,12 @@ object ItemAtlas { fun add(slot: Slot) { slots += slot + rearranged = true } fun remove(slot: Slot) { slots -= slot + rearranged = true } fun DrawScope.drawItem(slot: Slot) { @@ -136,7 +139,7 @@ object ItemAtlas { moving = moving || it.state().isAnimated } val changed = - scale != this.scale || models != renderedModels || + rearranged || scale != this.scale || models != renderedModels || slots.any { !ItemStack.areEqual(it.stack, it.rendered) } val now = System.nanoTime() if (!changed && !(moving && now - renderedAt >= ANIMATION_INTERVAL)) { @@ -153,6 +156,7 @@ object ItemAtlas { Strip(width, height).also { strip = it } } this.scale = scale + rearranged = false renderedModels = models slots.forEach { it.rendered = it.stack.copy() } draw(strip.framebuffer) diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index d66a55876..3cdb687f2 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -113,6 +113,8 @@ internal object Look { val rowHeight by style { Style.elementHeight.dp } val windowWidth by style { Style.windowWidth.dp } val settingsWidth by style { Style.settingsWidth.dp } + val notificationScale by style { Style.notificationScale } + val notificationWidth by style { Style.notificationWidth.dp } val windowGap by style { Style.windowGap.dp } val windowTop by style { Style.windowTop.dp } val modulePadding by style { Style.modulePadding.dp } @@ -129,6 +131,7 @@ internal object Look { internal object Motion : MotionDurationScale { private const val PAGE_MILLIS = 160 private const val GUI_MILLIS = 180 + private const val NOTIFICATION_MILLIS = 260 private val UNFOLDING = spring( stiffness = Spring.StiffnessMedium, @@ -142,6 +145,8 @@ internal object Motion : MotionDurationScale { else 0f } + val NOTIFICATIONS: FiniteAnimationSpec = tween(NOTIFICATION_MILLIS) + val UNSCALED = object : MotionDurationScale { override val scaleFactor get() = 1f diff --git a/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt new file mode 100644 index 000000000..a467ec9f7 --- /dev/null +++ b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt @@ -0,0 +1,68 @@ +/* + * Copyright 2026 Lambda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.lambda.interaction.handler.handlers + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.lambda.Lambda.mc +import com.lambda.core.Loadable +import com.lambda.event.events.ComposeEvent +import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe +import com.lambda.gui.Notifications +import com.lambda.gui.core.RenderThread +import com.lambda.module.modules.client.Style +import java.awt.Color + +object NotificationHandler : Loadable { + private const val MAX_KEPT = 40 + + private val kept = mutableStateListOf() + val notifications: List get() = kept + + init { + listenUnsafe { event -> + if (kept.isNotEmpty()) event.content { Notifications() } + } + } + + override fun load() = "Loaded Notification Handler" + + fun notify(title: String, message: String = "", accent: Color? = null) = + mc.execute { + val notification = Notification(title, message, accent) + kept += notification + if (kept.size > MAX_KEPT) kept.removeRange(0, kept.size - MAX_KEPT) + kept.filterNot { it.dismissed } + .dropLast(Style.maxNotifications) + .forEach { it.dismissed = true } + RenderThread.after((Style.notificationSeconds * 1000).toLong()) { + notification.dismissed = true + } + } + + fun remove(notification: Notification) { + kept -= notification + } + + class Notification(val title: String, val message: String, val accent: Color?) { + var dismissed by mutableStateOf(false) + internal set + } +} diff --git a/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt b/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt index 40a791379..78789fa2c 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt @@ -19,6 +19,7 @@ package com.lambda.module.modules.client import com.lambda.event.events.ModuleEvent import com.lambda.event.listener.SafeListener.Companion.listen +import com.lambda.interaction.handler.handlers.NotificationHandler import com.lambda.module.Module import com.lambda.module.ModuleTag import com.lambda.util.CommunicationUtils.log @@ -38,16 +39,17 @@ object ModuleNotifier : Module( tag = ModuleTag.CLIENT, enabledByDefault = true ) { - var notifyTarget by setting("Notify Target", setOf(NotifyTarget.ActionBar), NotifyTarget.entries.toSet(), description = "Where to send notifications when modules are toggled") + var notifyTarget by setting("Notify Target", setOf(NotifyTarget.Notification), NotifyTarget.entries.toSet(), description = "Where to send notifications when modules are toggled") enum class NotifyTarget(override val displayName: String, override val description: String) : Describable, NamedEnum { Chat("Chat", "Sends a message to chat when a module is toggled"), - ActionBar("Action Bar", "Sends a message to the action bar when a module is toggled"), ; + ActionBar("Action Bar", "Sends a message to the action bar when a module is toggled"), + Notification("Notification", "Slides a notification in at the lower right of the screen when a module is toggled"), ; } init { listen { event -> - logToTargets(event.module) { + logToTargets(event.module, "Enabled", Color(Colors.GREEN)) { color(Color(Colors.GREEN)) { literal("on") } @@ -55,7 +57,7 @@ object ModuleNotifier : Module( } listen { event -> - logToTargets(event.module) { + logToTargets(event.module, "Disabled", Color(Colors.RED)) { color(Color(Colors.RED)) { literal("off") } @@ -63,7 +65,10 @@ object ModuleNotifier : Module( } } - private fun logToTargets(module: Module, action: TextBuilder.() -> Unit) { + private fun logToTargets(module: Module, state: String, color: Color, action: TextBuilder.() -> Unit) { + if (NotifyTarget.Notification in notifyTarget) { + NotificationHandler.notify(module.name, state, color) + } if (NotifyTarget.Chat in notifyTarget) { module.log(buildText(action)) } diff --git a/src/main/kotlin/com/lambda/module/modules/client/Style.kt b/src/main/kotlin/com/lambda/module/modules/client/Style.kt index 8f81273d8..292b0dd21 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/Style.kt @@ -43,6 +43,7 @@ object Style : Module( private const val SHAPE_GROUP = "Shape" private const val LAYOUT_GROUP = "Layout" private const val MOTION_GROUP = "Motion" + private const val NOTIFICATIONS_GROUP = "Notifications" private const val DARK_THEME_GROUP = "Dark Theme" private const val LIGHT_THEME_GROUP = "Light Theme" @@ -101,6 +102,11 @@ object Style : Module( @Group(MOTION_GROUP) val scrollSpeed by setting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") @Group(MOTION_GROUP) val tooltipDelay by setting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") + @Group(NOTIFICATIONS_GROUP) val notificationScale by setting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface") + @Group(NOTIFICATIONS_GROUP) val notificationWidth by setting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines") + @Group(NOTIFICATIONS_GROUP) val notificationSeconds by setting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it slides away") + @Group(NOTIFICATIONS_GROUP) val maxNotifications by setting("Max Notifications", 5, 1..12, 1, "How many notifications stack before the oldest slides off the bottom of the screen") + @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( PaletteSettings( this, From 97121e8f9ea69b5cadfbc3104c1fa8699e214c1b Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:20:13 +0000 Subject: [PATCH 20/34] move gui and client settings, make the close gui button show the keybind too. Update the about menu's time. Capture menu dropdowns in close animations. --- .../ClientPlayInteractionManagerMixin.java | 4 +- src/main/kotlin/com/lambda/core/Loader.kt | 4 +- .../graphics/mc/renderer/ChunkedRenderer.kt | 6 +- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 230 ++++++++++++++++ src/main/kotlin/com/lambda/gui/LambdaGui.kt | 44 +-- .../com/lambda/gui/clickgui/ClickGui.kt | 21 +- .../com/lambda/gui/clickgui/OpenSettings.kt | 4 +- .../kotlin/com/lambda/gui/component/Popups.kt | 83 ++++-- .../kotlin/com/lambda/gui/component/Scroll.kt | 4 +- .../com/lambda/gui/component/Surface.kt | 24 ++ .../kotlin/com/lambda/gui/core/Retained.kt | 3 + .../kotlin/com/lambda/gui/menu/Dialogs.kt | 5 +- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 31 +-- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 60 ++-- .../handlers/InteractedBlockHandler.kt | 6 +- .../handler/handlers/NotificationHandler.kt | 6 +- .../handlers/breaking/BrokenBlockHandler.kt | 6 +- .../managers/inventory/InventoryManager.kt | 20 +- src/main/kotlin/com/lambda/module/Module.kt | 6 +- .../lambda/module/modules/client/Client.kt | 60 ---- .../com/lambda/module/modules/client/Style.kt | 259 ------------------ .../combat/autodisconnect/AutoDisconnect.kt | 10 +- .../autodisconnect/DisconnectDetailsWidget.kt | 10 +- .../lambda/module/modules/hud/TaskFlowHud.kt | 4 +- src/main/kotlin/com/lambda/task/Task.kt | 2 +- .../kotlin/com/lambda/task/tasks/BuildTask.kt | 4 +- .../com/lambda/util/CommunicationUtils.kt | 8 +- .../com/lambda/util/player/RotationUtils.kt | 22 +- .../kotlin/com/lambda/util/text/TextDsl.kt | 4 +- 29 files changed, 461 insertions(+), 489 deletions(-) delete mode 100644 src/main/kotlin/com/lambda/module/modules/client/Client.kt delete mode 100644 src/main/kotlin/com/lambda/module/modules/client/Style.kt diff --git a/src/main/java/com/lambda/mixin/entity/ClientPlayInteractionManagerMixin.java b/src/main/java/com/lambda/mixin/entity/ClientPlayInteractionManagerMixin.java index 5630fb0b2..2ba0b3192 100644 --- a/src/main/java/com/lambda/mixin/entity/ClientPlayInteractionManagerMixin.java +++ b/src/main/java/com/lambda/mixin/entity/ClientPlayInteractionManagerMixin.java @@ -17,13 +17,13 @@ package com.lambda.mixin.entity; +import com.lambda.config.ClientConfig; import com.lambda.event.EventFlow; import com.lambda.event.events.InventoryEvent; import com.lambda.event.events.PlayerEvent; import com.lambda.interaction.handler.handlers.BaritoneHandler; import com.lambda.interaction.manager.managers.inventory.InventoryManager; import com.lambda.interaction.manager.managers.rotating.RotationManager; -import com.lambda.module.modules.client.Client; import com.llamalad7.mixinextras.injector.ModifyExpressionValue; import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; @@ -120,7 +120,7 @@ public void clickSlotTail(int syncId, int slotId, int button, SlotActionType act @ModifyExpressionValue(method = "clickSlot", at = @At(value = "INVOKE", target = "Lnet/minecraft/screen/ScreenHandler;getRevision()I")) private int modifyClickSlotRevision(int originalRevision) { - return Client.INSTANCE.getAvoidInventoryDesync() ? -1 : originalRevision; + return ClientConfig.INSTANCE.getAvoidInventoryDesync() ? -1 : originalRevision; } /** diff --git a/src/main/kotlin/com/lambda/core/Loader.kt b/src/main/kotlin/com/lambda/core/Loader.kt index 88e0a416f..49e2bf8c3 100644 --- a/src/main/kotlin/com/lambda/core/Loader.kt +++ b/src/main/kotlin/com/lambda/core/Loader.kt @@ -22,13 +22,13 @@ import com.lambda.Lambda.LOG import com.lambda.util.CommunicationUtils.ascii import com.lambda.util.ReflectionUtils.getInstances import kotlin.system.measureTimeMillis -import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds object Loader { private val started = System.currentTimeMillis() val runtime: String - get() = "${(System.currentTimeMillis() - started).milliseconds}" + get() = "${((System.currentTimeMillis() - started) / 1000).seconds}" private val loadables = getInstances() diff --git a/src/main/kotlin/com/lambda/graphics/mc/renderer/ChunkedRenderer.kt b/src/main/kotlin/com/lambda/graphics/mc/renderer/ChunkedRenderer.kt index ca833a3d4..d1bc25678 100644 --- a/src/main/kotlin/com/lambda/graphics/mc/renderer/ChunkedRenderer.kt +++ b/src/main/kotlin/com/lambda/graphics/mc/renderer/ChunkedRenderer.kt @@ -18,6 +18,7 @@ package com.lambda.graphics.mc.renderer import com.lambda.Lambda.mc +import com.lambda.config.ClientConfig import com.lambda.context.SafeContext import com.lambda.event.events.RenderEvent import com.lambda.event.events.TickEvent @@ -29,7 +30,6 @@ import com.lambda.graphics.mc.RegionRenderer import com.lambda.graphics.mc.RenderBuilder import com.lambda.graphics.mc.RenderDsl import com.lambda.module.Module -import com.lambda.module.modules.client.Client import com.lambda.util.world.FastVector import com.lambda.util.world.fastVectorOf import com.mojang.blaze3d.buffers.GpuBufferSlice @@ -89,13 +89,13 @@ class ChunkedRenderer( owner.listenConcurrentlyUnsafe { if (pauseUpdates()) return@listenConcurrentlyUnsafe val depth = depthTest() - rebuildSet.take(Client.chunkRebuildsPerTick).forEach { chunkData -> + rebuildSet.take(ClientConfig.chunkRebuildsPerTick).forEach { chunkData -> if (rebuildSet.remove(chunkData)) chunkData.rebuild(depth) } } owner.listenUnsafe { - val polls = minOf(Client.chunkUploadsPerTick, uploadQueue.size) + val polls = minOf(ClientConfig.chunkUploadsPerTick, uploadQueue.size) repeat(polls) { uploadQueue.poll()?.invoke() } } diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index 486fbee9c..4921ab3b4 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -18,20 +18,39 @@ package com.lambda.gui import com.lambda.config.Config +import com.lambda.config.ConfigBlock +import com.lambda.config.Group import com.lambda.config.Tab import com.lambda.config.categories.GuiCategory import com.lambda.config.entries.onValueChange +import com.lambda.config.settings.appliedOnRelease import com.lambda.core.Loadable +import com.lambda.gui.theme.GuiFont +import com.lambda.gui.theme.GuiInterrupt +import com.lambda.gui.theme.GuiTransition +import com.lambda.gui.theme.Palette import com.lambda.util.KeyCode +import com.lambda.util.NamedEnum import com.lambda.util.WindowUtils.setLambdaWindowIcon +import com.lambda.util.math.toCompose import net.minecraft.SharedConstants import net.minecraft.client.util.Icons +import org.jetbrains.skiko.SystemTheme +import org.jetbrains.skiko.currentSystemTheme import java.awt.Color @Suppress("unused") object GuiConfig : Loadable, Config("GUI", GuiCategory) { private const val GENERAL_TAB = "General" private const val SNAPPING_TAB = "Snapping" + private const val STYLE_TAB = "Style" + private const val BACKDROP_GROUP = "Backdrop" + private const val SHAPE_GROUP = "Shape" + private const val LAYOUT_GROUP = "Layout" + private const val MOTION_GROUP = "Motion" + private const val NOTIFICATIONS_GROUP = "Notifications" + private const val DARK_THEME_GROUP = "Dark Theme" + private const val LIGHT_THEME_GROUP = "Light Theme" @Tab(GENERAL_TAB) val keybind by setting("Keybind", KeyCode.Y, "Opens and closes the click GUI", screenCheck = false) .onPressUnsafe { LambdaGui.toggle() } @@ -51,6 +70,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @Tab(GENERAL_TAB) val lambdaTitleAppendixName by setting("Append Username", true) { setLambdaWindowTitle } .onValueChange { _, _ -> mc.updateWindowTitle() } @Tab(GENERAL_TAB) val keepSettingsOpen by setting("Keep Settings Open", false, "Leaves a module's settings open when the click GUI closes, so they are still there when it opens again") + @Tab(GENERAL_TAB) val hoverSubmenus by setting("Open Submenus On Hover", true, "Opens a submenu when the pointer is over its row. When off, a submenu opens on a click.") @Tab(GENERAL_TAB) private val resetWindowLayout by setting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded") @Tab(SNAPPING_TAB) val snapEnabled by setting("Enable Snapping", true, "Master toggle for snapping HUD elements and click GUI windows into line when they are dragged") @@ -66,6 +86,149 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @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 } + private enum class ThemeMode(override val displayName: String) : NamedEnum { + Auto("Auto"), + Dark("Dark"), + Light("Light"), + } + + @Tab(STYLE_TAB) private val themeMode by setting("Theme", ThemeMode.Dark, "Auto follows the theme of your operating system") + @Tab(STYLE_TAB) 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") + @Tab(STYLE_TAB) val fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") + @Tab(STYLE_TAB) val scale by setting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() + + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimBackground by setting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimStrength by setting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blur by setting("Blur", true, "Blurs what is behind windows for a frosted glass look") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blurRadius by setting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val layerFade by setting("Layer Fade", 0.5f, 0f..1f, 0.05f, "How far the interface fades out underneath a panel, menu or window opened over it, letting the game show there instead so the two do not run together") { blur } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glow by setting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowRadius by setting("Glow Radius", 17f, 1f..100f, 1f) { glow } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowIntensity by setting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } + + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val windowRounding by setting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val panelRounding by setting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val menuRounding by setting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val controlRounding by setting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlineWidth by setting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val shadows by setting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") + + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val elementHeight by setting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowWidth by setting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingsWidth by setting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowGap by setting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowTop by setting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val modulePadding by setting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val panelPadding by setting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingSpacing by setting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val groupIndent by setting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val inlineSettings by setting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val multipleSettings by setting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") + + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animations by setting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animationSpeed by setting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openAnimation by setting("Open Animation", true, "Animates the click GUI in when it opens") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openStyle by setting("Open Style", setOf(GuiTransition.Unfold), GuiTransition.entries.toSet(), "What the click GUI does as it comes in, any of them together: its windows unfold out of their headers, and all of it fades, slides down or zooms in") { animations && openAnimation } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeAnimation by setting("Close Animation", true, "Animates the click GUI out when it closes. The game has the mouse and keyboard back at once: the animation only plays over it") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeStyle by setting("Close Style", setOf(GuiTransition.Unfold, GuiTransition.Fade), GuiTransition.entries.toSet(), "What the click GUI does as it goes out, any of them together: its windows fold into their headers, and all of it fades, slides up or zooms out") { animations && closeAnimation } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val interruptedAnimation by setting("Interrupted Animation", GuiInterrupt.Reverse, "What happens when the click GUI is opened or closed again before its animation is done: it turns around from where it is, or skips to the end and plays the other one in full") { animations && (openAnimation || closeAnimation) } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val windowAnimations by setting("Window Animations", true, "Category windows unfold out of their headers") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val panelAnimations by setting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val pageAnimations by setting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val smoothScrolling by setting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val scrollSpeed by setting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val tooltipDelay by setting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") + + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationScale by setting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface") + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationWidth by setting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines") + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSeconds by setting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it slides away") + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val maxNotifications by setting("Max Notifications", 5, 1..12, 1, "How many notifications stack before the oldest slides off the bottom of the screen") + + @Tab(STYLE_TAB) @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( + PaletteSettings( + this, + primary = Color(214, 77, 113), + secondary = Color(255, 141, 128), + surface = Color(69, 48, 55, 165), + panel = Color(55, 38, 45, 200), + inset = Color(0, 0, 0, 190), + onSurface = Color(246, 236, 239), + onSurfaceVariant = Color(184, 156, 166), + header = Color(222, 53, 101), + onHeader = Color(255, 246, 248), + moduleEnabled = Color(161, 42, 75), + onModuleEnabled = Color(255, 240, 244), + control = Color(214, 77, 113), + controlSelected = Color(92, 64, 75), + onControl = Color(246, 236, 239), + track = Color(38, 28, 32, 230), + input = Color(32, 23, 26, 230), + border = Color(128, 92, 104, 235), + textShadow = Color(0, 0, 0, 150), + glowA = Color(222, 53, 101), + glowB = Color(255, 141, 128), + ) + ) + + @Tab(STYLE_TAB) @Group(LIGHT_THEME_GROUP) private val lightTheme by configBlock( + PaletteSettings( + this, + primary = Color(222, 53, 101), + secondary = Color(209, 74, 59), + surface = Color(250, 236, 241, 228), + panel = Color(244, 226, 232, 240), + inset = Color(120, 0, 40, 68), + onSurface = Color(61, 40, 47), + onSurfaceVariant = Color(110, 86, 95), + header = Color(222, 53, 101), + onHeader = Color(255, 250, 251), + moduleEnabled = Color(232, 84, 126), + onModuleEnabled = Color(255, 250, 251), + control = Color(240, 139, 166), + controlSelected = Color(224, 197, 206), + onControl = Color(61, 40, 47), + track = Color(209, 192, 199, 220), + input = Color(255, 250, 252, 210), + border = Color(184, 154, 164, 238), + textShadow = Color(0, 0, 0, 0), + glowA = Color(222, 53, 101), + glowB = Color(255, 141, 128), + ) + ) + + private val theme: PaletteSettings + get() = + when (themeMode) { + ThemeMode.Dark -> darkTheme + ThemeMode.Light -> lightTheme + ThemeMode.Auto -> + if (SystemAppearance.isDark) darkTheme + else lightTheme + } + + val palette: Palette get() = theme.toPalette() + val glowColorA: Color get() = theme.glowA + val glowColorB: Color get() = theme.glowB + + private object SystemAppearance { + private const val REFRESH_MILLIS = 1000L + + private var checkedAt = 0L + private var dark = true + + val isDark: Boolean + get() { + val now = System.currentTimeMillis() + if (now - checkedAt > REFRESH_MILLIS) { + checkedAt = now + dark = currentSystemTheme != SystemTheme.LIGHT + } + return dark + } + } + internal data class WindowPlacement( val x: Float, val y: Float, @@ -112,3 +275,70 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { ) } } + +class PaletteSettings( + override val c: Config, + primary: Color, + secondary: Color, + surface: Color, + panel: Color, + inset: Color, + onSurface: Color, + onSurfaceVariant: Color, + header: Color, + onHeader: Color, + moduleEnabled: Color, + onModuleEnabled: Color, + control: Color, + controlSelected: Color, + onControl: Color, + track: Color, + input: Color, + border: Color, + textShadow: Color, + glowA: Color, + glowB: Color, +) : ConfigBlock { + private val primary by c.setting("Primary", primary, "Accent colour: the fill of sliders and ticked boxes") + private val secondary by c.setting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") + private val surface by c.setting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") + private val panel by c.setting("Panel", panel, "Fill of settings panels, menus and dialogs") + private val inset by c.setting("Inset", inset, "Shade behind settings that open under their module, and over the module whose settings are open beside it") + private val onSurface by c.setting("On Surface", onSurface, "Text on windows") + private val onSurfaceVariant by c.setting("On Surface Variant", onSurfaceVariant, "Subdued text on windows") + private val header by c.setting("Header", header) + private val onHeader by c.setting("On Header", onHeader) + private val moduleEnabled by c.setting("Module Enabled", moduleEnabled) + private val onModuleEnabled by c.setting("On Module Enabled", onModuleEnabled) + private val control by c.setting("Control", control, "Fill of dropdowns, buttons and key caps") + private val controlSelected by c.setting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") + private val onControl by c.setting("On Control", onControl) + private val track by c.setting("Slider Track", track) + private val input by c.setting("Text Field", input) + private val border by c.setting("Border", border) + private val textShadow by c.setting("Text Shadow", textShadow) + val glowA by c.setting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { GuiConfig.glow } + val glowB by c.setting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { GuiConfig.glow } + + fun toPalette() = + Palette( + primary = primary.toCompose(), + secondary = secondary.toCompose(), + surface = surface.toCompose(), + panel = panel.toCompose(), + inset = inset.toCompose(), + onSurface = onSurface.toCompose(), + onSurfaceVariant = onSurfaceVariant.toCompose(), + header = header.toCompose(), + onHeader = onHeader.toCompose(), + moduleEnabled = moduleEnabled.toCompose(), + onModuleEnabled = onModuleEnabled.toCompose(), + control = control.toCompose(), + controlSelected = controlSelected.toCompose(), + onControl = onControl.toCompose(), + track = track.toCompose(), + input = input.toCompose(), + border = border.toCompose(), + textShadow = textShadow.toCompose(), + ) +} diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index 8f025534a..ccf2c3eb9 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -37,6 +37,7 @@ import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.unit.IntSize import com.lambda.Lambda.LOG import com.lambda.Lambda.mc +import com.lambda.config.ClientConfig import com.lambda.config.settings.complex.KeybindSetting import com.lambda.core.Loadable import com.lambda.event.events.ClientEvent @@ -48,6 +49,7 @@ import com.lambda.gui.component.TextFocus import com.lambda.gui.core.ComposeSlot import com.lambda.gui.core.GameClipboard import com.lambda.gui.core.LocalObservations +import com.lambda.gui.core.LocalPresence import com.lambda.gui.core.Observations import com.lambda.gui.core.Retained import com.lambda.gui.core.SceneHost @@ -64,8 +66,6 @@ import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look import com.lambda.gui.theme.Motion import com.lambda.module.modules.client.AutoUpdater -import com.lambda.module.modules.client.Client -import com.lambda.module.modules.client.Style import com.lambda.sound.LambdaSound import com.lambda.sound.SoundHandler.play import com.lambda.util.CommunicationUtils.warn @@ -117,17 +117,17 @@ object LambdaGui : Loadable { else shownPresence internal val transitions: Collection get() = - if (leaving) Style.closeStyle - else Style.openStyle + if (leaving) GuiConfig.closeStyle + else GuiConfig.openStyle internal val unfoldsOpen get() = - Style.animations && - Style.openAnimation && - GuiTransition.Unfold in Style.openStyle + GuiConfig.animations && + GuiConfig.openAnimation && + GuiTransition.Unfold in GuiConfig.openStyle private val showsClickGui get() = screen == Screen.ClickGui || leaving internal val foldsClosed - get() = leaving && GuiTransition.Unfold in Style.closeStyle + get() = leaving && GuiTransition.Unfold in GuiConfig.closeStyle private val observations = Observations() private val clickGuiObservations = Observations() @@ -161,7 +161,7 @@ object LambdaGui : Loadable { fun close() { val animated = - Style.animations && Style.closeAnimation && Style.closeStyle.isNotEmpty() + GuiConfig.animations && GuiConfig.closeAnimation && GuiConfig.closeStyle.isNotEmpty() if (screen == Screen.ClickGui && animated) { if (shownPresence < 1f) skipTo(1f) leaving = true @@ -170,7 +170,7 @@ object LambdaGui : Loadable { } private fun skipTo(end: Float) { - if (Style.interruptedAnimation != GuiInterrupt.Finish) return + if (GuiConfig.interruptedAnimation != GuiInterrupt.Finish) return jumpTo(end) restarts++ } @@ -189,7 +189,7 @@ object LambdaGui : Loadable { if (!GuiScreen.canOpenOver(mc.currentScreen)) return if (leaving) skipTo(0f) else jumpTo(0f) - if (Client.clientSounds) LambdaSound.ModuleOn.play() + if (ClientConfig.clientSounds) LambdaSound.ModuleOn.play() GuiScreen.show() AutoUpdater.onGuiOpened() } @@ -204,7 +204,7 @@ object LambdaGui : Loadable { internal fun onScreenRemoved() { if (screen == null) return - if (Client.clientSounds) LambdaSound.ModuleOff.play() + if (ClientConfig.clientSounds) LambdaSound.ModuleOff.play() screen = null if (!leaving) jumpTo(0f) settled = false @@ -216,7 +216,7 @@ object LambdaGui : Loadable { 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 + val density = size.height / REFERENCE_HEIGHT * GuiConfig.scale if (!warmedUp) { warmedUp = true @@ -331,7 +331,7 @@ object LambdaGui : Loadable { shown = showsClickGui || warmingUp, clickGuiObservations ) { - ClickGui() + CompositionLocalProvider(LocalPresence provides ::presence) { ClickGui() } } aboveGui.Content() if (warmingUp) WarmUp() @@ -362,7 +362,7 @@ object LambdaGui : Loadable { if (present) 1f else 0f val animated = - if (present) Style.openAnimation && Style.openStyle.isNotEmpty() + if (present) GuiConfig.openAnimation && GuiConfig.openStyle.isNotEmpty() else leaving if (animated) { val spec = Motion.gui(abs(target - shownPresence)) @@ -377,7 +377,7 @@ object LambdaGui : Loadable { @Composable private fun WarmUp() { - SettingsList(Style.settingLayers) + SettingsList(GuiConfig.settingLayers) } private fun effects(density: Float): GuiCompositor.Effects { @@ -387,16 +387,16 @@ object LambdaGui : Loadable { else 1f return GuiCompositor.Effects( frost = - if (Style.blur) Style.blurRadius * density * strength + if (GuiConfig.blur) GuiConfig.blurRadius * density * strength else 0f, glow = - if (Style.glow && showsClickGui) Style.glowRadius * density + if (GuiConfig.glow && showsClickGui) GuiConfig.glowRadius * density else 0f, - glowIntensity = Style.glowIntensity * strength, - glowColorA = Style.glowColorA, - glowColorB = Style.glowColorB, + glowIntensity = GuiConfig.glowIntensity * strength, + glowColorA = GuiConfig.glowColorA, + glowColorB = GuiConfig.glowColorB, dim = - if (Style.dimBackground && showsClickGui) Style.dimStrength * presence + if (GuiConfig.dimBackground && showsClickGui) GuiConfig.dimStrength * presence else 0f, ) } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index 3a60767b1..da61a2e42 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -33,7 +33,6 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect -import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput @@ -50,6 +49,7 @@ import com.lambda.gui.Reveal import com.lambda.gui.Snap import com.lambda.gui.Snap.snapLines import com.lambda.gui.component.Button +import com.lambda.gui.component.guiPresence import com.lambda.gui.component.mouseClickable import com.lambda.gui.core.LocalShown import com.lambda.gui.core.observe @@ -58,15 +58,11 @@ import com.lambda.gui.menu.ConfigDialog import com.lambda.gui.menu.LoaderPromptDialog import com.lambda.gui.menu.MenuBar import com.lambda.gui.menu.NewAutomationConfigDialog -import com.lambda.gui.theme.GuiTransition import com.lambda.gui.theme.Look import com.lambda.module.HudModule import com.lambda.module.ModuleTag import com.lambda.module.modules.client.AutoUpdater -import com.lambda.module.modules.client.Style -private val SLIDE = 24.dp -private const val ZOOM = 0.92f internal val CLICK_GUI_CATEGORIES = ModuleTag.defaults - ModuleTag.HUD @@ -96,7 +92,7 @@ internal fun ClickGui() { } val settings = remember { OpenSettings() } - val inline by observe { Style.inlineSettings } + val inline by observe { GuiConfig.inlineSettings } val revealedModule = Reveal.module val revealedSetting = Reveal.setting @@ -139,18 +135,7 @@ internal fun ClickGui() { onClick = settings::closeAll ).snapLines { drop - }.graphicsLayer { - val presence = LambdaGui.presence - val styles = LambdaGui.transitions - if (GuiTransition.Fade in styles) alpha = presence - if (GuiTransition.Slide in styles) { - translationY = (presence - 1f) * SLIDE.toPx() - } - if (GuiTransition.Zoom in styles) { - scaleX = ZOOM + (1f - ZOOM) * presence - scaleY = scaleX - } - } + }.guiPresence() ) { val inRow = tags.count { it != ModuleTag.DEBUG } val screenWidth = with(density) { screen.width.toDp() } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt index 79a51a955..a049b2fe4 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt @@ -24,9 +24,9 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.geometry.Rect import androidx.compose.ui.unit.dp +import com.lambda.gui.GuiConfig import com.lambda.gui.settings.PanelPage import com.lambda.module.Module -import com.lambda.module.modules.client.Style internal class SettingsPanelState(val module: Module) { var page by mutableStateOf(PanelPage.Settings) @@ -52,7 +52,7 @@ internal class OpenSettings { fun isOpen(module: Module) = module in open fun open(module: Module) { - if (!Style.multipleSettings) closeAll() + if (!GuiConfig.multipleSettings) closeAll() closing -= module if (module !in open) open += module } diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 911f4956d..a373a53e8 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -25,6 +25,9 @@ import androidx.compose.animation.expandVertically import androidx.compose.animation.shrinkOut import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.background +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column @@ -62,6 +65,7 @@ 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.TransformOrigin import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.input.key.Key @@ -89,15 +93,17 @@ 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.GuiConfig +import com.lambda.gui.LambdaGui import com.lambda.gui.core.GameClipboard import com.lambda.gui.core.LocalShown import com.lambda.gui.core.Press import com.lambda.gui.core.awaitFrames +import com.lambda.gui.core.observe import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look import com.lambda.gui.theme.Motion import com.lambda.gui.theme.Type -import com.lambda.module.modules.client.Style import kotlin.math.max @OptIn(ExperimentalComposeUiApi::class) @@ -146,6 +152,10 @@ class MenuState { fun toggle() { if (dismissedBy != Press.id) isOpen = true } + + fun open() { + isOpen = true + } } @Composable @@ -235,6 +245,8 @@ private val LocalMenuDismiss = staticCompositionLocalOf<(() -> Unit)?> { null } private val LocalMenuOpen = compositionLocalOf { true } +private val LocalMenuHovered = compositionLocalOf { false } + @Composable private fun MenuPopup( open: Boolean, @@ -247,6 +259,8 @@ private fun MenuPopup( val open = open && LocalMenuOpen.current val dismissAll = LocalMenuDismiss.current ?: onDismiss val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() val shape = when { !attached -> RoundedCornerShape(Look.menuRounding) @@ -254,9 +268,14 @@ private fun MenuPopup( else -> RoundedCornerShape(bottomStart = Look.menuRounding, bottomEnd = Look.menuRounding) } FloatingPanel(open, position, onDismiss, shape, unfoldFrom) { panel -> - CompositionLocalProvider(LocalMenuDismiss provides dismissAll, LocalMenuOpen provides open) { + CompositionLocalProvider( + LocalMenuDismiss provides dismissAll, + LocalMenuOpen provides open, + LocalMenuHovered provides hovered + ) { ScrollColumn( modifier = Modifier + .hoverable(interactions) .heightIn(max = screenHeight) .width(IntrinsicSize.Max) .widthIn(min = maxOf(80.dp, with(LocalDensity.current) { unfoldFrom.width.toDp() })) @@ -331,14 +350,15 @@ private fun FloatingPanel( if (open) SideEffect(onDismiss) return } + val folding = LambdaGui.foldsClosed val visibility = remember { MutableTransitionState(false) } - visibility.targetState = open + visibility.targetState = open && !folding if (!open && visibility.isIdle && !visibility.currentState) return val host = LocalPopupHost.current if (host != null && host.closing && open) SideEffect(onDismiss) val own = remember { PopupHost() } - SideEffect { own.closing = !open } + SideEffect { own.closing = !open || folding } val colors = LambdaTheme.colors ScenePopup( @@ -354,10 +374,16 @@ private fun FloatingPanel( modifier = Modifier .swallowedBy(host) .onGloballyPositioned { own.place(it.boundsInWindow()) } + .guiPresence(position.anchor) .dropShadow(shape, close = true) .window(colors.panel, colors.border, shape), enter = expandIn(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, - exit = shrinkOut(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, + exit = + shrinkOut( + if (folding) Motion.guiFold + else Motion.panels, + position.corner + ) { it.coerceAtMost(unfoldFrom) }, ) { CompositionLocalProvider(LocalPopupHost provides own) { content(Modifier.onSizeChanged { position.unfolded = it }) @@ -377,6 +403,13 @@ private class UnfoldingPosition( var upwards by mutableStateOf(false) private set + val anchor + get() = + TransformOrigin( + if (leftwards) 1f else 0f, + if (upwards) 1f else 0f + ) + val corner get() = when { @@ -411,6 +444,8 @@ private class UnfoldingPosition( } } +private val SUGGESTIONS_ANCHOR = TransformOrigin(0.5f, 0f) + @Composable fun Suggestions( open: Boolean, @@ -421,8 +456,9 @@ fun Suggestions( if (open) SideEffect(onDismiss) return } + val folding = LambdaGui.foldsClosed val visibility = remember { MutableTransitionState(false) } - visibility.targetState = open + visibility.targetState = open && !folding if (!open && visibility.isIdle && !visibility.currentState) return val colors = LambdaTheme.colors @@ -446,10 +482,16 @@ fun Suggestions( AnimatedVisibility( visibleState = visibility, modifier = Modifier + .guiPresence(SUGGESTIONS_ANCHOR) .dropShadow(shape) .window(colors.panel, colors.border, shape), enter = expandVertically(Motion.panels, Alignment.Top), - exit = shrinkVertically(Motion.panels, Alignment.Top), + exit = + shrinkVertically( + if (folding) Motion.guiFold + else Motion.panels, + Alignment.Top + ), ) { ScrollColumn( modifier = Modifier @@ -515,20 +557,29 @@ fun Submenu( content: @Composable ColumnScope.() -> Unit ) { val colors = LambdaTheme.colors + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() + val menuHovered = LocalMenuHovered.current val menu = remember { MenuState() } + val onHover by observe { GuiConfig.hoverSubmenus } + LaunchedEffect(hovered, menuHovered, onHover) { + when { + !onHover -> Unit + hovered -> menu.open() + menuHovered -> menu.dismiss() + } + } Box { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() - .then( - if (enabled) { - Modifier - .hoverHighlight(colors.controlSelected) - .mouseClickable(onClick = menu::toggle) - } - else Modifier - ) + .hoverable(interactions, enabled) + .background(if (hovered || menu.isOpen) colors.controlSelected else Color.Transparent) + .mouseClickable(enabled) { + if (onHover) menu.open() + else menu.toggle() + } .padding(horizontal = 5.dp, vertical = 1.dp) ) { Text( @@ -646,7 +697,7 @@ fun Tooltip( var bounds by remember { mutableStateOf(Rect.Zero) } LaunchedEffect(hovered) { if (!hovered) return@LaunchedEffect - awaitFrames(Style.tooltipDelay.toLong()) + awaitFrames(GuiConfig.tooltipDelay.toLong()) visible = true } diff --git a/src/main/kotlin/com/lambda/gui/component/Scroll.kt b/src/main/kotlin/com/lambda/gui/component/Scroll.kt index 784bf7c3a..f0086104b 100644 --- a/src/main/kotlin/com/lambda/gui/component/Scroll.kt +++ b/src/main/kotlin/com/lambda/gui/component/Scroll.kt @@ -45,9 +45,9 @@ import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp +import com.lambda.gui.GuiConfig import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Motion -import com.lambda.module.modules.client.Style import kotlinx.coroutines.Job import kotlinx.coroutines.launch @@ -97,7 +97,7 @@ fun Modifier.wheelScrollable(state: ScrollableState): Modifier = val event = awaitPointerEvent(PointerEventPass.Initial) if (event.type != PointerEventType.Scroll) continue val change = event.changes.first() - val distance = change.scrollDelta.y * notch * Style.scrollSpeed + val distance = change.scrollDelta.y * notch * GuiConfig.scrollSpeed val canFollow = if (distance > 0) state.canScrollForward else state.canScrollBackward diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt index f619825ea..bb390e108 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -33,11 +33,13 @@ import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.TransformOrigin 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.graphicsLayer import androidx.compose.ui.graphics.skiaCanvas import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalDensity @@ -45,6 +47,9 @@ import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp +import com.lambda.gui.LambdaGui +import com.lambda.gui.core.LocalPresence +import com.lambda.gui.theme.GuiTransition import com.lambda.gui.theme.Look import org.jetbrains.skia.Canvas import org.jetbrains.skia.ColorFilter @@ -80,6 +85,25 @@ private val DRAWN = private val REPLACE = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC } private val WITHIN = Paint().apply { blendMode = org.jetbrains.skia.BlendMode.SRC_IN } +private val GUI_SLIDE = 24.dp +private const val GUI_ZOOM = 0.92f + +fun Modifier.guiPresence(anchor: TransformOrigin? = null): Modifier = + composed { + val presence = LocalPresence.current + graphicsLayer { + val shown = presence() + val styles = LambdaGui.transitions + if (GuiTransition.Fade in styles) alpha = shown + if (GuiTransition.Slide in styles && anchor == null) translationY = (shown - 1f) * GUI_SLIDE.toPx() + if (GuiTransition.Zoom in styles) { + scaleX = GUI_ZOOM + (1f - GUI_ZOOM) * shown + scaleY = scaleX + transformOrigin = anchor ?: TransformOrigin.Center + } + } + } + fun Modifier.glass(color: Color, shape: Shape): Modifier = clip(shape).composed { val sigma = with(LocalDensity.current) { Look.backdropBlur.toPx() } diff --git a/src/main/kotlin/com/lambda/gui/core/Retained.kt b/src/main/kotlin/com/lambda/gui/core/Retained.kt index b6f37f4e7..494bd2211 100644 --- a/src/main/kotlin/com/lambda/gui/core/Retained.kt +++ b/src/main/kotlin/com/lambda/gui/core/Retained.kt @@ -21,11 +21,14 @@ import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Modifier import androidx.compose.ui.layout.layout val LocalShown = compositionLocalOf { true } +val LocalPresence = staticCompositionLocalOf<() -> Float> { { 1f } } + @Composable internal fun Retained( shown: Boolean, diff --git a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt index c1419279f..598852fea 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -50,6 +50,7 @@ import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput import com.lambda.gui.component.rememberTexture import com.lambda.gui.core.LocalShown +import com.lambda.gui.core.observe import com.lambda.gui.settings.ConfigSettings import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Type @@ -103,8 +104,8 @@ internal fun NewAutomationConfigDialog(onDismiss: () -> Unit) { @Composable internal fun AboutDialog(onDismiss: () -> Unit) { val colors = LambdaTheme.colors - val facts = - remember { + val facts by + observe { val settings = ConfigLoader.configCategories.sumOf { category -> category.configs.sumOf { config -> diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index 3cf0067d7..7d025324e 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -63,10 +63,12 @@ import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import com.lambda.Lambda.REPO_URL import com.lambda.Lambda.mc +import com.lambda.config.ClientConfig 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.config.settings.complex.Bind import com.lambda.gui.GuiConfig import com.lambda.gui.LambdaGui import com.lambda.gui.clickgui.CLICK_GUI_CATEGORIES @@ -333,22 +335,12 @@ private fun LambdaMenu() { } } 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() } - } + MenuItem("Client Settings...") { ClickGuiState.dialog = ClickGuiDialog.Settings(ClientConfig) } + 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() Submenu("Open Folder") { FolderItem("Lambda Folder", FolderRegistry.lambda) FolderItem("Config Folder", FolderRegistry.config) @@ -361,11 +353,16 @@ private fun LambdaMenu() { } MenuDivider() MenuItem("About...") { ClickGuiState.dialog = ClickGuiDialog.About } + MenuDivider() MenuItem("Developer Mode", checked = ClickGuiState.developerMode) { ClickGuiState.developerMode = !ClickGuiState.developerMode } MenuDivider() - MenuItem("Close GUI", hint = "Esc") { LambdaGui.back() } + val keybind by observe { GuiConfig.keybind } + val closeKeys = + if (keybind == Bind.EMPTY) "Esc" + else "Esc/${keybind.name}" + MenuItem("Close GUI", hint = closeKeys) { LambdaGui.back() } MenuItem("Exit Client") { mc.scheduleStop() } } diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index 3cdb687f2..ad8f7b97f 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -48,10 +48,10 @@ import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import com.lambda.gui.GuiConfig import com.lambda.gui.core.Observation import com.lambda.gui.core.Observations import com.lambda.gui.core.observe -import com.lambda.module.modules.client.Style import com.lambda.util.NamedEnum import com.lambda.util.stream import kotlin.math.roundToInt @@ -97,30 +97,30 @@ data class Palette( internal object Look { private val observations = Observations() - val windowRounding by style { Style.windowRounding.dp } - val panelRounding by style { Style.panelRounding.dp } - val menuRounding by style { Style.menuRounding.dp } - val controlRounding by style { Style.controlRounding.dp } + val windowRounding by style { GuiConfig.windowRounding.dp } + val panelRounding by style { GuiConfig.panelRounding.dp } + val menuRounding by style { GuiConfig.menuRounding.dp } + val controlRounding by style { GuiConfig.controlRounding.dp } val boxRounding get() = controlRounding / 2 - val outlines by style { Style.outlines } - val outlineWidth by style { Style.outlineWidth.dp } - val shadows by style { Style.shadows } - val emboss by style { Style.emboss } - val backdropBlur by style { if (Style.blur) (Style.blurRadius / 2f).dp else 0.dp } - val underlay by style { 1f - Style.layerFade } + val outlines by style { GuiConfig.outlines } + val outlineWidth by style { GuiConfig.outlineWidth.dp } + val shadows by style { GuiConfig.shadows } + val emboss by style { GuiConfig.emboss } + val backdropBlur by style { if (GuiConfig.blur) (GuiConfig.blurRadius / 2f).dp else 0.dp } + val underlay by style { 1f - GuiConfig.layerFade } - val rowHeight by style { Style.elementHeight.dp } - val windowWidth by style { Style.windowWidth.dp } - val settingsWidth by style { Style.settingsWidth.dp } - val notificationScale by style { Style.notificationScale } - val notificationWidth by style { Style.notificationWidth.dp } - val windowGap by style { Style.windowGap.dp } - val windowTop by style { Style.windowTop.dp } - val modulePadding by style { Style.modulePadding.dp } - val panelPadding by style { Style.panelPadding.dp } - val settingSpacing by style { Style.settingSpacing.dp } - val groupIndent by style { Style.groupIndent.dp } + val rowHeight by style { GuiConfig.elementHeight.dp } + val windowWidth by style { GuiConfig.windowWidth.dp } + val settingsWidth by style { GuiConfig.settingsWidth.dp } + val notificationScale by style { GuiConfig.notificationScale } + val notificationWidth by style { GuiConfig.notificationWidth.dp } + val windowGap by style { GuiConfig.windowGap.dp } + val windowTop by style { GuiConfig.windowTop.dp } + val modulePadding by style { GuiConfig.modulePadding.dp } + val panelPadding by style { GuiConfig.panelPadding.dp } + val settingSpacing by style { GuiConfig.settingSpacing.dp } + val groupIndent by style { GuiConfig.groupIndent.dp } fun refresh() = observations.refresh() @@ -141,7 +141,7 @@ internal object Motion : MotionDurationScale { val SCROLL = object : MotionDurationScale { override val scaleFactor get() = - if (Style.smoothScrolling) 1f + if (GuiConfig.smoothScrolling) 1f else 0f } @@ -153,15 +153,15 @@ internal object Motion : MotionDurationScale { } override val scaleFactor get() = - if (Style.animations) 1f / Style.animationSpeed + if (GuiConfig.animations) 1f / GuiConfig.animationSpeed else 0f val windows: FiniteAnimationSpec - get() = if (Style.windowAnimations) spring() else snap() + get() = if (GuiConfig.windowAnimations) spring() else snap() val panels: FiniteAnimationSpec - get() = if (Style.panelAnimations) UNFOLDING else snap() + get() = if (GuiConfig.panelAnimations) UNFOLDING else snap() val pageMillis - get() = if (Style.pageAnimations) PAGE_MILLIS else 0 + get() = if (GuiConfig.pageAnimations) PAGE_MILLIS else 0 fun gui(distance: Float): FiniteAnimationSpec = tween((GUI_MILLIS * distance).roundToInt()) val guiFold: FiniteAnimationSpec @@ -249,9 +249,9 @@ val LocalContentColor = compositionLocalOf { Color.White } @Composable fun LambdaTheme(content: @Composable () -> Unit) { - val palette by observe { Style.palette } - val font by observe { Style.font } - val fontSize by observe { Style.fontSize } + val palette by observe { GuiConfig.palette } + val font by observe { GuiConfig.font } + val fontSize by observe { GuiConfig.fontSize } val measurer = rememberTextMeasurer() val typography = remember(font, fontSize) { diff --git a/src/main/kotlin/com/lambda/interaction/handler/handlers/InteractedBlockHandler.kt b/src/main/kotlin/com/lambda/interaction/handler/handlers/InteractedBlockHandler.kt index 829ce02ed..3340c4cae 100644 --- a/src/main/kotlin/com/lambda/interaction/handler/handlers/InteractedBlockHandler.kt +++ b/src/main/kotlin/com/lambda/interaction/handler/handlers/InteractedBlockHandler.kt @@ -17,6 +17,7 @@ package com.lambda.interaction.handler.handlers +import com.lambda.config.ClientConfig import com.lambda.config.automation.AutomationConfig import com.lambda.config.blocks.InteractConfig import com.lambda.event.events.WorldEvent @@ -24,7 +25,6 @@ import com.lambda.event.listener.SafeListener.Companion.listen import com.lambda.interaction.handler.PostActionHandler import com.lambda.interaction.manager.managers.interacting.InteractInfo import com.lambda.interaction.manager.managers.interacting.InteractManager.placeSound -import com.lambda.module.modules.client.Client import com.lambda.threading.runSafe import com.lambda.util.BlockUtils.matches import com.lambda.util.CommunicationUtils.warn @@ -35,7 +35,7 @@ internal object InteractedBlockHandler : PostActionHandler() { AutomationConfig.Companion.DEFAULT.buildConfig.maxPendingActions, AutomationConfig.Companion.DEFAULT.buildConfig.actionTimeout * 50L ) { - if (Client.verboseDebug) warn("${it::class.simpleName} at ${it.context.blockPos.toShortString()} timed out") + if (ClientConfig.verboseDebug) warn("${it::class.simpleName} at ${it.context.blockPos.toShortString()} timed out") if (it.interactConfig.interactConfirmationMode != InteractConfig.InteractConfirmationMode.AwaitThenPlace) { runSafe { world.setBlockState(it.context.blockPos, it.context.cachedState) @@ -57,7 +57,7 @@ internal object InteractedBlockHandler : PostActionHandler() { pending.stopPending() - if (Client.verboseDebug) this@InteractedBlockHandler.warn("Placed block at ${event.pos.toShortString()} was rejected with ${event.newState} instead of ${pending.context.expectedState}") + if (ClientConfig.verboseDebug) this@InteractedBlockHandler.warn("Placed block at ${event.pos.toShortString()} was rejected with ${event.newState} instead of ${pending.context.expectedState}") return@listen } diff --git a/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt index a467ec9f7..b5b748551 100644 --- a/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt +++ b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt @@ -25,9 +25,9 @@ import com.lambda.Lambda.mc import com.lambda.core.Loadable import com.lambda.event.events.ComposeEvent import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe +import com.lambda.gui.GuiConfig import com.lambda.gui.Notifications import com.lambda.gui.core.RenderThread -import com.lambda.module.modules.client.Style import java.awt.Color object NotificationHandler : Loadable { @@ -50,9 +50,9 @@ object NotificationHandler : Loadable { kept += notification if (kept.size > MAX_KEPT) kept.removeRange(0, kept.size - MAX_KEPT) kept.filterNot { it.dismissed } - .dropLast(Style.maxNotifications) + .dropLast(GuiConfig.maxNotifications) .forEach { it.dismissed = true } - RenderThread.after((Style.notificationSeconds * 1000).toLong()) { + RenderThread.after((GuiConfig.notificationSeconds * 1000).toLong()) { notification.dismissed = true } } diff --git a/src/main/kotlin/com/lambda/interaction/handler/handlers/breaking/BrokenBlockHandler.kt b/src/main/kotlin/com/lambda/interaction/handler/handlers/breaking/BrokenBlockHandler.kt index 25cbbeb7a..45b77b501 100644 --- a/src/main/kotlin/com/lambda/interaction/handler/handlers/breaking/BrokenBlockHandler.kt +++ b/src/main/kotlin/com/lambda/interaction/handler/handlers/breaking/BrokenBlockHandler.kt @@ -17,6 +17,8 @@ package com.lambda.interaction.handler.handlers.breaking +import com.lambda.config.ClientConfig +import com.lambda.config.ClientConfig.verboseDebug import com.lambda.config.automation.AutomationConfig.Companion.DEFAULT import com.lambda.config.blocks.BreakConfig.BreakConfirmationMode import com.lambda.context.SafeContext @@ -27,8 +29,6 @@ import com.lambda.interaction.construction.simulation.processing.ProcessorRegist import com.lambda.interaction.handler.PostActionHandler import com.lambda.interaction.manager.managers.breaking.BreakInfo import com.lambda.interaction.manager.managers.breaking.BreakManager.matchesBlockItem -import com.lambda.module.modules.client.Client -import com.lambda.module.modules.client.Client.verboseDebug import com.lambda.threading.runGameScheduled import com.lambda.threading.runSafe import com.lambda.util.BlockUtils.emptyState @@ -62,7 +62,7 @@ internal object BrokenBlockHandler : PostActionHandler() { if (!info.broken) { val message = "${info.type} ${info::class.simpleName} at ${info.context.blockPos.toShortString()} timed out with cached state ${info.context.cachedState}" if (verboseDebug) this@BrokenBlockHandler.warn(message) - } else if (!Client.ignoreItemDropWarnings) { + } else if (!ClientConfig.ignoreItemDropWarnings) { val message = "${info.type} ${info::class.simpleName}'s item drop at ${info.context.blockPos.toShortString()} timed out" if (verboseDebug) this@BrokenBlockHandler.warn(message) } diff --git a/src/main/kotlin/com/lambda/interaction/manager/managers/inventory/InventoryManager.kt b/src/main/kotlin/com/lambda/interaction/manager/managers/inventory/InventoryManager.kt index 952aab8bd..654a05647 100644 --- a/src/main/kotlin/com/lambda/interaction/manager/managers/inventory/InventoryManager.kt +++ b/src/main/kotlin/com/lambda/interaction/manager/managers/inventory/InventoryManager.kt @@ -18,6 +18,8 @@ package com.lambda.interaction.manager.managers.inventory import com.lambda.Lambda.LOG +import com.lambda.config.ClientConfig +import com.lambda.config.ClientConfig.verboseDebug import com.lambda.context.AutomatedSafeContext import com.lambda.context.SafeContext import com.lambda.event.EventFlow.post @@ -34,8 +36,6 @@ import com.lambda.interaction.manager.managers.inventory.InventoryManager.action import com.lambda.interaction.manager.managers.inventory.InventoryManager.activeRequest import com.lambda.interaction.manager.managers.inventory.InventoryManager.filter import com.lambda.interaction.manager.managers.inventory.InventoryManager.indexInventoryChanges -import com.lambda.module.modules.client.Client -import com.lambda.module.modules.client.Client.verboseDebug import com.lambda.threading.runSafe import com.lambda.threading.withSafeAutomated import com.llamalad7.mixinextras.injector.wrapoperation.Operation @@ -66,7 +66,7 @@ object InventoryManager : Manager(1) { InventorySyncFilter( { a, b -> ItemStack.areEqual(a, b) }, { it.copy() }, - Client.desyncTimeout * 50L + ClientConfig.desyncTimeout * 50L ) private var actionsThisTick = 0 @@ -75,14 +75,14 @@ object InventoryManager : Manager(1) { super.load() listen({ Int.MIN_VALUE }) { - if (Client.avoidInventoryDesync) indexInventoryChanges() + if (ClientConfig.avoidInventoryDesync) indexInventoryChanges() actionsThisTick = 0 activeRequest = null actions = mutableListOf() } listen { - if (Client.avoidInventoryDesync) indexInventoryChanges() + if (ClientConfig.avoidInventoryDesync) indexInventoryChanges() } listen { event -> @@ -139,7 +139,7 @@ object InventoryManager : Manager(1) { private fun populateFrom(request: InventoryRequest) { activeRequest = request actions = request.actions.toMutableList() - filter.maxAgeMs = Client.desyncTimeout * 50L + filter.maxAgeMs = ClientConfig.desyncTimeout * 50L } /** @@ -159,7 +159,7 @@ object InventoryManager : Manager(1) { action.action(this) if (action is InventoryAction.Player) sentPackets(1, PacketType.PlayerAction) else if (action is InventoryAction.Inventory) sentPackets(1, PacketType.Inventory) - if (Client.avoidInventoryDesync) indexInventoryChanges() + if (ClientConfig.avoidInventoryDesync) indexInventoryChanges() actionsThisTick++ iterator.remove() } @@ -235,7 +235,7 @@ object InventoryManager : Manager(1) { original.call(packet) return } - if (!mc.isOnThread || !Client.avoidInventoryDesync) { + if (!mc.isOnThread || !ClientConfig.avoidInventoryDesync) { original.call(packet) snapshotHandler(packetScreenHandler) return @@ -285,7 +285,7 @@ object InventoryManager : Manager(1) { runSafe { val stack = packet.contents() mc.tutorialManager.onSlotUpdate(stack) - if (!mc.isOnThread || !Client.avoidInventoryDesync) { + if (!mc.isOnThread || !ClientConfig.avoidInventoryDesync) { original.call(packet) snapshotHandler(player.currentScreenHandler) return @@ -320,7 +320,7 @@ object InventoryManager : Manager(1) { return } } - if (!mc.isOnThread || !Client.avoidInventoryDesync) { + if (!mc.isOnThread || !ClientConfig.avoidInventoryDesync) { original.call(packet) snapshotHandler(packetScreenHandler) return diff --git a/src/main/kotlin/com/lambda/module/Module.kt b/src/main/kotlin/com/lambda/module/Module.kt index 2f73164a5..0cc606c75 100644 --- a/src/main/kotlin/com/lambda/module/Module.kt +++ b/src/main/kotlin/com/lambda/module/Module.kt @@ -18,6 +18,7 @@ package com.lambda.module import com.lambda.command.LambdaCommand +import com.lambda.config.ClientConfig import com.lambda.config.Config import com.lambda.config.ConfigCategory import com.lambda.config.automation.IMutableAutomationConfig @@ -38,7 +39,6 @@ import com.lambda.event.listener.Listener import com.lambda.event.listener.SafeListener import com.lambda.event.listener.SafeListener.Companion.listen import com.lambda.event.listener.UnsafeListener -import com.lambda.module.modules.client.Client import com.lambda.sound.LambdaSound import com.lambda.sound.SoundHandler.play import com.lambda.util.KeyCode @@ -161,8 +161,8 @@ abstract class Module( get() = !isEnabled && !alwaysListening init { - onEnableUnsafe { if (Client.clientSounds) LambdaSound.ModuleOn.play() } - onDisableUnsafe { if (Client.clientSounds) LambdaSound.ModuleOff.play() } + onEnableUnsafe { if (ClientConfig.clientSounds) LambdaSound.ModuleOn.play() } + onDisableUnsafe { if (ClientConfig.clientSounds) LambdaSound.ModuleOff.play() } listen { if (autoDisable) disable() } listen { if (autoDisable) disable() } diff --git a/src/main/kotlin/com/lambda/module/modules/client/Client.kt b/src/main/kotlin/com/lambda/module/modules/client/Client.kt deleted file mode 100644 index 5c349d334..000000000 --- a/src/main/kotlin/com/lambda/module/modules/client/Client.kt +++ /dev/null @@ -1,60 +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.module.modules.client - -import com.lambda.config.Group -import com.lambda.config.Tab -import com.lambda.graphics.mc.renderer.TickedRenderer.Companion.tickedRenderer -import com.lambda.interaction.construction.simulation.result.Drawable -import com.lambda.module.Module -import com.lambda.module.ModuleTag -import java.awt.Color - -object Client : Module( - name = "Client", - description = "Global settings for Lambda", - tag = ModuleTag.CLIENT, - alwaysEnabled = true, -) { - private const val GENERAL_TAB = "General" - private const val DEBUG_TAB = "Debug" - - private const val RENDERING_GROUP = "Rendering" - - @Tab(GENERAL_TAB) val clientSounds by setting("Client Sounds", true, "Plays sounds when certain actions are performed with lambda. Toggling modules, for example") - @Tab(GENERAL_TAB) val buildTaskRenders by setting("Build Task Renders", false, "Displays renders from some build sim results generated from the build task") - @Tab(GENERAL_TAB) val avoidInventoryDesync by setting("Avoid Inventory Desync", true, "Cancels incoming inventory update packets if they match previous actions") - @Tab(GENERAL_TAB) val desyncTimeout by setting("Desync Timeout", 30, 1..30, 1, unit = " ticks", description = "Time to store previous inventory actions before dropping the cache") { avoidInventoryDesync } - @Tab(GENERAL_TAB) val scanShrinkFactor by setting("Scan Shrink Factor", 0.001, 0.0..1.0, 0.001, "How much to shrink block scans from the edges to avoid flagging anticheats") - @Tab(GENERAL_TAB) @Group(RENDERING_GROUP) val chunkUploadsPerTick by setting("Chunk Uploads", 16, 1..256, 1, unit = " chunks/tick") - @Tab(GENERAL_TAB) @Group(RENDERING_GROUP) val chunkRebuildsPerTick by setting("Chunk Rebuilds", 64, 1..256, 1, unit = " chunks/tick") - @Tab(GENERAL_TAB) val highlightColor by setting("Text Highlight Color", Color(214, 55, 87), "Base text highlight color") - - @Tab(DEBUG_TAB) val ignoreItemDropWarnings by setting("Ignore Drop Warnings", false, "Hides the item drop warnings from the break manager") - @Tab(DEBUG_TAB) val verboseDebug by setting("Verbose Debug", false, "Prints more, and more detailed, debug logs") - @Tab(DEBUG_TAB) val showInvisibleTasks by setting("Show Invisible Tasks", false, "Shows utility tasks such as chaining wrappers in the Task Flow HUD") - - @Volatile - var drawables = listOf() - - init { - tickedRenderer("Client Ticked Renderer") { - if (buildTaskRenders) drawables.forEach { with(it) { render() } } - } - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/module/modules/client/Style.kt b/src/main/kotlin/com/lambda/module/modules/client/Style.kt deleted file mode 100644 index 292b0dd21..000000000 --- a/src/main/kotlin/com/lambda/module/modules/client/Style.kt +++ /dev/null @@ -1,259 +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.module.modules.client - -import com.lambda.config.Config -import com.lambda.config.ConfigBlock -import com.lambda.config.Group -import com.lambda.config.settings.appliedOnRelease -import com.lambda.gui.theme.GuiFont -import com.lambda.gui.theme.GuiInterrupt -import com.lambda.gui.theme.GuiTransition -import com.lambda.gui.theme.Palette -import com.lambda.module.Module -import com.lambda.module.ModuleTag -import com.lambda.util.NamedEnum -import com.lambda.util.math.toCompose -import org.jetbrains.skiko.SystemTheme -import org.jetbrains.skiko.currentSystemTheme -import java.awt.Color - -object Style : Module( - name = "Style", - description = "How Lambda's interface looks", - tag = ModuleTag.CLIENT, - alwaysEnabled = true, -) { - private const val BACKDROP_GROUP = "Backdrop" - private const val SHAPE_GROUP = "Shape" - private const val LAYOUT_GROUP = "Layout" - private const val MOTION_GROUP = "Motion" - private const val NOTIFICATIONS_GROUP = "Notifications" - private const val DARK_THEME_GROUP = "Dark Theme" - private const val LIGHT_THEME_GROUP = "Light Theme" - - private enum class ThemeMode(override val displayName: String) : NamedEnum { - Auto("Auto"), - Dark("Dark"), - Light("Light"), - } - - private val themeMode by setting("Theme", ThemeMode.Dark, "Auto follows the theme of your operating system") - val font by setting("Font", GuiFont.Minecraft, "The Minecraft font is sharpest where the interface is a whole number of times its natural size: at 1080p and 2160p with a scale of 1") - val fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") - val scale by setting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() - - @Group(BACKDROP_GROUP) val dimBackground by setting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") - @Group(BACKDROP_GROUP) val dimStrength by setting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } - @Group(BACKDROP_GROUP) val blur by setting("Blur", true, "Blurs what is behind windows for a frosted glass look") - @Group(BACKDROP_GROUP) val blurRadius by setting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } - @Group(BACKDROP_GROUP) val layerFade by setting("Layer Fade", 0.5f, 0f..1f, 0.05f, "How far the interface fades out underneath a panel, menu or window opened over it, letting the game show there instead so the two do not run together") { blur } - @Group(BACKDROP_GROUP) val glow by setting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") - @Group(BACKDROP_GROUP) val glowRadius by setting("Glow Radius", 17f, 1f..100f, 1f) { glow } - @Group(BACKDROP_GROUP) val glowIntensity by setting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } - - @Group(SHAPE_GROUP) val windowRounding by setting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") - @Group(SHAPE_GROUP) val panelRounding by setting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") - @Group(SHAPE_GROUP) val menuRounding by setting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") - @Group(SHAPE_GROUP) val controlRounding by setting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") - @Group(SHAPE_GROUP) val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") - @Group(SHAPE_GROUP) val outlineWidth by setting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } - @Group(SHAPE_GROUP) val shadows by setting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") - @Group(SHAPE_GROUP) val emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") - - @Group(LAYOUT_GROUP) val elementHeight by setting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") - @Group(LAYOUT_GROUP) val windowWidth by setting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") - @Group(LAYOUT_GROUP) val settingsWidth by setting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") - @Group(LAYOUT_GROUP) val windowGap by setting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") - @Group(LAYOUT_GROUP) val windowTop by setting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") - @Group(LAYOUT_GROUP) val modulePadding by setting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") - @Group(LAYOUT_GROUP) val panelPadding by setting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") - @Group(LAYOUT_GROUP) val settingSpacing by setting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") - @Group(LAYOUT_GROUP) val groupIndent by setting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") - @Group(LAYOUT_GROUP) val inlineSettings by setting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") - @Group(LAYOUT_GROUP) val multipleSettings by setting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") - - @Group(MOTION_GROUP) val animations by setting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") - @Group(MOTION_GROUP) val animationSpeed by setting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } - @Group(MOTION_GROUP) val openAnimation by setting("Open Animation", true, "Animates the click GUI in when it opens") { animations } - @Group(MOTION_GROUP) val openStyle by setting("Open Style", setOf(GuiTransition.Unfold), GuiTransition.entries.toSet(), "What the click GUI does as it comes in, any of them together: its windows unfold out of their headers, and all of it fades, slides down or zooms in") { animations && openAnimation } - @Group(MOTION_GROUP) val closeAnimation by setting("Close Animation", true, "Animates the click GUI out when it closes. The game has the mouse and keyboard back at once: the animation only plays over it") { animations } - @Group(MOTION_GROUP) val closeStyle by setting("Close Style", setOf(GuiTransition.Unfold, GuiTransition.Fade), GuiTransition.entries.toSet(), "What the click GUI does as it goes out, any of them together: its windows fold into their headers, and all of it fades, slides up or zooms out") { animations && closeAnimation } - @Group(MOTION_GROUP) val interruptedAnimation by setting("Interrupted Animation", GuiInterrupt.Reverse, "What happens when the click GUI is opened or closed again before its animation is done: it turns around from where it is, or skips to the end and plays the other one in full") { animations && (openAnimation || closeAnimation) } - @Group(MOTION_GROUP) val windowAnimations by setting("Window Animations", true, "Category windows unfold out of their headers") { animations } - @Group(MOTION_GROUP) val panelAnimations by setting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } - @Group(MOTION_GROUP) val pageAnimations by setting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } - @Group(MOTION_GROUP) val smoothScrolling by setting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") - @Group(MOTION_GROUP) val scrollSpeed by setting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") - @Group(MOTION_GROUP) val tooltipDelay by setting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") - - @Group(NOTIFICATIONS_GROUP) val notificationScale by setting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface") - @Group(NOTIFICATIONS_GROUP) val notificationWidth by setting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines") - @Group(NOTIFICATIONS_GROUP) val notificationSeconds by setting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it slides away") - @Group(NOTIFICATIONS_GROUP) val maxNotifications by setting("Max Notifications", 5, 1..12, 1, "How many notifications stack before the oldest slides off the bottom of the screen") - - @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( - PaletteSettings( - this, - primary = Color(214, 77, 113), - secondary = Color(255, 141, 128), - surface = Color(69, 48, 55, 165), - panel = Color(55, 38, 45, 200), - inset = Color(0, 0, 0, 190), - onSurface = Color(246, 236, 239), - onSurfaceVariant = Color(184, 156, 166), - header = Color(222, 53, 101), - onHeader = Color(255, 246, 248), - moduleEnabled = Color(161, 42, 75), - onModuleEnabled = Color(255, 240, 244), - control = Color(214, 77, 113), - controlSelected = Color(92, 64, 75), - onControl = Color(246, 236, 239), - track = Color(38, 28, 32, 230), - input = Color(32, 23, 26, 230), - border = Color(128, 92, 104, 235), - textShadow = Color(0, 0, 0, 150), - glowA = Color(222, 53, 101), - glowB = Color(255, 141, 128), - ) - ) - - @Group(LIGHT_THEME_GROUP) private val lightTheme by configBlock( - PaletteSettings( - this, - primary = Color(222, 53, 101), - secondary = Color(209, 74, 59), - surface = Color(250, 236, 241, 228), - panel = Color(244, 226, 232, 240), - inset = Color(120, 0, 40, 68), - onSurface = Color(61, 40, 47), - onSurfaceVariant = Color(110, 86, 95), - header = Color(222, 53, 101), - onHeader = Color(255, 250, 251), - moduleEnabled = Color(232, 84, 126), - onModuleEnabled = Color(255, 250, 251), - control = Color(240, 139, 166), - controlSelected = Color(224, 197, 206), - onControl = Color(61, 40, 47), - track = Color(209, 192, 199, 220), - input = Color(255, 250, 252, 210), - border = Color(184, 154, 164, 238), - textShadow = Color(0, 0, 0, 0), - glowA = Color(222, 53, 101), - glowB = Color(255, 141, 128), - ) - ) - - private val theme: PaletteSettings - get() = - when (themeMode) { - ThemeMode.Dark -> darkTheme - ThemeMode.Light -> lightTheme - ThemeMode.Auto -> - if (SystemAppearance.isDark) darkTheme - else lightTheme - } - - val palette: Palette get() = theme.toPalette() - val glowColorA: Color get() = theme.glowA - val glowColorB: Color get() = theme.glowB - - private object SystemAppearance { - private const val REFRESH_MILLIS = 1000L - - private var checkedAt = 0L - private var dark = true - - val isDark: Boolean - get() { - val now = System.currentTimeMillis() - if (now - checkedAt > REFRESH_MILLIS) { - checkedAt = now - dark = currentSystemTheme != SystemTheme.LIGHT - } - return dark - } - } -} - -class PaletteSettings( - override val c: Config, - primary: Color, - secondary: Color, - surface: Color, - panel: Color, - inset: Color, - onSurface: Color, - onSurfaceVariant: Color, - header: Color, - onHeader: Color, - moduleEnabled: Color, - onModuleEnabled: Color, - control: Color, - controlSelected: Color, - onControl: Color, - track: Color, - input: Color, - border: Color, - textShadow: Color, - glowA: Color, - glowB: Color, -) : ConfigBlock { - private val primary by c.setting("Primary", primary, "Accent colour: the fill of sliders and ticked boxes") - private val secondary by c.setting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") - private val surface by c.setting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") - private val panel by c.setting("Panel", panel, "Fill of settings panels, menus and dialogs") - private val inset by c.setting("Inset", inset, "Shade behind settings that open under their module, and over the module whose settings are open beside it") - private val onSurface by c.setting("On Surface", onSurface, "Text on windows") - private val onSurfaceVariant by c.setting("On Surface Variant", onSurfaceVariant, "Subdued text on windows") - private val header by c.setting("Header", header) - private val onHeader by c.setting("On Header", onHeader) - private val moduleEnabled by c.setting("Module Enabled", moduleEnabled) - private val onModuleEnabled by c.setting("On Module Enabled", onModuleEnabled) - private val control by c.setting("Control", control, "Fill of dropdowns, buttons and key caps") - private val controlSelected by c.setting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") - private val onControl by c.setting("On Control", onControl) - private val track by c.setting("Slider Track", track) - private val input by c.setting("Text Field", input) - private val border by c.setting("Border", border) - private val textShadow by c.setting("Text Shadow", textShadow) - val glowA by c.setting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { Style.glow } - val glowB by c.setting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { Style.glow } - - fun toPalette() = - Palette( - primary = primary.toCompose(), - secondary = secondary.toCompose(), - surface = surface.toCompose(), - panel = panel.toCompose(), - inset = inset.toCompose(), - onSurface = onSurface.toCompose(), - onSurfaceVariant = onSurfaceVariant.toCompose(), - header = header.toCompose(), - onHeader = onHeader.toCompose(), - moduleEnabled = moduleEnabled.toCompose(), - onModuleEnabled = onModuleEnabled.toCompose(), - control = control.toCompose(), - controlSelected = controlSelected.toCompose(), - onControl = onControl.toCompose(), - track = track.toCompose(), - input = input.toCompose(), - border = border.toCompose(), - textShadow = textShadow.toCompose(), - ) -} diff --git a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt index 66129f462..bfa845843 100644 --- a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt +++ b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/AutoDisconnect.kt @@ -25,10 +25,10 @@ import com.lambda.event.events.PlayerEvent import com.lambda.event.events.TickEvent import com.lambda.event.events.WorldEvent import com.lambda.event.listener.SafeListener.Companion.listen +import com.lambda.gui.GuiConfig import com.lambda.interaction.handler.handlers.FriendHandler import com.lambda.module.Module import com.lambda.module.ModuleTag -import com.lambda.module.modules.client.Style import com.lambda.module.modules.network.AutoReconnect import com.lambda.sound.SoundHandler.playSound import com.lambda.util.CommunicationUtils @@ -655,7 +655,7 @@ object AutoDisconnect : Module( buildText { text(effect.effectType.value().name) if (effect.amplifier > 0) literal(" ${effect.amplifier + 1}") - color(Style.palette.onSurfaceVariant.toAwt()) { + color(GuiConfig.palette.onSurfaceVariant.toAwt()) { literal(" (${effectDuration(effect)})") } } @@ -744,7 +744,7 @@ object AutoDisconnect : Module( val customName = stack.get(DataComponentTypes.CUSTOM_NAME) if (customName != null) { text(stack.itemName) - color(Style.palette.onSurfaceVariant.toAwt()) { + color(GuiConfig.palette.onSurfaceVariant.toAwt()) { literal(" (") text(customName) literal(")") @@ -754,13 +754,13 @@ object AutoDisconnect : Module( } if (stack.isDamageable) { - color(Style.palette.onSurfaceVariant.toAwt()) { + color(GuiConfig.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") } } if (stack.maxCount > 1) { - color(Style.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.count})") } + color(GuiConfig.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.count})") } } if (selected) { diff --git a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt index e9196fbff..7f47c3465 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 @@ -18,7 +18,7 @@ package com.lambda.module.modules.combat.autodisconnect import androidx.compose.ui.graphics.toArgb -import com.lambda.module.modules.client.Style +import com.lambda.gui.GuiConfig import com.lambda.util.text.buildText import com.lambda.util.text.highlighted import com.lambda.util.text.text @@ -268,10 +268,10 @@ class DisconnectDetailsWidget( const val HOVER_PADDING = 2 const val HOVER_RADIUS = 1 - val COLOR_TEXT get() = Style.palette.onSurface.toArgb() - val COLOR_BACKGROUND get() = Style.palette.panel.toArgb() - val COLOR_BORDER get() = Style.palette.border.toArgb() - val COLOR_HOVER_BACKGROUND get() = Style.palette.controlSelected.toArgb() + val COLOR_TEXT get() = GuiConfig.palette.onSurface.toArgb() + val COLOR_BACKGROUND get() = GuiConfig.palette.panel.toArgb() + val COLOR_BORDER get() = GuiConfig.palette.border.toArgb() + val COLOR_HOVER_BACKGROUND get() = GuiConfig.palette.controlSelected.toArgb() val COLOR_HEADER get() = COLOR_TEXT } } 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 108de9564..ce7dbea80 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/TaskFlowHud.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/TaskFlowHud.kt @@ -19,11 +19,11 @@ package com.lambda.module.modules.hud import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import com.lambda.config.ClientConfig 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 import com.lambda.task.RootTask @Suppress("unused") @@ -33,7 +33,7 @@ object TaskFlowHud : HudModule( ) { @Composable override fun Content() { - val tasks by observe { RootTask.taskTree(Client.showInvisibleTasks) } + val tasks by observe { RootTask.taskTree(ClientConfig.showInvisibleTasks) } HudText(tasks) } } diff --git a/src/main/kotlin/com/lambda/task/Task.kt b/src/main/kotlin/com/lambda/task/Task.kt index 9e8cc6bf7..865de6d32 100644 --- a/src/main/kotlin/com/lambda/task/Task.kt +++ b/src/main/kotlin/com/lambda/task/Task.kt @@ -19,12 +19,12 @@ package com.lambda.task +import com.lambda.config.ClientConfig.verboseDebug import com.lambda.context.SafeContext import com.lambda.event.EventFlow.unsubscribe import com.lambda.event.Muteable import com.lambda.event.events.TickEvent import com.lambda.event.listener.SafeListener.Companion.listen -import com.lambda.module.modules.client.Client.verboseDebug import com.lambda.task.tasks.wrappers.withRecovery import com.lambda.threading.runSafe import com.lambda.util.CommunicationUtils.logError diff --git a/src/main/kotlin/com/lambda/task/tasks/BuildTask.kt b/src/main/kotlin/com/lambda/task/tasks/BuildTask.kt index f9f5d6504..d842d822b 100644 --- a/src/main/kotlin/com/lambda/task/tasks/BuildTask.kt +++ b/src/main/kotlin/com/lambda/task/tasks/BuildTask.kt @@ -17,6 +17,7 @@ package com.lambda.task.tasks +import com.lambda.config.ClientConfig import com.lambda.config.blocks.EatConfig.Companion.reasonEating import com.lambda.context.Automated import com.lambda.context.AutomatedSafeContext @@ -48,7 +49,6 @@ import com.lambda.interaction.container.SlotIdentity import com.lambda.interaction.handler.handlers.BaritoneHandler import com.lambda.interaction.manager.managers.breaking.breakRequest import com.lambda.interaction.manager.managers.interacting.interactRequest -import com.lambda.module.modules.client.Client import com.lambda.task.Task import com.lambda.task.Task.Ta5kBuilder import com.lambda.task.tasks.wrappers.softFail @@ -314,7 +314,7 @@ class BuildTask @Ta5kBuilder internal constructor( } private fun AutomatedSafeContext.processResults() { - Client.drawables = results + ClientConfig.drawables = results .filterIsInstance() .plus(pendingInteractions.toList()) .toList() diff --git a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt index b7b312d6f..ec6a2517d 100644 --- a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt +++ b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt @@ -24,9 +24,9 @@ import com.lambda.command.LambdaCommand import com.lambda.config.ConfigLoader import com.lambda.core.Loader import com.lambda.event.EventFlow +import com.lambda.gui.GuiConfig import com.lambda.module.Module import com.lambda.module.ModuleRegistry -import com.lambda.module.modules.client.Style import com.lambda.threading.runSafe import com.lambda.threading.runSafeGameScheduled import com.lambda.util.StringUtils.capitalize @@ -153,7 +153,7 @@ object CommunicationUtils { if (command.usage.isNotBlank()) { literal("\n") literal("Usage: ") - color(Style.palette.primary.toAwt()) { + color(GuiConfig.palette.primary.toAwt()) { literal(command.usage) } } @@ -161,7 +161,7 @@ object CommunicationUtils { literal("\n") literal("Aliases: ") joinToText(command.aliases) { - color(Style.palette.primary.toAwt()) { + color(GuiConfig.palette.primary.toAwt()) { literal(it) } } @@ -180,7 +180,7 @@ object CommunicationUtils { literal("\n") } literal("Keybind: ") - color(Style.palette.primary.toAwt()) { + color(GuiConfig.palette.primary.toAwt()) { if (module.keybind.key != 0 || module.keybind.mouse > -1) { literal(module.keybind.name) } else { diff --git a/src/main/kotlin/com/lambda/util/player/RotationUtils.kt b/src/main/kotlin/com/lambda/util/player/RotationUtils.kt index cb0af20ec..42bfb25de 100644 --- a/src/main/kotlin/com/lambda/util/player/RotationUtils.kt +++ b/src/main/kotlin/com/lambda/util/player/RotationUtils.kt @@ -17,6 +17,7 @@ package com.lambda.util.player +import com.lambda.config.ClientConfig import com.lambda.context.Automated import com.lambda.context.AutomatedSafeContext import com.lambda.context.SafeContext @@ -26,7 +27,6 @@ import com.lambda.interaction.construction.verify.SurfaceScan import com.lambda.interaction.manager.managers.rotating.Rotation import com.lambda.interaction.manager.managers.rotating.Rotation.Companion.rotationTo import com.lambda.interaction.manager.managers.rotating.RotationManager -import com.lambda.module.modules.client.Client import com.lambda.util.BlockUtils.blockState import com.lambda.util.PlaceDirection import com.lambda.util.extension.component6 @@ -192,7 +192,7 @@ object RotationUtils { val (scanBox, invalidSides) = getScanBox(preProcessing, allowInsideBox) ?: return (visibleSides - invalidSides).forEach { side -> val (minX, minY, minZ, maxX, maxY, maxZ) = scanBox - .offset(side.doubleVector.multiply(Client.scanShrinkFactor)) + .offset(side.doubleVector.multiply(ClientConfig.scanShrinkFactor)) .bounds(side) val stepX = (maxX - minX) / resolution @@ -225,31 +225,31 @@ object RotationUtils { val pos = when (side) { Direction.DOWN -> Vec3d( pov.x.coerceIn(minX, maxX), - minY - Client.scanShrinkFactor, + minY - ClientConfig.scanShrinkFactor, pov.z.coerceIn(minZ, maxZ) ) Direction.UP -> Vec3d( pov.x.coerceIn(minX, maxX), - maxY + Client.scanShrinkFactor, + maxY + ClientConfig.scanShrinkFactor, pov.z.coerceIn(minZ, maxZ) ) Direction.NORTH -> Vec3d( pov.x.coerceIn(minX, maxX), pov.y.coerceIn(minY, maxY), - minZ - Client.scanShrinkFactor + minZ - ClientConfig.scanShrinkFactor ) Direction.SOUTH -> Vec3d( pov.x.coerceIn(minX, maxX), pov.y.coerceIn(minY, maxY), - maxZ + Client.scanShrinkFactor + maxZ + ClientConfig.scanShrinkFactor ) Direction.WEST -> Vec3d( - minX - Client.scanShrinkFactor, + minX - ClientConfig.scanShrinkFactor, pov.y.coerceIn(minY, maxY), pov.z.coerceIn(minZ, maxZ) ) Direction.EAST -> Vec3d( - maxX + Client.scanShrinkFactor, + maxX + ClientConfig.scanShrinkFactor, pov.y.coerceIn(minY, maxY), pov.z.coerceIn(minZ, maxZ) ) @@ -275,7 +275,7 @@ object RotationUtils { preProcessing: PreProcessingData?, allowInsideBox: Boolean ): Pair>? = - with(contract(Client.scanShrinkFactor)) { + with(contract(ClientConfig.scanShrinkFactor)) { if (preProcessing == null || preProcessing.info.surfaceScan.mode == ScanMode.Full) return Pair(this, emptySet()) val (newXBounds, shrunkXSide) = toScanRange(minX, maxX, preProcessing.pos.x, Direction.Axis.X, preProcessing.info.surfaceScan) @@ -306,8 +306,8 @@ object RotationUtils { ): Pair, Direction?> { val range = if (scan.axis == axis) { when (scan.mode) { - ScanMode.GreaterBlockHalf -> max(origin + 0.5 + Client.scanShrinkFactor, min)..max - else -> min..min(origin + 0.5 - Client.scanShrinkFactor, max) + ScanMode.GreaterBlockHalf -> max(origin + 0.5 + ClientConfig.scanShrinkFactor, min)..max + else -> min..min(origin + 0.5 - ClientConfig.scanShrinkFactor, max) } } else min..max return Pair( diff --git a/src/main/kotlin/com/lambda/util/text/TextDsl.kt b/src/main/kotlin/com/lambda/util/text/TextDsl.kt index 1f209f697..838a9a733 100644 --- a/src/main/kotlin/com/lambda/util/text/TextDsl.kt +++ b/src/main/kotlin/com/lambda/util/text/TextDsl.kt @@ -17,7 +17,7 @@ package com.lambda.util.text -import com.lambda.module.modules.client.Client +import com.lambda.config.ClientConfig import net.minecraft.text.ClickEvent import net.minecraft.text.HoverEvent import net.minecraft.text.MutableText @@ -218,7 +218,7 @@ inline fun TextBuilder.color(color: Color?, action: TextBuilder.() -> Unit) { @TextDsl fun TextBuilder.highlighted(value: String) { - color(Client.highlightColor) { + color(ClientConfig.highlightColor) { literal(value) } } From ecedb4300be444ebe66864da0fe25014a3964421 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:39:13 +0000 Subject: [PATCH 21/34] better notification customizability: Choose which side of the screen, which direction the notifications flow, how many before limiting or limit by how many fit on screen, and choose how high up on the screen to spawn notifications --- .../render/InactivityFpsLimiterMixin.java | 5 +- .../kotlin/com/lambda/config/ClientConfig.kt | 53 ++++ .../com/lambda/config/entries/Setting.kt | 15 ++ .../config/settings/comparable/EnumSetting.kt | 13 +- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 47 +++- .../kotlin/com/lambda/gui/Notifications.kt | 232 ++++++++++++++---- .../com/lambda/gui/component/Controls.kt | 20 +- .../kotlin/com/lambda/gui/component/Popups.kt | 22 ++ .../com/lambda/gui/settings/SettingRow.kt | 41 ++++ src/main/kotlin/com/lambda/gui/theme/Theme.kt | 18 ++ .../handlers/InteractedBlockHandler.kt | 4 +- .../handler/handlers/NotificationHandler.kt | 9 +- .../module/modules/client/ModuleNotifier.kt | 8 +- 13 files changed, 430 insertions(+), 57 deletions(-) create mode 100644 src/main/kotlin/com/lambda/config/ClientConfig.kt diff --git a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java index 54ea7aab9..16b994f08 100644 --- a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java +++ b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java @@ -19,6 +19,7 @@ import com.lambda.gui.GuiScreen; import com.lambda.gui.LambdaGui; +import com.lambda.interaction.handler.handlers.NotificationHandler; import com.llamalad7.mixinextras.injector.ModifyReturnValue; import net.minecraft.client.MinecraftClient; import net.minecraft.client.option.InactivityFpsLimiter; @@ -35,7 +36,9 @@ public class InactivityFpsLimiterMixin { @ModifyReturnValue(method = "getLimitReason", at = @At("RETURN")) private InactivityFpsLimiter.LimitReason liftMenuLimit(InactivityFpsLimiter.LimitReason reason) { - boolean shown = client.currentScreen == GuiScreen.INSTANCE || LambdaGui.INSTANCE.getLeaving(); + boolean shown = client.currentScreen == GuiScreen.INSTANCE + || LambdaGui.INSTANCE.getLeaving() + || !NotificationHandler.INSTANCE.getNotifications().isEmpty(); if (reason == InactivityFpsLimiter.LimitReason.OUT_OF_LEVEL_MENU && shown) { return InactivityFpsLimiter.LimitReason.NONE; } diff --git a/src/main/kotlin/com/lambda/config/ClientConfig.kt b/src/main/kotlin/com/lambda/config/ClientConfig.kt new file mode 100644 index 000000000..065ccaa96 --- /dev/null +++ b/src/main/kotlin/com/lambda/config/ClientConfig.kt @@ -0,0 +1,53 @@ +/* + * 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.config + +import com.lambda.config.categories.LambdaCategory +import com.lambda.core.Loadable +import com.lambda.graphics.mc.renderer.TickedRenderer.Companion.tickedRenderer +import com.lambda.interaction.construction.simulation.result.Drawable +import java.awt.Color + +object ClientConfig : Loadable, Config("Client", LambdaCategory) { + private const val GENERAL_TAB = "General" + private const val DEBUG_TAB = "Debug" + + private const val RENDERING_GROUP = "Rendering" + + @Tab(GENERAL_TAB) val clientSounds by setting("Client Sounds", true, "Plays sounds when certain actions are performed with lambda. Toggling modules, for example") + @Tab(GENERAL_TAB) val buildTaskRenders by setting("Build Task Renders", false, "Displays renders from some build sim results generated from the build task") + @Tab(GENERAL_TAB) val avoidInventoryDesync by setting("Avoid Inventory Desync", true, "Cancels incoming inventory update packets if they match previous actions") + @Tab(GENERAL_TAB) val desyncTimeout by setting("Desync Timeout", 30, 1..30, 1, unit = " ticks", description = "Time to store previous inventory actions before dropping the cache") { avoidInventoryDesync } + @Tab(GENERAL_TAB) val scanShrinkFactor by setting("Scan Shrink Factor", 0.001, 0.0..1.0, 0.001, "How much to shrink block scans from the edges to avoid flagging anticheats") + @Tab(GENERAL_TAB) @Group(RENDERING_GROUP) val chunkUploadsPerTick by setting("Chunk Uploads", 16, 1..256, 1, unit = " chunks/tick") + @Tab(GENERAL_TAB) @Group(RENDERING_GROUP) val chunkRebuildsPerTick by setting("Chunk Rebuilds", 64, 1..256, 1, unit = " chunks/tick") + @Tab(GENERAL_TAB) val highlightColor by setting("Text Highlight Color", Color(214, 55, 87), "Base text highlight color") + + @Tab(DEBUG_TAB) val ignoreItemDropWarnings by setting("Ignore Drop Warnings", false, "Hides the item drop warnings from the break manager") + @Tab(DEBUG_TAB) val verboseDebug by setting("Verbose Debug", false, "Prints more, and more detailed, debug logs") + @Tab(DEBUG_TAB) val showInvisibleTasks by setting("Show Invisible Tasks", false, "Shows utility tasks such as chaining wrappers in the Task Flow HUD") + + @Volatile + var drawables = listOf() + + init { + tickedRenderer("Client Ticked Renderer") { + if (buildTaskRenders) drawables.forEach { with(it) { render() } } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/lambda/config/entries/Setting.kt b/src/main/kotlin/com/lambda/config/entries/Setting.kt index 691c1a505..e0f954f62 100644 --- a/src/main/kotlin/com/lambda/config/entries/Setting.kt +++ b/src/main/kotlin/com/lambda/config/entries/Setting.kt @@ -118,6 +118,9 @@ abstract class Setting( open var value by this val listeners = mutableListOf>() + val hoverListeners = mutableListOf<(hovered: Boolean) -> Unit>() + val holdListeners = mutableListOf<(held: Boolean) -> Unit>() + val clickListeners = mutableListOf<() -> Unit>() override val isModified get() = originalCore.value != originalCore.defaultValue @@ -262,6 +265,18 @@ fun , T> S.onValueSet(block: SafeContext.(from: T, to: T) -> Unit fun , T> S.onValueSetUnsafe(block: (from: T, to: T) -> Unit) = apply { listeners.add(ValueListener(false, block)) } +@ConfigEntryDsl +fun > S.onHover(block: (hovered: Boolean) -> Unit) = + apply { hoverListeners.add(block) } + +@ConfigEntryDsl +fun > S.onHold(block: (held: Boolean) -> Unit) = + apply { holdListeners.add(block) } + +@ConfigEntryDsl +fun > S.onClick(block: () -> Unit) = + apply { clickListeners.add(block) } + @ConfigEntryDsl fun , T> S.disabled(predicate: () -> Boolean) = apply { disabled = predicate } 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 ab05a32d7..bcdb2fc8e 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt @@ -46,6 +46,9 @@ class EnumSetting>( visibility: () -> Boolean, defaultValue: T ) : Setting(name, description, defaultValue, layer, config, visibility) { + val selectionHoverListeners = mutableListOf<(option: T?) -> Unit>() + val selectionClickListeners = mutableListOf<(option: T) -> Unit>() + @Composable override fun Gui() { val selected by observe { value } @@ -55,6 +58,8 @@ class EnumSetting>( selected = selected, optionLabel = { it.displayValue }, modifier = Modifier.padding(start = ROW_INSET), + onOptionHover = { option -> selectionHoverListeners.forEach { it(option) } }, + onOptionClick = { option -> selectionClickListeners.forEach { it(option) } }, ) { value = it } } @@ -75,4 +80,10 @@ class EnumSetting>( private val > T.enumValues: Array get() = declaringJavaClass.enumConstants -} \ No newline at end of file +} + +fun , T : Enum> S.onSelectionHover(block: (option: T?) -> Unit) = + apply { selectionHoverListeners.add(block) } + +fun , T : Enum> S.onSelectionClick(block: (option: T) -> Unit) = + apply { selectionClickListeners.add(block) } diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index 4921ab3b4..ebb231816 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -17,17 +17,30 @@ package com.lambda.gui +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import com.lambda.config.Config import com.lambda.config.ConfigBlock import com.lambda.config.Group import com.lambda.config.Tab import com.lambda.config.categories.GuiCategory +import com.lambda.config.entries.Setting +import com.lambda.config.entries.onHold import com.lambda.config.entries.onValueChange +import com.lambda.config.entries.onValueChangeUnsafe import com.lambda.config.settings.appliedOnRelease +import com.lambda.config.settings.comparable.EnumSetting +import com.lambda.config.settings.comparable.onSelectionHover import com.lambda.core.Loadable +import com.lambda.event.events.ComposeEvent +import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe import com.lambda.gui.theme.GuiFont import com.lambda.gui.theme.GuiInterrupt import com.lambda.gui.theme.GuiTransition +import com.lambda.gui.theme.NotificationFlow +import com.lambda.gui.theme.NotificationLimit +import com.lambda.gui.theme.NotificationSide import com.lambda.gui.theme.Palette import com.lambda.util.KeyCode import com.lambda.util.NamedEnum @@ -49,6 +62,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { private const val LAYOUT_GROUP = "Layout" private const val MOTION_GROUP = "Motion" private const val NOTIFICATIONS_GROUP = "Notifications" + private const val NOTIFICATION_PREVIEW_MILLIS = 1500L private const val DARK_THEME_GROUP = "Dark Theme" private const val LIGHT_THEME_GROUP = "Light Theme" @@ -141,10 +155,14 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @Tab(STYLE_TAB) @Group(MOTION_GROUP) val scrollSpeed by setting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") @Tab(STYLE_TAB) @Group(MOTION_GROUP) val tooltipDelay by setting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationScale by setting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface") - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationWidth by setting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines") - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSeconds by setting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it slides away") - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val maxNotifications by setting("Max Notifications", 5, 1..12, 1, "How many notifications stack before the oldest slides off the bottom of the screen") + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationScale by setting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationWidth by setting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSide by setting("Notification Side", NotificationSide.Right, "Which side of the screen notifications slide in from").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationHeight by setting("Notification Height", 0f, 0f..1f, 0.05f, "Where on that side the first notification sits. 0 is the bottom of the screen and 1 the top").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationFlow by setting("Notification Direction", NotificationFlow.Up, "Which way the stack grows: each new notification appears on this side of the ones already showing. They leave the other way, and the stack is kept on the screen").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSeconds by setting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it leaves") + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationLimit by setting("Notification Limit", NotificationLimit.Count, "Count lets the oldest go once more than Max Notifications are showing. Fit Screen shows as many as fit between Notification Height and the edge of the screen the stack grows towards, and the oldest goes when a new one would not fit").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val maxNotifications by setting("Max Notifications", 5, 1..12, 1, "How many notifications show at once before the oldest leaves") { notificationLimit == NotificationLimit.Count }.previewsNotifications() @Tab(STYLE_TAB) @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( PaletteSettings( @@ -229,6 +247,27 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { } } + private var notificationHeld = false + private var notificationPreviewEnd = 0L + internal var notificationOption by mutableStateOf(null) + private set + + init { + listenUnsafe { event -> + val previewing = notificationHeld || notificationOption != null || System.currentTimeMillis() < notificationPreviewEnd + if (previewing) event.content { NotificationPreview() } + } + } + + private fun , T> S.previewsNotifications() = + apply { + onHold { notificationHeld = it } + onValueChangeUnsafe { _, _ -> notificationPreviewEnd = System.currentTimeMillis() + NOTIFICATION_PREVIEW_MILLIS } + } + + private fun , T : Enum> S.previewsNotificationOptions() = + onSelectionHover { notificationOption = it } + internal data class WindowPlacement( val x: Float, val y: Float, diff --git a/src/main/kotlin/com/lambda/gui/Notifications.kt b/src/main/kotlin/com/lambda/gui/Notifications.kt index a550701f6..c5392e3e5 100644 --- a/src/main/kotlin/com/lambda/gui/Notifications.kt +++ b/src/main/kotlin/com/lambda/gui/Notifications.kt @@ -19,6 +19,7 @@ package com.lambda.gui import androidx.compose.animation.core.Animatable 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.IntrinsicSize @@ -33,66 +34,182 @@ 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.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.lambda.gui.component.ContentColor +import com.lambda.gui.component.Overlay import com.lambda.gui.component.Text import com.lambda.gui.component.window +import com.lambda.gui.core.observe import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look import com.lambda.gui.theme.Motion +import com.lambda.gui.theme.NotificationFlow +import com.lambda.gui.theme.NotificationLimit +import com.lambda.gui.theme.NotificationSide import com.lambda.gui.theme.Type import com.lambda.interaction.handler.handlers.NotificationHandler import com.lambda.interaction.handler.handlers.NotificationHandler.Notification import com.lambda.util.math.toCompose +import kotlinx.coroutines.launch +import kotlin.math.abs import kotlin.math.roundToInt private val MARGIN = 6.dp private val GAP = 4.dp private val STRIPE = 2.dp +private const val PREVIEW_COUNT = 3 +private const val PREVIEW_ALPHA = 0.8f @Composable internal fun Notifications() { val notifications = NotificationHandler.notifications if (notifications.isEmpty()) return - val heights = remember { mutableStateMapOf() } + Scaled { Stack(notifications) } +} + +@Composable +internal fun NotificationPreview() { + val option = GuiConfig.notificationOption + val limit by observe { option as? NotificationLimit ?: GuiConfig.notificationLimit } + val max by observe { GuiConfig.maxNotifications } + val leftSide = (option as? NotificationSide ?: Look.notificationSide) == NotificationSide.Left + val rising = (option as? NotificationFlow ?: Look.notificationFlow) == NotificationFlow.Up + val height = Look.notificationHeight + val screen = LocalWindowInfo.current.containerSize + var older by remember { mutableStateOf(0) } + var newest by remember { mutableStateOf(0) } + Scaled { + val margin = with(LocalDensity.current) { MARGIN.roundToPx() } + val gap = with(LocalDensity.current) { GAP.roundToPx() } + val line = margin + ((1f - height) * (screen.height - margin * 2)).roundToInt() + val room = + if (rising) line.coerceAtLeast(margin + older) - margin + else screen.height - margin - line.coerceAtMost(screen.height - margin - older) + val count = + when { + limit == NotificationLimit.Count -> max + older == 0 || newest == 0 -> PREVIEW_COUNT + else -> (1 + (room - newest) / (older + gap)).coerceAtLeast(1) + } + val newestAt = + if (rising) 0 + else count - 1 + val ghosts = + remember(count, newestAt) { + List(count) { + if (it == newestAt) Notification("Newest notification", "New ones appear here", null) + else Notification("Older notification", "", null) + } + } + val oldest = + if (count == 1) newest + else older + Overlay( + position = { window, size -> + IntOffset( + if (leftSide) margin + else window.width - margin - size.width, + ( + if (rising) line.coerceAtLeast(margin + oldest) - size.height + else line.coerceAtMost(window.height - margin - oldest) + ).coerceAtMost(window.height - margin - size.height).coerceAtLeast(margin) + ) + } + ) { + Column( + Modifier.graphicsLayer { alpha = PREVIEW_ALPHA }, + verticalArrangement = Arrangement.spacedBy(GAP) + ) { + ghosts.forEachIndexed { index, ghost -> + Card( + ghost, + leftSide, + Modifier.onSizeChanged { + if (index == newestAt) newest = it.height + else older = it.height + } + ) + } + } + } + } +} + +@Composable +private fun Scaled(content: @Composable () -> Unit) { val density = LocalDensity.current val scaled = Density(density.density * Look.notificationScale, density.fontScale) - CompositionLocalProvider(LocalDensity provides scaled) { - Stack(notifications, heights) - } + CompositionLocalProvider(LocalDensity provides scaled, content = content) } @Composable -private fun Stack(notifications: List, heights: MutableMap) { +private fun Stack(notifications: List) { + val heights = remember { mutableStateMapOf() } + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize + val margin = with(density) { MARGIN.roundToPx() } + val gap = with(density) { GAP.roundToPx() } + val live = notifications.filterNot { it.dismissed } + val oldest = live.firstOrNull()?.let { heights[it] } ?: 0 + val line = margin + ((1f - Look.notificationHeight) * (screen.height - margin * 2)).roundToInt() + val rising = Look.notificationFlow == NotificationFlow.Up + val anchor = + if (rising) line.coerceAtLeast(margin + oldest) + else line.coerceAtMost(screen.height - margin - oldest) + val stacked = (live.sumOf { (heights[it] ?: 0) + gap } - gap).coerceAtLeast(0) + val base = + if (rising) anchor.coerceAtLeast(margin + stacked).coerceAtMost(screen.height - margin) + else anchor.coerceAtMost(screen.height - margin - stacked).coerceAtLeast(margin) + + val limit by observe { GuiConfig.notificationLimit } + if (limit == NotificationLimit.Screen && live.all { it in heights }) { + val room = + if (rising) anchor - margin + else screen.height - margin - anchor + var taken = -gap + val fitting = + live.takeLastWhile { + taken += (heights[it] ?: 0) + gap + taken <= room + } + val crowded = live.dropLast(fitting.size.coerceAtLeast(1)) + SideEffect { crowded.forEach { it.dismissed = true } } + } + Box(Modifier.fillMaxSize()) { notifications.forEach { notification -> key(notification) { - val stacked = - notifications - .takeWhile { it !== notification } - .filterNot { it.dismissed } - .sumOf { heights[it] ?: 0 } - val beneath = notifications.takeWhile { it !== notification }.count { !it.dismissed } + val height = heights[notification] ?: 0 + val ahead = live.takeWhile { it !== notification }.sumOf { (heights[it] ?: 0) + gap } Toast( notification = notification, - stacked = stacked, - beneath = beneath, - height = heights[notification] ?: 0, + top = + if (rising) base - ahead - height + else base + ahead, + leaving = + if (rising) height + gap + else -height - gap, + measured = notification in heights, onMeasured = { heights[notification] = it }, onGone = { heights -= notification NotificationHandler.remove(notification) }, - modifier = Modifier.align(Alignment.BottomEnd) ) } } @@ -102,54 +219,85 @@ private fun Stack(notifications: List, heights: MutableMap Unit, onGone: () -> Unit, - modifier: Modifier = Modifier, ) { - val colors = LambdaTheme.colors val density = LocalDensity.current - val reach = with(density) { (Look.notificationWidth + MARGIN * 4).toPx() } - val rise = - if (notification.dismissed) -height - with(density) { (MARGIN * 4).toPx() } - else with(density) { (MARGIN + GAP * beneath).toPx() } + stacked + val screen = LocalWindowInfo.current.containerSize + val margin = with(density) { MARGIN.toPx() } + val width = with(density) { Look.notificationWidth.toPx() } + val reach = width + margin * 4 + val leftSide = Look.notificationSide == NotificationSide.Left val entered = remember { Animatable(0f) } - val risen = remember { Animatable(rise) } + val placed = remember { Animatable(top.toFloat()) } + val opacity = remember { Animatable(1f) } + var settled by remember { mutableStateOf(false) } LaunchedEffect(Unit) { entered.animateTo(1f, Motion.NOTIFICATIONS) } - LaunchedEffect(rise) { - risen.animateTo(rise, Motion.NOTIFICATIONS) - if (notification.dismissed) onGone() + LaunchedEffect(top, measured, notification.dismissed) { + if (notification.dismissed) return@LaunchedEffect + if (settled) placed.animateTo(top.toFloat(), Motion.NOTIFICATIONS) + else placed.snapTo(top.toFloat()) + settled = measured + } + LaunchedEffect(notification.dismissed) { + if (!notification.dismissed) return@LaunchedEffect + val end = placed.value + leaving + val leavesScreen = end >= screen.height || end + abs(leaving) <= 0 + if (!leavesScreen) launch { opacity.animateTo(0f, Motion.NOTIFICATIONS) } + placed.animateTo(end, Motion.NOTIFICATIONS) + onGone() } - val shape = RoundedCornerShape(Look.panelRounding) - Row( - modifier + Card( + notification, + leftSide, + Modifier .offset { + val hidden = (1f - entered.value) * reach IntOffset( - ((1f - entered.value) * reach).roundToInt() - MARGIN.roundToPx(), - -risen.value.roundToInt() + ( + if (leftSide) margin - hidden + else screen.width - margin - width + hidden + ).roundToInt(), + placed.value.roundToInt() ) } + .graphicsLayer { alpha = opacity.value } .onSizeChanged { onMeasured(it.height) } + ) +} + +@Composable +private fun Card(notification: Notification, leftSide: Boolean, modifier: Modifier = Modifier) { + val colors = LambdaTheme.colors + val accent = notification.accent?.toCompose() ?: colors.primary + Row( + modifier .width(Look.notificationWidth) .height(IntrinsicSize.Min) - .window(colors.panel, colors.border, shape, floating = true) + .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) ) { - Box( - Modifier - .width(STRIPE) - .fillMaxHeight() - .background(notification.accent?.toCompose() ?: colors.primary) - ) + if (!leftSide) Stripe(accent) ContentColor(colors.onSurface) { - Column(Modifier.padding(Look.panelPadding, Look.panelPadding / 2)) { + Column(Modifier.weight(1f).padding(Look.panelPadding, Look.panelPadding / 2)) { Text(notification.title, style = Type.label, maxLines = 1) if (notification.message.isNotEmpty()) { Text(notification.message, color = colors.onSurfaceVariant) } } } + if (leftSide) Stripe(accent) } } + +@Composable +private fun Stripe(color: Color) = + Box( + Modifier + .width(STRIPE) + .fillMaxHeight() + .background(color) + ) diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt index ee9ef830b..b21c3c703 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -39,10 +39,12 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable +import androidx.compose.runtime.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.Alignment import androidx.compose.ui.Modifier @@ -243,10 +245,18 @@ fun Dropdown( selected: T, optionLabel: (T) -> String, modifier: Modifier = Modifier, + onOptionHover: (option: T?) -> Unit = {}, + onOptionClick: (option: T) -> Unit = {}, onSelect: (T) -> Unit, ) { val menu = remember { MenuState() } var chip by remember { mutableStateOf(IntSize.Zero) } + var hovered by remember { mutableStateOf(null) } + val currentOnOptionHover by rememberUpdatedState(onOptionHover) + LaunchedEffect(hovered) { currentOnOptionHover(hovered) } + DisposableEffect(Unit) { + onDispose { currentOnOptionHover(null) } + } LabeledRow(label, modifier) { Box(Modifier.onSizeChanged { chip = it }) { Chip(onClick = menu::toggle) { @@ -259,7 +269,15 @@ fun Dropdown( unfoldFrom = IntSize(chip.width, 0) ) { options.forEach { option -> - MenuItem(optionLabel(option), selected = option == selected) { + MenuItem( + optionLabel(option), + selected = option == selected, + onHover = { + if (it) hovered = option + else if (hovered == option) hovered = null + } + ) { + onOptionClick(option) if (option != selected) onSelect(option) } } diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index a373a53e8..a7693a643 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -45,6 +45,7 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.Stable @@ -52,6 +53,7 @@ import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Alignment @@ -512,14 +514,23 @@ fun MenuItem( checked: Boolean? = null, selected: Boolean = false, hint: String? = null, + onHover: (hovered: Boolean) -> Unit = {}, onClick: () -> Unit, ) { val colors = LambdaTheme.colors val dismiss = LocalMenuDismiss.current + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() + val currentOnHover by rememberUpdatedState(onHover) + LaunchedEffect(hovered) { currentOnHover(hovered) } + DisposableEffect(Unit) { + onDispose { currentOnHover(false) } + } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() + .hoverable(interactions) .background(if (selected) colors.controlSelected else Color.Transparent) .then( if (!enabled) Modifier @@ -680,6 +691,17 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { } } +@Composable +fun Overlay( + position: (window: IntSize, size: IntSize) -> IntOffset, + content: @Composable () -> Unit +) = + ScenePopup( + popupPositionProvider = positionProvider { _, window, size -> position(window, size) }, + properties = PopupProperties(focusable = false), + content = content + ) + @Composable fun Tooltip( text: String, diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 6ae14cd30..edc3389bc 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -28,6 +28,7 @@ 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.key @@ -39,6 +40,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import com.lambda.config.entries.Setting @@ -61,6 +63,13 @@ internal val ROW_INSET = 3.dp @Composable fun SettingRow(setting: Setting<*>) { val disabled by observe { setting.disabled() } + val pointer = remember(setting) { RowPointer(setting) } + DisposableEffect(pointer) { + onDispose { + pointer.hovered = false + pointer.held = false + } + } val revealed = Reveal.setting === setting val lit by @@ -82,6 +91,22 @@ fun SettingRow(setting: Setting<*>) { Modifier .settingCell() .bringIntoViewRequester(intoView) + .pointerInput(pointer) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + val change = event.changes.first() + val inside = change.position.x in 0f..size.width.toFloat() && change.position.y in 0f..size.height.toFloat() + when (event.type) { + PointerEventType.Enter -> pointer.hovered = true + PointerEventType.Exit -> pointer.hovered = false + } + val wasHeld = pointer.held + pointer.held = event.changes.any { it.pressed } + if (wasHeld && !pointer.held && inside) setting.clickListeners.forEach { it() } + } + } + } .drawWithContent { drawContent() drawRect(lit) @@ -98,6 +123,22 @@ fun SettingRow(setting: Setting<*>) { } } +private class RowPointer(private val setting: Setting<*>) { + var hovered = false + set(value) { + if (field == value) return + field = value + setting.hoverListeners.forEach { it(value) } + } + + var held = false + set(value) { + if (field == value) return + field = value + setting.holdListeners.forEach { it(value) } + } +} + internal fun Modifier.settingCell(): Modifier = composed { fillMaxWidth() diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index ad8f7b97f..7d2ac6fc8 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -115,6 +115,9 @@ internal object Look { val settingsWidth by style { GuiConfig.settingsWidth.dp } val notificationScale by style { GuiConfig.notificationScale } val notificationWidth by style { GuiConfig.notificationWidth.dp } + val notificationSide by style { GuiConfig.notificationSide } + val notificationHeight by style { GuiConfig.notificationHeight } + val notificationFlow by style { GuiConfig.notificationFlow } val windowGap by style { GuiConfig.windowGap.dp } val windowTop by style { GuiConfig.windowTop.dp } val modulePadding by style { GuiConfig.modulePadding.dp } @@ -180,6 +183,21 @@ enum class GuiInterrupt(override val displayName: String) : NamedEnum { Finish("Skip To End"), } +enum class NotificationSide(override val displayName: String) : NamedEnum { + Left("Left"), + Right("Right"), +} + +enum class NotificationFlow(override val displayName: String) : NamedEnum { + Up("Up"), + Down("Down"), +} + +enum class NotificationLimit(override val displayName: String) : NamedEnum { + Count("Count"), + Screen("Fit Screen"), +} + enum class GuiFont( override val displayName: String, val size: TextUnit, diff --git a/src/main/kotlin/com/lambda/interaction/handler/handlers/InteractedBlockHandler.kt b/src/main/kotlin/com/lambda/interaction/handler/handlers/InteractedBlockHandler.kt index 3340c4cae..b145523cf 100644 --- a/src/main/kotlin/com/lambda/interaction/handler/handlers/InteractedBlockHandler.kt +++ b/src/main/kotlin/com/lambda/interaction/handler/handlers/InteractedBlockHandler.kt @@ -32,8 +32,8 @@ import com.lambda.util.collections.LimitedDecayQueue internal object InteractedBlockHandler : PostActionHandler() { override val pendingActions = LimitedDecayQueue( - AutomationConfig.Companion.DEFAULT.buildConfig.maxPendingActions, - AutomationConfig.Companion.DEFAULT.buildConfig.actionTimeout * 50L + AutomationConfig.DEFAULT.buildConfig.maxPendingActions, + AutomationConfig.DEFAULT.buildConfig.actionTimeout * 50L ) { if (ClientConfig.verboseDebug) warn("${it::class.simpleName} at ${it.context.blockPos.toShortString()} timed out") if (it.interactConfig.interactConfirmationMode != InteractConfig.InteractConfirmationMode.AwaitThenPlace) { diff --git a/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt index b5b748551..3a189ec6f 100644 --- a/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt +++ b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt @@ -28,6 +28,7 @@ import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe import com.lambda.gui.GuiConfig import com.lambda.gui.Notifications import com.lambda.gui.core.RenderThread +import com.lambda.gui.theme.NotificationLimit import java.awt.Color object NotificationHandler : Loadable { @@ -49,9 +50,11 @@ object NotificationHandler : Loadable { val notification = Notification(title, message, accent) kept += notification if (kept.size > MAX_KEPT) kept.removeRange(0, kept.size - MAX_KEPT) - kept.filterNot { it.dismissed } - .dropLast(GuiConfig.maxNotifications) - .forEach { it.dismissed = true } + if (GuiConfig.notificationLimit == NotificationLimit.Count) { + kept.filterNot { it.dismissed } + .dropLast(GuiConfig.maxNotifications) + .forEach { it.dismissed = true } + } RenderThread.after((GuiConfig.notificationSeconds * 1000).toLong()) { notification.dismissed = true } diff --git a/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt b/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt index 78789fa2c..bcb47abca 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt @@ -17,8 +17,9 @@ package com.lambda.module.modules.client +import com.lambda.Lambda.mc import com.lambda.event.events.ModuleEvent -import com.lambda.event.listener.SafeListener.Companion.listen +import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe import com.lambda.interaction.handler.handlers.NotificationHandler import com.lambda.module.Module import com.lambda.module.ModuleTag @@ -48,7 +49,7 @@ object ModuleNotifier : Module( } init { - listen { event -> + listenUnsafe { event -> logToTargets(event.module, "Enabled", Color(Colors.GREEN)) { color(Color(Colors.GREEN)) { literal("on") @@ -56,7 +57,7 @@ object ModuleNotifier : Module( } } - listen { event -> + listenUnsafe { event -> logToTargets(event.module, "Disabled", Color(Colors.RED)) { color(Color(Colors.RED)) { literal("off") @@ -69,6 +70,7 @@ object ModuleNotifier : Module( if (NotifyTarget.Notification in notifyTarget) { NotificationHandler.notify(module.name, state, color) } + if (mc.player == null) return if (NotifyTarget.Chat in notifyTarget) { module.log(buildText(action)) } From 6a215537a303bc17dc2cdb7d46ea839d1c06a244 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:47:52 +0000 Subject: [PATCH 22/34] better default watermark config, better default snapping config and fixed animations --- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 4 +- src/main/kotlin/com/lambda/gui/Snap.kt | 2 - .../com/lambda/gui/clickgui/SettingsPanel.kt | 6 +-- .../kotlin/com/lambda/gui/component/Popups.kt | 34 ++++++++------ src/main/kotlin/com/lambda/gui/hud/Hud.kt | 15 +++++-- .../kotlin/com/lambda/gui/hud/HudEditor.kt | 44 +++++++++++++++---- .../kotlin/com/lambda/module/HudModule.kt | 8 +++- .../lambda/module/modules/hud/Watermark.kt | 10 ++--- 8 files changed, 85 insertions(+), 38 deletions(-) diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index ebb231816..31bdc503f 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -90,7 +90,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @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 gridSize by setting("Grid Size", 5f, 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 } @@ -255,7 +255,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { init { listenUnsafe { event -> val previewing = notificationHeld || notificationOption != null || System.currentTimeMillis() < notificationPreviewEnd - if (previewing) event.content { NotificationPreview() } + if (previewing && !LambdaGui.leaving) event.content { NotificationPreview() } } } diff --git a/src/main/kotlin/com/lambda/gui/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt index 8e924d63f..85e27dcc5 100644 --- a/src/main/kotlin/com/lambda/gui/Snap.kt +++ b/src/main/kotlin/com/lambda/gui/Snap.kt @@ -78,8 +78,6 @@ internal object Snap { val neighbours = buildList { if (GuiConfig.snapToEdges) { - add(startAt(start(area))) - add(endAt(end(area))) others.forEach { other -> add(startAt(start(other))) add(endAt(end(other))) diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index f98cd5698..76d01f101 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -89,7 +89,7 @@ import com.lambda.module.ModuleTag import kotlinx.coroutines.launch import kotlin.math.roundToInt -private val MIN_WIDTH = 130.dp +internal val MIN_PANEL_WIDTH = 130.dp private val MIN_HEIGHT = 120.dp private val MIN_GRIP_HEIGHT = 3.dp private val INSET_SHADOW = 5.dp @@ -181,7 +181,7 @@ internal fun SettingsPanel( ) { Box( Modifier - .widthIn(MIN_WIDTH, Look.settingsWidth) + .widthIn(MIN_PANEL_WIDTH, Look.settingsWidth) .heightIn(max = maxHeight) .widthOfContent() .onSizeChanged { size = it } @@ -260,7 +260,7 @@ internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { } } -private fun Modifier.widthOfContent(): Modifier = +internal fun Modifier.widthOfContent(): Modifier = composed { val scope = rememberCoroutineScope() var width by remember { mutableStateOf?>(null) } diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index a7693a643..2c9823bfd 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -70,6 +70,7 @@ import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.graphics.drawscope.translate +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType @@ -98,6 +99,7 @@ import androidx.compose.ui.window.PopupProperties import com.lambda.gui.GuiConfig import com.lambda.gui.LambdaGui import com.lambda.gui.core.GameClipboard +import com.lambda.gui.core.LocalPresence import com.lambda.gui.core.LocalShown import com.lambda.gui.core.Press import com.lambda.gui.core.awaitFrames @@ -659,6 +661,7 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { return } val colors = LambdaTheme.colors + val presence = LocalPresence.current ScenePopup( popupPositionProvider = remember { positionProvider { _, _, _ -> IntOffset.Zero } @@ -667,25 +670,30 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { onKeyEvent = { onDismiss != null && it.dismissOnEscape(onDismiss) }, ) { KeyboardFocus.Layer() - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - .fillMaxSize() - .glass(Color.Black.copy(alpha = 0.35f), RectangleShape) - .mouseClickable(keyboard = false) { onDismiss?.invoke() } - ) { + Box(Modifier.fillMaxSize(), Alignment.Center) { + Box( + Modifier + .matchParentSize() + .graphicsLayer { alpha = presence() } + .glass(Color.Black.copy(alpha = 0.35f), RectangleShape) + .mouseClickable(keyboard = false) { onDismiss?.invoke() } + ) ContentColor(colors.onSurface) { - Box( + AnimatedVisibility( + visible = !LambdaGui.foldsClosed, modifier = Modifier + .guiPresence() .window( colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true - ) - .padding(6.dp), - content = content - ) + ), + enter = expandVertically(Motion.guiFold), + exit = shrinkVertically(Motion.guiFold), + ) { + Box(Modifier.padding(6.dp), content = content) + } } } } @@ -743,7 +751,7 @@ fun Tooltip( } ) { content() - if (visible && hovered) { + if (visible && hovered && !LambdaGui.leaving) { val below = with(LocalDensity.current) { 16.dp.roundToPx() } ScenePopup( popupPositionProvider = remember(pointer, bounds) { diff --git a/src/main/kotlin/com/lambda/gui/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt index ab09ddc2f..421dfd8ff 100644 --- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -22,6 +22,7 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key @@ -34,6 +35,8 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layout import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp import com.lambda.Lambda.mc import com.lambda.config.Config @@ -91,11 +94,14 @@ internal fun HudLayer(editor: HudEditorState? = null) { private fun HudElement(hud: HudModule, editor: HudEditorState?) { val anchor by observe { Offset(hud.anchorX, hud.anchorY) } val background by observe { hud.backgroundColor.value.toCompose() } + val scale by observe { hud.scale } var empty by remember { mutableStateOf(false) } if (editor != null) DisposableEffect(hud) { onDispose { editor.bounds -= hud } } + val density = LocalDensity.current + val scaled = remember(density, scale) { Density(density.density * scale, density.fontScale) } Box( Modifier .layout { measurable, constraints -> @@ -118,10 +124,13 @@ private fun HudElement(hud: HudModule, editor: HudEditorState?) { .then(if (editor != null) Modifier.hudEditable(hud, editor) else Modifier) .clipToBounds() .background(background) - .padding(ELEMENT_PADDING) ) { - Box(Modifier.onSizeChanged { empty = it.width == 0 || it.height == 0 }) { hud.Content() } - if (editor != null && empty) HudText(hud.name, color = LambdaTheme.colors.onSurfaceVariant) + CompositionLocalProvider(LocalDensity provides scaled) { + Box(Modifier.padding(ELEMENT_PADDING)) { + Box(Modifier.onSizeChanged { empty = it.width == 0 || it.height == 0 }) { hud.Content() } + if (editor != null && empty) HudText(hud.name, color = LambdaTheme.colors.onSurfaceVariant) + } + } } } diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt index 71bac86e2..e5904fb34 100644 --- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -27,10 +27,14 @@ import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.drag import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize +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.layout.widthIn +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect @@ -73,21 +77,30 @@ import com.lambda.gui.LambdaGui import com.lambda.gui.Reveal import com.lambda.gui.Snap import com.lambda.gui.Snap.snapLines +import com.lambda.gui.clickgui.MIN_PANEL_WIDTH +import com.lambda.gui.clickgui.widthOfContent 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.Text import com.lambda.gui.component.onMousePress import com.lambda.gui.component.rememberLast import com.lambda.gui.component.window import com.lambda.gui.core.observe import com.lambda.gui.settings.ConfigSettings +import com.lambda.gui.settings.ModuleSettings +import com.lambda.gui.settings.PanelPage +import com.lambda.gui.settings.ROW_INSET import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look +import com.lambda.gui.theme.Type import com.lambda.module.HudModule +import com.lambda.module.Module private val PANEL_SCALE = spring(stiffness = Spring.StiffnessMedium) +private val CONFIG_WIDTH = 150.dp internal class HudEditorState(snapping: State) { val snapping by snapping @@ -270,11 +283,8 @@ private fun ElementSettings(config: Config, open: Boolean, editor: HudEditorStat enter = scaleIn(PANEL_SCALE), exit = scaleOut(PANEL_SCALE), ) { - ConfigSettings( - config = config, - maxHeight = maxHeight, - onDone = { editor.configure(null) }, - modifier = Modifier + Column( + Modifier .onSizeChanged { size = it } .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) .pointerInput(Unit) { @@ -288,9 +298,27 @@ private fun ElementSettings(config: Config, open: Boolean, editor: HudEditorStat } } } - .padding(6.dp) - .width(200.dp) - ) + .padding(Look.panelPadding) + ) { + if (config is Module) { + var page by remember(config) { mutableStateOf(PanelPage.Settings) } + Column( + Modifier + .widthIn(MIN_PANEL_WIDTH, Look.settingsWidth) + .heightIn(max = maxHeight) + .widthOfContent() + ) { + Text( + config.name, + Modifier.padding(start = ROW_INSET, bottom = Look.settingSpacing), + style = Type.title, + maxLines = 1 + ) + ModuleSettings(config, page, { page = it }, rememberScrollState()) + } + } + else ConfigSettings(config, maxHeight, onDone = { editor.configure(null) }, Modifier.width(CONFIG_WIDTH)) + } } } diff --git a/src/main/kotlin/com/lambda/module/HudModule.kt b/src/main/kotlin/com/lambda/module/HudModule.kt index 330d1f82a..2b3074417 100644 --- a/src/main/kotlin/com/lambda/module/HudModule.kt +++ b/src/main/kotlin/com/lambda/module/HudModule.kt @@ -28,6 +28,9 @@ abstract class HudModule( alwaysListening: Boolean = false, enabledByDefault: Boolean = false, defaultKeybind: Bind = Bind.EMPTY, + defaultScale: Float = 1f, + defaultAnchorX: Float = DEFAULT_ANCHOR, + defaultAnchorY: Float? = null, ) : Module( name, description, @@ -37,9 +40,10 @@ abstract class HudModule( defaultKeybind = defaultKeybind ) { val backgroundColor = setting("Background Color", Color(0, 0, 0, 0)) + val scale by setting("Scale", defaultScale, 0.25f..5f, 0.05f, "Size of this element, on top of the Scale in HUD Settings") - 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 } + var anchorX by setting("HUD X", defaultAnchorX, 0f..1f, 0.001f) { false } + var anchorY by setting("HUD Y", defaultAnchorY ?: (DEFAULT_ANCHOR + DEFAULT_SPACING * created++).coerceAtMost(1f), 0f..1f, 0.001f) { false } @Composable abstract fun Content() 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 748d17b05..e97ea6acc 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt @@ -20,11 +20,9 @@ package com.lambda.module.modules.hud 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 @@ -33,17 +31,19 @@ object Watermark : HudModule( name = "Watermark", tag = ModuleTag.HUD, enabledByDefault = true, + defaultScale = 0.45f, + defaultAnchorX = 0.005f, + defaultAnchorY = 0.009f, ) { - private val scale by setting("Scale", 0.15f, 0.01f..1f, 0.01f) + private const val LOGO_SCALE = 0.05f @Composable override fun Content() { val logo = rememberTexture("textures/lambda.png") - val scale by observe { scale } Image( logo, "Lambda", - Modifier.size((logo.width * scale).dp, (logo.height * scale).dp) + Modifier.size((logo.width * LOGO_SCALE).dp, (logo.height * LOGO_SCALE).dp) ) } } From b8e6c3e7d071436c718dc7343cf0b40141959bc7 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:47:32 +0000 Subject: [PATCH 23/34] fixes automation config setting is modified checks, add dot for altered settings and add right click popup for resetting individual settings --- .../kotlin/com/lambda/config/ConfigEntry.kt | 5 +- .../com/lambda/config/entries/Property.kt | 2 +- .../com/lambda/config/entries/Setting.kt | 8 ++-- .../ConfigCategoryFallbackSerializer.kt | 2 +- .../lambda/config/settings/NumericSetting.kt | 19 ++++++-- .../lambda/config/settings/StringSetting.kt | 13 ++++- .../settings/collections/CollectionSetting.kt | 5 +- .../settings/comparable/BooleanSetting.kt | 4 +- .../config/settings/comparable/EnumSetting.kt | 2 + .../com/lambda/gui/component/Controls.kt | 17 +++++-- .../com/lambda/gui/settings/SettingRow.kt | 48 ++++++++++++++++++- 11 files changed, 104 insertions(+), 21 deletions(-) diff --git a/src/main/kotlin/com/lambda/config/ConfigEntry.kt b/src/main/kotlin/com/lambda/config/ConfigEntry.kt index 497a086b8..156005a4c 100644 --- a/src/main/kotlin/com/lambda/config/ConfigEntry.kt +++ b/src/main/kotlin/com/lambda/config/ConfigEntry.kt @@ -26,7 +26,10 @@ interface ConfigEntry { val layer: EntryLayer.Single<*> val config: Config - val isModified: Boolean + val isModified get() = isModified(core) + val isOriginalModified get() = isModified(originalCore) + + fun isModified(core: EntryCore): Boolean operator fun getValue(thisRef: Any?, property: Any?) = core.value operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) { core.value = newValue } diff --git a/src/main/kotlin/com/lambda/config/entries/Property.kt b/src/main/kotlin/com/lambda/config/entries/Property.kt index 5d458d647..2e01ffdcc 100644 --- a/src/main/kotlin/com/lambda/config/entries/Property.kt +++ b/src/main/kotlin/com/lambda/config/entries/Property.kt @@ -33,7 +33,7 @@ class Property( ) : ConfigEntry { override var core = EntryCore(defaultValue, setter(value)) override val originalCore = core - override val isModified get() = !equals.invoke(core.value, core.defaultValue) + override fun isModified(core: EntryCore) = !equals.invoke(core.value, core.defaultValue) operator fun setValue(thisRef: Any?, property: Any?, newValue: T) { core.value = setter(newValue) diff --git a/src/main/kotlin/com/lambda/config/entries/Setting.kt b/src/main/kotlin/com/lambda/config/entries/Setting.kt index e0f954f62..10a7da8e7 100644 --- a/src/main/kotlin/com/lambda/config/entries/Setting.kt +++ b/src/main/kotlin/com/lambda/config/entries/Setting.kt @@ -122,7 +122,7 @@ abstract class Setting( val holdListeners = mutableListOf<(held: Boolean) -> Unit>() val clickListeners = mutableListOf<() -> Unit>() - override val isModified get() = originalCore.value != originalCore.defaultValue + override fun isModified(core: EntryCore) = core.value != core.defaultValue override operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) { val oldValue = core.value @@ -134,12 +134,12 @@ abstract class Setting( } fun reset(silent: Boolean = false) { - if (!silent && originalCore.value == originalCore.defaultValue) { + if (!silent && !isModified) { ConfigCommand.info(notChangedMessage()) return } - if (!silent) ConfigCommand.info(resetMessage(value, originalCore.defaultValue)) - value = originalCore.defaultValue + if (!silent) ConfigCommand.info(resetMessage(value, core.defaultValue)) + value = core.defaultValue } fun restoreOriginalCore() { diff --git a/src/main/kotlin/com/lambda/config/serializers/ConfigCategoryFallbackSerializer.kt b/src/main/kotlin/com/lambda/config/serializers/ConfigCategoryFallbackSerializer.kt index a46eb33e5..4b5880463 100644 --- a/src/main/kotlin/com/lambda/config/serializers/ConfigCategoryFallbackSerializer.kt +++ b/src/main/kotlin/com/lambda/config/serializers/ConfigCategoryFallbackSerializer.kt @@ -103,7 +103,7 @@ object MultipleFallbackSerializer : FallbackSerializer>(E override fun serialize(multiple: EntryLayer.Multiple<*>, gen: JsonGenerator, ctxt: SerializationContext) { gen.writeStartObject() multiple.layers.forEach { layer -> - if (layer is EntryLayer.Single<*> && !layer.entry.isModified) return@forEach + if (layer is EntryLayer.Single<*> && !layer.entry.isOriginalModified) return@forEach val serialized = mapper.valueToTree(layer) if (serialized.isObject && serialized.isEmpty) return@forEach gen.writePOJOProperty(layer.name, serialized) diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index 64f395d32..d6092d8d6 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -43,6 +43,7 @@ import androidx.compose.ui.input.key.key import androidx.compose.ui.unit.dp import com.lambda.config.Config import com.lambda.config.ConfigEditorD5l +import com.lambda.config.EntryCore import com.lambda.config.SettingEditBuilder import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer @@ -54,6 +55,8 @@ import com.lambda.gui.component.keyboardFocusable import com.lambda.gui.component.mouseClickable import com.lambda.gui.component.scrubbable import com.lambda.gui.core.observe +import com.lambda.gui.settings.ALTERED_GAP +import com.lambda.gui.settings.AlteredDot import com.lambda.gui.settings.ROW_INSET import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look @@ -92,8 +95,8 @@ abstract class NumericSetting( var appliedOnRelease = false - override val isModified - get() = abs(originalCore.value.toDouble() - originalCore.defaultValue.toDouble()) > step.toDouble() * SAME + override fun isModified(core: EntryCore) = + abs(core.value.toDouble() - core.defaultValue.toDouble()) > step.toDouble() * SAME protected abstract fun convert(number: BigDecimal): T @@ -141,7 +144,7 @@ abstract class NumericSetting( current, ::parse, { value = it }, - Modifier.fillMaxWidth(), + Modifier.fillMaxWidth().padding(start = ROW_INSET), focused = true ) { typing = false @@ -163,6 +166,7 @@ abstract class NumericSetting( horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier .fillMaxWidth() + .padding(start = ROW_INSET) .heightIn(min = Look.rowHeight) .clip(RoundedCornerShape(Look.controlRounding)) .background(colors.track) @@ -191,7 +195,14 @@ abstract class NumericSetting( } .padding(horizontal = ROW_INSET) ) { - Text(name, Modifier.weight(1f), colors.onControl, maxLines = 1) + Row( + Modifier.weight(1f), + Arrangement.spacedBy(ALTERED_GAP), + Alignment.CenterVertically + ) { + AlteredDot(colors.onControl) + Text(name, color = colors.onControl, maxLines = 1) + } Text( text = label, modifier = Modifier.mouseClickable(keyboard = false) { typing = true }, diff --git a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt index 1a187531c..0c108d6a4 100644 --- a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt @@ -21,11 +21,13 @@ package com.lambda.config.settings import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row 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.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.lambda.brigadier.argument.greedyString @@ -40,6 +42,8 @@ import com.lambda.config.entries.SettingEntryLayer import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput import com.lambda.gui.core.observe +import com.lambda.gui.settings.ALTERED_GAP +import com.lambda.gui.settings.AlteredDot import com.lambda.gui.settings.Labeled import com.lambda.gui.settings.ROW_INSET import com.lambda.gui.settings.TEXT_FIELD_WIDTH @@ -66,7 +70,14 @@ class StringSetting( Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(1.dp) ) { - Text(name, Modifier.padding(start = ROW_INSET, top = 1.dp), maxLines = 1) + Row( + Modifier.padding(start = ROW_INSET, top = 1.dp), + Arrangement.spacedBy(ALTERED_GAP), + Alignment.CenterVertically + ) { + AlteredDot() + Text(name, maxLines = 1) + } TextInput( value, { this@StringSetting.value = it }, 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 0dbded7a6..d12059a13 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/CollectionSetting.kt @@ -22,6 +22,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.EntryCore import com.lambda.config.SettingEditBuilder import com.lambda.config.entries.ConfigEntryDsl import com.lambda.config.entries.Setting @@ -64,8 +65,8 @@ open class CollectionSetting( val deselectListeners = mutableListOf Unit>() val unsafeDeselectListeners = mutableListOf<(R) -> Unit>() - override val isModified: Boolean - get() = with(originalCore) { + override fun isModified(core: EntryCore>) = + with(core) { value.size != defaultValue.size || defaultValue.any { !value.contains(it) } } 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 64ebbe729..f0079abe0 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/BooleanSetting.kt @@ -38,6 +38,7 @@ import com.lambda.gui.component.Checkmark import com.lambda.gui.component.Text import com.lambda.gui.component.mouseClickable import com.lambda.gui.core.observe +import com.lambda.gui.settings.AlteredDot import com.lambda.gui.settings.ROW_INSET import com.lambda.gui.theme.Look import com.lambda.util.extension.CommandBuilder @@ -64,7 +65,8 @@ class BooleanSetting( .padding(horizontal = ROW_INSET) ) { Checkmark(checked) - Text(name, maxLines = 1) + Text(name, Modifier.weight(1f), maxLines = 1) + AlteredDot() } } 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 bcdb2fc8e..d4d5bfeec 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt @@ -32,6 +32,7 @@ import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer import com.lambda.gui.component.Dropdown import com.lambda.gui.core.observe +import com.lambda.gui.settings.AlteredDot import com.lambda.gui.settings.ROW_INSET import com.lambda.util.StringUtils.capitalize import com.lambda.util.extension.CommandBuilder @@ -58,6 +59,7 @@ class EnumSetting>( selected = selected, optionLabel = { it.displayValue }, modifier = Modifier.padding(start = ROW_INSET), + leading = { AlteredDot() }, onOptionHover = { option -> selectionHoverListeners.forEach { it(option) } }, onOptionClick = { option -> selectionClickListeners.forEach { it(option) } }, ) { value = it } diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt index b21c3c703..657b3a37e 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -70,6 +70,7 @@ import com.lambda.gui.theme.Look private const val TOGGLE_MILLIS = 150 private val SECTION_BAR = 1.dp private val LABEL_GAP = 3.dp +private val LEADING_GAP = 3.dp @Composable fun Button( @@ -117,7 +118,7 @@ fun Checkmark(checked: Boolean, modifier: Modifier = Modifier) { lineTo(side * 0.42f, side * 0.72f) lineTo(side * 0.78f, side * 0.28f) }, - color = colors.onPrimary, + color = colors.onControl, style = Stroke(side * 0.16f, cap = StrokeCap.Round, join = StrokeJoin.Round) ) } @@ -188,7 +189,7 @@ fun Section( .drawWithContent { drawContent() if (size.height > rowHeight.toPx() + 1f) { - drawRect(colors.primary, size = Size(SECTION_BAR.toPx(), size.height)) + drawRect(colors.secondary, size = Size(SECTION_BAR.toPx(), size.height)) } } ) { @@ -245,6 +246,7 @@ fun Dropdown( selected: T, optionLabel: (T) -> String, modifier: Modifier = Modifier, + leading: @Composable () -> Unit = {}, onOptionHover: (option: T?) -> Unit = {}, onOptionClick: (option: T) -> Unit = {}, onSelect: (T) -> Unit, @@ -257,7 +259,7 @@ fun Dropdown( DisposableEffect(Unit) { onDispose { currentOnOptionHover(null) } } - LabeledRow(label, modifier) { + LabeledRow(label, modifier, leading) { Box(Modifier.onSizeChanged { chip = it }) { Chip(onClick = menu::toggle) { SlidingText(optionLabel(selected), Modifier.weight(1f, fill = false)) @@ -290,11 +292,18 @@ fun Dropdown( fun LabeledRow( label: String, modifier: Modifier = Modifier, + leading: @Composable () -> Unit = {}, editor: @Composable RowScope.() -> Unit ) { Layout( content = { - Text(label, maxLines = 1) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(LEADING_GAP) + ) { + leading() + Text(label, maxLines = 1) + } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(LABEL_GAP), diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index edc3389bc..3e65f4e87 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -19,37 +19,53 @@ package com.lambda.gui.settings import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.tween +import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.relocation.BringIntoViewRequester import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.shape.CircleShape 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.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.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.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInWindow +import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.round import com.lambda.config.entries.Setting import com.lambda.gui.Reveal +import com.lambda.gui.component.ContextMenu import com.lambda.gui.component.LabeledRow import com.lambda.gui.component.LocalClickOnRelease import com.lambda.gui.component.LocalKeyboardReachable +import com.lambda.gui.component.MenuItem import com.lambda.gui.component.Tooltip import com.lambda.gui.component.hoverHighlight +import com.lambda.gui.component.rememberLast import com.lambda.gui.core.awaitFrames import com.lambda.gui.core.observe import com.lambda.gui.theme.LambdaTheme @@ -59,10 +75,18 @@ private const val SETTLE_MILLIS = 250L internal val TEXT_FIELD_WIDTH = 90.dp internal val NUMBER_FIELD_WIDTH = 34.dp internal val ROW_INSET = 3.dp +internal val ALTERED_GAP = 3.dp +private val ALTERED_DOT = 3.dp +private val LocalAltered = compositionLocalOf { false } + +@OptIn(ExperimentalComposeUiApi::class) @Composable fun SettingRow(setting: Setting<*>) { val disabled by observe { setting.disabled() } + val modified by observe { setting.isModified } + var origin by remember { mutableStateOf(Offset.Zero) } + var menu by remember { mutableStateOf(null) } val pointer = remember(setting) { RowPointer(setting) } DisposableEffect(pointer) { onDispose { @@ -91,12 +115,18 @@ fun SettingRow(setting: Setting<*>) { Modifier .settingCell() .bringIntoViewRequester(intoView) + .onGloballyPositioned { origin = it.positionInWindow() } .pointerInput(pointer) { awaitPointerEventScope { while (true) { val event = awaitPointerEvent(PointerEventPass.Initial) val change = event.changes.first() val inside = change.position.x in 0f..size.width.toFloat() && change.position.y in 0f..size.height.toFloat() + if (event.type == PointerEventType.Press && event.button == PointerButton.Secondary) { + change.consume() + menu = (origin + change.position).round() + continue + } when (event.type) { PointerEventType.Enter -> pointer.hovered = true PointerEventType.Exit -> pointer.hovered = false @@ -115,12 +145,21 @@ fun SettingRow(setting: Setting<*>) { ) { CompositionLocalProvider( LocalClickOnRelease provides true, - LocalKeyboardReachable provides !disabled + LocalKeyboardReachable provides !disabled, + LocalAltered provides modified ) { key(setting) { setting.Gui() } } } } + + rememberLast(menu)?.let { position -> + key(position) { + ContextMenu(menu != null, position, onDismiss = { menu = null }) { + MenuItem("Reset", enabled = modified) { setting.reset(silent = true) } + } + } + } } private class RowPointer(private val setting: Setting<*>) { @@ -162,4 +201,9 @@ internal fun Labeled( name: String, modifier: Modifier = Modifier, editor: @Composable RowScope.() -> Unit -) = LabeledRow(name, modifier.padding(start = ROW_INSET), editor) +) = LabeledRow(name, modifier.padding(start = ROW_INSET), { AlteredDot() }, editor) + +@Composable +internal fun AlteredDot(color: Color = LambdaTheme.colors.secondary) { + if (LocalAltered.current) Box(Modifier.size(ALTERED_DOT).background(color, CircleShape)) +} From 96fbbdc0fe50bc7e3e624e06fb4dbfeeb29e837b Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:11:25 +0000 Subject: [PATCH 24/34] fix outline cramping modules at the bottom of the category windows, make the altered dot stand out more in numeric settings and only allow the right click reset menu to pop up for altered settings --- .../lambda/config/settings/NumericSetting.kt | 2 +- .../com/lambda/gui/clickgui/CategoryWindow.kt | 9 ++++-- .../com/lambda/gui/settings/SettingRow.kt | 31 +++++++++++++++---- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index d6092d8d6..0100e5657 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -200,7 +200,7 @@ abstract class NumericSetting( Arrangement.spacedBy(ALTERED_GAP), Alignment.CenterVertically ) { - AlteredDot(colors.onControl) + AlteredDot(shadowed = true) Text(name, color = colors.onControl, maxLines = 1) } Text( diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index 8c6e068de..266ac6acc 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -241,6 +241,7 @@ internal fun CategoryWindow( ModuleRow( module = module, isEdited = settings.isOpen(module), + isLast = module === modules.last(), pressedIn = !inline, panel = settings.panelOf(module).takeUnless { inline }, onEdit = { settings.toggle(module) }, @@ -261,11 +262,15 @@ internal fun CategoryWindow( private fun ModuleRow( module: Module, isEdited: Boolean, + isLast: Boolean, pressedIn: Boolean, panel: SettingsPanelState?, onEdit: () -> Unit ) { val colors = LambdaTheme.colors + val end = + if (isLast && Look.outlines) Look.outlineWidth + else 0.dp val enabled by observe { module.isEnabled } val fill by animateColorAsState( @@ -310,8 +315,8 @@ private fun ModuleRow( .background(lit) .hoverHighlight(colors.raised) .then(if (Look.emboss) Modifier.background(EMBOSS) else Modifier) - .heightIn(min = Look.rowHeight) - .padding(horizontal = Look.modulePadding) + .heightIn(min = Look.rowHeight + end) + .padding(start = Look.modulePadding, end = Look.modulePadding, bottom = end) ) { SlidingText( text = module.name, diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 3e65f4e87..31f5643da 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -19,7 +19,6 @@ package com.lambda.gui.settings import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.tween -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxWidth @@ -27,7 +26,6 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.relocation.BringIntoViewRequester import androidx.compose.foundation.relocation.bringIntoViewRequester -import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider @@ -44,8 +42,10 @@ 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.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.PointerButton import androidx.compose.ui.input.pointer.PointerEventPass @@ -77,6 +77,8 @@ internal val NUMBER_FIELD_WIDTH = 34.dp internal val ROW_INSET = 3.dp internal val ALTERED_GAP = 3.dp private val ALTERED_DOT = 3.dp +private val ALTERED_SHADE = 3.5.dp +private const val ALTERED_SHADE_ALPHA = 0.3f private val LocalAltered = compositionLocalOf { false } @@ -122,7 +124,7 @@ fun SettingRow(setting: Setting<*>) { val event = awaitPointerEvent(PointerEventPass.Initial) val change = event.changes.first() val inside = change.position.x in 0f..size.width.toFloat() && change.position.y in 0f..size.height.toFloat() - if (event.type == PointerEventType.Press && event.button == PointerButton.Secondary) { + if (event.type == PointerEventType.Press && event.button == PointerButton.Secondary && modified) { change.consume() menu = (origin + change.position).round() continue @@ -156,7 +158,7 @@ fun SettingRow(setting: Setting<*>) { rememberLast(menu)?.let { position -> key(position) { ContextMenu(menu != null, position, onDismiss = { menu = null }) { - MenuItem("Reset", enabled = modified) { setting.reset(silent = true) } + MenuItem("Reset") { setting.reset(silent = true) } } } } @@ -204,6 +206,23 @@ internal fun Labeled( ) = LabeledRow(name, modifier.padding(start = ROW_INSET), { AlteredDot() }, editor) @Composable -internal fun AlteredDot(color: Color = LambdaTheme.colors.secondary) { - if (LocalAltered.current) Box(Modifier.size(ALTERED_DOT).background(color, CircleShape)) +internal fun AlteredDot(shadowed: Boolean = false) { + if (!LocalAltered.current) return + val colors = LambdaTheme.colors + Box( + Modifier.size(ALTERED_DOT).drawBehind { + val reach = ALTERED_SHADE.toPx() + if (shadowed) { + drawCircle( + Brush.radialGradient( + listOf(Color.Black.copy(alpha = ALTERED_SHADE_ALPHA), Color.Transparent), + center, + reach + ), + reach + ) + } + drawCircle(colors.secondary) + } + ) } From a584dc791f24dcf2a6608c611e1388a06943bac8 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:33:43 +0000 Subject: [PATCH 25/34] raise centered elements a small amount to favour placing odd pixels below rather than above as fonts tend to look lower if theyre centered --- .../lambda/config/settings/NumericSetting.kt | 6 ++-- .../lambda/config/settings/StringSetting.kt | 4 +-- .../settings/comparable/BooleanSetting.kt | 4 +-- .../config/settings/complex/KeybindSetting.kt | 4 +-- .../com/lambda/gui/clickgui/CategoryWindow.kt | 4 +-- .../com/lambda/gui/clickgui/SettingsPanel.kt | 3 +- .../com/lambda/gui/component/Centered.kt | 30 +++++++++++++++++++ .../com/lambda/gui/component/Controls.kt | 11 ++++--- .../kotlin/com/lambda/gui/component/Popups.kt | 8 ++--- .../kotlin/com/lambda/gui/component/Scroll.kt | 3 +- .../com/lambda/gui/component/TextInput.kt | 3 +- .../kotlin/com/lambda/gui/menu/Dialogs.kt | 4 +-- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 14 ++++----- .../lambda/gui/settings/CollectionEditor.kt | 6 ++-- .../com/lambda/gui/settings/ColorPicker.kt | 3 +- .../com/lambda/gui/settings/ModuleSettings.kt | 6 ++-- .../com/lambda/gui/settings/SettingsList.kt | 4 +-- 17 files changed, 73 insertions(+), 44 deletions(-) create mode 100644 src/main/kotlin/com/lambda/gui/component/Centered.kt diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index 0100e5657..f43daf9c8 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -31,7 +31,6 @@ 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 @@ -47,6 +46,7 @@ import com.lambda.config.EntryCore import com.lambda.config.SettingEditBuilder import com.lambda.config.entries.Setting import com.lambda.config.entries.SettingEntryLayer +import com.lambda.gui.component.Centered import com.lambda.gui.component.KeyboardFocus import com.lambda.gui.component.NumberInput import com.lambda.gui.component.Text @@ -162,7 +162,7 @@ abstract class NumericSetting( val label = remember(shown, unit) { format(shown) } val fraction by animateFloatAsState(fractionOf(shown)) Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier .fillMaxWidth() @@ -198,7 +198,7 @@ abstract class NumericSetting( Row( Modifier.weight(1f), Arrangement.spacedBy(ALTERED_GAP), - Alignment.CenterVertically + Centered.VERTICALLY ) { AlteredDot(shadowed = true) Text(name, color = colors.onControl, maxLines = 1) diff --git a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt index 0c108d6a4..ef947c8bf 100644 --- a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt @@ -27,7 +27,6 @@ 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.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.lambda.brigadier.argument.greedyString @@ -39,6 +38,7 @@ 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.Centered import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput import com.lambda.gui.core.observe @@ -73,7 +73,7 @@ class StringSetting( Row( Modifier.padding(start = ROW_INSET, top = 1.dp), Arrangement.spacedBy(ALTERED_GAP), - Alignment.CenterVertically + Centered.VERTICALLY ) { AlteredDot() Text(name, maxLines = 1) 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 f0079abe0..c964b02c3 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 androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.lambda.brigadier.argument.boolean @@ -34,6 +33,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.component.Centered import com.lambda.gui.component.Checkmark import com.lambda.gui.component.Text import com.lambda.gui.component.mouseClickable @@ -56,7 +56,7 @@ class BooleanSetting( override fun Gui() { val checked by observe { value } Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier .fillMaxWidth() 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 907ff2083..7937c388d 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -28,7 +28,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp @@ -50,6 +49,7 @@ 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.component.Centered import com.lambda.gui.component.Text import com.lambda.gui.component.Tooltip import com.lambda.gui.component.mouseClickable @@ -144,7 +144,7 @@ class KeybindSetting( Labeled(name) { Tooltip("Click, then press a key or mouse button. Backspace unbinds, Escape cancels.") { Box( - contentAlignment = Alignment.Center, + contentAlignment = Centered.BOTH, modifier = Modifier .height(Look.rowHeight) .clip(RoundedCornerShape(Look.controlRounding)) diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index 266ac6acc..ba45334aa 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -44,7 +44,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.geometry.Offset import androidx.compose.ui.geometry.Rect @@ -65,6 +64,7 @@ import com.lambda.gui.GuiConfig import com.lambda.gui.LambdaGui import com.lambda.gui.Reveal import com.lambda.gui.Snap +import com.lambda.gui.component.Centered import com.lambda.gui.component.ScrollColumn import com.lambda.gui.component.SlidingText import com.lambda.gui.component.Text @@ -297,7 +297,7 @@ private fun ModuleRow( Tooltip(module.description, Modifier.fillMaxWidth()) { Box( - contentAlignment = Alignment.CenterStart, + contentAlignment = Centered.START, modifier = Modifier .fillMaxWidth() .then( diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index 76d01f101..b374c1be9 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -71,6 +71,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp +import com.lambda.gui.component.Centered import com.lambda.gui.component.Expandable import com.lambda.gui.component.LocalPopupHost import com.lambda.gui.component.PopupHost @@ -292,7 +293,7 @@ private fun Grip( val density = LocalDensity.current val color = LambdaTheme.colors.onSurfaceVariant Box( - contentAlignment = Alignment.Center, + contentAlignment = Centered.BOTH, modifier = modifier .fillMaxWidth() .height(Look.panelPadding.coerceAtLeast(MIN_GRIP_HEIGHT)) diff --git a/src/main/kotlin/com/lambda/gui/component/Centered.kt b/src/main/kotlin/com/lambda/gui/component/Centered.kt new file mode 100644 index 000000000..aec8fd16b --- /dev/null +++ b/src/main/kotlin/com/lambda/gui/component/Centered.kt @@ -0,0 +1,30 @@ +/* + * 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.ui.Alignment +import androidx.compose.ui.BiasAlignment + +internal object Centered { + private const val RISE = -0.004f + + val VERTICALLY: Alignment.Vertical = BiasAlignment.Vertical(RISE) + val START: Alignment = BiasAlignment(-1f, RISE) + val END: Alignment = BiasAlignment(1f, RISE) + val BOTH: Alignment = BiasAlignment(0f, RISE) +} diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt index 657b3a37e..c2ecfaf2e 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -46,7 +46,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.clip import androidx.compose.ui.draw.drawWithContent @@ -88,7 +87,7 @@ fun Button( if (prominent) colors.onHeader else colors.onControl Box( - contentAlignment = Alignment.Center, + contentAlignment = Centered.BOTH, modifier = modifier .heightIn(min = Look.rowHeight + 2.dp) .clip(RoundedCornerShape(Look.controlRounding)) @@ -194,7 +193,7 @@ fun Section( } ) { Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier .fillMaxWidth() @@ -225,7 +224,7 @@ fun Chip( val colors = LambdaTheme.colors ContentColor(colors.onControl) { Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = modifier .height(Look.rowHeight) @@ -298,14 +297,14 @@ fun LabeledRow( Layout( content = { Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(LEADING_GAP) ) { leading() Text(label, maxLines = 1) } Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(LABEL_GAP), content = editor ) diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 2c9823bfd..c33d47448 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -529,7 +529,7 @@ fun MenuItem( onDispose { currentOnHover(false) } } Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, modifier = Modifier .fillMaxWidth() .hoverable(interactions) @@ -584,7 +584,7 @@ fun Submenu( } Box { Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, modifier = Modifier .fillMaxWidth() .hoverable(interactions, enabled) @@ -626,7 +626,7 @@ fun MenuHelp(text: String, label: String = "Help") { val colors = LambdaTheme.colors Tooltip(text, Modifier.fillMaxWidth()) { Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, modifier = Modifier .fillMaxWidth() .hoverHighlight(colors.raised) @@ -670,7 +670,7 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { onKeyEvent = { onDismiss != null && it.dismissOnEscape(onDismiss) }, ) { KeyboardFocus.Layer() - Box(Modifier.fillMaxSize(), Alignment.Center) { + Box(Modifier.fillMaxSize(), Centered.BOTH) { Box( Modifier .matchParentSize() diff --git a/src/main/kotlin/com/lambda/gui/component/Scroll.kt b/src/main/kotlin/com/lambda/gui/component/Scroll.kt index f0086104b..cb07cf709 100644 --- a/src/main/kotlin/com/lambda/gui/component/Scroll.kt +++ b/src/main/kotlin/com/lambda/gui/component/Scroll.kt @@ -37,7 +37,6 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.input.pointer.PointerEventPass @@ -73,7 +72,7 @@ fun Scrollbar(adapter: ScrollbarAdapter, modifier: Modifier) { Box(modifier) { VerticalScrollbar( adapter = adapter, - modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), + modifier = Modifier.align(Centered.END).fillMaxHeight(), style = ScrollbarStyle( minimalHeight = 12.dp, thickness = 2.dp, diff --git a/src/main/kotlin/com/lambda/gui/component/TextInput.kt b/src/main/kotlin/com/lambda/gui/component/TextInput.kt index ea13cd7b4..fc6f8490a 100644 --- a/src/main/kotlin/com/lambda/gui/component/TextInput.kt +++ b/src/main/kotlin/com/lambda/gui/component/TextInput.kt @@ -30,7 +30,6 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester @@ -136,7 +135,7 @@ fun TextInput( } .padding(horizontal = 3.dp, vertical = 1.dp), decorationBox = { innerTextField -> - Box(contentAlignment = Alignment.CenterStart) { + Box(contentAlignment = Centered.START) { if (field.text.isEmpty()) { Text( placeholder, diff --git a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt index 598852fea..e36e7ef00 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -30,7 +30,6 @@ 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 @@ -45,6 +44,7 @@ import com.lambda.config.automation.UserAutomationConfig import com.lambda.core.Loader import com.lambda.event.EventFlow import com.lambda.gui.component.Button +import com.lambda.gui.component.Centered import com.lambda.gui.component.Dialog import com.lambda.gui.component.Text import com.lambda.gui.component.TextInput @@ -190,7 +190,7 @@ internal fun LoaderPromptDialog(prompt: AutoUpdater.Prompt) { Row( Modifier.fillMaxWidth().padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Alignment.CenterVertically + verticalAlignment = Centered.VERTICALLY ) { Button( label = when (prompt) { diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index 7d025324e..4ed14b798 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -41,7 +41,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.focus.FocusRequester import androidx.compose.ui.focus.focusRequester @@ -74,6 +73,7 @@ import com.lambda.gui.LambdaGui import com.lambda.gui.clickgui.CLICK_GUI_CATEGORIES import com.lambda.gui.clickgui.ClickGuiDialog import com.lambda.gui.clickgui.ClickGuiState +import com.lambda.gui.component.Centered import com.lambda.gui.component.Menu import com.lambda.gui.component.MenuDivider import com.lambda.gui.component.MenuItem @@ -122,7 +122,7 @@ internal fun MenuBar(modifier: Modifier = Modifier) { var menus by remember { mutableStateOf(IntSize.Zero) } var search by remember { mutableStateOf(IntSize.Zero) } Box( - contentAlignment = Alignment.Center, + contentAlignment = Centered.BOTH, modifier = modifier .fillMaxWidth() .height(MENU_BAR_HEIGHT) @@ -132,10 +132,10 @@ internal fun MenuBar(modifier: Modifier = Modifier) { ) { Row( Modifier - .align(Alignment.CenterStart) + .align(Centered.START) .fillMaxHeight() .onSizeChanged { menus = it }, - verticalAlignment = Alignment.CenterVertically + verticalAlignment = Centered.VERTICALLY ) { BarMenu("Lambda", icon = "textures/lambda.png") { LambdaMenu() } BarMenu("Modules") { ModulesMenu() } @@ -164,7 +164,7 @@ private fun BarMenu( ) { val menu = remember { MenuState() } Box( - contentAlignment = Alignment.Center, + contentAlignment = Centered.BOTH, modifier = Modifier .fillMaxHeight() .hoverHighlight(LambdaTheme.colors.controlSelected) @@ -172,7 +172,7 @@ private fun BarMenu( .padding(horizontal = 6.dp) ) { Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(3.dp) ) { if (icon != null) { @@ -277,7 +277,7 @@ private fun ResultRow( } val point by rememberUpdatedState(onPoint) Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, modifier = Modifier .fillMaxWidth() .widthIn(min = SEARCH_WIDTH) diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt index b4382e18f..8a0b7b598 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -40,7 +40,6 @@ 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 @@ -48,6 +47,7 @@ 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.Centered import com.lambda.gui.component.Chip import com.lambda.gui.component.Dialog import com.lambda.gui.component.Ellipsis @@ -105,7 +105,7 @@ private fun CollectionWindow( Column(Modifier.width(360.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { Text(setting.name) Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(3.dp) ) { TextInput( @@ -208,7 +208,7 @@ private fun Pane( ) { items(entries) { entry -> Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier .fillMaxWidth() diff --git a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt index 869c99f04..6612c55e6 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt @@ -62,6 +62,7 @@ import com.lambda.gui.theme.Type import com.lambda.util.math.toCompose import kotlin.math.roundToInt import java.awt.Color as AwtColor +import com.lambda.gui.component.Centered private val PICKER_WIDTH = 130.dp private val HUES = (0..6).map { Color.hsv(it * 60f % 360f, 1f, 1f) } @@ -177,7 +178,7 @@ private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { } } Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(4.dp) ) { Text("Hex", color = colors.onSurfaceVariant, style = Type.label) diff --git a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt index 99d7731ed..f78267bd4 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt @@ -33,7 +33,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset @@ -47,6 +46,7 @@ import com.lambda.config.hasVisibleSettings import com.lambda.config.holds import com.lambda.gui.Reveal import com.lambda.gui.component.Button +import com.lambda.gui.component.Centered import com.lambda.gui.component.Dropdown import com.lambda.gui.component.LocalClickOnRelease import com.lambda.gui.component.ScrollColumn @@ -145,7 +145,7 @@ private fun PageStrip( val isSelected = page == selected val line by animateColorAsState(if (isSelected) colors.secondary else colors.raised) Box( - contentAlignment = Alignment.Center, + contentAlignment = Centered.BOTH, modifier = Modifier .weight(page.title.length + 2f) .height(Look.rowHeight + 1.dp) @@ -179,7 +179,7 @@ private fun SettingsPage(module: Module) { else { Box( Modifier.fillMaxWidth().padding(vertical = 4.dp), - contentAlignment = Alignment.Center + contentAlignment = Centered.BOTH ) { Text("No settings", color = LambdaTheme.colors.onSurfaceVariant) } diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt index 0a17882c9..6d9dd5e74 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -42,7 +42,6 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.onSizeChanged @@ -55,6 +54,7 @@ import com.lambda.config.entries.Setting import com.lambda.config.hasVisibleSettings import com.lambda.config.holds import com.lambda.gui.Reveal +import com.lambda.gui.component.Centered import com.lambda.gui.component.Chevron import com.lambda.gui.component.ContentColor import com.lambda.gui.component.Expandable @@ -142,7 +142,7 @@ private fun TabPicker(names: List, selected: String, onSelect: (String) Box(Modifier.fillMaxWidth().onSizeChanged { band = it }) { ContentColor(colors.onHeader) { Row( - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Centered.VERTICALLY, horizontalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier .fillMaxWidth() From d1930a3fbd4626ebd457af8506262e13865ddac3 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:43:53 +0000 Subject: [PATCH 26/34] post-merge cleanup --- .../lambda/config/settings/StringSetting.kt | 3 +- .../collections/BlockCollectionSetting.kt | 2 +- .../collections/ItemCollectionSetting.kt | 1 + src/main/kotlin/com/lambda/gui/GuiConfig.kt | 186 +++++------ .../lambda/gui/components/ClickGuiLayout.kt | 0 .../com/lambda/gui/components/HudGuiLayout.kt | 301 ------------------ src/main/kotlin/com/lambda/gui/hud/Hud.kt | 9 +- .../kotlin/com/lambda/module/HudModule.kt | 14 +- .../module/modules/client/AutoUpdater.kt | 7 - .../module/modules/client/ModuleNotifier.kt | 2 +- .../com/lambda/module/modules/hud/Armor.kt | 6 +- .../com/lambda/module/modules/hud/Fps.kt | 4 +- .../lambda/module/modules/hud/ModuleList.kt | 4 +- .../com/lambda/module/modules/hud/Tps.kt | 10 +- .../lambda/module/modules/hud/Watermark.kt | 4 - 15 files changed, 127 insertions(+), 426 deletions(-) delete mode 100644 src/main/kotlin/com/lambda/gui/components/ClickGuiLayout.kt delete mode 100644 src/main/kotlin/com/lambda/gui/components/HudGuiLayout.kt diff --git a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt index 283c0d2a0..cf2ab0e2c 100644 --- a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt @@ -56,10 +56,9 @@ fun Config.stringSetting( 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) } /** * @see [com.lambda.config.Config] 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 758d3ed58..dcbb39655 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/BlockCollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/BlockCollectionSetting.kt @@ -23,6 +23,7 @@ import com.lambda.config.entries.ConfigEntryDsl import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.serializers.BlockSerializer import net.minecraft.block.Block +import net.minecraft.item.ItemStack import net.minecraft.registry.Registries @ConfigEntryDsl @@ -34,7 +35,6 @@ fun Config.blockCollectionSetting( description: String = "", visibility: () -> Boolean = { true } ) = setting(name) { layer -> BlockCollectionSetting(name, description, this, layer, visibility, immutableCollection, defaultValue.toMutableList()) } -import net.minecraft.item.ItemStack class BlockCollectionSetting( name: String, 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 3874260e2..dba8476cf 100644 --- a/src/main/kotlin/com/lambda/config/settings/collections/ItemCollectionSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/collections/ItemCollectionSetting.kt @@ -23,6 +23,7 @@ import com.lambda.config.entries.ConfigEntryDsl import com.lambda.config.entries.SettingEntryLayer import com.lambda.config.serializers.ItemSerializer import net.minecraft.item.Item +import net.minecraft.item.ItemStack import net.minecraft.registry.Registries @ConfigEntryDsl diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index 31bdc503f..7a23c634a 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -30,8 +30,16 @@ import com.lambda.config.entries.onHold import com.lambda.config.entries.onValueChange import com.lambda.config.entries.onValueChangeUnsafe import com.lambda.config.settings.appliedOnRelease +import com.lambda.config.settings.collections.collectionSetting import com.lambda.config.settings.comparable.EnumSetting +import com.lambda.config.settings.comparable.boolSetting +import com.lambda.config.settings.comparable.enumSetting import com.lambda.config.settings.comparable.onSelectionHover +import com.lambda.config.settings.complex.colorSetting +import com.lambda.config.settings.complex.setting +import com.lambda.config.settings.functionSetting +import com.lambda.config.settings.numeric.floatSetting +import com.lambda.config.settings.numeric.intSetting import com.lambda.core.Loadable import com.lambda.event.events.ComposeEvent import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe @@ -68,7 +76,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @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) + @Tab(GENERAL_TAB) val setLambdaWindowIcon by boolSetting("Set Lambda Window Icon", true) .onValueChange { _, to -> if (to) setLambdaWindowIcon() else { @@ -79,26 +87,26 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { } } @JvmStatic - @Tab(GENERAL_TAB) val setLambdaWindowTitle by setting("Set Lambda Window Title", true) + @Tab(GENERAL_TAB) val setLambdaWindowTitle by boolSetting("Set Lambda Window Title", true) .onValueChange { _, _ -> mc.updateWindowTitle() } - @Tab(GENERAL_TAB) val lambdaTitleAppendixName by setting("Append Username", true) { setLambdaWindowTitle } + @Tab(GENERAL_TAB) val lambdaTitleAppendixName by boolSetting("Append Username", true) { setLambdaWindowTitle } .onValueChange { _, _ -> mc.updateWindowTitle() } - @Tab(GENERAL_TAB) val keepSettingsOpen by setting("Keep Settings Open", false, "Leaves a module's settings open when the click GUI closes, so they are still there when it opens again") - @Tab(GENERAL_TAB) val hoverSubmenus by setting("Open Submenus On Hover", true, "Opens a submenu when the pointer is over its row. When off, a submenu opens on a click.") - @Tab(GENERAL_TAB) private val resetWindowLayout by setting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded") + @Tab(GENERAL_TAB) val keepSettingsOpen by boolSetting("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 hoverSubmenus by boolSetting("Open Submenus On Hover", true, "Opens a submenu when the pointer is over its row. When off, a submenu opens on a click.") + @Tab(GENERAL_TAB) private val resetWindowLayout by functionSetting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded") - @Tab(SNAPPING_TAB) val snapEnabled by setting("Enable Snapping", true, "Master toggle for snapping HUD elements and click GUI windows into line when they are dragged") + @Tab(SNAPPING_TAB) val snapEnabled by boolSetting("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", 5f, 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 } + @Tab(SNAPPING_TAB) val showSnapLines by boolSetting("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 floatSetting("Grid Size", 5f, 2f..128f, 1f, "Grid step") { snapEnabled } + @Tab(SNAPPING_TAB) val snapToEdges by boolSetting("Snap To Element Edges", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToCenters by boolSetting("Snap To Element Centers", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToScreenCenter by boolSetting("Snap To Screen Center", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToGrid by boolSetting("Snap To Grid", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceElement by floatSetting("Snap Distance (Elements)", 20f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceScreen by floatSetting("Snap Distance (Screen Center)", 14f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceGrid by floatSetting("Snap Distance (Grid)", 12f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapLineColor by colorSetting("Snap Line Color", Color(255, 160, 0, 220)) { snapEnabled && showSnapLines } private enum class ThemeMode(override val displayName: String) : NamedEnum { Auto("Auto"), @@ -106,63 +114,63 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { Light("Light"), } - @Tab(STYLE_TAB) private val themeMode by setting("Theme", ThemeMode.Dark, "Auto follows the theme of your operating system") - @Tab(STYLE_TAB) 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") - @Tab(STYLE_TAB) val fontSize by setting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") - @Tab(STYLE_TAB) val scale by setting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() + @Tab(STYLE_TAB) private val themeMode by enumSetting("Theme", ThemeMode.Dark, "Auto follows the theme of your operating system") + @Tab(STYLE_TAB) val font by enumSetting("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") + @Tab(STYLE_TAB) val fontSize by floatSetting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") + @Tab(STYLE_TAB) val scale by floatSetting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimBackground by setting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimStrength by setting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blur by setting("Blur", true, "Blurs what is behind windows for a frosted glass look") - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blurRadius by setting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val layerFade by setting("Layer Fade", 0.5f, 0f..1f, 0.05f, "How far the interface fades out underneath a panel, menu or window opened over it, letting the game show there instead so the two do not run together") { blur } - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glow by setting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowRadius by setting("Glow Radius", 17f, 1f..100f, 1f) { glow } - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowIntensity by setting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimBackground by boolSetting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimStrength by floatSetting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blur by boolSetting("Blur", true, "Blurs what is behind windows for a frosted glass look") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blurRadius by floatSetting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val layerFade by floatSetting("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 } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glow by boolSetting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowRadius by floatSetting("Glow Radius", 17f, 1f..100f, 1f) { glow } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowIntensity by floatSetting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val windowRounding by setting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val panelRounding by setting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val menuRounding by setting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val controlRounding by setting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlines by setting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlineWidth by setting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val shadows by setting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val emboss by setting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val windowRounding by floatSetting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val panelRounding by floatSetting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val menuRounding by floatSetting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val controlRounding by floatSetting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlines by boolSetting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlineWidth by floatSetting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val shadows by boolSetting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val emboss by boolSetting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val elementHeight by setting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowWidth by setting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingsWidth by setting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowGap by setting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowTop by setting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val modulePadding by setting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val panelPadding by setting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingSpacing by setting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val groupIndent by setting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val inlineSettings by setting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val multipleSettings by setting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val elementHeight by floatSetting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowWidth by floatSetting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingsWidth by floatSetting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowGap by floatSetting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowTop by floatSetting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val modulePadding by floatSetting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val panelPadding by floatSetting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingSpacing by floatSetting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val groupIndent by floatSetting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val inlineSettings by boolSetting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val multipleSettings by boolSetting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animations by setting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animationSpeed by setting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openAnimation by setting("Open Animation", true, "Animates the click GUI in when it opens") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openStyle by setting("Open Style", setOf(GuiTransition.Unfold), GuiTransition.entries.toSet(), "What the click GUI does as it comes in, any of them together: its windows unfold out of their headers, and all of it fades, slides down or zooms in") { animations && openAnimation } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeAnimation by setting("Close Animation", true, "Animates the click GUI out when it closes. The game has the mouse and keyboard back at once: the animation only plays over it") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeStyle by setting("Close Style", setOf(GuiTransition.Unfold, GuiTransition.Fade), GuiTransition.entries.toSet(), "What the click GUI does as it goes out, any of them together: its windows fold into their headers, and all of it fades, slides up or zooms out") { animations && closeAnimation } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val interruptedAnimation by setting("Interrupted Animation", GuiInterrupt.Reverse, "What happens when the click GUI is opened or closed again before its animation is done: it turns around from where it is, or skips to the end and plays the other one in full") { animations && (openAnimation || closeAnimation) } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val windowAnimations by setting("Window Animations", true, "Category windows unfold out of their headers") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val panelAnimations by setting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val pageAnimations by setting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val smoothScrolling by setting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val scrollSpeed by setting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val tooltipDelay by setting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animations by boolSetting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animationSpeed by floatSetting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openAnimation by boolSetting("Open Animation", true, "Animates the click GUI in when it opens") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openStyle by collectionSetting("Open Style", setOf(GuiTransition.Unfold), GuiTransition.entries.toSet(), "What the click GUI does as it comes in, any of them together: its windows unfold out of their headers, and all of it fades, slides down or zooms in") { animations && openAnimation } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeAnimation by boolSetting("Close Animation", true, "Animates the click GUI out when it closes. The game has the mouse and keyboard back at once: the animation only plays over it") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeStyle by collectionSetting("Close Style", setOf(GuiTransition.Unfold, GuiTransition.Fade), GuiTransition.entries.toSet(), "What the click GUI does as it goes out, any of them together: its windows fold into their headers, and all of it fades, slides up or zooms out") { animations && closeAnimation } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val interruptedAnimation by enumSetting("Interrupted Animation", GuiInterrupt.Reverse, "What happens when the click GUI is opened or closed again before its animation is done: it turns around from where it is, or skips to the end and plays the other one in full") { animations && (openAnimation || closeAnimation) } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val windowAnimations by boolSetting("Window Animations", true, "Category windows unfold out of their headers") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val panelAnimations by boolSetting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val pageAnimations by boolSetting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val smoothScrolling by boolSetting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val scrollSpeed by floatSetting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val tooltipDelay by intSetting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationScale by setting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface").previewsNotifications() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationWidth by setting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines").previewsNotifications() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSide by setting("Notification Side", NotificationSide.Right, "Which side of the screen notifications slide in from").previewsNotificationOptions() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationHeight by setting("Notification Height", 0f, 0f..1f, 0.05f, "Where on that side the first notification sits. 0 is the bottom of the screen and 1 the top").previewsNotifications() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationFlow by setting("Notification Direction", NotificationFlow.Up, "Which way the stack grows: each new notification appears on this side of the ones already showing. They leave the other way, and the stack is kept on the screen").previewsNotificationOptions() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSeconds by setting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it leaves") - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationLimit by setting("Notification Limit", NotificationLimit.Count, "Count lets the oldest go once more than Max Notifications are showing. Fit Screen shows as many as fit between Notification Height and the edge of the screen the stack grows towards, and the oldest goes when a new one would not fit").previewsNotificationOptions() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val maxNotifications by setting("Max Notifications", 5, 1..12, 1, "How many notifications show at once before the oldest leaves") { notificationLimit == NotificationLimit.Count }.previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationScale by floatSetting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationWidth by floatSetting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSide by enumSetting("Notification Side", NotificationSide.Right, "Which side of the screen notifications slide in from").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationHeight by floatSetting("Notification Height", 0f, 0f..1f, 0.05f, "Where on that side the first notification sits. 0 is the bottom of the screen and 1 the top").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationFlow by enumSetting("Notification Direction", NotificationFlow.Up, "Which way the stack grows: each new notification appears on this side of the ones already showing. They leave the other way, and the stack is kept on the screen").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSeconds by floatSetting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it leaves") + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationLimit by enumSetting("Notification Limit", NotificationLimit.Count, "Count lets the oldest go once more than Max Notifications are showing. Fit Screen shows as many as fit between Notification Height and the edge of the screen the stack grows towards, and the oldest goes when a new one would not fit").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val maxNotifications by intSetting("Max Notifications", 5, 1..12, 1, "How many notifications show at once before the oldest leaves") { notificationLimit == NotificationLimit.Count }.previewsNotifications() @Tab(STYLE_TAB) @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( PaletteSettings( @@ -338,26 +346,26 @@ class PaletteSettings( glowA: Color, glowB: Color, ) : ConfigBlock { - private val primary by c.setting("Primary", primary, "Accent colour: the fill of sliders and ticked boxes") - private val secondary by c.setting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") - private val surface by c.setting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") - private val panel by c.setting("Panel", panel, "Fill of settings panels, menus and dialogs") - private val inset by c.setting("Inset", inset, "Shade behind settings that open under their module, and over the module whose settings are open beside it") - private val onSurface by c.setting("On Surface", onSurface, "Text on windows") - private val onSurfaceVariant by c.setting("On Surface Variant", onSurfaceVariant, "Subdued text on windows") - private val header by c.setting("Header", header) - private val onHeader by c.setting("On Header", onHeader) - private val moduleEnabled by c.setting("Module Enabled", moduleEnabled) - private val onModuleEnabled by c.setting("On Module Enabled", onModuleEnabled) - private val control by c.setting("Control", control, "Fill of dropdowns, buttons and key caps") - private val controlSelected by c.setting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") - private val onControl by c.setting("On Control", onControl) - private val track by c.setting("Slider Track", track) - private val input by c.setting("Text Field", input) - private val border by c.setting("Border", border) - private val textShadow by c.setting("Text Shadow", textShadow) - val glowA by c.setting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { GuiConfig.glow } - val glowB by c.setting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { GuiConfig.glow } + private val primary by c.colorSetting("Primary", primary, "Accent colour: the fill of sliders and ticked boxes") + private val secondary by c.colorSetting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") + private val surface by c.colorSetting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") + private val panel by c.colorSetting("Panel", panel, "Fill of settings panels, menus and dialogs") + private val inset by c.colorSetting("Inset", inset, "Shade behind settings that open under their module, and over the module whose settings are open beside it") + private val onSurface by c.colorSetting("On Surface", onSurface, "Text on windows") + private val onSurfaceVariant by c.colorSetting("On Surface Variant", onSurfaceVariant, "Subdued text on windows") + private val header by c.colorSetting("Header", header) + private val onHeader by c.colorSetting("On Header", onHeader) + private val moduleEnabled by c.colorSetting("Module Enabled", moduleEnabled) + private val onModuleEnabled by c.colorSetting("On Module Enabled", onModuleEnabled) + private val control by c.colorSetting("Control", control, "Fill of dropdowns, buttons and key caps") + private val controlSelected by c.colorSetting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") + private val onControl by c.colorSetting("On Control", onControl) + private val track by c.colorSetting("Slider Track", track) + private val input by c.colorSetting("Text Field", input) + private val border by c.colorSetting("Border", border) + private val textShadow by c.colorSetting("Text Shadow", textShadow) + val glowA by c.colorSetting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { GuiConfig.glow } + val glowB by c.colorSetting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { GuiConfig.glow } fun toPalette() = Palette( 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 e69de29bb..000000000 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 83b46fb78..000000000 --- a/src/main/kotlin/com/lambda/gui/components/HudGuiLayout.kt +++ /dev/null @@ -1,301 +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.config.settings.comparable.boolSetting -import com.lambda.config.settings.complex.colorSetting -import com.lambda.config.settings.numeric.floatSetting -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 boolSetting("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 floatSetting("HUD Corner Radius", 6.0f, 0.5f..24.0f, 0.5f) - val hudOutlineHaloColor by colorSetting("HUD Corner Halo Color", Color(140, 140, 140, 90)) - val hudOutlineBorderColor by colorSetting("HUD Corner Border Color", Color(190, 190, 190, 200)) - val hudOutlineHaloThickness by floatSetting("HUD Corner Halo Thickness", 3.0f, 1.0f..6.0f, 0.5f) - val hudOutlineBorderThickness by floatSetting("HUD Corner Border Thickness", 1.5f, 1.0f..4.0f, 0.5f) - val hudOutlineCornerInflate by floatSetting("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/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt index 421dfd8ff..3a941dde0 100644 --- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -41,6 +41,9 @@ 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.config.settings.comparable.boolSetting +import com.lambda.config.settings.complex.colorSetting +import com.lambda.config.settings.numeric.floatSetting import com.lambda.core.Loadable import com.lambda.gui.GuiScreen import com.lambda.gui.component.Text @@ -57,9 +60,9 @@ private val HUD_TEXT_SHADOW = Color.Black.copy(alpha = 0.75f) private val ELEMENT_PADDING = 1.dp object HudConfig : Loadable, Config("HUD", HudCategory) { - val showInScreens by setting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The HUD editor always shows them.") - val textColor by setting("Text Color", java.awt.Color.WHITE, "Colour of HUD text") - val scale by setting("Scale", 1f, 0.5f..3f, 0.05f, "Size of HUD text") + val showInScreens by boolSetting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The HUD editor always shows them.") + val textColor by colorSetting("Text Color", java.awt.Color.WHITE, "Colour of HUD text") + val scale by floatSetting("Scale", 1f, 0.5f..3f, 0.05f, "Size of HUD text") } internal object Hud { diff --git a/src/main/kotlin/com/lambda/module/HudModule.kt b/src/main/kotlin/com/lambda/module/HudModule.kt index 53cd02ed9..982ca5ecf 100644 --- a/src/main/kotlin/com/lambda/module/HudModule.kt +++ b/src/main/kotlin/com/lambda/module/HudModule.kt @@ -20,7 +20,7 @@ package com.lambda.module import androidx.compose.runtime.Composable import com.lambda.config.settings.complex.Bind import com.lambda.config.settings.complex.colorSetting -import com.lambda.gui.Layout +import com.lambda.config.settings.numeric.floatSetting import java.awt.Color abstract class HudModule( @@ -30,6 +30,9 @@ abstract class HudModule( alwaysListening: Boolean = false, enabledByDefault: Boolean = false, defaultKeybind: Bind = Bind.EMPTY, + defaultScale: Float = 1f, + defaultAnchorX: Float = DEFAULT_ANCHOR, + defaultAnchorY: Float? = null, ) : Module( name, description, @@ -38,17 +41,18 @@ abstract class HudModule( enabledByDefault, defaultKeybind = defaultKeybind ) { - val backgroundColor = setting("Background Color", Color(0, 0, 0, 0)) - val scale by setting("Scale", defaultScale, 0.25f..5f, 0.05f, "Size of this element, on top of the Scale in HUD Settings") + val backgroundColor = colorSetting("Background Color", Color(0, 0, 0, 0)) + val scale by floatSetting("Scale", defaultScale, 0.25f..5f, 0.05f, "Size of this element, on top of the Scale in HUD Settings") - var anchorX by setting("HUD X", defaultAnchorX, 0f..1f, 0.001f) { false } - var anchorY by setting("HUD Y", defaultAnchorY ?: (DEFAULT_ANCHOR + DEFAULT_SPACING * created++).coerceAtMost(1f), 0f..1f, 0.001f) { false } + var anchorX by floatSetting("HUD X", defaultAnchorX, 0f..1f, 0.001f) { false } + var anchorY by floatSetting("HUD Y", defaultAnchorY ?: (DEFAULT_ANCHOR + DEFAULT_SPACING * created++).coerceAtMost(1f), 0f..1f, 0.001f) { false } @Composable abstract fun Content() private companion object { const val DEFAULT_ANCHOR = 0.01f + const val DEFAULT_SPACING = 0.06f var created = 0 } diff --git a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt index 27f084131..7e059d880 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt @@ -20,13 +20,6 @@ package com.lambda.module.modules.client import com.lambda.Lambda.mc import com.lambda.config.settings.comparable.boolSetting import com.lambda.config.settings.comparable.enumSetting -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 diff --git a/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt b/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt index b2f55a82d..4284d181e 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/ModuleNotifier.kt @@ -41,7 +41,7 @@ object ModuleNotifier : Module( tag = ModuleTag.CLIENT, enabledByDefault = true ) { - var notifyTarget by collectionSetting("Notify Target", setOf(NotifyTarget.ActionBar), NotifyTarget.entries.toSet(), description = "Where to send notifications when modules are toggled") + var notifyTarget by collectionSetting("Notify Target", setOf(NotifyTarget.Notification), NotifyTarget.entries.toSet(), description = "Where to send notifications when modules are toggled") enum class NotifyTarget(override val displayName: String, override val description: String) : Describable, NamedEnum { Chat("Chat", "Sends a message to chat when a module is toggled"), diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt index d65f8cd53..46bb4088d 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt @@ -23,6 +23,8 @@ 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.config.settings.comparable.enumSetting +import com.lambda.config.settings.numeric.floatSetting import com.lambda.gui.component.ItemIcon import com.lambda.gui.core.observe import com.lambda.gui.core.observeSafe @@ -43,8 +45,8 @@ object Armor : HudModule( 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 layout by enumSetting("Layout", Layout.Horizontal) + private val iconSize by floatSetting("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( 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 9f16cf2dd..266cfb64d 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Fps.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Fps.kt @@ -17,10 +17,10 @@ package com.lambda.module.modules.hud -import com.lambda.config.settings.comparable.boolSetting -import com.lambda.config.settings.numeric.intSetting import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import com.lambda.config.settings.comparable.boolSetting +import com.lambda.config.settings.numeric.intSetting import com.lambda.event.events.RenderEvent import com.lambda.event.listener.SafeListener.Companion.listen import com.lambda.gui.core.observe 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 de8f107ef..51bfe651f 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt @@ -17,14 +17,12 @@ package com.lambda.module.modules.hud -import com.lambda.config.settings.comparable.boolSetting -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.comparable.boolSetting import com.lambda.config.settings.complex.Bind import com.lambda.gui.core.observe import com.lambda.gui.hud.HudText 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 a2d65569f..0b1c70779 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt @@ -17,12 +17,6 @@ package com.lambda.module.modules.hud -import com.lambda.config.settings.comparable.boolSetting -import com.lambda.config.settings.comparable.enumSetting -import com.lambda.config.settings.numeric.floatSetting -import com.lambda.config.settings.numeric.intSetting -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 @@ -36,6 +30,10 @@ 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.config.settings.comparable.boolSetting +import com.lambda.config.settings.comparable.enumSetting +import com.lambda.config.settings.numeric.floatSetting +import com.lambda.config.settings.numeric.intSetting import com.lambda.gui.core.observe import com.lambda.gui.hud.HudConfig import com.lambda.gui.hud.HudText 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 465baa3a8..e97ea6acc 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt @@ -23,10 +23,6 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.lambda.gui.component.rememberTexture -import com.lambda.config.settings.numeric.floatSetting -import com.lambda.graphics.texture.TextureOwner.upload -import com.lambda.gui.dsl.ImGuiBuilder -import com.lambda.imgui.ImGui import com.lambda.module.HudModule import com.lambda.module.ModuleTag From 68ec1432f3223e1a3c992cb734d695d962d1d0c6 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:34:09 +0000 Subject: [PATCH 27/34] cleanup, dialog animations and fixes --- .../graphics/mc/LambdaRenderPipelines.kt | 2 +- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 3 +- src/main/kotlin/com/lambda/gui/LambdaGui.kt | 82 ++++++++++++------- .../com/lambda/gui/clickgui/ClickGui.kt | 5 +- .../com/lambda/gui/component/Keyboard.kt | 4 +- .../com/lambda/gui/component/Pointer.kt | 4 +- .../kotlin/com/lambda/gui/component/Popups.kt | 54 +++++++----- .../com/lambda/gui/component/Surface.kt | 34 ++++---- src/main/kotlin/com/lambda/gui/core/Frames.kt | 8 +- .../kotlin/com/lambda/gui/core/Observe.kt | 7 +- .../kotlin/com/lambda/gui/core/Retained.kt | 51 ------------ .../kotlin/com/lambda/gui/menu/Dialogs.kt | 18 ++-- .../com/lambda/gui/render/GuiCompositor.kt | 26 +++--- .../lambda/gui/settings/CollectionEditor.kt | 19 ++++- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 16 ++-- .../lambda/shaders/core/gui_composite.fsh | 14 ++-- 16 files changed, 177 insertions(+), 170 deletions(-) delete mode 100644 src/main/kotlin/com/lambda/gui/core/Retained.kt diff --git a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt index 6eeff19c9..6a6808bda 100644 --- a/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt +++ b/src/main/kotlin/com/lambda/graphics/mc/LambdaRenderPipelines.kt @@ -337,7 +337,7 @@ object LambdaRenderPipelines : Loadable { guiPass( "gui_composite", Identifier.of("lambda", "core/gui_composite"), - samplers = listOf("GuiSampler", "BackdropSampler", "HaloSampler"), + samplers = listOf("GuiSampler", "BackdropSampler", "GlowSampler"), uniform = "GuiEffects", blend = BlendFunction.TRANSLUCENT_PREMULTIPLIED_ALPHA ) diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index 7a23c634a..622dbf6f8 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -123,7 +123,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimStrength by floatSetting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blur by boolSetting("Blur", true, "Blurs what is behind windows for a frosted glass look") @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blurRadius by floatSetting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val layerFade by floatSetting("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 } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val layerFade by floatSetting("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") @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glow by boolSetting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowRadius by floatSetting("Glow Radius", 17f, 1f..100f, 1f) { glow } @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowIntensity by floatSetting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } @@ -159,6 +159,7 @@ object GuiConfig : Loadable, Config("GUI", GuiCategory) { @Tab(STYLE_TAB) @Group(MOTION_GROUP) val windowAnimations by boolSetting("Window Animations", true, "Category windows unfold out of their headers") { animations } @Tab(STYLE_TAB) @Group(MOTION_GROUP) val panelAnimations by boolSetting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } @Tab(STYLE_TAB) @Group(MOTION_GROUP) val pageAnimations by boolSetting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val dialogAnimations by boolSetting("Dialog Animations", true, "Dialogs such as GUI Settings grow out of the centre of the screen as they open, and shrink back as they close") { animations } @Tab(STYLE_TAB) @Group(MOTION_GROUP) val smoothScrolling by boolSetting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") @Tab(STYLE_TAB) @Group(MOTION_GROUP) val scrollSpeed by floatSetting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") @Tab(STYLE_TAB) @Group(MOTION_GROUP) val tooltipDelay by intSetting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index ccf2c3eb9..5a7528e76 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -33,6 +33,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.layer.GraphicsLayer import androidx.compose.ui.graphics.rememberGraphicsLayer +import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.unit.IntSize import com.lambda.Lambda.LOG @@ -50,8 +51,8 @@ import com.lambda.gui.core.ComposeSlot import com.lambda.gui.core.GameClipboard import com.lambda.gui.core.LocalObservations import com.lambda.gui.core.LocalPresence +import com.lambda.gui.core.LocalShown import com.lambda.gui.core.Observations -import com.lambda.gui.core.Retained import com.lambda.gui.core.SceneHost import com.lambda.gui.core.SceneInput import com.lambda.gui.hud.Hud @@ -59,6 +60,7 @@ 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.PickerWarmUp import com.lambda.gui.settings.SettingsList import com.lambda.gui.theme.GuiInterrupt import com.lambda.gui.theme.GuiTransition @@ -120,10 +122,9 @@ object LambdaGui : Loadable { if (leaving) GuiConfig.closeStyle else GuiConfig.openStyle internal val unfoldsOpen - get() = - GuiConfig.animations && - GuiConfig.openAnimation && - GuiTransition.Unfold in GuiConfig.openStyle + get() = GuiConfig.animations && + GuiConfig.openAnimation && + GuiTransition.Unfold in GuiConfig.openStyle private val showsClickGui get() = screen == Screen.ClickGui || leaving internal val foldsClosed @@ -159,17 +160,33 @@ object LambdaGui : Loadable { else close() } + fun open(screen: Screen) { + if (broken) { + warn("Lambda's GUI stopped after repeated errors. Restart the game to bring it back.") + return + } + if (this.screen == null) { + if (!GuiScreen.canOpenOver(mc.currentScreen)) return + if (leaving) attemptSkipTo(0f) + else jumpTo(0f) + if (ClientConfig.clientSounds) LambdaSound.ModuleOn.play() + GuiScreen.show() + AutoUpdater.onGuiOpened() + } + leaving = false + this.screen = screen + } + fun close() { - val animated = - GuiConfig.animations && GuiConfig.closeAnimation && GuiConfig.closeStyle.isNotEmpty() + val animated = GuiConfig.animations && GuiConfig.closeAnimation && GuiConfig.closeStyle.isNotEmpty() if (screen == Screen.ClickGui && animated) { - if (shownPresence < 1f) skipTo(1f) + if (shownPresence < 1f) attemptSkipTo(1f) leaving = true } GuiScreen.close() } - private fun skipTo(end: Float) { + private fun attemptSkipTo(end: Float) { if (GuiConfig.interruptedAnimation != GuiInterrupt.Finish) return jumpTo(end) restarts++ @@ -180,23 +197,6 @@ object LambdaGui : Loadable { shownPresence = value } - fun open(screen: Screen) { - if (broken) { - warn("Lambda's GUI stopped after repeated errors. Restart the game to bring it back.") - return - } - if (this.screen == null) { - if (!GuiScreen.canOpenOver(mc.currentScreen)) return - if (leaving) skipTo(0f) - else jumpTo(0f) - if (ClientConfig.clientSounds) LambdaSound.ModuleOn.play() - GuiScreen.show() - AutoUpdater.onGuiOpened() - } - leaving = false - this.screen = screen - } - fun back() { if (screen == Screen.HudEditor) screen = Screen.ClickGui else close() @@ -290,7 +290,8 @@ object LambdaGui : Loadable { val host = createHost() warmingUp = true host.advance(size, density) - host.draw() + ItemAtlas.render() + host.draw(beforeScene = ItemAtlas::import) warmingUp = false host.advance(size, density) LOG.info("Prepared the GUI in ${(System.nanoTime() - start) / 1_000_000} ms") @@ -339,6 +340,27 @@ object LambdaGui : Loadable { } } + @Composable + private 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() } + } + } + @Composable private fun Underlay(content: @Composable () -> Unit) { val layer = rememberGraphicsLayer() @@ -369,8 +391,7 @@ object LambdaGui : Loadable { animate(shownPresence, target, animationSpec = spec) { value, _ -> shownPresence = value } - } - else shownPresence = target + } else shownPresence = target if (!present) leaving = false } } @@ -378,6 +399,7 @@ object LambdaGui : Loadable { @Composable private fun WarmUp() { SettingsList(GuiConfig.settingLayers) + PickerWarmUp() } private fun effects(density: Float): GuiCompositor.Effects { @@ -386,7 +408,7 @@ object LambdaGui : Loadable { if (showsClickGui) presence else 1f return GuiCompositor.Effects( - frost = + blur = if (GuiConfig.blur) GuiConfig.blurRadius * density * strength else 0f, glow = diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index da61a2e42..d79126b02 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -86,9 +86,8 @@ internal fun ClickGui() { val screen = LocalWindowInfo.current.containerSize val developerMode = ClickGuiState.developerMode val tags by observe { - CLICK_GUI_CATEGORIES.filter(ModuleTag::isTagShown) + listOfNotNull( - ModuleTag.DEBUG.takeIf { developerMode } - ) + CLICK_GUI_CATEGORIES.filter(ModuleTag::isTagShown) + + listOfNotNull(ModuleTag.DEBUG.takeIf { developerMode }) } val settings = remember { OpenSettings() } diff --git a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt index 58c89c7b4..4c2dd50e8 100644 --- a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt +++ b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt @@ -47,6 +47,8 @@ import com.lambda.gui.theme.LambdaTheme private val FOCUS_MARK = 1.dp +val LocalKeyboardReachable = compositionLocalOf { true } + internal object KeyboardFocus { var visible by mutableStateOf(false) @@ -86,6 +88,4 @@ fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = } } -val LocalKeyboardReachable = compositionLocalOf { true } - internal val KeyEvent.isActivation get() = key == Key.Enter || key == Key.Spacebar diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt index 9ed115f65..7ee39924c 100644 --- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -42,6 +42,8 @@ import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.IntSize +val LocalClickOnRelease = compositionLocalOf { false } + @OptIn(ExperimentalComposeUiApi::class) fun Modifier.mouseClickable( enabled: Boolean = true, @@ -97,8 +99,6 @@ fun Modifier.mouseClickable( } } -val LocalClickOnRelease = compositionLocalOf { false } - fun Modifier.onMousePress( button: PointerButton, onPress: (position: Offset) -> Unit diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index c33d47448..03c1a0459 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -19,6 +19,7 @@ package com.lambda.gui.component import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.expandIn import androidx.compose.animation.expandVertically @@ -123,6 +124,13 @@ private val FLOATING = ) private val SLACK = 4.dp +private const val DIALOG_ZOOM = 0.85f +private val SUGGESTIONS_ANCHOR = TransformOrigin(0.5f, 0f) + +private val LocalMenuDismiss = staticCompositionLocalOf<(() -> Unit)?> { null } +private val LocalMenuOpen = compositionLocalOf { true } +private val LocalMenuHovered = compositionLocalOf { false } +val LocalPopupHost = compositionLocalOf { null } @Composable private fun ScenePopup( @@ -245,12 +253,6 @@ private class LastValue { var value: T? = null } -private val LocalMenuDismiss = staticCompositionLocalOf<(() -> Unit)?> { null } - -private val LocalMenuOpen = compositionLocalOf { true } - -private val LocalMenuHovered = compositionLocalOf { false } - @Composable private fun MenuPopup( open: Boolean, @@ -306,8 +308,6 @@ class PopupHost { } } -val LocalPopupHost = compositionLocalOf { null } - private fun Modifier.swallowedBy(host: PopupHost?): Modifier = if (host == null) this else composed { @@ -448,8 +448,6 @@ private class UnfoldingPosition( } } -private val SUGGESTIONS_ANCHOR = TransformOrigin(0.5f, 0f) - @Composable fun Suggestions( open: Boolean, @@ -655,44 +653,56 @@ fun MenuDivider() = ) @Composable -fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.() -> Unit) { +fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.(dismiss: () -> Unit) -> Unit) { if (!LocalShown.current) { if (onDismiss != null) SideEffect(onDismiss) return } val colors = LambdaTheme.colors val presence = LocalPresence.current + val shape = RoundedCornerShape(Look.panelRounding) + val opened = remember { Animatable(0f) } + var closing by remember { mutableStateOf(false) } + val currentOnDismiss by rememberUpdatedState(onDismiss) + val dismiss = { closing = currentOnDismiss != null } + LaunchedEffect(closing) { + if (closing) { + opened.animateTo(0f, Motion.dialogs) + currentOnDismiss?.invoke() + } + else opened.animateTo(1f, Motion.dialogs) + } ScenePopup( popupPositionProvider = remember { positionProvider { _, _, _ -> IntOffset.Zero } }, properties = PopupProperties(focusable = true), - onKeyEvent = { onDismiss != null && it.dismissOnEscape(onDismiss) }, + onKeyEvent = { onDismiss != null && it.dismissOnEscape(dismiss) }, ) { KeyboardFocus.Layer() Box(Modifier.fillMaxSize(), Centered.BOTH) { Box( Modifier .matchParentSize() - .graphicsLayer { alpha = presence() } - .glass(Color.Black.copy(alpha = 0.35f), RectangleShape) - .mouseClickable(keyboard = false) { onDismiss?.invoke() } + .glass(Color.Black.copy(alpha = 0.35f), RectangleShape) { presence() * opened.value } + .mouseClickable(keyboard = false, onClick = dismiss) ) ContentColor(colors.onSurface) { AnimatedVisibility( visible = !LambdaGui.foldsClosed, modifier = Modifier + .graphicsLayer { + val shown = opened.value + alpha = shown + scaleX = DIALOG_ZOOM + (1f - DIALOG_ZOOM) * shown + scaleY = scaleX + } .guiPresence() - .window( - colors.panel, - colors.border, - RoundedCornerShape(Look.panelRounding), - floating = true - ), + .window(colors.panel, colors.border, shape, floating = true), enter = expandVertically(Motion.guiFold), exit = shrinkVertically(Motion.guiFold), ) { - Box(Modifier.padding(6.dp), content = content) + Box(Modifier.padding(6.dp)) { content(dismiss) } } } } diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt index bb390e108..a01c95a8e 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -26,7 +26,6 @@ import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.ClipOp import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline @@ -104,30 +103,33 @@ fun Modifier.guiPresence(anchor: TransformOrigin? = null): Modifier = } } -fun Modifier.glass(color: Color, shape: Shape): Modifier = +fun Modifier.glass(color: Color, shape: Shape, strength: () -> Float = { 1f }): Modifier = clip(shape).composed { val sigma = with(LocalDensity.current) { Look.backdropBlur.toPx() } val underlay = Look.underlay - val blur = - remember(sigma, underlay) { - if (sigma <= 0f) return@remember null - val blurred = ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) - if (underlay >= 1f) blurred - else ImageFilter.makeColorFilter(faded(underlay), blurred, null) - } + val full = remember(sigma, underlay) { backdropFilter(sigma, underlay) } drawBehind { - if (blur == null) { - drawRect(color, blendMode = BlendMode.Src) - return@drawBehind - } - drawIntoCanvas { canvas -> - canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), REPLACE, blur)) + val amount = strength().coerceIn(0f, 1f) + if (amount <= 0f) return@drawBehind + val backdrop = + if (amount >= 1f) full + else backdropFilter(sigma * amount, 1f - (1f - underlay) * amount) + if (backdrop != null) drawIntoCanvas { canvas -> + canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), REPLACE, backdrop)) canvas.skiaCanvas.restore() } - drawRect(color) + drawRect(color.copy(alpha = color.alpha * amount)) } } +private fun backdropFilter(sigma: Float, underlay: Float): ImageFilter? { + val blurred = + if (sigma > 0f) ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) + else null + return if (underlay >= 1f) blurred + else ImageFilter.makeColorFilter(faded(underlay), blurred, null) +} + fun Modifier.window( color: Color, border: Color, diff --git a/src/main/kotlin/com/lambda/gui/core/Frames.kt b/src/main/kotlin/com/lambda/gui/core/Frames.kt index dcb2c69f5..6352119f5 100644 --- a/src/main/kotlin/com/lambda/gui/core/Frames.kt +++ b/src/main/kotlin/com/lambda/gui/core/Frames.kt @@ -19,7 +19,11 @@ package com.lambda.gui.core import androidx.compose.runtime.withFrameNanos +private const val NANOS_PER_MILLI = 1_000_000 + suspend fun awaitFrames(millis: Long) { - val start = withFrameNanos { it } - while (withFrameNanos { it } - start < millis * 1_000_000) Unit + val end = withFrameNanos { it } + millis * NANOS_PER_MILLI + do { + val now = withFrameNanos { it } + } while (now < end) } diff --git a/src/main/kotlin/com/lambda/gui/core/Observe.kt b/src/main/kotlin/com/lambda/gui/core/Observe.kt index ebea6223b..6661cd070 100644 --- a/src/main/kotlin/com/lambda/gui/core/Observe.kt +++ b/src/main/kotlin/com/lambda/gui/core/Observe.kt @@ -20,12 +20,17 @@ package com.lambda.gui.core import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.State +import androidx.compose.runtime.compositionLocalOf 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 +val LocalShown = compositionLocalOf { true } +val LocalPresence = staticCompositionLocalOf { { 1f } } +internal val LocalObservations = staticCompositionLocalOf { error("observe was called outside the interface") } + @Composable fun observe(read: () -> T): State { val observations = LocalObservations.current @@ -54,5 +59,3 @@ internal class Observations { fun refresh() = active.forEach { it.refresh() } } - -internal val LocalObservations = staticCompositionLocalOf { error("observe was called outside the interface") } diff --git a/src/main/kotlin/com/lambda/gui/core/Retained.kt b/src/main/kotlin/com/lambda/gui/core/Retained.kt deleted file mode 100644 index 494bd2211..000000000 --- a/src/main/kotlin/com/lambda/gui/core/Retained.kt +++ /dev/null @@ -1,51 +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.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.runtime.staticCompositionLocalOf -import androidx.compose.ui.Modifier -import androidx.compose.ui.layout.layout - -val LocalShown = compositionLocalOf { true } - -val LocalPresence = staticCompositionLocalOf<() -> Float> { { 1f } } - -@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/menu/Dialogs.kt b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt index e36e7ef00..38cdb5974 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -66,8 +66,8 @@ internal fun ConfigDialog(config: Config, onDismiss: () -> Unit) { with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } * 0.7f - Dialog(onDismiss) { - ConfigSettings(config, maxHeight, onDismiss, Modifier.width(240.dp)) + Dialog(onDismiss) { dismiss -> + ConfigSettings(config, maxHeight, dismiss, Modifier.width(240.dp)) } } @@ -76,13 +76,13 @@ internal fun NewAutomationConfigDialog(onDismiss: () -> Unit) { var name by remember { mutableStateOf("") } val isAvailable = name.isNotBlank() && ConfigLoader.configs.none { it.name == name } - fun create() { + fun create(dismiss: () -> Unit) { if (!isAvailable) return UserAutomationConfig(name) - onDismiss() + dismiss() } - Dialog(onDismiss) { + Dialog(onDismiss) { dismiss -> Column(Modifier.width(180.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text("New Automation Config", style = Type.title) TextInput( @@ -94,8 +94,8 @@ internal fun NewAutomationConfigDialog(onDismiss: () -> Unit) { ) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { Spacer(Modifier.weight(1f)) - Button("Cancel", onClick = onDismiss) - Button("Create", enabled = isAvailable, onClick = ::create) + Button("Cancel", onClick = dismiss) + Button("Create", enabled = isAvailable) { create(dismiss) } } } } @@ -135,7 +135,7 @@ internal fun AboutDialog(onDismiss: () -> Unit) { .filter { it.isNotEmpty() } } - Dialog(onDismiss) { + Dialog(onDismiss) { dismiss -> Column(Modifier.width(240.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { Image( bitmap = rememberTexture("textures/lambda_text_color.png"), @@ -159,7 +159,7 @@ internal fun AboutDialog(onDismiss: () -> Unit) { Util.getOperatingSystem().open("$REPO_URL/blob/master/LICENSE.md") } Spacer(Modifier.weight(1f)) - Button("Close", onClick = onDismiss) + Button("Close", onClick = dismiss) } } } diff --git a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt index ccf13555a..b832e9543 100644 --- a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt +++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt @@ -31,7 +31,7 @@ import java.util.* internal object GuiCompositor { data class Effects( - val frost: Float = 0f, + val blur: Float = 0f, val glow: Float = 0f, val glowIntensity: Float = 0f, val glowColorA: Color = Color.WHITE, @@ -44,9 +44,9 @@ internal object GuiCompositor { } private val backdrop by lazy { BlurPyramid("Lambda GUI backdrop") } - private val halo by lazy { BlurPyramid("Lambda GUI glow") } - private var haloView: GpuTextureView? = null - private var haloRadius = 0f + private val glow by lazy { BlurPyramid("Lambda GUI glow") } + private var glowView: GpuTextureView? = null + private var glowRadius = 0f private val uniformSize = Std140SizeCalculator() @@ -77,18 +77,18 @@ internal object GuiCompositor { val linear = RenderSystem.getSamplerCache().get(FilterMode.LINEAR) val nearest = RenderSystem.getSamplerCache().get(FilterMode.NEAREST) - if (effects.frost <= 0f && effects.glow <= 0f && effects.dim <= 0f) { - haloView = null + if (effects.blur <= 0f && effects.glow <= 0f && effects.dim <= 0f) { + glowView = null return blit(gui) } val backdropView = - if (effects.frost > 0f) backdrop.blur(screen, width, height, effects.frost) + if (effects.blur > 0f) backdrop.blur(screen, width, height, effects.blur) 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 + if (effects.glow <= 0f) glowView = null + else if (guiChanged || glowView == null || glowRadius != effects.glow) { + glowView = glow.blur(gui, width, height, effects.glow) + glowRadius = effects.glow } writeUniforms(effects) @@ -98,7 +98,7 @@ internal object GuiCompositor { pass.setPipeline(LambdaRenderPipelines.GUI_COMPOSITE) pass.bindTexture("GuiSampler", gui, nearest) pass.bindTexture("BackdropSampler", backdropView, linear) - pass.bindTexture("HaloSampler", haloView ?: gui, linear) + pass.bindTexture("GlowSampler", glowView ?: gui, linear) pass.setUniform("GuiEffects", uniforms) pass.draw(0, 3) } @@ -123,7 +123,7 @@ internal object GuiCompositor { .putColor(effects.glowColorA) .putColor(effects.glowColorB) .putFloat(if (effects.glow > 0f) effects.glowIntensity else 0f) - .putFloat(if (effects.frost > 0f) 1f else 0f) + .putFloat(if (effects.blur > 0f) 1f else 0f) .putFloat((System.currentTimeMillis() % GLOW_CYCLE_MILLIS) / 1000f) .putFloat(effects.dim) .get() diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt index 8a0b7b598..11033f75a 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -66,6 +66,7 @@ import net.minecraft.item.ItemStack import net.minecraft.registry.Registries private val ICON_SIZE = 8.dp +private const val WARM_UP_ENTRIES = 64 @Composable internal fun CollectionButton(setting: CollectionSetting) { @@ -165,7 +166,7 @@ internal fun BlockPicker(setting: BlockSetting) { remember(query) { entries.filter { it.label.contains(query.trim(), ignoreCase = true) } } - Dialog(onDismiss = { picking = false }) { + Dialog(onDismiss = { picking = false }) { dismiss -> Column(Modifier.width(200.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { Text(setting.name) TextInput( @@ -177,12 +178,26 @@ internal fun BlockPicker(setting: BlockSetting) { ) Pane("Blocks (${matching.size})", matching, Modifier.height(220.dp)) { setting.value = it - picking = false + dismiss() } } } } +@Composable +internal fun PickerWarmUp() { + val entries = + remember { + Registries.BLOCK.take(WARM_UP_ENTRIES).map { + Entry(it, BlockSerializer.stringify(it), ItemStack(it.asItem())) + } + } + Column(Modifier.width(200.dp)) { + TextInput("", {}, Modifier.fillMaxWidth()) + Pane("", entries, Modifier.height(220.dp)) {} + } +} + private class Entry(val item: R, val label: String, val icon: ItemStack?) @Composable diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index 7d2ac6fc8..e445bbd1d 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -60,6 +60,12 @@ private const val LINE_HEIGHT = 10.95f private val ON_LIGHT_ACCENT = Color(0xFF1B1024) +private val LocalPalette = + staticCompositionLocalOf { error("No LambdaTheme in this composition") } +private val LocalTypography = + staticCompositionLocalOf { error("No LambdaTheme in this composition") } +val LocalContentColor = compositionLocalOf { Color.White } + @Immutable data class Palette( val primary: Color, @@ -134,6 +140,7 @@ internal object Look { internal object Motion : MotionDurationScale { private const val PAGE_MILLIS = 160 private const val GUI_MILLIS = 180 + private const val DIALOG_MILLIS = 140 private const val NOTIFICATION_MILLIS = 260 private val UNFOLDING = spring( @@ -165,6 +172,8 @@ internal object Motion : MotionDurationScale { get() = if (GuiConfig.panelAnimations) UNFOLDING else snap() val pageMillis get() = if (GuiConfig.pageAnimations) PAGE_MILLIS else 0 + val dialogs: FiniteAnimationSpec + get() = if (GuiConfig.dialogAnimations) tween(DIALOG_MILLIS) else snap() fun gui(distance: Float): FiniteAnimationSpec = tween((GUI_MILLIS * distance).roundToInt()) val guiFold: FiniteAnimationSpec @@ -258,13 +267,6 @@ object LambdaTheme { @Composable @ReadOnlyComposable get() = LocalPalette.current } -private val LocalPalette = - staticCompositionLocalOf { error("No LambdaTheme in this composition") } -private val LocalTypography = - staticCompositionLocalOf { error("No LambdaTheme in this composition") } - -val LocalContentColor = compositionLocalOf { Color.White } - @Composable fun LambdaTheme(content: @Composable () -> Unit) { val palette by observe { GuiConfig.palette } diff --git a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh index b7d4f8130..1987b22ee 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh @@ -2,13 +2,13 @@ uniform sampler2D GuiSampler; uniform sampler2D BackdropSampler; -uniform sampler2D HaloSampler; +uniform sampler2D GlowSampler; layout(std140) uniform GuiEffects { vec4 GlowColorA; vec4 GlowColorB; float GlowIntensity; - float Frost; + float Blur; float Time; float Dim; }; @@ -24,15 +24,15 @@ void main() { float covered = clamp(gui.a * 64.0, 0.0, 1.0); - float frost = Frost * covered; + float blurred = Blur * covered; vec3 backdrop = mix(texture(BackdropSampler, texCoord).rgb, DIM_COLOR, Dim); - vec4 under = vec4(backdrop, 1.0) * frost; + vec4 under = vec4(backdrop, 1.0) * blurred; if (GlowIntensity > 0.0) { - float halo = clamp(texture(HaloSampler, texCoord).a * 2.0, 0.0, 1.0); - float glow = clamp(pow(halo, 1.5) * GlowIntensity, 0.0, 1.0) * (1.0 - covered); + float glowMask = clamp(texture(GlowSampler, texCoord).a * 2.0, 0.0, 1.0); + float glow = clamp(pow(glowMask, 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); + under += vec4(mix(GlowColorA.rgb, GlowColorB.rgb, wave), 1.0) * glow * (1.0 - blurred); } vec4 over = gui + under * (1.0 - gui.a); From a1ccaa7ebbb638049a823cbfcb29e32659b946ae Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:08:06 +0000 Subject: [PATCH 28/34] fixes, better animation scheduling for opening categories and setting menus at the same time and anchor points for hud elements --- build.gradle.kts | 34 +- .../lambda/mixin/MinecraftClientMixin.java | 2 +- .../ClientPlayInteractionManagerMixin.java | 2 +- .../com/lambda/mixin/input/KeyboardMixin.java | 6 +- .../mixin/render/ComposeDelayMixin.java | 8 +- .../mixin/render/GameRendererMixin.java | 4 +- .../lambda/mixin/render/GuiRendererMixin.java | 38 +- .../render/InactivityFpsLimiterMixin.java | 26 +- .../lambda/config/settings/StringSetting.kt | 56 +- .../config/settings/comparable/EnumSetting.kt | 34 +- .../config/settings/complex/ColorSetting.kt | 4 +- .../config/settings/complex/KeybindSetting.kt | 158 +-- .../config/settings/complex/Vec3dSetting.kt | 50 +- .../config/settings/numeric/IntegerSetting.kt | 4 +- .../config/settings/numeric/LongSetting.kt | 2 +- src/main/kotlin/com/lambda/core/Loader.kt | 2 +- .../com/lambda/event/events/ComposeEvent.kt | 26 +- src/main/kotlin/com/lambda/gui/GuiConfig.kt | 592 ++++----- src/main/kotlin/com/lambda/gui/GuiScreen.kt | 232 ++-- src/main/kotlin/com/lambda/gui/LambdaGui.kt | 704 +++++----- .../kotlin/com/lambda/gui/Notifications.kt | 392 +++--- src/main/kotlin/com/lambda/gui/Reveal.kt | 84 +- src/main/kotlin/com/lambda/gui/Snap.kt | 214 +-- .../com/lambda/gui/clickgui/CategoryWindow.kt | 456 +++---- .../com/lambda/gui/clickgui/ClickGui.kt | 270 ++-- .../com/lambda/gui/clickgui/OpenSettings.kt | 70 +- .../com/lambda/gui/clickgui/SettingsPanel.kt | 376 +++--- .../com/lambda/gui/component/Centered.kt | 10 +- .../com/lambda/gui/component/Controls.kt | 452 +++---- .../kotlin/com/lambda/gui/component/Images.kt | 40 +- .../com/lambda/gui/component/Keyboard.kt | 62 +- .../com/lambda/gui/component/Pointer.kt | 222 ++-- .../kotlin/com/lambda/gui/component/Popups.kt | 1166 ++++++++--------- .../kotlin/com/lambda/gui/component/Scroll.kt | 142 +- .../com/lambda/gui/component/SlidingText.kt | 94 +- .../com/lambda/gui/component/Surface.kt | 224 ++-- .../kotlin/com/lambda/gui/component/Text.kt | 50 +- .../com/lambda/gui/component/TextInput.kt | 289 ++-- .../kotlin/com/lambda/gui/core/ComposeSlot.kt | 20 +- src/main/kotlin/com/lambda/gui/core/Frames.kt | 8 +- .../kotlin/com/lambda/gui/core/GlState.kt | 214 +-- .../kotlin/com/lambda/gui/core/Observe.kt | 28 +- .../com/lambda/gui/core/RenderThread.kt | 18 +- .../kotlin/com/lambda/gui/core/SceneHost.kt | 326 ++--- .../kotlin/com/lambda/gui/core/SceneInput.kt | 352 ++--- .../com/lambda/gui/core/ScenePlatform.kt | 72 +- src/main/kotlin/com/lambda/gui/hud/Hud.kt | 143 +- .../kotlin/com/lambda/gui/hud/HudEditor.kt | 457 +++---- .../kotlin/com/lambda/gui/menu/Dialogs.kt | 262 ++-- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 754 +++++------ src/main/kotlin/com/lambda/gui/menu/Search.kt | 229 ++-- .../com/lambda/gui/render/BlurPyramid.kt | 196 +-- .../com/lambda/gui/render/GuiCompositor.kt | 206 +-- .../kotlin/com/lambda/gui/render/ItemAtlas.kt | 398 +++--- .../lambda/gui/settings/CollectionEditor.kt | 300 ++--- .../com/lambda/gui/settings/ColorPicker.kt | 346 ++--- .../com/lambda/gui/settings/ConfigSettings.kt | 76 +- .../com/lambda/gui/settings/ModuleSettings.kt | 262 ++-- .../com/lambda/gui/settings/SettingRow.kt | 242 ++-- .../com/lambda/gui/settings/SettingsList.kt | 186 +-- src/main/kotlin/com/lambda/gui/theme/Theme.kt | 352 ++--- .../handler/handlers/NotificationHandler.kt | 60 +- .../managers/inventory/InventoryManager.kt | 2 +- .../kotlin/com/lambda/module/HudModule.kt | 80 +- src/main/kotlin/com/lambda/module/Module.kt | 24 +- .../module/modules/client/AutoUpdater.kt | 72 +- .../combat/autodisconnect/AutoDisconnect.kt | 16 +- .../autodisconnect/DisconnectDetailsWidget.kt | 10 +- .../lambda/module/modules/hud/AccountName.kt | 8 +- .../com/lambda/module/modules/hud/Armor.kt | 76 +- .../com/lambda/module/modules/hud/Baritone.kt | 24 +- .../lambda/module/modules/hud/ModuleList.kt | 46 +- .../lambda/module/modules/hud/Speedometer.kt | 8 +- .../lambda/module/modules/hud/TaskFlowHud.kt | 8 +- .../lambda/module/modules/hud/Watermark.kt | 24 +- .../module/modules/movement/BackTrack.kt | 4 +- .../lambda/module/modules/movement/Blink.kt | 4 +- .../lambda/module/modules/player/Replay.kt | 76 +- .../com/lambda/util/CommunicationUtils.kt | 6 +- .../kotlin/com/lambda/util/text/TextDsl.kt | 2 +- .../lambda/shaders/core/gui_blur_down.fsh | 16 +- .../lambda/shaders/core/gui_blur_up.fsh | 24 +- .../lambda/shaders/core/gui_composite.fsh | 38 +- 83 files changed, 6402 insertions(+), 6270 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 648e8c584..a2d06a519 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -49,7 +49,7 @@ val replacements = file("gradle.properties").inputStream().use { stream -> plugins { kotlin("jvm") version "2.3.21" - kotlin("plugin.compose") version "2.3.21" + kotlin("plugin.compose") version "2.3.21" id("org.jetbrains.dokka") version "2.1.0" id("fabric-loom") version "1.17-SNAPSHOT" id("com.gradleup.shadow") version "9.3.0" @@ -76,9 +76,9 @@ configurations.all { if (requested.group == "org.lwjgl") { useVersion(lwjglVersion) } - if (requested.group == "org.jetbrains.skiko") { - useVersion(skikoVersion) - } + if (requested.group == "org.jetbrains.skiko") { + useVersion(skikoVersion) + } } } @@ -88,7 +88,7 @@ repositories { maven("https://maven.2b2t.vc/releases") // Baritone maven("https://jitpack.io") // KDiscordIPC maven("https://api.modrinth.com/maven") - google() + google() mavenCentral() // Allow the use of local libraries @@ -178,18 +178,18 @@ dependencies { includeLib("com.pngencoder:pngencoder:$pngEncoderVersion") - listOf("runtime:runtime", "ui:ui", "foundation:foundation").forEach { module -> - shadowLib("org.jetbrains.compose.$module-desktop:$composeVersion") { - exclude(group = "org.jetbrains.kotlin") - exclude(group = "org.jetbrains.kotlinx") - } - } - skikoPlatforms.forEach { platform -> - shadowLib("org.jetbrains.skiko:skiko-awt-runtime-$platform:$skikoVersion") { - exclude(group = "org.jetbrains.kotlin") - exclude(group = "org.jetbrains.kotlinx") - } - } + listOf("runtime:runtime", "ui:ui", "foundation:foundation").forEach { module -> + shadowLib("org.jetbrains.compose.$module-desktop:$composeVersion") { + exclude(group = "org.jetbrains.kotlin") + exclude(group = "org.jetbrains.kotlinx") + } + } + skikoPlatforms.forEach { platform -> + shadowLib("org.jetbrains.skiko:skiko-awt-runtime-$platform:$skikoVersion") { + exclude(group = "org.jetbrains.kotlin") + exclude(group = "org.jetbrains.kotlinx") + } + } // Ktor includeLib("io.ktor:ktor-client-core:$ktorVersion") diff --git a/src/main/java/com/lambda/mixin/MinecraftClientMixin.java b/src/main/java/com/lambda/mixin/MinecraftClientMixin.java index d41043882..4c68fdd26 100644 --- a/src/main/java/com/lambda/mixin/MinecraftClientMixin.java +++ b/src/main/java/com/lambda/mixin/MinecraftClientMixin.java @@ -195,7 +195,7 @@ float getTargetMillisPerTick(float millis, Operation original) { @Inject(method = "updateWindowTitle", at = @At("HEAD"), cancellable = true) void updateWindowTitle(CallbackInfo ci) { - if (!GuiConfig.getSetLambdaWindowTitle()) return; + if (!GuiConfig.getSetLambdaWindowTitle()) return; WindowUtils.setLambdaTitle(); ci.cancel(); } diff --git a/src/main/java/com/lambda/mixin/entity/ClientPlayInteractionManagerMixin.java b/src/main/java/com/lambda/mixin/entity/ClientPlayInteractionManagerMixin.java index 2ba0b3192..d9311c336 100644 --- a/src/main/java/com/lambda/mixin/entity/ClientPlayInteractionManagerMixin.java +++ b/src/main/java/com/lambda/mixin/entity/ClientPlayInteractionManagerMixin.java @@ -120,7 +120,7 @@ public void clickSlotTail(int syncId, int slotId, int button, SlotActionType act @ModifyExpressionValue(method = "clickSlot", at = @At(value = "INVOKE", target = "Lnet/minecraft/screen/ScreenHandler;getRevision()I")) private int modifyClickSlotRevision(int originalRevision) { - return ClientConfig.INSTANCE.getAvoidInventoryDesync() ? -1 : originalRevision; + return ClientConfig.INSTANCE.getAvoidInventoryDesync() ? -1 : originalRevision; } /** diff --git a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java index 00da2bbe4..a28c4e243 100644 --- a/src/main/java/com/lambda/mixin/input/KeyboardMixin.java +++ b/src/main/java/com/lambda/mixin/input/KeyboardMixin.java @@ -34,11 +34,11 @@ public class KeyboardMixin { @WrapMethod(method = "onKey") private void onKey(long window, int action, KeyInput input, Operation original) { - if (EventFlow.post(new ButtonEvent.Keyboard.Press(input.key(), input.scancode(), action, input.modifiers())).isCanceled()) return; + if (EventFlow.post(new ButtonEvent.Keyboard.Press(input.key(), input.scancode(), action, input.modifiers())).isCanceled()) return; original.call(window, action, input); int key = input.key(); - if (!InventoryMove.isKeyMovementRelated(key)) return; - if (action != GLFW.GLFW_RELEASE && !InventoryMove.getShouldMove()) return; + if (!InventoryMove.isKeyMovementRelated(key)) return; + if (action != GLFW.GLFW_RELEASE && !InventoryMove.getShouldMove()) return; InputUtil.Key fromCode = InputUtil.fromKeyCode(input); KeyBinding.setKeyPressed(fromCode, action != 0); } diff --git a/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java b/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java index 52469a732..ae59cc626 100644 --- a/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java +++ b/src/main/java/com/lambda/mixin/render/ComposeDelayMixin.java @@ -28,8 +28,8 @@ @Mixin(value = Actuals_skikoKt.class, remap = false) public class ComposeDelayMixin { - @Inject(method = "postDelayed", at = @At("HEAD"), cancellable = true, require = 1) - private static void delayOnRenderThread(long delayMillis, Function0 block, CallbackInfoReturnable cir) { - cir.setReturnValue(RenderThread.after(delayMillis, block)); - } + @Inject(method = "postDelayed", at = @At("HEAD"), cancellable = true, require = 1) + private static void delayOnRenderThread(long delayMillis, Function0 block, CallbackInfoReturnable cir) { + cir.setReturnValue(RenderThread.after(delayMillis, block)); + } } diff --git a/src/main/java/com/lambda/mixin/render/GameRendererMixin.java b/src/main/java/com/lambda/mixin/render/GameRendererMixin.java index cf4304a15..e49df8ada 100644 --- a/src/main/java/com/lambda/mixin/render/GameRendererMixin.java +++ b/src/main/java/com/lambda/mixin/render/GameRendererMixin.java @@ -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) { - LambdaGui.INSTANCE.render(); + LambdaGui.INSTANCE.render(); } @WrapOperation(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;applyCursorTo(Lnet/minecraft/client/util/Window;)V")) @@ -102,7 +102,7 @@ private void applyCursorOverride(DrawContext context, Window window, Operation original) { - Framebuffer atlas = ItemAtlas.getTarget(); - return atlas != null ? atlas : original.call(client); - } + @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;getFramebuffer()Lnet/minecraft/client/gl/Framebuffer;"), require = 1) + private Framebuffer drawIntoItemAtlas(MinecraftClient client, Operation original) { + Framebuffer atlas = ItemAtlas.getTarget(); + return atlas != null ? atlas : original.call(client); + } - @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferWidth()I"), require = 1) - private int itemAtlasWidth(Window window, Operation original) { - Framebuffer atlas = ItemAtlas.getTarget(); - return atlas != null ? atlas.textureWidth : original.call(window); - } + @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferWidth()I"), require = 1) + private int itemAtlasWidth(Window window, Operation original) { + Framebuffer atlas = ItemAtlas.getTarget(); + return atlas != null ? atlas.textureWidth : original.call(window); + } - @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferHeight()I"), require = 1) - private int itemAtlasHeight(Window window, Operation original) { - Framebuffer atlas = ItemAtlas.getTarget(); - return atlas != null ? atlas.textureHeight : original.call(window); - } + @WrapOperation(method = "renderPreparedDraws", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getFramebufferHeight()I"), require = 1) + private int itemAtlasHeight(Window window, Operation original) { + Framebuffer atlas = ItemAtlas.getTarget(); + return atlas != null ? atlas.textureHeight : original.call(window); + } - @WrapOperation(method = {"renderPreparedDraws", "getWindowScaleFactor"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getScaleFactor()I"), require = 1) - private int itemAtlasScale(Window window, Operation original) { - return ItemAtlas.getTarget() != null ? ItemAtlas.getScale() : original.call(window); - } + @WrapOperation(method = {"renderPreparedDraws", "getWindowScaleFactor"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/Window;getScaleFactor()I"), require = 1) + private int itemAtlasScale(Window window, Operation original) { + return ItemAtlas.getTarget() != null ? ItemAtlas.getScale() : original.call(window); + } } diff --git a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java index 16b994f08..3173135c3 100644 --- a/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java +++ b/src/main/java/com/lambda/mixin/render/InactivityFpsLimiterMixin.java @@ -30,18 +30,18 @@ @Mixin(InactivityFpsLimiter.class) public class InactivityFpsLimiterMixin { - @Shadow - @Final - private MinecraftClient client; + @Shadow + @Final + private MinecraftClient client; - @ModifyReturnValue(method = "getLimitReason", at = @At("RETURN")) - private InactivityFpsLimiter.LimitReason liftMenuLimit(InactivityFpsLimiter.LimitReason reason) { - boolean shown = client.currentScreen == GuiScreen.INSTANCE - || LambdaGui.INSTANCE.getLeaving() - || !NotificationHandler.INSTANCE.getNotifications().isEmpty(); - if (reason == InactivityFpsLimiter.LimitReason.OUT_OF_LEVEL_MENU && shown) { - return InactivityFpsLimiter.LimitReason.NONE; - } - return reason; - } + @ModifyReturnValue(method = "getLimitReason", at = @At("RETURN")) + private InactivityFpsLimiter.LimitReason liftMenuLimit(InactivityFpsLimiter.LimitReason reason) { + boolean shown = client.currentScreen == GuiScreen.INSTANCE + || LambdaGui.INSTANCE.getLeaving() + || !NotificationHandler.INSTANCE.getNotifications().isEmpty(); + if (reason == InactivityFpsLimiter.LimitReason.OUT_OF_LEVEL_MENU && shown) { + return InactivityFpsLimiter.LimitReason.NONE; + } + return reason; + } } diff --git a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt index cf2ab0e2c..0ff82b101 100644 --- a/src/main/kotlin/com/lambda/config/settings/StringSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/StringSetting.kt @@ -73,34 +73,34 @@ class StringSetting( var multiline: Boolean = false, ) : Setting(name, description, defaultValue, layer, config, visibility) { - @Composable - override fun Gui() { - val value by observe { value } - if (multiline) Column( - Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(1.dp) - ) { - Row( - Modifier.padding(start = ROW_INSET, top = 1.dp), - Arrangement.spacedBy(ALTERED_GAP), - Centered.VERTICALLY - ) { - AlteredDot() - Text(name, maxLines = 1) - } - TextInput( - value, - { this@StringSetting.value = it }, - Modifier.fillMaxWidth(), - singleLine = false - ) - } - else Labeled(name) { - TextInput( - value, - { this@StringSetting.value = it }, - Modifier.width(TEXT_FIELD_WIDTH) - ) + @Composable + override fun Gui() { + val value by observe { value } + if (multiline) Column( + Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(1.dp) + ) { + Row( + Modifier.padding(start = ROW_INSET, top = 1.dp), + Arrangement.spacedBy(ALTERED_GAP), + Centered.VERTICALLY + ) { + AlteredDot() + Text(name, maxLines = 1) + } + TextInput( + value, + { this@StringSetting.value = it }, + Modifier.fillMaxWidth(), + singleLine = false + ) + } + else Labeled(name) { + TextInput( + value, + { this@StringSetting.value = it }, + Modifier.width(TEXT_FIELD_WIDTH) + ) } } 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 948c82832..f423240b5 100644 --- a/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/comparable/EnumSetting.kt @@ -56,22 +56,22 @@ class EnumSetting>( visibility: () -> Boolean, defaultValue: T ) : Setting(name, description, defaultValue, layer, config, visibility) { - val selectionHoverListeners = mutableListOf<(option: T?) -> Unit>() - val selectionClickListeners = mutableListOf<(option: T) -> Unit>() + val selectionHoverListeners = mutableListOf<(option: T?) -> Unit>() + val selectionClickListeners = mutableListOf<(option: T) -> Unit>() - @Composable - override fun Gui() { - val selected by observe { value } - Dropdown( - label = name, - options = selected.enumValues.asList(), - selected = selected, - optionLabel = { it.displayValue }, - modifier = Modifier.padding(start = ROW_INSET), - leading = { AlteredDot() }, - onOptionHover = { option -> selectionHoverListeners.forEach { it(option) } }, - onOptionClick = { option -> selectionClickListeners.forEach { it(option) } }, - ) { value = it } + @Composable + override fun Gui() { + val selected by observe { value } + Dropdown( + label = name, + options = selected.enumValues.asList(), + selected = selected, + optionLabel = { it.displayValue }, + modifier = Modifier.padding(start = ROW_INSET), + leading = { AlteredDot() }, + onOptionHover = { option -> selectionHoverListeners.forEach { it(option) } }, + onOptionClick = { option -> selectionClickListeners.forEach { it(option) } }, + ) { value = it } } override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { @@ -94,7 +94,7 @@ class EnumSetting>( } fun , T : Enum> S.onSelectionHover(block: (option: T?) -> Unit) = - apply { selectionHoverListeners.add(block) } + apply { selectionHoverListeners.add(block) } fun , T : Enum> S.onSelectionClick(block: (option: T) -> Unit) = - apply { selectionClickListeners.add(block) } + apply { selectionClickListeners.add(block) } 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 3d1853b04..23315885a 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/ColorSetting.kt @@ -48,8 +48,8 @@ class ColorSetting( visibility: () -> Boolean, defaultValue: Color ) : Setting(name, description, defaultValue, layer, config, visibility) { - @Composable - override fun Gui() = ColorPicker(this) + @Composable + override fun Gui() = ColorPicker(this) override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(integer("Red", 0, 255)) { red -> diff --git a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt index 898634e4b..278fabe9b 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/KeybindSetting.kt @@ -128,12 +128,12 @@ class KeybindSetting( get() = muteable?.isMuted == true && !alwaysListening init { - listenUnsafe(alwaysListen = true) { event -> - if (recorder === this) record(event) else if (!isMuted) onButtonEvent(event) - } - listenUnsafe(alwaysListen = true) { event -> - if (recorder === this) record(event) else if (!isMuted) onButtonEvent(event) - } + listenUnsafe(alwaysListen = true) { event -> + if (recorder === this) record(event) else if (!isMuted) onButtonEvent(event) + } + listenUnsafe(alwaysListen = true) { event -> + if (recorder === this) record(event) else if (!isMuted) onButtonEvent(event) + } } private fun onButtonEvent(event: ButtonEvent) { @@ -155,68 +155,68 @@ class KeybindSetting( } } - @Composable - override fun Gui() { - val colors = LambdaTheme.colors - val bind by observe { value } - val recording = recorder === this - - Labeled(name) { - Tooltip("Click, then press a key or mouse button. Backspace unbinds, Escape cancels.") { - Box( - contentAlignment = Centered.BOTH, - modifier = Modifier - .height(Look.rowHeight) - .clip(RoundedCornerShape(Look.controlRounding)) - .background(if (recording) colors.secondary else colors.control) - .mouseClickable { - val stoppedHere = stopped === this@KeybindSetting && stoppedBy == Press.id - if (!stoppedHere) recorder = this@KeybindSetting + @Composable + override fun Gui() { + val colors = LambdaTheme.colors + val bind by observe { value } + val recording = recorder === this + + Labeled(name) { + Tooltip("Click, then press a key or mouse button. Backspace unbinds, Escape cancels.") { + Box( + contentAlignment = Centered.BOTH, + modifier = Modifier + .height(Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(if (recording) colors.secondary else colors.control) + .mouseClickable { + val stoppedHere = stopped === this@KeybindSetting && stoppedBy == Press.id + if (!stoppedHere) recorder = this@KeybindSetting } - .padding(horizontal = 4.dp) - ) { - Text( - text = if (recording) "Press a key" else bind.name, - color = if (recording) colors.onSecondary else colors.onControl, - maxLines = 1, - ) + .padding(horizontal = 4.dp) + ) { + Text( + text = if (recording) "Press a key" else bind.name, + color = if (recording) colors.onSecondary else colors.onControl, + maxLines = 1, + ) } } } - } - - private fun record(event: ButtonEvent.Keyboard.Press) { - event.cancel() - val isModifier = event.keyCode in GLFW_KEY_LEFT_SHIFT..GLFW_KEY_RIGHT_SUPER - if (event.isRepeated || event.isPressed == isModifier) return - when (val key = event.translated) { - KeyCode.Unbound -> return - KeyCode.Escape -> Unit - KeyCode.Backspace, KeyCode.Delete -> value = Bind.EMPTY - else -> value = Bind(key.code, if (isModifier) 0 else event.modifiers, -1) + } + + private fun record(event: ButtonEvent.Keyboard.Press) { + event.cancel() + val isModifier = event.keyCode in GLFW_KEY_LEFT_SHIFT..GLFW_KEY_RIGHT_SUPER + if (event.isRepeated || event.isPressed == isModifier) return + when (val key = event.translated) { + KeyCode.Unbound -> return + KeyCode.Escape -> Unit + KeyCode.Backspace, KeyCode.Delete -> value = Bind.EMPTY + else -> value = Bind(key.code, if (isModifier) 0 else event.modifiers, -1) } - recorder = null - } - - private fun record(event: ButtonEvent.Mouse.Click) { - if (!event.isPressed) return - recorder = null - stopped = this - stoppedBy = Press.id + 1 - if (event.button == GLFW_MOUSE_BUTTON_LEFT) return - event.cancel() - value = Bind(0, event.modifiers, event.button) - } - - companion object { - private var recorder: KeybindSetting? by mutableStateOf(null) - private var stopped: KeybindSetting? = null - private var stoppedBy = 0L - - internal val isRecording get() = recorder != null - - internal fun stopRecording() { - recorder = null + recorder = null + } + + private fun record(event: ButtonEvent.Mouse.Click) { + if (!event.isPressed) return + recorder = null + stopped = this + stoppedBy = Press.id + 1 + if (event.button == GLFW_MOUSE_BUTTON_LEFT) return + event.cancel() + value = Bind(0, event.modifiers, event.button) + } + + companion object { + private var recorder: KeybindSetting? by mutableStateOf(null) + private var stopped: KeybindSetting? = null + private var stoppedBy = 0L + + internal val isRecording get() = recorder != null + + internal fun stopRecording() { + recorder = null } } @@ -229,22 +229,22 @@ class KeybindSetting( } optional(boolean("mouse button")) { isMouseButton -> executeWithResult { - val isMouse = isMouseButton != null && isMouseButton().value() - val bind = - if (isMouse) { - val num = - try { - nameArg().value().toInt() - } catch (_: NumberFormatException) { - return@executeWithResult failure("${nameArg().value()} doesn't match with a mouse button") - } - Bind(0, 0, mouse = num) - } else { - try { - Bind(KeyCode.valueOf(nameArg().value()).code, 0) - } catch (_: IllegalArgumentException) { - return@executeWithResult failure("${nameArg().value()} doesn't match with a bind") - } + val isMouse = isMouseButton != null && isMouseButton().value() + val bind = + if (isMouse) { + val num = + try { + nameArg().value().toInt() + } catch (_: NumberFormatException) { + return@executeWithResult failure("${nameArg().value()} doesn't match with a mouse button") + } + Bind(0, 0, mouse = num) + } else { + try { + Bind(KeyCode.valueOf(nameArg().value()).code, 0) + } catch (_: IllegalArgumentException) { + return@executeWithResult failure("${nameArg().value()} doesn't match with a bind") + } } trySetValue(bind) 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 8e0d6ab8e..ec1b2d0c7 100644 --- a/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/complex/Vec3dSetting.kt @@ -53,31 +53,31 @@ class Vec3dSetting( visibility: () -> Boolean, defaultValue: Vec3d ) : Setting(name, description, defaultValue, layer, config, visibility) { - @Composable - override fun Gui() { - val vec by observe { value } - Labeled(name) { - val parse = - { text: String -> text.toDoubleOrNull()?.takeIf(Double::isFinite) } - NumberInput( - vec.x, - parse, - { value = Vec3d(it, vec.y, vec.z) }, - Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) - ) - NumberInput( - vec.y, - parse, - { value = Vec3d(vec.x, it, vec.z) }, - Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) - ) - NumberInput( - vec.z, - parse, - { value = Vec3d(vec.x, vec.y, it) }, - Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) - ) - } + @Composable + override fun Gui() { + val vec by observe { value } + Labeled(name) { + val parse = + { text: String -> text.toDoubleOrNull()?.takeIf(Double::isFinite) } + NumberInput( + vec.x, + parse, + { value = Vec3d(it, vec.y, vec.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + vec.y, + parse, + { value = Vec3d(vec.x, it, vec.z) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + NumberInput( + vec.z, + parse, + { value = Vec3d(vec.x, vec.y, it) }, + Modifier.weight(1f, fill = false).width(NUMBER_FIELD_WIDTH) + ) + } } override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { diff --git a/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt b/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt index 9bdc064f0..4fb1edebe 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/IntegerSetting.kt @@ -55,8 +55,8 @@ class IntegerSetting( override var step: Int = 1, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { - override fun convert(number: BigDecimal) = - number.setScale(0, RoundingMode.HALF_UP).toInt() + override fun convert(number: BigDecimal) = + number.setScale(0, RoundingMode.HALF_UP).toInt() override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(integer(name, range.start, range.endInclusive)) { parameter -> diff --git a/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt b/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt index 0a8f45929..7d499cc9d 100644 --- a/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/numeric/LongSetting.kt @@ -55,7 +55,7 @@ class LongSetting( override var step: Long = 1, unit: String ) : NumericSetting(name, description, config, layer, defaultValue, visibility, range, step, unit) { - override fun convert(number: BigDecimal) = number.setScale(0, RoundingMode.HALF_UP).toLong() + override fun convert(number: BigDecimal) = number.setScale(0, RoundingMode.HALF_UP).toLong() override fun CommandBuilder.buildCommand(registry: CommandRegistryAccess) { required(long(name, range.start, range.endInclusive)) { parameter -> diff --git a/src/main/kotlin/com/lambda/core/Loader.kt b/src/main/kotlin/com/lambda/core/Loader.kt index 49e2bf8c3..08df1d63b 100644 --- a/src/main/kotlin/com/lambda/core/Loader.kt +++ b/src/main/kotlin/com/lambda/core/Loader.kt @@ -28,7 +28,7 @@ object Loader { private val started = System.currentTimeMillis() val runtime: String - get() = "${((System.currentTimeMillis() - started) / 1000).seconds}" + get() = "${((System.currentTimeMillis() - started) / 1000).seconds}" private val loadables = getInstances() diff --git a/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt b/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt index e45fdfb11..0710a204b 100644 --- a/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt +++ b/src/main/kotlin/com/lambda/event/events/ComposeEvent.kt @@ -21,20 +21,20 @@ import androidx.compose.runtime.Composable import com.lambda.event.Event sealed class ComposeEvent : Event { - private val added = mutableListOf<@Composable () -> Unit>() - val contents: List<@Composable () -> Unit> get() = added + private val added = mutableListOf<@Composable () -> Unit>() + val contents: List<@Composable () -> Unit> get() = added - fun content(content: @Composable () -> Unit) { - added += content - } + fun content(content: @Composable () -> Unit) { + added += content + } - sealed class Hud : ComposeEvent() { - class Pre : Hud() - class Post : Hud() - } + sealed class Hud : ComposeEvent() { + class Pre : Hud() + class Post : Hud() + } - sealed class Gui : ComposeEvent() { - class Pre : Gui() - class Post : Gui() - } + sealed class Gui : ComposeEvent() { + class Pre : Gui() + class Post : Gui() + } } diff --git a/src/main/kotlin/com/lambda/gui/GuiConfig.kt b/src/main/kotlin/com/lambda/gui/GuiConfig.kt index 622dbf6f8..964527c18 100644 --- a/src/main/kotlin/com/lambda/gui/GuiConfig.kt +++ b/src/main/kotlin/com/lambda/gui/GuiConfig.kt @@ -62,331 +62,331 @@ import java.awt.Color @Suppress("unused") object GuiConfig : Loadable, Config("GUI", GuiCategory) { - private const val GENERAL_TAB = "General" - private const val SNAPPING_TAB = "Snapping" - private const val STYLE_TAB = "Style" - private const val BACKDROP_GROUP = "Backdrop" - private const val SHAPE_GROUP = "Shape" - private const val LAYOUT_GROUP = "Layout" - private const val MOTION_GROUP = "Motion" - private const val NOTIFICATIONS_GROUP = "Notifications" - private const val NOTIFICATION_PREVIEW_MILLIS = 1500L - private const val DARK_THEME_GROUP = "Dark Theme" - private const val LIGHT_THEME_GROUP = "Light Theme" + private const val GENERAL_TAB = "General" + private const val SNAPPING_TAB = "Snapping" + private const val STYLE_TAB = "Style" + private const val BACKDROP_GROUP = "Backdrop" + private const val SHAPE_GROUP = "Shape" + private const val LAYOUT_GROUP = "Layout" + private const val MOTION_GROUP = "Motion" + private const val NOTIFICATIONS_GROUP = "Notifications" + private const val NOTIFICATION_PREVIEW_MILLIS = 1500L + private const val DARK_THEME_GROUP = "Dark Theme" + private const val LIGHT_THEME_GROUP = "Light Theme" - @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 boolSetting("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 boolSetting("Set Lambda Window Title", true) - .onValueChange { _, _ -> mc.updateWindowTitle() } - @Tab(GENERAL_TAB) val lambdaTitleAppendixName by boolSetting("Append Username", true) { setLambdaWindowTitle } - .onValueChange { _, _ -> mc.updateWindowTitle() } - @Tab(GENERAL_TAB) val keepSettingsOpen by boolSetting("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 hoverSubmenus by boolSetting("Open Submenus On Hover", true, "Opens a submenu when the pointer is over its row. When off, a submenu opens on a click.") - @Tab(GENERAL_TAB) private val resetWindowLayout by functionSetting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded") + @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 boolSetting("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 boolSetting("Set Lambda Window Title", true) + .onValueChange { _, _ -> mc.updateWindowTitle() } + @Tab(GENERAL_TAB) val lambdaTitleAppendixName by boolSetting("Append Username", true) { setLambdaWindowTitle } + .onValueChange { _, _ -> mc.updateWindowTitle() } + @Tab(GENERAL_TAB) val keepSettingsOpen by boolSetting("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 hoverSubmenus by boolSetting("Open Submenus On Hover", true, "Opens a submenu when the pointer is over its row. When off, a submenu opens on a click.") + @Tab(GENERAL_TAB) private val resetWindowLayout by functionSetting("Reset Window Layout", ::resetWindows, "Puts every category window of the click GUI back in its place in the row, unfolded") - @Tab(SNAPPING_TAB) val snapEnabled by boolSetting("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 boolSetting("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 floatSetting("Grid Size", 5f, 2f..128f, 1f, "Grid step") { snapEnabled } - @Tab(SNAPPING_TAB) val snapToEdges by boolSetting("Snap To Element Edges", true) { snapEnabled } - @Tab(SNAPPING_TAB) val snapToCenters by boolSetting("Snap To Element Centers", true) { snapEnabled } - @Tab(SNAPPING_TAB) val snapToScreenCenter by boolSetting("Snap To Screen Center", true) { snapEnabled } - @Tab(SNAPPING_TAB) val snapToGrid by boolSetting("Snap To Grid", true) { snapEnabled } - @Tab(SNAPPING_TAB) val snapDistanceElement by floatSetting("Snap Distance (Elements)", 20f, 1f..48f, 1f) { snapEnabled } - @Tab(SNAPPING_TAB) val snapDistanceScreen by floatSetting("Snap Distance (Screen Center)", 14f, 1f..48f, 1f) { snapEnabled } - @Tab(SNAPPING_TAB) val snapDistanceGrid by floatSetting("Snap Distance (Grid)", 12f, 1f..48f, 1f) { snapEnabled } - @Tab(SNAPPING_TAB) val snapLineColor by colorSetting("Snap Line Color", Color(255, 160, 0, 220)) { snapEnabled && showSnapLines } + @Tab(SNAPPING_TAB) val snapEnabled by boolSetting("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 boolSetting("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 floatSetting("Grid Size", 5f, 2f..128f, 1f, "Grid step") { snapEnabled } + @Tab(SNAPPING_TAB) val snapToEdges by boolSetting("Snap To Element Edges", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToCenters by boolSetting("Snap To Element Centers", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToScreenCenter by boolSetting("Snap To Screen Center", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapToGrid by boolSetting("Snap To Grid", true) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceElement by floatSetting("Snap Distance (Elements)", 20f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceScreen by floatSetting("Snap Distance (Screen Center)", 14f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapDistanceGrid by floatSetting("Snap Distance (Grid)", 12f, 1f..48f, 1f) { snapEnabled } + @Tab(SNAPPING_TAB) val snapLineColor by colorSetting("Snap Line Color", Color(255, 160, 0, 220)) { snapEnabled && showSnapLines } - private enum class ThemeMode(override val displayName: String) : NamedEnum { - Auto("Auto"), - Dark("Dark"), - Light("Light"), - } + private enum class ThemeMode(override val displayName: String) : NamedEnum { + Auto("Auto"), + Dark("Dark"), + Light("Light"), + } - @Tab(STYLE_TAB) private val themeMode by enumSetting("Theme", ThemeMode.Dark, "Auto follows the theme of your operating system") - @Tab(STYLE_TAB) val font by enumSetting("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") - @Tab(STYLE_TAB) val fontSize by floatSetting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") - @Tab(STYLE_TAB) val scale by floatSetting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() + @Tab(STYLE_TAB) private val themeMode by enumSetting("Theme", ThemeMode.Dark, "Auto follows the theme of your operating system") + @Tab(STYLE_TAB) val font by enumSetting("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") + @Tab(STYLE_TAB) val fontSize by floatSetting("Font Size", 0.85f, 0.5f..1.2f, 0.05f, "Size of text, as a share of the size the font reads best at. Rows grow to fit larger text. The Minecraft font is only sharp at 1") + @Tab(STYLE_TAB) val scale by floatSetting("Scale", 1f, 0.5f..1.5f, 0.05f, "Size of the interface. Dragged, it is applied when the button is let go. No larger than leaves room on the screen for every window and dialog").appliedOnRelease() - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimBackground by boolSetting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimStrength by floatSetting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blur by boolSetting("Blur", true, "Blurs what is behind windows for a frosted glass look") - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blurRadius by floatSetting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val layerFade by floatSetting("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") - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glow by boolSetting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowRadius by floatSetting("Glow Radius", 17f, 1f..100f, 1f) { glow } - @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowIntensity by floatSetting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimBackground by boolSetting("Dim Background", true, "Darkens what is behind the click GUI while it is open, whatever NoRender says about GUI shadows") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val dimStrength by floatSetting("Dim Strength", 0.6f, 0.05f..1f, 0.05f, "How dark the background gets. Minecraft's own menus use about 0.8") { dimBackground } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blur by boolSetting("Blur", true, "Blurs what is behind windows for a frosted glass look") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val blurRadius by floatSetting("Blur Radius", 4f, 1f..32f, 1f, "Strength of the blur") { blur } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val layerFade by floatSetting("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") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glow by boolSetting("Glow", false, "Surrounds the click GUI with a glow, in the two glow colours of the theme in use") + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowRadius by floatSetting("Glow Radius", 17f, 1f..100f, 1f) { glow } + @Tab(STYLE_TAB) @Group(BACKDROP_GROUP) val glowIntensity by floatSetting("Glow Intensity", 0.3f, 0.1f..3f, 0.1f) { glow } - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val windowRounding by floatSetting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val panelRounding by floatSetting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val menuRounding by floatSetting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val controlRounding by floatSetting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlines by boolSetting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlineWidth by floatSetting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val shadows by boolSetting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") - @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val emboss by boolSetting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val windowRounding by floatSetting("Window Rounding", 3f, 0f..12f, 0.5f, "Corners of the category windows, and of the band of tabs that is made like their headers. Square at 0") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val panelRounding by floatSetting("Panel Rounding", 5f, 0f..16f, 0.5f, "Corners of a module's settings panel, of dialogs and of the colour picker") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val menuRounding by floatSetting("Menu Rounding", 3f, 0f..12f, 0.5f, "Corners of menus, dropdowns, search results and tooltips") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val controlRounding by floatSetting("Control Rounding", 2f, 0f..8f, 0.5f, "Corners of sliders, chips, buttons, fields and group headings. Tick boxes get half of it") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlines by boolSetting("Outlines", true, "Draws a thin border around windows, panels and menus. Off for the look of pure glass") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val outlineWidth by floatSetting("Outline Width", 0.5f, 0.5f..3f, 0.5f, "Thickness of the outlines. 0.5 is one pixel at 1080p") { outlines } + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val shadows by boolSetting("Shadows", true, "Casts a soft shadow from panels, menus and dialogs onto the interface beneath them") + @Tab(STYLE_TAB) @Group(SHAPE_GROUP) val emboss by boolSetting("Emboss", false, "Lights each module faintly from above, so the list feels less flat") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val elementHeight by floatSetting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowWidth by floatSetting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingsWidth by floatSetting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowGap by floatSetting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowTop by floatSetting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val modulePadding by floatSetting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val panelPadding by floatSetting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingSpacing by floatSetting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val groupIndent by floatSetting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val inlineSettings by boolSetting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") - @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val multipleSettings by boolSetting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val elementHeight by floatSetting("Element Height", 11.5f, 10f..24f, 0.5f, "Height of a module in its category and of a row of settings, never less than its text needs") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowWidth by floatSetting("Window Width", 90f, 60f..160f, 5f, "Width of the category windows. Names too long for it slide under the pointer") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingsWidth by floatSetting("Settings Width", 180f, 130f..320f, 10f, "The widest a module's settings may get. Values too long for it slide under the pointer") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowGap by floatSetting("Window Gap", 2f, 0f..20f, 1f, "Room between the category windows in their row, and what one snaps to beside another") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val windowTop by floatSetting("Window Top", 94f, 20f..300f, 2f, "How far down the screen the row of category windows starts, for those that have not been moved") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val modulePadding by floatSetting("Module Padding", 4f, 0f..12f, 0.5f, "Room to either side of a module's name, and of its category's") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val panelPadding by floatSetting("Panel Padding", 4f, 0f..12f, 0.5f, "Room around the settings in a module's settings panel") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val settingSpacing by floatSetting("Setting Spacing", 1f, 0f..6f, 0.5f, "Room between one setting and the next") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val groupIndent by floatSetting("Group Indent", 5f, 0f..12f, 0.5f, "How far the settings of a group are set in behind its bar") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val inlineSettings by boolSetting("Inline Settings", false, "A module's settings drop down under it inside its window, as wide as the window and pushing the modules below it down, instead of popping out beside it") + @Tab(STYLE_TAB) @Group(LAYOUT_GROUP) val multipleSettings by boolSetting("Multiple Settings", false, "Lets the settings of several modules be open at once, where otherwise opening one closes the last. A click beside them closes them all either way") - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animations by boolSetting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animationSpeed by floatSetting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openAnimation by boolSetting("Open Animation", true, "Animates the click GUI in when it opens") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openStyle by collectionSetting("Open Style", setOf(GuiTransition.Unfold), GuiTransition.entries.toSet(), "What the click GUI does as it comes in, any of them together: its windows unfold out of their headers, and all of it fades, slides down or zooms in") { animations && openAnimation } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeAnimation by boolSetting("Close Animation", true, "Animates the click GUI out when it closes. The game has the mouse and keyboard back at once: the animation only plays over it") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeStyle by collectionSetting("Close Style", setOf(GuiTransition.Unfold, GuiTransition.Fade), GuiTransition.entries.toSet(), "What the click GUI does as it goes out, any of them together: its windows fold into their headers, and all of it fades, slides up or zooms out") { animations && closeAnimation } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val interruptedAnimation by enumSetting("Interrupted Animation", GuiInterrupt.Reverse, "What happens when the click GUI is opened or closed again before its animation is done: it turns around from where it is, or skips to the end and plays the other one in full") { animations && (openAnimation || closeAnimation) } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val windowAnimations by boolSetting("Window Animations", true, "Category windows unfold out of their headers") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val panelAnimations by boolSetting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val pageAnimations by boolSetting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val dialogAnimations by boolSetting("Dialog Animations", true, "Dialogs such as GUI Settings grow out of the centre of the screen as they open, and shrink back as they close") { animations } - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val smoothScrolling by boolSetting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val scrollSpeed by floatSetting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") - @Tab(STYLE_TAB) @Group(MOTION_GROUP) val tooltipDelay by intSetting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animations by boolSetting("Animations", true, "Unfolds, slides and fades the interface. Off, everything but scrolling is where it is going at once") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val animationSpeed by floatSetting("Animation Speed", 1f, 0.25f..4f, 0.25f, "How fast the interface animates, as a multiple of what it is made with") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openAnimation by boolSetting("Open Animation", true, "Animates the click GUI in when it opens") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val openStyle by collectionSetting("Open Style", setOf(GuiTransition.Unfold), GuiTransition.entries.toSet(), "What the click GUI does as it comes in, any of them together: its windows unfold out of their headers, and all of it fades, slides down or zooms in") { animations && openAnimation } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeAnimation by boolSetting("Close Animation", true, "Animates the click GUI out when it closes. The game has the mouse and keyboard back at once: the animation only plays over it") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val closeStyle by collectionSetting("Close Style", setOf(GuiTransition.Unfold, GuiTransition.Fade), GuiTransition.entries.toSet(), "What the click GUI does as it goes out, any of them together: its windows fold into their headers, and all of it fades, slides up or zooms out") { animations && closeAnimation } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val interruptedAnimation by enumSetting("Interrupted Animation", GuiInterrupt.Reverse, "What happens when the click GUI is opened or closed again before its animation is done: it turns around from where it is, or skips to the end and plays the other one in full") { animations && (openAnimation || closeAnimation) } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val windowAnimations by boolSetting("Window Animations", true, "Category windows unfold out of their headers") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val panelAnimations by boolSetting("Panel Animations", true, "Settings panels, menus, dropdowns and search results unfold out of what opened them") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val pageAnimations by boolSetting("Page Animations", true, "Changing the tab or the page of a settings panel slides the new one in") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val dialogAnimations by boolSetting("Dialog Animations", true, "Dialogs such as GUI Settings grow out of the centre of the screen as they open, and shrink back as they close") { animations } + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val smoothScrolling by boolSetting("Smooth Scrolling", true, "The mouse wheel sets a list off fast and lets it glide to rest. On its own: it works with Animations off, and at its own pace") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val scrollSpeed by floatSetting("Scroll Speed", 1f, 0.25f..3f, 0.25f, "How far a notch of the mouse wheel takes a list, as a multiple of three rows") + @Tab(STYLE_TAB) @Group(MOTION_GROUP) val tooltipDelay by intSetting("Tooltip Delay", 500, 0..2000, 50, "How long the pointer rests on something before its description shows", " ms") - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationScale by floatSetting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface").previewsNotifications() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationWidth by floatSetting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines").previewsNotifications() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSide by enumSetting("Notification Side", NotificationSide.Right, "Which side of the screen notifications slide in from").previewsNotificationOptions() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationHeight by floatSetting("Notification Height", 0f, 0f..1f, 0.05f, "Where on that side the first notification sits. 0 is the bottom of the screen and 1 the top").previewsNotifications() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationFlow by enumSetting("Notification Direction", NotificationFlow.Up, "Which way the stack grows: each new notification appears on this side of the ones already showing. They leave the other way, and the stack is kept on the screen").previewsNotificationOptions() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSeconds by floatSetting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it leaves") - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationLimit by enumSetting("Notification Limit", NotificationLimit.Count, "Count lets the oldest go once more than Max Notifications are showing. Fit Screen shows as many as fit between Notification Height and the edge of the screen the stack grows towards, and the oldest goes when a new one would not fit").previewsNotificationOptions() - @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val maxNotifications by intSetting("Max Notifications", 5, 1..12, 1, "How many notifications show at once before the oldest leaves") { notificationLimit == NotificationLimit.Count }.previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationScale by floatSetting("Notification Scale", 1f, 0.5f..3f, 0.05f, "Size of notifications, on top of the scale of the rest of the interface").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationWidth by floatSetting("Notification Width", 130f, 80f..300f, 10f, "How wide a notification is. Longer messages wrap onto more lines").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSide by enumSetting("Notification Side", NotificationSide.Right, "Which side of the screen notifications slide in from").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationHeight by floatSetting("Notification Height", 0f, 0f..1f, 0.05f, "Where on that side the first notification sits. 0 is the bottom of the screen and 1 the top").previewsNotifications() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationFlow by enumSetting("Notification Direction", NotificationFlow.Up, "Which way the stack grows: each new notification appears on this side of the ones already showing. They leave the other way, and the stack is kept on the screen").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationSeconds by floatSetting("Notification Time", 4f, 1f..15f, 0.5f, "How many seconds a notification stays before it leaves") + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val notificationLimit by enumSetting("Notification Limit", NotificationLimit.Count, "Count lets the oldest go once more than Max Notifications are showing. Fit Screen shows as many as fit between Notification Height and the edge of the screen the stack grows towards, and the oldest goes when a new one would not fit").previewsNotificationOptions() + @Tab(STYLE_TAB) @Group(NOTIFICATIONS_GROUP) val maxNotifications by intSetting("Max Notifications", 5, 1..12, 1, "How many notifications show at once before the oldest leaves") { notificationLimit == NotificationLimit.Count }.previewsNotifications() - @Tab(STYLE_TAB) @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( - PaletteSettings( - this, - primary = Color(214, 77, 113), - secondary = Color(255, 141, 128), - surface = Color(69, 48, 55, 165), - panel = Color(55, 38, 45, 200), - inset = Color(0, 0, 0, 190), - onSurface = Color(246, 236, 239), - onSurfaceVariant = Color(184, 156, 166), - header = Color(222, 53, 101), - onHeader = Color(255, 246, 248), - moduleEnabled = Color(161, 42, 75), - onModuleEnabled = Color(255, 240, 244), - control = Color(214, 77, 113), - controlSelected = Color(92, 64, 75), - onControl = Color(246, 236, 239), - track = Color(38, 28, 32, 230), - input = Color(32, 23, 26, 230), - border = Color(128, 92, 104, 235), - textShadow = Color(0, 0, 0, 150), - glowA = Color(222, 53, 101), - glowB = Color(255, 141, 128), - ) - ) + @Tab(STYLE_TAB) @Group(DARK_THEME_GROUP) private val darkTheme by configBlock( + PaletteSettings( + this, + primary = Color(214, 77, 113), + secondary = Color(255, 141, 128), + surface = Color(69, 48, 55, 165), + panel = Color(55, 38, 45, 200), + inset = Color(0, 0, 0, 190), + onSurface = Color(246, 236, 239), + onSurfaceVariant = Color(184, 156, 166), + header = Color(222, 53, 101), + onHeader = Color(255, 246, 248), + moduleEnabled = Color(161, 42, 75), + onModuleEnabled = Color(255, 240, 244), + control = Color(214, 77, 113), + controlSelected = Color(92, 64, 75), + onControl = Color(246, 236, 239), + track = Color(38, 28, 32, 230), + input = Color(32, 23, 26, 230), + border = Color(128, 92, 104, 235), + textShadow = Color(0, 0, 0, 150), + glowA = Color(222, 53, 101), + glowB = Color(255, 141, 128), + ) + ) - @Tab(STYLE_TAB) @Group(LIGHT_THEME_GROUP) private val lightTheme by configBlock( - PaletteSettings( - this, - primary = Color(222, 53, 101), - secondary = Color(209, 74, 59), - surface = Color(250, 236, 241, 228), - panel = Color(244, 226, 232, 240), - inset = Color(120, 0, 40, 68), - onSurface = Color(61, 40, 47), - onSurfaceVariant = Color(110, 86, 95), - header = Color(222, 53, 101), - onHeader = Color(255, 250, 251), - moduleEnabled = Color(232, 84, 126), - onModuleEnabled = Color(255, 250, 251), - control = Color(240, 139, 166), - controlSelected = Color(224, 197, 206), - onControl = Color(61, 40, 47), - track = Color(209, 192, 199, 220), - input = Color(255, 250, 252, 210), - border = Color(184, 154, 164, 238), - textShadow = Color(0, 0, 0, 0), - glowA = Color(222, 53, 101), - glowB = Color(255, 141, 128), - ) - ) + @Tab(STYLE_TAB) @Group(LIGHT_THEME_GROUP) private val lightTheme by configBlock( + PaletteSettings( + this, + primary = Color(222, 53, 101), + secondary = Color(209, 74, 59), + surface = Color(250, 236, 241, 228), + panel = Color(244, 226, 232, 240), + inset = Color(120, 0, 40, 68), + onSurface = Color(61, 40, 47), + onSurfaceVariant = Color(110, 86, 95), + header = Color(222, 53, 101), + onHeader = Color(255, 250, 251), + moduleEnabled = Color(232, 84, 126), + onModuleEnabled = Color(255, 250, 251), + control = Color(240, 139, 166), + controlSelected = Color(224, 197, 206), + onControl = Color(61, 40, 47), + track = Color(209, 192, 199, 220), + input = Color(255, 250, 252, 210), + border = Color(184, 154, 164, 238), + textShadow = Color(0, 0, 0, 0), + glowA = Color(222, 53, 101), + glowB = Color(255, 141, 128), + ) + ) - private val theme: PaletteSettings - get() = - when (themeMode) { - ThemeMode.Dark -> darkTheme - ThemeMode.Light -> lightTheme - ThemeMode.Auto -> - if (SystemAppearance.isDark) darkTheme - else lightTheme - } + private val theme: PaletteSettings + get() = + when (themeMode) { + ThemeMode.Dark -> darkTheme + ThemeMode.Light -> lightTheme + ThemeMode.Auto -> + if (SystemAppearance.isDark) darkTheme + else lightTheme + } - val palette: Palette get() = theme.toPalette() - val glowColorA: Color get() = theme.glowA - val glowColorB: Color get() = theme.glowB + val palette: Palette get() = theme.toPalette() + val glowColorA: Color get() = theme.glowA + val glowColorB: Color get() = theme.glowB - private object SystemAppearance { - private const val REFRESH_MILLIS = 1000L + private object SystemAppearance { + private const val REFRESH_MILLIS = 1000L - private var checkedAt = 0L - private var dark = true + 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 - } - } + val isDark: Boolean + get() { + val now = System.currentTimeMillis() + if (now - checkedAt > REFRESH_MILLIS) { + checkedAt = now + dark = currentSystemTheme != SystemTheme.LIGHT + } + return dark + } + } - private var notificationHeld = false - private var notificationPreviewEnd = 0L - internal var notificationOption by mutableStateOf(null) - private set + private var notificationHeld = false + private var notificationPreviewEnd = 0L + internal var notificationOption by mutableStateOf(null) + private set - init { - listenUnsafe { event -> - val previewing = notificationHeld || notificationOption != null || System.currentTimeMillis() < notificationPreviewEnd - if (previewing && !LambdaGui.leaving) event.content { NotificationPreview() } - } - } + init { + listenUnsafe { event -> + val previewing = notificationHeld || notificationOption != null || System.currentTimeMillis() < notificationPreviewEnd + if (previewing && !LambdaGui.leaving) event.content { NotificationPreview() } + } + } - private fun , T> S.previewsNotifications() = - apply { - onHold { notificationHeld = it } - onValueChangeUnsafe { _, _ -> notificationPreviewEnd = System.currentTimeMillis() + NOTIFICATION_PREVIEW_MILLIS } - } + private fun , T> S.previewsNotifications() = + apply { + onHold { notificationHeld = it } + onValueChangeUnsafe { _, _ -> notificationPreviewEnd = System.currentTimeMillis() + NOTIFICATION_PREVIEW_MILLIS } + } - private fun , T : Enum> S.previewsNotificationOptions() = - onSelectionHover { notificationOption = it } + private fun , T : Enum> S.previewsNotificationOptions() = + onSelectionHover { notificationOption = it } - internal data class WindowPlacement( - val x: Float, - val y: Float, - val collapsed: Boolean - ) { - val inRow get() = x.isNaN() || y.isNaN() + internal data class WindowPlacement( + val x: Float, + val y: Float, + val collapsed: Boolean + ) { + val inRow get() = x.isNaN() || y.isNaN() - companion object { - fun inRow(collapsed: Boolean) = WindowPlacement(Float.NaN, Float.NaN, collapsed) - } - } + companion object { + fun inRow(collapsed: Boolean) = WindowPlacement(Float.NaN, Float.NaN, collapsed) + } + } - private var windowPlacements by property("") - private var decodedFrom: String? = null - private var decoded = emptyMap() + private var windowPlacements by property("") + private var decodedFrom: String? = null + private var decoded = emptyMap() - internal var windows: Map - get() { - val saved = windowPlacements - if (saved != decodedFrom) { - decodedFrom = saved - decoded = saved.split(';').mapNotNull(::decodeWindow).toMap() - } - return decoded - } - set(value) { - windowPlacements = - value.entries.joinToString(";") { (tag, window) -> - "$tag:${window.x},${window.y},${window.collapsed}" - } - } + internal var windows: Map + get() { + val saved = windowPlacements + if (saved != decodedFrom) { + decodedFrom = saved + decoded = saved.split(';').mapNotNull(::decodeWindow).toMap() + } + return decoded + } + set(value) { + windowPlacements = + value.entries.joinToString(";") { (tag, window) -> + "$tag:${window.x},${window.y},${window.collapsed}" + } + } - internal fun resetWindows() { - windows = emptyMap() - } + internal fun resetWindows() { + windows = emptyMap() + } - private fun decodeWindow(entry: String): Pair? { - val (tag, fields) = entry.split(':').takeIf { it.size == 2 } ?: return null - val (x, y, collapsed) = fields.split(',').takeIf { it.size == 3 } ?: return null - return tag to WindowPlacement( - x.toFloatOrNull() ?: return null, - y.toFloatOrNull() ?: return null, - collapsed.toBoolean() - ) - } + 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() + ) + } } class PaletteSettings( - override val c: Config, - primary: Color, - secondary: Color, - surface: Color, - panel: Color, - inset: Color, - onSurface: Color, - onSurfaceVariant: Color, - header: Color, - onHeader: Color, - moduleEnabled: Color, - onModuleEnabled: Color, - control: Color, - controlSelected: Color, - onControl: Color, - track: Color, - input: Color, - border: Color, - textShadow: Color, - glowA: Color, - glowB: Color, + override val c: Config, + primary: Color, + secondary: Color, + surface: Color, + panel: Color, + inset: Color, + onSurface: Color, + onSurfaceVariant: Color, + header: Color, + onHeader: Color, + moduleEnabled: Color, + onModuleEnabled: Color, + control: Color, + controlSelected: Color, + onControl: Color, + track: Color, + input: Color, + border: Color, + textShadow: Color, + glowA: Color, + glowB: Color, ) : ConfigBlock { - private val primary by c.colorSetting("Primary", primary, "Accent colour: the fill of sliders and ticked boxes") - private val secondary by c.colorSetting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") - private val surface by c.colorSetting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") - private val panel by c.colorSetting("Panel", panel, "Fill of settings panels, menus and dialogs") - private val inset by c.colorSetting("Inset", inset, "Shade behind settings that open under their module, and over the module whose settings are open beside it") - private val onSurface by c.colorSetting("On Surface", onSurface, "Text on windows") - private val onSurfaceVariant by c.colorSetting("On Surface Variant", onSurfaceVariant, "Subdued text on windows") - private val header by c.colorSetting("Header", header) - private val onHeader by c.colorSetting("On Header", onHeader) - private val moduleEnabled by c.colorSetting("Module Enabled", moduleEnabled) - private val onModuleEnabled by c.colorSetting("On Module Enabled", onModuleEnabled) - private val control by c.colorSetting("Control", control, "Fill of dropdowns, buttons and key caps") - private val controlSelected by c.colorSetting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") - private val onControl by c.colorSetting("On Control", onControl) - private val track by c.colorSetting("Slider Track", track) - private val input by c.colorSetting("Text Field", input) - private val border by c.colorSetting("Border", border) - private val textShadow by c.colorSetting("Text Shadow", textShadow) - val glowA by c.colorSetting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { GuiConfig.glow } - val glowB by c.colorSetting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { GuiConfig.glow } + private val primary by c.colorSetting("Primary", primary, "Accent colour: the fill of sliders and ticked boxes") + private val secondary by c.colorSetting("Secondary", secondary, "Second accent: what is chosen among options, as in a menu or a row of pages") + private val surface by c.colorSetting("Surface", surface, "Fill of windows. Lower its opacity to see more of the blur") + private val panel by c.colorSetting("Panel", panel, "Fill of settings panels, menus and dialogs") + private val inset by c.colorSetting("Inset", inset, "Shade behind settings that open under their module, and over the module whose settings are open beside it") + private val onSurface by c.colorSetting("On Surface", onSurface, "Text on windows") + private val onSurfaceVariant by c.colorSetting("On Surface Variant", onSurfaceVariant, "Subdued text on windows") + private val header by c.colorSetting("Header", header) + private val onHeader by c.colorSetting("On Header", onHeader) + private val moduleEnabled by c.colorSetting("Module Enabled", moduleEnabled) + private val onModuleEnabled by c.colorSetting("On Module Enabled", onModuleEnabled) + private val control by c.colorSetting("Control", control, "Fill of dropdowns, buttons and key caps") + private val controlSelected by c.colorSetting("Control Selected", controlSelected, "Fill of the entry of a menu or list that is chosen or under the pointer") + private val onControl by c.colorSetting("On Control", onControl) + private val track by c.colorSetting("Slider Track", track) + private val input by c.colorSetting("Text Field", input) + private val border by c.colorSetting("Border", border) + private val textShadow by c.colorSetting("Text Shadow", textShadow) + val glowA by c.colorSetting("Glow Color 1", glowA, "Where the glow around the click GUI starts") { GuiConfig.glow } + val glowB by c.colorSetting("Glow Color 2", glowB, "Where the glow around the click GUI ends") { GuiConfig.glow } - fun toPalette() = - Palette( - primary = primary.toCompose(), - secondary = secondary.toCompose(), - surface = surface.toCompose(), - panel = panel.toCompose(), - inset = inset.toCompose(), - onSurface = onSurface.toCompose(), - onSurfaceVariant = onSurfaceVariant.toCompose(), - header = header.toCompose(), - onHeader = onHeader.toCompose(), - moduleEnabled = moduleEnabled.toCompose(), - onModuleEnabled = onModuleEnabled.toCompose(), - control = control.toCompose(), - controlSelected = controlSelected.toCompose(), - onControl = onControl.toCompose(), - track = track.toCompose(), - input = input.toCompose(), - border = border.toCompose(), - textShadow = textShadow.toCompose(), - ) + fun toPalette() = + Palette( + primary = primary.toCompose(), + secondary = secondary.toCompose(), + surface = surface.toCompose(), + panel = panel.toCompose(), + inset = inset.toCompose(), + onSurface = onSurface.toCompose(), + onSurfaceVariant = onSurfaceVariant.toCompose(), + header = header.toCompose(), + onHeader = onHeader.toCompose(), + moduleEnabled = moduleEnabled.toCompose(), + onModuleEnabled = onModuleEnabled.toCompose(), + control = control.toCompose(), + controlSelected = controlSelected.toCompose(), + onControl = onControl.toCompose(), + track = track.toCompose(), + input = input.toCompose(), + border = border.toCompose(), + textShadow = textShadow.toCompose(), + ) } diff --git a/src/main/kotlin/com/lambda/gui/GuiScreen.kt b/src/main/kotlin/com/lambda/gui/GuiScreen.kt index f0ee54200..6c0801f67 100644 --- a/src/main/kotlin/com/lambda/gui/GuiScreen.kt +++ b/src/main/kotlin/com/lambda/gui/GuiScreen.kt @@ -36,120 +36,122 @@ import net.minecraft.text.Text import org.lwjgl.glfw.GLFW object GuiScreen : Screen(Text.of("Lambda")), CursorOverrideProvider { - private var parent: Screen? = null - - private val backgroundScreens = - listOf( - TitleScreen::class.java, - MultiplayerScreen::class.java, - AutoDisconnectScreen::class.java, - ) - - fun canOpenOver(screen: Screen?) = - screen == null || backgroundScreens.any { it.isInstance(screen) } - - internal fun show() { - parent = mc.currentScreen - (parent as? OverlayBackgroundScreen)?.onOverlaidByGui() - mc.setScreen(this) - } - - override fun close() { - val previous = parent - parent = null - mc.setScreen(previous) - } - - override fun removed() { - KeybindSetting.stopRecording() - LambdaGui.onScreenRemoved() - } - - override fun shouldPause() = false - - override fun render( - context: DrawContext, - mouseX: Int, - mouseY: Int, - deltaTicks: Float - ) = Unit - - override fun renderBackground( - context: DrawContext, - mouseX: Int, - mouseY: Int, - delta: Float - ) { - val parent = parent - if (parent != null) { - parent.renderBackground(context, -1, -1, delta) - parent.render(context, -1, -1, delta) - context.drawDeferredElements() - } - } - - override fun resize(width: Int, height: Int) { - super.resize(width, height) - parent?.resize(width, height) - } - - override fun getCursorOverride(mouseX: Int, mouseY: Int): Cursor? = LambdaGui.cursor - - override fun mouseMoved(mouseX: Double, mouseY: Double) { - LambdaGui.input?.move(scenePosition(mouseX, mouseY)) - } - - override fun mouseClicked(click: Click, doubled: Boolean): Boolean { - val position = scenePosition(click.x(), click.y()) - TextFocus.press(position) - LambdaGui.input?.run { - move(position) - button(click.button(), true, click.modifiers()) - } - return true - } - - override fun mouseReleased(click: Click): Boolean { - LambdaGui.input?.run { - move(scenePosition(click.x(), click.y())) - button(click.button(), false, click.modifiers()) - } - return true - } - - override fun mouseScrolled( - mouseX: Double, - mouseY: Double, - horizontalAmount: Double, - verticalAmount: Double - ): Boolean { - LambdaGui.input?.scroll(horizontalAmount, verticalAmount) - return true - } - - override fun keyPressed(input: KeyInput): Boolean { - if (LambdaGui.input?.key(input.key(), true, input.modifiers()) == true) return true - if (input.key() == GLFW.GLFW_KEY_F && input.modifiers() and GLFW.GLFW_MOD_CONTROL != 0) { - ClickGuiState.focusSearch = LambdaGui.screen == LambdaGui.Screen.ClickGui - return true - } - if (input.isEscape && LambdaGui.onEscape?.invoke() != true) LambdaGui.back() - return true - } - - override fun keyReleased(input: KeyInput): Boolean { - LambdaGui.input?.key(input.key(), false, input.modifiers()) - return true - } - - override fun charTyped(input: CharInput): Boolean { - LambdaGui.input?.type(input.codepoint()) - return true - } - - private fun scenePosition(x: Double, y: Double): Offset { - val scale = mc.window.scaleFactor - return Offset((x * scale).toFloat(), (y * scale).toFloat()) - } + private var parent: Screen? = null + + private val backgroundScreens = + listOf( + TitleScreen::class.java, + MultiplayerScreen::class.java, + AutoDisconnectScreen::class.java, + ) + + val isOverScreen get() = parent != null + + fun canOpenOver(screen: Screen?) = + screen == null || backgroundScreens.any { it.isInstance(screen) } + + internal fun show() { + parent = mc.currentScreen + (parent as? OverlayBackgroundScreen)?.onOverlaidByGui() + mc.setScreen(this) + } + + override fun close() { + val previous = parent + parent = null + mc.setScreen(previous) + } + + override fun removed() { + KeybindSetting.stopRecording() + LambdaGui.onScreenRemoved() + } + + override fun shouldPause() = false + + override fun render( + context: DrawContext, + mouseX: Int, + mouseY: Int, + deltaTicks: Float + ) = Unit + + override fun renderBackground( + context: DrawContext, + mouseX: Int, + mouseY: Int, + delta: Float + ) { + val parent = parent + if (parent != null) { + parent.renderBackground(context, -1, -1, delta) + parent.render(context, -1, -1, delta) + context.drawDeferredElements() + } + } + + override fun resize(width: Int, height: Int) { + super.resize(width, height) + parent?.resize(width, height) + } + + override fun getCursorOverride(mouseX: Int, mouseY: Int): Cursor? = LambdaGui.cursor + + override fun mouseMoved(mouseX: Double, mouseY: Double) { + LambdaGui.input?.move(scenePosition(mouseX, mouseY)) + } + + override fun mouseClicked(click: Click, doubled: Boolean): Boolean { + val position = scenePosition(click.x(), click.y()) + TextFocus.press(position) + LambdaGui.input?.run { + move(position) + button(click.button(), true, click.modifiers()) + } + return true + } + + override fun mouseReleased(click: Click): Boolean { + LambdaGui.input?.run { + move(scenePosition(click.x(), click.y())) + button(click.button(), false, click.modifiers()) + } + return true + } + + override fun mouseScrolled( + mouseX: Double, + mouseY: Double, + horizontalAmount: Double, + verticalAmount: Double + ): Boolean { + LambdaGui.input?.scroll(horizontalAmount, verticalAmount) + return true + } + + override fun keyPressed(input: KeyInput): Boolean { + if (LambdaGui.input?.key(input.key(), true, input.modifiers()) == true) return true + if (input.key() == GLFW.GLFW_KEY_F && input.modifiers() and GLFW.GLFW_MOD_CONTROL != 0) { + ClickGuiState.focusSearch = LambdaGui.screen == LambdaGui.Screen.ClickGui + return true + } + if (input.isEscape && LambdaGui.onEscape?.invoke() != true) LambdaGui.back() + return true + } + + override fun keyReleased(input: KeyInput): Boolean { + LambdaGui.input?.key(input.key(), false, input.modifiers()) + return true + } + + override fun charTyped(input: CharInput): Boolean { + LambdaGui.input?.type(input.codepoint()) + return true + } + + private fun scenePosition(x: Double, y: Double): Offset { + val scale = mc.window.scaleFactor + return Offset((x * scale).toFloat(), (y * scale).toFloat()) + } } diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index 5a7528e76..a2c65291b 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -79,358 +79,354 @@ import kotlin.concurrent.thread import kotlin.math.abs object LambdaGui : Loadable { - private const val REFERENCE_HEIGHT = 540f - private const val MAX_FAILURES = 3 - private const val FAILURE_WINDOW_NANOS = 60_000_000_000L - - enum class Screen { - ClickGui, - HudEditor - } - - var screen: Screen? by mutableStateOf(null) - private set - - private var host: SceneHost? = null - private var failures = 0 - private var failedAt = 0L - private var broken = false - - private val beneathHud = ComposeSlot { ComposeEvent.Hud.Pre() } - private val aboveHud = ComposeSlot { ComposeEvent.Hud.Post() } - private val beneathGui = ComposeSlot { ComposeEvent.Gui.Pre() } - private val aboveGui = ComposeSlot { ComposeEvent.Gui.Post() } - private var underlay: GraphicsLayer? = null - private var layered by mutableStateOf(false) - - private var settled = true - private var warmingUp by mutableStateOf(false) - private var warmedUp = false - - private var shownPresence by mutableFloatStateOf(0f) - private var animation: Job? = null - var leaving by mutableStateOf(false) - private set - internal var restarts by mutableIntStateOf(0) - private set - internal val presence - get() = - if (warmingUp) 1f - else shownPresence - internal val transitions: Collection - get() = - if (leaving) GuiConfig.closeStyle - else GuiConfig.openStyle - internal val unfoldsOpen - get() = GuiConfig.animations && - GuiConfig.openAnimation && - GuiTransition.Unfold in GuiConfig.openStyle - private val showsClickGui - get() = screen == Screen.ClickGui || leaving - internal val foldsClosed - get() = leaving && GuiTransition.Unfold in GuiConfig.closeStyle - - private val observations = Observations() - private val clickGuiObservations = Observations() - - internal val input: SceneInput? get() = host?.input - internal val cursor: Cursor? get() = host?.platform?.cursor - internal var onEscape: (() -> Boolean)? = null - - val isCapturingKeys get() = TextFocus.isTyping || KeybindSetting.isRecording - - init { - listenUnsafe { shutDown() } - } - - override fun load(): String { - thread(name = "Lambda GUI preload", isDaemon = true) { - runCatching { - prepareSkiko() - Library.staticLoad() - FontMgr.default - }.onFailure { LOG.warn("Could not preload the GUI's native library", it) } - } - return "Loaded GUI" - } - - fun toggle() { - if (isCapturingKeys) return - if (screen == null) open(Screen.ClickGui) - else close() - } - - fun open(screen: Screen) { - if (broken) { - warn("Lambda's GUI stopped after repeated errors. Restart the game to bring it back.") - return - } - if (this.screen == null) { - if (!GuiScreen.canOpenOver(mc.currentScreen)) return - if (leaving) attemptSkipTo(0f) - else jumpTo(0f) - if (ClientConfig.clientSounds) LambdaSound.ModuleOn.play() - GuiScreen.show() - AutoUpdater.onGuiOpened() - } - leaving = false - this.screen = screen - } - - fun close() { - val animated = GuiConfig.animations && GuiConfig.closeAnimation && GuiConfig.closeStyle.isNotEmpty() - if (screen == Screen.ClickGui && animated) { - if (shownPresence < 1f) attemptSkipTo(1f) - leaving = true - } - GuiScreen.close() - } - - private fun attemptSkipTo(end: Float) { - if (GuiConfig.interruptedAnimation != GuiInterrupt.Finish) return - jumpTo(end) - restarts++ - } - - private fun jumpTo(value: Float) { - animation?.cancel() - shownPresence = value - } - - fun back() { - if (screen == Screen.HudEditor) screen = Screen.ClickGui - else close() - } - - internal fun onScreenRemoved() { - if (screen == null) return - if (ClientConfig.clientSounds) LambdaSound.ModuleOff.play() - screen = null - if (!leaving) jumpTo(0f) - settled = false - input?.release() - host?.platform?.cursor = null - } - - fun render() { - if (broken) return - val size = IntSize(mc.window.framebufferWidth, mc.window.framebufferHeight) - if (size.width <= 0 || size.height <= 0) return - val density = size.height / REFERENCE_HEIGHT * GuiConfig.scale - - if (!warmedUp) { - warmedUp = true - warmUp(size, density) - } - val showsGui = screen != null || leaving - beneathHud.collect() - aboveHud.collect() - beneathGui.collect(showsGui) - aboveGui.collect(showsGui) - val showsHud = !beneathHud.isEmpty || !aboveHud.isEmpty || screen == null && Hud.shown.isNotEmpty() - if (!showsGui && !showsHud && settled) return - layered = showsGui && showsHud - - try { - val host = host ?: createHost() - settled = true - - observations.refresh() - Look.refresh() - if (screen == Screen.ClickGui) clickGuiObservations.refresh() - val sceneChanged = host.advance(size, density) - val itemsChanged = ItemAtlas.render() - val redraw = sceneChanged || itemsChanged - if (redraw) host.draw(underlay.takeIf { layered }, ItemAtlas::import) - - if (layered) host.underlayTexture?.let(GuiCompositor::blit) - GuiCompositor.composite( - host.texture ?: return, - size.width, - size.height, - redraw, - effects(density) - ) - } catch (e: Throwable) { - if (e is OutOfMemoryError) throw e - fail(e) - } - } - - private fun fail(error: Throwable) { - val now = System.nanoTime() - if (now - failedAt > FAILURE_WINDOW_NANOS) failures = 0 - failedAt = now - broken = ++failures >= MAX_FAILURES - LOG.error( - if (broken) "Lambda's interface failed again and was switched off" - else "Lambda's interface failed and is being rebuilt", - error - ) - - val failed = host - host = null - underlay = null - ItemAtlas.release() - runCatching { failed?.closeAndFree() }.onFailure { - LOG.warn("Could not free the failed interface", it) - } - observations.active.clear() - clickGuiObservations.active.clear() - if (screen != null) GuiScreen.close() - warn( - if (broken) "Lambda's interface stopped after repeated errors. Check the log, and restart the game to bring it back." - else "Lambda's interface hit an error and was restarted. Check the log for what went wrong." - ) - } - - private fun warmUp(size: IntSize, density: Float) { - val start = System.nanoTime() - try { - val host = createHost() - warmingUp = true - host.advance(size, density) - ItemAtlas.render() - host.draw(beforeScene = ItemAtlas::import) - warmingUp = false - host.advance(size, density) - LOG.info("Prepared the GUI in ${(System.nanoTime() - start) / 1_000_000} ms") - } catch (e: Throwable) { - LOG.warn("Could not prepare the GUI ahead of its first use", e) - warmingUp = false - val failed = host - host = null - ItemAtlas.release() - runCatching { failed?.closeAndFree() } - } - } - - private fun createHost(): SceneHost { - prepareSkiko() - return SceneHost(Motion) { Content() }.also { host = it } - } - - @Composable - private fun Content() { - CompositionLocalProvider( - LocalObservations provides observations, - LocalClipboard provides GameClipboard - ) { - LambdaTheme { - KeyboardFocus.Layer() - Reveal.Expiry() - Presence() - - Underlay { - beneathHud.Content() - if (screen == null) HudLayer() - aboveHud.Content() - } - beneathGui.Content() - if (screen == Screen.HudEditor) HudEditor() - Retained( - shown = showsClickGui || warmingUp, - clickGuiObservations - ) { - CompositionLocalProvider(LocalPresence provides ::presence) { ClickGui() } - } - aboveGui.Content() - if (warmingUp) WarmUp() - } - } - } - - @Composable - private 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() } - } - } - - @Composable - private fun Underlay(content: @Composable () -> Unit) { - val layer = rememberGraphicsLayer() - SideEffect { underlay = layer } - Box( - modifier = Modifier - .fillMaxSize() - .drawWithContent { - if (layered) layer.record { this@drawWithContent.drawContent() } - else drawContent() - }, - ) { content() } - } - - @Composable - private fun Presence() { - val present = screen == Screen.ClickGui - LaunchedEffect(present) { - animation = coroutineContext[Job] - val target = - if (present) 1f - else 0f - val animated = - if (present) GuiConfig.openAnimation && GuiConfig.openStyle.isNotEmpty() - else leaving - if (animated) { - val spec = Motion.gui(abs(target - shownPresence)) - animate(shownPresence, target, animationSpec = spec) { value, _ -> - shownPresence = value - } - } else shownPresence = target - if (!present) leaving = false - } - } - - @Composable - private fun WarmUp() { - SettingsList(GuiConfig.settingLayers) - PickerWarmUp() - } - - private fun effects(density: Float): GuiCompositor.Effects { - if (screen == null && !leaving) return GuiCompositor.Effects.NONE - val strength = - if (showsClickGui) presence - else 1f - return GuiCompositor.Effects( - blur = - if (GuiConfig.blur) GuiConfig.blurRadius * density * strength - else 0f, - glow = - if (GuiConfig.glow && showsClickGui) GuiConfig.glowRadius * density - else 0f, - glowIntensity = GuiConfig.glowIntensity * strength, - glowColorA = GuiConfig.glowColorA, - glowColorB = GuiConfig.glowColorB, - dim = - if (GuiConfig.dimBackground && showsClickGui) GuiConfig.dimStrength * presence - else 0f, - ) - } - - private fun shutDown() { - host?.close() - host = null - } - - private fun prepareSkiko() { - if (System.getProperty("skiko.renderApi") != null) return - System.setProperty("skiko.renderApi", "OPENGL") - System.setProperty("skiko.macos.opengl.enabled", "true") - } + private const val REFERENCE_HEIGHT = 540f + private const val MAX_FAILURES = 3 + private const val FAILURE_WINDOW_NANOS = 60_000_000_000L + + enum class Screen { + ClickGui, + HudEditor + } + + var screen: Screen? by mutableStateOf(null) + private set + + private var host: SceneHost? = null + private var failures = 0 + private var failedAt = 0L + private var broken = false + + private val beneathHud = ComposeSlot { ComposeEvent.Hud.Pre() } + private val aboveHud = ComposeSlot { ComposeEvent.Hud.Post() } + private val beneathGui = ComposeSlot { ComposeEvent.Gui.Pre() } + private val aboveGui = ComposeSlot { ComposeEvent.Gui.Post() } + private var underlay: GraphicsLayer? = null + private var layered by mutableStateOf(false) + + private var settled = true + private var warmingUp by mutableStateOf(false) + private var warmedUp = false + + private var shownPresence by mutableFloatStateOf(0f) + private var animation: Job? = null + var leaving by mutableStateOf(false) + private set + internal var restarts by mutableIntStateOf(0) + private set + internal val presence + get() = + if (warmingUp) 1f + else shownPresence + internal val transitions: Collection + get() = + if (leaving) GuiConfig.closeStyle + else GuiConfig.openStyle + internal val unfoldsOpen + get() = GuiConfig.animations && + GuiConfig.openAnimation && + GuiTransition.Unfold in GuiConfig.openStyle + private val showsClickGui + get() = screen == Screen.ClickGui || leaving + internal val foldsClosed + get() = leaving && GuiTransition.Unfold in GuiConfig.closeStyle + + private val observations = Observations() + private val clickGuiObservations = Observations() + + internal val input: SceneInput? get() = host?.input + internal val cursor: Cursor? get() = host?.platform?.cursor + internal var onEscape: (() -> Boolean)? = null + + val isCapturingKeys get() = TextFocus.isTyping || KeybindSetting.isRecording + + init { + listenUnsafe { shutDown() } + } + + override fun load(): String { + thread(name = "Lambda GUI preload", isDaemon = true) { + runCatching { + prepareSkiko() + Library.staticLoad() + FontMgr.default + }.onFailure { LOG.warn("Could not preload the GUI's native library", it) } + } + return "Loaded GUI" + } + + fun toggle() { + if (isCapturingKeys) return + if (screen == null) open(Screen.ClickGui) + else close() + } + + fun open(screen: Screen) { + if (broken) { + warn("Lambda's GUI stopped after repeated errors. Restart the game to bring it back.") + return + } + if (this.screen == null) { + if (!GuiScreen.canOpenOver(mc.currentScreen)) return + if (leaving) attemptSkipTo(0f) + else jumpTo(0f) + if (ClientConfig.clientSounds) LambdaSound.ModuleOn.play() + GuiScreen.show() + AutoUpdater.onGuiOpened() + } + leaving = false + this.screen = screen + } + + fun close() { + val animated = GuiConfig.animations && GuiConfig.closeAnimation && GuiConfig.closeStyle.isNotEmpty() + if (screen == Screen.ClickGui && animated) { + if (shownPresence < 1f) attemptSkipTo(1f) + leaving = true + } + GuiScreen.close() + } + + private fun attemptSkipTo(end: Float) { + if (GuiConfig.interruptedAnimation != GuiInterrupt.Finish) return + jumpTo(end) + restarts++ + } + + private fun jumpTo(value: Float) { + animation?.cancel() + shownPresence = value + } + + fun back() { + if (screen == Screen.HudEditor) screen = Screen.ClickGui + else close() + } + + internal fun onScreenRemoved() { + if (screen == null) return + if (ClientConfig.clientSounds) LambdaSound.ModuleOff.play() + screen = null + if (!leaving) jumpTo(0f) + settled = false + input?.release() + host?.platform?.cursor = null + } + + fun render() { + if (broken) return + val size = IntSize(mc.window.framebufferWidth, mc.window.framebufferHeight) + if (size.width <= 0 || size.height <= 0) return + val density = size.height / REFERENCE_HEIGHT * GuiConfig.scale + + if (!warmedUp) { + warmedUp = true + warmUp(size, density) + } + val showsGui = screen != null || leaving + beneathHud.collect() + aboveHud.collect() + beneathGui.collect(showsGui) + aboveGui.collect(showsGui) + val showsHud = !beneathHud.isEmpty || !aboveHud.isEmpty || screen == null && Hud.shown.isNotEmpty() + if (!showsGui && !showsHud && settled) return + layered = showsGui && showsHud + + try { + val host = host ?: createHost() + settled = true + + observations.refresh() + Look.refresh() + if (screen == Screen.ClickGui) clickGuiObservations.refresh() + val sceneChanged = host.advance(size, density) + val itemsChanged = ItemAtlas.render() + val redraw = sceneChanged || itemsChanged + if (redraw) host.draw(underlay.takeIf { layered }, ItemAtlas::import) + + if (layered) host.underlayTexture?.let(GuiCompositor::blit) + GuiCompositor.composite( + host.texture ?: return, + size.width, + size.height, + redraw, + effects(density) + ) + } catch (e: Throwable) { + if (e is OutOfMemoryError) throw e + fail(e) + } + } + + private fun fail(error: Throwable) { + val now = System.nanoTime() + if (now - failedAt > FAILURE_WINDOW_NANOS) failures = 0 + failedAt = now + broken = ++failures >= MAX_FAILURES + LOG.error( + if (broken) "Lambda's interface failed again and was switched off" + else "Lambda's interface failed and is being rebuilt", + error + ) + + val failed = host + host = null + underlay = null + ItemAtlas.release() + runCatching { failed?.closeAndFree() }.onFailure { + LOG.warn("Could not free the failed interface", it) + } + observations.active.clear() + clickGuiObservations.active.clear() + if (screen != null) GuiScreen.close() + warn( + if (broken) "Lambda's interface stopped after repeated errors. Check the log, and restart the game to bring it back." + else "Lambda's interface hit an error and was restarted. Check the log for what went wrong." + ) + } + + private fun warmUp(size: IntSize, density: Float) { + val start = System.nanoTime() + try { + val host = createHost() + warmingUp = true + host.advance(size, density) + ItemAtlas.render() + host.draw(beforeScene = ItemAtlas::import) + warmingUp = false + host.advance(size, density) + LOG.info("Prepared the GUI in ${(System.nanoTime() - start) / 1_000_000} ms") + } catch (e: Throwable) { + LOG.warn("Could not prepare the GUI ahead of its first use", e) + warmingUp = false + val failed = host + host = null + ItemAtlas.release() + runCatching { failed?.closeAndFree() } + } + } + + private fun createHost(): SceneHost { + prepareSkiko() + return SceneHost(Motion) { Content() }.also { host = it } + } + + @Composable + private fun Content() { + CompositionLocalProvider( + LocalObservations provides observations, + LocalClipboard provides GameClipboard + ) { + LambdaTheme { + KeyboardFocus.Layer() + Reveal.Expiry() + Presence() + + Underlay { + beneathHud.Content() + if (screen == null) HudLayer() + aboveHud.Content() + } + beneathGui.Content() + if (screen == Screen.HudEditor) HudEditor() + Retained(showsClickGui || warmingUp) { + CompositionLocalProvider(LocalPresence provides ::presence) { ClickGui() } + } + aboveGui.Content() + if (warmingUp) WarmUp() + } + } + } + + @Composable + private fun Retained( + shown: Boolean, + content: @Composable () -> Unit + ) { + CompositionLocalProvider( + LocalShown provides shown, + LocalObservations provides clickGuiObservations + ) { + Box( + Modifier.layout { measurable, constraints -> + val placeable = measurable.measure(constraints) + layout(placeable.width, placeable.height) { + if (shown) placeable.place(0, 0) + } + } + ) { content() } + } + } + + @Composable + private fun Underlay(content: @Composable () -> Unit) { + val layer = rememberGraphicsLayer() + SideEffect { underlay = layer } + Box( + modifier = Modifier + .fillMaxSize() + .drawWithContent { + if (layered) layer.record { this@drawWithContent.drawContent() } + else drawContent() + }, + ) { content() } + } + + @Composable + private fun Presence() { + val present = screen == Screen.ClickGui + LaunchedEffect(present) { + animation = coroutineContext[Job] + val target = + if (present) 1f + else 0f + val animated = + if (present) GuiConfig.openAnimation && GuiConfig.openStyle.isNotEmpty() + else leaving + if (animated) { + val spec = Motion.gui(abs(target - shownPresence)) + animate(shownPresence, target, animationSpec = spec) { value, _ -> + shownPresence = value + } + } else shownPresence = target + if (!present) leaving = false + } + } + + @Composable + private fun WarmUp() { + SettingsList(GuiConfig.settingLayers) + PickerWarmUp() + } + + private fun effects(density: Float): GuiCompositor.Effects { + if (screen == null && !leaving) return GuiCompositor.Effects.NONE + val strength = + if (showsClickGui) presence + else 1f + return GuiCompositor.Effects( + blur = + if (GuiConfig.blur) GuiConfig.blurRadius * density * strength + else 0f, + glow = + if (GuiConfig.glow && showsClickGui) GuiConfig.glowRadius * density + else 0f, + glowIntensity = GuiConfig.glowIntensity * strength, + glowColorA = GuiConfig.glowColorA, + glowColorB = GuiConfig.glowColorB, + dim = + if (GuiConfig.dimBackground && showsClickGui) GuiConfig.dimStrength * presence + else 0f, + ) + } + + private fun shutDown() { + host?.close() + host = null + } + + private fun prepareSkiko() { + if (System.getProperty("skiko.renderApi") != null) return + System.setProperty("skiko.renderApi", "OPENGL") + System.setProperty("skiko.macos.opengl.enabled", "true") + } } diff --git a/src/main/kotlin/com/lambda/gui/Notifications.kt b/src/main/kotlin/com/lambda/gui/Notifications.kt index c5392e3e5..6ff4ef03b 100644 --- a/src/main/kotlin/com/lambda/gui/Notifications.kt +++ b/src/main/kotlin/com/lambda/gui/Notifications.kt @@ -77,227 +77,227 @@ private const val PREVIEW_ALPHA = 0.8f @Composable internal fun Notifications() { - val notifications = NotificationHandler.notifications - if (notifications.isEmpty()) return - Scaled { Stack(notifications) } + val notifications = NotificationHandler.notifications + if (notifications.isEmpty()) return + Scaled { Stack(notifications) } } @Composable internal fun NotificationPreview() { - val option = GuiConfig.notificationOption - val limit by observe { option as? NotificationLimit ?: GuiConfig.notificationLimit } - val max by observe { GuiConfig.maxNotifications } - val leftSide = (option as? NotificationSide ?: Look.notificationSide) == NotificationSide.Left - val rising = (option as? NotificationFlow ?: Look.notificationFlow) == NotificationFlow.Up - val height = Look.notificationHeight - val screen = LocalWindowInfo.current.containerSize - var older by remember { mutableStateOf(0) } - var newest by remember { mutableStateOf(0) } - Scaled { - val margin = with(LocalDensity.current) { MARGIN.roundToPx() } - val gap = with(LocalDensity.current) { GAP.roundToPx() } - val line = margin + ((1f - height) * (screen.height - margin * 2)).roundToInt() - val room = - if (rising) line.coerceAtLeast(margin + older) - margin - else screen.height - margin - line.coerceAtMost(screen.height - margin - older) - val count = - when { - limit == NotificationLimit.Count -> max - older == 0 || newest == 0 -> PREVIEW_COUNT - else -> (1 + (room - newest) / (older + gap)).coerceAtLeast(1) - } - val newestAt = - if (rising) 0 - else count - 1 - val ghosts = - remember(count, newestAt) { - List(count) { - if (it == newestAt) Notification("Newest notification", "New ones appear here", null) - else Notification("Older notification", "", null) - } - } - val oldest = - if (count == 1) newest - else older - Overlay( - position = { window, size -> - IntOffset( - if (leftSide) margin - else window.width - margin - size.width, - ( - if (rising) line.coerceAtLeast(margin + oldest) - size.height - else line.coerceAtMost(window.height - margin - oldest) - ).coerceAtMost(window.height - margin - size.height).coerceAtLeast(margin) - ) - } - ) { - Column( - Modifier.graphicsLayer { alpha = PREVIEW_ALPHA }, - verticalArrangement = Arrangement.spacedBy(GAP) - ) { - ghosts.forEachIndexed { index, ghost -> - Card( - ghost, - leftSide, - Modifier.onSizeChanged { - if (index == newestAt) newest = it.height - else older = it.height - } - ) - } - } - } - } + val option = GuiConfig.notificationOption + val limit by observe { option as? NotificationLimit ?: GuiConfig.notificationLimit } + val max by observe { GuiConfig.maxNotifications } + val leftSide = (option as? NotificationSide ?: Look.notificationSide) == NotificationSide.Left + val rising = (option as? NotificationFlow ?: Look.notificationFlow) == NotificationFlow.Up + val height = Look.notificationHeight + val screen = LocalWindowInfo.current.containerSize + var older by remember { mutableStateOf(0) } + var newest by remember { mutableStateOf(0) } + Scaled { + val margin = with(LocalDensity.current) { MARGIN.roundToPx() } + val gap = with(LocalDensity.current) { GAP.roundToPx() } + val line = margin + ((1f - height) * (screen.height - margin * 2)).roundToInt() + val room = + if (rising) line.coerceAtLeast(margin + older) - margin + else screen.height - margin - line.coerceAtMost(screen.height - margin - older) + val count = + when { + limit == NotificationLimit.Count -> max + older == 0 || newest == 0 -> PREVIEW_COUNT + else -> (1 + (room - newest) / (older + gap)).coerceAtLeast(1) + } + val newestAt = + if (rising) 0 + else count - 1 + val ghosts = + remember(count, newestAt) { + List(count) { + if (it == newestAt) Notification("Newest notification", "New ones appear here", null) + else Notification("Older notification", "", null) + } + } + val oldest = + if (count == 1) newest + else older + Overlay( + position = { window, size -> + IntOffset( + if (leftSide) margin + else window.width - margin - size.width, + ( + if (rising) line.coerceAtLeast(margin + oldest) - size.height + else line.coerceAtMost(window.height - margin - oldest) + ).coerceAtMost(window.height - margin - size.height).coerceAtLeast(margin) + ) + } + ) { + Column( + Modifier.graphicsLayer { alpha = PREVIEW_ALPHA }, + verticalArrangement = Arrangement.spacedBy(GAP) + ) { + ghosts.forEachIndexed { index, ghost -> + Card( + ghost, + leftSide, + Modifier.onSizeChanged { + if (index == newestAt) newest = it.height + else older = it.height + } + ) + } + } + } + } } @Composable private fun Scaled(content: @Composable () -> Unit) { - val density = LocalDensity.current - val scaled = Density(density.density * Look.notificationScale, density.fontScale) - CompositionLocalProvider(LocalDensity provides scaled, content = content) + val density = LocalDensity.current + val scaled = Density(density.density * Look.notificationScale, density.fontScale) + CompositionLocalProvider(LocalDensity provides scaled, content = content) } @Composable private fun Stack(notifications: List) { - val heights = remember { mutableStateMapOf() } - val density = LocalDensity.current - val screen = LocalWindowInfo.current.containerSize - val margin = with(density) { MARGIN.roundToPx() } - val gap = with(density) { GAP.roundToPx() } - val live = notifications.filterNot { it.dismissed } - val oldest = live.firstOrNull()?.let { heights[it] } ?: 0 - val line = margin + ((1f - Look.notificationHeight) * (screen.height - margin * 2)).roundToInt() - val rising = Look.notificationFlow == NotificationFlow.Up - val anchor = - if (rising) line.coerceAtLeast(margin + oldest) - else line.coerceAtMost(screen.height - margin - oldest) - val stacked = (live.sumOf { (heights[it] ?: 0) + gap } - gap).coerceAtLeast(0) - val base = - if (rising) anchor.coerceAtLeast(margin + stacked).coerceAtMost(screen.height - margin) - else anchor.coerceAtMost(screen.height - margin - stacked).coerceAtLeast(margin) + val heights = remember { mutableStateMapOf() } + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize + val margin = with(density) { MARGIN.roundToPx() } + val gap = with(density) { GAP.roundToPx() } + val live = notifications.filterNot { it.dismissed } + val oldest = live.firstOrNull()?.let { heights[it] } ?: 0 + val line = margin + ((1f - Look.notificationHeight) * (screen.height - margin * 2)).roundToInt() + val rising = Look.notificationFlow == NotificationFlow.Up + val anchor = + if (rising) line.coerceAtLeast(margin + oldest) + else line.coerceAtMost(screen.height - margin - oldest) + val stacked = (live.sumOf { (heights[it] ?: 0) + gap } - gap).coerceAtLeast(0) + val base = + if (rising) anchor.coerceAtLeast(margin + stacked).coerceAtMost(screen.height - margin) + else anchor.coerceAtMost(screen.height - margin - stacked).coerceAtLeast(margin) - val limit by observe { GuiConfig.notificationLimit } - if (limit == NotificationLimit.Screen && live.all { it in heights }) { - val room = - if (rising) anchor - margin - else screen.height - margin - anchor - var taken = -gap - val fitting = - live.takeLastWhile { - taken += (heights[it] ?: 0) + gap - taken <= room - } - val crowded = live.dropLast(fitting.size.coerceAtLeast(1)) - SideEffect { crowded.forEach { it.dismissed = true } } - } + val limit by observe { GuiConfig.notificationLimit } + if (limit == NotificationLimit.Screen && live.all { it in heights }) { + val room = + if (rising) anchor - margin + else screen.height - margin - anchor + var taken = -gap + val fitting = + live.takeLastWhile { + taken += (heights[it] ?: 0) + gap + taken <= room + } + val crowded = live.dropLast(fitting.size.coerceAtLeast(1)) + SideEffect { crowded.forEach { it.dismissed = true } } + } - Box(Modifier.fillMaxSize()) { - notifications.forEach { notification -> - key(notification) { - val height = heights[notification] ?: 0 - val ahead = live.takeWhile { it !== notification }.sumOf { (heights[it] ?: 0) + gap } - Toast( - notification = notification, - top = - if (rising) base - ahead - height - else base + ahead, - leaving = - if (rising) height + gap - else -height - gap, - measured = notification in heights, - onMeasured = { heights[notification] = it }, - onGone = { - heights -= notification - NotificationHandler.remove(notification) - }, - ) - } - } - } + Box(Modifier.fillMaxSize()) { + notifications.forEach { notification -> + key(notification) { + val height = heights[notification] ?: 0 + val ahead = live.takeWhile { it !== notification }.sumOf { (heights[it] ?: 0) + gap } + Toast( + notification = notification, + top = + if (rising) base - ahead - height + else base + ahead, + leaving = + if (rising) height + gap + else -height - gap, + measured = notification in heights, + onMeasured = { heights[notification] = it }, + onGone = { + heights -= notification + NotificationHandler.remove(notification) + }, + ) + } + } + } } @Composable private fun Toast( - notification: Notification, - top: Int, - leaving: Int, - measured: Boolean, - onMeasured: (height: Int) -> Unit, - onGone: () -> Unit, + notification: Notification, + top: Int, + leaving: Int, + measured: Boolean, + onMeasured: (height: Int) -> Unit, + onGone: () -> Unit, ) { - val density = LocalDensity.current - val screen = LocalWindowInfo.current.containerSize - val margin = with(density) { MARGIN.toPx() } - val width = with(density) { Look.notificationWidth.toPx() } - val reach = width + margin * 4 - val leftSide = Look.notificationSide == NotificationSide.Left - val entered = remember { Animatable(0f) } - val placed = remember { Animatable(top.toFloat()) } - val opacity = remember { Animatable(1f) } - var settled by remember { mutableStateOf(false) } - LaunchedEffect(Unit) { entered.animateTo(1f, Motion.NOTIFICATIONS) } - LaunchedEffect(top, measured, notification.dismissed) { - if (notification.dismissed) return@LaunchedEffect - if (settled) placed.animateTo(top.toFloat(), Motion.NOTIFICATIONS) - else placed.snapTo(top.toFloat()) - settled = measured - } - LaunchedEffect(notification.dismissed) { - if (!notification.dismissed) return@LaunchedEffect - val end = placed.value + leaving - val leavesScreen = end >= screen.height || end + abs(leaving) <= 0 - if (!leavesScreen) launch { opacity.animateTo(0f, Motion.NOTIFICATIONS) } - placed.animateTo(end, Motion.NOTIFICATIONS) - onGone() - } + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize + val margin = with(density) { MARGIN.toPx() } + val width = with(density) { Look.notificationWidth.toPx() } + val reach = width + margin * 4 + val leftSide = Look.notificationSide == NotificationSide.Left + val entered = remember { Animatable(0f) } + val placed = remember { Animatable(top.toFloat()) } + val opacity = remember { Animatable(1f) } + var settled by remember { mutableStateOf(false) } + LaunchedEffect(Unit) { entered.animateTo(1f, Motion.NOTIFICATIONS) } + LaunchedEffect(top, measured, notification.dismissed) { + if (notification.dismissed) return@LaunchedEffect + if (settled) placed.animateTo(top.toFloat(), Motion.NOTIFICATIONS) + else placed.snapTo(top.toFloat()) + settled = measured + } + LaunchedEffect(notification.dismissed) { + if (!notification.dismissed) return@LaunchedEffect + val end = placed.value + leaving + val leavesScreen = end >= screen.height || end + abs(leaving) <= 0 + if (!leavesScreen) launch { opacity.animateTo(0f, Motion.NOTIFICATIONS) } + placed.animateTo(end, Motion.NOTIFICATIONS) + onGone() + } - Card( - notification, - leftSide, - Modifier - .offset { - val hidden = (1f - entered.value) * reach - IntOffset( - ( - if (leftSide) margin - hidden - else screen.width - margin - width + hidden - ).roundToInt(), - placed.value.roundToInt() - ) - } - .graphicsLayer { alpha = opacity.value } - .onSizeChanged { onMeasured(it.height) } - ) + Card( + notification, + leftSide, + Modifier + .offset { + val hidden = (1f - entered.value) * reach + IntOffset( + ( + if (leftSide) margin - hidden + else screen.width - margin - width + hidden + ).roundToInt(), + placed.value.roundToInt() + ) + } + .graphicsLayer { alpha = opacity.value } + .onSizeChanged { onMeasured(it.height) } + ) } @Composable private fun Card(notification: Notification, leftSide: Boolean, modifier: Modifier = Modifier) { - val colors = LambdaTheme.colors - val accent = notification.accent?.toCompose() ?: colors.primary - Row( - modifier - .width(Look.notificationWidth) - .height(IntrinsicSize.Min) - .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) - ) { - if (!leftSide) Stripe(accent) - ContentColor(colors.onSurface) { - Column(Modifier.weight(1f).padding(Look.panelPadding, Look.panelPadding / 2)) { - Text(notification.title, style = Type.label, maxLines = 1) - if (notification.message.isNotEmpty()) { - Text(notification.message, color = colors.onSurfaceVariant) - } - } - } - if (leftSide) Stripe(accent) - } + val colors = LambdaTheme.colors + val accent = notification.accent?.toCompose() ?: colors.primary + Row( + modifier + .width(Look.notificationWidth) + .height(IntrinsicSize.Min) + .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) + ) { + if (!leftSide) Stripe(accent) + ContentColor(colors.onSurface) { + Column(Modifier.weight(1f).padding(Look.panelPadding, Look.panelPadding / 2)) { + Text(notification.title, style = Type.label, maxLines = 1) + if (notification.message.isNotEmpty()) { + Text(notification.message, color = colors.onSurfaceVariant) + } + } + } + if (leftSide) Stripe(accent) + } } @Composable private fun Stripe(color: Color) = - Box( - Modifier - .width(STRIPE) - .fillMaxHeight() - .background(color) - ) + Box( + Modifier + .width(STRIPE) + .fillMaxHeight() + .background(color) + ) diff --git a/src/main/kotlin/com/lambda/gui/Reveal.kt b/src/main/kotlin/com/lambda/gui/Reveal.kt index 2b1cccd47..49eb754c6 100644 --- a/src/main/kotlin/com/lambda/gui/Reveal.kt +++ b/src/main/kotlin/com/lambda/gui/Reveal.kt @@ -34,51 +34,51 @@ import com.lambda.module.ModuleRegistry import com.lambda.module.ModuleTag internal object Reveal { - private const val MILLIS = 1800L + private const val MILLIS = 1800L - var module: Module? by mutableStateOf(null) - private set - var setting: Setting<*>? by mutableStateOf(null) - private set + var module: Module? by mutableStateOf(null) + private set + var setting: Setting<*>? by mutableStateOf(null) + private set - fun show(config: Config, setting: Setting<*>? = null) { - val owner = owner(config) - module = owner - this.setting = setting - when (owner) { - is HudModule -> LambdaGui.open(LambdaGui.Screen.HudEditor) - is Module -> uncover(owner) - else -> ClickGuiState.dialog = ClickGuiDialog.Settings(config) - } - } + fun show(config: Config, setting: Setting<*>? = null) { + val owner = owner(config) + module = owner + this.setting = setting + when (owner) { + is HudModule -> LambdaGui.open(LambdaGui.Screen.HudEditor) + is Module -> uncover(owner) + else -> ClickGuiState.dialog = ClickGuiDialog.Settings(config) + } + } - @Composable - fun Expiry() { - val module = module - val setting = setting - LaunchedEffect(module, setting) { - if (module == null && setting == null) return@LaunchedEffect - awaitFrames(MILLIS) - this@Reveal.module = null - this@Reveal.setting = null - } - } + @Composable + fun Expiry() { + val module = module + val setting = setting + LaunchedEffect(module, setting) { + if (module == null && setting == null) return@LaunchedEffect + awaitFrames(MILLIS) + this@Reveal.module = null + this@Reveal.setting = null + } + } - private fun owner(config: Config): Module? = config as? Module - ?: config.takeIf { it !== AutomationConfig.DEFAULT } - ?.let { - ModuleRegistry.modules.firstOrNull { module -> - module.automationConfig === config - } - } + private fun owner(config: Config): Module? = config as? Module + ?: config.takeIf { it !== AutomationConfig.DEFAULT } + ?.let { + ModuleRegistry.modules.firstOrNull { module -> + module.automationConfig === config + } + } - private fun uncover(module: Module) { - val tag = module.tag - if (tag == ModuleTag.DEBUG) ClickGuiState.developerMode = - true else ModuleTag.shownTags += tag - module.showInClickGui.value = true - GuiConfig.windows[tag.name]?.takeIf { it.collapsed }?.let { - GuiConfig.windows += tag.name to it.copy(collapsed = false) - } - } + private fun uncover(module: Module) { + val tag = module.tag + if (tag == ModuleTag.DEBUG) ClickGuiState.developerMode = + true else ModuleTag.shownTags += tag + module.showInClickGui.value = true + GuiConfig.windows[tag.name]?.takeIf { it.collapsed }?.let { + GuiConfig.windows += tag.name to it.copy(collapsed = false) + } + } } diff --git a/src/main/kotlin/com/lambda/gui/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt index 85e27dcc5..951c69434 100644 --- a/src/main/kotlin/com/lambda/gui/Snap.kt +++ b/src/main/kotlin/com/lambda/gui/Snap.kt @@ -35,111 +35,111 @@ import kotlin.math.max import kotlin.math.roundToInt internal object Snap { - private const val MIN_GRID_STEP = 4f - private val GRID_COLOR = Color.White.copy(alpha = 0.11f) - - data class Guides(val x: Float?, val y: Float?) { - companion object { - val NONE = Guides(null, null) - } - } - - data class Result(val position: Offset, val guides: Guides) - - private class Target(val shift: Float, val guide: Float?) - - val isActive: Boolean - get() = - GuiConfig.snapEnabled && - (GuiConfig.snapKey == Bind.EMPTY || GuiConfig.snapKey.isSatisfied()) - - private fun gridStep(density: Density) = - with(density) { max(MIN_GRID_STEP, GuiConfig.gridSize.dp.toPx()) } - - fun free(element: Rect, area: Rect) = - Result(element.topLeft.keptIn(area, element.size), Guides.NONE) - - fun snap( - element: Rect, - others: Collection, - area: Rect, - density: Density, - spacing: Float = 0f - ): Result = - with(density) { - fun axis(start: (Rect) -> Float, end: (Rect) -> Float): Target { - fun center(rect: Rect) = (start(rect) + end(rect)) / 2 - val from = start(element) - val size = end(element) - from - fun startAt(at: Float, guide: Float? = at) = Target(at - from, guide) - fun endAt(at: Float, guide: Float? = at) = Target(at - size - from, guide) - fun centerAt(at: Float, guide: Float? = at) = Target(at - size / 2 - from, guide) - - val neighbours = - buildList { - if (GuiConfig.snapToEdges) { - others.forEach { other -> - add(startAt(start(other))) - add(endAt(end(other))) - add(startAt(end(other) + spacing, end(other) + spacing / 2)) - add(endAt(start(other) - spacing, start(other) - spacing / 2)) - } - } - if (GuiConfig.snapToCenters) others.forEach { add(centerAt(center(it))) } - } - val middle = center(area) - val screenCenter = - listOf( - startAt(middle), - centerAt(middle), - endAt(middle) - ).takeIf { GuiConfig.snapToScreenCenter }.orEmpty() - val step = gridStep(density) - fun onGrid(line: Float) = (line / step).roundToInt() * step - val grid = - listOf( - startAt(onGrid(from), null), - centerAt(onGrid(from + size / 2), null), - endAt(onGrid(from + size), null), - ).takeIf { GuiConfig.snapToGrid }.orEmpty() - - return listOf( - neighbours to GuiConfig.snapDistanceElement.dp.toPx(), - screenCenter to GuiConfig.snapDistanceScreen.dp.toPx(), - grid to GuiConfig.snapDistanceGrid.dp.toPx(), - ).firstNotNullOfOrNull { (targets, reach) -> - targets.minByOrNull { abs(it.shift) }?.takeIf { abs(it.shift) <= reach } - } ?: Target(0f, null) - } - - val x = axis({ it.left }, { it.right }) - val y = axis({ it.top }, { it.bottom }) - Result((element.topLeft + Offset(x.shift, y.shift)).keptIn(area, element.size), Guides(x.guide, y.guide)) - } - - fun Modifier.snapLines(drop: () -> Result?): Modifier = - drawWithContent { - val guides = drop()?.guides.takeIf { GuiConfig.showSnapLines } - if (guides != null && isActive && GuiConfig.snapToGrid) drawGrid() - drawContent() - if (guides != null) { - val color = GuiConfig.snapLineColor.toCompose() - guides.x?.let { drawLine(color, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } - guides.y?.let { drawLine(color, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } - } - } - - private fun DrawScope.drawGrid() { - val step = gridStep(this) - generateSequence(0f) { it + step }.takeWhile { it <= size.width } - .forEach { drawLine(GRID_COLOR, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } - generateSequence(0f) { it + step }.takeWhile { it <= size.height } - .forEach { drawLine(GRID_COLOR, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } - } - - private fun Offset.keptIn(area: Rect, element: Size) = - Offset( - x.coerceIn(area.left, max(area.left, area.right - element.width)), - y.coerceIn(area.top, max(area.top, area.bottom - element.height)) - ) + private const val MIN_GRID_STEP = 4f + private val GRID_COLOR = Color.White.copy(alpha = 0.11f) + + data class Guides(val x: Float?, val y: Float?) { + companion object { + val NONE = Guides(null, null) + } + } + + data class Result(val position: Offset, val guides: Guides) + + private class Target(val shift: Float, val guide: Float?) + + val isActive: Boolean + get() = + GuiConfig.snapEnabled && + (GuiConfig.snapKey == Bind.EMPTY || GuiConfig.snapKey.isSatisfied()) + + private fun gridStep(density: Density) = + with(density) { max(MIN_GRID_STEP, GuiConfig.gridSize.dp.toPx()) } + + fun free(element: Rect, area: Rect) = + Result(element.topLeft.keptIn(area, element.size), Guides.NONE) + + fun snap( + element: Rect, + others: Collection, + area: Rect, + density: Density, + spacing: Float = 0f + ): Result = + with(density) { + fun axis(start: (Rect) -> Float, end: (Rect) -> Float): Target { + fun center(rect: Rect) = (start(rect) + end(rect)) / 2 + val from = start(element) + val size = end(element) - from + fun startAt(at: Float, guide: Float? = at) = Target(at - from, guide) + fun endAt(at: Float, guide: Float? = at) = Target(at - size - from, guide) + fun centerAt(at: Float, guide: Float? = at) = Target(at - size / 2 - from, guide) + + val neighbours = + buildList { + if (GuiConfig.snapToEdges) { + others.forEach { other -> + add(startAt(start(other))) + add(endAt(end(other))) + add(startAt(end(other) + spacing, end(other) + spacing / 2)) + add(endAt(start(other) - spacing, start(other) - spacing / 2)) + } + } + if (GuiConfig.snapToCenters) others.forEach { add(centerAt(center(it))) } + } + val middle = center(area) + val screenCenter = + listOf( + startAt(middle), + centerAt(middle), + endAt(middle) + ).takeIf { GuiConfig.snapToScreenCenter }.orEmpty() + val step = gridStep(density) + fun onGrid(line: Float) = (line / step).roundToInt() * step + val grid = + listOf( + startAt(onGrid(from), null), + centerAt(onGrid(from + size / 2), null), + endAt(onGrid(from + size), null), + ).takeIf { GuiConfig.snapToGrid }.orEmpty() + + return listOf( + neighbours to GuiConfig.snapDistanceElement.dp.toPx(), + screenCenter to GuiConfig.snapDistanceScreen.dp.toPx(), + grid to GuiConfig.snapDistanceGrid.dp.toPx(), + ).firstNotNullOfOrNull { (targets, reach) -> + targets.minByOrNull { abs(it.shift) }?.takeIf { abs(it.shift) <= reach } + } ?: Target(0f, null) + } + + val x = axis({ it.left }, { it.right }) + val y = axis({ it.top }, { it.bottom }) + Result((element.topLeft + Offset(x.shift, y.shift)).keptIn(area, element.size), Guides(x.guide, y.guide)) + } + + fun Modifier.snapLines(drop: () -> Result?): Modifier = + drawWithContent { + val guides = drop()?.guides.takeIf { GuiConfig.showSnapLines } + if (guides != null && isActive && GuiConfig.snapToGrid) drawGrid() + drawContent() + if (guides != null) { + val color = GuiConfig.snapLineColor.toCompose() + guides.x?.let { drawLine(color, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } + guides.y?.let { drawLine(color, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } + } + } + + private fun DrawScope.drawGrid() { + val step = gridStep(this) + generateSequence(0f) { it + step }.takeWhile { it <= size.width } + .forEach { drawLine(GRID_COLOR, Offset(it, 0f), Offset(it, size.height), Stroke.HairlineWidth) } + generateSequence(0f) { it + step }.takeWhile { it <= size.height } + .forEach { drawLine(GRID_COLOR, Offset(0f, it), Offset(size.width, it), Stroke.HairlineWidth) } + } + + private fun Offset.keptIn(area: Rect, element: Size) = + Offset( + x.coerceIn(area.left, max(area.left, area.right - element.width)), + y.coerceIn(area.top, max(area.top, area.bottom - element.height)) + ) } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt index ba45334aa..2c3960ddb 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/CategoryWindow.kt @@ -89,244 +89,254 @@ import kotlin.math.absoluteValue private val REACH = 40.dp private const val IN_ROW = 1.5f private val EMBOSS = - Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05f), Color.Transparent)) + Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.05f), Color.Transparent)) @Composable internal fun CategoryWindow( - tag: ModuleTag, - defaultPosition: DpOffset, - bounds: MutableMap, - snapping: Boolean, - onDrop: (Snap.Result?) -> Unit, - settings: OpenSettings, - inline: Boolean, - onFocus: () -> Unit, - modifier: Modifier = Modifier, + tag: ModuleTag, + defaultPosition: DpOffset, + bounds: MutableMap, + snapping: Boolean, + onDrop: (Snap.Result?) -> Unit, + settings: OpenSettings, + inline: Boolean, + onFocus: () -> Unit, + modifier: Modifier = Modifier, ) { - val modules by - observe { - ModuleRegistry.modules.filter { it.tag == tag && it.showInClickGui.value } - } - if (modules.isEmpty()) return + val modules by + observe { + ModuleRegistry.modules.filter { it.tag == tag && it.showInClickGui.value } + } + if (modules.isEmpty()) return - val colors = LambdaTheme.colors - val density = LocalDensity.current - val screen = LocalWindowInfo.current.containerSize.toSize() - val screenHeight = with(density) { screen.height.toDp() } - val area = - Rect( - 0f, - with(density) { MENU_BAR_HEIGHT.toPx() }, - screen.width, - screen.height - ) + val colors = LambdaTheme.colors + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize.toSize() + val screenHeight = with(density) { screen.height.toDp() } + val area = + Rect( + 0f, + with(density) { MENU_BAR_HEIGHT.toPx() }, + screen.width, + screen.height + ) - val placement by observe { GuiConfig.windows[tag.name] } - val position = placement?.takeUnless { it.inRow }?.let { DpOffset(it.x.dp, it.y.dp) } - val collapsed = placement?.collapsed ?: false + val placement by observe { GuiConfig.windows[tag.name] } + val position = placement?.takeUnless { it.inRow }?.let { DpOffset(it.x.dp, it.y.dp) } + val collapsed = placement?.collapsed ?: false - var dragged by remember { mutableStateOf(null) } - val drop = - dragged?.let { corner -> - val window = Rect(corner, bounds[tag]?.size ?: Size.Zero) - if (snapping) { - Snap.snap( - window, - bounds.filterKeys { it != tag }.values, - area, - density, - with(density) { Look.windowGap.toPx() } - ) - } - else Snap.free(window, area) - } - if (drop != null) SideEffect { onDrop(drop) } - val shownPosition = - drop?.let { - with(density) { DpOffset(it.position.x.toDp(), it.position.y.toDp()) } - } ?: (position ?: defaultPosition).let { at -> - val screenWidth = with(density) { screen.width.toDp() } - DpOffset( - at.x.coerceIn( - 0.dp, - (screenWidth - Look.windowWidth).coerceAtLeast(0.dp) - ), - at.y.coerceIn( - MENU_BAR_HEIGHT, - (screenHeight - REACH).coerceAtLeast(MENU_BAR_HEIGHT) - ), - ) - } - val currentPosition by rememberUpdatedState(shownPosition) - DisposableEffect(tag) { - onDispose { bounds -= tag } - } + var dragged by remember { mutableStateOf(null) } + val drop = + dragged?.let { corner -> + val window = Rect(corner, bounds[tag]?.size ?: Size.Zero) + if (snapping) { + Snap.snap( + window, + bounds.filterKeys { it != tag }.values, + area, + density, + with(density) { Look.windowGap.toPx() } + ) + } + else Snap.free(window, area) + } + if (drop != null) SideEffect { onDrop(drop) } + val shownPosition = + drop?.let { + with(density) { DpOffset(it.position.x.toDp(), it.position.y.toDp()) } + } ?: (position ?: defaultPosition).let { at -> + val screenWidth = with(density) { screen.width.toDp() } + DpOffset( + at.x.coerceIn( + 0.dp, + (screenWidth - Look.windowWidth).coerceAtLeast(0.dp) + ), + at.y.coerceIn( + MENU_BAR_HEIGHT, + (screenHeight - REACH).coerceAtLeast(MENU_BAR_HEIGHT) + ), + ) + } + val currentPosition by rememberUpdatedState(shownPosition) + DisposableEffect(tag) { + onDispose { bounds -= tag } + } - fun place(at: DpOffset, collapsed: Boolean) { - val inRow = (at.x - defaultPosition.x).value.absoluteValue < IN_ROW && - (at.y - defaultPosition.y).value.absoluteValue < IN_ROW - GuiConfig.windows += tag.name to - if (inRow) GuiConfig.WindowPlacement.inRow(collapsed) - else GuiConfig.WindowPlacement(at.x.value, at.y.value, collapsed) - } - LaunchedEffect(placement) { - position?.let { place(it, collapsed) } - } + fun place(at: DpOffset, collapsed: Boolean) { + val inRow = (at.x - defaultPosition.x).value.absoluteValue < IN_ROW && + (at.y - defaultPosition.y).value.absoluteValue < IN_ROW + GuiConfig.windows += tag.name to + if (inRow) GuiConfig.WindowPlacement.inRow(collapsed) + else GuiConfig.WindowPlacement(at.x.value, at.y.value, collapsed) + } + LaunchedEffect(placement) { + position?.let { place(it, collapsed) } + } - Column( - modifier = modifier - .offset(shownPosition.x, shownPosition.y) - .width(Look.windowWidth) - .onGloballyPositioned { bounds[tag] = Rect(it.positionInRoot(), it.size.toSize()) } - .pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent(PointerEventPass.Initial) - if (event.type == PointerEventType.Press) onFocus() - } - } - } - .window(colors.surface, colors.border, RoundedCornerShape(Look.windowRounding)) - ) { - Text( - text = tag.name, - color = colors.onHeader, - style = Type.title.shadowed(), - maxLines = 1, - modifier = Modifier - .fillMaxWidth() - .background(colors.header) - .mouseDraggable( - onDragStart = { dragged = bounds[tag]?.topLeft }, - onDragEnd = { - if (dragged != null) place(currentPosition, collapsed) - dragged = null - onDrop(null) - }, - ) { delta -> dragged = dragged?.plus(delta) } - .mouseClickable(onRightClick = { - if (!collapsed) settings.close(modules) - place(currentPosition, !collapsed) - }) - .padding(horizontal = Look.modulePadding, vertical = 2.dp) - ) + Column( + modifier = modifier + .offset(shownPosition.x, shownPosition.y) + .width(Look.windowWidth) + .onGloballyPositioned { bounds[tag] = Rect(it.positionInRoot(), it.size.toSize()) } + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Press) onFocus() + } + } + } + .window(colors.surface, colors.border, RoundedCornerShape(Look.windowRounding)) + ) { + Text( + text = tag.name, + color = colors.onHeader, + style = Type.title.shadowed(), + maxLines = 1, + modifier = Modifier + .fillMaxWidth() + .background(colors.header) + .mouseDraggable( + onDragStart = { dragged = bounds[tag]?.topLeft }, + onDragEnd = { + if (dragged != null) place(currentPosition, collapsed) + dragged = null + onDrop(null) + }, + ) { delta -> dragged = dragged?.plus(delta) } + .mouseClickable(onRightClick = { + if (!collapsed) settings.close(modules) + place(currentPosition, !collapsed) + }) + .padding(horizontal = Look.modulePadding, vertical = 2.dp) + ) - val shown = LocalShown.current - val folding = LambdaGui.foldsClosed - val unfolded = - remember(shown, LambdaGui.restarts) { - MutableTransitionState( - (folding || !LambdaGui.unfoldsOpen) && shown && !collapsed - ) - } - unfolded.targetState = shown && !folding && !collapsed - val settled = unfolded.isIdle && unfolded.currentState - val hanging = modules.mapNotNull(settings::panelOf) - SideEffect { hanging.forEach { it.settled = settled } } - AnimatedVisibility( - visibleState = unfolded, - enter = expandVertically(Motion.windows), - exit = - shrinkVertically( - if (folding) Motion.guiFold - else Motion.windows - ), - ) { - ScrollColumn( - Modifier.heightIn( - max = (screenHeight - shownPosition.y - 24.dp).coerceAtLeast(48.dp) - ) - ) { - modules.forEach { module -> - ModuleRow( - module = module, - isEdited = settings.isOpen(module), - isLast = module === modules.last(), - pressedIn = !inline, - panel = settings.panelOf(module).takeUnless { inline }, - onEdit = { settings.toggle(module) }, - ) - if (inline) { - InlineSettings( - settings.stateOf(module), - open = settings.isOpen(module) - ) - } - } - } - } - } + val shown = LocalShown.current + val folding = LambdaGui.foldsClosed + val unfolded = + remember(shown, LambdaGui.restarts) { + MutableTransitionState( + (folding || !LambdaGui.unfoldsOpen) && shown && !collapsed + ) + } + unfolded.targetState = shown && !folding && !collapsed + val settled = unfolded.isIdle && unfolded.currentState + val hanging = modules.mapNotNull(settings::panelOf) + val unfolding = unfolded.targetState + SideEffect { + hanging.forEach { + it.unfolding = unfolding + it.settled = settled + } + } + AnimatedVisibility( + visibleState = unfolded, + enter = expandVertically(Motion.windows), + exit = + shrinkVertically( + if (folding) Motion.guiFold + else Motion.windows + ), + ) { + ScrollColumn( + Modifier.heightIn( + max = (screenHeight - shownPosition.y - 24.dp).coerceAtLeast(48.dp) + ) + ) { + modules.forEach { module -> + ModuleRow( + module = module, + isEdited = settings.isOpen(module), + isLast = module === modules.last(), + pressedIn = !inline, + panel = settings.panelOf(module).takeUnless { inline }, + onEdit = { settings.toggle(module) }, + ) + if (inline) { + InlineSettings( + settings.stateOf(module), + open = settings.isOpen(module) + ) + } + } + } + } + } } @Composable private fun ModuleRow( - module: Module, - isEdited: Boolean, - isLast: Boolean, - pressedIn: Boolean, - panel: SettingsPanelState?, - onEdit: () -> Unit + module: Module, + isEdited: Boolean, + isLast: Boolean, + pressedIn: Boolean, + panel: SettingsPanelState?, + onEdit: () -> Unit ) { - val colors = LambdaTheme.colors - val end = - if (isLast && Look.outlines) Look.outlineWidth - else 0.dp - val enabled by observe { module.isEnabled } - val fill by - animateColorAsState( - if (enabled) colors.moduleEnabled else Color.Transparent, - spring() - ) - val pressed by - animateColorAsState( - if (isEdited && pressedIn) colors.inset.copy(alpha = colors.inset.alpha / 2) - else Color.Transparent, - spring() - ) + val colors = LambdaTheme.colors + val end = + if (isLast && Look.outlines) Look.outlineWidth + else 0.dp + val enabled by observe { module.isEnabled } + val fill by + animateColorAsState( + if (enabled) colors.moduleEnabled else Color.Transparent, + spring() + ) + val pressed by + animateColorAsState( + if (isEdited && pressedIn) colors.inset.copy(alpha = colors.inset.alpha / 2) + else Color.Transparent, + spring() + ) - val revealed = Reveal.module === module && Reveal.setting == null - val lit by - animateColorAsState( - if (revealed) colors.onSurface.copy(alpha = 0.4f) else Color.Transparent, - tween(250) - ) - val intoView = remember { BringIntoViewRequester() } - LaunchedEffect(revealed) { - if (revealed) intoView.bringIntoView() - } + val revealed = Reveal.module === module && Reveal.setting == null + val lit by + animateColorAsState( + if (revealed) colors.onSurface.copy(alpha = 0.4f) else Color.Transparent, + tween(250) + ) + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(revealed) { + if (revealed) intoView.bringIntoView() + } + DisposableEffect(panel) { + onDispose { panel?.placed = false } + } - Tooltip(module.description, Modifier.fillMaxWidth()) { - Box( - contentAlignment = Centered.START, - modifier = Modifier - .fillMaxWidth() - .then( - if (panel == null) Modifier - else Modifier.onGloballyPositioned { - panel.row = Rect(it.positionInRoot(), it.size.toSize()) - } - ) - .bringIntoViewRequester(intoView) - .mouseClickable(onRightClick = onEdit) { - if (module.alwaysEnabled) onEdit() else module.toggle() - } - .background(fill) - .background(pressed) - .background(lit) - .hoverHighlight(colors.raised) - .then(if (Look.emboss) Modifier.background(EMBOSS) else Modifier) - .heightIn(min = Look.rowHeight + end) - .padding(start = Look.modulePadding, end = Look.modulePadding, bottom = end) - ) { - SlidingText( - text = module.name, - color = when { - enabled -> colors.onModuleEnabled - isEdited -> colors.onSurface - else -> colors.onSurfaceVariant - }, - style = Type.body.shadowed(), - ) - } - } + Tooltip(module.description, Modifier.fillMaxWidth()) { + Box( + contentAlignment = Centered.START, + modifier = Modifier + .fillMaxWidth() + .then( + if (panel == null) Modifier + else Modifier.onGloballyPositioned { + panel.row = Rect(it.positionInRoot(), it.size.toSize()) + panel.placed = true + } + ) + .bringIntoViewRequester(intoView) + .mouseClickable(onRightClick = onEdit) { + if (module.alwaysEnabled) onEdit() else module.toggle() + } + .background(fill) + .background(pressed) + .background(lit) + .hoverHighlight(colors.raised) + .then(if (Look.emboss) Modifier.background(EMBOSS) else Modifier) + .heightIn(min = Look.rowHeight + end) + .padding(start = Look.modulePadding, end = Look.modulePadding, bottom = end) + ) { + SlidingText( + text = module.name, + color = when { + enabled -> colors.onModuleEnabled + isEdited -> colors.onSurface + else -> colors.onSurfaceVariant + }, + style = Type.body.shadowed(), + ) + } + } } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index d79126b02..e3aa97988 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -69,146 +69,146 @@ internal val CLICK_GUI_CATEGORIES = ModuleTag.defaults - ModuleTag.HUD private class RowLayout(var row: Triple, var shown: Boolean = false) internal sealed interface ClickGuiDialog { - data object About : ClickGuiDialog - data object NewAutomationConfig : ClickGuiDialog - data class Settings(val config: Config) : ClickGuiDialog + data object About : ClickGuiDialog + data object NewAutomationConfig : ClickGuiDialog + data class Settings(val config: Config) : ClickGuiDialog } internal object ClickGuiState { - var dialog: ClickGuiDialog? by mutableStateOf(null) - var developerMode by mutableStateOf(false) - var focusSearch by mutableStateOf(false) + var dialog: ClickGuiDialog? by mutableStateOf(null) + var developerMode by mutableStateOf(false) + var focusSearch by mutableStateOf(false) } @Composable internal fun ClickGui() { - val density = LocalDensity.current - val screen = LocalWindowInfo.current.containerSize - val developerMode = ClickGuiState.developerMode - val tags by observe { - CLICK_GUI_CATEGORIES.filter(ModuleTag::isTagShown) + - listOfNotNull(ModuleTag.DEBUG.takeIf { developerMode }) - } - - val settings = remember { OpenSettings() } - val inline by observe { GuiConfig.inlineSettings } - - val revealedModule = Reveal.module - val revealedSetting = Reveal.setting - LaunchedEffect(revealedModule, revealedSetting) { - if ( - revealedModule != null && - revealedModule !is HudModule && - revealedSetting != null - ) { - settings.open(revealedModule) - } - } - - val shown = LocalShown.current - LaunchedEffect(shown) { - if (!shown && !GuiConfig.keepSettingsOpen) settings.forget() - } - - val row = Triple(Look.windowWidth, Look.windowGap, Look.windowTop) - val laidOut = remember { RowLayout(row) } - SideEffect { - if (row != laidOut.row && shown && laidOut.shown) { - GuiConfig.windows = - GuiConfig.windows.mapValues { - GuiConfig.WindowPlacement.inRow(it.value.collapsed) - } - } - laidOut.row = row - laidOut.shown = shown - } - - val stacking = remember { mutableStateListOf() } - val bounds = remember { mutableStateMapOf() } - val snapping by observe { Snap.isActive } - var drop by remember { mutableStateOf(null) } - - Box( - Modifier.fillMaxSize().mouseClickable( - keyboard = false, - onClick = settings::closeAll - ).snapLines { - drop - }.guiPresence() - ) { - val inRow = tags.count { it != ModuleTag.DEBUG } - val screenWidth = with(density) { screen.width.toDp() } - val pitch = - (Look.windowWidth + Look.windowGap) - .coerceAtMost( - (screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1) - ) - .coerceAtLeast(0.dp) - val rowWidth = Look.windowWidth + pitch * (inRow - 1) - val rowStart = ((screenWidth - rowWidth) / 2).coerceAtLeast(0.dp) - - tags.forEachIndexed { index, tag -> - key(tag) { - CategoryWindow( - tag = tag, - defaultPosition = DpOffset(rowStart + pitch * index, Look.windowTop), - bounds = bounds, - snapping = snapping, - onDrop = { drop = it }, - settings = settings, - inline = inline, - onFocus = { - stacking.remove(tag) - stacking.add(tag) - }, - modifier = Modifier.zIndex(stacking.indexOf(tag).toFloat()) - ) - } - } - - settings.panels.forEach { panel -> - key(panel.module) { - SettingsPanel( - panel = panel, - open = settings.isOpen(panel.module) && !inline, - windows = bounds, - onClosed = { settings.closed(panel.module) }, - modifier = Modifier.zIndex(stacking.size.toFloat()) - ) - } - } - - MenuBar( - Modifier - .align(Alignment.TopStart) - .zIndex(stacking.size + 1f) - .pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent(PointerEventPass.Initial) - if (event.type == PointerEventType.Press) settings.closeAll() - } - } - } - ) - Button( - label = "HUD Editor", - modifier = Modifier - .align(Alignment.BottomEnd) - .padding(4.dp) - .zIndex(stacking.size + 1f), - prominent = true, - ) { LambdaGui.open(LambdaGui.Screen.HudEditor) } - } - - val prompt = observe { AutoUpdater.prompt }.value - val closeDialog = { ClickGuiState.dialog = null } - val dialog = ClickGuiState.dialog - when { - prompt != null -> LoaderPromptDialog(prompt) - dialog is ClickGuiDialog.About -> AboutDialog(closeDialog) - dialog is ClickGuiDialog.NewAutomationConfig -> - NewAutomationConfigDialog(closeDialog) - dialog is ClickGuiDialog.Settings -> ConfigDialog(dialog.config, closeDialog) - } + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize + val developerMode = ClickGuiState.developerMode + val tags by observe { + CLICK_GUI_CATEGORIES.filter(ModuleTag::isTagShown) + + listOfNotNull(ModuleTag.DEBUG.takeIf { developerMode }) + } + + val settings = remember { OpenSettings() } + val inline by observe { GuiConfig.inlineSettings } + + val revealedModule = Reveal.module + val revealedSetting = Reveal.setting + LaunchedEffect(revealedModule, revealedSetting) { + if ( + revealedModule != null && + revealedModule !is HudModule && + revealedSetting != null + ) { + settings.open(revealedModule) + } + } + + val shown = LocalShown.current + LaunchedEffect(shown) { + if (!shown && !GuiConfig.keepSettingsOpen) settings.forget() + } + + val row = Triple(Look.windowWidth, Look.windowGap, Look.windowTop) + val laidOut = remember { RowLayout(row) } + SideEffect { + if (row != laidOut.row && shown && laidOut.shown) { + GuiConfig.windows = + GuiConfig.windows.mapValues { + GuiConfig.WindowPlacement.inRow(it.value.collapsed) + } + } + laidOut.row = row + laidOut.shown = shown + } + + val stacking = remember { mutableStateListOf() } + val bounds = remember { mutableStateMapOf() } + val snapping by observe { Snap.isActive } + var drop by remember { mutableStateOf(null) } + + Box( + Modifier.fillMaxSize().mouseClickable( + keyboard = false, + onClick = settings::closeAll + ).snapLines { + drop + }.guiPresence() + ) { + val inRow = tags.count { it != ModuleTag.DEBUG } + val screenWidth = with(density) { screen.width.toDp() } + val pitch = + (Look.windowWidth + Look.windowGap) + .coerceAtMost( + (screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1) + ) + .coerceAtLeast(0.dp) + val rowWidth = Look.windowWidth + pitch * (inRow - 1) + val rowStart = ((screenWidth - rowWidth) / 2).coerceAtLeast(0.dp) + + tags.forEachIndexed { index, tag -> + key(tag) { + CategoryWindow( + tag = tag, + defaultPosition = DpOffset(rowStart + pitch * index, Look.windowTop), + bounds = bounds, + snapping = snapping, + onDrop = { drop = it }, + settings = settings, + inline = inline, + onFocus = { + stacking.remove(tag) + stacking.add(tag) + }, + modifier = Modifier.zIndex(stacking.indexOf(tag).toFloat()) + ) + } + } + + settings.panels.forEach { panel -> + key(panel.module) { + SettingsPanel( + panel = panel, + open = settings.isOpen(panel.module) && !inline, + windows = bounds, + onClosed = { settings.closed(panel.module) }, + modifier = Modifier.zIndex(stacking.size.toFloat()) + ) + } + } + + MenuBar( + Modifier + .align(Alignment.TopStart) + .zIndex(stacking.size + 1f) + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Press) settings.closeAll() + } + } + } + ) + Button( + label = "HUD Editor", + modifier = Modifier + .align(Alignment.BottomEnd) + .padding(4.dp) + .zIndex(stacking.size + 1f), + prominent = true, + ) { LambdaGui.open(LambdaGui.Screen.HudEditor) } + } + + val prompt = observe { AutoUpdater.prompt }.value + val closeDialog = { ClickGuiState.dialog = null } + val dialog = ClickGuiState.dialog + when { + prompt != null -> LoaderPromptDialog(prompt) + dialog is ClickGuiDialog.About -> AboutDialog(closeDialog) + dialog is ClickGuiDialog.NewAutomationConfig -> + NewAutomationConfigDialog(closeDialog) + dialog is ClickGuiDialog.Settings -> ConfigDialog(dialog.config, closeDialog) + } } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt index a049b2fe4..2349459d9 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt @@ -29,53 +29,55 @@ import com.lambda.gui.settings.PanelPage import com.lambda.module.Module internal class SettingsPanelState(val module: Module) { - var page by mutableStateOf(PanelPage.Settings) - var extension by mutableStateOf(0.dp) - var row by mutableStateOf(Rect.Zero) - var settled by mutableStateOf(false) + var page by mutableStateOf(PanelPage.Settings) + var extension by mutableStateOf(0.dp) + var row by mutableStateOf(Rect.Zero) + var placed by mutableStateOf(false) + var unfolding by mutableStateOf(false) + var settled by mutableStateOf(false) } @Stable internal class OpenSettings { - private val states = HashMap() - private val open = mutableStateListOf() - private val closing = mutableStateListOf() + private val states = HashMap() + private val open = mutableStateListOf() + private val closing = mutableStateListOf() - val panels: List get() = (open + closing).map(::stateOf) + val panels: List get() = (open + closing).map(::stateOf) - fun stateOf(module: Module) = states.getOrPut(module) { SettingsPanelState(module) } + fun stateOf(module: Module) = states.getOrPut(module) { SettingsPanelState(module) } - fun panelOf(module: Module) = - if (module in open || module in closing) stateOf(module) - else null + fun panelOf(module: Module) = + if (module in open || module in closing) stateOf(module) + else null - fun isOpen(module: Module) = module in open + fun isOpen(module: Module) = module in open - fun open(module: Module) { - if (!GuiConfig.multipleSettings) closeAll() - closing -= module - if (module !in open) open += module - } + fun open(module: Module) { + if (!GuiConfig.multipleSettings) closeAll() + closing -= module + if (module !in open) open += module + } - fun toggle(module: Module) = - if (isOpen(module)) close(module) - else open(module) + fun toggle(module: Module) = + if (isOpen(module)) close(module) + else open(module) - fun close(module: Module) { - if (open.remove(module)) closing += module - } + fun close(module: Module) { + if (open.remove(module)) closing += module + } - fun close(modules: Collection) = - open.filter { it in modules }.forEach(::close) + fun close(modules: Collection) = + open.filter { it in modules }.forEach(::close) - fun closeAll() = open.toList().forEach(::close) + fun closeAll() = open.toList().forEach(::close) - fun closed(module: Module) { - closing -= module - } + fun closed(module: Module) { + closing -= module + } - fun forget() { - open.clear() - closing.clear() - } + fun forget() { + open.clear() + closing.clear() + } } diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index b374c1be9..7c95218fd 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -99,209 +99,211 @@ private val WIDTH_CHANGE = spring(stiffness = Spring.StiffnessMedium) @Composable internal fun SettingsPanel( - panel: SettingsPanelState, - open: Boolean, - windows: Map, - onClosed: () -> Unit, - modifier: Modifier = Modifier, + panel: SettingsPanelState, + open: Boolean, + windows: Map, + onClosed: () -> Unit, + modifier: Modifier = Modifier, ) { - val row = panel.row - val visibility = remember(LocalShown.current) { MutableTransitionState(false) } - val wanted = open && panel.settled && !row.isEmpty - val popups = remember { PopupHost() } - SideEffect { popups.closing = !wanted } - visibility.targetState = wanted - if (!open && visibility.isIdle && !visibility.currentState) { - SideEffect(onClosed) - return - } - if (row.isEmpty) return + val row = panel.row + val visibility = remember(LocalShown.current) { MutableTransitionState(false) } + val window = windows[panel.module.tag] + val beneath = window == null || row.top >= window.top + val hung = panel.placed && (panel.settled || panel.unfolding && beneath) + val wanted = open && hung && !row.isEmpty + val popups = remember { PopupHost() } + SideEffect { popups.closing = !wanted } + visibility.targetState = wanted + if (!open && visibility.isIdle && !visibility.currentState) { + SideEffect(onClosed) + return + } + if (row.isEmpty) return - val density = LocalDensity.current - val screen = LocalWindowInfo.current.containerSize - var size by remember { mutableStateOf(IntSize.Zero) } - var unfolded by remember { mutableStateOf(0) } + val density = LocalDensity.current + val screen = LocalWindowInfo.current.containerSize + var size by remember { mutableStateOf(IntSize.Zero) } + var unfolded by remember { mutableStateOf(0) } - val scroll = rememberScrollState() - val screenHeight = with(density) { screen.height.toDp() } - val barBottom = with(density) { MENU_BAR_HEIGHT.toPx() } - val window = windows[panel.module.tag] - val top = - ( - if (window == null) row.top - else { - row.top.coerceIn( - window.top, - (window.bottom - row.height).coerceAtLeast(window.top) - ) - } - ).coerceAtLeast(barBottom) - val below = with(density) { (screen.height - top).toDp() }.coerceAtLeast(MIN_HEIGHT) - val highest = screenHeight - MENU_BAR_HEIGHT - val maxHeight = (below + panel.extension).coerceAtMost(highest) + val scroll = rememberScrollState() + val screenHeight = with(density) { screen.height.toDp() } + val barBottom = with(density) { MENU_BAR_HEIGHT.toPx() } + val top = + ( + if (window == null) row.top + else { + row.top.coerceIn( + window.top, + (window.bottom - row.height).coerceAtLeast(window.top) + ) + } + ).coerceAtLeast(barBottom) + val below = with(density) { (screen.height - top).toDp() }.coerceAtLeast(MIN_HEIGHT) + val highest = screenHeight - MENU_BAR_HEIGHT + val maxHeight = (below + panel.extension).coerceAtMost(highest) - val overlap = with(density) { 1.dp.toPx() } - val fitsRight = row.right - overlap + size.width <= screen.width - val fitsLeft = row.left + overlap - size.width >= 0 - val flipped = !fitsRight && (fitsLeft || row.left > screen.width - row.right) - val lift = (top + unfolded - screen.height).coerceIn(0f, top - barBottom) + val overlap = with(density) { 1.dp.toPx() } + val fitsRight = row.right - overlap + size.width <= screen.width + val fitsLeft = row.left + overlap - size.width >= 0 + val flipped = !fitsRight && (fitsLeft || row.left > screen.width - row.right) + val lift = (top + unfolded - screen.height).coerceIn(0f, top - barBottom) - val shape = - RoundedCornerShape( - topStart = if (flipped || lift > 0f) Look.panelRounding else 0.dp, - topEnd = if (!flipped || lift > 0f) Look.panelRounding else 0.dp, - bottomEnd = Look.panelRounding, - bottomStart = Look.panelRounding, - ) - val seam = - if (flipped) Alignment.TopEnd - else Alignment.TopStart + val shape = + RoundedCornerShape( + topStart = if (flipped || lift > 0f) Look.panelRounding else 0.dp, + topEnd = if (!flipped || lift > 0f) Look.panelRounding else 0.dp, + bottomEnd = Look.panelRounding, + bottomStart = Look.panelRounding, + ) + val seam = + if (flipped) Alignment.TopEnd + else Alignment.TopStart - Box( - modifier - .offset { - val room = (screen.width - size.width).coerceAtLeast(0) - IntOffset( - if (flipped) (row.left + overlap).roundToInt().coerceIn(screen.width - room, screen.width) - else (row.right - overlap).roundToInt().coerceIn(0, room), - (top - lift).roundToInt() - ) - } - .size(0.dp) - .wrapContentSize(seam, unbounded = true) - ) { - AnimatedVisibility( - visibleState = visibility, - modifier = Modifier - .onSizeChanged { unfolded = it.height } - .onGloballyPositioned { popups.place(it.boundsInWindow()) } - .dropShadow(RoundedCornerShape(Look.panelRounding)) - .window(LambdaTheme.colors.panel, LambdaTheme.colors.border, shape), - enter = expandIn(Motion.panels, seam), - exit = shrinkOut(Motion.panels, seam), - ) { - Box( - Modifier - .widthIn(MIN_PANEL_WIDTH, Look.settingsWidth) - .heightIn(max = maxHeight) - .widthOfContent() - .onSizeChanged { size = it } - ) { - CompositionLocalProvider(LocalPopupHost provides popups) { - Column(Modifier.padding(Look.panelPadding)) { - ModuleSettings( - panel.module, - panel.page, - { panel.page = it }, - scroll - ) - } - } - if (scroll.maxValue > 0 || lift > 0f) { - Grip( - onDragStart = { - panel.extension = panel.extension.coerceAtMost(with(density) { lift.toDp() }) - }, - onDrag = { up -> - val needed = panel.extension + with(density) { scroll.maxValue.toDp() } - panel.extension = - (panel.extension + up).coerceIn( - 0.dp, - needed - .coerceAtMost(highest - below) - .coerceAtLeast(0.dp) - ) - }, - modifier = Modifier.align(Alignment.TopCenter) - ) - } - } - } - } + Box( + modifier + .offset { + val room = (screen.width - size.width).coerceAtLeast(0) + IntOffset( + if (flipped) (row.left + overlap).roundToInt().coerceIn(screen.width - room, screen.width) + else (row.right - overlap).roundToInt().coerceIn(0, room), + (top - lift).roundToInt() + ) + } + .size(0.dp) + .wrapContentSize(seam, unbounded = true) + ) { + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier + .onSizeChanged { unfolded = it.height } + .onGloballyPositioned { popups.place(it.boundsInWindow()) } + .dropShadow(RoundedCornerShape(Look.panelRounding)) + .window(LambdaTheme.colors.panel, LambdaTheme.colors.border, shape), + enter = expandIn(Motion.panels, seam), + exit = shrinkOut(Motion.panels, seam), + ) { + Box( + Modifier + .widthIn(MIN_PANEL_WIDTH, Look.settingsWidth) + .heightIn(max = maxHeight) + .widthOfContent() + .onSizeChanged { size = it } + ) { + CompositionLocalProvider(LocalPopupHost provides popups) { + Column(Modifier.padding(Look.panelPadding)) { + ModuleSettings( + panel.module, + panel.page, + { panel.page = it }, + scroll + ) + } + } + if (scroll.maxValue > 0 || lift > 0f) { + Grip( + onDragStart = { + panel.extension = panel.extension.coerceAtMost(with(density) { lift.toDp() }) + }, + onDrag = { up -> + val needed = panel.extension + with(density) { scroll.maxValue.toDp() } + panel.extension = + (panel.extension + up).coerceIn( + 0.dp, + needed + .coerceAtMost(highest - below) + .coerceAtLeast(0.dp) + ) + }, + modifier = Modifier.align(Alignment.TopCenter) + ) + } + } + } + } } @Composable internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { - val intoView = remember { BringIntoViewRequester() } - LaunchedEffect(open) { - if (open) { - awaitFrames(SETTLE_MILLIS) - intoView.bringIntoView() - } - } - Expandable(open) { - val colors = LambdaTheme.colors - Column( - Modifier - .fillMaxWidth() - .bringIntoViewRequester(intoView) - .background(colors.panel) - .background(colors.inset.copy(alpha = colors.inset.alpha / 4)) - .drawWithCache { - val depth = INSET_SHADOW.toPx().coerceAtMost(size.height / 2) - val dark = colors.inset.copy(alpha = colors.inset.alpha / 2) - val top = Brush.verticalGradient(listOf(dark, Color.Transparent), 0f, depth) - val bottom = - Brush.verticalGradient( - listOf(Color.Transparent, dark), - size.height - depth, - size.height - ) - onDrawBehind { - drawRect(top, size = Size(size.width, depth)) - drawRect( - bottom, - Offset(0f, size.height - depth), - Size(size.width, depth) - ) - } - } - .padding(Look.panelPadding / 2) - ) { ModuleSettings(panel.module, panel.page, { panel.page = it }, scroll = null) } - } + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(open) { + if (open) { + awaitFrames(SETTLE_MILLIS) + intoView.bringIntoView() + } + } + Expandable(open) { + val colors = LambdaTheme.colors + Column( + Modifier + .fillMaxWidth() + .bringIntoViewRequester(intoView) + .background(colors.panel) + .background(colors.inset.copy(alpha = colors.inset.alpha / 4)) + .drawWithCache { + val depth = INSET_SHADOW.toPx().coerceAtMost(size.height / 2) + val dark = colors.inset.copy(alpha = colors.inset.alpha / 2) + val top = Brush.verticalGradient(listOf(dark, Color.Transparent), 0f, depth) + val bottom = + Brush.verticalGradient( + listOf(Color.Transparent, dark), + size.height - depth, + size.height + ) + onDrawBehind { + drawRect(top, size = Size(size.width, depth)) + drawRect( + bottom, + Offset(0f, size.height - depth), + Size(size.width, depth) + ) + } + } + .padding(Look.panelPadding / 2) + ) { ModuleSettings(panel.module, panel.page, { panel.page = it }, scroll = null) } + } } internal fun Modifier.widthOfContent(): Modifier = - composed { - val scope = rememberCoroutineScope() - var width by remember { mutableStateOf?>(null) } - layout { measurable, constraints -> - val wanted = - measurable.maxIntrinsicWidth(constraints.maxHeight) - .coerceIn(constraints.minWidth, constraints.maxWidth).toFloat() - val current = width ?: Animatable(wanted).also { width = it } - if (current.targetValue != wanted) { - scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } - } + composed { + val scope = rememberCoroutineScope() + var width by remember { mutableStateOf?>(null) } + layout { measurable, constraints -> + val wanted = + measurable.maxIntrinsicWidth(constraints.maxHeight) + .coerceIn(constraints.minWidth, constraints.maxWidth).toFloat() + val current = width ?: Animatable(wanted).also { width = it } + if (current.targetValue != wanted) { + scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } + } - val placeable = - measurable.measure( - Constraints.fixedWidth(current.value.roundToInt()).copy( - maxHeight = constraints.maxHeight - ) - ) - layout(placeable.width, placeable.height) { placeable.place(0, 0) } - } - } + val placeable = + measurable.measure( + Constraints.fixedWidth(current.value.roundToInt()).copy( + maxHeight = constraints.maxHeight + ) + ) + layout(placeable.width, placeable.height) { placeable.place(0, 0) } + } + } @Composable private fun Grip( - onDragStart: () -> Unit, - onDrag: (up: Dp) -> Unit, - modifier: Modifier = Modifier + onDragStart: () -> Unit, + onDrag: (up: Dp) -> Unit, + modifier: Modifier = Modifier ) { - val density = LocalDensity.current - val color = LambdaTheme.colors.onSurfaceVariant - Box( - contentAlignment = Centered.BOTH, - modifier = modifier - .fillMaxWidth() - .height(Look.panelPadding.coerceAtLeast(MIN_GRIP_HEIGHT)) - .pointerHoverIcon(ResizeVerticalIcon) - .mouseDraggable(onDragStart = onDragStart) { delta -> - onDrag(with(density) { -delta.y.toDp() }) - } - ) { - Spacer(Modifier.size(16.dp, 1.dp).background(color, RoundedCornerShape(50))) - } + val density = LocalDensity.current + val color = LambdaTheme.colors.onSurfaceVariant + Box( + contentAlignment = Centered.BOTH, + modifier = modifier + .fillMaxWidth() + .height(Look.panelPadding.coerceAtLeast(MIN_GRIP_HEIGHT)) + .pointerHoverIcon(ResizeVerticalIcon) + .mouseDraggable(onDragStart = onDragStart) { delta -> + onDrag(with(density) { -delta.y.toDp() }) + } + ) { + Spacer(Modifier.size(16.dp, 1.dp).background(color, RoundedCornerShape(50))) + } } diff --git a/src/main/kotlin/com/lambda/gui/component/Centered.kt b/src/main/kotlin/com/lambda/gui/component/Centered.kt index aec8fd16b..f18b7f458 100644 --- a/src/main/kotlin/com/lambda/gui/component/Centered.kt +++ b/src/main/kotlin/com/lambda/gui/component/Centered.kt @@ -21,10 +21,10 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.BiasAlignment internal object Centered { - private const val RISE = -0.004f + private const val RISE = -0.004f - val VERTICALLY: Alignment.Vertical = BiasAlignment.Vertical(RISE) - val START: Alignment = BiasAlignment(-1f, RISE) - val END: Alignment = BiasAlignment(1f, RISE) - val BOTH: Alignment = BiasAlignment(0f, RISE) + val VERTICALLY: Alignment.Vertical = BiasAlignment.Vertical(RISE) + val START: Alignment = BiasAlignment(-1f, RISE) + val END: Alignment = BiasAlignment(1f, RISE) + val BOTH: Alignment = BiasAlignment(0f, RISE) } diff --git a/src/main/kotlin/com/lambda/gui/component/Controls.kt b/src/main/kotlin/com/lambda/gui/component/Controls.kt index c2ecfaf2e..0ed802299 100644 --- a/src/main/kotlin/com/lambda/gui/component/Controls.kt +++ b/src/main/kotlin/com/lambda/gui/component/Controls.kt @@ -73,271 +73,271 @@ private val LEADING_GAP = 3.dp @Composable fun Button( - label: String, - modifier: Modifier = Modifier, - enabled: Boolean = true, - prominent: Boolean = false, - onClick: () -> Unit, + label: String, + modifier: Modifier = Modifier, + enabled: Boolean = true, + prominent: Boolean = false, + onClick: () -> Unit, ) { - val colors = LambdaTheme.colors - val fill = - if (prominent) colors.header - else colors.control - val text = - if (prominent) colors.onHeader - else colors.onControl - Box( - contentAlignment = Centered.BOTH, - modifier = modifier - .heightIn(min = Look.rowHeight + 2.dp) - .clip(RoundedCornerShape(Look.controlRounding)) - .background(fill) - .hoverHighlight(text.copy(alpha = if (enabled) 0.12f else 0f)) - .mouseClickable(enabled, onClick = onClick) - .padding(horizontal = 5.dp, vertical = 1.dp) - ) { - Text(label, color = if (enabled) text else colors.onSurfaceVariant, maxLines = 1) - } + val colors = LambdaTheme.colors + val fill = + if (prominent) colors.header + else colors.control + val text = + if (prominent) colors.onHeader + else colors.onControl + Box( + contentAlignment = Centered.BOTH, + modifier = modifier + .heightIn(min = Look.rowHeight + 2.dp) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(fill) + .hoverHighlight(text.copy(alpha = if (enabled) 0.12f else 0f)) + .mouseClickable(enabled, onClick = onClick) + .padding(horizontal = 5.dp, vertical = 1.dp) + ) { + Text(label, color = if (enabled) text else colors.onSurfaceVariant, maxLines = 1) + } } @Composable fun Checkmark(checked: Boolean, modifier: Modifier = Modifier) { - val colors = LambdaTheme.colors - Canvas( - modifier - .size(9.dp) - .clip(RoundedCornerShape(Look.boxRounding)) - .background(if (checked) colors.primary else colors.track) - ) { - if (!checked) return@Canvas - val side = size.minDimension - drawPath( - path = Path().apply { - moveTo(side * 0.22f, side * 0.52f) - lineTo(side * 0.42f, side * 0.72f) - lineTo(side * 0.78f, side * 0.28f) - }, - color = colors.onControl, - style = Stroke(side * 0.16f, cap = StrokeCap.Round, join = StrokeJoin.Round) - ) - } + val colors = LambdaTheme.colors + Canvas( + modifier + .size(9.dp) + .clip(RoundedCornerShape(Look.boxRounding)) + .background(if (checked) colors.primary else colors.track) + ) { + if (!checked) return@Canvas + val side = size.minDimension + drawPath( + path = Path().apply { + moveTo(side * 0.22f, side * 0.52f) + lineTo(side * 0.42f, side * 0.72f) + lineTo(side * 0.78f, side * 0.28f) + }, + color = colors.onControl, + style = Stroke(side * 0.16f, cap = StrokeCap.Round, join = StrokeJoin.Round) + ) + } } @Composable fun Ellipsis(modifier: Modifier = Modifier, color: Color = LocalContentColor.current) { - Canvas(modifier.size(7.dp, 5.dp)) { - val dot = 1.dp.toPx() - val top = (size.height - dot) / 2 - repeat(3) { - drawRect(color, Offset(it * (size.width - dot) / 2, top), Size(dot, dot)) - } - } + Canvas(modifier.size(7.dp, 5.dp)) { + val dot = 1.dp.toPx() + val top = (size.height - dot) / 2 + repeat(3) { + drawRect(color, Offset(it * (size.width - dot) / 2, top), Size(dot, dot)) + } + } } @Composable fun Chevron( - degrees: Float, - modifier: Modifier = Modifier, - color: Color = LocalContentColor.current + 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 - ) - } + Canvas(modifier.size(5.dp).rotate(degrees)) { + drawPath( + path = Path().apply { + moveTo(size.width * 0.2f, size.height * 0.1f) + lineTo(size.width * 0.9f, size.height * 0.5f) + lineTo(size.width * 0.2f, size.height * 0.9f) + close() + }, + color = color + ) + } } @Composable fun Expandable( - visible: Boolean, - modifier: Modifier = Modifier, - content: @Composable () -> Unit + 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() } + AnimatedVisibility( + visible = visible, + modifier = modifier, + enter = expandVertically(tween(TOGGLE_MILLIS)) + fadeIn(tween(TOGGLE_MILLIS)), + exit = shrinkVertically(tween(TOGGLE_MILLIS)) + fadeOut(tween(TOGGLE_MILLIS)), + ) { content() } } @Composable fun Section( - title: String, - revealed: Boolean = false, - content: @Composable ColumnScope.() -> Unit, + title: String, + revealed: Boolean = false, + content: @Composable ColumnScope.() -> Unit, ) { - val colors = LambdaTheme.colors - var expanded by remember { mutableStateOf(false) } - LaunchedEffect(revealed) { - if (revealed) expanded = true - } - val turn by animateFloatAsState(if (expanded) 90f else 0f, tween(TOGGLE_MILLIS)) - val rowHeight = Look.rowHeight + val colors = LambdaTheme.colors + var expanded by remember { mutableStateOf(false) } + LaunchedEffect(revealed) { + if (revealed) expanded = true + } + val turn by animateFloatAsState(if (expanded) 90f else 0f, tween(TOGGLE_MILLIS)) + val rowHeight = Look.rowHeight - Column( - Modifier - .fillMaxWidth() - .padding(top = 1.dp) - .drawWithContent { - drawContent() - if (size.height > rowHeight.toPx() + 1f) { - drawRect(colors.secondary, size = Size(SECTION_BAR.toPx(), size.height)) - } - } - ) { - Row( - verticalAlignment = Centered.VERTICALLY, - horizontalArrangement = Arrangement.spacedBy(3.dp), - modifier = Modifier - .fillMaxWidth() - .heightIn(min = Look.rowHeight) - .clip(RoundedCornerShape(Look.controlRounding)) - .background(colors.raised) - .mouseClickable { expanded = !expanded } - .padding(horizontal = 4.dp) - ) { - Chevron(turn, color = colors.onSurface) - Text(title, color = colors.onSurface, maxLines = 1) - } - Expandable(expanded) { - Column( - Modifier.fillMaxWidth().padding(start = Look.groupIndent, top = 1.dp), - content = content - ) - } - } + Column( + Modifier + .fillMaxWidth() + .padding(top = 1.dp) + .drawWithContent { + drawContent() + if (size.height > rowHeight.toPx() + 1f) { + drawRect(colors.secondary, size = Size(SECTION_BAR.toPx(), size.height)) + } + } + ) { + Row( + verticalAlignment = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.raised) + .mouseClickable { expanded = !expanded } + .padding(horizontal = 4.dp) + ) { + Chevron(turn, color = colors.onSurface) + Text(title, color = colors.onSurface, maxLines = 1) + } + Expandable(expanded) { + Column( + Modifier.fillMaxWidth().padding(start = Look.groupIndent, top = 1.dp), + content = content + ) + } + } } @Composable fun Chip( - onClick: () -> Unit, - modifier: Modifier = Modifier, - content: @Composable RowScope.() -> Unit + onClick: () -> Unit, + modifier: Modifier = Modifier, + content: @Composable RowScope.() -> Unit ) { - val colors = LambdaTheme.colors - ContentColor(colors.onControl) { - Row( - verticalAlignment = Centered.VERTICALLY, - horizontalArrangement = Arrangement.spacedBy(3.dp), - modifier = modifier - .height(Look.rowHeight) - .clip(RoundedCornerShape(Look.controlRounding)) - .background(colors.control) - .hoverHighlight(colors.onControl.copy(alpha = 0.12f)) - .mouseClickable(onClick = onClick) - .padding(horizontal = 4.dp), - content = content - ) - } + val colors = LambdaTheme.colors + ContentColor(colors.onControl) { + Row( + verticalAlignment = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = modifier + .height(Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.control) + .hoverHighlight(colors.onControl.copy(alpha = 0.12f)) + .mouseClickable(onClick = onClick) + .padding(horizontal = 4.dp), + content = content + ) + } } @Composable fun Dropdown( - label: String, - options: List, - selected: T, - optionLabel: (T) -> String, - modifier: Modifier = Modifier, - leading: @Composable () -> Unit = {}, - onOptionHover: (option: T?) -> Unit = {}, - onOptionClick: (option: T) -> Unit = {}, - onSelect: (T) -> Unit, + label: String, + options: List, + selected: T, + optionLabel: (T) -> String, + modifier: Modifier = Modifier, + leading: @Composable () -> Unit = {}, + onOptionHover: (option: T?) -> Unit = {}, + onOptionClick: (option: T) -> Unit = {}, + onSelect: (T) -> Unit, ) { - val menu = remember { MenuState() } - var chip by remember { mutableStateOf(IntSize.Zero) } - var hovered by remember { mutableStateOf(null) } - val currentOnOptionHover by rememberUpdatedState(onOptionHover) - LaunchedEffect(hovered) { currentOnOptionHover(hovered) } - DisposableEffect(Unit) { - onDispose { currentOnOptionHover(null) } - } - LabeledRow(label, modifier, leading) { - Box(Modifier.onSizeChanged { chip = it }) { - Chip(onClick = menu::toggle) { - SlidingText(optionLabel(selected), Modifier.weight(1f, fill = false)) - Chevron(90f) - } - Menu( - menu.isOpen, - onDismiss = menu::dismiss, - unfoldFrom = IntSize(chip.width, 0) - ) { - options.forEach { option -> - MenuItem( - optionLabel(option), - selected = option == selected, - onHover = { - if (it) hovered = option - else if (hovered == option) hovered = null - } - ) { - onOptionClick(option) - if (option != selected) onSelect(option) - } - } - } - } - } + val menu = remember { MenuState() } + var chip by remember { mutableStateOf(IntSize.Zero) } + var hovered by remember { mutableStateOf(null) } + val currentOnOptionHover by rememberUpdatedState(onOptionHover) + LaunchedEffect(hovered) { currentOnOptionHover(hovered) } + DisposableEffect(Unit) { + onDispose { currentOnOptionHover(null) } + } + LabeledRow(label, modifier, leading) { + Box(Modifier.onSizeChanged { chip = it }) { + Chip(onClick = menu::toggle) { + SlidingText(optionLabel(selected), Modifier.weight(1f, fill = false)) + Chevron(90f) + } + Menu( + menu.isOpen, + onDismiss = menu::dismiss, + unfoldFrom = IntSize(chip.width, 0) + ) { + options.forEach { option -> + MenuItem( + optionLabel(option), + selected = option == selected, + onHover = { + if (it) hovered = option + else if (hovered == option) hovered = null + } + ) { + onOptionClick(option) + if (option != selected) onSelect(option) + } + } + } + } + } } @Composable fun LabeledRow( - label: String, - modifier: Modifier = Modifier, - leading: @Composable () -> Unit = {}, - editor: @Composable RowScope.() -> Unit + label: String, + modifier: Modifier = Modifier, + leading: @Composable () -> Unit = {}, + editor: @Composable RowScope.() -> Unit ) { - Layout( - content = { - Row( - verticalAlignment = Centered.VERTICALLY, - horizontalArrangement = Arrangement.spacedBy(LEADING_GAP) - ) { - leading() - Text(label, maxLines = 1) - } - Row( - verticalAlignment = Centered.VERTICALLY, - horizontalArrangement = Arrangement.spacedBy(LABEL_GAP), - content = editor - ) - }, - modifier = modifier.fillMaxWidth().heightIn(min = Look.rowHeight), - ) { (name, edited), constraints -> - val gap = LABEL_GAP.roundToPx() - val loose = constraints.copy(minWidth = 0, minHeight = 0) - val room = constraints.maxWidth - val wanted = edited.maxIntrinsicWidth(constraints.maxHeight) - val editorWidth = - if (!constraints.hasBoundedWidth) wanted - else { - wanted.coerceAtMost( - maxOf( - room - name.maxIntrinsicWidth(constraints.maxHeight) - gap, - room * 3 / 5 - ) - ) - } - val editor = edited.measure(loose.copy(maxWidth = editorWidth.coerceAtLeast(0))) - val nameRoom = - if (constraints.hasBoundedWidth) (room - editor.width - gap).coerceAtLeast(0) - else Constraints.Infinity - val text = name.measure(loose.copy(maxWidth = nameRoom)) + Layout( + content = { + Row( + verticalAlignment = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(LEADING_GAP) + ) { + leading() + Text(label, maxLines = 1) + } + Row( + verticalAlignment = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(LABEL_GAP), + content = editor + ) + }, + modifier = modifier.fillMaxWidth().heightIn(min = Look.rowHeight), + ) { (name, edited), constraints -> + val gap = LABEL_GAP.roundToPx() + val loose = constraints.copy(minWidth = 0, minHeight = 0) + val room = constraints.maxWidth + val wanted = edited.maxIntrinsicWidth(constraints.maxHeight) + val editorWidth = + if (!constraints.hasBoundedWidth) wanted + else { + wanted.coerceAtMost( + maxOf( + room - name.maxIntrinsicWidth(constraints.maxHeight) - gap, + room * 3 / 5 + ) + ) + } + val editor = edited.measure(loose.copy(maxWidth = editorWidth.coerceAtLeast(0))) + val nameRoom = + if (constraints.hasBoundedWidth) (room - editor.width - gap).coerceAtLeast(0) + else Constraints.Infinity + val text = name.measure(loose.copy(maxWidth = nameRoom)) - val width = - if (constraints.hasBoundedWidth) room - else text.width + gap + editor.width - val height = maxOf(text.height, editor.height, constraints.minHeight) - layout(width, height) { - text.place(0, (height - text.height) / 2) - editor.place(width - editor.width, (height - editor.height) / 2) - } - } + val width = + if (constraints.hasBoundedWidth) room + else text.width + gap + editor.width + val height = maxOf(text.height, editor.height, constraints.minHeight) + layout(width, height) { + text.place(0, (height - text.height) / 2) + editor.place(width - editor.width, (height - editor.height) / 2) + } + } } diff --git a/src/main/kotlin/com/lambda/gui/component/Images.kt b/src/main/kotlin/com/lambda/gui/component/Images.kt index 558852697..2fc2eb492 100644 --- a/src/main/kotlin/com/lambda/gui/component/Images.kt +++ b/src/main/kotlin/com/lambda/gui/component/Images.kt @@ -38,27 +38,27 @@ import kotlin.math.roundToInt @Composable fun rememberTexture(path: String): ImageBitmap = - remember(path) { - path.stream - .use { Image.makeFromEncoded(it.readAllBytes()) } - .toComposeImageBitmap() - } + remember(path) { + path.stream + .use { Image.makeFromEncoded(it.readAllBytes()) } + .toComposeImageBitmap() + } @Composable fun ItemIcon(stack: ItemStack, size: Dp, modifier: Modifier = Modifier) { - val slot = remember { ItemAtlas.Slot() } - val density = LocalDensity.current - val pixels = - with(density) { - ItemAtlas.ITEM * (size.toPx() / ItemAtlas.ITEM).roundToInt().coerceAtLeast(1) - } - SideEffect { - slot.stack = stack - slot.size = pixels - } - DisposableEffect(slot) { - ItemAtlas.add(slot) - onDispose { ItemAtlas.remove(slot) } - } - Spacer(modifier.size(with(density) { pixels.toDp() }).drawBehind { drawItem(slot) }) + val slot = remember { ItemAtlas.Slot() } + val density = LocalDensity.current + val pixels = + with(density) { + ItemAtlas.ITEM * (size.toPx() / ItemAtlas.ITEM).roundToInt().coerceAtLeast(1) + } + SideEffect { + slot.stack = stack + slot.size = pixels + } + DisposableEffect(slot) { + ItemAtlas.add(slot) + onDispose { ItemAtlas.remove(slot) } + } + Spacer(modifier.size(with(density) { pixels.toDp() }).drawBehind { drawItem(slot) }) } diff --git a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt index 4c2dd50e8..8edc9057f 100644 --- a/src/main/kotlin/com/lambda/gui/component/Keyboard.kt +++ b/src/main/kotlin/com/lambda/gui/component/Keyboard.kt @@ -50,42 +50,42 @@ private val FOCUS_MARK = 1.dp val LocalKeyboardReachable = compositionLocalOf { true } internal object KeyboardFocus { - var visible by mutableStateOf(false) + var visible by mutableStateOf(false) - private val layers = ArrayList() + private val layers = ArrayList() - fun move(direction: FocusDirection) = layers.lastOrNull()?.moveFocus(direction) == true + fun move(direction: FocusDirection) = layers.lastOrNull()?.moveFocus(direction) == true - @Composable - fun Layer() { - val manager = LocalFocusManager.current - DisposableEffect(manager) { - layers += manager - onDispose { layers -= manager } - } - } + @Composable + fun Layer() { + val manager = LocalFocusManager.current + DisposableEffect(manager) { + layers += manager + onDispose { layers -= manager } + } + } } fun Modifier.keyboardFocusable(onKey: (KeyEvent) -> Boolean): Modifier = - composed { - if (!LocalKeyboardReachable.current) return@composed Modifier - var focused by remember { mutableStateOf(false) } - val handle by rememberUpdatedState(onKey) - val mark = LambdaTheme.colors.onSurface - onFocusChanged { focused = it.isFocused } - .onKeyEvent { it.type == KeyEventType.KeyDown && KeyboardFocus.visible && handle(it) } - .focusable() - .drawWithContent { - drawContent() - if (!focused || !KeyboardFocus.visible) return@drawWithContent - val width = FOCUS_MARK.toPx() - drawRect( - mark, - Offset(width / 2, width / 2), - Size(size.width - width, size.height - width), - style = Stroke(width) - ) - } - } + composed { + if (!LocalKeyboardReachable.current) return@composed Modifier + var focused by remember { mutableStateOf(false) } + val handle by rememberUpdatedState(onKey) + val mark = LambdaTheme.colors.onSurface + onFocusChanged { focused = it.isFocused } + .onKeyEvent { it.type == KeyEventType.KeyDown && KeyboardFocus.visible && handle(it) } + .focusable() + .drawWithContent { + drawContent() + if (!focused || !KeyboardFocus.visible) return@drawWithContent + val width = FOCUS_MARK.toPx() + drawRect( + mark, + Offset(width / 2, width / 2), + Size(size.width - width, size.height - width), + style = Stroke(width) + ) + } + } internal val KeyEvent.isActivation get() = key == Key.Enter || key == Key.Spacebar diff --git a/src/main/kotlin/com/lambda/gui/component/Pointer.kt b/src/main/kotlin/com/lambda/gui/component/Pointer.kt index 7ee39924c..ae825641a 100644 --- a/src/main/kotlin/com/lambda/gui/component/Pointer.kt +++ b/src/main/kotlin/com/lambda/gui/component/Pointer.kt @@ -46,134 +46,134 @@ val LocalClickOnRelease = compositionLocalOf { false } @OptIn(ExperimentalComposeUiApi::class) fun Modifier.mouseClickable( - enabled: Boolean = true, - keyboard: Boolean = true, - onRightClick: (() -> Unit)? = null, - onClick: (() -> Unit)? = null, + enabled: Boolean = true, + keyboard: Boolean = true, + onRightClick: (() -> Unit)? = null, + onClick: (() -> Unit)? = null, ): Modifier = - if (!enabled) this - else composed { - val onRelease = LocalClickOnRelease.current - val actionFor by rememberUpdatedState { button: PointerButton? -> - when (button) { - PointerButton.Primary -> onClick - PointerButton.Secondary -> onRightClick - else -> null - } - } - val keys = - if (!keyboard) Modifier - else Modifier.keyboardFocusable { event -> - val action = - if (event.isShiftPressed) onRightClick - else onClick ?: onRightClick - if (event.isActivation) action?.invoke() - event.isActivation && action != null - } - keys.pointerInput(onRelease) { - awaitPointerEventScope { - while (true) { - val press = awaitPointerEvent() - val down = press.changes.first() - val button = press.button - if (press.type != PointerEventType.Press || down.isConsumed || actionFor(button) == null) continue - down.consume() - if (!onRelease) { - actionFor(button)?.invoke() - continue - } + if (!enabled) this + else composed { + val onRelease = LocalClickOnRelease.current + val actionFor by rememberUpdatedState { button: PointerButton? -> + when (button) { + PointerButton.Primary -> onClick + PointerButton.Secondary -> onRightClick + else -> null + } + } + val keys = + if (!keyboard) Modifier + else Modifier.keyboardFocusable { event -> + val action = + if (event.isShiftPressed) onRightClick + else onClick ?: onRightClick + if (event.isActivation) action?.invoke() + event.isActivation && action != null + } + keys.pointerInput(onRelease) { + awaitPointerEventScope { + while (true) { + val press = awaitPointerEvent() + val down = press.changes.first() + val button = press.button + if (press.type != PointerEventType.Press || down.isConsumed || actionFor(button) == null) continue + down.consume() + if (!onRelease) { + actionFor(button)?.invoke() + continue + } - while (true) { - val event = awaitPointerEvent() - val change = event.changes.first() - if (event.type == PointerEventType.Press) break - if (event.type != PointerEventType.Release || event.button != button) continue - change.consume() - val inside = change.position.x in 0f..size.width.toFloat() && - change.position.y in 0f..size.height.toFloat() - if (inside) actionFor(button)?.invoke() - break - } - } - } - } - } + while (true) { + val event = awaitPointerEvent() + val change = event.changes.first() + if (event.type == PointerEventType.Press) break + if (event.type != PointerEventType.Release || event.button != button) continue + change.consume() + val inside = change.position.x in 0f..size.width.toFloat() && + change.position.y in 0f..size.height.toFloat() + if (inside) actionFor(button)?.invoke() + break + } + } + } + } + } fun Modifier.onMousePress( - button: PointerButton, - onPress: (position: Offset) -> Unit + button: PointerButton, + onPress: (position: Offset) -> Unit ): Modifier = - onPress { pressed, position -> - if (pressed == button) onPress(position) - pressed == button - } + onPress { pressed, position -> + if (pressed == button) onPress(position) + pressed == button + } @OptIn(ExperimentalComposeUiApi::class) private fun Modifier.onPress( - handle: (button: PointerButton?, position: Offset) -> Boolean + 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() - } - } - } - } + composed { + val currentHandle by rememberUpdatedState(handle) + pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.first() + if (event.type != PointerEventType.Press || change.isConsumed) continue + if (currentHandle(event.button, change.position)) change.consume() + } + } + } + } fun Modifier.consumeClicks(): Modifier = - pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent() - if (event.type == PointerEventType.Press) event.changes.forEach { it.consume() } - } - } - } + pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + if (event.type == PointerEventType.Press) event.changes.forEach { it.consume() } + } + } + } @OptIn(ExperimentalFoundationApi::class) fun Modifier.mouseDraggable( - onDragStart: () -> Unit = {}, - onDragEnd: () -> Unit = {}, - onDrag: (Offset) -> Unit, + onDragStart: () -> Unit = {}, + onDragEnd: () -> Unit = {}, + onDrag: (Offset) -> Unit, ): Modifier = - onDrag( - matcher = PointerMatcher.mouse(PointerButton.Primary), - onDragStart = { onDragStart() }, - onDragCancel = onDragEnd, - onDragEnd = onDragEnd, - onDrag = onDrag, - ) + onDrag( + matcher = PointerMatcher.mouse(PointerButton.Primary), + onDragStart = { onDragStart() }, + onDragCancel = onDragEnd, + onDragEnd = onDragEnd, + onDrag = onDrag, + ) fun Modifier.scrubbable( - onEnd: () -> Unit = {}, - onScrub: (position: Offset, size: IntSize) -> Unit + onEnd: () -> Unit = {}, + onScrub: (position: Offset, size: IntSize) -> Unit ): Modifier = - composed { - val currentOnScrub by rememberUpdatedState(onScrub) - val currentOnEnd by rememberUpdatedState(onEnd) - pointerInput(Unit) { - awaitEachGesture { - val down = awaitFirstDown() - down.consume() - currentOnScrub(down.position, size) - drag(down.id) { change -> - change.consume() - currentOnScrub(change.position, size) - } - currentOnEnd() - } - } - } + composed { + val currentOnScrub by rememberUpdatedState(onScrub) + val currentOnEnd by rememberUpdatedState(onEnd) + pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown() + down.consume() + currentOnScrub(down.position, size) + drag(down.id) { change -> + change.consume() + currentOnScrub(change.position, size) + } + currentOnEnd() + } + } + } fun Modifier.hoverHighlight(color: Color): Modifier = - composed { - val interactions = remember { MutableInteractionSource() } - val hovered by interactions.collectIsHoveredAsState() - hoverable(interactions).background(if (hovered) color else Color.Transparent) - } + 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 index 03c1a0459..0886e6df5 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -113,15 +113,15 @@ import kotlin.math.max @OptIn(ExperimentalComposeUiApi::class) private val FLOATING = - PopupProperties( - focusable = true, - dismissOnBackPress = true, - dismissOnClickOutside = true, - clippingEnabled = true, - usePlatformDefaultWidth = false, - usePlatformInsets = true, - consumePointerInputOutside = false, - ) + PopupProperties( + focusable = true, + dismissOnBackPress = true, + dismissOnClickOutside = true, + clippingEnabled = true, + usePlatformDefaultWidth = false, + usePlatformInsets = true, + consumePointerInputOutside = false, + ) private val SLACK = 4.dp private const val DIALOG_ZOOM = 0.85f @@ -134,677 +134,677 @@ val LocalPopupHost = compositionLocalOf { null } @Composable private fun ScenePopup( - popupPositionProvider: PopupPositionProvider, - onDismissRequest: (() -> Unit)? = null, - properties: PopupProperties = PopupProperties(), - onKeyEvent: ((KeyEvent) -> Boolean)? = null, - content: @Composable () -> Unit, + popupPositionProvider: PopupPositionProvider, + onDismissRequest: (() -> Unit)? = null, + properties: PopupProperties = PopupProperties(), + onKeyEvent: ((KeyEvent) -> Boolean)? = null, + content: @Composable () -> Unit, ) = - Popup(popupPositionProvider, onDismissRequest, properties, onKeyEvent = onKeyEvent) { - CompositionLocalProvider(LocalClipboard provides GameClipboard, content = content) - } + Popup(popupPositionProvider, onDismissRequest, properties, onKeyEvent = onKeyEvent) { + CompositionLocalProvider(LocalClipboard provides GameClipboard, content = content) + } enum class MenuPlacement { - Below, + Below, - Beside, + Beside, } @Stable class MenuState { - var isOpen by mutableStateOf(false) - private set - private var dismissedBy = -1L - - fun dismiss() { - isOpen = false - dismissedBy = Press.id - } - - fun toggle() { - if (dismissedBy != Press.id) isOpen = true - } - - fun open() { - isOpen = true - } + var isOpen by mutableStateOf(false) + private set + private var dismissedBy = -1L + + fun dismiss() { + isOpen = false + dismissedBy = Press.id + } + + fun toggle() { + if (dismissedBy != Press.id) isOpen = true + } + + fun open() { + isOpen = true + } } @Composable fun Menu( - open: Boolean, - onDismiss: () -> Unit, - placement: MenuPlacement = MenuPlacement.Below, - unfoldFrom: IntSize = IntSize.Zero, - attached: Boolean = false, - content: @Composable ColumnScope.() -> Unit, + open: Boolean, + onDismiss: () -> Unit, + placement: MenuPlacement = MenuPlacement.Below, + unfoldFrom: IntSize = IntSize.Zero, + attached: Boolean = false, + content: @Composable ColumnScope.() -> Unit, ) { - MenuPopup( - open, - remember(placement) { UnfoldingPosition(placement::place) }, - onDismiss, - unfoldFrom, - attached, - content - ) + MenuPopup( + open, + remember(placement) { UnfoldingPosition(placement::place) }, + onDismiss, + unfoldFrom, + attached, + content + ) } private fun MenuPlacement.place(anchor: IntRect, window: IntSize, popup: IntSize) = - when (this) { - MenuPlacement.Below -> - IntOffset( - anchor.left, - if (anchor.bottom + popup.height <= window.height || - anchor.top - popup.height < 0 - ) { - anchor.bottom - } - else anchor.top - popup.height - ) - MenuPlacement.Beside -> - IntOffset( - if (anchor.right + popup.width <= window.width) anchor.right - else anchor.left - popup.width, - anchor.top - ) - } + when (this) { + MenuPlacement.Below -> + IntOffset( + anchor.left, + if (anchor.bottom + popup.height <= window.height || + anchor.top - popup.height < 0 + ) { + anchor.bottom + } + else anchor.top - popup.height + ) + MenuPlacement.Beside -> + IntOffset( + if (anchor.right + popup.width <= window.width) anchor.right + else anchor.left - popup.width, + anchor.top + ) + } @Composable fun Popout( - open: Boolean, - onDismiss: () -> Unit, - content: @Composable ColumnScope.() -> Unit + open: Boolean, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit ) { - val position = remember { UnfoldingPosition(MenuPlacement.Beside::place) } - FloatingPanel( - open, - position, - onDismiss, - RoundedCornerShape(Look.panelRounding) - ) { panel -> - Column(panel.padding(3.dp), content = content) - } + val position = remember { UnfoldingPosition(MenuPlacement.Beside::place) } + FloatingPanel( + open, + position, + onDismiss, + RoundedCornerShape(Look.panelRounding) + ) { panel -> + Column(panel.padding(3.dp), content = content) + } } @Composable fun ContextMenu( - open: Boolean, - position: IntOffset, - onDismiss: () -> Unit, - content: @Composable ColumnScope.() -> Unit + open: Boolean, + position: IntOffset, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit ) = - MenuPopup( - open, - remember(position) { UnfoldingPosition { _, _, _ -> position } }, - onDismiss, - IntSize.Zero, - false, - content - ) + MenuPopup( + open, + remember(position) { UnfoldingPosition { _, _, _ -> position } }, + onDismiss, + IntSize.Zero, + false, + content + ) @Composable fun rememberLast(value: T?): T? { - val last = remember { LastValue() } - if (value != null) last.value = value - return last.value + val last = remember { LastValue() } + if (value != null) last.value = value + return last.value } private class LastValue { - var value: T? = null + var value: T? = null } @Composable private fun MenuPopup( - open: Boolean, - position: UnfoldingPosition, - onDismiss: () -> Unit, - unfoldFrom: IntSize, - attached: Boolean, - content: @Composable ColumnScope.() -> Unit, + open: Boolean, + position: UnfoldingPosition, + onDismiss: () -> Unit, + unfoldFrom: IntSize, + attached: Boolean, + content: @Composable ColumnScope.() -> Unit, ) { - val open = open && LocalMenuOpen.current - val dismissAll = LocalMenuDismiss.current ?: onDismiss - val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } - val interactions = remember { MutableInteractionSource() } - val hovered by interactions.collectIsHoveredAsState() - val shape = - when { - !attached -> RoundedCornerShape(Look.menuRounding) - position.upwards -> RoundedCornerShape(topStart = Look.menuRounding, topEnd = Look.menuRounding) - else -> RoundedCornerShape(bottomStart = Look.menuRounding, bottomEnd = Look.menuRounding) - } - FloatingPanel(open, position, onDismiss, shape, unfoldFrom) { panel -> - CompositionLocalProvider( - LocalMenuDismiss provides dismissAll, - LocalMenuOpen provides open, - LocalMenuHovered provides hovered - ) { - ScrollColumn( - modifier = Modifier - .hoverable(interactions) - .heightIn(max = screenHeight) - .width(IntrinsicSize.Max) - .widthIn(min = maxOf(80.dp, with(LocalDensity.current) { unfoldFrom.width.toDp() })) - .then(panel) - .clip(shape), - content = content - ) - } - } + val open = open && LocalMenuOpen.current + val dismissAll = LocalMenuDismiss.current ?: onDismiss + val screenHeight = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() + val shape = + when { + !attached -> RoundedCornerShape(Look.menuRounding) + position.upwards -> RoundedCornerShape(topStart = Look.menuRounding, topEnd = Look.menuRounding) + else -> RoundedCornerShape(bottomStart = Look.menuRounding, bottomEnd = Look.menuRounding) + } + FloatingPanel(open, position, onDismiss, shape, unfoldFrom) { panel -> + CompositionLocalProvider( + LocalMenuDismiss provides dismissAll, + LocalMenuOpen provides open, + LocalMenuHovered provides hovered + ) { + ScrollColumn( + modifier = Modifier + .hoverable(interactions) + .heightIn(max = screenHeight) + .width(IntrinsicSize.Max) + .widthIn(min = maxOf(80.dp, with(LocalDensity.current) { unfoldFrom.width.toDp() })) + .then(panel) + .clip(shape), + content = content + ) + } + } } class PopupHost { - var closing by mutableStateOf(false) + var closing by mutableStateOf(false) - var bounds by mutableStateOf(Rect.Zero) - private set + var bounds by mutableStateOf(Rect.Zero) + private set - var full = Rect.Zero - private set + var full = Rect.Zero + private set - fun place(bounds: Rect) { - this.bounds = bounds - if (!closing) full = bounds - } + fun place(bounds: Rect) { + this.bounds = bounds + if (!closing) full = bounds + } } private fun Modifier.swallowedBy(host: PopupHost?): Modifier = - if (host == null) this - else composed { - var origin by remember { mutableStateOf(Offset.Zero) } - onGloballyPositioned { origin = it.positionInWindow() }.drawWithContent { - if (!host.closing) return@drawWithContent drawContent() - val full = host.full - val left = host.bounds - val slack = SLACK.toPx() - val dx = - when { - origin.x >= full.right - slack -> left.right - full.right - origin.x + size.width <= full.left + slack -> left.left - full.left - else -> null - } - val dy = - when { - origin.y >= full.bottom - slack -> left.bottom - full.bottom - origin.y + size.height <= full.top + slack -> left.top - full.top - else -> null - } - val far = 10_000f - clipRect( - if (dx == null) left.left - origin.x else -far, - if (dy == null) left.top - origin.y else -far, - if (dx == null) left.right - origin.x else far, - if (dy == null) left.bottom - origin.y else far, - ) { - translate(dx ?: 0f, dy ?: 0f) { this@drawWithContent.drawContent() } - } - } - } + if (host == null) this + else composed { + var origin by remember { mutableStateOf(Offset.Zero) } + onGloballyPositioned { origin = it.positionInWindow() }.drawWithContent { + if (!host.closing) return@drawWithContent drawContent() + val full = host.full + val left = host.bounds + val slack = SLACK.toPx() + val dx = + when { + origin.x >= full.right - slack -> left.right - full.right + origin.x + size.width <= full.left + slack -> left.left - full.left + else -> null + } + val dy = + when { + origin.y >= full.bottom - slack -> left.bottom - full.bottom + origin.y + size.height <= full.top + slack -> left.top - full.top + else -> null + } + val far = 10_000f + clipRect( + if (dx == null) left.left - origin.x else -far, + if (dy == null) left.top - origin.y else -far, + if (dx == null) left.right - origin.x else far, + if (dy == null) left.bottom - origin.y else far, + ) { + translate(dx ?: 0f, dy ?: 0f) { this@drawWithContent.drawContent() } + } + } + } @Composable private fun FloatingPanel( - open: Boolean, - position: UnfoldingPosition, - onDismiss: () -> Unit, - shape: Shape, - unfoldFrom: IntSize = IntSize.Zero, - content: @Composable (panel: Modifier) -> Unit, + open: Boolean, + position: UnfoldingPosition, + onDismiss: () -> Unit, + shape: Shape, + unfoldFrom: IntSize = IntSize.Zero, + content: @Composable (panel: Modifier) -> Unit, ) { - if (!LocalShown.current) { - if (open) SideEffect(onDismiss) - return - } - val folding = LambdaGui.foldsClosed - val visibility = remember { MutableTransitionState(false) } - visibility.targetState = open && !folding - if (!open && visibility.isIdle && !visibility.currentState) return - - val host = LocalPopupHost.current - if (host != null && host.closing && open) SideEffect(onDismiss) - val own = remember { PopupHost() } - SideEffect { own.closing = !open || folding } - - val colors = LambdaTheme.colors - ScenePopup( - popupPositionProvider = position, - onDismissRequest = { if (open) onDismiss() }, - properties = FLOATING, - onKeyEvent = { open && it.dismissOnEscape(onDismiss) }, - ) { - if (open) KeyboardFocus.Layer() - ContentColor(colors.onSurface) { - AnimatedVisibility( - visibleState = visibility, - modifier = Modifier - .swallowedBy(host) - .onGloballyPositioned { own.place(it.boundsInWindow()) } - .guiPresence(position.anchor) - .dropShadow(shape, close = true) - .window(colors.panel, colors.border, shape), - enter = expandIn(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, - exit = - shrinkOut( - if (folding) Motion.guiFold - else Motion.panels, - position.corner - ) { it.coerceAtMost(unfoldFrom) }, - ) { - CompositionLocalProvider(LocalPopupHost provides own) { - content(Modifier.onSizeChanged { position.unfolded = it }) - } - } - } - } + if (!LocalShown.current) { + if (open) SideEffect(onDismiss) + return + } + val folding = LambdaGui.foldsClosed + val visibility = remember { MutableTransitionState(false) } + visibility.targetState = open && !folding + if (!open && visibility.isIdle && !visibility.currentState) return + + val host = LocalPopupHost.current + if (host != null && host.closing && open) SideEffect(onDismiss) + val own = remember { PopupHost() } + SideEffect { own.closing = !open || folding } + + val colors = LambdaTheme.colors + ScenePopup( + popupPositionProvider = position, + onDismissRequest = { if (open) onDismiss() }, + properties = FLOATING, + onKeyEvent = { open && it.dismissOnEscape(onDismiss) }, + ) { + if (open) KeyboardFocus.Layer() + ContentColor(colors.onSurface) { + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier + .swallowedBy(host) + .onGloballyPositioned { own.place(it.boundsInWindow()) } + .guiPresence(position.anchor) + .dropShadow(shape, close = true) + .window(colors.panel, colors.border, shape), + enter = expandIn(Motion.panels, position.corner) { it.coerceAtMost(unfoldFrom) }, + exit = + shrinkOut( + if (folding) Motion.guiFold + else Motion.panels, + position.corner + ) { it.coerceAtMost(unfoldFrom) }, + ) { + CompositionLocalProvider(LocalPopupHost provides own) { + content(Modifier.onSizeChanged { position.unfolded = it }) + } + } + } + } } private class UnfoldingPosition( - private val position: (anchor: IntRect, window: IntSize, popup: IntSize) -> IntOffset, + private val position: (anchor: IntRect, window: IntSize, popup: IntSize) -> IntOffset, ) : PopupPositionProvider { - var unfolded = IntSize.Zero - - private var leftwards by mutableStateOf(false) - - var upwards by mutableStateOf(false) - private set - - val anchor - get() = - TransformOrigin( - if (leftwards) 1f else 0f, - if (upwards) 1f else 0f - ) - - val corner - get() = - when { - upwards -> - if (leftwards) Alignment.BottomEnd - else Alignment.BottomStart - else -> - if (leftwards) Alignment.TopEnd - else Alignment.TopStart - } - - override fun calculatePosition( - anchorBounds: IntRect, - windowSize: IntSize, - layoutDirection: LayoutDirection, - popupContentSize: IntSize, - ): IntOffset { - val full = - IntSize( - max(unfolded.width, popupContentSize.width), - max(unfolded.height, popupContentSize.height) - ) - val wanted = position(anchorBounds, windowSize, full) - leftwards = wanted.x + full.width <= anchorBounds.left - upwards = wanted.y + full.height <= anchorBounds.top - val x = wanted.x.coerceIn(0, (windowSize.width - full.width).coerceAtLeast(0)) - val y = wanted.y.coerceIn(0, (windowSize.height - full.height).coerceAtLeast(0)) - return IntOffset( - if (leftwards) x + full.width - popupContentSize.width else x, - if (upwards) y + full.height - popupContentSize.height else y - ) - } + var unfolded = IntSize.Zero + + private var leftwards by mutableStateOf(false) + + var upwards by mutableStateOf(false) + private set + + val anchor + get() = + TransformOrigin( + if (leftwards) 1f else 0f, + if (upwards) 1f else 0f + ) + + val corner + get() = + when { + upwards -> + if (leftwards) Alignment.BottomEnd + else Alignment.BottomStart + else -> + if (leftwards) Alignment.TopEnd + else Alignment.TopStart + } + + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset { + val full = + IntSize( + max(unfolded.width, popupContentSize.width), + max(unfolded.height, popupContentSize.height) + ) + val wanted = position(anchorBounds, windowSize, full) + leftwards = wanted.x + full.width <= anchorBounds.left + upwards = wanted.y + full.height <= anchorBounds.top + val x = wanted.x.coerceIn(0, (windowSize.width - full.width).coerceAtLeast(0)) + val y = wanted.y.coerceIn(0, (windowSize.height - full.height).coerceAtLeast(0)) + return IntOffset( + if (leftwards) x + full.width - popupContentSize.width else x, + if (upwards) y + full.height - popupContentSize.height else y + ) + } } @Composable fun Suggestions( - open: Boolean, - onDismiss: () -> Unit, - content: @Composable ColumnScope.() -> Unit + open: Boolean, + onDismiss: () -> Unit, + content: @Composable ColumnScope.() -> Unit ) { - if (!LocalShown.current) { - if (open) SideEffect(onDismiss) - return - } - val folding = LambdaGui.foldsClosed - val visibility = remember { MutableTransitionState(false) } - visibility.targetState = open && !folding - if (!open && visibility.isIdle && !visibility.currentState) return - - val colors = LambdaTheme.colors - val shape = RoundedCornerShape(Look.menuRounding) - val screenHeight = - with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } - ScenePopup( - popupPositionProvider = remember { - positionProvider { anchor, window, popup -> - val centred = anchor.left + (anchor.width - popup.width) / 2 - IntOffset( - centred.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), - anchor.bottom - ) - } - }, - onDismissRequest = { if (open) onDismiss() }, - properties = PopupProperties(focusable = false), - ) { - ContentColor(colors.onSurface) { - AnimatedVisibility( - visibleState = visibility, - modifier = Modifier - .guiPresence(SUGGESTIONS_ANCHOR) - .dropShadow(shape) - .window(colors.panel, colors.border, shape), - enter = expandVertically(Motion.panels, Alignment.Top), - exit = - shrinkVertically( - if (folding) Motion.guiFold - else Motion.panels, - Alignment.Top - ), - ) { - ScrollColumn( - modifier = Modifier - .heightIn(max = screenHeight * 0.6f) - .width(IntrinsicSize.Max) - .animateContentSize(Motion.panels), - content = content - ) - } - } - } + if (!LocalShown.current) { + if (open) SideEffect(onDismiss) + return + } + val folding = LambdaGui.foldsClosed + val visibility = remember { MutableTransitionState(false) } + visibility.targetState = open && !folding + if (!open && visibility.isIdle && !visibility.currentState) return + + val colors = LambdaTheme.colors + val shape = RoundedCornerShape(Look.menuRounding) + val screenHeight = + with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } + ScenePopup( + popupPositionProvider = remember { + positionProvider { anchor, window, popup -> + val centred = anchor.left + (anchor.width - popup.width) / 2 + IntOffset( + centred.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), + anchor.bottom + ) + } + }, + onDismissRequest = { if (open) onDismiss() }, + properties = PopupProperties(focusable = false), + ) { + ContentColor(colors.onSurface) { + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier + .guiPresence(SUGGESTIONS_ANCHOR) + .dropShadow(shape) + .window(colors.panel, colors.border, shape), + enter = expandVertically(Motion.panels, Alignment.Top), + exit = + shrinkVertically( + if (folding) Motion.guiFold + else Motion.panels, + Alignment.Top + ), + ) { + ScrollColumn( + modifier = Modifier + .heightIn(max = screenHeight * 0.6f) + .width(IntrinsicSize.Max) + .animateContentSize(Motion.panels), + content = content + ) + } + } + } } @Composable fun MenuItem( - label: String, - enabled: Boolean = true, - checked: Boolean? = null, - selected: Boolean = false, - hint: String? = null, - onHover: (hovered: Boolean) -> Unit = {}, - onClick: () -> Unit, + label: String, + enabled: Boolean = true, + checked: Boolean? = null, + selected: Boolean = false, + hint: String? = null, + onHover: (hovered: Boolean) -> Unit = {}, + onClick: () -> Unit, ) { - val colors = LambdaTheme.colors - val dismiss = LocalMenuDismiss.current - val interactions = remember { MutableInteractionSource() } - val hovered by interactions.collectIsHoveredAsState() - val currentOnHover by rememberUpdatedState(onHover) - LaunchedEffect(hovered) { currentOnHover(hovered) } - DisposableEffect(Unit) { - onDispose { currentOnHover(false) } - } - Row( - verticalAlignment = Centered.VERTICALLY, - modifier = Modifier - .fillMaxWidth() - .hoverable(interactions) - .background(if (selected) colors.controlSelected else Color.Transparent) - .then( - if (!enabled) Modifier - else Modifier.hoverHighlight(colors.controlSelected).mouseClickable { - onClick() - if (checked == null) dismiss?.invoke() - } - ) - .padding(horizontal = 5.dp, vertical = 1.dp) - ) { - if (checked != null) Checkmark(checked, Modifier.padding(end = 3.dp)) - val color = - when { - !enabled -> colors.onSurfaceVariant - selected -> colors.secondary - else -> colors.onSurface - } - Text(label, Modifier.weight(1f), color, maxLines = 1) - if (hint != null) { - Text( - hint, - Modifier.padding(start = 12.dp), - colors.onSurfaceVariant, - Type.label, - maxLines = 1 - ) - } - } + val colors = LambdaTheme.colors + val dismiss = LocalMenuDismiss.current + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() + val currentOnHover by rememberUpdatedState(onHover) + LaunchedEffect(hovered) { currentOnHover(hovered) } + DisposableEffect(Unit) { + onDispose { currentOnHover(false) } + } + Row( + verticalAlignment = Centered.VERTICALLY, + modifier = Modifier + .fillMaxWidth() + .hoverable(interactions) + .background(if (selected) colors.controlSelected else Color.Transparent) + .then( + if (!enabled) Modifier + else Modifier.hoverHighlight(colors.controlSelected).mouseClickable { + onClick() + if (checked == null) dismiss?.invoke() + } + ) + .padding(horizontal = 5.dp, vertical = 1.dp) + ) { + if (checked != null) Checkmark(checked, Modifier.padding(end = 3.dp)) + val color = + when { + !enabled -> colors.onSurfaceVariant + selected -> colors.secondary + else -> colors.onSurface + } + Text(label, Modifier.weight(1f), color, maxLines = 1) + if (hint != null) { + Text( + hint, + Modifier.padding(start = 12.dp), + colors.onSurfaceVariant, + Type.label, + maxLines = 1 + ) + } + } } @Composable fun Submenu( - label: String, - enabled: Boolean = true, - content: @Composable ColumnScope.() -> Unit + label: String, + enabled: Boolean = true, + content: @Composable ColumnScope.() -> Unit ) { - val colors = LambdaTheme.colors - val interactions = remember { MutableInteractionSource() } - val hovered by interactions.collectIsHoveredAsState() - val menuHovered = LocalMenuHovered.current - val menu = remember { MenuState() } - val onHover by observe { GuiConfig.hoverSubmenus } - LaunchedEffect(hovered, menuHovered, onHover) { - when { - !onHover -> Unit - hovered -> menu.open() - menuHovered -> menu.dismiss() - } - } - Box { - Row( - verticalAlignment = Centered.VERTICALLY, - modifier = Modifier - .fillMaxWidth() - .hoverable(interactions, enabled) - .background(if (hovered || menu.isOpen) colors.controlSelected else Color.Transparent) - .mouseClickable(enabled) { - if (onHover) menu.open() - else menu.toggle() - } - .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 - ) - } + val colors = LambdaTheme.colors + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() + val menuHovered = LocalMenuHovered.current + val menu = remember { MenuState() } + val onHover by observe { GuiConfig.hoverSubmenus } + LaunchedEffect(hovered, menuHovered, onHover) { + when { + !onHover -> Unit + hovered -> menu.open() + menuHovered -> menu.dismiss() + } + } + Box { + Row( + verticalAlignment = Centered.VERTICALLY, + modifier = Modifier + .fillMaxWidth() + .hoverable(interactions, enabled) + .background(if (hovered || menu.isOpen) colors.controlSelected else Color.Transparent) + .mouseClickable(enabled) { + if (onHover) menu.open() + else menu.toggle() + } + .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 - ) + Text( + label, + Modifier.padding(horizontal = 5.dp, vertical = 1.dp), + LambdaTheme.colors.onSurfaceVariant, + maxLines = 1 + ) @Composable fun MenuHelp(text: String, label: String = "Help") { - val colors = LambdaTheme.colors - Tooltip(text, Modifier.fillMaxWidth()) { - Row( - verticalAlignment = Centered.VERTICALLY, - 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 - ) - } - } + val colors = LambdaTheme.colors + Tooltip(text, Modifier.fillMaxWidth()) { + Row( + verticalAlignment = Centered.VERTICALLY, + 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) - ) + Spacer( + Modifier + .fillMaxWidth() + .padding(horizontal = 3.dp, vertical = 1.dp) + .height(1.dp) + .background(LambdaTheme.colors.border) + ) @Composable fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.(dismiss: () -> Unit) -> Unit) { - if (!LocalShown.current) { - if (onDismiss != null) SideEffect(onDismiss) - return - } - val colors = LambdaTheme.colors - val presence = LocalPresence.current - val shape = RoundedCornerShape(Look.panelRounding) - val opened = remember { Animatable(0f) } - var closing by remember { mutableStateOf(false) } - val currentOnDismiss by rememberUpdatedState(onDismiss) - val dismiss = { closing = currentOnDismiss != null } - LaunchedEffect(closing) { - if (closing) { - opened.animateTo(0f, Motion.dialogs) - currentOnDismiss?.invoke() - } - else opened.animateTo(1f, Motion.dialogs) - } - ScenePopup( - popupPositionProvider = remember { - positionProvider { _, _, _ -> IntOffset.Zero } - }, - properties = PopupProperties(focusable = true), - onKeyEvent = { onDismiss != null && it.dismissOnEscape(dismiss) }, - ) { - KeyboardFocus.Layer() - Box(Modifier.fillMaxSize(), Centered.BOTH) { - Box( - Modifier - .matchParentSize() - .glass(Color.Black.copy(alpha = 0.35f), RectangleShape) { presence() * opened.value } - .mouseClickable(keyboard = false, onClick = dismiss) - ) - ContentColor(colors.onSurface) { - AnimatedVisibility( - visible = !LambdaGui.foldsClosed, - modifier = Modifier - .graphicsLayer { - val shown = opened.value - alpha = shown - scaleX = DIALOG_ZOOM + (1f - DIALOG_ZOOM) * shown - scaleY = scaleX - } - .guiPresence() - .window(colors.panel, colors.border, shape, floating = true), - enter = expandVertically(Motion.guiFold), - exit = shrinkVertically(Motion.guiFold), - ) { - Box(Modifier.padding(6.dp)) { content(dismiss) } - } - } - } - } + if (!LocalShown.current) { + if (onDismiss != null) SideEffect(onDismiss) + return + } + val colors = LambdaTheme.colors + val presence = LocalPresence.current + val shape = RoundedCornerShape(Look.panelRounding) + val opened = remember { Animatable(0f) } + var closing by remember { mutableStateOf(false) } + val currentOnDismiss by rememberUpdatedState(onDismiss) + val dismiss = { closing = currentOnDismiss != null } + LaunchedEffect(closing) { + if (closing) { + opened.animateTo(0f, Motion.dialogs) + currentOnDismiss?.invoke() + } + else opened.animateTo(1f, Motion.dialogs) + } + ScenePopup( + popupPositionProvider = remember { + positionProvider { _, _, _ -> IntOffset.Zero } + }, + properties = PopupProperties(focusable = true), + onKeyEvent = { onDismiss != null && it.dismissOnEscape(dismiss) }, + ) { + KeyboardFocus.Layer() + Box(Modifier.fillMaxSize(), Centered.BOTH) { + Box( + Modifier + .matchParentSize() + .glass(Color.Black.copy(alpha = 0.35f), RectangleShape) { presence() * opened.value } + .mouseClickable(keyboard = false, onClick = dismiss) + ) + ContentColor(colors.onSurface) { + AnimatedVisibility( + visible = !LambdaGui.foldsClosed, + modifier = Modifier + .graphicsLayer { + val shown = opened.value + alpha = shown + scaleX = DIALOG_ZOOM + (1f - DIALOG_ZOOM) * shown + scaleY = scaleX + } + .guiPresence() + .window(colors.panel, colors.border, shape, floating = true), + enter = expandVertically(Motion.guiFold), + exit = shrinkVertically(Motion.guiFold), + ) { + Box(Modifier.padding(6.dp)) { content(dismiss) } + } + } + } + } } @Composable fun Overlay( - position: (window: IntSize, size: IntSize) -> IntOffset, - content: @Composable () -> Unit + position: (window: IntSize, size: IntSize) -> IntOffset, + content: @Composable () -> Unit ) = - ScenePopup( - popupPositionProvider = positionProvider { _, window, size -> position(window, size) }, - properties = PopupProperties(focusable = false), - content = content - ) + ScenePopup( + popupPositionProvider = positionProvider { _, window, size -> position(window, size) }, + properties = PopupProperties(focusable = false), + content = content + ) @Composable fun Tooltip( - text: String, - modifier: Modifier = Modifier, - content: @Composable () -> Unit + 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(GuiConfig.tooltipDelay.toLong()) - visible = true - } - - Box( - modifier - .onGloballyPositioned { bounds = it.boundsInWindow() } - .pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent(PointerEventPass.Initial) - when (event.type) { - PointerEventType.Enter -> hovered = !event.buttons.areAnyPressed - PointerEventType.Exit, PointerEventType.Press -> { - hovered = false - visible = false - } - } - if (!visible) pointer = event.changes.first().position - } - } - } - ) { - content() - if (visible && hovered && !LambdaGui.leaving) { - val below = with(LocalDensity.current) { 16.dp.roundToPx() } - ScenePopup( - popupPositionProvider = remember(pointer, bounds) { - positionProvider { _, window, popup -> - val at = (bounds.topLeft + pointer).round() + IntOffset(0, below) - IntOffset( - at.x.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), - at.y.coerceIn(0, (window.height - popup.height).coerceAtLeast(0)) - ) - } - }, - properties = PopupProperties(focusable = false), - ) { - Text( - text = text, - color = colors.onSurface, - style = Type.label, - modifier = Modifier - .widthIn(max = 220.dp) - .window(colors.panel, colors.border, RoundedCornerShape(Look.menuRounding)) - .padding(horizontal = 4.dp, vertical = 2.dp) - ) - } - } - } + 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(GuiConfig.tooltipDelay.toLong()) + visible = true + } + + Box( + modifier + .onGloballyPositioned { bounds = it.boundsInWindow() } + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + when (event.type) { + PointerEventType.Enter -> hovered = !event.buttons.areAnyPressed + PointerEventType.Exit, PointerEventType.Press -> { + hovered = false + visible = false + } + } + if (!visible) pointer = event.changes.first().position + } + } + } + ) { + content() + if (visible && hovered && !LambdaGui.leaving) { + val below = with(LocalDensity.current) { 16.dp.roundToPx() } + ScenePopup( + popupPositionProvider = remember(pointer, bounds) { + positionProvider { _, window, popup -> + val at = (bounds.topLeft + pointer).round() + IntOffset(0, below) + IntOffset( + at.x.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), + at.y.coerceIn(0, (window.height - popup.height).coerceAtLeast(0)) + ) + } + }, + properties = PopupProperties(focusable = false), + ) { + Text( + text = text, + color = colors.onSurface, + style = Type.label, + modifier = Modifier + .widthIn(max = 220.dp) + .window(colors.panel, colors.border, RoundedCornerShape(Look.menuRounding)) + .padding(horizontal = 4.dp, vertical = 2.dp) + ) + } + } + } } private fun KeyEvent.dismissOnEscape(onDismiss: () -> Unit): Boolean { - if (key != Key.Escape) return false - if (type == KeyEventType.KeyDown) onDismiss() - return true + if (key != Key.Escape) return false + if (type == KeyEventType.KeyDown) onDismiss() + return true } private fun positionProvider( - position: (anchor: IntRect, window: IntSize, popup: IntSize) -> IntOffset + 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) - } + object : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ) = position(anchorBounds, windowSize, popupContentSize) + } private fun IntSize.coerceAtMost(other: IntSize) = IntSize(minOf(width, other.width), minOf(height, other.height)) diff --git a/src/main/kotlin/com/lambda/gui/component/Scroll.kt b/src/main/kotlin/com/lambda/gui/component/Scroll.kt index cb07cf709..f03862fc6 100644 --- a/src/main/kotlin/com/lambda/gui/component/Scroll.kt +++ b/src/main/kotlin/com/lambda/gui/component/Scroll.kt @@ -56,86 +56,86 @@ private const val SCROLLBAR_FADE_MILLIS = 150 @Composable fun ScrollColumn( - modifier: Modifier = Modifier, - scroll: ScrollState = rememberScrollState(), - content: @Composable ColumnScope.() -> Unit, + 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()) - } + Box(modifier.wheelScrollable(scroll)) { + Column(Modifier.verticalScroll(scroll), content = content) + if (scroll.maxValue > 0) Scrollbar(rememberScrollbarAdapter(scroll), Modifier.matchParentSize()) + } } @Composable fun Scrollbar(adapter: ScrollbarAdapter, modifier: Modifier) { - val colors = LambdaTheme.colors - Box(modifier) { - VerticalScrollbar( - adapter = adapter, - modifier = Modifier.align(Centered.END).fillMaxHeight(), - style = ScrollbarStyle( - minimalHeight = 12.dp, - thickness = 2.dp, - shape = RoundedCornerShape(1.dp), - hoverDurationMillis = SCROLLBAR_FADE_MILLIS, - unhoverColor = colors.onSurfaceVariant.copy(alpha = 0.5f), - hoverColor = colors.onSurface - ) - ) - } + val colors = LambdaTheme.colors + Box(modifier) { + VerticalScrollbar( + adapter = adapter, + modifier = Modifier.align(Centered.END).fillMaxHeight(), + style = ScrollbarStyle( + minimalHeight = 12.dp, + thickness = 2.dp, + shape = RoundedCornerShape(1.dp), + hoverDurationMillis = SCROLLBAR_FADE_MILLIS, + unhoverColor = colors.onSurfaceVariant.copy(alpha = 0.5f), + hoverColor = colors.onSurface + ) + ) + } } fun Modifier.wheelScrollable(state: ScrollableState): Modifier = - composed { - val scope = rememberCoroutineScope() - val notch = with(LocalDensity.current) { WHEEL_STEP.toPx() } - val glide = remember { WheelGlide() } - pointerInput(state, notch) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent(PointerEventPass.Initial) - if (event.type != PointerEventType.Scroll) continue - val change = event.changes.first() - val distance = change.scrollDelta.y * notch * GuiConfig.scrollSpeed - val canFollow = - if (distance > 0) state.canScrollForward - else state.canScrollBackward - if (distance == 0f || !canFollow || change.isConsumed) continue - change.consume() + composed { + val scope = rememberCoroutineScope() + val notch = with(LocalDensity.current) { WHEEL_STEP.toPx() } + val glide = remember { WheelGlide() } + pointerInput(state, notch) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type != PointerEventType.Scroll) continue + val change = event.changes.first() + val distance = change.scrollDelta.y * notch * GuiConfig.scrollSpeed + val canFollow = + if (distance > 0) state.canScrollForward + else state.canScrollBackward + if (distance == 0f || !canFollow || change.isConsumed) continue + change.consume() - val total = - distance + - if (glide.remaining * distance > 0) glide.remaining - else 0f - glide.job?.cancel() - glide.job = - scope.launch(Motion.SCROLL) { - var travelled = 0f - glide.remaining = total - try { - state.scroll(MutatePriority.UserInput) { - animate( - 0f, - total, - animationSpec = GLIDE - ) { value, _ -> - scrollBy(value - travelled) - travelled = value - glide.remaining = total - value - } - } - } finally { - if (glide.job === coroutineContext[Job]) { - glide.remaining = 0f - } - } - } - } - } - } - } + val total = + distance + + if (glide.remaining * distance > 0) glide.remaining + else 0f + glide.job?.cancel() + glide.job = + scope.launch(Motion.SCROLL) { + var travelled = 0f + glide.remaining = total + try { + state.scroll(MutatePriority.UserInput) { + animate( + 0f, + total, + animationSpec = GLIDE + ) { value, _ -> + scrollBy(value - travelled) + travelled = value + glide.remaining = total - value + } + } + } finally { + if (glide.job === coroutineContext[Job]) { + glide.remaining = 0f + } + } + } + } + } + } + } private class WheelGlide { - var remaining = 0f - var job: Job? = null + var remaining = 0f + var job: Job? = null } diff --git a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt index 479c3a07d..c4f5a9c9b 100644 --- a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt +++ b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt @@ -52,54 +52,54 @@ private const val BACK_MILLIS = 250 @Composable fun SlidingText( - text: String, - modifier: Modifier = Modifier, - color: Color = LocalContentColor.current, - style: TextStyle = Type.body, + text: String, + modifier: Modifier = Modifier, + color: Color = LocalContentColor.current, + style: TextStyle = Type.body, ) { - var overflow by remember { mutableIntStateOf(0) } - val interactions = remember { MutableInteractionSource() } - val hovered by interactions.collectIsHoveredAsState() - val pixelsPerSecond = with(LocalDensity.current) { SLIDE_SPEED.toPx() } + var overflow by remember { mutableIntStateOf(0) } + val interactions = remember { MutableInteractionSource() } + val hovered by interactions.collectIsHoveredAsState() + val pixelsPerSecond = with(LocalDensity.current) { SLIDE_SPEED.toPx() } - val slide = remember { Animatable(0f) } - LaunchedEffect(hovered, overflow) { - if (!hovered || overflow == 0) { - slide.animateTo(0f, tween(BACK_MILLIS)) - return@LaunchedEffect - } - val outMillis = (overflow / pixelsPerSecond * 1000).roundToInt().coerceAtLeast(BACK_MILLIS) - withContext(Motion.UNSCALED) { - slide.animateTo( - targetValue = 0f, - animationSpec = infiniteRepeatable( - keyframes { - durationMillis = REST_MILLIS + outMillis + END_REST_MILLIS + BACK_MILLIS - 0f at REST_MILLIS using LinearEasing - 1f at REST_MILLIS + outMillis - 1f at REST_MILLIS + outMillis + END_REST_MILLIS - } - ) - ) - } - } + val slide = remember { Animatable(0f) } + LaunchedEffect(hovered, overflow) { + if (!hovered || overflow == 0) { + slide.animateTo(0f, tween(BACK_MILLIS)) + return@LaunchedEffect + } + val outMillis = (overflow / pixelsPerSecond * 1000).roundToInt().coerceAtLeast(BACK_MILLIS) + withContext(Motion.UNSCALED) { + slide.animateTo( + targetValue = 0f, + animationSpec = infiniteRepeatable( + keyframes { + durationMillis = REST_MILLIS + outMillis + END_REST_MILLIS + BACK_MILLIS + 0f at REST_MILLIS using LinearEasing + 1f at REST_MILLIS + outMillis + 1f at REST_MILLIS + outMillis + END_REST_MILLIS + } + ) + ) + } + } - Text( - text = text, - color = color, - style = style, - softWrap = false, - modifier = modifier - .hoverable(interactions) - .clipToBounds() - .layout { measurable, constraints -> - val placeable = measurable.measure(constraints.copy(maxWidth = Constraints.Infinity)) - overflow = - if (constraints.hasBoundedWidth) (placeable.width - constraints.maxWidth).coerceAtLeast(0) - else 0 - layout(placeable.width - overflow, placeable.height) { - placeable.place(-(slide.value * overflow).roundToInt(), 0) - } - } - ) + Text( + text = text, + color = color, + style = style, + softWrap = false, + modifier = modifier + .hoverable(interactions) + .clipToBounds() + .layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(maxWidth = Constraints.Infinity)) + overflow = + if (constraints.hasBoundedWidth) (placeable.width - constraints.maxWidth).coerceAtLeast(0) + else 0 + layout(placeable.width - overflow, placeable.height) { + placeable.place(-(slide.value * overflow).roundToInt(), 0) + } + } + ) } diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt index a01c95a8e..84a5cb693 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -68,18 +68,18 @@ private val CLOSE_SHADOW_BLUR = 3.dp private val CLOSE_SHADOW_DROP = 2.dp private val DRAWN = - ImageFilter.makeColorFilter( - ColorFilter.makeMatrix( - ColorMatrix( - 0f, 0f, 0f, 0f, 0f, - 0f, 0f, 0f, 0f, 0f, - 0f, 0f, 0f, 0f, 0f, - 0f, 0f, 0f, 64f, 0f, - ) - ), - null, - null - ) + 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 } @@ -88,118 +88,118 @@ private val GUI_SLIDE = 24.dp private const val GUI_ZOOM = 0.92f fun Modifier.guiPresence(anchor: TransformOrigin? = null): Modifier = - composed { - val presence = LocalPresence.current - graphicsLayer { - val shown = presence() - val styles = LambdaGui.transitions - if (GuiTransition.Fade in styles) alpha = shown - if (GuiTransition.Slide in styles && anchor == null) translationY = (shown - 1f) * GUI_SLIDE.toPx() - if (GuiTransition.Zoom in styles) { - scaleX = GUI_ZOOM + (1f - GUI_ZOOM) * shown - scaleY = scaleX - transformOrigin = anchor ?: TransformOrigin.Center - } - } - } + composed { + val presence = LocalPresence.current + graphicsLayer { + val shown = presence() + val styles = LambdaGui.transitions + if (GuiTransition.Fade in styles) alpha = shown + if (GuiTransition.Slide in styles && anchor == null) translationY = (shown - 1f) * GUI_SLIDE.toPx() + if (GuiTransition.Zoom in styles) { + scaleX = GUI_ZOOM + (1f - GUI_ZOOM) * shown + scaleY = scaleX + transformOrigin = anchor ?: TransformOrigin.Center + } + } + } fun Modifier.glass(color: Color, shape: Shape, strength: () -> Float = { 1f }): Modifier = - clip(shape).composed { - val sigma = with(LocalDensity.current) { Look.backdropBlur.toPx() } - val underlay = Look.underlay - val full = remember(sigma, underlay) { backdropFilter(sigma, underlay) } - drawBehind { - val amount = strength().coerceIn(0f, 1f) - if (amount <= 0f) return@drawBehind - val backdrop = - if (amount >= 1f) full - else backdropFilter(sigma * amount, 1f - (1f - underlay) * amount) - if (backdrop != null) drawIntoCanvas { canvas -> - canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), REPLACE, backdrop)) - canvas.skiaCanvas.restore() - } - drawRect(color.copy(alpha = color.alpha * amount)) - } - } + clip(shape).composed { + val sigma = with(LocalDensity.current) { Look.backdropBlur.toPx() } + val underlay = Look.underlay + val full = remember(sigma, underlay) { backdropFilter(sigma, underlay) } + drawBehind { + val amount = strength().coerceIn(0f, 1f) + if (amount <= 0f) return@drawBehind + val backdrop = + if (amount >= 1f) full + else backdropFilter(sigma * amount, 1f - (1f - underlay) * amount) + if (backdrop != null) drawIntoCanvas { canvas -> + canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), REPLACE, backdrop)) + canvas.skiaCanvas.restore() + } + drawRect(color.copy(alpha = color.alpha * amount)) + } + } private fun backdropFilter(sigma: Float, underlay: Float): ImageFilter? { - val blurred = - if (sigma > 0f) ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) - else null - return if (underlay >= 1f) blurred - else ImageFilter.makeColorFilter(faded(underlay), blurred, null) + val blurred = + if (sigma > 0f) ImageFilter.makeBlur(sigma, sigma, FilterTileMode.CLAMP) + else null + return if (underlay >= 1f) blurred + else ImageFilter.makeColorFilter(faded(underlay), blurred, null) } fun Modifier.window( - color: Color, - border: Color, - shape: Shape, - floating: Boolean = false + color: Color, + border: Color, + shape: Shape, + floating: Boolean = false ): Modifier = - (if (floating) dropShadow(shape) else this) - .border(Look.outlineWidth, if (Look.outlines) border else Color.Transparent, shape) - .glass(color, shape) - .clip(if (Look.outlines) Inset(shape, Look.outlineWidth / 2) else RectangleShape) - .consumeClicks() + (if (floating) dropShadow(shape) else this) + .border(Look.outlineWidth, if (Look.outlines) border else Color.Transparent, shape) + .glass(color, shape) + .clip(if (Look.outlines) Inset(shape, Look.outlineWidth / 2) else RectangleShape) + .consumeClicks() private data class Inset(private val shape: Shape, private val inset: Dp) : Shape { - override fun createOutline( - size: Size, - layoutDirection: LayoutDirection, - density: Density - ): Outline { - val edge = with(density) { inset.toPx() } - val inner = - Size( - (size.width - edge * 2).coerceAtLeast(0f), - (size.height - edge * 2).coerceAtLeast(0f) - ) - val path = Path().apply { addOutline(shape.createOutline(inner, layoutDirection, density)) } - path.translate(Offset(edge, edge)) - return Outline.Generic(path) - } + override fun createOutline( + size: Size, + layoutDirection: LayoutDirection, + density: Density + ): Outline { + val edge = with(density) { inset.toPx() } + val inner = + Size( + (size.width - edge * 2).coerceAtLeast(0f), + (size.height - edge * 2).coerceAtLeast(0f) + ) + val path = Path().apply { addOutline(shape.createOutline(inner, layoutDirection, density)) } + path.translate(Offset(edge, edge)) + return Outline.Generic(path) + } } fun Modifier.dropShadow(shape: Shape, close: Boolean = false): Modifier = - drawWithCache { - val body = Path().apply { addOutline(shape.createOutline(size, layoutDirection, this@drawWithCache)) } - val drop = (if (close) CLOSE_SHADOW_DROP else SHADOW_DROP).toPx() - val blur = (if (close) CLOSE_SHADOW_BLUR else SHADOW_BLUR).toPx() - val reach = blur * 3 - val shadow = - Paint().apply { - color = (if (close) CLOSE_SHADOW_COLOR else SHADOW_COLOR).toArgb() - maskFilter = MaskFilter.makeBlur(FilterBlurMode.NORMAL, blur) - } - onDrawBehind { - if (!Look.shadows) return@onDrawBehind - clipPath(body, ClipOp.Difference) { - clipRect( - -reach, - drop - reach, - size.width + reach, - size.height + drop + reach - ) { - drawIntoCanvas { canvas -> - val skia = canvas.skiaCanvas - skia.saveLayer(Canvas.SaveLayerRec(null, null, DRAWN)) - skia.saveLayer(null, WITHIN) - skia.translate(0f, drop) - skia.drawPath(body.asSkiaPath(), shadow) - skia.restore() - skia.restore() - } - } - } - } - } + drawWithCache { + val body = Path().apply { addOutline(shape.createOutline(size, layoutDirection, this@drawWithCache)) } + val drop = (if (close) CLOSE_SHADOW_DROP else SHADOW_DROP).toPx() + val blur = (if (close) CLOSE_SHADOW_BLUR else SHADOW_BLUR).toPx() + val reach = blur * 3 + val shadow = + Paint().apply { + color = (if (close) CLOSE_SHADOW_COLOR else SHADOW_COLOR).toArgb() + maskFilter = MaskFilter.makeBlur(FilterBlurMode.NORMAL, blur) + } + onDrawBehind { + if (!Look.shadows) return@onDrawBehind + clipPath(body, ClipOp.Difference) { + clipRect( + -reach, + drop - reach, + size.width + reach, + size.height + drop + reach + ) { + drawIntoCanvas { canvas -> + val skia = canvas.skiaCanvas + skia.saveLayer(Canvas.SaveLayerRec(null, null, DRAWN)) + skia.saveLayer(null, WITHIN) + skia.translate(0f, drop) + skia.drawPath(body.asSkiaPath(), shadow) + skia.restore() + skia.restore() + } + } + } + } + } private fun faded(fraction: Float) = - ColorFilter.makeMatrix( - ColorMatrix( - 1f, 0f, 0f, 0f, 0f, - 0f, 1f, 0f, 0f, 0f, - 0f, 0f, 1f, 0f, 0f, - 0f, 0f, 0f, fraction, 0f, - ) - ) + ColorFilter.makeMatrix( + ColorMatrix( + 1f, 0f, 0f, 0f, 0f, + 0f, 1f, 0f, 0f, 0f, + 0f, 0f, 1f, 0f, 0f, + 0f, 0f, 0f, fraction, 0f, + ) + ) diff --git a/src/main/kotlin/com/lambda/gui/component/Text.kt b/src/main/kotlin/com/lambda/gui/component/Text.kt index ba8385a78..fb8231131 100644 --- a/src/main/kotlin/com/lambda/gui/component/Text.kt +++ b/src/main/kotlin/com/lambda/gui/component/Text.kt @@ -38,41 +38,41 @@ private val LocalTextShadow = compositionLocalOf { null } @Composable fun Text( - text: String, - modifier: Modifier = Modifier, - color: Color = LocalContentColor.current, - style: TextStyle = Type.body, - maxLines: Int = Int.MAX_VALUE, - softWrap: Boolean = true, + text: String, + modifier: Modifier = Modifier, + color: Color = LocalContentColor.current, + style: TextStyle = Type.body, + maxLines: Int = Int.MAX_VALUE, + softWrap: Boolean = true, ) { - if (maxLines == 1) return SlidingText(text, modifier, color, style) - BasicText( - text = text, - modifier = modifier, - style = style.copy(color = color, shadow = style.shadow ?: LocalTextShadow.current), - maxLines = maxLines, - softWrap = softWrap, - overflow = if (maxLines == Int.MAX_VALUE) TextOverflow.Clip else TextOverflow.Ellipsis, - ) + if (maxLines == 1) return SlidingText(text, modifier, color, style) + BasicText( + text = text, + modifier = modifier, + style = style.copy(color = color, shadow = style.shadow ?: LocalTextShadow.current), + maxLines = maxLines, + softWrap = softWrap, + overflow = if (maxLines == Int.MAX_VALUE) TextOverflow.Clip else TextOverflow.Ellipsis, + ) } @Composable fun ContentColor(color: Color, content: @Composable () -> Unit) = - CompositionLocalProvider(LocalContentColor provides color, content = content) + CompositionLocalProvider(LocalContentColor provides color, content = content) @Composable fun SoftTextShadow(content: @Composable () -> Unit) { - val density = LocalDensity.current - val color = LambdaTheme.colors.textShadow - val shadow = - remember(density, color) { - with(density) { Shadow(color, Offset(0f, 0.5.dp.toPx()), blurRadius = 1.5.dp.toPx()) } - } - CompositionLocalProvider(LocalTextShadow provides shadow, content = content) + val density = LocalDensity.current + val color = LambdaTheme.colors.textShadow + val shadow = + remember(density, color) { + with(density) { Shadow(color, Offset(0f, 0.5.dp.toPx()), blurRadius = 1.5.dp.toPx()) } + } + CompositionLocalProvider(LocalTextShadow provides shadow, content = content) } @Composable fun TextStyle.shadowed(color: Color = LambdaTheme.colors.textShadow): TextStyle { - val offset = with(LocalDensity.current) { 1.dp.toPx() } - return copy(shadow = Shadow(color, Offset(offset, offset))) + val offset = with(LocalDensity.current) { 1.dp.toPx() } + return copy(shadow = Shadow(color, Offset(offset, offset))) } diff --git a/src/main/kotlin/com/lambda/gui/component/TextInput.kt b/src/main/kotlin/com/lambda/gui/component/TextInput.kt index fc6f8490a..44bc6d065 100644 --- a/src/main/kotlin/com/lambda/gui/component/TextInput.kt +++ b/src/main/kotlin/com/lambda/gui/component/TextInput.kt @@ -26,10 +26,13 @@ import androidx.compose.foundation.text.BasicTextField import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.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.setValue +import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester @@ -43,142 +46,208 @@ 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.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.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInWindow 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.IntOffset import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.round +import com.lambda.Lambda.mc import com.lambda.gui.theme.LambdaTheme import com.lambda.gui.theme.Look import com.lambda.gui.theme.Type internal object TextFocus { - private val fields = mutableListOf() + private val fields = mutableListOf() - val isTyping get() = fields.isNotEmpty() + val isTyping get() = fields.isNotEmpty() - fun press(position: Offset) = fields.filter { position !in it.bounds }.forEach { it.release() } + fun press(position: Offset) = + fields.filter { !it.pinned && position !in it.bounds }.forEach { it.release() } - fun add(field: Field) = fields.add(field) - fun remove(field: Field) = fields.remove(field) + fun add(field: Field) = fields.add(field) + fun remove(field: Field) = fields.remove(field) - class Field(val release: () -> Unit) { - var bounds = Rect.Zero - } + class Field(val release: () -> Unit) { + var bounds = Rect.Zero + var pinned = false + } } +@OptIn(ExperimentalComposeUiApi::class) @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, + 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 colors = LambdaTheme.colors + var field by remember { mutableStateOf(TextFieldValue(value, TextRange(value.length))) } + var adopted by remember { mutableStateOf(value) } + if (value != adopted) { + adopted = value + if (value != field.text) field = TextFieldValue(value, TextRange(value.length)) + } - val focus = remember { FocusRequester() } - var hadFocus by remember { mutableStateOf(false) } - var hasFocus by remember { mutableStateOf(false) } - if (focused) LaunchedEffect(Unit) { focus.requestFocus() } - val focusManager = LocalFocusManager.current - val typing = remember(focusManager) { TextFocus.Field { focusManager.clearFocus() } } - if (hasFocus) DisposableEffect(typing) { - TextFocus.add(typing) - onDispose { TextFocus.remove(typing) } - } + val focus = remember { FocusRequester() } + var hadFocus by remember { mutableStateOf(false) } + var hasFocus by remember { mutableStateOf(false) } + if (focused) LaunchedEffect(Unit) { focus.requestFocus() } + val focusManager = LocalFocusManager.current + val typing = remember(focusManager) { TextFocus.Field { focusManager.clearFocus() } } + if (hasFocus) DisposableEffect(typing) { + TextFocus.add(typing) + onDispose { TextFocus.remove(typing) } + } - BasicTextField( - value = field, - onValueChange = { - val edited = it.text != field.text - field = it - if (edited) onValueChange(it.text) - }, - enabled = LocalKeyboardReachable.current, - singleLine = singleLine, - textStyle = style.copy(color = colors.onControl), - cursorBrush = SolidColor(colors.onControl), - modifier = modifier - .heightIn(min = Look.rowHeight) - .clip(RoundedCornerShape(Look.controlRounding)) - .background(colors.input) - .onGloballyPositioned { typing.bounds = it.boundsInWindow() } - .focusRequester(focus) - .onFocusChanged { - hasFocus = it.isFocused - if (it.isFocused) hadFocus = true - else if (hadFocus) onDone?.invoke() - } - .onPreviewKeyEvent { event -> - if ( - onDone == null || - (event.key != Key.Enter && event.key != Key.Escape) - ) { - false - } - else { - if (event.type == KeyEventType.KeyDown) onDone() - true - } - } - .padding(horizontal = 3.dp, vertical = 1.dp), - decorationBox = { innerTextField -> - Box(contentAlignment = Centered.START) { - if (field.text.isEmpty()) { - Text( - placeholder, - color = colors.onSurfaceVariant, - style = style, - maxLines = 1 - ) - } - innerTextField() - } - } - ) + val reachable = LocalKeyboardReachable.current + var origin by remember { mutableStateOf(Offset.Zero) } + var menu by remember { mutableStateOf(null) } + SideEffect { typing.pinned = menu != null } + fun edit(to: TextFieldValue) { + val edited = to.text != field.text + field = to + if (edited) onValueChange(to.text) + } + + BasicTextField( + value = field, + onValueChange = ::edit, + enabled = reachable, + singleLine = singleLine, + textStyle = style.copy(color = colors.onControl), + cursorBrush = SolidColor(colors.onControl), + modifier = modifier + .heightIn(min = Look.rowHeight) + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.input) + .onGloballyPositioned { + typing.bounds = it.boundsInWindow() + origin = it.positionInWindow() + } + .pointerInput(reachable) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type != PointerEventType.Press || event.button != PointerButton.Secondary) continue + val change = event.changes.first() + change.consume() + if (!reachable) continue + focus.requestFocus() + menu = (origin + change.position).round() + } + } + } + .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 = Centered.START) { + if (field.text.isEmpty()) { + Text( + placeholder, + color = colors.onSurfaceVariant, + style = style, + maxLines = 1 + ) + } + innerTextField() + } + } + ) + + rememberLast(menu)?.let { position -> + key(position) { + ContextMenu(menu != null, position, onDismiss = { menu = null }) { + val selected = !field.selection.collapsed + MenuItem("Cut", enabled = selected) { + mc.keyboard.clipboard = field.selected + edit(field.replacingSelection("")) + } + MenuItem("Copy", enabled = selected) { mc.keyboard.clipboard = field.selected } + MenuItem("Paste", enabled = mc.keyboard.clipboard.isNotEmpty()) { + val pasted = mc.keyboard.clipboard + edit( + field.replacingSelection( + if (singleLine) pasted.filterNot { it == '\n' || it == '\r' } + else pasted + ) + ) + } + MenuItem("Select All", enabled = field.text.isNotEmpty()) { + field = field.copy(selection = TextRange(0, field.text.length)) + } + } + } + } } +private val TextFieldValue.selected get() = text.substring(selection.min, selection.max) + +private fun TextFieldValue.replacingSelection(with: String) = + TextFieldValue( + text.replaceRange(selection.min, selection.max, with), + TextRange(selection.min + with.length) + ) + @Composable fun NumberInput( - value: T, - parse: (String) -> T?, - onCommit: (T) -> Unit, - modifier: Modifier = Modifier, - focused: Boolean = false, - onDone: () -> Unit = {}, + value: T, + parse: (String) -> T?, + onCommit: (T) -> Unit, + modifier: Modifier = Modifier, + focused: Boolean = false, + onDone: () -> Unit = {}, ) { - var draft by remember { mutableStateOf(null) } - fun finish(commit: Boolean) { - val typed = draft - draft = null - if (commit && typed != null) { - parse(typed.trim())?.takeIf { it != value }?.let(onCommit) - } - onDone() - } - TextInput( - value = draft ?: value.toString(), - onValueChange = { draft = it }, - modifier = modifier.onPreviewKeyEvent { event -> - if (event.key != Key.Escape) false - else { - if (event.type == KeyEventType.KeyDown) finish(commit = false) - true - } - }, - focused = focused, - onDone = { finish(commit = true) }, - ) + var draft by remember { mutableStateOf(null) } + fun finish(commit: Boolean) { + val typed = draft + draft = null + if (commit && typed != null) { + parse(typed.trim())?.takeIf { it != value }?.let(onCommit) + } + onDone() + } + TextInput( + value = draft ?: value.toString(), + onValueChange = { draft = it }, + modifier = modifier.onPreviewKeyEvent { event -> + if (event.key != Key.Escape) false + else { + if (event.type == KeyEventType.KeyDown) finish(commit = false) + true + } + }, + focused = focused, + onDone = { finish(commit = true) }, + ) } diff --git a/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt b/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt index d44d114e7..730b161c2 100644 --- a/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt +++ b/src/main/kotlin/com/lambda/gui/core/ComposeSlot.kt @@ -25,16 +25,16 @@ import com.lambda.event.EventFlow.post import com.lambda.event.events.ComposeEvent internal class ComposeSlot(private val event: () -> ComposeEvent) { - private var contents by mutableStateOf(emptyList<@Composable () -> Unit>()) - val isEmpty get() = contents.isEmpty() + private var contents by mutableStateOf(emptyList<@Composable () -> Unit>()) + val isEmpty get() = contents.isEmpty() - fun collect(active: Boolean = true) { - val collected = - if (active) event().post().contents - else emptyList() - if (collected != contents) contents = collected - } + fun collect(active: Boolean = true) { + val collected = + if (active) event().post().contents + else emptyList() + if (collected != contents) contents = collected + } - @Composable - fun Content() = contents.forEach { it() } + @Composable + fun Content() = contents.forEach { it() } } diff --git a/src/main/kotlin/com/lambda/gui/core/Frames.kt b/src/main/kotlin/com/lambda/gui/core/Frames.kt index 6352119f5..838f1d38a 100644 --- a/src/main/kotlin/com/lambda/gui/core/Frames.kt +++ b/src/main/kotlin/com/lambda/gui/core/Frames.kt @@ -22,8 +22,8 @@ import androidx.compose.runtime.withFrameNanos private const val NANOS_PER_MILLI = 1_000_000 suspend fun awaitFrames(millis: Long) { - val end = withFrameNanos { it } + millis * NANOS_PER_MILLI - do { - val now = withFrameNanos { it } - } while (now < end) + val end = withFrameNanos { it } + millis * NANOS_PER_MILLI + do { + val now = withFrameNanos { it } + } while (now < end) } diff --git a/src/main/kotlin/com/lambda/gui/core/GlState.kt b/src/main/kotlin/com/lambda/gui/core/GlState.kt index ef8382c87..d83f53e81 100644 --- a/src/main/kotlin/com/lambda/gui/core/GlState.kt +++ b/src/main/kotlin/com/lambda/gui/core/GlState.kt @@ -81,118 +81,118 @@ import org.lwjgl.opengl.GL33.glBindSampler import org.lwjgl.system.MemoryStack internal object GlState { - private const val TEXTURE_UNITS = 12 + 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 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) + 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() - } - } + inline fun borrow(block: () -> T): T { + val restore = capture() + try { + prepare() + return block() + } finally { + restore() + } + } - fun prepare() { - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) - glBindBuffer(GL_PIXEL_PACK_BUFFER, 0) - UNPACK_PARAMETERS.forEachIndexed { index, parameter -> - glPixelStorei(parameter, UNPACK_DEFAULTS[index]) - } - } + fun prepare() { + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) + glBindBuffer(GL_PIXEL_PACK_BUFFER, 0) + UNPACK_PARAMETERS.forEachIndexed { index, parameter -> + glPixelStorei(parameter, UNPACK_DEFAULTS[index]) + } + } - fun capture(): () -> Unit { - val activeTexture = glGetInteger(GL_ACTIVE_TEXTURE) - repeat(TEXTURE_UNITS) { unit -> - glActiveTexture(GL_TEXTURE0 + unit) - textures[unit] = glGetInteger(GL_TEXTURE_BINDING_2D) - samplers[unit] = glGetInteger(GL_SAMPLER_BINDING) - } - glActiveTexture(activeTexture) + fun capture(): () -> Unit { + val activeTexture = glGetInteger(GL_ACTIVE_TEXTURE) + repeat(TEXTURE_UNITS) { unit -> + glActiveTexture(GL_TEXTURE0 + unit) + textures[unit] = glGetInteger(GL_TEXTURE_BINDING_2D) + samplers[unit] = glGetInteger(GL_SAMPLER_BINDING) + } + glActiveTexture(activeTexture) - val program = glGetInteger(GL_CURRENT_PROGRAM) - val vertexArray = glGetInteger(GL_VERTEX_ARRAY_BINDING) - val arrayBuffer = glGetInteger(GL_ARRAY_BUFFER_BINDING) - val unpackBuffer = glGetInteger(GL_PIXEL_UNPACK_BUFFER_BINDING) - val packBuffer = glGetInteger(GL_PIXEL_PACK_BUFFER_BINDING) - val drawFramebuffer = glGetInteger(GL_DRAW_FRAMEBUFFER_BINDING) - val readFramebuffer = glGetInteger(GL_READ_FRAMEBUFFER_BINDING) - val blendSrcRgb = glGetInteger(GL_BLEND_SRC_RGB) - val blendDstRgb = glGetInteger(GL_BLEND_DST_RGB) - val blendSrcAlpha = glGetInteger(GL_BLEND_SRC_ALPHA) - val blendDstAlpha = glGetInteger(GL_BLEND_DST_ALPHA) - val blendEquationRgb = glGetInteger(GL_BLEND_EQUATION_RGB) - val blendEquationAlpha = glGetInteger(GL_BLEND_EQUATION_ALPHA) - val depthMask = glGetBoolean(GL_DEPTH_WRITEMASK) - val colorMask = - MemoryStack.stackPush().use { stack -> - val mask = stack.malloc(4) - glGetBooleanv(GL_COLOR_WRITEMASK, mask) - BooleanArray(4) { mask[it].toInt() != 0 } - } - glGetIntegerv(GL_VIEWPORT, viewport) - glGetIntegerv(GL_SCISSOR_BOX, scissor) - CAPABILITIES.forEachIndexed { index, capability -> - capabilities[index] = glIsEnabled(capability) - } - UNPACK_PARAMETERS.forEachIndexed { index, parameter -> - unpack[index] = glGetInteger(parameter) - } + val program = glGetInteger(GL_CURRENT_PROGRAM) + val vertexArray = glGetInteger(GL_VERTEX_ARRAY_BINDING) + val arrayBuffer = glGetInteger(GL_ARRAY_BUFFER_BINDING) + val unpackBuffer = glGetInteger(GL_PIXEL_UNPACK_BUFFER_BINDING) + val packBuffer = glGetInteger(GL_PIXEL_PACK_BUFFER_BINDING) + val drawFramebuffer = glGetInteger(GL_DRAW_FRAMEBUFFER_BINDING) + val readFramebuffer = glGetInteger(GL_READ_FRAMEBUFFER_BINDING) + val blendSrcRgb = glGetInteger(GL_BLEND_SRC_RGB) + val blendDstRgb = glGetInteger(GL_BLEND_DST_RGB) + val blendSrcAlpha = glGetInteger(GL_BLEND_SRC_ALPHA) + val blendDstAlpha = glGetInteger(GL_BLEND_DST_ALPHA) + val blendEquationRgb = glGetInteger(GL_BLEND_EQUATION_RGB) + val blendEquationAlpha = glGetInteger(GL_BLEND_EQUATION_ALPHA) + val depthMask = glGetBoolean(GL_DEPTH_WRITEMASK) + val colorMask = + MemoryStack.stackPush().use { stack -> + val mask = stack.malloc(4) + glGetBooleanv(GL_COLOR_WRITEMASK, mask) + BooleanArray(4) { mask[it].toInt() != 0 } + } + glGetIntegerv(GL_VIEWPORT, viewport) + glGetIntegerv(GL_SCISSOR_BOX, scissor) + CAPABILITIES.forEachIndexed { index, capability -> + capabilities[index] = glIsEnabled(capability) + } + UNPACK_PARAMETERS.forEachIndexed { index, parameter -> + unpack[index] = glGetInteger(parameter) + } - return { - glUseProgram(program) - repeat(TEXTURE_UNITS) { unit -> - glActiveTexture(GL_TEXTURE0 + unit) - glBindTexture(GL_TEXTURE_2D, textures[unit]) - glBindSampler(unit, samplers[unit]) - } - glActiveTexture(activeTexture) - glBindVertexArray(vertexArray) - glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer) - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, unpackBuffer) - glBindBuffer(GL_PIXEL_PACK_BUFFER, packBuffer) - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFramebuffer) - glBindFramebuffer(GL_READ_FRAMEBUFFER, readFramebuffer) - glBlendEquationSeparate(blendEquationRgb, blendEquationAlpha) - glBlendFuncSeparate(blendSrcRgb, blendDstRgb, blendSrcAlpha, blendDstAlpha) - glDepthMask(depthMask) - glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]) - glViewport(viewport[0], viewport[1], viewport[2], viewport[3]) - glScissor(scissor[0], scissor[1], scissor[2], scissor[3]) - CAPABILITIES.forEachIndexed { index, capability -> - if (capabilities[index]) glEnable(capability) else glDisable(capability) - } - UNPACK_PARAMETERS.forEachIndexed { index, parameter -> - glPixelStorei(parameter, unpack[index]) - } - } - } + return { + glUseProgram(program) + repeat(TEXTURE_UNITS) { unit -> + glActiveTexture(GL_TEXTURE0 + unit) + glBindTexture(GL_TEXTURE_2D, textures[unit]) + glBindSampler(unit, samplers[unit]) + } + glActiveTexture(activeTexture) + glBindVertexArray(vertexArray) + glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, unpackBuffer) + glBindBuffer(GL_PIXEL_PACK_BUFFER, packBuffer) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFramebuffer) + glBindFramebuffer(GL_READ_FRAMEBUFFER, readFramebuffer) + glBlendEquationSeparate(blendEquationRgb, blendEquationAlpha) + glBlendFuncSeparate(blendSrcRgb, blendDstRgb, blendSrcAlpha, blendDstAlpha) + glDepthMask(depthMask) + glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]) + glViewport(viewport[0], viewport[1], viewport[2], viewport[3]) + glScissor(scissor[0], scissor[1], scissor[2], scissor[3]) + CAPABILITIES.forEachIndexed { index, capability -> + if (capabilities[index]) glEnable(capability) else glDisable(capability) + } + UNPACK_PARAMETERS.forEachIndexed { index, parameter -> + glPixelStorei(parameter, unpack[index]) + } + } + } } diff --git a/src/main/kotlin/com/lambda/gui/core/Observe.kt b/src/main/kotlin/com/lambda/gui/core/Observe.kt index 6661cd070..01fb6a4f6 100644 --- a/src/main/kotlin/com/lambda/gui/core/Observe.kt +++ b/src/main/kotlin/com/lambda/gui/core/Observe.kt @@ -33,29 +33,29 @@ internal val LocalObservations = staticCompositionLocalOf { error( @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 + val observations = LocalObservations.current + val observation = remember { Observation(read) } + observation.read = read + DisposableEffect(observations) { + observations.active += observation + onDispose { observations.active -= observation } + } + return observation.state } @Composable fun observeSafe(read: SafeContext.() -> T): State = observe { runSafe(read) } internal class Observation(var read: () -> T) { - val state = mutableStateOf(read()) + val state = mutableStateOf(read()) - fun refresh() { - state.value = read() - } + fun refresh() { + state.value = read() + } } internal class Observations { - val active = ArrayList>() + val active = ArrayList>() - fun refresh() = active.forEach { it.refresh() } + fun refresh() = active.forEach { it.refresh() } } diff --git a/src/main/kotlin/com/lambda/gui/core/RenderThread.kt b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt index b6dacb820..9f553ae8e 100644 --- a/src/main/kotlin/com/lambda/gui/core/RenderThread.kt +++ b/src/main/kotlin/com/lambda/gui/core/RenderThread.kt @@ -28,16 +28,16 @@ import kotlin.coroutines.CoroutineContext import kotlin.time.Duration.Companion.milliseconds object RenderThread : CoroutineDispatcher() { - private val scope = CoroutineScope(this + SupervisorJob()) + private val scope = CoroutineScope(this + SupervisorJob()) - override fun isDispatchNeeded(context: CoroutineContext) = !mc.isOnThread + override fun isDispatchNeeded(context: CoroutineContext) = !mc.isOnThread - override fun dispatch(context: CoroutineContext, block: Runnable) = mc.send(block) + override fun dispatch(context: CoroutineContext, block: Runnable) = mc.send(block) - @JvmStatic - fun after(millis: Long, block: () -> Unit): Job = - scope.launch { - delay(millis.milliseconds) - block() - } + @JvmStatic + fun after(millis: Long, block: () -> Unit): Job = + scope.launch { + delay(millis.milliseconds) + block() + } } diff --git a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt index 2f40b41fc..8ea916d07 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneHost.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneHost.kt @@ -62,171 +62,171 @@ import kotlin.coroutines.CoroutineContext @OptIn(InternalComposeUiApi::class) internal class SceneHost( - context: CoroutineContext, - content: @Composable () -> Unit + context: CoroutineContext, + content: @Composable () -> Unit ) : AutoCloseable { - val platform = ScenePlatform() - - private val recomposer = FrameRecomposer(RenderThread + context) - private var invalidated = true - - private val scene: ComposeScene = - CanvasLayersComposeScene( - frameRecomposer = recomposer, - platformContext = platform, - invalidateDraw = { invalidated = true }, - ).also { it.setContent(content = content) } - - val input = SceneInput(scene) - - private var skia: DirectContext? = null - private var target: SkiaTarget? = null - private var underlayTarget: SkiaTarget? = null - - val texture: GpuTextureView? get() = target?.view - val underlayTexture: GpuTextureView? get() = underlayTarget?.view - - fun advance(size: IntSize, density: Float): Boolean { - if (scene.size != size || scene.density.density != density) { - scene.density = Density(density) - scene.size = size - platform.resize(size, density) - invalidated = true - } - recomposer.performFrame(System.nanoTime()) - scene.measureAndLayout() - return invalidated || scene.hasPendingDraw || target == null - } - - fun draw(underlay: GraphicsLayer? = null, beforeScene: (DirectContext) -> Unit = {}) { - val size = scene.size ?: return - val outgrown = - listOfNotNull( - target?.takeIf { it.size != size }, - underlayTarget?.takeIf { it.size != size || underlay == null } - ) - val target = target?.takeIf { it !in outgrown } ?: SkiaTarget(size).also { target = it } - val underlayTarget = - if (underlay == null) null - else underlayTarget?.takeIf { it !in outgrown } ?: SkiaTarget(size) - this.underlayTarget = underlayTarget - GlState.borrow { - val skia = skia ?: DirectContext.makeGL().also { skia = it } - outgrown.forEach { it.detach() } - val surface = target.attach(skia) - val underlaySurface = underlayTarget?.attach(skia) - skia.resetGLAll() - beforeScene(skia) - surface.canvas.clear(Color.TRANSPARENT) - scene.draw(surface.canvas.asComposeCanvas()) - surface.flushAndSubmit() - if (underlay != null && underlaySurface != null) { - underlaySurface.canvas.clear(Color.TRANSPARENT) - CanvasDrawScope().draw( - scene.density, - LayoutDirection.Ltr, - underlaySurface.canvas.asComposeCanvas(), - size.toSize() - ) { drawLayer(underlay) } - underlaySurface.flushAndSubmit() - } - } - outgrown.forEach { it.close() } - invalidated = false - } - - override fun close() { - scene.close() - recomposer.close() - } - - fun closeAndFree() { - runCatching { scene.close() } - runCatching { recomposer.close() } - val freed = listOfNotNull(target, underlayTarget) - target = null - underlayTarget = null - GlState.borrow { - freed.forEach { it.detach() } - skia?.close() - } - skia = null - freed.forEach { it.close() } - } + val platform = ScenePlatform() + + private val recomposer = FrameRecomposer(RenderThread + context) + private var invalidated = true + + private val scene: ComposeScene = + CanvasLayersComposeScene( + frameRecomposer = recomposer, + platformContext = platform, + invalidateDraw = { invalidated = true }, + ).also { it.setContent(content = content) } + + val input = SceneInput(scene) + + private var skia: DirectContext? = null + private var target: SkiaTarget? = null + private var underlayTarget: SkiaTarget? = null + + val texture: GpuTextureView? get() = target?.view + val underlayTexture: GpuTextureView? get() = underlayTarget?.view + + fun advance(size: IntSize, density: Float): Boolean { + if (scene.size != size || scene.density.density != density) { + scene.density = Density(density) + scene.size = size + platform.resize(size, density) + invalidated = true + } + recomposer.performFrame(System.nanoTime()) + scene.measureAndLayout() + return invalidated || scene.hasPendingDraw || target == null + } + + fun draw(underlay: GraphicsLayer? = null, beforeScene: (DirectContext) -> Unit = {}) { + val size = scene.size ?: return + val outgrown = + listOfNotNull( + target?.takeIf { it.size != size }, + underlayTarget?.takeIf { it.size != size || underlay == null } + ) + val target = target?.takeIf { it !in outgrown } ?: SkiaTarget(size).also { target = it } + val underlayTarget = + if (underlay == null) null + else underlayTarget?.takeIf { it !in outgrown } ?: SkiaTarget(size) + this.underlayTarget = underlayTarget + GlState.borrow { + val skia = skia ?: DirectContext.makeGL().also { skia = it } + outgrown.forEach { it.detach() } + val surface = target.attach(skia) + val underlaySurface = underlayTarget?.attach(skia) + skia.resetGLAll() + beforeScene(skia) + surface.canvas.clear(Color.TRANSPARENT) + scene.draw(surface.canvas.asComposeCanvas()) + surface.flushAndSubmit() + if (underlay != null && underlaySurface != null) { + underlaySurface.canvas.clear(Color.TRANSPARENT) + CanvasDrawScope().draw( + scene.density, + LayoutDirection.Ltr, + underlaySurface.canvas.asComposeCanvas(), + size.toSize() + ) { drawLayer(underlay) } + underlaySurface.flushAndSubmit() + } + } + outgrown.forEach { it.close() } + invalidated = false + } + + override fun close() { + scene.close() + recomposer.close() + } + + fun closeAndFree() { + runCatching { scene.close() } + runCatching { recomposer.close() } + val freed = listOfNotNull(target, underlayTarget) + target = null + underlayTarget = null + GlState.borrow { + freed.forEach { it.detach() } + skia?.close() + } + skia = null + freed.forEach { it.close() } + } } private class SkiaTarget(val size: IntSize) : AutoCloseable { - private val texture: GpuTexture = - RenderSystem.getDevice().createTexture( - { "Lambda GUI" }, - GpuTexture.USAGE_RENDER_ATTACHMENT or GpuTexture.USAGE_TEXTURE_BINDING, - TextureFormat.RGBA8, - size.width, size.height, 1, 1 - ) - val view: GpuTextureView = RenderSystem.getDevice().createTextureView(texture) - - private var framebuffer = 0 - private var stencil = 0 - private var renderTarget: BackendRenderTarget? = null - private var surface: Surface? = null - - fun attach(skia: DirectContext): Surface = surface - ?: run { - framebuffer = glGenFramebuffers() - stencil = glGenRenderbuffers() - glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) - glFramebufferTexture2D( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, - (texture as GlTexture).glId, - 0 - ) - glBindRenderbuffer(GL_RENDERBUFFER, stencil) - glRenderbufferStorage( - GL_RENDERBUFFER, - GL_DEPTH24_STENCIL8, - size.width, - size.height - ) - glFramebufferRenderbuffer( - GL_FRAMEBUFFER, - GL_DEPTH_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, - stencil - ) - - val renderTarget = - BackendRenderTarget.makeGL( - size.width, - size.height, - 0, - 8, - framebuffer, - FramebufferFormat.GR_GL_RGBA8 - ).also { renderTarget = it } - Surface.makeFromBackendRenderTarget( - skia, - renderTarget, - SurfaceOrigin.BOTTOM_LEFT, - SurfaceColorFormat.RGBA_8888, - ColorSpace.sRGB - )?.also { surface = it } ?: error("Skia rejected the GUI render target") - } - - fun detach() { - surface?.close() - surface = null - renderTarget?.close() - renderTarget = null - if (framebuffer != 0) glDeleteFramebuffers(framebuffer) - if (stencil != 0) glDeleteRenderbuffers(stencil) - framebuffer = 0 - stencil = 0 - } - - override fun close() { - view.close() - texture.close() - } + private val texture: GpuTexture = + RenderSystem.getDevice().createTexture( + { "Lambda GUI" }, + GpuTexture.USAGE_RENDER_ATTACHMENT or GpuTexture.USAGE_TEXTURE_BINDING, + TextureFormat.RGBA8, + size.width, size.height, 1, 1 + ) + val view: GpuTextureView = RenderSystem.getDevice().createTextureView(texture) + + private var framebuffer = 0 + private var stencil = 0 + private var renderTarget: BackendRenderTarget? = null + private var surface: Surface? = null + + fun attach(skia: DirectContext): Surface = surface + ?: run { + framebuffer = glGenFramebuffers() + stencil = glGenRenderbuffers() + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) + glFramebufferTexture2D( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + (texture as GlTexture).glId, + 0 + ) + glBindRenderbuffer(GL_RENDERBUFFER, stencil) + glRenderbufferStorage( + GL_RENDERBUFFER, + GL_DEPTH24_STENCIL8, + size.width, + size.height + ) + glFramebufferRenderbuffer( + GL_FRAMEBUFFER, + GL_DEPTH_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, + stencil + ) + + val renderTarget = + BackendRenderTarget.makeGL( + size.width, + size.height, + 0, + 8, + framebuffer, + FramebufferFormat.GR_GL_RGBA8 + ).also { renderTarget = it } + Surface.makeFromBackendRenderTarget( + skia, + renderTarget, + SurfaceOrigin.BOTTOM_LEFT, + SurfaceColorFormat.RGBA_8888, + ColorSpace.sRGB + )?.also { surface = it } ?: error("Skia rejected the GUI render target") + } + + fun detach() { + surface?.close() + surface = null + renderTarget?.close() + renderTarget = null + if (framebuffer != 0) glDeleteFramebuffers(framebuffer) + if (stencil != 0) glDeleteRenderbuffers(stencil) + framebuffer = 0 + stencil = 0 + } + + override fun close() { + view.close() + texture.close() + } } diff --git a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt index 858774b77..6deb7c369 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt @@ -34,185 +34,185 @@ import java.awt.Component import java.awt.event.KeyEvent as AwtKeyEvent internal object Press { - var id = 0L - private set + var id = 0L + private set - fun begin() { - id++ - } + fun begin() { + id++ + } } @OptIn(InternalComposeUiApi::class) internal class SceneInput(private val scene: ComposeScene) { - private var position = Offset.Zero - private var pressedButtons = 0 - - fun move(position: Offset) { - this.position = position - pointer(PointerEventType.Move) - } - - fun button(button: Int, pressed: Boolean, modifiers: Int) { - val mask = 1 shl button - pressedButtons = - if (pressed) pressedButtons or mask - else pressedButtons and mask.inv() - if (pressed) { - Press.begin() - KeyboardFocus.visible = false - } - pointer( - if (pressed) PointerEventType.Press else PointerEventType.Release, - button.toPointerButton(), - modifiers - ) - } - - fun scroll(horizontal: Double, vertical: Double) { - pointer( - PointerEventType.Scroll, - scroll = Offset(horizontal.toFloat(), -vertical.toFloat()) * LINES_PER_NOTCH - ) - } - - fun key(key: Int, pressed: Boolean, modifiers: Int): Boolean { - if (pressed) Press.begin() - val shift = modifiers and GLFW.GLFW_MOD_SHIFT != 0 - val direction = - when (key.takeIf { pressed }) { - GLFW.GLFW_KEY_TAB -> - if (shift) FocusDirection.Previous - else FocusDirection.Next - GLFW.GLFW_KEY_UP -> FocusDirection.Up - GLFW.GLFW_KEY_DOWN -> FocusDirection.Down - GLFW.GLFW_KEY_LEFT -> FocusDirection.Left - GLFW.GLFW_KEY_RIGHT -> FocusDirection.Right - else -> null - } - if (direction != null) KeyboardFocus.visible = true - - val handled = - scene.sendKeyEvent( - KeyEvent( - key = Key(key.toAwtKeyCode()), - type = if (pressed) KeyEventType.KeyDown else KeyEventType.KeyUp, - isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, - isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, - isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, - isShiftPressed = shift, - ) - ) - if (handled || direction == null) return handled - val inOrder = - when (direction) { - FocusDirection.Up, FocusDirection.Left -> FocusDirection.Previous - else -> FocusDirection.Next - } - return KeyboardFocus.move(direction) || direction != inOrder && KeyboardFocus.move(inOrder) - } - - fun type(codePoint: Int): Boolean = - Character.toChars(codePoint).fold(false) { handled, char -> - val typed = - AwtKeyEvent( - awtSource, - AwtKeyEvent.KEY_TYPED, - System.currentTimeMillis(), - 0, - AwtKeyEvent.VK_UNDEFINED, - char - ) - scene.sendKeyEvent( - KeyEvent( - key = Key.Unknown, - type = KeyEventType.Unknown, - codePoint = char.code, - nativeEvent = typed - ) - ) || handled - } - - fun release() { - pressedButtons = 0 - position = OFF_SCREEN - pointer(PointerEventType.Exit) - scene.cancelPointerInput() - scene.focusManager.releaseFocus() - KeyboardFocus.visible = false - } - - private fun pointer( - type: PointerEventType, - button: PointerButton? = null, - modifiers: Int = 0, - scroll: Offset = Offset.Zero, - ) { - scene.sendPointerEvent( - eventType = type, - position = position, - scrollDelta = scroll, - buttons = PointerButtons( - isPrimaryPressed = pressedButtons and 0b1 != 0, - isSecondaryPressed = pressedButtons and 0b10 != 0, - isTertiaryPressed = pressedButtons and 0b100 != 0, - isBackPressed = pressedButtons and 0b1000 != 0, - isForwardPressed = pressedButtons and 0b10000 != 0, - ), - keyboardModifiers = PointerKeyboardModifiers( - isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, - isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, - isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, - isShiftPressed = modifiers and GLFW.GLFW_MOD_SHIFT != 0, - ), - button = button, - ) - } - - private companion object { - val OFF_SCREEN = Offset(-1e6f, -1e6f) - - const val LINES_PER_NOTCH = 3f - - val awtSource = object : Component() {} - - fun Int.toPointerButton() = - when (this) { - GLFW.GLFW_MOUSE_BUTTON_LEFT -> PointerButton.Primary - GLFW.GLFW_MOUSE_BUTTON_RIGHT -> PointerButton.Secondary - GLFW.GLFW_MOUSE_BUTTON_MIDDLE -> PointerButton.Tertiary - GLFW.GLFW_MOUSE_BUTTON_4 -> PointerButton.Back - GLFW.GLFW_MOUSE_BUTTON_5 -> PointerButton.Forward - else -> null - } - - fun Int.toAwtKeyCode() = - when (this) { - GLFW.GLFW_KEY_ESCAPE -> AwtKeyEvent.VK_ESCAPE - GLFW.GLFW_KEY_ENTER, GLFW.GLFW_KEY_KP_ENTER -> AwtKeyEvent.VK_ENTER - GLFW.GLFW_KEY_TAB -> AwtKeyEvent.VK_TAB - GLFW.GLFW_KEY_SPACE -> AwtKeyEvent.VK_SPACE - GLFW.GLFW_KEY_BACKSPACE -> AwtKeyEvent.VK_BACK_SPACE - GLFW.GLFW_KEY_INSERT -> AwtKeyEvent.VK_INSERT - GLFW.GLFW_KEY_DELETE -> AwtKeyEvent.VK_DELETE - GLFW.GLFW_KEY_RIGHT -> AwtKeyEvent.VK_RIGHT - GLFW.GLFW_KEY_LEFT -> AwtKeyEvent.VK_LEFT - GLFW.GLFW_KEY_DOWN -> AwtKeyEvent.VK_DOWN - GLFW.GLFW_KEY_UP -> AwtKeyEvent.VK_UP - GLFW.GLFW_KEY_PAGE_UP -> AwtKeyEvent.VK_PAGE_UP - GLFW.GLFW_KEY_PAGE_DOWN -> AwtKeyEvent.VK_PAGE_DOWN - GLFW.GLFW_KEY_HOME -> AwtKeyEvent.VK_HOME - GLFW.GLFW_KEY_END -> AwtKeyEvent.VK_END - GLFW.GLFW_KEY_LEFT_SHIFT, GLFW.GLFW_KEY_RIGHT_SHIFT -> - AwtKeyEvent.VK_SHIFT - GLFW.GLFW_KEY_LEFT_CONTROL, GLFW.GLFW_KEY_RIGHT_CONTROL -> - AwtKeyEvent.VK_CONTROL - GLFW.GLFW_KEY_LEFT_ALT, GLFW.GLFW_KEY_RIGHT_ALT -> AwtKeyEvent.VK_ALT - GLFW.GLFW_KEY_LEFT_SUPER, GLFW.GLFW_KEY_RIGHT_SUPER -> AwtKeyEvent.VK_META - in GLFW.GLFW_KEY_A..GLFW.GLFW_KEY_Z, - in GLFW.GLFW_KEY_0..GLFW.GLFW_KEY_9 -> this - in GLFW.GLFW_KEY_F1..GLFW.GLFW_KEY_F12 -> - AwtKeyEvent.VK_F1 + (this - GLFW.GLFW_KEY_F1) - else -> AwtKeyEvent.VK_UNDEFINED - } - } + private var position = Offset.Zero + private var pressedButtons = 0 + + fun move(position: Offset) { + this.position = position + pointer(PointerEventType.Move) + } + + fun button(button: Int, pressed: Boolean, modifiers: Int) { + val mask = 1 shl button + pressedButtons = + if (pressed) pressedButtons or mask + else pressedButtons and mask.inv() + if (pressed) { + Press.begin() + KeyboardFocus.visible = false + } + pointer( + if (pressed) PointerEventType.Press else PointerEventType.Release, + button.toPointerButton(), + modifiers + ) + } + + fun scroll(horizontal: Double, vertical: Double) { + pointer( + PointerEventType.Scroll, + scroll = Offset(horizontal.toFloat(), -vertical.toFloat()) * LINES_PER_NOTCH + ) + } + + fun key(key: Int, pressed: Boolean, modifiers: Int): Boolean { + if (pressed) Press.begin() + val shift = modifiers and GLFW.GLFW_MOD_SHIFT != 0 + val direction = + when (key.takeIf { pressed }) { + GLFW.GLFW_KEY_TAB -> + if (shift) FocusDirection.Previous + else FocusDirection.Next + GLFW.GLFW_KEY_UP -> FocusDirection.Up + GLFW.GLFW_KEY_DOWN -> FocusDirection.Down + GLFW.GLFW_KEY_LEFT -> FocusDirection.Left + GLFW.GLFW_KEY_RIGHT -> FocusDirection.Right + else -> null + } + if (direction != null) KeyboardFocus.visible = true + + val handled = + scene.sendKeyEvent( + KeyEvent( + key = Key(key.toAwtKeyCode()), + type = if (pressed) KeyEventType.KeyDown else KeyEventType.KeyUp, + isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, + isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, + isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, + isShiftPressed = shift, + ) + ) + if (handled || direction == null) return handled + val inOrder = + when (direction) { + FocusDirection.Up, FocusDirection.Left -> FocusDirection.Previous + else -> FocusDirection.Next + } + return KeyboardFocus.move(direction) || direction != inOrder && KeyboardFocus.move(inOrder) + } + + fun type(codePoint: Int): Boolean = + Character.toChars(codePoint).fold(false) { handled, char -> + val typed = + AwtKeyEvent( + awtSource, + AwtKeyEvent.KEY_TYPED, + System.currentTimeMillis(), + 0, + AwtKeyEvent.VK_UNDEFINED, + char + ) + scene.sendKeyEvent( + KeyEvent( + key = Key.Unknown, + type = KeyEventType.Unknown, + codePoint = char.code, + nativeEvent = typed + ) + ) || handled + } + + fun release() { + pressedButtons = 0 + position = OFF_SCREEN + pointer(PointerEventType.Exit) + scene.cancelPointerInput() + scene.focusManager.releaseFocus() + KeyboardFocus.visible = false + } + + private fun pointer( + type: PointerEventType, + button: PointerButton? = null, + modifiers: Int = 0, + scroll: Offset = Offset.Zero, + ) { + scene.sendPointerEvent( + eventType = type, + position = position, + scrollDelta = scroll, + buttons = PointerButtons( + isPrimaryPressed = pressedButtons and 0b1 != 0, + isSecondaryPressed = pressedButtons and 0b10 != 0, + isTertiaryPressed = pressedButtons and 0b100 != 0, + isBackPressed = pressedButtons and 0b1000 != 0, + isForwardPressed = pressedButtons and 0b10000 != 0, + ), + keyboardModifiers = PointerKeyboardModifiers( + isCtrlPressed = modifiers and GLFW.GLFW_MOD_CONTROL != 0, + isMetaPressed = modifiers and GLFW.GLFW_MOD_SUPER != 0, + isAltPressed = modifiers and GLFW.GLFW_MOD_ALT != 0, + isShiftPressed = modifiers and GLFW.GLFW_MOD_SHIFT != 0, + ), + button = button, + ) + } + + private companion object { + val OFF_SCREEN = Offset(-1e6f, -1e6f) + + const val LINES_PER_NOTCH = 3f + + val awtSource = object : Component() {} + + fun Int.toPointerButton() = + when (this) { + GLFW.GLFW_MOUSE_BUTTON_LEFT -> PointerButton.Primary + GLFW.GLFW_MOUSE_BUTTON_RIGHT -> PointerButton.Secondary + GLFW.GLFW_MOUSE_BUTTON_MIDDLE -> PointerButton.Tertiary + GLFW.GLFW_MOUSE_BUTTON_4 -> PointerButton.Back + GLFW.GLFW_MOUSE_BUTTON_5 -> PointerButton.Forward + else -> null + } + + fun Int.toAwtKeyCode() = + when (this) { + GLFW.GLFW_KEY_ESCAPE -> AwtKeyEvent.VK_ESCAPE + GLFW.GLFW_KEY_ENTER, GLFW.GLFW_KEY_KP_ENTER -> AwtKeyEvent.VK_ENTER + GLFW.GLFW_KEY_TAB -> AwtKeyEvent.VK_TAB + GLFW.GLFW_KEY_SPACE -> AwtKeyEvent.VK_SPACE + GLFW.GLFW_KEY_BACKSPACE -> AwtKeyEvent.VK_BACK_SPACE + GLFW.GLFW_KEY_INSERT -> AwtKeyEvent.VK_INSERT + GLFW.GLFW_KEY_DELETE -> AwtKeyEvent.VK_DELETE + GLFW.GLFW_KEY_RIGHT -> AwtKeyEvent.VK_RIGHT + GLFW.GLFW_KEY_LEFT -> AwtKeyEvent.VK_LEFT + GLFW.GLFW_KEY_DOWN -> AwtKeyEvent.VK_DOWN + GLFW.GLFW_KEY_UP -> AwtKeyEvent.VK_UP + GLFW.GLFW_KEY_PAGE_UP -> AwtKeyEvent.VK_PAGE_UP + GLFW.GLFW_KEY_PAGE_DOWN -> AwtKeyEvent.VK_PAGE_DOWN + GLFW.GLFW_KEY_HOME -> AwtKeyEvent.VK_HOME + GLFW.GLFW_KEY_END -> AwtKeyEvent.VK_END + GLFW.GLFW_KEY_LEFT_SHIFT, GLFW.GLFW_KEY_RIGHT_SHIFT -> + AwtKeyEvent.VK_SHIFT + GLFW.GLFW_KEY_LEFT_CONTROL, GLFW.GLFW_KEY_RIGHT_CONTROL -> + AwtKeyEvent.VK_CONTROL + GLFW.GLFW_KEY_LEFT_ALT, GLFW.GLFW_KEY_RIGHT_ALT -> AwtKeyEvent.VK_ALT + GLFW.GLFW_KEY_LEFT_SUPER, GLFW.GLFW_KEY_RIGHT_SUPER -> AwtKeyEvent.VK_META + in GLFW.GLFW_KEY_A..GLFW.GLFW_KEY_Z, + in GLFW.GLFW_KEY_0..GLFW.GLFW_KEY_9 -> this + in GLFW.GLFW_KEY_F1..GLFW.GLFW_KEY_F12 -> + AwtKeyEvent.VK_F1 + (this - GLFW.GLFW_KEY_F1) + else -> AwtKeyEvent.VK_UNDEFINED + } + } } diff --git a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt index 579123235..9afa78de6 100644 --- a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt +++ b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt @@ -39,51 +39,51 @@ import java.awt.datatransfer.Transferable @OptIn(InternalComposeUiApi::class) internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { - private val window = - object : WindowInfo { - override val isWindowFocused get() = true - override var containerSize by mutableStateOf(IntSize.Zero) - override var containerDpSize by mutableStateOf(DpSize.Zero) - } - var cursor: Cursor? = null + private val window = + object : WindowInfo { + override val isWindowFocused get() = true + override var containerSize by mutableStateOf(IntSize.Zero) + override var containerDpSize by mutableStateOf(DpSize.Zero) + } + var cursor: Cursor? = null - override val windowInfo: WindowInfo get() = window + 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) - } + 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 - } - } + override fun setPointerIcon(pointerIcon: PointerIcon) { + cursor = + when (pointerIcon) { + PointerIcon.Text -> StandardCursors.IBEAM + PointerIcon.Hand -> StandardCursors.POINTING_HAND + PointerIcon.Crosshair -> StandardCursors.CROSSHAIR + ResizeVerticalIcon -> StandardCursors.RESIZE_NS + else -> null + } + } } object ResizeVerticalIcon : PointerIcon @OptIn(ExperimentalComposeUiApi::class) internal object GameClipboard : Clipboard { - @Suppress("OVERRIDE_DEPRECATION") - override val nativeClipboard: Any get() = this + @Suppress("OVERRIDE_DEPRECATION") + override val nativeClipboard: Any get() = this - override suspend fun getClipEntry(): ClipEntry? = - mc.keyboard.clipboard.takeIf { it.isNotEmpty() }?.let { - ClipEntry(StringSelection(it)) - } + override suspend fun 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 - ?: "" - } + 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/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt index 3a941dde0..35f931688 100644 --- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -37,7 +37,10 @@ import androidx.compose.ui.layout.layout import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.round import com.lambda.Lambda.mc import com.lambda.config.Config import com.lambda.config.categories.HudCategory @@ -60,95 +63,89 @@ private val HUD_TEXT_SHADOW = Color.Black.copy(alpha = 0.75f) private val ELEMENT_PADDING = 1.dp object HudConfig : Loadable, Config("HUD", HudCategory) { - val showInScreens by boolSetting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The HUD editor always shows them.") - val textColor by colorSetting("Text Color", java.awt.Color.WHITE, "Colour of HUD text") - val scale by floatSetting("Scale", 1f, 0.5f..3f, 0.05f, "Size of HUD text") + val showInScreens by boolSetting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The HUD editor always shows them.") + val textColor by colorSetting("Text Color", java.awt.Color.WHITE, "Colour of HUD text") + val scale by floatSetting("Scale", 1f, 0.5f..3f, 0.05f, "Size of HUD text") } internal object Hud { - val modules: List by lazy { ModuleRegistry.modules.filterIsInstance() } + val modules: List by lazy { ModuleRegistry.modules.filterIsInstance() } - val enabled: List - get() = modules.filter { it.isEnabled } + val enabled: List + get() = modules.filter { it.isEnabled } - val shown: List - get() { - val screen = mc.currentScreen - val covered = screen != null && screen !is GuiScreen && !HudConfig.showInScreens - return if (mc.world == null || mc.options.hudHidden || covered) emptyList() - else enabled - } + val shown: List + get() { + val screen = mc.currentScreen + val covered = screen != null && screen !is GuiScreen && !HudConfig.showInScreens + return if (mc.world == null || mc.options.hudHidden || covered) emptyList() + else enabled + } } @Composable internal fun HudLayer(editor: HudEditorState? = null) { - val shown by observe { - if (editor != null) Hud.enabled - else Hud.shown - } - Box(Modifier.fillMaxSize()) { - shown.forEach { hud -> - key(hud) { HudElement(hud, editor) } - } - } + val shown by observe { + if (editor != null) Hud.enabled + else Hud.shown + } + Box(Modifier.fillMaxSize()) { + shown.forEach { hud -> + key(hud) { HudElement(hud, editor) } + } + } } @Composable private fun HudElement(hud: HudModule, editor: HudEditorState?) { - val anchor by observe { Offset(hud.anchorX, hud.anchorY) } - val background by observe { hud.backgroundColor.value.toCompose() } - val scale by observe { hud.scale } - var empty by remember { mutableStateOf(false) } - if (editor != null) DisposableEffect(hud) { - onDispose { editor.bounds -= hud } - } + val pinned by observe { Offset(hud.anchorX, hud.anchorY) } + val anchor by observe { hud.anchor } + val background by observe { hud.backgroundColor.value.toCompose() } + val scale by observe { hud.scale } + var empty by remember { mutableStateOf(false) } + if (editor != null) DisposableEffect(hud) { + onDispose { editor.bounds -= hud } + } - val density = LocalDensity.current - val scaled = remember(density, scale) { Density(density.density * scale, density.fontScale) } - Box( - Modifier - .layout { measurable, constraints -> - val placeable = - measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) - val roomX = (constraints.maxWidth - placeable.width).coerceAtLeast(0) - val roomY = (constraints.maxHeight - placeable.height).coerceAtLeast(0) - val dragged = editor?.shownPosition(hud) - layout(constraints.maxWidth, constraints.maxHeight) { - placeable.place( - (dragged?.x ?: (roomX * anchor.x)) - .roundToInt() - .coerceIn(0, roomX), - (dragged?.y ?: (roomY * anchor.y)) - .roundToInt() - .coerceIn(0, roomY) - ) - } - } - .then(if (editor != null) Modifier.hudEditable(hud, editor) else Modifier) - .clipToBounds() - .background(background) - ) { - CompositionLocalProvider(LocalDensity provides scaled) { - Box(Modifier.padding(ELEMENT_PADDING)) { - Box(Modifier.onSizeChanged { empty = it.width == 0 || it.height == 0 }) { hud.Content() } - if (editor != null && empty) HudText(hud.name, color = LambdaTheme.colors.onSurfaceVariant) - } - } - } + val density = LocalDensity.current + val scaled = remember(density, scale) { Density(density.density * scale, density.fontScale) } + Box( + Modifier + .layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) + val size = IntSize(placeable.width, placeable.height) + val screen = IntSize(constraints.maxWidth, constraints.maxHeight) + hud.shownSize = size + hud.shownScreen = screen + val point = IntOffset((screen.width * pinned.x).roundToInt(), (screen.height * pinned.y).roundToInt()) + val topLeft = editor?.shownPosition(hud)?.round() ?: (point - anchor.offset(size)) + layout(screen.width, screen.height) { placeable.place(topLeft) } + } + .then(if (editor != null) Modifier.hudEditable(hud, editor) else Modifier) + .clipToBounds() + .background(background) + ) { + CompositionLocalProvider(LocalDensity provides scaled) { + Box(Modifier.padding(ELEMENT_PADDING)) { + Box(Modifier.onSizeChanged { empty = it.width == 0 || it.height == 0 }) { hud.Content() } + if (editor != null && empty) HudText(hud.name, color = LambdaTheme.colors.onSurfaceVariant) + } + } + } } @Composable fun HudText(text: String, modifier: Modifier = Modifier, color: Color? = null) { - val hudColor by observe { HudConfig.textColor.toCompose() } - val scale by observe { HudConfig.scale } - val size = Type.body.fontSize * scale - Text( - text, - modifier, - color ?: hudColor, - Type.body.copy( - fontSize = size, - lineHeight = size * 1.25f - ).shadowed(HUD_TEXT_SHADOW) - ) + val hudColor by observe { HudConfig.textColor.toCompose() } + val scale by observe { HudConfig.scale } + val size = Type.body.fontSize * scale + Text( + text, + modifier, + color ?: hudColor, + Type.body.copy( + fontSize = size, + lineHeight = size * 1.25f + ).shadowed(HUD_TEXT_SHADOW) + ) } diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt index e5904fb34..94a73561a 100644 --- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -49,7 +49,8 @@ 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.composed +import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size @@ -101,270 +102,276 @@ import com.lambda.module.Module private val PANEL_SCALE = spring(stiffness = Spring.StiffnessMedium) private val CONFIG_WIDTH = 150.dp +private val ANCHOR_MARK = 1.5.dp +private const val ANCHOR_MARK_ALPHA = 0.9f internal class HudEditorState(snapping: State) { - val snapping by snapping + val snapping by snapping - val bounds = mutableStateMapOf() + val bounds = mutableStateMapOf() - var dragged by mutableStateOf(null) - var draggedTo by mutableStateOf(Offset.Zero) + var dragged by mutableStateOf(null) + var draggedTo by mutableStateOf(Offset.Zero) - var menu by mutableStateOf?>(null) - private set + var menu by mutableStateOf?>(null) + private set - var menusOpened by mutableStateOf(0) - private set + var menusOpened by mutableStateOf(0) + private set - fun openMenu(position: Offset, hud: HudModule?) { - menu = position to hud - menusOpened++ - } + fun openMenu(position: Offset, hud: HudModule?) { + menu = position to hud + menusOpened++ + } - fun closeMenu() { - menu = null - } + fun closeMenu() { + menu = null + } - var configuring by mutableStateOf(null) - private set + var configuring by mutableStateOf(null) + private set - var panelPosition by mutableStateOf(Offset.Zero) + var panelPosition by mutableStateOf(Offset.Zero) - var panelBounds = Rect.Zero + var panelBounds = Rect.Zero - fun configure(config: Config?, position: Offset? = null) { - configuring = config - if (config != null) panelPosition = position - ?: Offset( - screen.width / 2 - 120 * density.density, - screen.height * 0.15f - ) - } + fun configure(config: Config?, position: Offset? = null) { + configuring = config + if (config != null) panelPosition = position + ?: Offset( + screen.width / 2 - 120 * density.density, + screen.height * 0.15f + ) + } - var screen = Size.Zero - var density = Density(1f) + var screen = Size.Zero + var density = Density(1f) - val drop: Snap.Result? by - derivedStateOf { - val hud = dragged ?: return@derivedStateOf null - val element = Rect(draggedTo, bounds[hud]?.size ?: return@derivedStateOf null) - if (this.snapping) { - Snap.snap( - element, - bounds.filterKeys { it != hud }.values, - Rect(Offset.Zero, screen), - density - ) - } - else Snap.free(element, Rect(Offset.Zero, screen)) - } + val drop: Snap.Result? by + derivedStateOf { + val hud = dragged ?: return@derivedStateOf null + val element = Rect(draggedTo, bounds[hud]?.size ?: return@derivedStateOf null) + if (this.snapping) { + Snap.snap( + element, + bounds.filterKeys { it != hud }.values, + Rect(Offset.Zero, screen), + density + ) + } + else Snap.free(element, Rect(Offset.Zero, screen)) + } - fun shownPosition(hud: HudModule) = drop?.position.takeIf { dragged == hud } + fun shownPosition(hud: HudModule) = drop?.position.takeIf { dragged == hud } } @Composable internal fun HudEditor() { - val snapping = observe { Snap.isActive } - val editor = remember { HudEditorState(snapping) } - editor.screen = LocalWindowInfo.current.containerSize.toSize() - editor.density = LocalDensity.current + val snapping = observe { Snap.isActive } + val editor = remember { HudEditorState(snapping) } + editor.screen = LocalWindowInfo.current.containerSize.toSize() + editor.density = LocalDensity.current - val revealedElement = Reveal.module as? HudModule - val revealedSetting = Reveal.setting - LaunchedEffect(revealedElement, revealedSetting) { - if (revealedElement != null && revealedSetting != null) editor.configure(revealedElement) - } + val revealedElement = Reveal.module as? HudModule + val revealedSetting = Reveal.setting + LaunchedEffect(revealedElement, revealedSetting) { + if (revealedElement != null && revealedSetting != null) editor.configure(revealedElement) + } - Box( - Modifier - .fillMaxSize() - .onMousePress(PointerButton.Secondary) { editor.openMenu(it, null) } - .pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent(PointerEventPass.Initial) - if (event.type != PointerEventType.Press || editor.configuring == null) continue - if (event.changes.first().position !in editor.panelBounds) editor.configure(null) - } - } - } - .snapLines { editor.drop } - ) { - HudLayer(editor) - rememberLast(editor.configuring)?.let { config -> - key(config) { ElementSettings(config, editor.configuring === config, editor) } - } - } + Box( + Modifier + .fillMaxSize() + .onMousePress(PointerButton.Secondary) { editor.openMenu(it, null) } + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type != PointerEventType.Press || editor.configuring == null) continue + if (event.changes.first().position !in editor.panelBounds) editor.configure(null) + } + } + } + .snapLines { editor.drop } + ) { + HudLayer(editor) + rememberLast(editor.configuring)?.let { config -> + key(config) { ElementSettings(config, editor.configuring === config, editor) } + } + } - rememberLast(editor.menu)?.let { (position, hud) -> - key(editor.menusOpened) { - ContextMenu( - editor.menu != null, - position.round(), - onDismiss = editor::closeMenu - ) { - if (hud != null) ElementMenu(hud, editor) - else ScreenMenu(position, editor) - } - } - } + rememberLast(editor.menu)?.let { (position, hud) -> + key(editor.menusOpened) { + ContextMenu( + editor.menu != null, + position.round(), + onDismiss = editor::closeMenu + ) { + if (hud != null) ElementMenu(hud, editor) + else ScreenMenu(position, editor) + } + } + } } @Composable private fun ElementMenu(hud: HudModule, editor: HudEditorState) { - MenuLabel(hud.name) - MenuItem("Settings...") { editor.configure(hud, editor.menu?.first) } - MenuItem("Remove") { hud.disable() } - MenuDivider() - EditorHelp() + MenuLabel(hud.name) + MenuItem("Settings...") { editor.configure(hud, editor.menu?.first) } + MenuItem("Remove") { hud.disable() } + MenuDivider() + EditorHelp() } @Composable private fun EditorHelp() { - val snapping by observe { - when { - !GuiConfig.snapEnabled -> "" - GuiConfig.snapKey == Bind.EMPTY -> " Elements snap into line." - else -> " Hold ${GuiConfig.snapKey.name} to snap it into line." - } - } - MenuHelp("Drag an element to move it.$snapping Right click an element to remove or configure it, or the empty screen to add one.") + val snapping by observe { + when { + !GuiConfig.snapEnabled -> "" + GuiConfig.snapKey == Bind.EMPTY -> " Elements snap into line." + else -> " Hold ${GuiConfig.snapKey.name} to snap it into line." + } + } + MenuHelp("Drag an element to move it.$snapping Right click an element to remove or configure it, or the empty screen to add one.") } @Composable private fun ScreenMenu(position: Offset, editor: HudEditorState) { - val screen = LocalWindowInfo.current.containerSize - val hidden by observe { Hud.modules.filter { !it.isEnabled }.sortedBy { it.name.lowercase() } } - if (hidden.isEmpty()) MenuLabel("Every HUD element is shown") - else { - MenuLabel("Add HUD Element") - hidden.forEach { hud -> - MenuItem(hud.name) { - hud.anchorX = (position.x / screen.width).coerceIn(0f, 1f) - hud.anchorY = (position.y / screen.height).coerceIn(0f, 1f) - hud.enable() - } - } - } - MenuDivider() - MenuItem("HUD Settings...") { editor.configure(HudConfig, position) } - EditorHelp() - MenuItem("Back") { LambdaGui.back() } + val screen = LocalWindowInfo.current.containerSize + val hidden by observe { Hud.modules.filter { !it.isEnabled }.sortedBy { it.name.lowercase() } } + if (hidden.isEmpty()) MenuLabel("Every HUD element is shown") + else { + MenuLabel("Add HUD Element") + hidden.forEach { hud -> + MenuItem(hud.name) { + hud.anchorX = (position.x / screen.width).coerceIn(0f, 1f) + hud.anchorY = (position.y / screen.height).coerceIn(0f, 1f) + hud.enable() + } + } + } + MenuDivider() + MenuItem("HUD Settings...") { editor.configure(HudConfig, position) } + EditorHelp() + MenuItem("Back") { LambdaGui.back() } } @Composable private fun ElementSettings(config: Config, open: Boolean, editor: HudEditorState) { - val colors = LambdaTheme.colors - val density = LocalDensity.current - val maxHeight = with(density) { editor.screen.height.toDp() } * 0.6f - var size by remember { mutableStateOf(IntSize.Zero) } - val room = - Offset( - (editor.screen.width - size.width).coerceAtLeast(0f), - (editor.screen.height - size.height).coerceAtLeast(0f) - ) - val position = - Offset( - editor.panelPosition.x.coerceIn(0f, room.x), - editor.panelPosition.y.coerceIn(0f, room.y) - ) - val shownAt by rememberUpdatedState(position) - if (open) editor.panelBounds = Rect(position, size.toSize()) - DisposableEffect(Unit) { - LambdaGui.onEscape = { (editor.configuring != null).also { editor.configure(null) } } - onDispose { LambdaGui.onEscape = null } - } + val colors = LambdaTheme.colors + val density = LocalDensity.current + val maxHeight = with(density) { editor.screen.height.toDp() } * 0.6f + var size by remember { mutableStateOf(IntSize.Zero) } + val room = + Offset( + (editor.screen.width - size.width).coerceAtLeast(0f), + (editor.screen.height - size.height).coerceAtLeast(0f) + ) + val position = + Offset( + editor.panelPosition.x.coerceIn(0f, room.x), + editor.panelPosition.y.coerceIn(0f, room.y) + ) + val shownAt by rememberUpdatedState(position) + if (open) editor.panelBounds = Rect(position, size.toSize()) + DisposableEffect(Unit) { + LambdaGui.onEscape = { (editor.configuring != null).also { editor.configure(null) } } + onDispose { LambdaGui.onEscape = null } + } - val visibility = remember { MutableTransitionState(false) } - visibility.targetState = open - AnimatedVisibility( - visibleState = visibility, - modifier = Modifier.offset { position.round() }, - enter = scaleIn(PANEL_SCALE), - exit = scaleOut(PANEL_SCALE), - ) { - Column( - Modifier - .onSizeChanged { size = it } - .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) - .pointerInput(Unit) { - awaitEachGesture { - val down = awaitFirstDown() - down.consume() - editor.panelPosition = shownAt - drag(down.id) { change -> - editor.panelPosition += change.positionChange() - change.consume() - } - } - } - .padding(Look.panelPadding) - ) { - if (config is Module) { - var page by remember(config) { mutableStateOf(PanelPage.Settings) } - Column( - Modifier - .widthIn(MIN_PANEL_WIDTH, Look.settingsWidth) - .heightIn(max = maxHeight) - .widthOfContent() - ) { - Text( - config.name, - Modifier.padding(start = ROW_INSET, bottom = Look.settingSpacing), - style = Type.title, - maxLines = 1 - ) - ModuleSettings(config, page, { page = it }, rememberScrollState()) - } - } - else ConfigSettings(config, maxHeight, onDone = { editor.configure(null) }, Modifier.width(CONFIG_WIDTH)) - } - } + val visibility = remember { MutableTransitionState(false) } + visibility.targetState = open + AnimatedVisibility( + visibleState = visibility, + modifier = Modifier.offset { position.round() }, + enter = scaleIn(PANEL_SCALE), + exit = scaleOut(PANEL_SCALE), + ) { + Column( + Modifier + .onSizeChanged { size = it } + .window(colors.panel, colors.border, RoundedCornerShape(Look.panelRounding), floating = true) + .pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown() + down.consume() + editor.panelPosition = shownAt + drag(down.id) { change -> + editor.panelPosition += change.positionChange() + change.consume() + } + } + } + .padding(Look.panelPadding) + ) { + if (config is Module) { + var page by remember(config) { mutableStateOf(PanelPage.Settings) } + Column( + Modifier + .widthIn(MIN_PANEL_WIDTH, Look.settingsWidth) + .heightIn(max = maxHeight) + .widthOfContent() + ) { + Text( + config.name, + Modifier.padding(start = ROW_INSET, bottom = Look.settingSpacing), + style = Type.title, + maxLines = 1 + ) + ModuleSettings(config, page, { page = it }, rememberScrollState()) + } + } + else ConfigSettings(config, maxHeight, onDone = { editor.configure(null) }, Modifier.width(CONFIG_WIDTH)) + } + } } 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() + composed { + val anchor by observe { hud.anchor } + Modifier + .onGloballyPositioned { editor.bounds[hud] = Rect(it.positionInRoot(), it.size.toSize()) } + .onMousePress(PointerButton.Secondary) { position -> + editor.bounds[hud]?.let { editor.openMenu(it.topLeft + position, hud) } + } + .pointerInput(hud) { + awaitEachGesture { + val down = awaitFirstDown() + val origin = editor.bounds[hud] ?: return@awaitEachGesture + down.consume() - editor.draggedTo = origin.topLeft - editor.dragged = hud - try { - drag(down.id) { change -> - editor.draggedTo += change.positionChange() - change.consume() - } - } finally { - val dropped = editor.drop?.position ?: origin.topLeft - val room = editor.screen - origin.size - hud.anchorX = - if (room.width > 0f) (dropped.x / room.width).coerceIn(0f, 1f) - else 0f - hud.anchorY = - if (room.height > 0f) (dropped.y / room.height).coerceIn(0f, 1f) - else 0f - editor.dragged = null - } - } - } - .drawBehind { - val width = Look.outlineWidth.toPx() - val alpha = - if (editor.dragged == hud || Reveal.module === hud) 0.9f - else 0.35f - drawRect( - color = Color.White.copy(alpha = alpha), - topLeft = Offset(width / 2, width / 2), - size = Size(size.width - width, size.height - width), - style = Stroke(width) - ) - } - -private operator fun Size.minus(other: Size) = Size(width - other.width, height - other.height) + editor.draggedTo = origin.topLeft + editor.dragged = hud + try { + drag(down.id) { change -> + editor.draggedTo += change.positionChange() + change.consume() + } + } finally { + hud.place((editor.drop?.position ?: origin.topLeft).round()) + editor.dragged = null + } + } + } + .drawWithContent { + drawContent() + val width = Look.outlineWidth.toPx() + val alpha = + if (editor.dragged == hud || Reveal.module === hud) 0.9f + else 0.35f + drawRect( + color = Color.White.copy(alpha = alpha), + topLeft = Offset(width / 2, width / 2), + size = Size(size.width - width, size.height - width), + style = Stroke(width) + ) + val mark = ANCHOR_MARK.toPx() + drawRect( + Color.White.copy(alpha = ANCHOR_MARK_ALPHA), + Offset( + ((size.width - mark) * anchor.x).coerceAtLeast(0f), + ((size.height - mark) * anchor.y).coerceAtLeast(0f) + ), + Size(mark, mark) + ) + } + } diff --git a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt index 38cdb5974..4b3b9788b 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Dialogs.kt @@ -62,150 +62,150 @@ import net.minecraft.util.Util @Composable internal fun ConfigDialog(config: Config, onDismiss: () -> Unit) { - val maxHeight = - with(LocalDensity.current) { - LocalWindowInfo.current.containerSize.height.toDp() - } * 0.7f - Dialog(onDismiss) { dismiss -> - ConfigSettings(config, maxHeight, dismiss, Modifier.width(240.dp)) - } + val maxHeight = + with(LocalDensity.current) { + LocalWindowInfo.current.containerSize.height.toDp() + } * 0.7f + Dialog(onDismiss) { dismiss -> + ConfigSettings(config, maxHeight, dismiss, Modifier.width(240.dp)) + } } @Composable internal fun NewAutomationConfigDialog(onDismiss: () -> Unit) { - var name by remember { mutableStateOf("") } - val isAvailable = name.isNotBlank() && ConfigLoader.configs.none { it.name == name } + var name by remember { mutableStateOf("") } + val isAvailable = name.isNotBlank() && ConfigLoader.configs.none { it.name == name } - fun create(dismiss: () -> Unit) { - if (!isAvailable) return - UserAutomationConfig(name) - dismiss() - } + fun create(dismiss: () -> Unit) { + if (!isAvailable) return + UserAutomationConfig(name) + dismiss() + } - Dialog(onDismiss) { dismiss -> - 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 = dismiss) - Button("Create", enabled = isAvailable) { create(dismiss) } - } - } - } + Dialog(onDismiss) { dismiss -> + 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 = dismiss) + Button("Create", enabled = isAvailable) { create(dismiss) } + } + } + } } @Composable internal fun AboutDialog(onDismiss: () -> Unit) { - val colors = LambdaTheme.colors - val facts by - observe { - 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() } - } + val colors = LambdaTheme.colors + val facts by + observe { + 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) { dismiss -> - 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 = dismiss) - } - } - } + Dialog(onDismiss) { dismiss -> + 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 = dismiss) + } + } + } } @Composable internal fun LoaderPromptDialog(prompt: AutoUpdater.Prompt) { - if (!LocalShown.current && prompt == AutoUpdater.Prompt.FirstLaunch) return - val colors = LambdaTheme.colors - Dialog(onDismiss = { AutoUpdater.answerPrompt(accepted = false) }) { - Column(Modifier.width(260.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { - when (prompt) { - AutoUpdater.Prompt.Uninstall -> { - Text("Uninstall Lambda Loader?", style = Type.title) - Text("This will close the client automatically once the uninstall is finished.") - } - AutoUpdater.Prompt.FirstLaunch, AutoUpdater.Prompt.Install -> { - Text("Switch to Lambda Loader?", style = Type.title) - Text("Lambda Loader replaces this version-specific Lambda jar with a lightweight bootstrap that keeps Lambda up to date.") - Text("• Automatic updates on launch\n• No manual jar replacement") - Text("If you choose to switch, Lambda will install the loader and close the game so changes apply on next start.") - Text( - "You can change this later from the AutoUpdater module.", - color = colors.onSurfaceVariant - ) - } - } - Row( - Modifier.fillMaxWidth().padding(top = 4.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Centered.VERTICALLY - ) { - 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) } - } - } - } + if (!LocalShown.current && prompt == AutoUpdater.Prompt.FirstLaunch) return + val colors = LambdaTheme.colors + Dialog(onDismiss = { AutoUpdater.answerPrompt(accepted = false) }) { + Column(Modifier.width(260.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + when (prompt) { + AutoUpdater.Prompt.Uninstall -> { + Text("Uninstall Lambda Loader?", style = Type.title) + Text("This will close the client automatically once the uninstall is finished.") + } + AutoUpdater.Prompt.FirstLaunch, AutoUpdater.Prompt.Install -> { + Text("Switch to Lambda Loader?", style = Type.title) + Text("Lambda Loader replaces this version-specific Lambda jar with a lightweight bootstrap that keeps Lambda up to date.") + Text("• Automatic updates on launch\n• No manual jar replacement") + Text("If you choose to switch, Lambda will install the loader and close the game so changes apply on next start.") + Text( + "You can change this later from the AutoUpdater module.", + color = colors.onSurfaceVariant + ) + } + } + Row( + Modifier.fillMaxWidth().padding(top = 4.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Centered.VERTICALLY + ) { + 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 index 4ed14b798..428c4d91b 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -117,421 +117,421 @@ private val SEARCH_WIDTH = 150.dp @Composable internal fun MenuBar(modifier: Modifier = Modifier) { - val colors = LambdaTheme.colors - var bar by remember { mutableStateOf(IntSize.Zero) } - var menus by remember { mutableStateOf(IntSize.Zero) } - var search by remember { mutableStateOf(IntSize.Zero) } - Box( - contentAlignment = Centered.BOTH, - modifier = modifier - .fillMaxWidth() - .height(MENU_BAR_HEIGHT) - .onSizeChanged { bar = it } - .glass(colors.surface, RectangleShape) - .consumeClicks() - ) { - Row( - Modifier - .align(Centered.START) - .fillMaxHeight() - .onSizeChanged { menus = it }, - verticalAlignment = Centered.VERTICALLY - ) { - BarMenu("Lambda", icon = "textures/lambda.png") { LambdaMenu() } - BarMenu("Modules") { ModulesMenu() } - BarMenu("Automation") { AutomationMenu() } - BarMenu("Minecraft") { MinecraftMenu() } - BarMenu("Help") { HelpMenu() } - } - SearchField( - Modifier - .onSizeChanged { search = it } - .offset { - IntOffset( - (menus.width - (bar.width - search.width) / 2).coerceAtLeast(0), - 0 - ) - } - ) - } + val colors = LambdaTheme.colors + var bar by remember { mutableStateOf(IntSize.Zero) } + var menus by remember { mutableStateOf(IntSize.Zero) } + var search by remember { mutableStateOf(IntSize.Zero) } + Box( + contentAlignment = Centered.BOTH, + modifier = modifier + .fillMaxWidth() + .height(MENU_BAR_HEIGHT) + .onSizeChanged { bar = it } + .glass(colors.surface, RectangleShape) + .consumeClicks() + ) { + Row( + Modifier + .align(Centered.START) + .fillMaxHeight() + .onSizeChanged { menus = it }, + verticalAlignment = Centered.VERTICALLY + ) { + BarMenu("Lambda", icon = "textures/lambda.png") { LambdaMenu() } + BarMenu("Modules") { ModulesMenu() } + BarMenu("Automation") { AutomationMenu() } + BarMenu("Minecraft") { MinecraftMenu() } + BarMenu("Help") { HelpMenu() } + } + SearchField( + Modifier + .onSizeChanged { search = it } + .offset { + IntOffset( + (menus.width - (bar.width - search.width) / 2).coerceAtLeast(0), + 0 + ) + } + ) + } } @Composable private fun BarMenu( - label: String, - icon: String? = null, - content: @Composable ColumnScope.() -> Unit + label: String, + icon: String? = null, + content: @Composable ColumnScope.() -> Unit ) { - val menu = remember { MenuState() } - Box( - contentAlignment = Centered.BOTH, - modifier = Modifier - .fillMaxHeight() - .hoverHighlight(LambdaTheme.colors.controlSelected) - .mouseClickable(onClick = menu::toggle) - .padding(horizontal = 6.dp) - ) { - Row( - verticalAlignment = Centered.VERTICALLY, - horizontalArrangement = Arrangement.spacedBy(3.dp) - ) { - if (icon != null) { - Image( - rememberTexture(icon), - contentDescription = null, - Modifier.size(ICON_SIZE), - filterQuality = FilterQuality.High - ) - } - Text(label, maxLines = 1) - } - Menu(menu.isOpen, onDismiss = menu::dismiss, content = content) - } + val menu = remember { MenuState() } + Box( + contentAlignment = Centered.BOTH, + modifier = Modifier + .fillMaxHeight() + .hoverHighlight(LambdaTheme.colors.controlSelected) + .mouseClickable(onClick = menu::toggle) + .padding(horizontal = 6.dp) + ) { + Row( + verticalAlignment = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + if (icon != null) { + Image( + rememberTexture(icon), + contentDescription = null, + Modifier.size(ICON_SIZE), + filterQuality = FilterQuality.High + ) + } + Text(label, maxLines = 1) + } + Menu(menu.isOpen, onDismiss = menu::dismiss, content = content) + } } @Composable private fun SearchField(modifier: Modifier = Modifier) { - val focus = LocalFocusManager.current - val field = remember { FocusRequester() } - val asked = ClickGuiState.focusSearch - LaunchedEffect(asked) { - if (asked) field.requestFocus() - ClickGuiState.focusSearch = false - } - var query by remember { mutableStateOf("") } - var listed by remember { mutableStateOf(false) } - val results = remember(query) { Search.find(query.trim()) } - val open = listed && query.isNotBlank() - val shown = rememberLast(results.takeIf { open }).orEmpty() - var marked by remember(results) { mutableStateOf(0) } + val focus = LocalFocusManager.current + val field = remember { FocusRequester() } + val asked = ClickGuiState.focusSearch + LaunchedEffect(asked) { + if (asked) field.requestFocus() + ClickGuiState.focusSearch = false + } + var query by remember { mutableStateOf("") } + var listed by remember { mutableStateOf(false) } + val results = remember(query) { Search.find(query.trim()) } + val open = listed && query.isNotBlank() + val shown = rememberLast(results.takeIf { open }).orEmpty() + var marked by remember(results) { mutableStateOf(0) } - fun choose(result: Search.Result) { - query = "" - listed = false - focus.clearFocus() - result.choose() - } + fun choose(result: Search.Result) { + query = "" + listed = false + focus.clearFocus() + result.choose() + } - Box( - modifier.onPreviewKeyEvent { event -> - when { - event.type != KeyEventType.KeyDown -> false - event.key == Key.Escape && query.isNotEmpty() -> { - query = "" - listed = false - true - } - event.key == Key.Enter -> { - if (open) results.getOrNull(marked)?.let(::choose) - true - } - !open || results.isEmpty() -> false - event.key == Key.DirectionDown || - event.key == Key.Tab && !event.isShiftPressed -> { - marked = (marked + 1).mod(results.size) - true - } - event.key == Key.DirectionUp || event.key == Key.Tab -> { - marked = (marked - 1).mod(results.size) - true - } - else -> false - } - } - ) { - TextInput( - value = query, - onValueChange = { - query = it - listed = true - }, - modifier = Modifier.width(SEARCH_WIDTH).focusRequester(field), - placeholder = "Search modules and settings", - ) - Suggestions(open, onDismiss = { listed = false }) { - if (shown.isEmpty()) MenuLabel("Nothing found") - shown.forEachIndexed { index, result -> - ResultRow( - result, - marked = index == marked, - onPoint = { marked = index } - ) { - choose(result) - } - } - } - } + Box( + modifier.onPreviewKeyEvent { event -> + when { + event.type != KeyEventType.KeyDown -> false + event.key == Key.Escape && query.isNotEmpty() -> { + query = "" + listed = false + true + } + event.key == Key.Enter -> { + if (open) results.getOrNull(marked)?.let(::choose) + true + } + !open || results.isEmpty() -> false + event.key == Key.DirectionDown || + event.key == Key.Tab && !event.isShiftPressed -> { + marked = (marked + 1).mod(results.size) + true + } + event.key == Key.DirectionUp || event.key == Key.Tab -> { + marked = (marked - 1).mod(results.size) + true + } + else -> false + } + } + ) { + TextInput( + value = query, + onValueChange = { + query = it + listed = true + }, + modifier = Modifier.width(SEARCH_WIDTH).focusRequester(field), + placeholder = "Search modules and settings", + ) + Suggestions(open, onDismiss = { listed = false }) { + if (shown.isEmpty()) MenuLabel("Nothing found") + shown.forEachIndexed { index, result -> + ResultRow( + result, + marked = index == marked, + onPoint = { marked = index } + ) { + choose(result) + } + } + } + } } @Composable private fun ResultRow( - result: Search.Result, - marked: Boolean, - onPoint: () -> Unit, - onClick: () -> Unit + result: Search.Result, + marked: Boolean, + onPoint: () -> Unit, + onClick: () -> Unit ) { - val colors = LambdaTheme.colors - val intoView = remember { BringIntoViewRequester() } - LaunchedEffect(marked) { - if (marked) intoView.bringIntoView() - } - val point by rememberUpdatedState(onPoint) - Row( - verticalAlignment = Centered.VERTICALLY, - modifier = Modifier - .fillMaxWidth() - .widthIn(min = SEARCH_WIDTH) - .bringIntoViewRequester(intoView) - .background(if (marked) colors.controlSelected else Color.Transparent) - .pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - if (awaitPointerEvent().type == PointerEventType.Move) point() - } - } - } - .mouseClickable(keyboard = false, onClick = onClick) - .padding(horizontal = 5.dp, vertical = 1.dp) - ) { - Text(result.name, maxLines = 1) - Spacer(Modifier.weight(1f).widthIn(min = 10.dp)) - Text( - result.origin, - color = colors.onSurfaceVariant, - style = Type.label, - maxLines = 1 - ) - } + val colors = LambdaTheme.colors + val intoView = remember { BringIntoViewRequester() } + LaunchedEffect(marked) { + if (marked) intoView.bringIntoView() + } + val point by rememberUpdatedState(onPoint) + Row( + verticalAlignment = Centered.VERTICALLY, + modifier = Modifier + .fillMaxWidth() + .widthIn(min = SEARCH_WIDTH) + .bringIntoViewRequester(intoView) + .background(if (marked) colors.controlSelected else Color.Transparent) + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + if (awaitPointerEvent().type == PointerEventType.Move) point() + } + } + } + .mouseClickable(keyboard = false, onClick = onClick) + .padding(horizontal = 5.dp, vertical = 1.dp) + ) { + Text(result.name, maxLines = 1) + Spacer(Modifier.weight(1f).widthIn(min = 10.dp)) + Text( + result.origin, + color = colors.onSurfaceVariant, + style = Type.label, + maxLines = 1 + ) + } } @Composable private fun LambdaMenu() { - Submenu("Save Config") { - MenuItem("Save All Configs") { - ConfigLoader.configCategories.forEach { it.trySaveToFile(true) } - GuiConfig.info( - "Saved ${ConfigLoader.configCategories.size} configuration files." - ) - } - ConfigLoader.configCategories.forEach { category -> - MenuItem("Save ${category.name}") { - category.trySaveToFile(true) - GuiConfig.info("Saved ${category.name}") - } - } - } - Submenu("Load Config") { - MenuItem("Load All Configs") { - ConfigLoader.configCategories.forEach { it.tryLoadFromFile() } - GuiConfig.info( - "Loaded ${ConfigLoader.configCategories.size} configuration files." - ) - } - ConfigLoader.configCategories.forEach { category -> - MenuItem("Load ${category.name}") { - category.tryLoadFromFile() - GuiConfig.info("Loaded ${category.name}") - } - } - } - MenuDivider() - MenuItem("Client Settings...") { ClickGuiState.dialog = ClickGuiDialog.Settings(ClientConfig) } - 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() - 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 } - MenuDivider() - MenuItem("Developer Mode", checked = ClickGuiState.developerMode) { - ClickGuiState.developerMode = !ClickGuiState.developerMode - } - MenuDivider() - val keybind by observe { GuiConfig.keybind } - val closeKeys = - if (keybind == Bind.EMPTY) "Esc" - else "Esc/${keybind.name}" - MenuItem("Close GUI", hint = closeKeys) { LambdaGui.back() } - MenuItem("Exit Client") { mc.scheduleStop() } + 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() + MenuItem("Client Settings...") { ClickGuiState.dialog = ClickGuiDialog.Settings(ClientConfig) } + 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() + 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 } + MenuDivider() + MenuItem("Developer Mode", checked = ClickGuiState.developerMode) { + ClickGuiState.developerMode = !ClickGuiState.developerMode + } + MenuDivider() + val keybind by observe { GuiConfig.keybind } + val closeKeys = + if (keybind == Bind.EMPTY) "Esc" + else "Esc/${keybind.name}" + MenuItem("Close GUI", hint = closeKeys) { LambdaGui.back() } + MenuItem("Exit Client") { mc.scheduleStop() } } @Composable private fun ModulesMenu() { - Submenu("Shown Categories") { - CLICK_GUI_CATEGORIES.forEach { tag -> - val shown by observe { ModuleTag.isTagShown(tag) } - MenuItem(tag.name, checked = shown) { ModuleTag.toggleTag(tag) } - } - } - MenuDivider() - CLICK_GUI_CATEGORIES.forEach { tag -> - Submenu(tag.name) { - ModuleRegistry.modules.filter { it.tag == tag }.forEach { module -> - val shown by observe { module.showInClickGui.value } - MenuItem(module.name, checked = shown) { - module.showInClickGui.value = !shown - } - } - } - } + Submenu("Shown Categories") { + CLICK_GUI_CATEGORIES.forEach { tag -> + val shown by observe { ModuleTag.isTagShown(tag) } + MenuItem(tag.name, checked = shown) { ModuleTag.toggleTag(tag) } + } + } + MenuDivider() + CLICK_GUI_CATEGORIES.forEach { tag -> + Submenu(tag.name) { + ModuleRegistry.modules.filter { it.tag == tag }.forEach { module -> + val shown by observe { module.showInClickGui.value } + MenuItem(module.name, checked = shown) { + module.showInClickGui.value = !shown + } + } + } + } } @Composable private fun AutomationMenu() { - val configs by - observe { - UserAutomationCategory.configs.filterIsInstance() - } - MenuItem("New Config...") { - ClickGuiState.dialog = ClickGuiDialog.NewAutomationConfig - } - MenuDivider() - configs.forEach { config -> - MenuItem("${config.name}...") { - ClickGuiState.dialog = ClickGuiDialog.Settings(config) - } - } - MenuItem("${AutomationConfig.DEFAULT.name}...") { - ClickGuiState.dialog = ClickGuiDialog.Settings(AutomationConfig.DEFAULT) - } + 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 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)}" - ) - } - } + 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") } + 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) } + 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 index 5dd745eb8..17250b853 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Search.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt @@ -23,6 +23,7 @@ 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.GuiScreen import com.lambda.gui.Reveal import com.lambda.gui.clickgui.ClickGuiState import com.lambda.module.HudModule @@ -33,116 +34,120 @@ import com.lambda.util.StringUtils.levenshteinDistance import net.minecraft.client.gui.screen.ChatScreen internal object Search { - sealed interface Result { - val name: String - - val origin: String - - fun choose() - - class OfModule(val module: Module) : Result { - override val name get() = module.name - override val origin = - if (module is HudModule) "HUD element" - else "${module.tag.name} module" - override fun choose() = Reveal.show(module) - } - - class OfSetting( - val setting: Setting<*>, - val config: Config, - path: List - ) : Result { - override val name get() = setting.name - override val origin = (listOf(config.name) + path).joinToString(" \u00bb ") - override fun choose() = Reveal.show(config, setting) - } - - class OfCommand(val command: LambdaCommand) : Result { - override val name = "${CommandRegistry.prefix}${command.name}" - override val origin = "Command" - override fun choose() = mc.setScreen(ChatScreen("${CommandRegistry.prefix}${command.name} ", true)) - } - } - - private const val MAX_RESULTS = 30 - - private const val MODULE_BONUS = 300 - private const val HUD_MODULE_BONUS = 270 - private const val COMMAND_BONUS = 200 - - fun find(query: String): List { - if (query.isEmpty()) return emptyList() - val needle = query.lowercase() - return rank(needle, lenient = false).ifEmpty { rank(needle, lenient = true) } - .sortedByDescending { it.second } - .take(MAX_RESULTS) - .map { it.first } - } - - private fun rank(query: String, lenient: Boolean): List> = - buildList { - fun consider(result: () -> Result, bonus: Int, vararg names: String) { - val score = names.maxOf { score(query, it.lowercase(), lenient) } - if (score > 0) add(result() to score + bonus) - } - - fun hidden(config: Any) = - config is Module && - config.tag == ModuleTag.DEBUG && - !ClickGuiState.developerMode - - ModuleRegistry.modules.forEach { module -> - if (hidden(module)) return@forEach - consider( - { Result.OfModule(module) }, - if (module is HudModule) HUD_MODULE_BONUS else MODULE_BONUS, - module.name, - module.tag.name - ) - } - CommandRegistry.commands.forEach { command -> - consider( - { Result.OfCommand(command) }, - COMMAND_BONUS, - command.name, - *command.aliases.toTypedArray() - ) - } - ConfigLoader.configCategories.forEach { category -> - category.configs.forEach { config -> - if (hidden(config)) return@forEach - config.settingLayers.forEachEntry { path, single -> - val setting = single.entry - if (setting.visibility()) { - consider( - { - Result.OfSetting( - setting, - config, - path.map { it.name } - ) - }, - 0, - setting.name - ) - } - } - } - } - } - - private fun score(query: String, target: String, lenient: Boolean): Int { - if (target.isEmpty()) return 0 - if (target == query) return 200 - if (target.startsWith(query)) return 100 + query.length * 50 / target.length - if (target.contains(query)) return 50 + query.length * 40 / target.length - - val distance = query.levenshteinDistance(target) - val allowed = - if (lenient) (query.length / 2).coerceIn(2, 6) - else (query.length / 3).coerceIn(1, 4) - return if (distance <= allowed) (50 - distance * 10).coerceAtLeast(1) - else 0 - } + sealed interface Result { + val name: String + + val origin: String + + fun choose() + + class OfModule(val module: Module) : Result { + override val name get() = module.name + override val origin = + if (module is HudModule) "HUD element" + else "${module.tag.name} module" + override fun choose() = Reveal.show(module) + } + + class OfSetting( + val setting: Setting<*>, + val config: Config, + path: List + ) : Result { + override val name get() = setting.name + override val origin = (listOf(config.name) + path).joinToString(" \u00bb ") + override fun choose() = Reveal.show(config, setting) + } + + class OfCommand(val command: LambdaCommand) : Result { + override val name = "${CommandRegistry.prefix}${command.name}" + override val origin = "Command" + override fun choose() = mc.setScreen(ChatScreen("${CommandRegistry.prefix}${command.name} ", true)) + } + } + + private const val MAX_RESULTS = 30 + + private const val MODULE_BONUS = 300 + private const val HUD_MODULE_BONUS = 270 + private const val COMMAND_BONUS = 200 + + private val chatReachable get() = mc.world != null && !GuiScreen.isOverScreen + + fun find(query: String): List { + if (query.isEmpty()) return emptyList() + val needle = query.lowercase() + return rank(needle, lenient = false).ifEmpty { rank(needle, lenient = true) } + .sortedByDescending { it.second } + .take(MAX_RESULTS) + .map { it.first } + } + + private fun rank(query: String, lenient: Boolean): List> = + buildList { + fun consider(result: () -> Result, bonus: Int, vararg names: String) { + val score = names.maxOf { score(query, it.lowercase(), lenient) } + if (score > 0) add(result() to score + bonus) + } + + fun hidden(config: Any) = + config is Module && + config.tag == ModuleTag.DEBUG && + !ClickGuiState.developerMode + + ModuleRegistry.modules.forEach { module -> + if (hidden(module)) return@forEach + consider( + { Result.OfModule(module) }, + if (module is HudModule) HUD_MODULE_BONUS else MODULE_BONUS, + module.name, + module.tag.name + ) + } + if (chatReachable) { + CommandRegistry.commands.forEach { command -> + consider( + { Result.OfCommand(command) }, + COMMAND_BONUS, + command.name, + *command.aliases.toTypedArray() + ) + } + } + ConfigLoader.configCategories.forEach { category -> + category.configs.forEach { config -> + if (hidden(config)) return@forEach + config.settingLayers.forEachEntry { path, single -> + val setting = single.entry + if (setting.visibility()) { + consider( + { + Result.OfSetting( + setting, + config, + path.map { it.name } + ) + }, + 0, + setting.name + ) + } + } + } + } + } + + private fun score(query: String, target: String, lenient: Boolean): Int { + if (target.isEmpty()) return 0 + if (target == query) return 200 + if (target.startsWith(query)) return 100 + query.length * 50 / target.length + if (target.contains(query)) return 50 + query.length * 40 / target.length + + val distance = query.levenshteinDistance(target) + val allowed = + if (lenient) (query.length / 2).coerceIn(2, 6) + else (query.length / 3).coerceIn(1, 4) + return if (distance <= allowed) (50 - distance * 10).coerceAtLeast(1) + else 0 + } } diff --git a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt index 0caddf426..73504c822 100644 --- a/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt +++ b/src/main/kotlin/com/lambda/gui/render/BlurPyramid.kt @@ -32,113 +32,113 @@ import kotlin.math.ceil import kotlin.math.log2 internal class BlurPyramid(private val name: String) { - private var levels = emptyList() - private var width = 0 - private var height = 0 + private 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 + private val spreadUniform: GpuBuffer = + RenderSystem.getDevice().createBuffer( + { "$name spread" }, + GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, + SPREAD_UNIFORM_SIZE + ) + private var spread = Float.NaN - fun blur( - source: GpuTextureView, - width: Int, - height: Int, - radius: Float - ): GpuTextureView { - resize(width, height) - val depth = - (ceil(log2(radius.coerceAtLeast(1f))).toInt() - 1).coerceIn(1, levels.size) - writeSpread((radius / (1 shl depth)).coerceIn(MIN_SPREAD, MAX_SPREAD)) + fun blur( + source: GpuTextureView, + width: Int, + height: Int, + radius: Float + ): GpuTextureView { + resize(width, height) + val depth = + (ceil(log2(radius.coerceAtLeast(1f))).toInt() - 1).coerceIn(1, levels.size) + writeSpread((radius / (1 shl depth)).coerceIn(MIN_SPREAD, MAX_SPREAD)) - var input = source - repeat(depth) { index -> - pass(LambdaRenderPipelines.GUI_BLUR_DOWN, input, levels[index].view) - input = levels[index].view - } - (depth - 2 downTo 0).forEach { index -> - pass(LambdaRenderPipelines.GUI_BLUR_UP, input, levels[index].view) - input = levels[index].view - } - return input - } + var input = source + repeat(depth) { index -> + pass(LambdaRenderPipelines.GUI_BLUR_DOWN, input, levels[index].view) + input = levels[index].view + } + (depth - 2 downTo 0).forEach { index -> + pass(LambdaRenderPipelines.GUI_BLUR_UP, input, levels[index].view) + input = levels[index].view + } + return input + } - private fun pass( - pipeline: RenderPipeline, - input: GpuTextureView, - output: GpuTextureView - ) { - RenderSystem.getDevice().createCommandEncoder() - .createRenderPass({ name }, output, OptionalInt.empty()) - .use { pass -> - pass.setPipeline(pipeline) - pass.bindTexture( - "InSampler", - input, - RenderSystem.getSamplerCache().get(FilterMode.LINEAR) - ) - pass.setUniform("BlurSpread", spreadUniform) - pass.draw(0, 3) - } - } + private fun 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 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 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) + 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() - } - } + override fun close() { + view.close() + texture.close() + } + } - private companion object { - const val MAX_DEPTH = 6 + private companion object { + const val MAX_DEPTH = 6 - const val MIN_SPREAD = 0.5f - const val MAX_SPREAD = 2f + const val MIN_SPREAD = 0.5f + const val MAX_SPREAD = 2f - const val SPREAD_UNIFORM_SIZE = 16L - } + 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 index b832e9543..6c6a9b864 100644 --- a/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt +++ b/src/main/kotlin/com/lambda/gui/render/GuiCompositor.kt @@ -30,117 +30,117 @@ import java.awt.Color import java.util.* internal object GuiCompositor { - data class Effects( - val blur: Float = 0f, - val glow: Float = 0f, - val glowIntensity: Float = 0f, - val glowColorA: Color = Color.WHITE, - val glowColorB: Color = Color.WHITE, - val dim: Float = 0f, - ) { - companion object { - val NONE = Effects() - } - } + data class Effects( + val blur: Float = 0f, + val glow: Float = 0f, + val glowIntensity: Float = 0f, + val glowColorA: Color = Color.WHITE, + val glowColorB: Color = Color.WHITE, + val dim: Float = 0f, + ) { + companion object { + val NONE = Effects() + } + } - private val backdrop by lazy { BlurPyramid("Lambda GUI backdrop") } - private val glow by lazy { BlurPyramid("Lambda GUI glow") } - private var glowView: GpuTextureView? = null - private var glowRadius = 0f + private val backdrop by lazy { BlurPyramid("Lambda GUI backdrop") } + private val glow by lazy { BlurPyramid("Lambda GUI glow") } + private var glowView: GpuTextureView? = null + private var glowRadius = 0f - private val uniformSize = - Std140SizeCalculator() - .putVec4() - .putVec4() - .putFloat() - .putFloat() - .putFloat() - .putFloat() - .align(16) - .get() - private val uniforms: GpuBuffer by lazy { - RenderSystem.getDevice().createBuffer( - { "Lambda GUI effects" }, - GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, - uniformSize.toLong() - ) - } + private val uniformSize = + Std140SizeCalculator() + .putVec4() + .putVec4() + .putFloat() + .putFloat() + .putFloat() + .putFloat() + .align(16) + .get() + private val uniforms: GpuBuffer by lazy { + RenderSystem.getDevice().createBuffer( + { "Lambda GUI effects" }, + GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_COPY_DST, + uniformSize.toLong() + ) + } - fun composite( - gui: GpuTextureView, - width: Int, - height: Int, - guiChanged: Boolean, - effects: Effects - ) { - val screen = mc.framebuffer.colorAttachmentView ?: return - val linear = RenderSystem.getSamplerCache().get(FilterMode.LINEAR) - val nearest = RenderSystem.getSamplerCache().get(FilterMode.NEAREST) + 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.blur <= 0f && effects.glow <= 0f && effects.dim <= 0f) { - glowView = null - return blit(gui) - } + if (effects.blur <= 0f && effects.glow <= 0f && effects.dim <= 0f) { + glowView = null + return blit(gui) + } - val backdropView = - if (effects.blur > 0f) backdrop.blur(screen, width, height, effects.blur) - else gui - if (effects.glow <= 0f) glowView = null - else if (guiChanged || glowView == null || glowRadius != effects.glow) { - glowView = glow.blur(gui, width, height, effects.glow) - glowRadius = effects.glow - } + val backdropView = + if (effects.blur > 0f) backdrop.blur(screen, width, height, effects.blur) + else gui + if (effects.glow <= 0f) glowView = null + else if (guiChanged || glowView == null || glowRadius != effects.glow) { + glowView = glow.blur(gui, width, height, effects.glow) + glowRadius = 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("GlowSampler", glowView ?: gui, linear) - pass.setUniform("GuiEffects", uniforms) - pass.draw(0, 3) - } - } + 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("GlowSampler", glowView ?: gui, linear) + pass.setUniform("GuiEffects", uniforms) + pass.draw(0, 3) + } + } - fun blit(layer: GpuTextureView) { - val screen = mc.framebuffer.colorAttachmentView ?: return - val nearest = RenderSystem.getSamplerCache().get(FilterMode.NEAREST) - RenderSystem.getDevice().createCommandEncoder() - .createRenderPass({ "Lambda GUI" }, screen, OptionalInt.empty()) - .use { pass -> - pass.setPipeline(LambdaRenderPipelines.GUI_BLIT) - pass.bindTexture("InSampler", layer, nearest) - pass.draw(0, 3) - } - } + fun blit(layer: GpuTextureView) { + val screen = mc.framebuffer.colorAttachmentView ?: return + val nearest = RenderSystem.getSamplerCache().get(FilterMode.NEAREST) + RenderSystem.getDevice().createCommandEncoder() + .createRenderPass({ "Lambda GUI" }, screen, OptionalInt.empty()) + .use { pass -> + pass.setPipeline(LambdaRenderPipelines.GUI_BLIT) + pass.bindTexture("InSampler", layer, nearest) + pass.draw(0, 3) + } + } - private fun writeUniforms(effects: Effects) { - MemoryStack.stackPush().use { stack -> - val data = - Std140Builder.onStack(stack, uniformSize) - .putColor(effects.glowColorA) - .putColor(effects.glowColorB) - .putFloat(if (effects.glow > 0f) effects.glowIntensity else 0f) - .putFloat(if (effects.blur > 0f) 1f else 0f) - .putFloat((System.currentTimeMillis() % GLOW_CYCLE_MILLIS) / 1000f) - .putFloat(effects.dim) - .get() - RenderSystem.getDevice().createCommandEncoder().writeToBuffer( - uniforms.slice(), - data - ) - } - } + 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.blur > 0f) 1f else 0f) + .putFloat((System.currentTimeMillis() % GLOW_CYCLE_MILLIS) / 1000f) + .putFloat(effects.dim) + .get() + RenderSystem.getDevice().createCommandEncoder().writeToBuffer( + uniforms.slice(), + data + ) + } + } - private fun Std140Builder.putColor(color: Color) = - putVec4( - color.red / 255f, - color.green / 255f, - color.blue / 255f, - color.alpha / 255f - ) + private fun Std140Builder.putColor(color: Color) = + putVec4( + color.red / 255f, + color.green / 255f, + color.blue / 255f, + color.alpha / 255f + ) - private const val GLOW_CYCLE_MILLIS = 3_141_592L + 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 index 25fa5739a..de66908b8 100644 --- a/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt +++ b/src/main/kotlin/com/lambda/gui/render/ItemAtlas.kt @@ -49,203 +49,203 @@ import org.jetbrains.skia.SurfaceOrigin import kotlin.math.ceil object ItemAtlas { - class Slot { - var stack: ItemStack = ItemStack.EMPTY - - var size = 0 - - internal var rendered: ItemStack = ItemStack.EMPTY - } - - @JvmStatic - var target: Framebuffer? = null - private set - - @JvmStatic - var scale = 1 - private set - - private val slots = ArrayList() - private var strip: Strip? = null - private var pendingImport = false - private var rearranged = false - - private val state = GuiRenderState() - private val context by lazy { DrawContext(mc, state, 0, 0) } - private val renderer by lazy { - GuiRenderer( - state, - mc.bufferBuilders.entityVertexConsumers, - mc.gameRenderer.entityRenderCommandQueue, - mc.gameRenderer.entityRenderDispatcher, - emptyList() - ) - } - - private var renderedModels = emptyList() - private var renderedAt = 0L - - private var image: Image? by mutableStateOf(null, neverEqualPolicy()) - - fun add(slot: Slot) { - slots += slot - rearranged = true - } - - fun remove(slot: Slot) { - slots -= slot - rearranged = true - } - - fun DrawScope.drawItem(slot: Slot) { - val strip = image ?: return - val index = slots.indexOf(slot) - val cell = CELL * scale - if (index < 0 || slot.rendered.isEmpty || (index + 1) * cell > strip.width) return - drawIntoCanvas { canvas -> - canvas.skiaCanvas.drawImageRect( - strip, - Rect.makeXYWH(index * cell.toFloat(), 0f, cell.toFloat(), cell.toFloat()), - Rect.makeWH(size.width * CELL / ITEM, size.height * CELL / ITEM), - SamplingMode.LINEAR, - null, - true - ) - } - } - - fun render(): Boolean { - if (slots.isEmpty()) { - if (strip == null) return false - strip?.close() - strip = null - pendingImport = true - return true - } - val scale = ceil(slots.maxOf { it.size } / ITEM.toFloat()).toInt() - if (scale <= 0) return false - - slots.forEachIndexed { index, slot -> - context.drawItem(slot.stack, index * CELL, 0) - context.drawStackOverlay(mc.textRenderer, slot.stack, index * CELL, 0) - } - val models = ArrayList() - var moving = - slots.any { - it.stack.hasGlint() || mc.player?.itemCooldownManager?.isCoolingDown(it.stack) == true - } - state.forEachItemElement { - models += it.state().modelKey - moving = moving || it.state().isAnimated - } - val changed = - rearranged || scale != this.scale || models != renderedModels || - slots.any { !ItemStack.areEqual(it.stack, it.rendered) } - val now = System.nanoTime() - if (!changed && !(moving && now - renderedAt >= ANIMATION_INTERVAL)) { - state.clear() - return false - } - renderedAt = now - - val width = slots.size * CELL * scale - val height = CELL * scale - val strip = strip?.takeIf { it.width == width && it.height == height } - ?: run { - strip?.close() - Strip(width, height).also { strip = it } - } - this.scale = scale - rearranged = false - renderedModels = models - slots.forEach { it.rendered = it.stack.copy() } - draw(strip.framebuffer) - pendingImport = true - return true - } - - fun release() { - slots.clear() - image?.close() - image = null - strip?.close() - strip = null - pendingImport = false - renderedModels = emptyList() - } - - fun import(skia: DirectContext) { - if (!pendingImport) return - pendingImport = false - val previous = image - image = strip?.snapshot(skia) - previous?.close() - } - - private fun draw(framebuffer: Framebuffer) { - RenderSystem.getDevice().createCommandEncoder() - .clearColorAndDepthTextures( - framebuffer.colorAttachment, - 0, - framebuffer.depthAttachment, - 1.0 - ) - - val projection = RenderSystem.getProjectionMatrixBuffer() - val projectionType = RenderSystem.getProjectionType() - target = framebuffer - try { - renderer.incrementFrame() - renderer.render(mc.gameRenderer.fogRenderer.getFogBuffer(FogRenderer.FogType.NONE)) - } finally { - target = null - if (projection != null) RenderSystem.setProjectionMatrix(projection, projectionType) - } - } - - private class Strip(val width: Int, val height: Int) : AutoCloseable { - val framebuffer = SimpleFramebuffer("Lambda GUI items", width, height, true) - - private val glFramebuffer = - (framebuffer.colorAttachment as GlTexture) - .getOrCreateFramebuffer((RenderSystem.getDevice() as GlBackend).bufferManager, null) - private var renderTarget: BackendRenderTarget? = null - private var surface: Surface? = null - - fun snapshot(skia: DirectContext): Image? { - val surface = surface - ?: run { - val renderTarget = - BackendRenderTarget.makeGL( - width, - height, - 0, - 0, - glFramebuffer, - FramebufferFormat.GR_GL_RGBA8 - ).also { renderTarget = it } - Surface.makeFromBackendRenderTarget( - skia, - renderTarget, - SurfaceOrigin.BOTTOM_LEFT, - SurfaceColorFormat.RGBA_8888, - ColorSpace.sRGB - ).also { surface = it } - } ?: return null - surface.notifyContentWillChange(ContentChangeMode.DISCARD) - return surface.makeImageSnapshot() - } - - override fun close() { - surface?.close() - renderTarget?.close() - framebuffer.delete() - } - } - - private const val ANIMATION_INTERVAL = 1_000_000_000L / 75 - - const val ITEM = 16 - - private const val CELL = 18 + class Slot { + var stack: ItemStack = ItemStack.EMPTY + + var size = 0 + + internal var rendered: ItemStack = ItemStack.EMPTY + } + + @JvmStatic + var target: Framebuffer? = null + private set + + @JvmStatic + var scale = 1 + private set + + private val slots = ArrayList() + private var strip: Strip? = null + private var pendingImport = false + private var rearranged = false + + private val state = GuiRenderState() + private val context by lazy { DrawContext(mc, state, 0, 0) } + private val renderer by lazy { + GuiRenderer( + state, + mc.bufferBuilders.entityVertexConsumers, + mc.gameRenderer.entityRenderCommandQueue, + mc.gameRenderer.entityRenderDispatcher, + emptyList() + ) + } + + private var renderedModels = emptyList() + private var renderedAt = 0L + + private var image: Image? by mutableStateOf(null, neverEqualPolicy()) + + fun add(slot: Slot) { + slots += slot + rearranged = true + } + + fun remove(slot: Slot) { + slots -= slot + rearranged = true + } + + fun DrawScope.drawItem(slot: Slot) { + val strip = image ?: return + val index = slots.indexOf(slot) + val cell = CELL * scale + if (index < 0 || slot.rendered.isEmpty || (index + 1) * cell > strip.width) return + drawIntoCanvas { canvas -> + canvas.skiaCanvas.drawImageRect( + strip, + Rect.makeXYWH(index * cell.toFloat(), 0f, cell.toFloat(), cell.toFloat()), + Rect.makeWH(size.width * CELL / ITEM, size.height * CELL / ITEM), + SamplingMode.LINEAR, + null, + true + ) + } + } + + fun render(): Boolean { + if (slots.isEmpty()) { + if (strip == null) return false + strip?.close() + strip = null + pendingImport = true + return true + } + val scale = ceil(slots.maxOf { it.size } / ITEM.toFloat()).toInt() + if (scale <= 0) return false + + slots.forEachIndexed { index, slot -> + context.drawItem(slot.stack, index * CELL, 0) + context.drawStackOverlay(mc.textRenderer, slot.stack, index * CELL, 0) + } + val models = ArrayList() + var moving = + slots.any { + it.stack.hasGlint() || mc.player?.itemCooldownManager?.isCoolingDown(it.stack) == true + } + state.forEachItemElement { + models += it.state().modelKey + moving = moving || it.state().isAnimated + } + val changed = + rearranged || scale != this.scale || models != renderedModels || + slots.any { !ItemStack.areEqual(it.stack, it.rendered) } + val now = System.nanoTime() + if (!changed && !(moving && now - renderedAt >= ANIMATION_INTERVAL)) { + state.clear() + return false + } + renderedAt = now + + val width = slots.size * CELL * scale + val height = CELL * scale + val strip = strip?.takeIf { it.width == width && it.height == height } + ?: run { + strip?.close() + Strip(width, height).also { strip = it } + } + this.scale = scale + rearranged = false + renderedModels = models + slots.forEach { it.rendered = it.stack.copy() } + draw(strip.framebuffer) + pendingImport = true + return true + } + + fun release() { + slots.clear() + image?.close() + image = null + strip?.close() + strip = null + pendingImport = false + renderedModels = emptyList() + } + + fun import(skia: DirectContext) { + if (!pendingImport) return + pendingImport = false + val previous = image + image = strip?.snapshot(skia) + previous?.close() + } + + private fun draw(framebuffer: Framebuffer) { + RenderSystem.getDevice().createCommandEncoder() + .clearColorAndDepthTextures( + framebuffer.colorAttachment, + 0, + framebuffer.depthAttachment, + 1.0 + ) + + val projection = RenderSystem.getProjectionMatrixBuffer() + val projectionType = RenderSystem.getProjectionType() + target = framebuffer + try { + renderer.incrementFrame() + renderer.render(mc.gameRenderer.fogRenderer.getFogBuffer(FogRenderer.FogType.NONE)) + } finally { + target = null + if (projection != null) RenderSystem.setProjectionMatrix(projection, projectionType) + } + } + + private class Strip(val width: Int, val height: Int) : AutoCloseable { + val framebuffer = SimpleFramebuffer("Lambda GUI items", width, height, true) + + private val glFramebuffer = + (framebuffer.colorAttachment as GlTexture) + .getOrCreateFramebuffer((RenderSystem.getDevice() as GlBackend).bufferManager, null) + private var renderTarget: BackendRenderTarget? = null + private var surface: Surface? = null + + fun snapshot(skia: DirectContext): Image? { + val surface = surface + ?: run { + val renderTarget = + BackendRenderTarget.makeGL( + width, + height, + 0, + 0, + glFramebuffer, + FramebufferFormat.GR_GL_RGBA8 + ).also { renderTarget = it } + Surface.makeFromBackendRenderTarget( + skia, + renderTarget, + SurfaceOrigin.BOTTOM_LEFT, + SurfaceColorFormat.RGBA_8888, + ColorSpace.sRGB + ).also { surface = it } + } ?: return null + surface.notifyContentWillChange(ContentChangeMode.DISCARD) + return surface.makeImageSnapshot() + } + + override fun close() { + surface?.close() + renderTarget?.close() + framebuffer.delete() + } + } + + private const val ANIMATION_INTERVAL = 1_000_000_000L / 75 + + const val ITEM = 16 + + private const val CELL = 18 } diff --git a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt index 11033f75a..a3b83f2da 100644 --- a/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt +++ b/src/main/kotlin/com/lambda/gui/settings/CollectionEditor.kt @@ -70,178 +70,178 @@ private const val WARM_UP_ENTRIES = 64 @Composable internal fun CollectionButton(setting: CollectionSetting) { - val count by observe { setting.value.size } - var editing by remember { mutableStateOf(false) } + val count by observe { setting.value.size } + var editing by remember { mutableStateOf(false) } - Labeled(setting.name) { - Chip(onClick = { editing = true }) { - Text("$count selected", Modifier.weight(1f, fill = false), maxLines = 1) - Ellipsis() - } - } - if (editing) CollectionWindow(setting) { editing = false } + Labeled(setting.name) { + Chip(onClick = { editing = true }) { + Text("$count selected", Modifier.weight(1f, fill = false), maxLines = 1) + Ellipsis() + } + } + if (editing) CollectionWindow(setting) { editing = false } } @Composable private fun CollectionWindow( - setting: CollectionSetting, - onDismiss: () -> Unit + setting: CollectionSetting, + onDismiss: () -> Unit ) { - val selected by observe { setting.value.toSet() } - val entries = - remember(setting.immutableCollection) { - setting.immutableCollection.map { - Entry(it, setting.label(it), setting.icon(it)) - } - } - var query by remember { mutableStateOf("") } - val matching = - remember(entries, query) { - entries.filter { it.label.contains(query.trim(), ignoreCase = true) } - } - val (chosen, available) = - remember(matching, selected) { matching.partition { it.item in selected } } + 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 = Centered.VERTICALLY, - horizontalArrangement = Arrangement.spacedBy(3.dp) - ) { - TextInput( - query, - { query = it }, - Modifier.weight(1f), - placeholder = "Search ${setting.name}", - focused = true - ) - Button("Invert", Modifier.height(Look.rowHeight)) { - setting.invertSelection() - } - } - Row( - Modifier.height(220.dp), - horizontalArrangement = Arrangement.spacedBy(3.dp) - ) { - Pane("Available (${available.size})", available, Modifier.weight(1f)) { - setting.select(it) - } - Pane("Selected (${chosen.size})", chosen, Modifier.weight(1f)) { - setting.deselect(it) - } - } - } - } + Dialog(onDismiss) { + Column(Modifier.width(360.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text(setting.name) + Row( + verticalAlignment = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + TextInput( + query, + { query = it }, + Modifier.weight(1f), + placeholder = "Search ${setting.name}", + focused = true + ) + Button("Invert", Modifier.height(Look.rowHeight)) { + setting.invertSelection() + } + } + Row( + Modifier.height(220.dp), + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + Pane("Available (${available.size})", available, Modifier.weight(1f)) { + setting.select(it) + } + Pane("Selected (${chosen.size})", chosen, Modifier.weight(1f)) { + setting.deselect(it) + } + } + } + } } @Composable internal fun BlockPicker(setting: BlockSetting) { - val block by observe { setting.value } - var picking by remember { mutableStateOf(false) } + val block by observe { setting.value } + var picking by remember { mutableStateOf(false) } - Labeled(setting.name) { - Chip(onClick = { picking = true }) { - Box(Modifier.size(ICON_SIZE)) { - ItemIcon(ItemStack(block.asItem()), ICON_SIZE) - } - Text( - BlockSerializer.stringify(block), - Modifier.weight(1f, fill = false), - maxLines = 1 - ) - Ellipsis() - } - } - if (!picking) return + Labeled(setting.name) { + Chip(onClick = { picking = true }) { + Box(Modifier.size(ICON_SIZE)) { + ItemIcon(ItemStack(block.asItem()), ICON_SIZE) + } + Text( + BlockSerializer.stringify(block), + Modifier.weight(1f, fill = false), + maxLines = 1 + ) + Ellipsis() + } + } + if (!picking) return - val entries = - remember { - Registries.BLOCK.map { - Entry(it, BlockSerializer.stringify(it), ItemStack(it.asItem())) - } - } - var query by remember { mutableStateOf("") } - val matching = - remember(query) { - entries.filter { it.label.contains(query.trim(), ignoreCase = true) } - } - Dialog(onDismiss = { picking = false }) { dismiss -> - 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 - dismiss() - } - } - } + 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 }) { dismiss -> + 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 + dismiss() + } + } + } } @Composable internal fun PickerWarmUp() { - val entries = - remember { - Registries.BLOCK.take(WARM_UP_ENTRIES).map { - Entry(it, BlockSerializer.stringify(it), ItemStack(it.asItem())) - } - } - Column(Modifier.width(200.dp)) { - TextInput("", {}, Modifier.fillMaxWidth()) - Pane("", entries, Modifier.height(220.dp)) {} - } + val entries = + remember { + Registries.BLOCK.take(WARM_UP_ENTRIES).map { + Entry(it, BlockSerializer.stringify(it), ItemStack(it.asItem())) + } + } + Column(Modifier.width(200.dp)) { + TextInput("", {}, Modifier.fillMaxWidth()) + Pane("", entries, Modifier.height(220.dp)) {} + } } 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 + title: String, + entries: List>, + modifier: Modifier, + onClick: (R) -> Unit ) { - val colors = LambdaTheme.colors - Column(modifier.fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text(title, color = colors.onSurfaceVariant, style = Type.label) - val list = rememberLazyListState() - Box( - Modifier - .fillMaxSize() - .clip(RoundedCornerShape(Look.controlRounding)) - .background(colors.input) - ) { - LazyColumn( - state = list, - modifier = Modifier.fillMaxSize().wheelScrollable(list) - ) { - items(entries) { entry -> - Row( - verticalAlignment = Centered.VERTICALLY, - horizontalArrangement = Arrangement.spacedBy(3.dp), - modifier = Modifier - .fillMaxWidth() - .heightIn(min = Look.rowHeight) - .hoverHighlight(colors.controlSelected) - .mouseClickable { onClick(entry.item) } - .padding(horizontal = 4.dp) - ) { - if (entry.icon != null) Box(Modifier.size(ICON_SIZE)) { - ItemIcon(entry.icon, ICON_SIZE) - } - Text(entry.label, color = colors.onControl, maxLines = 1) - } - } - } - if (list.canScrollForward || list.canScrollBackward) { - Scrollbar(rememberScrollbarAdapter(list), Modifier.matchParentSize()) - } - } - } + val colors = LambdaTheme.colors + Column(modifier.fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(title, color = colors.onSurfaceVariant, style = Type.label) + val list = rememberLazyListState() + Box( + Modifier + .fillMaxSize() + .clip(RoundedCornerShape(Look.controlRounding)) + .background(colors.input) + ) { + LazyColumn( + state = list, + modifier = Modifier.fillMaxSize().wheelScrollable(list) + ) { + items(entries) { entry -> + Row( + verticalAlignment = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight) + .hoverHighlight(colors.controlSelected) + .mouseClickable { onClick(entry.item) } + .padding(horizontal = 4.dp) + ) { + if (entry.icon != null) Box(Modifier.size(ICON_SIZE)) { + ItemIcon(entry.icon, ICON_SIZE) + } + Text(entry.label, color = colors.onControl, maxLines = 1) + } + } + } + if (list.canScrollForward || list.canScrollBackward) { + Scrollbar(rememberScrollbarAdapter(list), Modifier.matchParentSize()) + } + } + } } diff --git a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt index 6612c55e6..0b9248351 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt @@ -69,203 +69,203 @@ private val HUES = (0..6).map { Color.hsv(it * 60f % 360f, 1f, 1f) } @Composable internal fun ColorPicker(setting: ColorSetting) { - val color by observe { setting.value } - val picker = remember { MenuState() } + val color by observe { setting.value } + val picker = remember { MenuState() } - Labeled(setting.name, Modifier.mouseClickable(onClick = picker::toggle)) { - Box(Modifier.padding(end = 2.dp)) { - Spacer( - Modifier - .size(20.dp, 9.dp) - .clip(RoundedCornerShape(Look.boxRounding)) - .drawBehind { - drawCheckerboard() - drawRect(color.toCompose()) - } - ) - Popout(picker.isOpen, onDismiss = picker::dismiss) { - Column(Modifier.width(PICKER_WIDTH)) { - Picker(color) { setting.value = it } - } - } - } - } + Labeled(setting.name, Modifier.mouseClickable(onClick = picker::toggle)) { + Box(Modifier.padding(end = 2.dp)) { + Spacer( + Modifier + .size(20.dp, 9.dp) + .clip(RoundedCornerShape(Look.boxRounding)) + .drawBehind { + drawCheckerboard() + drawRect(color.toCompose()) + } + ) + Popout(picker.isOpen, onDismiss = picker::dismiss) { + Column(Modifier.width(PICKER_WIDTH)) { + Picker(color) { setting.value = it } + } + } + } + } } @Composable private fun Picker(color: AwtColor, onColorChange: (AwtColor) -> Unit) { - val colors = LambdaTheme.colors + val colors = LambdaTheme.colors - var hsb by - remember { - mutableStateOf(AwtColor.RGBtoHSB(color.red, color.green, color.blue, null)) - } - var adopted by remember { mutableStateOf(color) } - if (color != adopted) { - adopted = color - val shown = AwtColor.HSBtoRGB(hsb[0], hsb[1], hsb[2]) and 0xFFFFFF - if (shown != color.rgb and 0xFFFFFF) { - hsb = AwtColor.RGBtoHSB(color.red, color.green, color.blue, null) - } - } + var hsb by + remember { + mutableStateOf(AwtColor.RGBtoHSB(color.red, color.green, color.blue, null)) + } + var adopted by remember { mutableStateOf(color) } + if (color != adopted) { + adopted = color + val shown = AwtColor.HSBtoRGB(hsb[0], hsb[1], hsb[2]) and 0xFFFFFF + if (shown != color.rgb and 0xFFFFFF) { + hsb = AwtColor.RGBtoHSB(color.red, color.green, color.blue, null) + } + } - fun pick( - hue: Float = hsb[0], - saturation: Float = hsb[1], - brightness: Float = hsb[2], - alpha: Int = color.alpha - ) { - hsb = floatArrayOf(hue, saturation, brightness) - val rgb = AwtColor.HSBtoRGB(hue, saturation, brightness) - onColorChange(AwtColor(rgb and 0xFFFFFF or (alpha shl 24), true)) - } + fun pick( + hue: Float = hsb[0], + saturation: Float = hsb[1], + brightness: Float = hsb[2], + alpha: Int = color.alpha + ) { + hsb = floatArrayOf(hue, saturation, brightness) + val rgb = AwtColor.HSBtoRGB(hue, saturation, brightness) + onColorChange(AwtColor(rgb and 0xFFFFFF or (alpha shl 24), true)) + } - Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { - Spacer( - Modifier - .fillMaxWidth() - .aspectRatio(1.4f) - .clip(RoundedCornerShape(Look.boxRounding)) - .drawBehind { - drawRect(Color.hsv(hsb[0] * 360f, 1f, 1f)) - drawRect(Brush.horizontalGradient(listOf(Color.White, Color.Transparent))) - drawRect(Brush.verticalGradient(listOf(Color.Transparent, Color.Black))) - val center = Offset(hsb[1] * size.width, (1f - hsb[2]) * size.height) - drawCircle( - Color.Black, - 3.5.dp.toPx(), - center, - style = Stroke(1.dp.toPx()) - ) - drawCircle( - Color.White, - 3.dp.toPx(), - center, - style = Stroke(1.dp.toPx()) - ) - } - .scrubbable { position, size -> - pick( - saturation = (position.x / size.width).coerceIn(0f, 1f), - brightness = 1f - (position.y / size.height).coerceIn(0f, 1f) - ) - } - ) - Bar(hsb[0], onChange = { pick(hue = it) }) { - drawRect(Brush.horizontalGradient(HUES)) - } - Bar(color.alpha / 255f, onChange = { pick(alpha = (it * 255).roundToInt()) }) { - drawCheckerboard() - drawRect( - Brush.horizontalGradient( - listOf(Color.Transparent, color.toCompose().copy(alpha = 1f)) - ) - ) - } + Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { + Spacer( + Modifier + .fillMaxWidth() + .aspectRatio(1.4f) + .clip(RoundedCornerShape(Look.boxRounding)) + .drawBehind { + drawRect(Color.hsv(hsb[0] * 360f, 1f, 1f)) + drawRect(Brush.horizontalGradient(listOf(Color.White, Color.Transparent))) + drawRect(Brush.verticalGradient(listOf(Color.Transparent, Color.Black))) + val center = Offset(hsb[1] * size.width, (1f - hsb[2]) * size.height) + drawCircle( + Color.Black, + 3.5.dp.toPx(), + center, + style = Stroke(1.dp.toPx()) + ) + drawCircle( + Color.White, + 3.dp.toPx(), + center, + style = Stroke(1.dp.toPx()) + ) + } + .scrubbable { position, size -> + pick( + saturation = (position.x / size.width).coerceIn(0f, 1f), + brightness = 1f - (position.y / size.height).coerceIn(0f, 1f) + ) + } + ) + Bar(hsb[0], onChange = { pick(hue = it) }) { + drawRect(Brush.horizontalGradient(HUES)) + } + Bar(color.alpha / 255f, onChange = { pick(alpha = (it * 255).roundToInt()) }) { + drawCheckerboard() + drawRect( + Brush.horizontalGradient( + listOf(Color.Transparent, color.toCompose().copy(alpha = 1f)) + ) + ) + } - Row(horizontalArrangement = Arrangement.spacedBy(2.dp)) { - Channel("R", color.red) { - onColorChange(AwtColor(it, color.green, color.blue, color.alpha)) - } - Channel("G", color.green) { - onColorChange(AwtColor(color.red, it, color.blue, color.alpha)) - } - Channel("B", color.blue) { - onColorChange(AwtColor(color.red, color.green, it, color.alpha)) - } - Channel("A", color.alpha) { - onColorChange(AwtColor(color.red, color.green, color.blue, it)) - } - } - Row( - verticalAlignment = Centered.VERTICALLY, - 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 - ) - } - } + 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 = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text("Hex", color = colors.onSurfaceVariant, style = Type.label) + TextInput( + color.toHex(), + { text -> parseHex(text)?.let(onColorChange) }, + Modifier.weight(1f), + style = Type.label + ) + } + } } @Composable private fun Bar( - fraction: Float, - onChange: (Float) -> Unit, - background: DrawScope.() -> Unit + fraction: Float, + onChange: (Float) -> Unit, + background: DrawScope.() -> Unit ) { - Spacer( - Modifier - .fillMaxWidth() - .height(10.dp) - .clip(RoundedCornerShape(Look.boxRounding)) - .drawBehind { - background() - val thumb = Size(4.dp.toPx(), size.height) - val left = Offset(fraction * (size.width - thumb.width), 0f) - val corner = CornerRadius(1.dp.toPx()) - drawRoundRect(Color.White, left, thumb, corner) - drawRoundRect( - Color.Black, - left, - thumb, - corner, - style = Stroke(0.5.dp.toPx()) - ) - } - .scrubbable { position, size -> - onChange((position.x / size.width).coerceIn(0f, 1f)) - } - ) + Spacer( + Modifier + .fillMaxWidth() + .height(10.dp) + .clip(RoundedCornerShape(Look.boxRounding)) + .drawBehind { + background() + val thumb = Size(4.dp.toPx(), size.height) + val left = Offset(fraction * (size.width - thumb.width), 0f) + val corner = CornerRadius(1.dp.toPx()) + drawRoundRect(Color.White, left, thumb, corner) + drawRoundRect( + Color.Black, + left, + thumb, + corner, + style = Stroke(0.5.dp.toPx()) + ) + } + .scrubbable { position, size -> + onChange((position.x / size.width).coerceIn(0f, 1f)) + } + ) } @Composable private fun RowScope.Channel(label: String, value: Int, onChange: (Int) -> Unit) { - Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) { - Text(label, color = LambdaTheme.colors.onSurfaceVariant, style = Type.label) - NumberInput( - value, - { it.toIntOrNull()?.coerceIn(0, 255) }, - onChange, - Modifier.fillMaxWidth() - ) - } + Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) { + Text(label, color = LambdaTheme.colors.onSurfaceVariant, style = Type.label) + NumberInput( + value, + { it.toIntOrNull()?.coerceIn(0, 255) }, + onChange, + Modifier.fillMaxWidth() + ) + } } private fun DrawScope.drawCheckerboard() { - val cell = 4.dp.toPx() - drawRect(Color(0xFFCCCCCC)) - var row = 0 - while (row * cell < size.height) { - var column = row % 2 - while (column * cell < size.width) { - drawRect( - Color(0xFF999999), - Offset(column * cell, row * cell), - Size(cell, cell) - ) - column += 2 - } - row++ - } + 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) + if (alpha == 255) "#%02X%02X%02X".format(red, green, blue) + else "#%02X%02X%02X%02X".format(red, green, blue, alpha) private fun parseHex(text: String): AwtColor? { - val digits = text.removePrefix("#") - if ( - digits.length != 6 && digits.length != 8 || - digits.any { it.digitToIntOrNull(16) == null } - ) { - return null - } - val channels = digits.chunked(2).map { it.toIntOrNull(16) ?: return null } - return AwtColor(channels[0], channels[1], channels[2], channels.getOrElse(3) { 255 }) + val digits = text.removePrefix("#") + if ( + digits.length != 6 && digits.length != 8 || + digits.any { it.digitToIntOrNull(16) == null } + ) { + return null + } + val channels = digits.chunked(2).map { it.toIntOrNull(16) ?: return null } + return AwtColor(channels[0], channels[1], channels[2], channels.getOrElse(3) { 255 }) } diff --git a/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt index 217a10d04..b0e05a595 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ConfigSettings.kt @@ -44,43 +44,43 @@ import com.lambda.module.Module @Composable internal fun ConfigSettings( - config: Config, - maxHeight: Dp, - onDone: () -> Unit, - modifier: Modifier = Modifier + config: Config, + maxHeight: Dp, + onDone: () -> Unit, + modifier: Modifier = Modifier ) { - Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text( - "${config.name} Settings", - Modifier.fillMaxWidth().padding(horizontal = 4.dp), - style = Type.title - ) - if (config is Module) { - var page by remember(config) { mutableStateOf(PanelPage.Settings) } - Column(Modifier.heightIn(max = maxHeight)) { - ModuleSettings(config, page, { page = it }, rememberScrollState()) - } - } else { - ScrollColumn(Modifier.heightIn(max = maxHeight)) { - SoftTextShadow { - if (config is UserAutomationConfig) SettingRow(config.linkedModules) - SettingsList(config.settingLayers) - } - } - } - Row( - Modifier.fillMaxWidth().padding(horizontal = 4.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp) - ) { - if (config is UserAutomationConfig) { - Button("Delete") { - config.delete() - onDone() - } - } - Spacer(Modifier.weight(1f)) - if (config !is Module) Button("Reset") { config.resetSettings() } - Button("Done", onClick = onDone) - } - } + Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + "${config.name} Settings", + Modifier.fillMaxWidth().padding(horizontal = 4.dp), + style = Type.title + ) + if (config is Module) { + var page by remember(config) { mutableStateOf(PanelPage.Settings) } + Column(Modifier.heightIn(max = maxHeight)) { + ModuleSettings(config, page, { page = it }, rememberScrollState()) + } + } else { + ScrollColumn(Modifier.heightIn(max = maxHeight)) { + SoftTextShadow { + if (config is UserAutomationConfig) SettingRow(config.linkedModules) + SettingsList(config.settingLayers) + } + } + } + Row( + Modifier.fillMaxWidth().padding(horizontal = 4.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + if (config is UserAutomationConfig) { + Button("Delete") { + config.delete() + onDone() + } + } + Spacer(Modifier.weight(1f)) + if (config !is Module) Button("Reset") { config.resetSettings() } + Button("Done", onClick = onDone) + } + } } diff --git a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt index f78267bd4..62292b63a 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ModuleSettings.kt @@ -63,168 +63,168 @@ import com.lambda.module.modules.client.AutoUpdater import kotlinx.coroutines.launch internal enum class PanelPage(val title: String) { - Settings("Settings"), - Module("Module"), - Automation("Automation"), + Settings("Settings"), + Module("Module"), + Automation("Automation"), } @Composable internal fun ColumnScope.ModuleSettings( - module: Module, - selected: PanelPage, - onSelect: (PanelPage) -> Unit, - scroll: ScrollState? + module: Module, + selected: PanelPage, + onSelect: (PanelPage) -> Unit, + scroll: ScrollState? ) { - val pages = pagesOf(module) - val page = selected.takeIf { it in pages } ?: PanelPage.Settings - val revealed = Reveal.setting.takeIf { Reveal.module === module } - LaunchedEffect(revealed) { - if (revealed != null) onSelect(pageOf(module, revealed)) - } - val scope = rememberCoroutineScope() + val pages = pagesOf(module) + val page = selected.takeIf { it in pages } ?: PanelPage.Settings + val revealed = Reveal.setting.takeIf { Reveal.module === module } + LaunchedEffect(revealed) { + if (revealed != null) onSelect(pageOf(module, revealed)) + } + val scope = rememberCoroutineScope() - SoftTextShadow { - if (pages.size > 1) PageStrip(pages, page) { - onSelect(it) - if (scroll != null) scope.launch { scroll.scrollTo(0) } - } - val turned = - @Composable { - AnimatedContent( - targetState = page, - modifier = Modifier.fillMaxWidth(), - transitionSpec = { pageTurn(towardsEnd = targetState > initialState) } - ) { shown -> - Column(Modifier.fillMaxWidth()) { - when (shown) { - PanelPage.Settings -> SettingsPage(module) - PanelPage.Module -> ModulePage(module) - PanelPage.Automation -> AutomationPage(module) - } - } - } - } - if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } - else turned() - } + SoftTextShadow { + if (pages.size > 1) PageStrip(pages, page) { + onSelect(it) + if (scroll != null) scope.launch { scroll.scrollTo(0) } + } + val turned = + @Composable { + AnimatedContent( + targetState = page, + modifier = Modifier.fillMaxWidth(), + transitionSpec = { pageTurn(towardsEnd = targetState > initialState) } + ) { shown -> + Column(Modifier.fillMaxWidth()) { + when (shown) { + PanelPage.Settings -> SettingsPage(module) + PanelPage.Module -> ModulePage(module) + PanelPage.Automation -> AutomationPage(module) + } + } + } + } + if (scroll != null) ScrollColumn(Modifier.weight(1f, fill = false), scroll) { turned() } + else turned() + } } private fun pagesOf(module: Module): List = - when { - module == AutoUpdater -> listOf(PanelPage.Settings) - module.automationConfig === AutomationConfig.DEFAULT -> - listOf(PanelPage.Settings, PanelPage.Module) - else -> PanelPage.entries - } + when { + module == AutoUpdater -> listOf(PanelPage.Settings) + module.automationConfig === AutomationConfig.DEFAULT -> + listOf(PanelPage.Settings, PanelPage.Module) + else -> PanelPage.entries + } private fun pageOf(module: Module, setting: Setting<*>): PanelPage = - when { - module.automationConfig !== AutomationConfig.DEFAULT && - module.automationConfig.settingLayers.holds(setting) -> PanelPage.Automation - setting in moduleSettings(module) -> PanelPage.Module - else -> PanelPage.Settings - } + when { + module.automationConfig !== AutomationConfig.DEFAULT && + module.automationConfig.settingLayers.holds(setting) -> PanelPage.Automation + setting in moduleSettings(module) -> PanelPage.Module + else -> PanelPage.Settings + } private fun moduleSettings(module: Module): List> = - listOfNotNull( - module.keybindSetting.takeUnless { module.alwaysEnabled }, - module.prioritySetting, - module.disableOnReleaseSetting.takeUnless { module.alwaysEnabled }, - module.drawSetting.takeUnless { module.alwaysEnabled }, - ) + listOfNotNull( + module.keybindSetting.takeUnless { module.alwaysEnabled }, + module.prioritySetting, + module.disableOnReleaseSetting.takeUnless { module.alwaysEnabled }, + module.drawSetting.takeUnless { module.alwaysEnabled }, + ) @Composable private fun PageStrip( - pages: List, - selected: PanelPage, - onSelect: (PanelPage) -> Unit + pages: List, + selected: PanelPage, + onSelect: (PanelPage) -> Unit ) { - val colors = LambdaTheme.colors - Row(Modifier.fillMaxWidth().padding(bottom = 2.dp)) { - pages.forEach { page -> - val isSelected = page == selected - val line by animateColorAsState(if (isSelected) colors.secondary else colors.raised) - Box( - contentAlignment = Centered.BOTH, - modifier = Modifier - .weight(page.title.length + 2f) - .height(Look.rowHeight + 1.dp) - .hoverHighlight(colors.raised) - .mouseClickable { onSelect(page) } - .drawBehind { - val thickness = 1.dp.toPx() - drawRect( - line, - Offset(0f, size.height - thickness), - Size(size.width, thickness) - ) - } - .padding(horizontal = 4.dp) - ) { - Text( - page.title, - color = if (isSelected) colors.onSurface else colors.onSurfaceVariant, - maxLines = 1, - softWrap = false - ) - } - } - } + val colors = LambdaTheme.colors + Row(Modifier.fillMaxWidth().padding(bottom = 2.dp)) { + pages.forEach { page -> + val isSelected = page == selected + val line by animateColorAsState(if (isSelected) colors.secondary else colors.raised) + Box( + contentAlignment = Centered.BOTH, + modifier = Modifier + .weight(page.title.length + 2f) + .height(Look.rowHeight + 1.dp) + .hoverHighlight(colors.raised) + .mouseClickable { onSelect(page) } + .drawBehind { + val thickness = 1.dp.toPx() + drawRect( + line, + Offset(0f, size.height - thickness), + Size(size.width, thickness) + ) + } + .padding(horizontal = 4.dp) + ) { + Text( + page.title, + color = if (isSelected) colors.onSurface else colors.onSurfaceVariant, + maxLines = 1, + softWrap = false + ) + } + } + } } @Composable private fun SettingsPage(module: Module) { - val any by observe { module.settingLayers.hasVisibleSettings() } - if (any) SettingsList(module.settingLayers) - else { - Box( - Modifier.fillMaxWidth().padding(vertical = 4.dp), - contentAlignment = Centered.BOTH - ) { - Text("No settings", color = LambdaTheme.colors.onSurfaceVariant) - } - } + val any by observe { module.settingLayers.hasVisibleSettings() } + if (any) SettingsList(module.settingLayers) + else { + Box( + Modifier.fillMaxWidth().padding(vertical = 4.dp), + contentAlignment = Centered.BOTH + ) { + Text("No settings", color = LambdaTheme.colors.onSurfaceVariant) + } + } } @Composable private fun AutomationPage(module: Module) { - val linked by observe { module.backingAutomationConfig } - CompositionLocalProvider(LocalClickOnRelease provides true) { - AutomationConfigSelector(module, linked) - } - key(linked) { SettingsList(module.automationConfig.settingLayers) } + val linked by observe { module.backingAutomationConfig } + CompositionLocalProvider(LocalClickOnRelease provides true) { + AutomationConfigSelector(module, linked) + } + key(linked) { SettingsList(module.automationConfig.settingLayers) } } @Composable private fun ModulePage(module: Module) { - moduleSettings(module).forEach { SettingRow(it) } - Tooltip( - "Resets all settings for this module to their default values", - Modifier.fillMaxWidth() - ) { - CompositionLocalProvider(LocalClickOnRelease provides true) { - Button("Reset", Modifier.settingCell().height(Look.rowHeight)) { - module.resetSettings() - } - } - } + moduleSettings(module).forEach { SettingRow(it) } + Tooltip( + "Resets all settings for this module to their default values", + Modifier.fillMaxWidth() + ) { + CompositionLocalProvider(LocalClickOnRelease provides true) { + Button("Reset", Modifier.settingCell().height(Look.rowHeight)) { + module.resetSettings() + } + } + } } @Composable private fun AutomationConfigSelector(module: Module, linked: AutomationConfig) { - val options by observe { - listOf(module.defaultAutomationConfig) + - UserAutomationCategory.configs.filterIsInstance() - } - Dropdown( - label = "Linked Config", - options = options, - selected = linked, - optionLabel = { it.name }, - modifier = Modifier.settingCell().padding(start = ROW_INSET), - ) { selected -> - (module.backingAutomationConfig as? UserAutomationConfig)?.linkedModules?.value?.remove(module.name) - (selected as? UserAutomationConfig)?.linkedModules?.value?.add(module.name) - module.automationConfig = selected - } + val options by observe { + listOf(module.defaultAutomationConfig) + + UserAutomationCategory.configs.filterIsInstance() + } + Dropdown( + label = "Linked Config", + options = options, + selected = linked, + optionLabel = { it.name }, + modifier = Modifier.settingCell().padding(start = ROW_INSET), + ) { selected -> + (module.backingAutomationConfig as? UserAutomationConfig)?.linkedModules?.value?.remove(module.name) + (selected as? UserAutomationConfig)?.linkedModules?.value?.add(module.name) + module.automationConfig = selected + } } diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 31f5643da..5517b8c13 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -85,144 +85,144 @@ private val LocalAltered = compositionLocalOf { false } @OptIn(ExperimentalComposeUiApi::class) @Composable fun SettingRow(setting: Setting<*>) { - val disabled by observe { setting.disabled() } - val modified by observe { setting.isModified } - var origin by remember { mutableStateOf(Offset.Zero) } - var menu by remember { mutableStateOf(null) } - val pointer = remember(setting) { RowPointer(setting) } - DisposableEffect(pointer) { - onDispose { - pointer.hovered = false - pointer.held = false - } - } + val disabled by observe { setting.disabled() } + val modified by observe { setting.isModified } + var origin by remember { mutableStateOf(Offset.Zero) } + var menu by remember { mutableStateOf(null) } + val pointer = remember(setting) { RowPointer(setting) } + DisposableEffect(pointer) { + onDispose { + pointer.hovered = false + pointer.held = false + } + } - 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() - } - } + 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) - .onGloballyPositioned { origin = it.positionInWindow() } - .pointerInput(pointer) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent(PointerEventPass.Initial) - val change = event.changes.first() - val inside = change.position.x in 0f..size.width.toFloat() && change.position.y in 0f..size.height.toFloat() - if (event.type == PointerEventType.Press && event.button == PointerButton.Secondary && modified) { - change.consume() - menu = (origin + change.position).round() - continue - } - when (event.type) { - PointerEventType.Enter -> pointer.hovered = true - PointerEventType.Exit -> pointer.hovered = false - } - val wasHeld = pointer.held - pointer.held = event.changes.any { it.pressed } - if (wasHeld && !pointer.held && inside) setting.clickListeners.forEach { it() } - } - } - } - .drawWithContent { - drawContent() - drawRect(lit) - } - .enabled(!disabled) - ) { - CompositionLocalProvider( - LocalClickOnRelease provides true, - LocalKeyboardReachable provides !disabled, - LocalAltered provides modified - ) { - key(setting) { setting.Gui() } - } - } - } + Tooltip(setting.description, Modifier.fillMaxWidth()) { + Box( + Modifier + .settingCell() + .bringIntoViewRequester(intoView) + .onGloballyPositioned { origin = it.positionInWindow() } + .pointerInput(pointer) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + val change = event.changes.first() + val inside = change.position.x in 0f..size.width.toFloat() && change.position.y in 0f..size.height.toFloat() + if (event.type == PointerEventType.Press && event.button == PointerButton.Secondary && modified) { + change.consume() + menu = (origin + change.position).round() + continue + } + when (event.type) { + PointerEventType.Enter -> pointer.hovered = true + PointerEventType.Exit -> pointer.hovered = false + } + val wasHeld = pointer.held + pointer.held = event.changes.any { it.pressed } + if (wasHeld && !pointer.held && inside) setting.clickListeners.forEach { it() } + } + } + } + .drawWithContent { + drawContent() + drawRect(lit) + } + .enabled(!disabled) + ) { + CompositionLocalProvider( + LocalClickOnRelease provides true, + LocalKeyboardReachable provides !disabled, + LocalAltered provides modified + ) { + key(setting) { setting.Gui() } + } + } + } - rememberLast(menu)?.let { position -> - key(position) { - ContextMenu(menu != null, position, onDismiss = { menu = null }) { - MenuItem("Reset") { setting.reset(silent = true) } - } - } - } + rememberLast(menu)?.let { position -> + key(position) { + ContextMenu(menu != null, position, onDismiss = { menu = null }) { + MenuItem("Reset") { setting.reset(silent = true) } + } + } + } } private class RowPointer(private val setting: Setting<*>) { - var hovered = false - set(value) { - if (field == value) return - field = value - setting.hoverListeners.forEach { it(value) } - } + var hovered = false + set(value) { + if (field == value) return + field = value + setting.hoverListeners.forEach { it(value) } + } - var held = false - set(value) { - if (field == value) return - field = value - setting.holdListeners.forEach { it(value) } - } + var held = false + set(value) { + if (field == value) return + field = value + setting.holdListeners.forEach { it(value) } + } } internal fun Modifier.settingCell(): Modifier = - composed { - fillMaxWidth() - .padding(vertical = Look.settingSpacing / 2) - .clip(RoundedCornerShape(Look.controlRounding)) - .hoverHighlight(LambdaTheme.colors.hover) - } + composed { + fillMaxWidth() + .padding(vertical = Look.settingSpacing / 2) + .clip(RoundedCornerShape(Look.controlRounding)) + .hoverHighlight(LambdaTheme.colors.hover) + } private fun Modifier.enabled(enabled: Boolean): Modifier = - if (enabled) this - else alpha(0.5f).pointerInput(Unit) { - awaitPointerEventScope { - while (true) awaitPointerEvent(PointerEventPass.Initial).changes.forEach { - it.consume() - } - } - } + if (enabled) this + else alpha(0.5f).pointerInput(Unit) { + awaitPointerEventScope { + while (true) awaitPointerEvent(PointerEventPass.Initial).changes.forEach { + it.consume() + } + } + } @Composable internal fun Labeled( - name: String, - modifier: Modifier = Modifier, - editor: @Composable RowScope.() -> Unit + name: String, + modifier: Modifier = Modifier, + editor: @Composable RowScope.() -> Unit ) = LabeledRow(name, modifier.padding(start = ROW_INSET), { AlteredDot() }, editor) @Composable internal fun AlteredDot(shadowed: Boolean = false) { - if (!LocalAltered.current) return - val colors = LambdaTheme.colors - Box( - Modifier.size(ALTERED_DOT).drawBehind { - val reach = ALTERED_SHADE.toPx() - if (shadowed) { - drawCircle( - Brush.radialGradient( - listOf(Color.Black.copy(alpha = ALTERED_SHADE_ALPHA), Color.Transparent), - center, - reach - ), - reach - ) - } - drawCircle(colors.secondary) - } - ) + if (!LocalAltered.current) return + val colors = LambdaTheme.colors + Box( + Modifier.size(ALTERED_DOT).drawBehind { + val reach = ALTERED_SHADE.toPx() + if (shadowed) { + drawCircle( + Brush.radialGradient( + listOf(Color.Black.copy(alpha = ALTERED_SHADE_ALPHA), Color.Transparent), + center, + reach + ), + reach + ) + } + drawCircle(colors.secondary) + } + ) } diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt index 6d9dd5e74..f86e30668 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingsList.kt @@ -73,115 +73,115 @@ import com.lambda.gui.theme.Type @Composable fun SettingsList(layer: EntryLayer>) { - when (layer) { - is EntryLayer.Single -> { - val setting = layer.entry - val visible by observe { setting.visibility() } - Expandable(visible) { SettingRow(setting) } - } + 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 + is EntryLayer.Multiple -> { + val hasVisibleSettings by observe { layer.hasVisibleSettings() } + if (!hasVisibleSettings) return - val tabs = layer.layers.filterIsInstance>>() - when { - layer.multipleType == MultipleLayerType.Group -> - Section( - layer.name, - revealed = Reveal.setting?.let(layer::holds) == true - ) { - Children(layer) - } - else -> - Column(Modifier.fillMaxWidth()) { - layer.layers.filter { it !is EntryLayer.Tab }.forEach { SettingsList(it) } - if (tabs.isNotEmpty()) Tabs(tabs) - } - } - } - } + val tabs = layer.layers.filterIsInstance>>() + when { + layer.multipleType == MultipleLayerType.Group -> + Section( + layer.name, + revealed = Reveal.setting?.let(layer::holds) == true + ) { + Children(layer) + } + else -> + Column(Modifier.fillMaxWidth()) { + layer.layers.filter { it !is EntryLayer.Tab }.forEach { SettingsList(it) } + if (tabs.isNotEmpty()) Tabs(tabs) + } + } + } + } } @Composable private fun Children(layer: EntryLayer.Multiple>) = - layer.layers.forEach { SettingsList(it) } + layer.layers.forEach { SettingsList(it) } @Composable private fun Tabs(tabs: List>>) { - val shown by observe { tabs.filter { it.hasVisibleSettings() } } - if (shown.isEmpty()) return - var selectedName by remember { mutableStateOf(shown.first().name) } - val selected = shown.firstOrNull { it.name == selectedName } ?: shown.first() - val revealed = Reveal.setting - LaunchedEffect(revealed) { - if (revealed != null) { - shown.firstOrNull { it.holds(revealed) }?.let { selectedName = it.name } - } - } + val shown by observe { tabs.filter { it.hasVisibleSettings() } } + if (shown.isEmpty()) return + var selectedName by remember { mutableStateOf(shown.first().name) } + val selected = shown.firstOrNull { it.name == selectedName } ?: shown.first() + val revealed = Reveal.setting + LaunchedEffect(revealed) { + if (revealed != null) { + shown.firstOrNull { it.holds(revealed) }?.let { selectedName = it.name } + } + } - Column(Modifier.fillMaxWidth().padding(top = 1.dp)) { - TabPicker(shown.map { it.name }, selected.name) { selectedName = it } - AnimatedContent( - targetState = selected, - modifier = Modifier.fillMaxWidth(), - transitionSpec = { pageTurn(towardsEnd = shown.indexOf(targetState) > shown.indexOf(initialState)) }, - ) { tab -> - Column(Modifier.fillMaxWidth().padding(vertical = 1.dp)) { Children(tab) } - } - } + Column(Modifier.fillMaxWidth().padding(top = 1.dp)) { + TabPicker(shown.map { it.name }, selected.name) { selectedName = it } + AnimatedContent( + targetState = selected, + modifier = Modifier.fillMaxWidth(), + transitionSpec = { pageTurn(towardsEnd = shown.indexOf(targetState) > shown.indexOf(initialState)) }, + ) { tab -> + Column(Modifier.fillMaxWidth().padding(vertical = 1.dp)) { Children(tab) } + } + } } @Composable private fun TabPicker(names: List, selected: String, onSelect: (String) -> Unit) { - val colors = LambdaTheme.colors - val menu = remember { MenuState() } - var band by remember { mutableStateOf(IntSize.Zero) } - val choice = names.size > 1 + val colors = LambdaTheme.colors + val menu = remember { MenuState() } + var band by remember { mutableStateOf(IntSize.Zero) } + val choice = names.size > 1 - Box(Modifier.fillMaxWidth().onSizeChanged { band = it }) { - ContentColor(colors.onHeader) { - Row( - verticalAlignment = Centered.VERTICALLY, - horizontalArrangement = Arrangement.spacedBy(4.dp), - modifier = Modifier - .fillMaxWidth() - .heightIn(min = Look.rowHeight + 2.dp) - .clip(RoundedCornerShape(topStart = Look.windowRounding, topEnd = Look.windowRounding)) - .background(colors.header) - .then( - if (!choice) Modifier - else { - Modifier - .hoverHighlight(colors.onHeader.copy(alpha = 0.12f)) - .mouseClickable(onClick = menu::toggle) - } - ) - .padding(horizontal = 6.dp) - ) { - Text(selected, Modifier.weight(1f), style = Type.title, maxLines = 1) - if (choice) Chevron(90f) - } - } - Menu( - menu.isOpen, - onDismiss = menu::dismiss, - unfoldFrom = IntSize(band.width, 0), - attached = true - ) { - names.forEach { name -> - MenuItem(name, selected = name == selected) { - if (name != selected) onSelect(name) - } - } - } - } + Box(Modifier.fillMaxWidth().onSizeChanged { band = it }) { + ContentColor(colors.onHeader) { + Row( + verticalAlignment = Centered.VERTICALLY, + horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier + .fillMaxWidth() + .heightIn(min = Look.rowHeight + 2.dp) + .clip(RoundedCornerShape(topStart = Look.windowRounding, topEnd = Look.windowRounding)) + .background(colors.header) + .then( + if (!choice) Modifier + else { + Modifier + .hoverHighlight(colors.onHeader.copy(alpha = 0.12f)) + .mouseClickable(onClick = menu::toggle) + } + ) + .padding(horizontal = 6.dp) + ) { + Text(selected, Modifier.weight(1f), style = Type.title, maxLines = 1) + if (choice) Chevron(90f) + } + } + Menu( + menu.isOpen, + onDismiss = menu::dismiss, + unfoldFrom = IntSize(band.width, 0), + attached = true + ) { + names.forEach { name -> + MenuItem(name, selected = name == selected) { + if (name != selected) onSelect(name) + } + } + } + } } internal fun AnimatedContentTransitionScope<*>.pageTurn(towardsEnd: Boolean): ContentTransform { - val millis = Motion.pageMillis - val slide = tween(millis) - return (fadeIn(tween(millis)) + slideInHorizontally(slide) { if (towardsEnd) it / 5 else -it / 5 }) - .togetherWith(fadeOut(tween(millis / 2)) + slideOutHorizontally(slide) { if (towardsEnd) -it / 5 else it / 5 }) - .using(SizeTransform(clip = true) { _, _ -> tween(millis) }) + val millis = Motion.pageMillis + val slide = tween(millis) + return (fadeIn(tween(millis)) + slideInHorizontally(slide) { if (towardsEnd) it / 5 else -it / 5 }) + .togetherWith(fadeOut(tween(millis / 2)) + slideOutHorizontally(slide) { if (towardsEnd) -it / 5 else it / 5 }) + .using(SizeTransform(clip = true) { _, _ -> tween(millis) }) } diff --git a/src/main/kotlin/com/lambda/gui/theme/Theme.kt b/src/main/kotlin/com/lambda/gui/theme/Theme.kt index e445bbd1d..324f521be 100644 --- a/src/main/kotlin/com/lambda/gui/theme/Theme.kt +++ b/src/main/kotlin/com/lambda/gui/theme/Theme.kt @@ -61,238 +61,238 @@ private const val LINE_HEIGHT = 10.95f private val ON_LIGHT_ACCENT = Color(0xFF1B1024) private val LocalPalette = - staticCompositionLocalOf { error("No LambdaTheme in this composition") } + staticCompositionLocalOf { error("No LambdaTheme in this composition") } private val LocalTypography = - staticCompositionLocalOf { error("No LambdaTheme in this composition") } + staticCompositionLocalOf { error("No LambdaTheme in this composition") } val LocalContentColor = compositionLocalOf { Color.White } @Immutable data class Palette( - val primary: Color, - val secondary: Color, - val surface: Color, - val panel: Color, - val inset: Color, - val onSurface: Color, - val onSurfaceVariant: Color, - val header: Color, - val onHeader: Color, - val moduleEnabled: Color, - val onModuleEnabled: Color, - val control: Color, - val controlSelected: Color, - val onControl: Color, - val track: Color, - val input: Color, - val border: Color, - val textShadow: Color, + val primary: Color, + val secondary: Color, + val surface: Color, + val panel: Color, + val inset: Color, + val onSurface: Color, + val onSurfaceVariant: Color, + val header: Color, + val onHeader: Color, + val moduleEnabled: Color, + val onModuleEnabled: Color, + val control: Color, + val controlSelected: Color, + val onControl: Color, + val track: Color, + val input: Color, + val border: Color, + val textShadow: Color, ) { - val onPrimary = primary.contrast() - val onSecondary = secondary.contrast() - val trackFilled = - if (onControl.luminance() > 0.5f) primary - else primary.copy(alpha = 0.6f) - val raised = onSurface.copy(alpha = 0.11f) - val hover = onSurface.copy(alpha = 0.06f) + val onPrimary = primary.contrast() + val onSecondary = secondary.contrast() + val trackFilled = + if (onControl.luminance() > 0.5f) primary + else primary.copy(alpha = 0.6f) + val raised = onSurface.copy(alpha = 0.11f) + val hover = onSurface.copy(alpha = 0.06f) - private fun Color.contrast() = - if (luminance() > 0.2f) ON_LIGHT_ACCENT - else Color.White + private fun Color.contrast() = + if (luminance() > 0.2f) ON_LIGHT_ACCENT + else Color.White } internal object Look { - private val observations = Observations() + private val observations = Observations() - val windowRounding by style { GuiConfig.windowRounding.dp } - val panelRounding by style { GuiConfig.panelRounding.dp } - val menuRounding by style { GuiConfig.menuRounding.dp } - val controlRounding by style { GuiConfig.controlRounding.dp } - val boxRounding get() = controlRounding / 2 + val windowRounding by style { GuiConfig.windowRounding.dp } + val panelRounding by style { GuiConfig.panelRounding.dp } + val menuRounding by style { GuiConfig.menuRounding.dp } + val controlRounding by style { GuiConfig.controlRounding.dp } + val boxRounding get() = controlRounding / 2 - val outlines by style { GuiConfig.outlines } - val outlineWidth by style { GuiConfig.outlineWidth.dp } - val shadows by style { GuiConfig.shadows } - val emboss by style { GuiConfig.emboss } - val backdropBlur by style { if (GuiConfig.blur) (GuiConfig.blurRadius / 2f).dp else 0.dp } - val underlay by style { 1f - GuiConfig.layerFade } + val outlines by style { GuiConfig.outlines } + val outlineWidth by style { GuiConfig.outlineWidth.dp } + val shadows by style { GuiConfig.shadows } + val emboss by style { GuiConfig.emboss } + val backdropBlur by style { if (GuiConfig.blur) (GuiConfig.blurRadius / 2f).dp else 0.dp } + val underlay by style { 1f - GuiConfig.layerFade } - val rowHeight by style { GuiConfig.elementHeight.dp } - val windowWidth by style { GuiConfig.windowWidth.dp } - val settingsWidth by style { GuiConfig.settingsWidth.dp } - val notificationScale by style { GuiConfig.notificationScale } - val notificationWidth by style { GuiConfig.notificationWidth.dp } - val notificationSide by style { GuiConfig.notificationSide } - val notificationHeight by style { GuiConfig.notificationHeight } - val notificationFlow by style { GuiConfig.notificationFlow } - val windowGap by style { GuiConfig.windowGap.dp } - val windowTop by style { GuiConfig.windowTop.dp } - val modulePadding by style { GuiConfig.modulePadding.dp } - val panelPadding by style { GuiConfig.panelPadding.dp } - val settingSpacing by style { GuiConfig.settingSpacing.dp } - val groupIndent by style { GuiConfig.groupIndent.dp } + val rowHeight by style { GuiConfig.elementHeight.dp } + val windowWidth by style { GuiConfig.windowWidth.dp } + val settingsWidth by style { GuiConfig.settingsWidth.dp } + val notificationScale by style { GuiConfig.notificationScale } + val notificationWidth by style { GuiConfig.notificationWidth.dp } + val notificationSide by style { GuiConfig.notificationSide } + val notificationHeight by style { GuiConfig.notificationHeight } + val notificationFlow by style { GuiConfig.notificationFlow } + val windowGap by style { GuiConfig.windowGap.dp } + val windowTop by style { GuiConfig.windowTop.dp } + val modulePadding by style { GuiConfig.modulePadding.dp } + val panelPadding by style { GuiConfig.panelPadding.dp } + val settingSpacing by style { GuiConfig.settingSpacing.dp } + val groupIndent by style { GuiConfig.groupIndent.dp } - fun refresh() = observations.refresh() + fun refresh() = observations.refresh() - private fun style(read: () -> T): State = - Observation(read).also { observations.active += it }.state + private fun style(read: () -> T): State = + Observation(read).also { observations.active += it }.state } internal object Motion : MotionDurationScale { - private const val PAGE_MILLIS = 160 - private const val GUI_MILLIS = 180 - private const val DIALOG_MILLIS = 140 - private const val NOTIFICATION_MILLIS = 260 - private val UNFOLDING = - spring( - stiffness = Spring.StiffnessMedium, - visibilityThreshold = IntSize.VisibilityThreshold - ) + private const val PAGE_MILLIS = 160 + private const val GUI_MILLIS = 180 + private const val DIALOG_MILLIS = 140 + private const val NOTIFICATION_MILLIS = 260 + private val UNFOLDING = + spring( + stiffness = Spring.StiffnessMedium, + visibilityThreshold = IntSize.VisibilityThreshold + ) - val SCROLL = - object : MotionDurationScale { - override val scaleFactor get() = - if (GuiConfig.smoothScrolling) 1f - else 0f - } + val SCROLL = + object : MotionDurationScale { + override val scaleFactor get() = + if (GuiConfig.smoothScrolling) 1f + else 0f + } - val NOTIFICATIONS: FiniteAnimationSpec = tween(NOTIFICATION_MILLIS) + val NOTIFICATIONS: FiniteAnimationSpec = tween(NOTIFICATION_MILLIS) - val UNSCALED = - object : MotionDurationScale { - override val scaleFactor get() = 1f - } + val UNSCALED = + object : MotionDurationScale { + override val scaleFactor get() = 1f + } - override val scaleFactor get() = - if (GuiConfig.animations) 1f / GuiConfig.animationSpeed - else 0f + override val scaleFactor get() = + if (GuiConfig.animations) 1f / GuiConfig.animationSpeed + else 0f - val windows: FiniteAnimationSpec - get() = if (GuiConfig.windowAnimations) spring() else snap() - val panels: FiniteAnimationSpec - get() = if (GuiConfig.panelAnimations) UNFOLDING else snap() - val pageMillis - get() = if (GuiConfig.pageAnimations) PAGE_MILLIS else 0 - val dialogs: FiniteAnimationSpec - get() = if (GuiConfig.dialogAnimations) tween(DIALOG_MILLIS) else snap() - fun gui(distance: Float): FiniteAnimationSpec = - tween((GUI_MILLIS * distance).roundToInt()) - val guiFold: FiniteAnimationSpec - get() = tween(GUI_MILLIS) + val windows: FiniteAnimationSpec + get() = if (GuiConfig.windowAnimations) spring() else snap() + val panels: FiniteAnimationSpec + get() = if (GuiConfig.panelAnimations) UNFOLDING else snap() + val pageMillis + get() = if (GuiConfig.pageAnimations) PAGE_MILLIS else 0 + val dialogs: FiniteAnimationSpec + get() = if (GuiConfig.dialogAnimations) tween(DIALOG_MILLIS) else snap() + fun gui(distance: Float): FiniteAnimationSpec = + tween((GUI_MILLIS * distance).roundToInt()) + val guiFold: FiniteAnimationSpec + get() = tween(GUI_MILLIS) } enum class GuiTransition(override val displayName: String) : NamedEnum { - Unfold("Unfold"), - Fade("Fade"), - Slide("Slide"), - Zoom("Zoom"), + Unfold("Unfold"), + Fade("Fade"), + Slide("Slide"), + Zoom("Zoom"), } enum class GuiInterrupt(override val displayName: String) : NamedEnum { - Reverse("Reverse"), - Finish("Skip To End"), + Reverse("Reverse"), + Finish("Skip To End"), } enum class NotificationSide(override val displayName: String) : NamedEnum { - Left("Left"), - Right("Right"), + Left("Left"), + Right("Right"), } enum class NotificationFlow(override val displayName: String) : NamedEnum { - Up("Up"), - Down("Down"), + Up("Up"), + Down("Down"), } enum class NotificationLimit(override val displayName: String) : NamedEnum { - Count("Count"), - Screen("Fit Screen"), + Count("Count"), + Screen("Fit Screen"), } enum class GuiFont( - override val displayName: String, - val size: TextUnit, - val smallSize: TextUnit, - val titleWeight: FontWeight + 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); + 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 - } - } + val family: FontFamily by lazy { + fun font(file: String, weight: FontWeight) = + Font(file, "fonts/$file".stream.use { it.readAllBytes() }, weight) + when (this) { + Minecraft -> + FontFamily(font("MinecraftDefault-Regular.ttf", FontWeight.Normal)) + FiraSans -> + FontFamily( + font("FiraSans-Regular.ttf", FontWeight.Normal), + font("FiraSans-Bold.ttf", FontWeight.Bold) + ) + System -> FontFamily.SansSerif + } + } } @Immutable private class Typography(font: GuiFont, scale: Float = 1f) { - val title = compact(font, font.size * scale, font.titleWeight) - val body = compact(font, font.size * scale) - val label = compact(font, font.smallSize * scale) + val title = compact(font, font.size * scale, font.titleWeight) + val body = compact(font, font.size * scale) + val label = compact(font, font.smallSize * scale) - private fun compact( - font: GuiFont, - size: TextUnit, - weight: FontWeight = FontWeight.Normal - ) = - TextStyle( - fontFamily = font.family, - fontWeight = weight, - fontSize = size, - lineHeight = if (font == GuiFont.Minecraft) size else size * 1.25f, - lineHeightStyle = LineHeightStyle( - LineHeightStyle.Alignment.Center, - LineHeightStyle.Trim.Both - ), - ) + private fun compact( + font: GuiFont, + size: TextUnit, + weight: FontWeight = FontWeight.Normal + ) = + TextStyle( + fontFamily = font.family, + fontWeight = weight, + fontSize = size, + lineHeight = if (font == GuiFont.Minecraft) size else size * 1.25f, + lineHeightStyle = LineHeightStyle( + LineHeightStyle.Alignment.Center, + LineHeightStyle.Trim.Both + ), + ) } object Type { - val title: TextStyle @Composable @ReadOnlyComposable get() = LocalTypography.current.title - val body: TextStyle @Composable @ReadOnlyComposable get() = LocalTypography.current.body - val label: TextStyle @Composable @ReadOnlyComposable get() = LocalTypography.current.label + 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 + val colors: Palette + @Composable @ReadOnlyComposable get() = LocalPalette.current } @Composable fun LambdaTheme(content: @Composable () -> Unit) { - val palette by observe { GuiConfig.palette } - val font by observe { GuiConfig.font } - val fontSize by observe { GuiConfig.fontSize } - val measurer = rememberTextMeasurer() - val typography = - remember(font, fontSize) { - if (font == GuiFont.Minecraft) return@remember Typography(font, fontSize) - val line = - measurer.measure( - "Ag", - Typography(font).body, - density = Density(1f) - ).size.height - Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f) * fontSize) - } - CompositionLocalProvider( - LocalPalette provides palette, - LocalTypography provides typography, - LocalTextSelectionColors provides - TextSelectionColors( - palette.primary, - palette.primary.copy(alpha = 0.4f) - ), - LocalContentColor provides palette.onSurface, - content = content - ) + val palette by observe { GuiConfig.palette } + val font by observe { GuiConfig.font } + val fontSize by observe { GuiConfig.fontSize } + val measurer = rememberTextMeasurer() + val typography = + remember(font, fontSize) { + if (font == GuiFont.Minecraft) return@remember Typography(font, fontSize) + val line = + measurer.measure( + "Ag", + Typography(font).body, + density = Density(1f) + ).size.height + Typography(font, (LINE_HEIGHT / line).coerceAtMost(1f) * fontSize) + } + CompositionLocalProvider( + LocalPalette provides palette, + LocalTypography provides typography, + LocalTextSelectionColors provides + TextSelectionColors( + palette.primary, + palette.primary.copy(alpha = 0.4f) + ), + LocalContentColor provides palette.onSurface, + content = content + ) } diff --git a/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt index 3a189ec6f..309e353a2 100644 --- a/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt +++ b/src/main/kotlin/com/lambda/interaction/handler/handlers/NotificationHandler.kt @@ -32,40 +32,40 @@ import com.lambda.gui.theme.NotificationLimit import java.awt.Color object NotificationHandler : Loadable { - private const val MAX_KEPT = 40 + private const val MAX_KEPT = 40 - private val kept = mutableStateListOf() - val notifications: List get() = kept + private val kept = mutableStateListOf() + val notifications: List get() = kept - init { - listenUnsafe { event -> - if (kept.isNotEmpty()) event.content { Notifications() } - } - } + init { + listenUnsafe { event -> + if (kept.isNotEmpty()) event.content { Notifications() } + } + } - override fun load() = "Loaded Notification Handler" + override fun load() = "Loaded Notification Handler" - fun notify(title: String, message: String = "", accent: Color? = null) = - mc.execute { - val notification = Notification(title, message, accent) - kept += notification - if (kept.size > MAX_KEPT) kept.removeRange(0, kept.size - MAX_KEPT) - if (GuiConfig.notificationLimit == NotificationLimit.Count) { - kept.filterNot { it.dismissed } - .dropLast(GuiConfig.maxNotifications) - .forEach { it.dismissed = true } - } - RenderThread.after((GuiConfig.notificationSeconds * 1000).toLong()) { - notification.dismissed = true - } - } + fun notify(title: String, message: String = "", accent: Color? = null) = + mc.execute { + val notification = Notification(title, message, accent) + kept += notification + if (kept.size > MAX_KEPT) kept.removeRange(0, kept.size - MAX_KEPT) + if (GuiConfig.notificationLimit == NotificationLimit.Count) { + kept.filterNot { it.dismissed } + .dropLast(GuiConfig.maxNotifications) + .forEach { it.dismissed = true } + } + RenderThread.after((GuiConfig.notificationSeconds * 1000).toLong()) { + notification.dismissed = true + } + } - fun remove(notification: Notification) { - kept -= notification - } + fun remove(notification: Notification) { + kept -= notification + } - class Notification(val title: String, val message: String, val accent: Color?) { - var dismissed by mutableStateOf(false) - internal set - } + class Notification(val title: String, val message: String, val accent: Color?) { + var dismissed by mutableStateOf(false) + internal set + } } diff --git a/src/main/kotlin/com/lambda/interaction/manager/managers/inventory/InventoryManager.kt b/src/main/kotlin/com/lambda/interaction/manager/managers/inventory/InventoryManager.kt index 654a05647..795d480a9 100644 --- a/src/main/kotlin/com/lambda/interaction/manager/managers/inventory/InventoryManager.kt +++ b/src/main/kotlin/com/lambda/interaction/manager/managers/inventory/InventoryManager.kt @@ -75,7 +75,7 @@ object InventoryManager : Manager(1) { super.load() listen({ Int.MIN_VALUE }) { - if (ClientConfig.avoidInventoryDesync) indexInventoryChanges() + if (ClientConfig.avoidInventoryDesync) indexInventoryChanges() actionsThisTick = 0 activeRequest = null actions = mutableListOf() diff --git a/src/main/kotlin/com/lambda/module/HudModule.kt b/src/main/kotlin/com/lambda/module/HudModule.kt index 982ca5ecf..f2d04733f 100644 --- a/src/main/kotlin/com/lambda/module/HudModule.kt +++ b/src/main/kotlin/com/lambda/module/HudModule.kt @@ -18,10 +18,31 @@ package com.lambda.module import androidx.compose.runtime.Composable +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import com.lambda.config.entries.onValueChangeUnsafe +import com.lambda.config.settings.comparable.enumSetting import com.lambda.config.settings.complex.Bind import com.lambda.config.settings.complex.colorSetting import com.lambda.config.settings.numeric.floatSetting +import com.lambda.util.NamedEnum import java.awt.Color +import kotlin.math.roundToInt + +@Suppress("unused") +enum class HudAnchor(override val displayName: String, val x: Float, val y: Float) : NamedEnum { + TopLeft("Top Left", 0f, 0f), + Top("Top", 0.5f, 0f), + TopRight("Top Right", 1f, 0f), + Left("Left", 0f, 0.5f), + Center("Center", 0.5f, 0.5f), + Right("Right", 1f, 0.5f), + BottomLeft("Bottom Left", 0f, 1f), + Bottom("Bottom", 0.5f, 1f), + BottomRight("Bottom Right", 1f, 1f); + + fun offset(size: IntSize) = IntOffset((size.width * x).roundToInt(), (size.height * y).roundToInt()) +} abstract class HudModule( name: String, @@ -30,30 +51,51 @@ abstract class HudModule( alwaysListening: Boolean = false, enabledByDefault: Boolean = false, defaultKeybind: Bind = Bind.EMPTY, - defaultScale: Float = 1f, - defaultAnchorX: Float = DEFAULT_ANCHOR, - defaultAnchorY: Float? = null, + defaultScale: Float = 1f, + defaultAnchorX: Float = DEFAULT_ANCHOR, + defaultAnchorY: Float? = null, ) : Module( - name, - description, - tag, - alwaysListening, - enabledByDefault, - defaultKeybind = defaultKeybind + name, + description, + tag, + alwaysListening, + enabledByDefault, + defaultKeybind = defaultKeybind ) { val backgroundColor = colorSetting("Background Color", Color(0, 0, 0, 0)) - val scale by floatSetting("Scale", defaultScale, 0.25f..5f, 0.05f, "Size of this element, on top of the Scale in HUD Settings") + val scale by floatSetting("Scale", defaultScale, 0.25f..5f, 0.05f, "Size of this element, on top of the Scale in HUD Settings") + + val anchor by enumSetting("Anchor", HudAnchor.TopLeft, "The corner or side of this element that stays exactly where it is on the screen. When the element grows or shrinks it does so away from that point. Changing it does not move the element") + .onValueChangeUnsafe { from, to -> reanchor(from, to) } + + var shownSize = IntSize.Zero + var shownScreen = IntSize.Zero + + var anchorX by floatSetting("HUD X", defaultAnchorX, 0f..1f, 0.001f) { false } + var anchorY by floatSetting("HUD Y", defaultAnchorY ?: (DEFAULT_ANCHOR + DEFAULT_SPACING * created++).coerceAtMost(1f), 0f..1f, 0.001f) { false } + + @Composable + abstract fun Content() + + fun place(topLeft: IntOffset) = pin(topLeft + anchor.offset(shownSize)) - var anchorX by floatSetting("HUD X", defaultAnchorX, 0f..1f, 0.001f) { false } - var anchorY by floatSetting("HUD Y", defaultAnchorY ?: (DEFAULT_ANCHOR + DEFAULT_SPACING * created++).coerceAtMost(1f), 0f..1f, 0.001f) { false } + private fun reanchor(from: HudAnchor, to: HudAnchor) { + val screen = shownScreen + val pinned = IntOffset((screen.width * anchorX).roundToInt(), (screen.height * anchorY).roundToInt()) + pin(pinned - from.offset(shownSize) + to.offset(shownSize)) + } - @Composable - abstract fun Content() + private fun pin(point: IntOffset) { + val screen = shownScreen + if (screen.width <= 0 || screen.height <= 0) return + anchorX = (point.x / screen.width.toFloat()).coerceIn(0f, 1f) + anchorY = (point.y / screen.height.toFloat()).coerceIn(0f, 1f) + } - private companion object { - const val DEFAULT_ANCHOR = 0.01f + private companion object { + const val DEFAULT_ANCHOR = 0.01f - const val DEFAULT_SPACING = 0.06f - var created = 0 - } + 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 09341c5e8..4107ef523 100644 --- a/src/main/kotlin/com/lambda/module/Module.kt +++ b/src/main/kotlin/com/lambda/module/Module.kt @@ -128,8 +128,8 @@ abstract class Module( enabledByDefault: Boolean = false, modulePriority: Int = 0, defaultKeybind: Bind = Bind.EMPTY, - autoDisable: Boolean = false, - val alwaysEnabled: Boolean = false, + autoDisable: Boolean = false, + val alwaysEnabled: Boolean = false, ) : Nameable, Muteable, OwnerPriority, Config(name, ModuleCategory), IMutableAutomationConfig by MutableAutomationConfig() { @@ -149,11 +149,11 @@ abstract class Module( val drawSetting = boolSetting("Draw", true, "Draws the module in the module list hud element") { false } val showInClickGui = boolSetting("Show In ClickGui", true, "Shows the module in the ClickGui layout") { false } - var isEnabled: Boolean - get() = alwaysEnabled || isEnabledSetting.value - private set(value) { - isEnabledSetting.value = value - } + var isEnabled: Boolean + get() = alwaysEnabled || isEnabledSetting.value + private set(value) { + isEnabledSetting.value = value + } val isDisabled get() = !isEnabled val keybind by keybindSetting @@ -164,8 +164,8 @@ abstract class Module( get() = !isEnabled && !alwaysListening init { - onEnableUnsafe { if (ClientConfig.clientSounds) LambdaSound.ModuleOn.play() } - onDisableUnsafe { if (ClientConfig.clientSounds) LambdaSound.ModuleOff.play() } + onEnableUnsafe { if (ClientConfig.clientSounds) LambdaSound.ModuleOn.play() } + onDisableUnsafe { if (ClientConfig.clientSounds) LambdaSound.ModuleOff.play() } listen { if (autoDisable) disable() } listen { if (autoDisable) disable() } @@ -177,21 +177,21 @@ abstract class Module( @ModuleDsl fun enable() { - if (alwaysEnabled) return + if (alwaysEnabled) return ModuleEvent.Enabled(this@Module).post() isEnabled = true } @ModuleDsl fun disable() { - if (alwaysEnabled) return + if (alwaysEnabled) return ModuleEvent.Disabled(this@Module).post() isEnabled = false } @ModuleDsl fun toggle() { - if (alwaysEnabled) return + 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 7e059d880..2aa41ce5c 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt @@ -44,10 +44,10 @@ object AutoUpdater : Module( private var loaderPromptHandled by property(false) - internal enum class Prompt { FirstLaunch, Install, Uninstall } + internal enum class Prompt { FirstLaunch, Install, Uninstall } - internal var prompt: Prompt? = null - private set + internal var prompt: Prompt? = null + private set private var firstLaunchStateInitialized = false private const val MAVEN_URL = "https://maven.lambda-client.org" @@ -62,40 +62,40 @@ object AutoUpdater : Module( } init { - onEnableUnsafe { prompt = Prompt.Install.takeIf { LambdaGui.screen != null && prompt != Prompt.Uninstall } } - onDisableUnsafe { prompt = Prompt.Uninstall.takeIf { LambdaGui.screen != null && prompt != Prompt.Install } } - } - - internal fun onGuiOpened() { - if (firstLaunchStateInitialized) return - firstLaunchStateInitialized = true - - if (FabricLoader.getInstance().isModLoaded("lambda-loader")) { - loaderPromptHandled = true - if (!isEnabled) enable() - return - } - if (!loaderPromptHandled) prompt = Prompt.FirstLaunch - } - - internal fun answerPrompt(accepted: Boolean) { - when (prompt) { - Prompt.FirstLaunch -> { - loaderPromptHandled = true - prompt = null - if (accepted) installLoader() + onEnableUnsafe { prompt = Prompt.Install.takeIf { LambdaGui.screen != null && prompt != Prompt.Uninstall } } + onDisableUnsafe { prompt = Prompt.Uninstall.takeIf { LambdaGui.screen != null && prompt != Prompt.Install } } + } + + internal fun onGuiOpened() { + if (firstLaunchStateInitialized) return + firstLaunchStateInitialized = true + + if (FabricLoader.getInstance().isModLoaded("lambda-loader")) { + loaderPromptHandled = true + if (!isEnabled) enable() + return + } + if (!loaderPromptHandled) prompt = Prompt.FirstLaunch + } + + internal fun answerPrompt(accepted: Boolean) { + when (prompt) { + Prompt.FirstLaunch -> { + loaderPromptHandled = true + prompt = null + if (accepted) installLoader() } - Prompt.Install -> - if (accepted) { - prompt = null - installLoader() - } else disable() - Prompt.Uninstall -> - if (accepted) { - prompt = null - installClient() - } else enable() - null -> Unit + Prompt.Install -> + if (accepted) { + prompt = null + installLoader() + } else disable() + Prompt.Uninstall -> + if (accepted) { + prompt = null + installClient() + } else enable() + null -> Unit } } 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 da550a183..114582984 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 @@ -659,9 +659,9 @@ object AutoDisconnect : Module( buildText { text(effect.effectType.value().name) if (effect.amplifier > 0) literal(" ${effect.amplifier + 1}") - color(GuiConfig.palette.onSurfaceVariant.toAwt()) { - literal(" (${effectDuration(effect)})") - } + color(GuiConfig.palette.onSurfaceVariant.toAwt()) { + literal(" (${effectDuration(effect)})") + } } ) } @@ -748,7 +748,7 @@ object AutoDisconnect : Module( val customName = stack.get(DataComponentTypes.CUSTOM_NAME) if (customName != null) { text(stack.itemName) - color(GuiConfig.palette.onSurfaceVariant.toAwt()) { + color(GuiConfig.palette.onSurfaceVariant.toAwt()) { literal(" (") text(customName) literal(")") @@ -758,13 +758,13 @@ object AutoDisconnect : Module( } if (stack.isDamageable) { - color(GuiConfig.palette.onSurfaceVariant.toAwt()) { - literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") - } + color(GuiConfig.palette.onSurfaceVariant.toAwt()) { + literal(" (${stack.maxDamage - stack.damage}/${stack.maxDamage})") + } } if (stack.maxCount > 1) { - color(GuiConfig.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.count})") } + color(GuiConfig.palette.onSurfaceVariant.toAwt()) { literal(" (${stack.count})") } } if (selected) { diff --git a/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt b/src/main/kotlin/com/lambda/module/modules/combat/autodisconnect/DisconnectDetailsWidget.kt index 7f47c3465..f593a18bc 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 @@ -268,10 +268,10 @@ class DisconnectDetailsWidget( const val HOVER_PADDING = 2 const val HOVER_RADIUS = 1 - val COLOR_TEXT get() = GuiConfig.palette.onSurface.toArgb() - val COLOR_BACKGROUND get() = GuiConfig.palette.panel.toArgb() - val COLOR_BORDER get() = GuiConfig.palette.border.toArgb() - val COLOR_HOVER_BACKGROUND get() = GuiConfig.palette.controlSelected.toArgb() - val COLOR_HEADER get() = COLOR_TEXT + val COLOR_TEXT get() = GuiConfig.palette.onSurface.toArgb() + val COLOR_BACKGROUND get() = GuiConfig.palette.panel.toArgb() + val COLOR_BORDER get() = GuiConfig.palette.border.toArgb() + val COLOR_HOVER_BACKGROUND get() = GuiConfig.palette.controlSelected.toArgb() + val COLOR_HEADER get() = COLOR_TEXT } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/AccountName.kt b/src/main/kotlin/com/lambda/module/modules/hud/AccountName.kt index d25f8825f..f6fe53d57 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/AccountName.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/AccountName.kt @@ -30,9 +30,9 @@ object AccountName : HudModule( description = "Displays the current accounts name", tag = ModuleTag.HUD ) { - @Composable - override fun Content() { - val name by observeSafe { player.name.string } - name?.let { HudText(it) } + @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 index 46bb4088d..84ae6936f 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Armor.kt @@ -36,47 +36,47 @@ 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, + 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 enum class Layout(override val displayName: String) : NamedEnum { + Horizontal("Horizontal"), + Vertical("Vertical"), + } - private val layout by enumSetting("Layout", Layout.Horizontal) - private val iconSize by floatSetting("Icon Size", 16f, 8f..64f, 1f, "Items are drawn at the nearest whole multiple of their 16 pixels, as Minecraft draws them") + private val layout by enumSetting("Layout", Layout.Horizontal) + private val iconSize by floatSetting("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 - ) + private val slots = + listOf( + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + ) - @Composable - override fun Content() { - val worn by observeSafe { slots.map(player::getEquippedStack).filterNot { it.isEmpty } } - val layout by observe { layout } - val size by observe { iconSize.dp } + @Composable + override fun Content() { + val worn by observeSafe { slots.map(player::getEquippedStack).filterNot { it.isEmpty } } + val layout by observe { layout } + val size by observe { iconSize.dp } - val pieces = worn.orEmpty() - if (pieces.isEmpty()) { - HudText("No armor") - return - } - val spacing = Arrangement.spacedBy(size / 8) - when (layout) { - Layout.Horizontal -> - Row(horizontalArrangement = spacing) { - pieces.forEach { ItemIcon(it, size) } - } - Layout.Vertical -> - Column(verticalArrangement = spacing) { - pieces.forEach { ItemIcon(it, size) } - } - } - } + val pieces = worn.orEmpty() + if (pieces.isEmpty()) { + HudText("No armor") + return + } + val spacing = Arrangement.spacedBy(size / 8) + when (layout) { + Layout.Horizontal -> + Row(horizontalArrangement = spacing) { + pieces.forEach { ItemIcon(it, size) } + } + Layout.Vertical -> + Column(verticalArrangement = spacing) { + pieces.forEach { ItemIcon(it, size) } + } + } + } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Baritone.kt b/src/main/kotlin/com/lambda/module/modules/hud/Baritone.kt index 03de639e0..ae1a72f9c 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Baritone.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Baritone.kt @@ -32,18 +32,18 @@ object Baritone : HudModule( description = "Look inside of Baritones head", tag = ModuleTag.HUD, ) { - @Composable - override fun Content() { - val status by observe { status() } - HudText(status) - } + @Composable + override fun Content() { + val status by observe { status() } + HudText(status) + } - 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" - } + 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/ModuleList.kt b/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt index 51bfe651f..51659325d 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/ModuleList.kt @@ -42,29 +42,29 @@ object ModuleList : HudModule( drawSetting.value = false } - @Composable - override fun Content() { - val entries by observe { - ModuleRegistry.modules - .filter { it.isEnabled && it.draw && !it.alwaysEnabled } - .map { it.name to it.keybind.takeIf { bind -> bind.key != 0 || bind.mouse != -1 } } - .filter { (_, bind) -> bind != null || !onlyBound } - } - val showKeybind by observe { showKeybind } - Column { - entries.forEach { (name, bind) -> - Row { - HudText(name) - if (showKeybind) { - HudText( - " [${(bind ?: Bind.EMPTY).name}]", - color = - if (bind != null) Color.Green - else Color.Red - ) - } - } - } + @Composable + override fun Content() { + val entries by observe { + ModuleRegistry.modules + .filter { it.isEnabled && it.draw && !it.alwaysEnabled } + .map { it.name to it.keybind.takeIf { bind -> bind.key != 0 || bind.mouse != -1 } } + .filter { (_, bind) -> bind != null || !onlyBound } + } + val showKeybind by observe { showKeybind } + Column { + entries.forEach { (name, bind) -> + Row { + HudText(name) + if (showKeybind) { + HudText( + " [${(bind ?: Bind.EMPTY).name}]", + color = + if (bind != null) Color.Green + else Color.Red + ) + } + } + } } } } diff --git a/src/main/kotlin/com/lambda/module/modules/hud/Speedometer.kt b/src/main/kotlin/com/lambda/module/modules/hud/Speedometer.kt index 55152eb65..c3d7a938f 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Speedometer.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Speedometer.kt @@ -71,9 +71,9 @@ object Speedometer : HudModule( speedUnit.convertFromMinecraft(vecDelta.length()) } - @Composable - override fun Content() { - val text by observe { "Speed: %.2f %s".format(speed, speedUnit.unitName) } - HudText(text) + @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 ce7dbea80..d1f7bd028 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/TaskFlowHud.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/TaskFlowHud.kt @@ -31,9 +31,9 @@ object TaskFlowHud : HudModule( name = "TaskFlowHud", tag = ModuleTag.HUD, ) { - @Composable - override fun Content() { - val tasks by observe { RootTask.taskTree(ClientConfig.showInvisibleTasks) } - HudText(tasks) + @Composable + override fun Content() { + val tasks by observe { RootTask.taskTree(ClientConfig.showInvisibleTasks) } + HudText(tasks) } } 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 e97ea6acc..a2fdcb19c 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Watermark.kt @@ -31,19 +31,19 @@ object Watermark : HudModule( name = "Watermark", tag = ModuleTag.HUD, enabledByDefault = true, - defaultScale = 0.45f, - defaultAnchorX = 0.005f, - defaultAnchorY = 0.009f, + defaultScale = 0.45f, + defaultAnchorX = 0.005f, + defaultAnchorY = 0.0089f, ) { - private const val LOGO_SCALE = 0.05f + private const val LOGO_SCALE = 0.05f - @Composable - override fun Content() { - val logo = rememberTexture("textures/lambda.png") - Image( - logo, - "Lambda", - Modifier.size((logo.width * LOGO_SCALE).dp, (logo.height * LOGO_SCALE).dp) - ) + @Composable + override fun Content() { + val logo = rememberTexture("textures/lambda.png") + Image( + logo, + "Lambda", + Modifier.size((logo.width * LOGO_SCALE).dp, (logo.height * LOGO_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 4d5a7b96e..f66b4400d 100644 --- a/src/main/kotlin/com/lambda/module/modules/movement/BackTrack.kt +++ b/src/main/kotlin/com/lambda/module/modules/movement/BackTrack.kt @@ -63,7 +63,7 @@ object BackTrack : Module( description = "Gives reach advantage by delaying your packets", tag = ModuleTag.MOVEMENT, ) { - private val BOX_COLOR = Color(130, 200, 255) + private val BOX_COLOR = Color(130, 200, 255) private val outbound by boolSetting("Outbound", true) private val mode by enumSetting("Mode", Mode.Fixed) @@ -177,7 +177,7 @@ object BackTrack : Module( immediateRenderer("BackTrack Immediate Renderer") { val target = target ?: return@immediateRenderer - val c1 = BOX_COLOR + val c1 = BOX_COLOR val c2 = Color.RED val p = target.hurtTime / 10.0 val c = lerp(p, c1, c2) diff --git a/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt b/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt index ce7e83545..c48759135 100644 --- a/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt +++ b/src/main/kotlin/com/lambda/module/modules/movement/Blink.kt @@ -49,7 +49,7 @@ object Blink : Module( description = "Holds packets", tag = ModuleTag.MOVEMENT, ) { - private val BOX_COLOR = Color(130, 200, 255) + private val BOX_COLOR = Color(130, 200, 255) private var delay by intSetting("Delay", 500, 50..10000, 10) private val shiftVelocity by boolSetting("Shift velocity", true) @@ -75,7 +75,7 @@ object Blink : Module( } immediateRenderer("Blink Immediate Renderer") { - val color = BOX_COLOR + val color = BOX_COLOR box(box.update(lastBox).box(mc.tickDelta) ?: return@immediateRenderer) { colors(color.setAlpha(0.3), color) } diff --git a/src/main/kotlin/com/lambda/module/modules/player/Replay.kt b/src/main/kotlin/com/lambda/module/modules/player/Replay.kt index d86983f0d..47898f419 100644 --- a/src/main/kotlin/com/lambda/module/modules/player/Replay.kt +++ b/src/main/kotlin/com/lambda/module/modules/player/Replay.kt @@ -91,8 +91,8 @@ object Replay : Module( tag = ModuleTag.PLAYER, autoDisable = true ) { - private val HIGHLIGHT_COLOR = Color(130, 200, 255) - private val ACTION_COLOR = Color(225, 130, 225) + private val HIGHLIGHT_COLOR = Color(130, 200, 255) + private val ACTION_COLOR = Color(225, 130, 225) private val record by setting("Record", KeyCode.R) .onPress { handleRecord() } @@ -204,11 +204,11 @@ object Replay : Module( val index = recordings.indexOf(saving) this@Replay.info(buildText { literal("Auto saved #") - color(HIGHLIGHT_COLOR) { literal("$index") } + color(HIGHLIGHT_COLOR) { literal("$index") } literal(" of ") - color(HIGHLIGHT_COLOR) { literal(saving.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(saving.duration.toString()) } literal(" at ") - color(HIGHLIGHT_COLOR) { literal(saving.endPos.format(precision = 1)) } + color(HIGHLIGHT_COLOR) { literal(saving.endPos.format(precision = 1)) } playMessage(saving) saveMessage(saving) pruneMessage(saving) @@ -226,9 +226,9 @@ object Replay : Module( buffer = playback?.duplicate() this@Replay.info(buildText { if (repeats > 0) { - color(HIGHLIGHT_COLOR) { literal("[$repeats / $loops]") } + color(HIGHLIGHT_COLOR) { literal("[$repeats / $loops]") } } else { - color(HIGHLIGHT_COLOR) { literal("[$repeats/∞]") } + color(HIGHLIGHT_COLOR) { literal("[$repeats/∞]") } } literal(" Replay looped.") }) @@ -239,7 +239,7 @@ object Replay : Module( state = State.Inactive this@Replay.info(buildText { literal("Replay finished after ") - color(HIGHLIGHT_COLOR) { literal(playback?.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(playback?.duration.toString()) } literal(".") }) return@listen @@ -264,9 +264,9 @@ object Replay : Module( info(buildText { literal("Recording #${recordings.indexOf(deserialized)} ") - color(HIGHLIGHT_COLOR) { literal(file.nameWithoutExtension) } + color(HIGHLIGHT_COLOR) { literal(file.nameWithoutExtension) } literal(" loaded. Duration: ") - color(HIGHLIGHT_COLOR) { literal(deserialized.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(deserialized.duration.toString()) } playMessage(deserialized) pruneMessage(deserialized) }) @@ -295,9 +295,9 @@ object Replay : Module( playback = recording info(buildText { literal("Replaying recording #") - color(HIGHLIGHT_COLOR) { literal(index.toString()) } + color(HIGHLIGHT_COLOR) { literal(index.toString()) } literal(" of ") - color(HIGHLIGHT_COLOR) { literal(recording.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(recording.duration.toString()) } }) return CommandResult.success() } @@ -311,13 +311,13 @@ object Replay : Module( recordings.add(pruned) info(buildText { literal("Shortened recording #") - color(HIGHLIGHT_COLOR) { literal(recordings.indexOf(toShorten).toString()) } + color(HIGHLIGHT_COLOR) { literal(recordings.indexOf(toShorten).toString()) } literal(" of ") - color(HIGHLIGHT_COLOR) { literal(toShorten.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(toShorten.duration.toString()) } literal(" to new recording #") - color(HIGHLIGHT_COLOR) { literal(recordings.indexOf(pruned).toString()) } + color(HIGHLIGHT_COLOR) { literal(recordings.indexOf(pruned).toString()) } literal(" of ") - color(HIGHLIGHT_COLOR) { literal(pruned.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(pruned.duration.toString()) } playMessage(pruned) saveMessage(pruned) }) @@ -333,7 +333,7 @@ object Replay : Module( buffer = it.duplicate() info(buildText { literal("Replaying most recent recording #${recordings.indexOf(it)}. Duration: ") - color(HIGHLIGHT_COLOR) { literal(it.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(it.duration.toString()) } }) } ?: run { this@Replay.warn("No recording to replay.") @@ -377,9 +377,9 @@ object Replay : Module( recordings.add(rec) this@Replay.info(buildText { literal("Stopped recording #") - color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(rec)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(rec)}") } literal(" of ") - color(HIGHLIGHT_COLOR) { literal(rec.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(rec.duration.toString()) } literal(".") playMessage(rec) saveMessage(rec) @@ -394,9 +394,9 @@ object Replay : Module( recordings.add(checkRec) this@Replay.info(buildText { literal("Checkpoint #") - color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(checkRec)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(checkRec)}") } literal(" created at ") - color(HIGHLIGHT_COLOR) { literal(checkRec.endPos.format(precision = 0)) } + color(HIGHLIGHT_COLOR) { literal(checkRec.endPos.format(precision = 0)) } literal(".") playMessage(checkRec) saveMessage(checkRec) @@ -415,9 +415,9 @@ object Replay : Module( playMode = PlayMode.entries[(playMode.ordinal + 1) % PlayMode.entries.size] info(buildText { literal("Set play mode to ") - color(HIGHLIGHT_COLOR) { literal(playMode.name) } + color(HIGHLIGHT_COLOR) { literal(playMode.name) } literal(" (previously ") - color(HIGHLIGHT_COLOR) { literal(oldMode.name) } + color(HIGHLIGHT_COLOR) { literal(oldMode.name) } literal(")") }) } @@ -437,30 +437,30 @@ object Replay : Module( this@Replay.info(buildText { literal("Saved recording #") - color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(" of ") - color(HIGHLIGHT_COLOR) { literal(recording.duration.toString()) } + color(HIGHLIGHT_COLOR) { literal(recording.duration.toString()) } literal(" in file ") - color(HIGHLIGHT_COLOR) { literal(name) } + color(HIGHLIGHT_COLOR) { literal(name) } val filePath = file.toPath().pathString hoverEvent(HoverEvents.showText(buildText { literal("Open file ") - color(HIGHLIGHT_COLOR) { literal(filePath) } + color(HIGHLIGHT_COLOR) { literal(filePath) } })) { clickEvent(ClickEvents.openFile(filePath)) { literal(" [") - color(ACTION_COLOR) { literal("OPEN FILE") } + color(ACTION_COLOR) { literal("OPEN FILE") } literal("]") } } val parentPath = file.parentFile.toPath().pathString hoverEvent(HoverEvents.showText(buildText { literal("Open folder ") - color(HIGHLIGHT_COLOR) { literal(parentPath) } + color(HIGHLIGHT_COLOR) { literal(parentPath) } })) { clickEvent(ClickEvents.openFile(parentPath)) { literal(" [") - color(ACTION_COLOR) { literal("OPEN FOLDER") } + color(ACTION_COLOR) { literal("OPEN FOLDER") } literal("]") } } @@ -471,12 +471,12 @@ object Replay : Module( private fun TextBuilder.playMessage(recording: Recording) { hoverEvent(HoverEvents.showText(buildText { literal("Click to replay recording #") - color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(".") })) { clickEvent(ClickEvents.suggestCommand(";replay play ${recordings.indexOf(recording)}")) { literal(" [") - color(ACTION_COLOR) { + color(ACTION_COLOR) { literal("PLAY") } literal("]") @@ -489,17 +489,17 @@ object Replay : Module( hoverEvent(HoverEvents.showText(buildText { literal(" Recording can be shortened by ") - color(HIGHLIGHT_COLOR) { + color(HIGHLIGHT_COLOR) { literal(recording.pruneTimesave.toString()) } literal(" by removing idles and cyclic paths.") })) { clickEvent(ClickEvents.suggestCommand(";replay prune ${recordings.indexOf(recording)}")) { literal(" [") - color(ACTION_COLOR) { + color(ACTION_COLOR) { literal("PRUNE ") } - color(HIGHLIGHT_COLOR) { + color(HIGHLIGHT_COLOR) { literal("${recording.pruneTimesave}") } literal("]") @@ -510,12 +510,12 @@ object Replay : Module( private fun TextBuilder.saveMessage(recording: Recording) { hoverEvent(HoverEvents.showText(buildText { literal("Click to save recording #") - color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } + color(HIGHLIGHT_COLOR) { literal("${recordings.indexOf(recording)}") } literal(".") })) { clickEvent(ClickEvents.suggestCommand(";replay save ${recordings.indexOf(recording)} ${getTime(fileFormatter).sanitizeForFilename()}")) { literal(" [") - color(ACTION_COLOR) { literal("SAVE") } + color(ACTION_COLOR) { literal("SAVE") } literal("]") } } @@ -535,7 +535,7 @@ object Replay : Module( } this@Replay.info(buildText { literal("Postprocessing finished. Shortened recording by ") - color(HIGHLIGHT_COLOR) { literal((duration - pruned.duration).toString()) } + color(HIGHLIGHT_COLOR) { literal((duration - pruned.duration).toString()) } literal(".") }) return pruned diff --git a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt index ec6a2517d..d3741641f 100644 --- a/src/main/kotlin/com/lambda/util/CommunicationUtils.kt +++ b/src/main/kotlin/com/lambda/util/CommunicationUtils.kt @@ -153,7 +153,7 @@ object CommunicationUtils { if (command.usage.isNotBlank()) { literal("\n") literal("Usage: ") - color(GuiConfig.palette.primary.toAwt()) { + color(GuiConfig.palette.primary.toAwt()) { literal(command.usage) } } @@ -161,7 +161,7 @@ object CommunicationUtils { literal("\n") literal("Aliases: ") joinToText(command.aliases) { - color(GuiConfig.palette.primary.toAwt()) { + color(GuiConfig.palette.primary.toAwt()) { literal(it) } } @@ -180,7 +180,7 @@ object CommunicationUtils { literal("\n") } literal("Keybind: ") - color(GuiConfig.palette.primary.toAwt()) { + color(GuiConfig.palette.primary.toAwt()) { if (module.keybind.key != 0 || module.keybind.mouse > -1) { literal(module.keybind.name) } else { diff --git a/src/main/kotlin/com/lambda/util/text/TextDsl.kt b/src/main/kotlin/com/lambda/util/text/TextDsl.kt index 838a9a733..da68092eb 100644 --- a/src/main/kotlin/com/lambda/util/text/TextDsl.kt +++ b/src/main/kotlin/com/lambda/util/text/TextDsl.kt @@ -218,7 +218,7 @@ inline fun TextBuilder.color(color: Color?, action: TextBuilder.() -> Unit) { @TextDsl fun TextBuilder.highlighted(value: String) { - color(ClientConfig.highlightColor) { + color(ClientConfig.highlightColor) { literal(value) } } 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 index 0bc8370d2..7a860417e 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_blur_down.fsh @@ -3,7 +3,7 @@ uniform sampler2D InSampler; layout(std140) uniform BlurSpread { - float Spread; + float Spread; }; in vec2 texCoord; @@ -11,13 +11,13 @@ in vec2 texCoord; out vec4 fragColor; void main() { - vec2 texel = Spread / vec2(textureSize(InSampler, 0)); + 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)); + 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; + 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 index a6034ef27..30f0e66d7 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_blur_up.fsh @@ -3,7 +3,7 @@ uniform sampler2D InSampler; layout(std140) uniform BlurSpread { - float Spread; + float Spread; }; in vec2 texCoord; @@ -11,17 +11,17 @@ in vec2 texCoord; out vec4 fragColor; void main() { - vec2 texel = Spread / vec2(textureSize(InSampler, 0)); - vec2 near = texel * 0.5; + 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; + 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; + 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 index 1987b22ee..59c78f3ce 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh @@ -5,12 +5,12 @@ uniform sampler2D BackdropSampler; uniform sampler2D GlowSampler; layout(std140) uniform GuiEffects { - vec4 GlowColorA; - vec4 GlowColorB; - float GlowIntensity; - float Blur; - float Time; - float Dim; + vec4 GlowColorA; + vec4 GlowColorB; + float GlowIntensity; + float Blur; + float Time; + float Dim; }; const vec3 DIM_COLOR = vec3(16.0 / 255.0); @@ -20,21 +20,21 @@ in vec2 texCoord; out vec4 fragColor; void main() { - vec4 gui = texture(GuiSampler, texCoord); + vec4 gui = texture(GuiSampler, texCoord); - float covered = clamp(gui.a * 64.0, 0.0, 1.0); + float covered = clamp(gui.a * 64.0, 0.0, 1.0); - float blurred = Blur * covered; - vec3 backdrop = mix(texture(BackdropSampler, texCoord).rgb, DIM_COLOR, Dim); - vec4 under = vec4(backdrop, 1.0) * blurred; + float blurred = Blur * covered; + vec3 backdrop = mix(texture(BackdropSampler, texCoord).rgb, DIM_COLOR, Dim); + vec4 under = vec4(backdrop, 1.0) * blurred; - if (GlowIntensity > 0.0) { - float glowMask = clamp(texture(GlowSampler, texCoord).a * 2.0, 0.0, 1.0); - float glow = clamp(pow(glowMask, 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 - blurred); - } + if (GlowIntensity > 0.0) { + float glowMask = clamp(texture(GlowSampler, texCoord).a * 2.0, 0.0, 1.0); + float glow = clamp(pow(glowMask, 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 - blurred); + } - vec4 over = gui + under * (1.0 - gui.a); - fragColor = over + vec4(DIM_COLOR, 1.0) * Dim * (1.0 - over.a); + vec4 over = gui + under * (1.0 - gui.a); + fragColor = over + vec4(DIM_COLOR, 1.0) * Dim * (1.0 - over.a); } From dafb4a50f8152297315b4ea182a5a68b4273a704 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:15:28 +0000 Subject: [PATCH 29/34] formatting --- .../kotlin/com/lambda/config/settings/NumericSetting.kt | 4 ++-- src/main/kotlin/com/lambda/gui/LambdaGui.kt | 2 +- src/main/kotlin/com/lambda/gui/Notifications.kt | 8 ++++---- src/main/kotlin/com/lambda/gui/Snap.kt | 8 ++++---- src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt | 4 ++-- src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt | 2 +- src/main/kotlin/com/lambda/gui/component/Popups.kt | 4 ++-- src/main/kotlin/com/lambda/gui/component/Surface.kt | 8 ++++---- src/main/kotlin/com/lambda/gui/core/Frames.kt | 2 +- src/main/kotlin/com/lambda/gui/core/SceneInput.kt | 2 +- src/main/kotlin/com/lambda/gui/hud/HudEditor.kt | 2 +- src/main/kotlin/com/lambda/gui/menu/MenuBar.kt | 4 ++-- src/main/kotlin/com/lambda/gui/menu/Search.kt | 6 +++--- src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt | 2 +- src/main/kotlin/com/lambda/module/HudModule.kt | 2 +- src/main/kotlin/com/lambda/module/modules/hud/Tps.kt | 2 +- .../assets/lambda/shaders/core/gui_composite.fsh | 6 +++--- 17 files changed, 34 insertions(+), 34 deletions(-) diff --git a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt index f43daf9c8..9cd794933 100644 --- a/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt +++ b/src/main/kotlin/com/lambda/config/settings/NumericSetting.kt @@ -118,7 +118,7 @@ abstract class NumericSetting( when { fraction <= 0f -> range.start fraction >= 1f -> range.endInclusive - else -> onGrid(lowest + (highest - lowest) * fraction.toBigDecimal(), RoundingMode.HALF_UP) + else -> onGrid(lowest + ((highest - lowest) * fraction.toBigDecimal()), RoundingMode.HALF_UP) } private fun stepped(by: Int): T = @@ -128,7 +128,7 @@ abstract class NumericSetting( val step = step.decimal if (step.signum() <= 0) return convert(target.coerceIn(lowest, highest)) val steps = (target - lowest).divide(step, 0, rounding) + offset.toBigDecimal() - return convert((lowest + step * steps).coerceIn(lowest, highest)) + return convert((lowest + (step * steps)).coerceIn(lowest, highest)) } @Composable diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index a2c65291b..2e5be7ce0 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -227,7 +227,7 @@ object LambdaGui : Loadable { aboveHud.collect() beneathGui.collect(showsGui) aboveGui.collect(showsGui) - val showsHud = !beneathHud.isEmpty || !aboveHud.isEmpty || screen == null && Hud.shown.isNotEmpty() + val showsHud = !beneathHud.isEmpty || !aboveHud.isEmpty || (screen == null && Hud.shown.isNotEmpty()) if (!showsGui && !showsHud && settled) return layered = showsGui && showsHud diff --git a/src/main/kotlin/com/lambda/gui/Notifications.kt b/src/main/kotlin/com/lambda/gui/Notifications.kt index 6ff4ef03b..4a9aa197c 100644 --- a/src/main/kotlin/com/lambda/gui/Notifications.kt +++ b/src/main/kotlin/com/lambda/gui/Notifications.kt @@ -96,7 +96,7 @@ internal fun NotificationPreview() { Scaled { val margin = with(LocalDensity.current) { MARGIN.roundToPx() } val gap = with(LocalDensity.current) { GAP.roundToPx() } - val line = margin + ((1f - height) * (screen.height - margin * 2)).roundToInt() + val line = margin + ((1f - height) * (screen.height - (margin * 2))).roundToInt() val room = if (rising) line.coerceAtLeast(margin + older) - margin else screen.height - margin - line.coerceAtMost(screen.height - margin - older) @@ -104,7 +104,7 @@ internal fun NotificationPreview() { when { limit == NotificationLimit.Count -> max older == 0 || newest == 0 -> PREVIEW_COUNT - else -> (1 + (room - newest) / (older + gap)).coerceAtLeast(1) + else -> (1 + ((room - newest) / (older + gap))).coerceAtLeast(1) } val newestAt = if (rising) 0 @@ -166,7 +166,7 @@ private fun Stack(notifications: List) { val gap = with(density) { GAP.roundToPx() } val live = notifications.filterNot { it.dismissed } val oldest = live.firstOrNull()?.let { heights[it] } ?: 0 - val line = margin + ((1f - Look.notificationHeight) * (screen.height - margin * 2)).roundToInt() + val line = margin + ((1f - Look.notificationHeight) * (screen.height - (margin * 2))).roundToInt() val rising = Look.notificationFlow == NotificationFlow.Up val anchor = if (rising) line.coerceAtLeast(margin + oldest) @@ -229,7 +229,7 @@ private fun Toast( val screen = LocalWindowInfo.current.containerSize val margin = with(density) { MARGIN.toPx() } val width = with(density) { Look.notificationWidth.toPx() } - val reach = width + margin * 4 + val reach = width + (margin * 4) val leftSide = Look.notificationSide == NotificationSide.Left val entered = remember { Animatable(0f) } val placed = remember { Animatable(top.toFloat()) } diff --git a/src/main/kotlin/com/lambda/gui/Snap.kt b/src/main/kotlin/com/lambda/gui/Snap.kt index 951c69434..b56b48513 100644 --- a/src/main/kotlin/com/lambda/gui/Snap.kt +++ b/src/main/kotlin/com/lambda/gui/Snap.kt @@ -73,7 +73,7 @@ internal object Snap { val size = end(element) - from fun startAt(at: Float, guide: Float? = at) = Target(at - from, guide) fun endAt(at: Float, guide: Float? = at) = Target(at - size - from, guide) - fun centerAt(at: Float, guide: Float? = at) = Target(at - size / 2 - from, guide) + fun centerAt(at: Float, guide: Float? = at) = Target(at - (size / 2) - from, guide) val neighbours = buildList { @@ -81,8 +81,8 @@ internal object Snap { others.forEach { other -> add(startAt(start(other))) add(endAt(end(other))) - add(startAt(end(other) + spacing, end(other) + spacing / 2)) - add(endAt(start(other) - spacing, start(other) - spacing / 2)) + add(startAt(end(other) + spacing, end(other) + (spacing / 2))) + add(endAt(start(other) - spacing, start(other) - (spacing / 2))) } } if (GuiConfig.snapToCenters) others.forEach { add(centerAt(center(it))) } @@ -99,7 +99,7 @@ internal object Snap { val grid = listOf( startAt(onGrid(from), null), - centerAt(onGrid(from + size / 2), null), + centerAt(onGrid(from + (size / 2)), null), endAt(onGrid(from + size), null), ).takeIf { GuiConfig.snapToGrid }.orEmpty() diff --git a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt index e3aa97988..de9075d71 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/ClickGui.kt @@ -144,14 +144,14 @@ internal fun ClickGui() { (screenWidth - Look.windowWidth) / (inRow - 1).coerceAtLeast(1) ) .coerceAtLeast(0.dp) - val rowWidth = Look.windowWidth + pitch * (inRow - 1) + val rowWidth = Look.windowWidth + (pitch * (inRow - 1)) val rowStart = ((screenWidth - rowWidth) / 2).coerceAtLeast(0.dp) tags.forEachIndexed { index, tag -> key(tag) { CategoryWindow( tag = tag, - defaultPosition = DpOffset(rowStart + pitch * index, Look.windowTop), + defaultPosition = DpOffset(rowStart + (pitch * index), Look.windowTop), bounds = bounds, snapping = snapping, onDrop = { drop = it }, diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index 7c95218fd..b19fe45f5 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -109,7 +109,7 @@ internal fun SettingsPanel( val visibility = remember(LocalShown.current) { MutableTransitionState(false) } val window = windows[panel.module.tag] val beneath = window == null || row.top >= window.top - val hung = panel.placed && (panel.settled || panel.unfolding && beneath) + val hung = panel.placed && (panel.settled || (panel.unfolding && beneath)) val wanted = open && hung && !row.isEmpty val popups = remember { PopupHost() } SideEffect { popups.closing = !wanted } diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 0886e6df5..4060c506c 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -470,7 +470,7 @@ fun Suggestions( ScenePopup( popupPositionProvider = remember { positionProvider { anchor, window, popup -> - val centred = anchor.left + (anchor.width - popup.width) / 2 + val centred = anchor.left + ((anchor.width - popup.width) / 2) IntOffset( centred.coerceIn(0, (window.width - popup.width).coerceAtLeast(0)), anchor.bottom @@ -694,7 +694,7 @@ fun Dialog(onDismiss: (() -> Unit)?, content: @Composable BoxScope.(dismiss: () .graphicsLayer { val shown = opened.value alpha = shown - scaleX = DIALOG_ZOOM + (1f - DIALOG_ZOOM) * shown + scaleX = DIALOG_ZOOM + ((1f - DIALOG_ZOOM) * shown) scaleY = scaleX } .guiPresence() diff --git a/src/main/kotlin/com/lambda/gui/component/Surface.kt b/src/main/kotlin/com/lambda/gui/component/Surface.kt index 84a5cb693..fc61c71b0 100644 --- a/src/main/kotlin/com/lambda/gui/component/Surface.kt +++ b/src/main/kotlin/com/lambda/gui/component/Surface.kt @@ -96,7 +96,7 @@ fun Modifier.guiPresence(anchor: TransformOrigin? = null): Modifier = if (GuiTransition.Fade in styles) alpha = shown if (GuiTransition.Slide in styles && anchor == null) translationY = (shown - 1f) * GUI_SLIDE.toPx() if (GuiTransition.Zoom in styles) { - scaleX = GUI_ZOOM + (1f - GUI_ZOOM) * shown + scaleX = GUI_ZOOM + ((1f - GUI_ZOOM) * shown) scaleY = scaleX transformOrigin = anchor ?: TransformOrigin.Center } @@ -113,7 +113,7 @@ fun Modifier.glass(color: Color, shape: Shape, strength: () -> Float = { 1f }): if (amount <= 0f) return@drawBehind val backdrop = if (amount >= 1f) full - else backdropFilter(sigma * amount, 1f - (1f - underlay) * amount) + else backdropFilter(sigma * amount, 1f - ((1f - underlay) * amount)) if (backdrop != null) drawIntoCanvas { canvas -> canvas.skiaCanvas.saveLayer(Canvas.SaveLayerRec(Rect.makeWH(size.width, size.height), REPLACE, backdrop)) canvas.skiaCanvas.restore() @@ -151,8 +151,8 @@ private data class Inset(private val shape: Shape, private val inset: Dp) : Shap val edge = with(density) { inset.toPx() } val inner = Size( - (size.width - edge * 2).coerceAtLeast(0f), - (size.height - edge * 2).coerceAtLeast(0f) + (size.width - (edge * 2)).coerceAtLeast(0f), + (size.height - (edge * 2)).coerceAtLeast(0f) ) val path = Path().apply { addOutline(shape.createOutline(inner, layoutDirection, density)) } path.translate(Offset(edge, edge)) diff --git a/src/main/kotlin/com/lambda/gui/core/Frames.kt b/src/main/kotlin/com/lambda/gui/core/Frames.kt index 838f1d38a..4462ef3ba 100644 --- a/src/main/kotlin/com/lambda/gui/core/Frames.kt +++ b/src/main/kotlin/com/lambda/gui/core/Frames.kt @@ -22,7 +22,7 @@ import androidx.compose.runtime.withFrameNanos private const val NANOS_PER_MILLI = 1_000_000 suspend fun awaitFrames(millis: Long) { - val end = withFrameNanos { it } + millis * NANOS_PER_MILLI + val end = withFrameNanos { it } + (millis * NANOS_PER_MILLI) do { val now = withFrameNanos { it } } while (now < end) diff --git a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt index 6deb7c369..cc8596f2e 100644 --- a/src/main/kotlin/com/lambda/gui/core/SceneInput.kt +++ b/src/main/kotlin/com/lambda/gui/core/SceneInput.kt @@ -108,7 +108,7 @@ internal class SceneInput(private val scene: ComposeScene) { FocusDirection.Up, FocusDirection.Left -> FocusDirection.Previous else -> FocusDirection.Next } - return KeyboardFocus.move(direction) || direction != inOrder && KeyboardFocus.move(inOrder) + return KeyboardFocus.move(direction) || (direction != inOrder && KeyboardFocus.move(inOrder)) } fun type(codePoint: Int): Boolean = diff --git a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt index 94a73561a..9626a2f93 100644 --- a/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt +++ b/src/main/kotlin/com/lambda/gui/hud/HudEditor.kt @@ -139,7 +139,7 @@ internal class HudEditorState(snapping: State) { configuring = config if (config != null) panelPosition = position ?: Offset( - screen.width / 2 - 120 * density.density, + (screen.width / 2) - (120 * density.density), screen.height * 0.15f ) } diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index 428c4d91b..465be3dba 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -148,7 +148,7 @@ internal fun MenuBar(modifier: Modifier = Modifier) { .onSizeChanged { search = it } .offset { IntOffset( - (menus.width - (bar.width - search.width) / 2).coerceAtLeast(0), + (menus.width - ((bar.width - search.width) / 2)).coerceAtLeast(0), 0 ) } @@ -227,7 +227,7 @@ private fun SearchField(modifier: Modifier = Modifier) { } !open || results.isEmpty() -> false event.key == Key.DirectionDown || - event.key == Key.Tab && !event.isShiftPressed -> { + (event.key == Key.Tab && !event.isShiftPressed) -> { marked = (marked + 1).mod(results.size) true } diff --git a/src/main/kotlin/com/lambda/gui/menu/Search.kt b/src/main/kotlin/com/lambda/gui/menu/Search.kt index 17250b853..ca23bbbf9 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Search.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt @@ -140,14 +140,14 @@ internal object Search { 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 + if (target.startsWith(query)) return 100 + (query.length * 50 / target.length) + if (target.contains(query)) return 50 + (query.length * 40 / target.length) val distance = query.levenshteinDistance(target) val allowed = if (lenient) (query.length / 2).coerceIn(2, 6) else (query.length / 3).coerceIn(1, 4) - return if (distance <= allowed) (50 - distance * 10).coerceAtLeast(1) + return if (distance <= allowed) (50 - (distance * 10)).coerceAtLeast(1) else 0 } } diff --git a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt index 0b9248351..b016b9692 100644 --- a/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt +++ b/src/main/kotlin/com/lambda/gui/settings/ColorPicker.kt @@ -261,7 +261,7 @@ private fun AwtColor.toHex() = private fun parseHex(text: String): AwtColor? { val digits = text.removePrefix("#") if ( - digits.length != 6 && digits.length != 8 || + (digits.length != 6 && digits.length != 8) || digits.any { it.digitToIntOrNull(16) == null } ) { return null diff --git a/src/main/kotlin/com/lambda/module/HudModule.kt b/src/main/kotlin/com/lambda/module/HudModule.kt index f2d04733f..2395245e2 100644 --- a/src/main/kotlin/com/lambda/module/HudModule.kt +++ b/src/main/kotlin/com/lambda/module/HudModule.kt @@ -72,7 +72,7 @@ abstract class HudModule( var shownScreen = IntSize.Zero var anchorX by floatSetting("HUD X", defaultAnchorX, 0f..1f, 0.001f) { false } - var anchorY by floatSetting("HUD Y", defaultAnchorY ?: (DEFAULT_ANCHOR + DEFAULT_SPACING * created++).coerceAtMost(1f), 0f..1f, 0.001f) { false } + var anchorY by floatSetting("HUD Y", defaultAnchorY ?: (DEFAULT_ANCHOR + (DEFAULT_SPACING * created++)).coerceAtMost(1f), 0f..1f, 0.001f) { false } @Composable abstract fun Content() 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 0b1c70779..d7c3ac6ca 100644 --- a/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt +++ b/src/main/kotlin/com/lambda/module/modules/hud/Tps.kt @@ -91,7 +91,7 @@ object Tps : HudModule( val path = Path() points.forEachIndexed { index, value -> val x = index * size.width / (points.size - 1) - val y = size.height - (value - min) / range * size.height + 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/resources/assets/lambda/shaders/core/gui_composite.fsh b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh index 59c78f3ce..e33bd6bfc 100644 --- a/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh +++ b/src/main/resources/assets/lambda/shaders/core/gui_composite.fsh @@ -31,10 +31,10 @@ void main() { if (GlowIntensity > 0.0) { float glowMask = clamp(texture(GlowSampler, texCoord).a * 2.0, 0.0, 1.0); float glow = clamp(pow(glowMask, 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); + 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 - blurred); } - vec4 over = gui + under * (1.0 - gui.a); - fragColor = over + vec4(DIM_COLOR, 1.0) * Dim * (1.0 - over.a); + vec4 over = gui + (under * (1.0 - gui.a)); + fragColor = over + (vec4(DIM_COLOR, 1.0) * Dim * (1.0 - over.a)); } From be2b4ec847dac916dbbf296ad97a61b5c79f7494 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:19:13 +0000 Subject: [PATCH 30/34] fix right click context menu's potentially shifting element position --- .../com/lambda/gui/component/TextInput.kt | 49 +++++++++---------- .../com/lambda/gui/settings/SettingRow.kt | 11 ++--- 2 files changed, 29 insertions(+), 31 deletions(-) diff --git a/src/main/kotlin/com/lambda/gui/component/TextInput.kt b/src/main/kotlin/com/lambda/gui/component/TextInput.kt index 44bc6d065..2a4df4baf 100644 --- a/src/main/kotlin/com/lambda/gui/component/TextInput.kt +++ b/src/main/kotlin/com/lambda/gui/component/TextInput.kt @@ -181,34 +181,33 @@ fun TextInput( ) } innerTextField() - } - } - ) - - rememberLast(menu)?.let { position -> - key(position) { - ContextMenu(menu != null, position, onDismiss = { menu = null }) { - val selected = !field.selection.collapsed - MenuItem("Cut", enabled = selected) { - mc.keyboard.clipboard = field.selected - edit(field.replacingSelection("")) - } - MenuItem("Copy", enabled = selected) { mc.keyboard.clipboard = field.selected } - MenuItem("Paste", enabled = mc.keyboard.clipboard.isNotEmpty()) { - val pasted = mc.keyboard.clipboard - edit( - field.replacingSelection( - if (singleLine) pasted.filterNot { it == '\n' || it == '\r' } - else pasted - ) - ) - } - MenuItem("Select All", enabled = field.text.isNotEmpty()) { - field = field.copy(selection = TextRange(0, field.text.length)) + rememberLast(menu)?.let { position -> + key(position) { + ContextMenu(menu != null, position, onDismiss = { menu = null }) { + val selected = !field.selection.collapsed + MenuItem("Cut", enabled = selected) { + mc.keyboard.clipboard = field.selected + edit(field.replacingSelection("")) + } + MenuItem("Copy", enabled = selected) { mc.keyboard.clipboard = field.selected } + MenuItem("Paste", enabled = mc.keyboard.clipboard.isNotEmpty()) { + val pasted = mc.keyboard.clipboard + edit( + field.replacingSelection( + if (singleLine) pasted.filterNot { it == '\n' || it == '\r' } + else pasted + ) + ) + } + MenuItem("Select All", enabled = field.text.isNotEmpty()) { + field = field.copy(selection = TextRange(0, field.text.length)) + } + } + } } } } - } + ) } private val TextFieldValue.selected get() = text.substring(selection.min, selection.max) diff --git a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt index 5517b8c13..3260d7733 100644 --- a/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt +++ b/src/main/kotlin/com/lambda/gui/settings/SettingRow.kt @@ -153,12 +153,11 @@ fun SettingRow(setting: Setting<*>) { key(setting) { setting.Gui() } } } - } - - rememberLast(menu)?.let { position -> - key(position) { - ContextMenu(menu != null, position, onDismiss = { menu = null }) { - MenuItem("Reset") { setting.reset(silent = true) } + rememberLast(menu)?.let { position -> + key(position) { + ContextMenu(menu != null, position, onDismiss = { menu = null }) { + MenuItem("Reset") { setting.reset(silent = true) } + } } } } From d212aab548ccdf85458d2fca5436fdeb00dd0547 Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:46:42 +0000 Subject: [PATCH 31/34] lazy search --- .../kotlin/com/lambda/gui/component/Popups.kt | 30 ++++++++--- .../kotlin/com/lambda/gui/menu/MenuBar.kt | 54 ++++++++++++------- src/main/kotlin/com/lambda/gui/menu/Search.kt | 31 ++++++++--- 3 files changed, 81 insertions(+), 34 deletions(-) diff --git a/src/main/kotlin/com/lambda/gui/component/Popups.kt b/src/main/kotlin/com/lambda/gui/component/Popups.kt index 4060c506c..270d8cf6f 100644 --- a/src/main/kotlin/com/lambda/gui/component/Popups.kt +++ b/src/main/kotlin/com/lambda/gui/component/Popups.kt @@ -43,6 +43,11 @@ 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.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.LazyListState +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.CompositionLocalProvider @@ -88,6 +93,7 @@ import androidx.compose.ui.layout.positionInWindow import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize @@ -452,7 +458,9 @@ private class UnfoldingPosition( fun Suggestions( open: Boolean, onDismiss: () -> Unit, - content: @Composable ColumnScope.() -> Unit + width: Dp, + list: LazyListState = rememberLazyListState(), + content: LazyListScope.() -> Unit ) { if (!LocalShown.current) { if (open) SideEffect(onDismiss) @@ -495,13 +503,21 @@ fun Suggestions( Alignment.Top ), ) { - ScrollColumn( - modifier = Modifier + Box( + Modifier + .width(width) .heightIn(max = screenHeight * 0.6f) - .width(IntrinsicSize.Max) - .animateContentSize(Motion.panels), - content = content - ) + .animateContentSize(Motion.panels) + ) { + LazyColumn( + state = list, + modifier = Modifier.fillMaxWidth().wheelScrollable(list), + content = content + ) + if (list.canScrollForward || list.canScrollBackward) { + Scrollbar(rememberScrollbarAdapter(list), Modifier.matchParentSize()) + } + } } } } diff --git a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt index 465be3dba..894232f41 100644 --- a/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt +++ b/src/main/kotlin/com/lambda/gui/menu/MenuBar.kt @@ -31,9 +31,9 @@ import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.relocation.BringIntoViewRequester -import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -114,6 +114,8 @@ import java.util.* internal val MENU_BAR_HEIGHT = 15.dp private val ICON_SIZE = 9.dp private val SEARCH_WIDTH = 150.dp +private val RESULTS_WIDTH = 260.dp +private val RESULT_GAP = 10.dp @Composable internal fun MenuBar(modifier: Modifier = Modifier) { @@ -204,6 +206,10 @@ private fun SearchField(modifier: Modifier = Modifier) { val open = listed && query.isNotBlank() val shown = rememberLast(results.takeIf { open }).orEmpty() var marked by remember(results) { mutableStateOf(0) } + val list = rememberLazyListState() + LaunchedEffect(results, marked) { + if (open) list.reveal(marked) + } fun choose(result: Search.Result) { query = "" @@ -248,9 +254,9 @@ private fun SearchField(modifier: Modifier = Modifier) { modifier = Modifier.width(SEARCH_WIDTH).focusRequester(field), placeholder = "Search modules and settings", ) - Suggestions(open, onDismiss = { listed = false }) { - if (shown.isEmpty()) MenuLabel("Nothing found") - shown.forEachIndexed { index, result -> + Suggestions(open, onDismiss = { listed = false }, RESULTS_WIDTH, list) { + if (shown.isEmpty()) item { MenuLabel("Nothing found") } + itemsIndexed(shown) { index, result -> ResultRow( result, marked = index == marked, @@ -263,6 +269,20 @@ private fun SearchField(modifier: Modifier = Modifier) { } } +private suspend fun LazyListState.reveal(index: Int) { + val rows = layoutInfo.visibleItemsInfo + val height = layoutInfo.viewportEndOffset - layoutInfo.viewportStartOffset + val row = rows.firstOrNull { it.index == index } + val rowHeight = (row ?: rows.firstOrNull())?.size ?: 0 + val first = rows.firstOrNull()?.index ?: 0 + when { + row == null && index < first -> scrollToItem(index) + row == null -> scrollToItem(index, rowHeight - height) + row.offset < 0 -> scrollToItem(index) + row.offset + row.size > height -> scrollToItem(index, rowHeight - height) + } +} + @Composable private fun ResultRow( result: Search.Result, @@ -271,17 +291,11 @@ private fun ResultRow( onClick: () -> Unit ) { val colors = LambdaTheme.colors - val intoView = remember { BringIntoViewRequester() } - LaunchedEffect(marked) { - if (marked) intoView.bringIntoView() - } val point by rememberUpdatedState(onPoint) Row( verticalAlignment = Centered.VERTICALLY, modifier = Modifier .fillMaxWidth() - .widthIn(min = SEARCH_WIDTH) - .bringIntoViewRequester(intoView) .background(if (marked) colors.controlSelected else Color.Transparent) .pointerInput(Unit) { awaitPointerEventScope { @@ -294,13 +308,15 @@ private fun ResultRow( .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 - ) + Spacer(Modifier.width(RESULT_GAP)) + Box(Modifier.weight(1f), contentAlignment = Centered.END) { + Text( + result.origin, + color = colors.onSurfaceVariant, + style = Type.label, + maxLines = 1 + ) + } } } diff --git a/src/main/kotlin/com/lambda/gui/menu/Search.kt b/src/main/kotlin/com/lambda/gui/menu/Search.kt index ca23bbbf9..96ed54b6f 100644 --- a/src/main/kotlin/com/lambda/gui/menu/Search.kt +++ b/src/main/kotlin/com/lambda/gui/menu/Search.kt @@ -22,6 +22,8 @@ import com.lambda.command.CommandRegistry import com.lambda.command.LambdaCommand import com.lambda.config.Config import com.lambda.config.ConfigLoader +import com.lambda.config.automation.AutomationConfig +import com.lambda.config.automation.UserAutomationConfig import com.lambda.config.entries.Setting import com.lambda.gui.GuiScreen import com.lambda.gui.Reveal @@ -66,28 +68,38 @@ internal object Search { } } - private const val MAX_RESULTS = 30 - private const val MODULE_BONUS = 300 private const val HUD_MODULE_BONUS = 270 private const val COMMAND_BONUS = 200 + private const val OWN_PLACE = 0 + private const val SHARED_AUTOMATION_PLACE = 1 + private const val MODULE_AUTOMATION_PLACE = 2 + private val chatReachable get() = mc.world != null && !GuiScreen.isOverScreen 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 } + .sortedWith(compareByDescending { it.score }.thenBy { it.place }) + .map { it.result } } - private fun rank(query: String, lenient: Boolean): List> = + private class Ranked(val result: Result, val score: Int, val place: Int) + + private fun place(config: Config) = + when { + config !is AutomationConfig -> OWN_PLACE + config === AutomationConfig.DEFAULT || config is UserAutomationConfig -> SHARED_AUTOMATION_PLACE + else -> MODULE_AUTOMATION_PLACE + } + + private fun rank(query: String, lenient: Boolean): List = buildList { - fun consider(result: () -> Result, bonus: Int, vararg names: String) { + fun consider(result: () -> Result, bonus: Int, place: Int, vararg names: String) { val score = names.maxOf { score(query, it.lowercase(), lenient) } - if (score > 0) add(result() to score + bonus) + if (score > 0) add(Ranked(result(), score + bonus, place)) } fun hidden(config: Any) = @@ -100,6 +112,7 @@ internal object Search { consider( { Result.OfModule(module) }, if (module is HudModule) HUD_MODULE_BONUS else MODULE_BONUS, + OWN_PLACE, module.name, module.tag.name ) @@ -109,6 +122,7 @@ internal object Search { consider( { Result.OfCommand(command) }, COMMAND_BONUS, + OWN_PLACE, command.name, *command.aliases.toTypedArray() ) @@ -129,6 +143,7 @@ internal object Search { ) }, 0, + place(config), setting.name ) } From 736c6509d8c1cc441a3ac7682eae534b0f13b2da Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:11:20 +0000 Subject: [PATCH 32/34] default to showing hud in screens only from the minecraft package and fix AutoUpdater prompting even if you're using the loader already --- src/main/kotlin/com/lambda/gui/LambdaGui.kt | 9 ++++++-- src/main/kotlin/com/lambda/gui/hud/Hud.kt | 9 ++++++-- .../module/modules/client/AutoUpdater.kt | 22 ++++++++++++++----- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/src/main/kotlin/com/lambda/gui/LambdaGui.kt b/src/main/kotlin/com/lambda/gui/LambdaGui.kt index 2e5be7ce0..8a8451dcc 100644 --- a/src/main/kotlin/com/lambda/gui/LambdaGui.kt +++ b/src/main/kotlin/com/lambda/gui/LambdaGui.kt @@ -55,7 +55,9 @@ import com.lambda.gui.core.LocalShown import com.lambda.gui.core.Observations import com.lambda.gui.core.SceneHost import com.lambda.gui.core.SceneInput +import com.lambda.gui.core.observe import com.lambda.gui.hud.Hud +import com.lambda.gui.hud.HudConfig import com.lambda.gui.hud.HudEditor import com.lambda.gui.hud.HudLayer import com.lambda.gui.render.GuiCompositor @@ -125,6 +127,8 @@ object LambdaGui : Loadable { get() = GuiConfig.animations && GuiConfig.openAnimation && GuiTransition.Unfold in GuiConfig.openStyle + private val showsHudLayer + get() = screen == null || (screen == Screen.ClickGui && HudConfig.showInClickGui) private val showsClickGui get() = screen == Screen.ClickGui || leaving internal val foldsClosed @@ -227,7 +231,7 @@ object LambdaGui : Loadable { aboveHud.collect() beneathGui.collect(showsGui) aboveGui.collect(showsGui) - val showsHud = !beneathHud.isEmpty || !aboveHud.isEmpty || (screen == null && Hud.shown.isNotEmpty()) + val showsHud = !beneathHud.isEmpty || !aboveHud.isEmpty || (showsHudLayer && Hud.shown.isNotEmpty()) if (!showsGui && !showsHud && settled) return layered = showsGui && showsHud @@ -323,7 +327,8 @@ object LambdaGui : Loadable { Underlay { beneathHud.Content() - if (screen == null) HudLayer() + val hudShown by observe { showsHudLayer } + if (hudShown) HudLayer() aboveHud.Content() } beneathGui.Content() diff --git a/src/main/kotlin/com/lambda/gui/hud/Hud.kt b/src/main/kotlin/com/lambda/gui/hud/Hud.kt index 35f931688..727ceac74 100644 --- a/src/main/kotlin/com/lambda/gui/hud/Hud.kt +++ b/src/main/kotlin/com/lambda/gui/hud/Hud.kt @@ -57,13 +57,16 @@ import com.lambda.gui.theme.Type import com.lambda.module.HudModule import com.lambda.module.ModuleRegistry import com.lambda.util.math.toCompose +import net.minecraft.client.gui.screen.Screen import kotlin.math.roundToInt private val HUD_TEXT_SHADOW = Color.Black.copy(alpha = 0.75f) private val ELEMENT_PADDING = 1.dp +private const val VANILLA_PACKAGE = "net.minecraft." object HudConfig : Loadable, Config("HUD", HudCategory) { - val showInScreens by boolSetting("Show In Screens", false, "Keep HUD elements drawn while a Minecraft screen (inventory, mod settings, ...) is open. The HUD editor always shows them.") + val showInScreens by boolSetting("Show In Screens", true, "Keep HUD elements drawn while one of Minecraft's own screens (inventory, chat, pause menu, ...) is open. Screens added by other mods always hide them, and the HUD editor always shows them.") + val showInClickGui by boolSetting("Show In Click GUI", false, "Keep HUD elements drawn behind the click GUI while it is open") val textColor by colorSetting("Text Color", java.awt.Color.WHITE, "Colour of HUD text") val scale by floatSetting("Scale", 1f, 0.5f..3f, 0.05f, "Size of HUD text") } @@ -74,10 +77,12 @@ internal object Hud { val enabled: List get() = modules.filter { it.isEnabled } + private val Screen.isVanilla get() = javaClass.name.startsWith(VANILLA_PACKAGE) + val shown: List get() { val screen = mc.currentScreen - val covered = screen != null && screen !is GuiScreen && !HudConfig.showInScreens + val covered = screen != null && screen !is GuiScreen && !(HudConfig.showInScreens && screen.isVanilla) return if (mc.world == null || mc.options.hudHidden || covered) emptyList() else enabled } 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 2aa41ce5c..76383c4f3 100644 --- a/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt +++ b/src/main/kotlin/com/lambda/module/modules/client/AutoUpdater.kt @@ -20,6 +20,8 @@ package com.lambda.module.modules.client import com.lambda.Lambda.mc import com.lambda.config.settings.comparable.boolSetting import com.lambda.config.settings.comparable.enumSetting +import com.lambda.event.events.ClientEvent +import com.lambda.event.listener.UnsafeListener.Companion.listenUnsafe import com.lambda.gui.LambdaGui import com.lambda.module.Module import com.lambda.module.ModuleTag @@ -50,6 +52,7 @@ object AutoUpdater : Module( private set private var firstLaunchStateInitialized = false + private const val LOADER_ID = "lambda-loader" private const val MAVEN_URL = "https://maven.lambda-client.org" private const val LOADER_STABLE_META = "$MAVEN_URL/stable/com/lambda/lambda-loader/maven-metadata.xml" private const val LOADER_DEV_META = "$MAVEN_URL/dev/com/lambda/lambda-loader/maven-metadata.xml" @@ -61,16 +64,25 @@ object AutoUpdater : Module( Dev } - init { - onEnableUnsafe { prompt = Prompt.Install.takeIf { LambdaGui.screen != null && prompt != Prompt.Uninstall } } - onDisableUnsafe { prompt = Prompt.Uninstall.takeIf { LambdaGui.screen != null && prompt != Prompt.Install } } + private val usesLoader get() = FabricLoader.getInstance().isModLoaded(LOADER_ID) + + init { + onEnableUnsafe { + prompt = Prompt.Install.takeIf { LambdaGui.screen != null && prompt != Prompt.Uninstall && !usesLoader } + } + onDisableUnsafe { + prompt = Prompt.Uninstall.takeIf { LambdaGui.screen != null && prompt != Prompt.Install && usesLoader } + } + listenUnsafe(alwaysListen = true) { + if (usesLoader) loaderPromptHandled = true + } } internal fun onGuiOpened() { if (firstLaunchStateInitialized) return firstLaunchStateInitialized = true - if (FabricLoader.getInstance().isModLoaded("lambda-loader")) { + if (usesLoader) { loaderPromptHandled = true if (!isEnabled) enable() return @@ -137,7 +149,7 @@ object AutoUpdater : Module( return@runIO } - val loaderJarPath = getModJarPath("lambda-loader") + val loaderJarPath = getModJarPath(LOADER_ID) if (debug) debug("Lambda loader JAR path: $loaderJarPath") val jarFile = loaderJarPath.toFile() From 7f2cb1b1fbc004ad6f16ec60ac26e982342e088b Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:48:40 +0000 Subject: [PATCH 33/34] prevent excess re-measuring due to sliding text --- src/main/kotlin/com/lambda/gui/component/SlidingText.kt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt index c4f5a9c9b..527182afa 100644 --- a/src/main/kotlin/com/lambda/gui/component/SlidingText.kt +++ b/src/main/kotlin/com/lambda/gui/component/SlidingText.kt @@ -94,11 +94,12 @@ fun SlidingText( .clipToBounds() .layout { measurable, constraints -> val placeable = measurable.measure(constraints.copy(maxWidth = Constraints.Infinity)) - overflow = + val over = if (constraints.hasBoundedWidth) (placeable.width - constraints.maxWidth).coerceAtLeast(0) else 0 - layout(placeable.width - overflow, placeable.height) { - placeable.place(-(slide.value * overflow).roundToInt(), 0) + if (constraints.hasBoundedWidth) overflow = over + layout(placeable.width - over, placeable.height) { + placeable.place(-(slide.value * over).roundToInt(), 0) } } ) From 666f885b58f9cd1626687583b0bde0fd3e3230dd Mon Sep 17 00:00:00 2001 From: beanbag44 <107891830+beanbag44@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:12:17 +0000 Subject: [PATCH 34/34] resizable width for setting panels --- .../com/lambda/gui/clickgui/OpenSettings.kt | 1 + .../com/lambda/gui/clickgui/SettingsPanel.kt | 76 +++++++++++++++++-- .../com/lambda/gui/core/ScenePlatform.kt | 3 + 3 files changed, 72 insertions(+), 8 deletions(-) diff --git a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt index 2349459d9..895722867 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/OpenSettings.kt @@ -31,6 +31,7 @@ import com.lambda.module.Module internal class SettingsPanelState(val module: Module) { var page by mutableStateOf(PanelPage.Settings) var extension by mutableStateOf(0.dp) + var widening by mutableStateOf(0.dp) var row by mutableStateOf(Rect.Zero) var placed by mutableStateOf(false) var unfolding by mutableStateOf(false) diff --git a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt index b19fe45f5..08a4b05e3 100644 --- a/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt +++ b/src/main/kotlin/com/lambda/gui/clickgui/SettingsPanel.kt @@ -29,14 +29,17 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight 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.layout.wrapContentWidth import androidx.compose.foundation.relocation.BringIntoViewRequester import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.rememberScrollState @@ -46,6 +49,7 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -79,6 +83,7 @@ import com.lambda.gui.component.dropShadow import com.lambda.gui.component.mouseDraggable import com.lambda.gui.component.window import com.lambda.gui.core.LocalShown +import com.lambda.gui.core.ResizeHorizontalIcon import com.lambda.gui.core.ResizeVerticalIcon import com.lambda.gui.core.awaitFrames import com.lambda.gui.menu.MENU_BAR_HEIGHT @@ -124,6 +129,7 @@ internal fun SettingsPanel( val screen = LocalWindowInfo.current.containerSize var size by remember { mutableStateOf(IntSize.Zero) } var unfolded by remember { mutableStateOf(0) } + var natural by remember { mutableIntStateOf(0) } val scroll = rememberScrollState() val screenHeight = with(density) { screen.height.toDp() } @@ -147,6 +153,13 @@ internal fun SettingsPanel( val fitsLeft = row.left + overlap - size.width >= 0 val flipped = !fitsRight && (fitsLeft || row.left > screen.width - row.right) val lift = (top + unfolded - screen.height).coerceIn(0f, top - barBottom) + val widest = Look.settingsWidth + panel.widening + val beside = + with(density) { + if (flipped) (row.left + overlap).toDp() + else (screen.width - row.right + overlap).toDp() + } + val unmet = (with(density) { natural.toDp() } - Look.settingsWidth).coerceAtLeast(0.dp) val shape = RoundedCornerShape( @@ -184,9 +197,9 @@ internal fun SettingsPanel( ) { Box( Modifier - .widthIn(MIN_PANEL_WIDTH, Look.settingsWidth) + .widthIn(MIN_PANEL_WIDTH, widest) .heightIn(max = maxHeight) - .widthOfContent() + .widthOfContent { natural = it } .onSizeChanged { size = it } ) { CompositionLocalProvider(LocalPopupHost provides popups) { @@ -217,6 +230,26 @@ internal fun SettingsPanel( modifier = Modifier.align(Alignment.TopCenter) ) } + if (unmet > panel.widening || panel.widening > 0.dp) { + SideGrip( + onDragStart = { panel.widening = panel.widening.coerceAtMost(unmet) }, + onDrag = { right -> + val outwards = + if (flipped) -right + else right + panel.widening = + (panel.widening + outwards).coerceIn( + 0.dp, + unmet + .coerceAtMost(beside - Look.settingsWidth) + .coerceAtLeast(0.dp) + ) + }, + modifier = Modifier + .matchParentSize() + .wrapContentWidth(if (flipped) Alignment.Start else Alignment.End) + ) + } } } } @@ -263,22 +296,27 @@ internal fun InlineSettings(panel: SettingsPanelState, open: Boolean) { } } -internal fun Modifier.widthOfContent(): Modifier = +internal fun Modifier.widthOfContent(onNatural: (Int) -> Unit = {}): Modifier = composed { val scope = rememberCoroutineScope() var width by remember { mutableStateOf?>(null) } + var cap by remember { mutableIntStateOf(0) } layout { measurable, constraints -> - val wanted = - measurable.maxIntrinsicWidth(constraints.maxHeight) - .coerceIn(constraints.minWidth, constraints.maxWidth).toFloat() - val current = width ?: Animatable(wanted).also { width = it } + val natural = measurable.maxIntrinsicWidth(constraints.maxHeight) + if (constraints.hasBoundedWidth) onNatural(natural) + val wanted = natural.coerceIn(constraints.minWidth, constraints.maxWidth).toFloat() + val resized = constraints.hasBoundedWidth && constraints.maxWidth != cap + if (resized) cap = constraints.maxWidth + val current = width?.takeUnless { resized } ?: Animatable(wanted).also { width = it } if (current.targetValue != wanted) { scope.launch { current.animateTo(wanted, WIDTH_CHANGE) } } val placeable = measurable.measure( - Constraints.fixedWidth(current.value.roundToInt()).copy( + Constraints.fixedWidth( + current.value.roundToInt().coerceIn(constraints.minWidth, constraints.maxWidth) + ).copy( maxHeight = constraints.maxHeight ) ) @@ -307,3 +345,25 @@ private fun Grip( Spacer(Modifier.size(16.dp, 1.dp).background(color, RoundedCornerShape(50))) } } + +@Composable +private fun SideGrip( + onDragStart: () -> Unit, + onDrag: (right: Dp) -> Unit, + modifier: Modifier = Modifier +) { + val density = LocalDensity.current + val color = LambdaTheme.colors.onSurfaceVariant + Box( + contentAlignment = Centered.BOTH, + modifier = modifier + .fillMaxHeight() + .width(Look.panelPadding.coerceAtLeast(MIN_GRIP_HEIGHT)) + .pointerHoverIcon(ResizeHorizontalIcon) + .mouseDraggable(onDragStart = onDragStart) { delta -> + onDrag(with(density) { delta.x.toDp() }) + } + ) { + Spacer(Modifier.size(1.dp, 16.dp).background(color, RoundedCornerShape(50))) + } +} diff --git a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt index 9afa78de6..de8e93bca 100644 --- a/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt +++ b/src/main/kotlin/com/lambda/gui/core/ScenePlatform.kt @@ -61,6 +61,7 @@ internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { PointerIcon.Hand -> StandardCursors.POINTING_HAND PointerIcon.Crosshair -> StandardCursors.CROSSHAIR ResizeVerticalIcon -> StandardCursors.RESIZE_NS + ResizeHorizontalIcon -> StandardCursors.RESIZE_EW else -> null } } @@ -68,6 +69,8 @@ internal class ScenePlatform : PlatformContext by PlatformContext.Empty() { object ResizeVerticalIcon : PointerIcon +object ResizeHorizontalIcon : PointerIcon + @OptIn(ExperimentalComposeUiApi::class) internal object GameClipboard : Clipboard { @Suppress("OVERRIDE_DEPRECATION")