HumbleUI / JWM

Cross-platform window management and OS integration library for Java
Apache License 2.0
546 stars 44 forks source link

Jetpack Compose example #172

Open DevSrSouza opened 2 years ago

DevSrSouza commented 2 years ago

I saw that Compose-jb now was an experimental example for LWJGL/GLFW using ComposeScene.

Is possible, with this new API from Compose, be able to use with JWM? If so, would be awesome to see a code sample.

tonsky commented 2 years ago

Should be possible, yes. Do you want to make a PR with an example?

DevSrSouza commented 2 years ago

I don't know JWM enough to do that, I think.

tonsky commented 2 years ago

Great places to start is https://github.com/HumbleUI/JWM/blob/main/docs/Getting%20Started.md and https://github.com/HumbleUI/JWM/blob/main/examples/dashboard/java/Example.java. Let me know if you have any questions. I’d do it myself but I am not sure how long it might be delayed because of conflicting priorities

DevSrSouza commented 2 years ago

cc @smallshen

GavinRay97 commented 2 years ago

Had a look at that example l, am pretty sure you could integrate it easily.

You need access to just 2 things for this to work:

Here is what it should look like: (You would need to sort out the remaining glfw() calls because JWM manages these internally I believe)

fun main() {
    var width = 640
    var height = 480

    // Initialize JWM OpenGL
    // Then:
    var surface = // get JWM GL Surface
    val windowHandle = //get JWM GL Window Handle

    val glfwDispatcher = GlfwCoroutineDispatcher() // a custom coroutine dispatcher, in which Compose will run
    glfwSetWindowCloseCallback(windowHandle) { glfwDispatcher.stop() }

    lateinit var composeScene: ComposeScene

    fun render() {
       // You might need to change this call, not sure what the proper code is to get the canvas from the surface
        surface.canvas.clear(Color.WHITE)
        composeScene.constraints = Constraints(maxWidth = width, maxHeight = height)
        composeScene.render(surface.canvas, System.nanoTime())

        context.flush()
        glfwSwapBuffers(windowHandle)
    }

    val frameDispatcher = FrameDispatcher(glfwDispatcher) { render() }

    val density = Density(glfwGetWindowContentScale(windowHandle))
    composeScene = ComposeScene(glfwDispatcher, density, invalidate = frameDispatcher::scheduleFrame)

    glfwSetWindowSizeCallback(windowHandle) { _, windowWidth, windowHeight ->
        width = windowWidth
        height = windowHeight
        surface.close()
        surface = createSurface(width, height, context)

        glfwSwapInterval(0)
        render()
        glfwSwapInterval(1)
    }

    composeScene.subscribeToGLFWEvents(windowHandle)
    composeScene.setContent { App() }
    glfwShowWindow(windowHandle)

    glfwDispatcher.runLoop()

    composeScene.close()
    glfwDestroyWindow(windowHandle)

    exitProcess(0)
}
smallshen commented 2 years ago

@DevSrSouza https://github.com/smallshen/JWM-Compose