Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion alchemist-composeui/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Libs.alchemist
import Util.devServer
import Util.webCommonConfiguration
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
Expand Down Expand Up @@ -30,11 +31,22 @@ kotlin {
sourceSets {
val commonMain by getting {
dependencies {
api(alchemist("graphql"))
implementation(compose.runtime)
implementation(compose.ui)
implementation(compose.foundation)
implementation(compose.material)
implementation(compose.material3)
implementation(compose.components.resources)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.apollo.runtime)
}
}

val jvmMain by getting {
dependencies {
implementation(compose.desktop.currentOs)
implementation(libs.kotlin.coroutines.swing)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,37 +9,127 @@

package it.unibo.alchemist.boundary.composeui

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.apollographql.apollo3.api.Error
import it.unibo.alchemist.boundary.composeui.viewmodels.SimulationStatus
import it.unibo.alchemist.boundary.composeui.viewmodels.SimulationViewModel

/**
* Application entry point, this will be rendered the same in all the platforms.
*/
@Composable
fun app() {
MaterialTheme {
var showContent by remember { mutableStateOf(false) }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = { showContent = !showContent }) {
Text("Click me!")
}
AnimatedVisibility(showContent) {
val greeting = remember { getPlatform() }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Text("Compose: $greeting")
fun App(viewModel: SimulationViewModel = viewModel { SimulationViewModel() }) {
val status by viewModel.status.collectAsStateWithLifecycle()
val errors by viewModel.errors.collectAsStateWithLifecycle()
val nodes by viewModel.nodes.collectAsStateWithLifecycle()
Scaffold(
topBar = { TopBar(status) },
) { innerPadding ->
Column(
modifier = Modifier.padding(innerPadding).padding(horizontal = 8.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
ControlButton(status, viewModel::play, viewModel::pause)
OutlinedCard(
modifier = Modifier.fillMaxSize(),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface,
),
border = BorderStroke(1.dp, Color.Black),
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.verticalScroll(
rememberScrollState(),
),
) {
if (errors.isNotEmpty()) {
ErrorDialog(viewModel::fetch, errors)
}
for (node in nodes) {
NodeDrawer(node.id)
}
}
}
}
}
}

/**
* Top bar put on top of the application.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopBar(status: SimulationStatus) {
TopAppBar(
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
titleContentColor = MaterialTheme.colorScheme.primary,
),
title = {
Text(
"Simulation: $status",
)
},
)
}

/**
* Button to control the simulation.
*/
@Composable
fun ControlButton(status: SimulationStatus, resume: () -> Unit, pause: () -> Unit) {
if (status == SimulationStatus.Running) {
Button(onClick = { pause() }) {
Text("Pause", modifier = Modifier.padding(8.dp))
}
} else {
Button(onClick = { resume() }) {
Text("Resume", modifier = Modifier.padding(8.dp))
}
}
}

/**
* Display the error dialog, currently used to circumvent the null issue we're facing when subscribing to simulation.
*/
@Composable
fun ErrorDialog(dismiss: () -> Unit, errors: List<Error>) {
AlertDialog(
onDismissRequest = dismiss,
title = { Text("Error") },
text = {
for (error in errors) {
Text(error.message)
}
},
confirmButton = {
Button(onClick = dismiss) {
Text("OK")
}
},
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2010-2025, Danilo Pianini and contributors
* listed, for each module, in the respective subproject's build.gradle.kts file.
*
* This file is part of Alchemist, and is distributed under the terms of the
* GNU General Public License, with a linking exception,
* as described in the file LICENSE in the Alchemist distribution's top directory.
*/

package it.unibo.alchemist.boundary.composeui

import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import it.unibo.alchemist.boundary.composeui.viewmodels.NodeViewModel

/**
* Display the information of a node, subscribing to its own channel for data.
*/
@Composable
fun NodeDrawer(nodeId: Int) {
val nodeModel: NodeViewModel = viewModel(key = "node-$nodeId") { NodeViewModel(nodeId) }
val nodeInfo by nodeModel.nodeInfo.collectAsStateWithLifecycle()
Text("Node $nodeId: $nodeInfo")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright (C) 2010-2025, Danilo Pianini and contributors
* listed, for each module, in the respective subproject's build.gradle.kts file.
*
* This file is part of Alchemist, and is distributed under the terms of the
* GNU General Public License, with a linking exception,
* as described in the file LICENSE in the Alchemist distribution's top directory.
*/

package it.unibo.alchemist.boundary.composeui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Error
import it.unibo.alchemist.boundary.graphql.client.GraphQLClientFactory
import it.unibo.alchemist.boundary.graphql.client.NodeInfoSubscription
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class Molecule(val name: String)

data class MoleculeConcentration(val concentration: String, val molecule: Molecule)

data class NodeInfo(
val id: Int,
val moleculeCount: Int,
val properties: List<String>,
val contents: List<MoleculeConcentration>,
)

class NodeViewModel(private val nodeId: Int) : ViewModel() {
private val _nodeInfo = MutableStateFlow<NodeInfo?>(null)
val nodeInfo = _nodeInfo.asStateFlow()

private val _errors = MutableStateFlow<List<Error>>(emptyList())
val errors = _errors.asStateFlow()

// TODO: parameterize the host and port and separate client in different file
private val client = GraphQLClientFactory.subscriptionClient(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to add URL and port as configuration/parameter of NodeViewModel

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I've actually left this as is for a couple of reasons:

  1. When launching the GUI through the ComposeMonitor, the simulation file provides the fields for the connection, these fields then can be used to generate a client inside a Dependency Injection mechanism (or simply a Factory) that then provides the the dependency to every ViewModel
  2. This in fact is not the case for the WASM/JS build, that probably needs an additional View to allow the user to set the data.

"127.0.0.1",
3000,
)

private fun load() {
_errors.value = emptyList()
viewModelScope.launch {
client.subscription(NodeInfoSubscription(nodeId))
.toFlow()
.collect { response ->
response.data?.let { data ->
_nodeInfo.value = NodeInfo(
data.environment.nodeById.id,
data.environment.nodeById.moleculeCount,
data.environment.nodeById.properties,
data.environment.nodeById.contents.entries.map {
MoleculeConcentration(
it.concentration,
Molecule(it.molecule.name),
)
},
)
}
}
}
}

init {
load()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright (C) 2010-2025, Danilo Pianini and contributors
* listed, for each module, in the respective subproject's build.gradle.kts file.
*
* This file is part of Alchemist, and is distributed under the terms of the
* GNU General Public License, with a linking exception,
* as described in the file LICENSE in the Alchemist distribution's top directory.
*/

package it.unibo.alchemist.boundary.composeui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Error
import it.unibo.alchemist.boundary.graphql.client.GraphQLClientFactory
import it.unibo.alchemist.boundary.graphql.client.PauseSimulationMutation
import it.unibo.alchemist.boundary.graphql.client.PlaySimulationMutation
import it.unibo.alchemist.boundary.graphql.client.SimulationSubscription
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

enum class SimulationStatus {
Init,
Ready,
Paused,
Running,
Terminated,
}

data class Node(val id: Int, val coordinates: List<Double>)

class SimulationViewModel : ViewModel() {
private val _nodes = MutableStateFlow<List<Node>>(emptyList())
private val _status = MutableStateFlow(SimulationStatus.Init)
private val _errors = MutableStateFlow<List<Error>>(emptyList())

val nodes = _nodes.asStateFlow()
val status = _status.asStateFlow()
val errors = _errors.asStateFlow()

// TODO: parameterize the host and port and separate client in different file
private val client = GraphQLClientFactory.subscriptionClient(
"127.0.0.1",
3000,
)

fun pause() {
viewModelScope.launch {
client.mutation(PauseSimulationMutation()).execute()
}
}

fun play() {
viewModelScope.launch {
client.mutation(PlaySimulationMutation()).execute()
}
}

fun fetch() {
_errors.value = emptyList()
viewModelScope.launch {
client.subscription(SimulationSubscription())
.toFlow()
.collect { response ->
if (response.hasErrors()) {
response.errors?.let { errors ->
_errors.update { errors }
}
}
response.data?.let { data ->
_status.update {
when (data.simulation.status) {
"READY" -> SimulationStatus.Ready
"PAUSED" -> SimulationStatus.Paused
"RUNNING" -> SimulationStatus.Running
"TERMINATED" -> SimulationStatus.Terminated
else -> SimulationStatus.Init
}
}
_nodes.value = data.simulation.environment.nodeToPos.entries.map {
Node(
id = it.id,
coordinates = it.position.coordinates,
)
}
}
}
}
}

init {
fetch()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import org.jetbrains.skiko.wasm.onWasmReady
fun main() {
onWasmReady {
ComposeViewport(checkNotNull(document.body)) {
app()
App()
}
}
}
Loading
Loading