diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java index 9a027c00ee..ce55834deb 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java @@ -27,6 +27,7 @@ //~ gui_graphics package org.polyfrost.oneconfig.internal; +import java.util.function.BooleanSupplier; import com.mojang.brigadier.Command; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; @@ -193,6 +194,8 @@ private static boolean isHudEditor(Object screen) { } private static boolean isTabListVisible() { + BooleanSupplier override = HudManager.tabListVisibility; + if (override != null) return override.getAsBoolean(); Minecraft minecraft = Minecraft.getInstance(); if (!minecraft.options.keyPlayerList.isDown()) return false; if (minecraft.level == null || minecraft.player == null) return false; @@ -347,6 +350,8 @@ private static void registerEventHandlers() { EventManager.register(WorldEvent.Load.class, e -> { showFirstLaunchNotification(); }); + // leaving a world or server ends any temporary visibility flip + EventManager.register(WorldEvent.Unload.class, e -> HudManager.resetVisibilityKeys()); // after loading finishes so translation keys are available EventManager.register(ResourceFinishedLoading.class, e -> SearchCorpus.INSTANCE.init()); EventManager.register(ResourceFinishedLoading.class, e -> CompatLoader.INSTANCE.onResourcesLoaded()); diff --git a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/LegacyHudRenderer.kt b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/LegacyHudRenderer.kt index c8ffdd2bd7..f2b3556032 100644 --- a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/LegacyHudRenderer.kt +++ b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/LegacyHudRenderer.kt @@ -63,8 +63,9 @@ object LegacyHudRenderer { for (hud in HudManager.activeInstances) { if (hud !is LegacyHud) continue if (!HudManager.isEditing) { - if (hud.hidden) continue + if (hud.effectivelyHidden && !hud.drawsWhileHidden()) continue if (HudManager.isGuiHidden) continue + if (HudManager.allHudsHiddenByKey) continue if (HudManager.isDebugScreenVisible && !hud.showInF3) continue if (HudManager.isTabListVisible && !hud.showInTab) continue if (!HudManager.overrideShowInScreens) { diff --git a/minecraft/src/main/resources/assets/oneconfig/lang/en_us.json b/minecraft/src/main/resources/assets/oneconfig/lang/en_us.json index 12119e6d59..eb9a4443b0 100644 --- a/minecraft/src/main/resources/assets/oneconfig/lang/en_us.json +++ b/minecraft/src/main/resources/assets/oneconfig/lang/en_us.json @@ -52,6 +52,17 @@ "oneconfig.preferences.hud_marquee_anim_duration.title": "Selection Box Animation Duration (ms)", "oneconfig.preferences.hud_marquee_anim_duration.description": "The duration of the fade animation for the drag selection rectangle in milliseconds.", + "oneconfig.preferences.category.huds": "HUDs", + "oneconfig.preferences.hud_toggle_all_keybind.title": "Hide All HUDs", + "oneconfig.preferences.hud_toggle_all_keybind.description": "Temporarily hides every HUD. Each HUD can also have its own key in its Visibility settings.", + "oneconfig.preferences.hud_toggle_all_mode.title": "Hide All HUDs Mode", + "oneconfig.preferences.hud_toggle_all_mode.description": "Held hides HUDs only while the key is held. Toggle switches them on each press. Quick Press switches on a tap and switches back when a longer hold is released.", + "oneconfig.preferences.hud_toggle_all_hold_threshold.title": "Hold Threshold (ms)", + "oneconfig.preferences.hud_toggle_all_hold_threshold.description": "How long the key must be held in Quick Press mode before releasing it switches back.", + "oneconfig.preferences.key_mode.held": "Held", + "oneconfig.preferences.key_mode.toggle": "Toggle", + "oneconfig.preferences.key_mode.quick_press": "Quick Press", + "oneconfig.preferences.background_blur.title": "Background Blur", "oneconfig.preferences.background_blur.description": "Blurs the full game background when the OneConfig menu is open.", "oneconfig.preferences.reduced_motion.title": "Reduced Motion", diff --git a/modules/hud/api/hud.api b/modules/hud/api/hud.api index abff455fcd..64be93c8ef 100644 --- a/modules/hud/api/hud.api +++ b/modules/hud/api/hud.api @@ -48,6 +48,7 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one protected final fun contentChanged ()V public fun defaultPosition ()Lkotlin/Pair; public fun deletable ()Z + public fun drawsWhileHidden ()Z public final fun getAlignment ()Lorg/polyfrost/compose/layout/PolyAlign; public fun getAlwaysRedraw ()Z public final fun getAnchorOffsetX ()F @@ -78,12 +79,14 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one public final fun getEffectiveGrowthAnchor ()Lorg/polyfrost/oneconfig/api/hud/v1/HudAnchor; public final fun getEffectiveScale ()F public final fun getEffectiveSelfAnchorPoint ()Lorg/polyfrost/oneconfig/api/hud/v1/HudAnchor; + public final fun getEffectivelyHidden ()Z public fun getExternalPlacement ()Lorg/polyfrost/oneconfig/api/hud/v1/ExternalPlacement; public final fun getFont ()Lorg/polyfrost/oneconfig/api/hud/v1/Font; public final fun getFullShadow ()Z public final fun getGrowthAnchor ()Lorg/polyfrost/oneconfig/api/hud/v1/HudAnchor; public final fun getHasBeenMoved ()Z public fun getHidden ()Z + public fun getHudEnabled ()Z public final fun getKeepBgWhenHidden ()Z public fun getLocked ()Z public final fun getMergeAcrossColours ()Z @@ -122,7 +125,7 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one public final fun getShowInF3 ()Z public final fun getShowInScreens ()Z public final fun getShowInTab ()Z - public final fun getShowKey ()I + public final synthetic fun getShowKey ()I public final fun getShowShadow ()Z public fun getStaticH ()F public fun getStaticW ()F @@ -137,13 +140,19 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one public final fun getTextScale ()F public final fun getTextUnderline ()Z public final fun getTextWeight ()Lorg/polyfrost/oneconfig/api/hud/v1/Weight; - public final fun getToggleKey ()I + public final synthetic fun getToggleKey ()I public final fun getToggleKeybind ()Lorg/polyfrost/oneconfig/api/ui/v1/keybind/OneConfigKeybind; public final fun getUseGuiScale ()Z + public final fun getVisibilityKeyActive ()Z + public final fun getVisibilityKeyHoldThreshold ()I + public final fun getVisibilityKeyMode ()Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode; + public final fun getVisibilityKeybind ()Lorg/polyfrost/oneconfig/api/ui/v1/keybind/OneConfigKeybind; public fun getX ()F public fun getY ()F public fun hasBackground ()Z public fun hasBorder ()Z + public fun hasVisibilityKeyMode ()Z + public fun hasVisibilityKeybind ()Z public final fun hudBackground ()Lorg/polyfrost/compose/composables/PolyModifier; public final fun hudBackground (Lorg/polyfrost/compose/composables/PolyModifier;)Lorg/polyfrost/compose/composables/PolyModifier; public static synthetic fun hudBackground$default (Lorg/polyfrost/oneconfig/api/hud/v1/Hud;Lorg/polyfrost/compose/composables/PolyModifier;ILjava/lang/Object;)Lorg/polyfrost/compose/composables/PolyModifier; @@ -163,6 +172,7 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one public final fun reseedStaticHeight ()V public final fun reseedStaticSizeIfNeeded ()V public final fun reseedStaticWidth ()V + public fun resetVisibilityKey ()V public final fun setAbsolutePosition (FF)V public final fun setAlignment (Lorg/polyfrost/compose/layout/PolyAlign;)V public final fun setAnchorOffsetX (F)V @@ -188,6 +198,7 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one public final fun setGrowthAnchor (Lorg/polyfrost/oneconfig/api/hud/v1/HudAnchor;)V public final fun setGrowthAnchorKeepingPosition (Lorg/polyfrost/oneconfig/api/hud/v1/HudAnchor;)V public fun setHidden (Z)V + public fun setHudEnabled (Z)V public final fun setKeepBgWhenHidden (Z)V public final fun setLayoutRefH (F)V public final fun setLayoutRefW (F)V @@ -217,7 +228,7 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one public final fun setShowInF3 (Z)V public final fun setShowInScreens (Z)V public final fun setShowInTab (Z)V - public final fun setShowKey (I)V + public final synthetic fun setShowKey (I)V public final fun setShowShadow (Z)V public fun setStaticH (F)V public fun setStaticW (F)V @@ -232,9 +243,12 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one public final fun setTextScale (F)V public final fun setTextUnderline (Z)V public final fun setTextWeight (Lorg/polyfrost/oneconfig/api/hud/v1/Weight;)V - public final fun setToggleKey (I)V + public final synthetic fun setToggleKey (I)V public final fun setToggleKeybind (Lorg/polyfrost/oneconfig/api/ui/v1/keybind/OneConfigKeybind;)V public final fun setUseGuiScale (Z)V + public final fun setVisibilityKeyHoldThreshold (I)V + public final fun setVisibilityKeyMode (Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode;)V + public final fun setVisibilityKeybind (Lorg/polyfrost/oneconfig/api/ui/v1/keybind/OneConfigKeybind;)V public fun setX (F)V public fun setY (F)V public fun setup ()V @@ -246,6 +260,7 @@ public abstract class org/polyfrost/oneconfig/api/hud/v1/Hud : org/polyfrost/one protected fun updateRelativeX (F)V protected fun updateRelativeY (F)V protected final fun updateWhenChanged (Ljava/lang/String;)V + public final fun visibilityKeyInput (Z)V public final fun withSystemPosition (Lkotlin/jvm/functions/Function0;)Ljava/lang/Object; public fun xForWidth (F)F public fun yForHeight (F)F @@ -341,7 +356,9 @@ public final class org/polyfrost/oneconfig/api/hud/v1/HudManager { public static field layoutRefWidth F public static field overrideShowInScreens Z public static field partialTick F + public static field tabListVisibility Ljava/util/function/BooleanSupplier; public final fun getActiveInstances ()Ljava/util/ArrayList; + public static final fun getAllHudsHiddenByKey ()Z public final fun getHudsOfType (Ljava/lang/Class;)Ljava/util/ArrayList; public static final fun getLayoutReferenceHeight ()F public static final fun getLayoutReferenceWidth ()F @@ -369,6 +386,8 @@ public final class org/polyfrost/oneconfig/api/hud/v1/HudManager { public static synthetic fun registerLater$default (Ljava/lang/String;Ljava/lang/String;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;ILjava/lang/Object;)V public final fun removeHud (Lorg/polyfrost/oneconfig/api/hud/v1/Hud;Z)V public static synthetic fun removeHud$default (Lorg/polyfrost/oneconfig/api/hud/v1/HudManager;Lorg/polyfrost/oneconfig/api/hud/v1/Hud;ZILjava/lang/Object;)V + public static final fun resetAllHudsKey ()V + public static final fun resetVisibilityKeys ()V public static final fun suppressionReasons (Lorg/polyfrost/oneconfig/api/hud/v1/Hud;)Ljava/util/List; public final fun toggleAllHuds (Lorg/polyfrost/oneconfig/api/hud/v1/Hud;Z)V public final fun unregister (Lorg/polyfrost/oneconfig/api/hud/v1/Hud;ZZ)Ljava/util/ArrayList; diff --git a/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/Hud.kt b/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/Hud.kt index b21a089fce..92ea64be40 100644 --- a/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/Hud.kt +++ b/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/Hud.kt @@ -54,7 +54,11 @@ import org.polyfrost.oneconfig.api.config.v1.backend.Backend import org.polyfrost.oneconfig.api.hud.v1.HudManager.LOGGER import org.polyfrost.oneconfig.api.platform.v1.Platform import org.polyfrost.oneconfig.api.ui.v1.ExperimentalOneConfigUiApi +import org.polyfrost.oneconfig.api.ui.v1.keybind.BindNotInScreen import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyModifiers +import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyPressMode +import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyPressState +import org.polyfrost.oneconfig.api.ui.v1.keybind.KeybindHelper import org.polyfrost.oneconfig.api.ui.v1.keybind.KeybindManager import org.polyfrost.oneconfig.api.ui.v1.keybind.OneConfigKeybind import org.polyfrost.oneconfig.api.ui.v1.page.PageText @@ -133,6 +137,9 @@ private val BORDER_OPTIONS = arrayOf("border", "borderEnabled", "borderColor", " internal const val POS_SCHEMA = 1 +/** Mirrors `MinecraftKeybindRegistrar.NO_MIRROR_METADATA` which this module cannot see */ +private const val NO_MC_MIRROR_METADATA = "oc_no_mc_mirror" + // every open getter the cached frame geometry or the background merge key reads // a subclass overriding one of these is read live, so a new open geometry property must be added here // or an override of it would be served a stale cached value @@ -422,8 +429,119 @@ public abstract class Hud( @Switch(title = "Show in Chat") public var showInChat: Boolean = true - public var toggleKey: Int = -1 - public var showKey: Int = -1 + @Deprecated("Binary compatibility, replaced by visibilityKeybind", level = DeprecationLevel.HIDDEN) + public var toggleKey: Int + get() = -1 + set(_) {} + + @Deprecated("Binary compatibility, replaced by visibilityKeybind", level = DeprecationLevel.HIDDEN) + public var showKey: Int + get() = -1 + set(_) {} + + /** + * Key which temporarily flips this HUD between shown and hidden without touching [hidden] + * + * Whether it shows or hides the HUD depends on [hidden] so a shown HUD is hidden by it and a hidden HUD shown + */ + public var visibilityKeybind: OneConfigKeybind + get() = _visibilityKeybind.value + set(v) { + _visibilityKeybind.value = v + refreshVisibilityKeybind() + } + + private var _visibilityKeybind: MutableState = mutableStateOf(KeybindHelper.builder().build()) + + private var _visibilityKeyMode: MutableState = mutableStateOf(KeyPressMode.Held) + public var visibilityKeyMode: KeyPressMode + get() = _visibilityKeyMode.value + set(v) { + if (_visibilityKeyMode.value != v) resetVisibilityKey() + _visibilityKeyMode.value = v + } + + private var _visibilityKeyHoldThreshold: MutableState = mutableStateOf(300) + + /** How long in milliseconds a [KeyPressMode.QuickPress] press must be held to act as a hold */ + public var visibilityKeyHoldThreshold: Int + get() = _visibilityKeyHoldThreshold.value + set(v) { _visibilityKeyHoldThreshold.value = v } + + @Transient + private var visibilityKeyState = KeyPressState() + + @Transient + private var registeredVisibilityKeybind: OneConfigKeybind? = null + + @Transient + private var _visibilityKeyActive: MutableState = mutableStateOf(false) + + /** Whether [visibilityKeybind] is currently flipping this HUD's visibility */ + public val visibilityKeyActive: Boolean get() = _visibilityKeyActive.value + + /** + * Whether this HUD has its own [visibilityKeybind] + * + * Return `false` for a HUD which is shown and hidden by some other input, and override + * [hasVisibilityKeyMode] to keep offering the press mode settings for that input + */ + public open fun hasVisibilityKeybind(): Boolean = true + + /** Whether the [visibilityKeyMode] and [visibilityKeyHoldThreshold] settings apply to this HUD */ + public open fun hasVisibilityKeyMode(): Boolean = hasVisibilityKeybind() + + /** Whether this HUD is hidden right now, taking [visibilityKeybind] into account */ + public val effectivelyHidden: Boolean get() = hidden != visibilityKeyActive + + /** + * Feeds the held state of whatever key flips this HUD's visibility through [visibilityKeyMode] + * + * [visibilityKeybind] does this on its own, so call it only for a HUD driven by another input (see + * [hasVisibilityKeybind]). Repeated calls with the same [down] change nothing + * + * Ignored while the editor is open + */ + public fun visibilityKeyInput(down: Boolean) { + if (HudManager.isEditing) return + visibilityKeyState.input(down, visibilityKeyMode, visibilityKeyHoldThreshold.toLong()) + _visibilityKeyActive.put(visibilityKeyState.active) + } + + /** + * Whether this HUD is switched on, which is what its switch in the HUD library shows and changes + * + * Defaults to not [hidden]. A HUD which stays hidden until its key shows it should override this with a + * switch of its own, or switching it on in the library would leave it shown for good + */ + public open var hudEnabled: Boolean + get() = !hidden + set(v) { hidden = !v } + + /** + * Puts this HUD back to its configured visibility and forgets any key press in progress + * + * Called when the editor's show/hide action is used on this HUD, the world unloads or the key or its mode + * changes, so a HUD driven by + * another input (see [hasVisibilityKeybind]) can override it to reset that input too + */ + @MustBeInvokedByOverriders + public open fun resetVisibilityKey() { + visibilityKeyState.reset() + _visibilityKeyActive.put(false) + } + + private fun refreshVisibilityKeybind() { + registeredVisibilityKeybind?.let(KeybindManager::unregister) + registeredVisibilityKeybind = null + resetVisibilityKey() + val src = visibilityKeybind + if (!isReal || !hasVisibilityKeybind() || !src.isBound) return + // the configured keybind loses its action when loaded so a separate bind carries it + registeredVisibilityKeybind = KeybindManager.register( + BindNotInScreen(src.keyCodes, src.mouseBtns, src.mods, 0L) { visibilityKeyInput(it); true } + ) + } @Transient private var toggleBind: OneConfigKeybind? = null @@ -1289,7 +1407,7 @@ public abstract class Hud( public var keepBgWhenHidden: Boolean get() = _keepBgWhenHidden.value; set(v) { _keepBgWhenHidden.put(v) } internal val keepsHiddenBackground: Boolean - get() = hidden && keepBgWhenHidden && showBackground && mergeBackground && + get() = effectivelyHidden && keepBgWhenHidden && showBackground && mergeBackground && hasBackground() && canMergeBackground() && this !is LegacyHudMarker /** @@ -1629,7 +1747,7 @@ public abstract class Hud( flagRevision = rev if (!liveRedrawInputs.get(javaClass)) flagRedraw = alwaysRedraw if (!hasExternalGeometry) { - flagHidden = hidden + flagHidden = effectivelyHidden flagUseGuiScale = useGuiScale flagCustomScale = customScale flagFixedGuiScale = fixedGuiScale @@ -1644,7 +1762,7 @@ public abstract class Hud( get() = if (!liveRedrawInputs.get(javaClass) && refreshFrameFlags()) flagRedraw else alwaysRedraw internal val frameHidden: Boolean - get() = if (!hasExternalGeometry && refreshFrameFlags()) flagHidden else hidden + get() = if (!hasExternalGeometry && refreshFrameFlags()) flagHidden else effectivelyHidden internal val frameEffectiveScale: Float get() { @@ -1735,11 +1853,28 @@ public abstract class Hud( tree["anchorOffsetY"] = ktProperty(out::anchorOffsetY).apply { addDisplayCondition(hideFromConfigUi) } tree["movedByPlayer"] = ktProperty(out::movedByPlayer).apply { addDisplayCondition(hideFromConfigUi) } } - tree["toggleKey"] = ktProperty(out::toggleKey).apply { addDisplayCondition(hideFromConfigUi) } - tree["showKey"] = ktProperty(out::showKey).apply { addDisplayCondition(hideFromConfigUi) } if (tree["toggleKeybind"] == null) { tree["toggleKeybind"] = ktProperty(out::toggleKeybind).apply { addDisplayCondition(hideFromConfigUi) } } + if (out.hasVisibilityKeybind()) { + tree["visibilityKeybind"] = ktProperty(out::visibilityKeybind, "Visibility Keybind").apply { + description = "Temporarily shows this HUD if it is hidden, or hides it if it is shown." + // one entry per HUD would flood Minecraft's Controls menu + addMetadata(NO_MC_MIRROR_METADATA, true) + addDisplayCondition(hideFromConfigUi) + } + } + if (out.hasVisibilityKeyMode()) { + tree["visibilityKeyMode"] = ktProperty(out::visibilityKeyMode, "Key Mode").apply { + description = "Held: only while the key is held. Toggle: each press switches. Quick Press: a tap switches, holding switches back on release." + addMetadata("optionLabels", arrayOf("Held", "Toggle", "Quick Press")) + addDisplayCondition(hideFromConfigUi) + } + tree["visibilityKeyHoldThreshold"] = ktProperty(out::visibilityKeyHoldThreshold, "Hold Threshold").apply { + description = "How long the key must be held in Quick Press mode before releasing it switches back." + addDisplayCondition(hideFromConfigUi) + } + } tree["alignment"] = ktProperty(out::alignment).apply { addDisplayCondition(hideFromConfigUi) } tree["growthAnchor"] = ktProperty(out::growthAnchor).apply { description = "The point this HUD stays pinned to when its size changes, so it only ever grows away from that point." @@ -1833,6 +1968,7 @@ public abstract class Hud( this.tree = tree syncToggleKeybind() for (bind in clonedKeybinds) KeybindManager.register(bind) + refreshVisibilityKeybind() } return out } @@ -1870,6 +2006,14 @@ public abstract class Hud( */ public open fun shouldShow(): Boolean = true + /** + * Return `true` while this HUD still has something to draw after being hidden, such as a closing + * animation, so it keeps being drawn until that finishes + * + * Called every frame while the HUD is hidden outside the editor + */ + public open fun drawsWhileHidden(): Boolean = false + public open fun showByDefault(): Boolean = false public open fun hasBackground(): Boolean = true @@ -1937,6 +2081,7 @@ public abstract class Hud( toggleBind?.let(KeybindManager::unregister) for (bind in clonedKeybinds) KeybindManager.unregister(bind) tree = null + refreshVisibilityKeybind() } @ApiStatus.Internal @@ -1967,8 +2112,6 @@ public abstract class Hud( chainParents = emptyList() parentGeom = FloatArray(0) geomValid = false - showKey = -1 - toggleKey = -1 toggleBind = this@Hud.toggleBind?.let { src -> OneConfigKeybind(src.keyCodes?.copyOf(), src.mouseBtns?.copyOf(), src.mods, src.durationNanos, ::onToggleKeybind).also { it.unresolvedKeyInputs = src.unresolvedKeyInputs @@ -1979,6 +2122,13 @@ public abstract class Hud( positionBatch = 0 positionMovePending = false _movedByPlayer = mutableStateOf(this@Hud.movedByPlayer) + // the clone registers its own bind once it is made + _visibilityKeybind = mutableStateOf(this@Hud.visibilityKeybind.let { it.copyWith(it.keyCodes?.clone(), it.mouseBtns?.clone(), it.mods) }) + _visibilityKeyMode = mutableStateOf(this@Hud.visibilityKeyMode) + _visibilityKeyHoldThreshold = mutableStateOf(this@Hud.visibilityKeyHoldThreshold) + visibilityKeyState = KeyPressState() + registeredVisibilityKeybind = null + _visibilityKeyActive = mutableStateOf(false) _staticWidth = mutableStateOf(this@Hud.staticWidth) _section = mutableStateOf(this@Hud.section) _relativeX = mutableStateOf(this@Hud.relativeX) diff --git a/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudBackgroundMerge.kt b/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudBackgroundMerge.kt index 98b370a3ff..801708afb6 100644 --- a/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudBackgroundMerge.kt +++ b/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudBackgroundMerge.kt @@ -209,7 +209,7 @@ internal object HudBackgroundMerge { fun canMerge(hud: Hud): Boolean = hud !is LegacyHudMarker && hud.canMergeBackground() && hud.showBackground && hud.mergeBackground && hud.hasBackground() && !hud.borderEnabled && - (!hud.hidden || hud.keepBgWhenHidden) && + (!hud.effectivelyHidden || hud.keepBgWhenHidden) && hud.renderedW > 0f && hud.renderedH > 0f fun sameStyle(a: Hud, b: Hud): Boolean = @@ -735,7 +735,7 @@ internal object HudBackgroundMerge { key = key * 31 + (if (hud.mergeDiagonally) 1 else 0) key = key * 31 + (if (hud.mergeAcrossColours) 1 else 0) key = key * 31 + (if (hud.bgChroma) 1 else 0) - key = key * 31 + (if (hud.hidden) 1 else 0) + key = key * 31 + (if (hud.effectivelyHidden) 1 else 0) key = key * 31 + (if (hud.keepBgWhenHidden) 1 else 0) key = key * 31 + (if (hud.borderEnabled) 1 else 0) } diff --git a/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudManager.kt b/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudManager.kt index 544f739680..32824777dc 100644 --- a/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudManager.kt +++ b/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudManager.kt @@ -51,6 +51,8 @@ import org.polyfrost.oneconfig.api.hud.v1.events.HudEditorToggleEvent import org.polyfrost.oneconfig.api.platform.v1.Platform import org.polyfrost.oneconfig.api.ui.v1.ExperimentalOneConfigUiApi import org.polyfrost.oneconfig.api.ui.v1.InternalOneConfigUiApi +import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyPressMode +import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyPressState import org.polyfrost.oneconfig.utils.v1.MHUtils import java.lang.ref.WeakReference import java.util.Collections @@ -59,6 +61,7 @@ import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference +import java.util.function.BooleanSupplier import java.util.function.Consumer private fun Throwable.isFatalHudFailure(): Boolean = this is VirtualMachineError @@ -162,6 +165,53 @@ public object HudManager { */ @Volatile @JvmField public var isGuiHidden: Boolean = false + /** + * Set while the global HUD visibility keybind is hiding every HUD + * + * Like [isGuiHidden] this never applies while the editor is open + */ + @Volatile + @get:JvmStatic + public var allHudsHiddenByKey: Boolean = false + private set + + private val allHudsKeyState = KeyPressState() + + /** + * Feeds the global HUD visibility keybind + * + * Ignored while the editor is open + */ + @ApiStatus.Internal + @JvmStatic + public fun allHudsKeyInput(down: Boolean, mode: KeyPressMode, holdThresholdMs: Long) { + if (isEditing) return + allHudsKeyState.input(down, mode, holdThresholdMs) + allHudsHiddenByKey = allHudsKeyState.active + } + + /** Shows every HUD the global HUD visibility keybind hid, leaving the per-HUD keybinds alone */ + @JvmStatic + public fun resetAllHudsKey() { + allHudsKeyState.reset() + allHudsHiddenByKey = false + } + + /** Puts every HUD back to its configured visibility, undoing both the global and the per-HUD keybinds */ + @JvmStatic + public fun resetVisibilityKeys() { + resetAllHudsKey() + for (hud in activeInstances) hud.resetVisibilityKey() + } + + /** + * Overrides how OneConfig decides whether the tab list is open, for mods which change when it opens + * + * `null` falls back to whether the player list key is held + */ + @Volatile @JvmField public var tabListVisibility: BooleanSupplier? = null + + @Volatile @JvmField public var overrideShowInScreens: Boolean = false @ApiStatus.Internal @@ -734,10 +784,17 @@ public object HudManager { } private fun shouldDraw(hud: Hud): Boolean { - if (!isEditing && (hud.frameHidden || isSuppressed(hud))) return false + if (!isEditing && ((hud.frameHidden && !drawsWhileHidden(hud)) || isSuppressed(hud))) return false return isShown(hud) } + private fun drawsWhileHidden(hud: Hud): Boolean = try { + hud.drawsWhileHidden() + } catch (e: Throwable) { + LOGGER.error("Failed to check whether HUD ${hud.title} draws while hidden", e) + false + } + private fun keepsBackgroundOnly(hud: Hud): Boolean = !isEditing && hud.frameHidden && !isSuppressed(hud) && hud.keepsHiddenBackground && isShown(hud) @@ -886,6 +943,7 @@ public object HudManager { private fun isShown(hud: Hud): Boolean { if (isEditing) return true if (isGuiHidden) return false + if (allHudsHiddenByKey) return false if (isDebugScreenVisible && !hud.showInF3) return false if (isTabListVisible && !hud.showInTab) return false if (!overrideShowInScreens) { @@ -1236,6 +1294,7 @@ public object HudManager { key = key * 31L + (if (isGuiScreenOpen) 1 else 0) key = key * 31L + (if (isChatScreenOpen) 1 else 0) key = key * 31L + (if (isGuiHidden) 1 else 0) + key = key * 31L + (if (allHudsHiddenByKey) 1 else 0) key = key * 31L + (if (overrideShowInScreens) 1 else 0) key = key * 31L + (if (isEditing) 1 else 0) key = key * 31L + (if (inWorld) 1 else 0) @@ -1485,7 +1544,7 @@ public object HudManager { } private fun drawHud(hud: Hud, root: RootNode, ctx: RenderContext) { - if (isEditing && (hud.hidden || isSuppressed(hud))) { + if (isEditing && (hud.effectivelyHidden || isSuppressed(hud))) { ctx.saveLayerAlpha(HIDDEN_HUD_ALPHA) root.render(ctx) ctx.restore() diff --git a/modules/internal/src/main/java/org/polyfrost/oneconfig/internal/OneConfigConfig.java b/modules/internal/src/main/java/org/polyfrost/oneconfig/internal/OneConfigConfig.java index 008b6c40e8..62344fd7ef 100644 --- a/modules/internal/src/main/java/org/polyfrost/oneconfig/internal/OneConfigConfig.java +++ b/modules/internal/src/main/java/org/polyfrost/oneconfig/internal/OneConfigConfig.java @@ -12,9 +12,12 @@ import org.polyfrost.oneconfig.api.config.v1.annotations.Number; import org.polyfrost.oneconfig.api.config.v1.annotations.Slider; import org.polyfrost.oneconfig.api.config.v1.annotations.Switch; +import org.polyfrost.oneconfig.api.hud.v1.HudManager; import org.polyfrost.oneconfig.api.platform.v1.Keys; import org.polyfrost.oneconfig.api.platform.v1.Platform; +import org.polyfrost.oneconfig.api.ui.v1.keybind.BindNotInScreen; import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyModifiers; +import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyPressMode; import org.polyfrost.oneconfig.api.ui.v1.keybind.KeybindManager; import org.polyfrost.oneconfig.api.ui.v1.keybind.KeybindUtils; import org.polyfrost.oneconfig.api.ui.v1.keybind.OneConfigKeybind; @@ -200,6 +203,36 @@ public class OneConfigConfig extends Config { ) public static float marqueeSelectionAnimDuration = 150f; + @Keybind( + title = "oneconfig.preferences.hud_toggle_all_keybind.title", + subcategory = "oneconfig.preferences.category.huds", + description = "oneconfig.preferences.hud_toggle_all_keybind.description" + ) + public static OneConfigKeybind hudToggleAllKeybind = + new OneConfigKeybind(null, null, KeyModifiers.NONE, 0L, pressed -> true); + + @Dropdown( + title = "oneconfig.preferences.hud_toggle_all_mode.title", + subcategory = "oneconfig.preferences.category.huds", + options = { + "oneconfig.preferences.key_mode.held", + "oneconfig.preferences.key_mode.toggle", + "oneconfig.preferences.key_mode.quick_press" + }, + description = "oneconfig.preferences.hud_toggle_all_mode.description" + ) + public static KeyPressMode hudToggleAllKeyMode = KeyPressMode.Held; + + @Slider( + title = "oneconfig.preferences.hud_toggle_all_hold_threshold.title", + subcategory = "oneconfig.preferences.category.huds", + min = 50f, + max = 1000f, + step = 50f, + description = "oneconfig.preferences.hud_toggle_all_hold_threshold.description" + ) + public static float hudToggleAllHoldThreshold = 300f; + @Slider( title = "oneconfig.preferences.hud_drag_ui_opacity.title", subcategory = "oneconfig.preferences.category.hud_editor", @@ -436,6 +469,11 @@ public class OneConfigConfig extends Config { private static final AtomicReference registeredHudShortcutsAltKeybind = new AtomicReference<>(); + /** + * The keybind registered with the {@link KeybindManager} for temporarily hiding every HUD + */ + private static OneConfigKeybind registeredHudToggleAllKeybind; + public OneConfigConfig() { super("oneconfig.json", "assets/oneconfig/brand/oneconfig-icon.svg", "OneConfig", Category.QOL); INSTANCE = this; @@ -590,6 +628,47 @@ protected void initialize(boolean byConfigManager) { return false; }); refreshHudShortcutsAltKeybind(); + addCallback( + "hudToggleAllKeybind", (OneConfigKeybind kb) -> { + refreshHudToggleAllKeybind(); + return false; + }); + refreshHudToggleAllKeybind(); + addCallback( + "hudToggleAllKeyMode", (KeyPressMode mode) -> { + HudManager.resetVisibilityKeys(); + return false; + }); + addDependency( + "hudToggleAllHoldThreshold", + "Mode", + () -> hudToggleAllKeyMode == KeyPressMode.QuickPress ? Property.Display.SHOWN : Property.Display.DISABLED); + } + + /** + * Rebuilds the keybind which temporarily hides every HUD + *

+ * Built as a {@link BindNotInScreen} so it never fires while a screen is open + */ + private static void refreshHudToggleAllKeybind() { + if (registeredHudToggleAllKeybind != null) { + KeybindManager.unregister(registeredHudToggleAllKeybind); + registeredHudToggleAllKeybind = null; + } + HudManager.resetVisibilityKeys(); + OneConfigKeybind src = hudToggleAllKeybind; + if (src == null || !src.isBound()) { + return; + } + registeredHudToggleAllKeybind = KeybindManager.register(new BindNotInScreen( + src.getKeyCodes(), + src.getMouseBtns(), + src.getMods(), + 0L, + pressed -> { + HudManager.allHudsKeyInput(pressed, hudToggleAllKeyMode, (long) hudToggleAllHoldThreshold); + return true; + })); } private static final String[] SOUND_OPTIONS = {"enableUIMenuSounds", "enableUIClickSounds", "enableUISliderSounds", "enableHudEditorSounds", "uiSoundVolume"}; diff --git a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudModCardData.kt b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudModCardData.kt index 25a9f763a3..151c151431 100644 --- a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudModCardData.kt +++ b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudModCardData.kt @@ -116,12 +116,18 @@ internal class HudModCardData( override fun isEnabled(): Boolean { HudManager.revision HudManager.instancesRevision.intValue - return placed().any { !it.hidden } + return placed().any { it.hudEnabled } } override fun setEnabled(enabled: Boolean) { val huds = placed() - Snapshot.withMutableSnapshot { huds.forEach { it.hidden = !enabled } } + // switching HUDs on or off ends any keybind flip so they really end up as chosen + Snapshot.withMutableSnapshot { + huds.forEach { + it.resetVisibilityKey() + it.hudEnabled = enabled + } + } huds.forEach { runCatching { it.save() } } HudManager.invalidate() } diff --git a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudSettingsReset.kt b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudSettingsReset.kt index f44635a990..91e44bb901 100644 --- a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudSettingsReset.kt +++ b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudSettingsReset.kt @@ -371,7 +371,7 @@ private fun buildHudCanvasMenuEntries( highlightAnchor: Boolean, ): List { val actionTargets = targets.ifEmpty { listOf(hud) } - val allHidden = actionTargets.all { it.hidden } + val allHidden = actionTargets.all { it.effectivelyHidden } val allLocked = actionTargets.all { it.locked } val entries = ArrayList(24) @@ -384,12 +384,7 @@ private fun buildHudCanvasMenuEntries( ) entries += MenuAction( if (allHidden) translated("oneconfig.hud.menu.show", "Show") else translated("oneconfig.hud.menu.hide", "Hide"), - { - Snapshot.withMutableSnapshot { - val hide = actionTargets.any { !it.hidden } - actionTargets.forEach { it.hidden = hide } - } - }, + { toggleHudVisibility(actionTargets) }, icon = if (allHidden) "eye-off" else "eye", shortcutHint = keybindHint(OneConfigConfig.hudVisibilityKeybind), ) diff --git a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudVisibility.kt b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudVisibility.kt new file mode 100644 index 0000000000..6c585e18ff --- /dev/null +++ b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/HudVisibility.kt @@ -0,0 +1,20 @@ +package org.polyfrost.oneconfig.internal.ui.hud + +import androidx.compose.runtime.snapshots.Snapshot +import org.polyfrost.oneconfig.api.hud.v1.Hud + +/** + * The editor's show/hide action + * + * A HUD its visibility keybind is temporarily showing or hiding goes back to its configured visibility, + * every other HUD is shown or hidden for good + */ +fun toggleHudVisibility(huds: List) { + if (huds.isEmpty()) return + val hide = huds.any { !it.effectivelyHidden } + Snapshot.withMutableSnapshot { + for (hud in huds) { + if (hud.visibilityKeyActive) hud.resetVisibilityKey() else hud.hidden = hide + } + } +} diff --git a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/HudDesignSession.kt b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/HudDesignSession.kt index 558ad575dd..bdb290aa85 100644 --- a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/HudDesignSession.kt +++ b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/HudDesignSession.kt @@ -3,12 +3,12 @@ package org.polyfrost.oneconfig.internal.ui.hud.screens import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshots.Snapshot import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import org.polyfrost.oneconfig.api.hud.v1.Hud import org.polyfrost.oneconfig.api.hud.v1.HudManager import org.polyfrost.oneconfig.internal.ui.hud.resetAllHudProperties +import org.polyfrost.oneconfig.internal.ui.hud.toggleHudVisibility internal sealed interface StudioCommand { data class Select(val huds: List) : StudioCommand @@ -93,10 +93,7 @@ object HudDesignSession { if (!HudManager.isEditorOpen) return false val huds = activeSelection if (huds.isEmpty()) return false - Snapshot.withMutableSnapshot { - val hide = huds.any { !it.hidden } - huds.forEach { it.hidden = hide } - } + toggleHudVisibility(huds) return true } diff --git a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/HudDesignStudio.kt b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/HudDesignStudio.kt index fbbe4b422c..59ba28dc72 100644 --- a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/HudDesignStudio.kt +++ b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/HudDesignStudio.kt @@ -123,6 +123,7 @@ import org.polyfrost.oneconfig.internal.ui.hud.repairHudStaticSize import org.polyfrost.oneconfig.internal.ui.hud.screens.sections.Layout import org.polyfrost.oneconfig.internal.ui.hud.screens.sections.Settings import org.polyfrost.oneconfig.internal.ui.hud.screens.sections.Style +import org.polyfrost.oneconfig.internal.ui.hud.toggleHudVisibility import org.polyfrost.oneconfig.internal.ui.screens.rememberHasHudOptions import org.polyfrost.oneconfig.internal.ui.search.SearchCorpus import org.polyfrost.oneconfig.internal.ui.search.SearchScope @@ -162,6 +163,16 @@ internal fun notifyHudLocked() { ) } +private var allHudsHiddenToast: Notification? = null + +private fun notifyAllHudsHidden() { + allHudsHiddenToast?.let { if (NotificationsManager.contains(it)) return } + allHudsHiddenToast = Notifications.builder( + "All HUDs hidden", + "The Hide All HUDs keybind is hiding every HUD outside the editor.", + ).action("Show HUDs") { HudManager.resetAllHudsKey() }.send() +} + @OptIn(ExperimentalComposeUiApi::class) private fun Modifier.safePointerEvent( eventType: PointerEventType, @@ -256,11 +267,14 @@ private val lockedHudDashEffect = PathEffect.dashPathEffect(floatArrayOf(2f, 4f) private const val IDLE_HUD_BOX_ALPHA = 0.2f private const val HOVERED_HUD_BOX_ALPHA = 0.5f private const val HIDDEN_HUD_BOX_ALPHA = 0.4f +private const val TEMPORARY_HUD_BOX_ALPHA = 0.8f private class StudioCanvasColors( val idleBox: Color, val hoveredBox: Color, val hiddenBox: Color, + /** Outline of a HUD its visibility keybind is currently showing or hiding */ + val temporaryBox: Color, val locked: Color, val onLocked: Color, val hiddenLegacyScrim: Color, @@ -280,6 +294,7 @@ private fun rememberStudioCanvasColors(): StudioCanvasColors { idleBox = theme.onMedia.copy(alpha = IDLE_HUD_BOX_ALPHA), hoveredBox = theme.onMedia.copy(alpha = HOVERED_HUD_BOX_ALPHA), hiddenBox = theme.onMedia.copy(alpha = HIDDEN_HUD_BOX_ALPHA), + temporaryBox = accent.copy(alpha = TEMPORARY_HUD_BOX_ALPHA), locked = theme.warning, onLocked = theme.pageSurface, hiddenLegacyScrim = theme.scrimColor, @@ -688,9 +703,9 @@ private fun drawHudContents(ctx: RenderContext, mcToScreen: Float) { sk.save() sk.translate(bounds.x * mcToScreen, bounds.y * mcToScreen) if (contentScale != 1f) sk.scale(contentScale, contentScale) - if (hud.hidden) sk.saveLayerAlpha(0.35f) + if (hud.effectivelyHidden) sk.saveLayerAlpha(0.35f) try { root.render(ctx) } catch (_: Throwable) {} - if (hud.hidden) sk.restore() + if (hud.effectivelyHidden) sk.restore() sk.restore() } } @@ -1036,7 +1051,8 @@ private fun HudActionBar( val barX = (layout.x / densityFloat).coerceAtLeast(0f) val barY = (layout.y / densityFloat).coerceAtLeast(0f) val barPadding = (actionBarPadding(actionBarGapPx) / densityFloat).dp - val isHidden = hud.hidden + val isHidden = hud.effectivelyHidden + val isTemporary = hud.visibilityKeyActive val isLocked = hud.locked Row( modifier = Modifier @@ -1059,9 +1075,10 @@ private fun HudActionBar( if (isHidden) "eye-off" else "eye", if (isHidden) translated("oneconfig.hud.menu.show", "Show") else translated("oneconfig.hud.menu.hide", "Hide"), iconSize, + tint = if (isTemporary) Accent else Color.Unspecified, sound = UiSound.Click, ) { - Snapshot.withMutableSnapshot { hud.hidden = !hud.hidden } + toggleHudVisibility(listOf(hud)) } HudActionButton( if (isLocked) "lock" else "unlock", @@ -1537,6 +1554,11 @@ fun HudDesignStudio(visible: Boolean = true) { } } + // the editor shows every HUD regardless, so say why they will all be gone again once it closes + LaunchedEffect(visible) { + if (visible && HudManager.allHudsHiddenByKey) notifyAllHudsHidden() + } + LaunchedEffect(Unit) { while (true) { try { @@ -2425,7 +2447,7 @@ fun HudDesignStudio(visible: Boolean = true) { colors = canvasColors, showBadge = singleSelection, ) - } else if (hud.hidden) { + } else if (hud.effectivelyHidden) { if (hud is LegacyHud) { drawRect( color = canvasColors.hiddenLegacyScrim, @@ -2434,14 +2456,14 @@ fun HudDesignStudio(visible: Boolean = true) { ) } drawRect( - color = if (isHovered) canvasColors.hoveredBox else canvasColors.hiddenBox, + color = if (isHovered) canvasColors.hoveredBox else if (hud.visibilityKeyActive) canvasColors.temporaryBox else canvasColors.hiddenBox, topLeft = Offset(sx, sy), size = Size(sw, sh), style = Stroke(width = 1f, pathEffect = hiddenHudDashEffect) ) } else { drawRect( - color = if (isHovered) canvasColors.hoveredBox else canvasColors.idleBox, + color = if (isHovered) canvasColors.hoveredBox else if (hud.visibilityKeyActive) canvasColors.temporaryBox else canvasColors.idleBox, topLeft = Offset(sx, sy), size = Size(sw, sh), style = Stroke(width = 1f) diff --git a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/sections/Settings.kt b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/sections/Settings.kt index a9aab8f04a..4a2b5f6093 100644 --- a/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/sections/Settings.kt +++ b/modules/internal/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/hud/screens/sections/Settings.kt @@ -11,9 +11,15 @@ import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.unit.dp import org.polyfrost.oneconfig.api.hud.v1.Hud import org.polyfrost.oneconfig.api.hud.v1.LegacyHudMarker +import org.polyfrost.oneconfig.api.ui.v1.components.NumberField +import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyPressMode +import org.polyfrost.oneconfig.internal.ui.api.settings.KeybindOptionData +import org.polyfrost.oneconfig.internal.ui.components.settings.Dropdown +import org.polyfrost.oneconfig.internal.ui.components.settings.KeybindOption import org.polyfrost.oneconfig.internal.ui.hud.HudSettingTarget import org.polyfrost.oneconfig.internal.ui.hud.HudSettingsContent import org.polyfrost.oneconfig.internal.ui.hud.hudOptionsCanReset +import org.polyfrost.oneconfig.internal.ui.hud.hudProperty import org.polyfrost.oneconfig.internal.ui.hud.resetHudOptions import org.polyfrost.oneconfig.internal.ui.screens.HudConfigScreen @@ -33,6 +39,8 @@ fun Settings(hud: Hud?, query: String) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { hud.tree?.let { HudConfigScreen(it, query) } + if (hud.hasVisibilityKeyMode()) VisibilityKeyCard(hud, query) + if (hud !is LegacyHudMarker) { val canReset = remember(showInF3, showInTab, showInScreens, showInChat) { hudOptionsCanReset(hud, VISIBILITY_OPTIONS) @@ -76,3 +84,47 @@ fun Settings(hud: Hud?, query: String) { } } } + +@Composable +private fun VisibilityKeyCard(hud: Hud, query: String) { + val keyProp = hudProperty(hud, "visibilityKeybind") + if (hudProperty(hud, "visibilityKeyMode") == null) return + var mode by remember { mutableStateOf(hud.visibilityKeyMode) } + var holdThreshold by remember { mutableStateOf(hud.visibilityKeyHoldThreshold.toFloat()) } + // a HUD without its own key is driven by some other input so its mode always applies + val bound = keyProp == null || hud.visibilityKeybind.isBound + + CardSection("Visibility Keybind", query, "Visibility Keybind", "Key Mode", "Hold Threshold") { + if (keyProp != null) { + HudSettingTarget(hud, "visibilityKeybind") { + ControlRow("Key") { KeybindOption(KeybindOptionData(keyProp)) } + } + } + if (bound) { + HudSettingTarget(hud, "visibilityKeyMode") { + ControlRow("Key Mode") { + Dropdown(KeyPressMode.entries.map { it.name }, mode.ordinal, onSelect = { + Snapshot.withMutableSnapshot { mode = KeyPressMode.entries[it]; hud.visibilityKeyMode = mode } + }, width = 176.dp) + } + } + if (mode == KeyPressMode.QuickPress) { + HudSettingTarget(hud, "visibilityKeyHoldThreshold") { + ControlRow("Hold Threshold") { + NumberField( + holdThreshold, + { + holdThreshold = it + Snapshot.withMutableSnapshot { hud.visibilityKeyHoldThreshold = it.toInt() } + }, + range = 50f..1000f, + step = 50f, + unit = "ms", + width = 176.dp, + ) + } + } + } + } + } +} diff --git a/modules/ui/api/ui.api b/modules/ui/api/ui.api index 84c44bdd74..d97f74b669 100644 --- a/modules/ui/api/ui.api +++ b/modules/ui/api/ui.api @@ -1994,6 +1994,26 @@ public final class org/polyfrost/oneconfig/api/ui/v1/keybind/KeyModifiers { public static final fun of (I)B } +public final class org/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode : java/lang/Enum { + public static final field Held Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode; + public static final field QuickPress Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode; + public static final field Toggle Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode; + public static fun values ()[Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode; +} + +public final class org/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressState { + public static final field $stable I + public fun ()V + public final fun getActive ()Z + public final fun input (ZLorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode;J)Z + public final fun input (ZLorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode;JJ)Z + public static synthetic fun input$default (Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressState;ZLorg/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressMode;JJILjava/lang/Object;)Z + public final fun isDown ()Z + public final fun reset ()Z +} + public final class org/polyfrost/oneconfig/api/ui/v1/keybind/KeybindHelper { public static final field $stable I public static final field Companion Lorg/polyfrost/oneconfig/api/ui/v1/keybind/KeybindHelper$Companion; diff --git a/modules/ui/src/main/kotlin/org/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressState.kt b/modules/ui/src/main/kotlin/org/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressState.kt new file mode 100644 index 0000000000..a79c54dd95 --- /dev/null +++ b/modules/ui/src/main/kotlin/org/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressState.kt @@ -0,0 +1,83 @@ +package org.polyfrost.oneconfig.api.ui.v1.keybind + +private const val NOT_PRESSED = Long.MIN_VALUE + +/** + * How a key drives a temporary on/off state + */ +public enum class KeyPressMode { + /** Active only while the key is held */ + Held, + + /** Each press flips the state */ + Toggle, + + /** + * A press flips the state straight away + * + * Releasing it after holding for longer than the hold threshold puts the state back to how it was + * before the press so a tap acts as [Toggle] and a hold acts as [Held] + */ + QuickPress; +} + +/** + * Edge-driven state machine turning key presses and releases into an active flag according to a [KeyPressMode] + * + * Feed it every change of the key's held state through [input], from a keybind action or by polling a key + */ +public class KeyPressState { + /** Whether the state is currently on */ + public var active: Boolean = false + private set + + /** Whether the key was down at the last [input] */ + public var isDown: Boolean = false + private set + + private var pressedAt = NOT_PRESSED + private var activeBeforePress = false + + /** + * Records the key as [down] or released + * + * Repeated calls with the same [down] are ignored so this is safe to call every tick or frame + * + * @param holdThresholdMs how long a [KeyPressMode.QuickPress] press must be held to count as a hold + * @return whether [active] changed + */ + @JvmOverloads + public fun input(down: Boolean, mode: KeyPressMode, holdThresholdMs: Long, nowNanos: Long = System.nanoTime()): Boolean { + if (down == isDown) return false + isDown = down + val before = active + when (mode) { + KeyPressMode.Held -> active = down + KeyPressMode.Toggle -> if (down) active = !active + KeyPressMode.QuickPress -> if (down) { + activeBeforePress = active + pressedAt = nowNanos + active = !active + } else { + // a press which began under another mode has no start time and so cannot be a hold + if (pressedAt != NOT_PRESSED && nowNanos - pressedAt > holdThresholdMs * 1_000_000L) active = activeBeforePress + pressedAt = NOT_PRESSED + } + } + if (mode != KeyPressMode.QuickPress) pressedAt = NOT_PRESSED + return active != before + } + + /** + * Turns the state off and forgets any press in progress + * + * @return whether [active] changed + */ + public fun reset(): Boolean { + val was = active + active = false + isDown = false + pressedAt = NOT_PRESSED + return was + } +} diff --git a/modules/ui/src/test/java/org/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressStateTest.java b/modules/ui/src/test/java/org/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressStateTest.java new file mode 100644 index 0000000000..23c5a65080 --- /dev/null +++ b/modules/ui/src/test/java/org/polyfrost/oneconfig/api/ui/v1/keybind/KeyPressStateTest.java @@ -0,0 +1,114 @@ +/* + * This file is part of OneConfig. + * OneConfig - Next Generation Config Library for Minecraft: Java Edition + * Copyright (C) 2021~2024 Polyfrost. + * + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * OneConfig is licensed under the terms of version 3 of the GNU Lesser + * General Public License as published by the Free Software Foundation, AND + * under the Additional Terms Applicable to OneConfig, as published by Polyfrost, + * either version 1.0 of the Additional Terms, 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License. If not, see . You should + * have also received a copy of the Additional Terms Applicable + * to OneConfig, as published by Polyfrost. If not, see + * + */ + +package org.polyfrost.oneconfig.api.ui.v1.keybind; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class KeyPressStateTest { + private static final long THRESHOLD_MS = 300L; + private static final long MS = 1_000_000L; + + @Test + void heldIsActiveOnlyWhileDown() { + KeyPressState state = new KeyPressState(); + assertTrue(state.input(true, KeyPressMode.Held, THRESHOLD_MS, 0L)); + assertTrue(state.getActive()); + assertFalse(state.input(true, KeyPressMode.Held, THRESHOLD_MS, 10L * MS)); + assertTrue(state.input(false, KeyPressMode.Held, THRESHOLD_MS, 20L * MS)); + assertFalse(state.getActive()); + } + + @Test + void toggleFlipsOnEachPress() { + KeyPressState state = new KeyPressState(); + state.input(true, KeyPressMode.Toggle, THRESHOLD_MS, 0L); + state.input(false, KeyPressMode.Toggle, THRESHOLD_MS, 1000L * MS); + assertTrue(state.getActive()); + state.input(true, KeyPressMode.Toggle, THRESHOLD_MS, 2000L * MS); + state.input(false, KeyPressMode.Toggle, THRESHOLD_MS, 2010L * MS); + assertFalse(state.getActive()); + } + + @Test + void quickPressTapActsAsToggle() { + KeyPressState state = new KeyPressState(); + state.input(true, KeyPressMode.QuickPress, THRESHOLD_MS, 0L); + state.input(false, KeyPressMode.QuickPress, THRESHOLD_MS, 100L * MS); + assertTrue(state.getActive()); + state.input(true, KeyPressMode.QuickPress, THRESHOLD_MS, 500L * MS); + state.input(false, KeyPressMode.QuickPress, THRESHOLD_MS, 600L * MS); + assertFalse(state.getActive()); + } + + @Test + void quickPressHoldReturnsToStateBeforePress() { + KeyPressState state = new KeyPressState(); + state.input(true, KeyPressMode.QuickPress, THRESHOLD_MS, 0L); + assertTrue(state.getActive()); + state.input(false, KeyPressMode.QuickPress, THRESHOLD_MS, 400L * MS); + assertFalse(state.getActive()); + + // latched on by a tap, then a hold peeks it off and puts it back on + state.input(true, KeyPressMode.QuickPress, THRESHOLD_MS, 1000L * MS); + state.input(false, KeyPressMode.QuickPress, THRESHOLD_MS, 1050L * MS); + assertTrue(state.getActive()); + state.input(true, KeyPressMode.QuickPress, THRESHOLD_MS, 2000L * MS); + assertFalse(state.getActive()); + state.input(false, KeyPressMode.QuickPress, THRESHOLD_MS, 2500L * MS); + assertTrue(state.getActive()); + } + + @Test + void quickPressAtThresholdIsStillATap() { + KeyPressState state = new KeyPressState(); + state.input(true, KeyPressMode.QuickPress, THRESHOLD_MS, 0L); + state.input(false, KeyPressMode.QuickPress, THRESHOLD_MS, THRESHOLD_MS * MS); + assertTrue(state.getActive()); + } + + @Test + void releaseOfPressFromAnotherModeIsNotAHold() { + KeyPressState state = new KeyPressState(); + state.input(true, KeyPressMode.Toggle, THRESHOLD_MS, 0L); + state.input(false, KeyPressMode.QuickPress, THRESHOLD_MS, 5000L * MS); + assertTrue(state.getActive()); + } + + @Test + void resetForgetsPressInProgress() { + KeyPressState state = new KeyPressState(); + state.input(true, KeyPressMode.QuickPress, THRESHOLD_MS, 0L); + assertTrue(state.reset()); + assertFalse(state.getActive()); + assertFalse(state.isDown()); + state.input(false, KeyPressMode.QuickPress, THRESHOLD_MS, 5000L * MS); + assertFalse(state.getActive()); + } +}