All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.peanuuutz.fork.ui.scene.toast.ComposeToast.kt Maven / Gradle / Ivy

The newest version!
package net.peanuuutz.fork.ui.scene.toast

import androidx.compose.runtime.Composable
import net.minecraft.client.toast.Toast
import net.minecraft.client.toast.ToastManager
import net.minecraft.client.util.math.MatrixStack
import net.peanuuutz.fork.render.vertex.currentTransformation
import net.peanuuutz.fork.ui.internal.GlobalUIContext
import net.peanuuutz.fork.ui.scene.screen.ScreenCanvas
import net.peanuuutz.fork.ui.ui.context.owner.OwnerContainer
import net.peanuuutz.fork.ui.ui.context.owner.OwnerContainerImpl
import net.peanuuutz.fork.ui.ui.draw.canvas.Canvas
import net.peanuuutz.fork.ui.ui.unit.FloatOffset
import net.peanuuutz.fork.util.fork.ForkLogger

abstract class ComposeToast(
    canvas: Canvas = ScreenCanvas()
) : Toast {
    @Composable
    abstract fun Content()

    fun init() {
        initInternal()
    }

    fun dispose() {
        disposeInternal()
    }

    // ======== Internal ========

    private val ownerContainer: OwnerContainer = OwnerContainerImpl()

    private val owner: ToastOwner = ToastOwner(
        context = GlobalUIContext.recomposer,
        container = ownerContainer,
        shouldReceiveEvents = false,
        canvas = canvas
    )

    init {
        ownerContainer.attach(owner)
    }

    private val contentLambda: @Composable () -> Unit = { Content() }

    override fun getWidth(): Int {
        return owner.size.width
    }

    override fun getHeight(): Int {
        return owner.size.height
    }

    private fun initInternal() {
        try {
            owner.setContent(contentLambda)
        } catch (e: Exception) {
            val message = "Exception occurred while initializing ${this::class.simpleName}"
            ForkLogger.error(message, e)
            dispose()
        }
    }

    override fun draw(matrices: MatrixStack, manager: ToastManager, startTime: Long): Toast.Visibility {
        return try {
            val transform = matrices.currentTransformation
            owner.position = FloatOffset(transform[3, 0], transform[3, 1])
            ownerContainer.draw()
            owner.state
        } catch (e: Exception) {
            val message = "Exception occurred while rendering ${this::class.simpleName}"
            ForkLogger.error(message, e)
            dispose()
            Toast.Visibility.HIDE
        }
    }

    private fun disposeInternal() {
        owner.exit()
        ownerContainer.dispose()
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy