aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/gui/CheckboxComponent.kt
blob: 761c0865f39f2868840c92a1ef818775712e2299 (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
package moe.nea.firmament.gui

import io.github.notenoughupdates.moulconfig.gui.GuiComponent
import io.github.notenoughupdates.moulconfig.gui.GuiImmediateContext
import io.github.notenoughupdates.moulconfig.gui.MouseEvent
import io.github.notenoughupdates.moulconfig.observer.GetSetter
import io.github.notenoughupdates.moulconfig.platform.ModernRenderContext
import net.minecraft.client.render.RenderLayer
import moe.nea.firmament.Firmament

class CheckboxComponent<T>(
	val state: GetSetter<T>,
	val value: T,
) : GuiComponent() {
	override fun getWidth(): Int {
		return 16
	}

	override fun getHeight(): Int {
		return 16
	}

	fun isEnabled(): Boolean {
		return state.get() == value
	}

	override fun render(context: GuiImmediateContext) {
		val ctx = (context.renderContext as ModernRenderContext).drawContext
		ctx.drawGuiTexture(
			RenderLayer::getGuiTextured,
			if (isEnabled()) Firmament.identifier("firmament:widget/checkbox_checked")
			else Firmament.identifier("firmament:widget/checkbox_unchecked"),
			0, 0,
			16, 16
		)
	}

	var isClicking = false

	override fun mouseEvent(mouseEvent: MouseEvent, context: GuiImmediateContext): Boolean {
		if (mouseEvent is MouseEvent.Click) {
			if (isClicking && !mouseEvent.mouseState && mouseEvent.mouseButton == 0) {
				isClicking = false
				if (context.isHovered)
					state.set(value)
				return true
			}
			if (mouseEvent.mouseState && mouseEvent.mouseButton == 0 && context.isHovered) {
				requestFocus()
				isClicking = true
				return true
			}
		}
		return false
	}
}