PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/client/screen/ScrollTrackView.kt

75 lines
2.1 KiB
Kotlin
Raw Normal View History

2021-03-26 02:16:28 +00:00
package net.shadowfacts.phycon.client.screen
2021-03-21 02:31:53 +00:00
import net.minecraft.util.Identifier
import net.minecraft.util.math.MathHelper
import net.shadowfacts.cacao.geometry.Point
import net.shadowfacts.cacao.geometry.Rect
import net.shadowfacts.cacao.util.MouseButton
import net.shadowfacts.cacao.util.texture.Texture
import net.shadowfacts.cacao.view.TextureView
import net.shadowfacts.cacao.view.View
import net.shadowfacts.phycon.PhysicalConnectivity
/**
* @author shadowfacts
*/
class ScrollTrackView(
val scrollPositionChanged: (ScrollTrackView) -> Unit,
): View() {
companion object {
private val THUMB = Texture(Identifier(PhysicalConnectivity.MODID, "textures/gui/terminal.png"), 52, 230)
private const val THUMB_WIDTH = 12.0
private const val THUMB_HEIGHT = 15.0
}
private lateinit var thumbView: TextureView
private var grabbedY: Double? = null
/**
* The [0,1] normalized position of the scroll thumb.
*/
var scrollPosition: Double
get() = thumbView.frame.top / (frame.height - THUMB_HEIGHT)
set(value) {
val newTop = MathHelper.clamp(value, 0.0, 1.0) * (frame.height - THUMB_HEIGHT)
thumbView.frame = Rect(0.0, newTop, THUMB_WIDTH, THUMB_HEIGHT)
}
init {
respondsToDragging = true
}
override fun wasAdded() {
super.wasAdded()
thumbView = addSubview(TextureView(THUMB).apply {
usesConstraintBasedLayout = false
frame = Rect(0.0, 0.0, THUMB_WIDTH, THUMB_HEIGHT)
})
}
2021-12-22 23:59:51 +00:00
override fun mouseDragged(startPoint: Point, delta: Point, mouseButton: MouseButton): Boolean {
if (grabbedY == null && startPoint !in thumbView.frame) {
val newCenter = MathHelper.clamp(startPoint.y, THUMB_HEIGHT / 2, frame.height - THUMB_HEIGHT / 2)
2021-03-21 02:31:53 +00:00
thumbView.frame = Rect(0.0, newCenter - THUMB_HEIGHT / 2, THUMB_WIDTH, THUMB_HEIGHT)
}
if (grabbedY == null) {
2021-12-22 23:59:51 +00:00
grabbedY = startPoint.y - thumbView.frame.top
2021-03-21 02:31:53 +00:00
}
2021-12-22 23:59:51 +00:00
val newTop = MathHelper.clamp(startPoint.y - grabbedY!!, 0.0, frame.height - THUMB_HEIGHT)
2021-03-21 02:31:53 +00:00
thumbView.frame = Rect(0.0, newTop, THUMB_WIDTH, THUMB_HEIGHT)
scrollPositionChanged(this)
return true
}
override fun mouseDragEnded(point: Point, mouseButton: MouseButton) {
grabbedY = null
}
}