aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/keybindings/SavedKeyBinding.kt
blob: 8f08e5fe63f2921aaaedab44e5cc133456a188c7 (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
package moe.nea.firmament.keybindings

import kotlinx.serialization.Serializable
import net.minecraft.text.Text

@Serializable
data class SavedKeyBinding(
	val button: GenericInputButton,
	val modifiers: InputModifiers,
) {
	companion object {
		fun isShiftDown() = InputModifiers.current().shift

		fun unbound(): SavedKeyBinding = withoutMods(GenericInputButton.unbound())
		fun withoutMods(input: GenericInputButton) = SavedKeyBinding(input, InputModifiers.none())
		fun keyWithoutMods(keyCode: Int): SavedKeyBinding = withoutMods(GenericInputButton.ofKeyCode(keyCode))
		fun keyWithMods(keyCode: Int, mods: InputModifiers) =
			SavedKeyBinding(GenericInputButton.ofKeyCode(keyCode), mods)
	}

	fun isPressed(atLeast: Boolean = false): Boolean {
		if (!button.isPressed())
			return false
		val mods = InputModifiers.current()
			.without(InputModifiers.ofKey(button))
		return mods.matches(this.modifiers, atLeast)
	}

	override fun toString(): String {
		return format().string
	}

	fun format(): Text {
		val stroke = Text.empty()
		if (!modifiers.isEmpty()) {
			stroke.append(modifiers.format())
			stroke.append(" + ")
		}
		stroke.append(button.format())
		return stroke
	}

	val isBound: Boolean get() = button.isBound()
	fun matches(action: GenericInputAction, inputModifiers: InputModifiers, atLeast: Boolean = false): Boolean {
		return action.matches(button) && this.modifiers.matches(inputModifiers, atLeast)
	}

}