Exit Full View

Games Cupboard / gamescupboard-client / src / commonMain / kotlin / uk / co / nickthecoder / gamescupboard / client / Toolbar.kt

package uk.co.nickthecoder.gamescupboard.client

import RunCommand
import com.soywiz.korge.annotations.KorgeExperimental
import com.soywiz.korge.ui.*
import com.soywiz.korge.view.*
import uk.co.nickthecoder.gamescupboard.common.CommandPrototype
import kotlin.math.max

fun Container.toolbarButton(label: String, action: () -> Unit): UIButton {
    val fakeText = Text(label, mySkin.textSize)
    val width = max(fakeText.width + toolbarButtonPadding * 2, toolbarButtonSize.toDouble())
    val button = UIButton(width, toolbarButtonSize.toDouble(), label)
    button.uiSkin = mySkin
    button.onPress.add { action() }
    addChild(button)
    return button
}

class Toolbar(width: Double, height: Double) : FixedSizeContainer(width, height) {

    private val marginX = toolbarMargin.toDouble()
    private val spacing = toolbarSpacing
    private val sendSpacing = 20.0

    private val background = roundRect(width + 2, height, 0.0, 0.0, toolbarColor)

    val chatInput = chatInput().apply {
        x = marginX
        y = (height - this.height) / 2
    }

    val sendButton = toolbarButton("Send") {
        chatInput.send()
    }

    private val restartButton = toolbarButton("Reset") {
        RunCommand("reset", emptyList()).send()
    }

    private val buttons = mutableListOf(restartButton)

    init {
        resize()
    }

    @OptIn(KorgeExperimental::class)
    fun resize() {
        val width = stage?.actualVirtualRight ?: 800.0
        // Deprecated? WFT? How can we change the width of a rectangle?
        background.width = width
        var tx = width - marginX
        for (button in buttons) {
            button.y = (height - button.height) / 2
            button.x = tx - button.width
            tx = button.x - spacing
        }
        sendButton.y = (height - sendButton.height) / 2
        sendButton.x = tx - sendSpacing - sendButton.width
        tx = sendButton.x - spacing

        // Deprecated? WFT? How can we change the width of a textInput?
        chatInput.textInput.width = tx - chatInput.x
    }

    fun addCommandPrototype(prototype: CommandPrototype) {
        val button = toolbarButton(prototype.label) {
            prototype.run()
        }
        buttons.add(button)
        resize()
    }

}