aboutsummaryrefslogtreecommitdiff
path: root/src/compat/yacl/java/KeybindingController.kt
blob: 6be9dd1bcaf42e6e57d48f2f2628961833d570e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package moe.nea.firmament.compat.yacl

import dev.isxander.yacl3.api.Controller
import dev.isxander.yacl3.api.Option
import dev.isxander.yacl3.api.utils.Dimension
import dev.isxander.yacl3.gui.AbstractWidget
import dev.isxander.yacl3.gui.YACLScreen
import dev.isxander.yacl3.gui.controllers.ControllerWidget
import net.minecraft.text.Text
import moe.nea.firmament.gui.config.KeyBindingHandler
import moe.nea.firmament.gui.config.KeyBindingStateManager
import moe.nea.firmament.gui.config.ManagedOption
import moe.nea.firmament.keybindings.SavedKeyBinding

class KeybindingController(
	val option: Option<SavedKeyBinding>,
	val managedOption: ManagedOption<SavedKeyBinding>,
) : Controller<SavedKeyBinding> {
	val handler = managedOption.handler as KeyBindingHandler
	override fun option(): Option<SavedKeyBinding> {
		return option
	}

	override fun formatValue(): Text {
		return option.pendingValue().format()
	}

	override fun provideWidget(screen: YACLScreen, widgetDimension: Dimension<Int>): AbstractWidget {
		lateinit var button: ControllerWidget<KeybindingController>
		val sm = KeyBindingStateManager(
			{ option.pendingValue() },
			{ option.requestSet(it) },
			{ screen.focused = null },
			{ screen.focused = button }
		)
		button = object : ControllerWidget<KeybindingController>(this, screen, widgetDimension) {
			override fun getHoveredControlWidth(): Int {
				return 130
			}

			override fun getValueText(): Text {
				return sm.label
			}

			override fun keyPressed(keyCode: Int, scanCode: Int, modifiers: Int): Boolean {
				return sm.keyboardEvent(keyCode, true)
			}

			override fun keyReleased(keyCode: Int, scanCode: Int, modifiers: Int): Boolean {
				return sm.keyboardEvent(keyCode, false)
			}

			override fun unfocus() {
				sm.onLostFocus()
			}

			override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
				if (button == 0 && isHovered) {
					sm.onClick()
					return true
				}
				return super.mouseClicked(mouseX, mouseY, button)
			}
		}
		option.addListener { t, u ->
			sm.updateLabel()
		}
		sm.updateLabel()
		return button
	}
}