ASMR/src/main/kotlin/net/shadowfacts/shadowui/UIView.kt

79 lines
2.1 KiB
Kotlin

package net.shadowfacts.shadowui
import com.mojang.blaze3d.platform.GlStateManager
import net.shadowfacts.kiwidsl.dsl
import net.shadowfacts.shadowui.geometry.UIRect
import net.shadowfacts.shadowui.util.Color
import net.shadowfacts.shadowui.util.RenderHelper
import no.birkett.kiwi.Solver
class UIView {
lateinit var solver: Solver
// in the coordinate system of the screen
val leftAnchor = LayoutVariable(this, "left")
val rightAnchor = LayoutVariable(this, "right")
val topAnchor = LayoutVariable(this, "top")
val bottomAnchor = LayoutVariable(this, "bottom")
val widthAnchor = LayoutVariable(this, "width")
val heightAnchor = LayoutVariable(this, "height")
val centerXAnchor = LayoutVariable(this, "centerX")
val centerYAnchor = LayoutVariable(this, "centerY")
// The rectangle for this view in the coordinate system of the parent view.
lateinit var frame: UIRect
// The rectangle for this view in its own coordinate system.
lateinit var bounds: UIRect
var backgroundColor = Color(0xff0000)
var parent: UIView? = null
val subviews = mutableListOf<UIView>()
fun addSubview(view: UIView) {
subviews.add(view)
view.parent = this
view.solver = solver
view.wasAdded()
}
fun wasAdded() {
createInternalConstraints()
}
fun createInternalConstraints() {
solver.dsl {
rightAnchor equalTo (leftAnchor + widthAnchor)
bottomAnchor equalTo (topAnchor + heightAnchor)
centerXAnchor equalTo (leftAnchor + widthAnchor / 2)
centerYAnchor equalTo (topAnchor + heightAnchor / 2)
}
}
fun didLayout() {
subviews.forEach(UIView::didLayout)
val parentLeft = parent?.leftAnchor?.value ?: 0.0
val parentTop = parent?.topAnchor?.value ?: 0.0
frame = UIRect(leftAnchor.value - parentLeft, topAnchor.value - parentTop, widthAnchor.value, heightAnchor.value)
bounds = UIRect(0.0, 0.0, widthAnchor.value, heightAnchor.value)
}
fun draw() {
GlStateManager.pushMatrix()
GlStateManager.translated(frame.left, frame.top, 0.0)
RenderHelper.fill(bounds, backgroundColor)
drawContent()
subviews.forEach(UIView::draw)
GlStateManager.popMatrix()
}
fun drawContent() {}
}