A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
feat(status): live charts for phone and VM resources
ExTv78af071a3910
diff --git a/app/src/main/java/com/excp/podroid/ui/components/LiveLineChart.kt b/app/src/main/java/com/excp/podroid/ui/components/LiveLineChart.ktnew file mode 100644index 0000000..f6676fb--- /dev/null+++ b/app/src/main/java/com/excp/podroid/ui/components/LiveLineChart.kt@@ -0,0 +1,67 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ */+package com.excp.podroid.ui.components++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.material3.MaterialTheme+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.unit.dp++data class ChartSeries(+ val values: List<Float>,+ val color: Color,+)++@Composable+fun LiveLineChart(+ series: List<ChartSeries>,+ modifier: Modifier = Modifier,+ yMax: Float? = null,+ heightDp: Int = 120,+) {+ val gridColor = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f)+ Canvas(+ modifier = modifier+ .fillMaxWidth()+ .height(heightDp.dp),+ ) {+ val w = size.width+ val h = size.height+ if (w <= 0f || h <= 0f) return@Canvas++ // Horizontal grid+ for (i in 0..3) {+ val y = h * i / 3f+ drawLine(gridColor, Offset(0f, y), Offset(w, y), strokeWidth = 1f)+ }++ val peak = series.flatMap { it.values }.maxOrNull()?.coerceAtLeast(0.01f) ?: 1f+ val maxY = (yMax ?: (peak * 1.15f)).coerceAtLeast(0.01f)++ series.forEach { s ->+ if (s.values.size < 2) return@forEach+ val path = Path()+ val n = s.values.size+ s.values.forEachIndexed { i, v ->+ val x = if (n == 1) 0f else w * i / (n - 1)+ val y = h - (v.coerceIn(0f, maxY) / maxY) * h+ if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)+ }+ drawPath(+ path = path,+ color = s.color,+ style = Stroke(width = 2.5.dp.toPx(), cap = StrokeCap.Round),+ )+ }+ }+}diff --git a/app/src/main/java/com/excp/podroid/ui/components/MetricChartCard.kt b/app/src/main/java/com/excp/podroid/ui/components/MetricChartCard.ktnew file mode 100644index 0000000..f77d5ec--- /dev/null+++ b/app/src/main/java/com/excp/podroid/ui/components/MetricChartCard.kt@@ -0,0 +1,128 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * Metric tile: title, live line chart, colored legend rows.+ */+package com.excp.podroid.ui.components++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Card+import androidx.compose.material3.CardDefaults+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.excp.podroid.ui.theme.PodroidTokens++data class MetricLegend(+ val label: String,+ val value: String,+ val color: Color,+ val subtitle: String? = null,+)++@Composable+fun MetricChartCard(+ title: String,+ legends: List<MetricLegend>,+ series: List<ChartSeries>,+ modifier: Modifier = Modifier,+ yMax: Float? = null,+ unavailable: String? = null,+ timeHint: String? = null,+) {+ Card(+ modifier = modifier.fillMaxWidth(),+ shape = RoundedCornerShape(PodroidTokens.Radius.Chip),+ colors = CardDefaults.cardColors(+ containerColor = MaterialTheme.colorScheme.surface,+ ),+ elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),+ ) {+ Column(+ modifier = Modifier.padding(PodroidTokens.Spacing.MD),+ verticalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.titleSmall,+ fontWeight = FontWeight.SemiBold,+ color = MaterialTheme.colorScheme.onSurface,+ )++ if (unavailable != null) {+ Text(+ text = unavailable,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier+ .fillMaxWidth()+ .height(120.dp)+ .padding(top = PodroidTokens.Spacing.LG),+ )+ } else {+ LiveLineChart(series = series, yMax = yMax)+ if (timeHint != null) {+ Text(+ text = timeHint,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }++ legends.forEach { legend ->+ Row(+ modifier = Modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Spacer(+ modifier = Modifier+ .width(3.dp)+ .height(28.dp)+ .background(legend.color, RoundedCornerShape(1.dp)),+ )+ Spacer(modifier = Modifier.width(PodroidTokens.Spacing.SM))+ Column(modifier = Modifier.weight(1f)) {+ Text(+ text = legend.label,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurface,+ )+ if (legend.subtitle != null) {+ Text(+ text = legend.subtitle,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ Text(+ text = legend.value,+ style = MaterialTheme.typography.bodyMedium,+ fontFamily = FontFamily.Monospace,+ fontWeight = FontWeight.Medium,+ color = MaterialTheme.colorScheme.onSurface,+ )+ }+ }+ }+ }+}diff --git a/app/src/main/java/com/excp/podroid/ui/components/VmLoadGraph.kt b/app/src/main/java/com/excp/podroid/ui/components/VmLoadGraph.ktdeleted file mode 100644index 3487e8d..0000000--- a/app/src/main/java/com/excp/podroid/ui/components/VmLoadGraph.kt+++ /dev/null@@ -1,110 +0,0 @@-package com.excp.podroid.ui.components--import androidx.compose.foundation.Canvas-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.padding-import androidx.compose.material3.MaterialTheme-import androidx.compose.material3.Text-import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.graphics.Path-import androidx.compose.ui.graphics.StrokeCap-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.font.FontFamily-import androidx.compose.ui.unit.dp-import com.excp.podroid.R-import com.excp.podroid.ui.theme.PodroidTokens--@Composable-fun VmLoadGraph(- samples: List<Float>,- currentPercent: Float?,- modifier: Modifier = Modifier,- unavailableReason: String? = null,-) {- Column(modifier = modifier.fillMaxWidth()) {- val headline = when {- unavailableReason != null -> unavailableReason- currentPercent != null -> stringResource(R.string.status_vm_load_current, currentPercent.toInt())- samples.isNotEmpty() -> stringResource(R.string.status_vm_load_collecting)- else -> stringResource(R.string.status_vm_load_waiting)- }- Text(- text = headline,- style = MaterialTheme.typography.bodyMedium,- fontFamily = FontFamily.Monospace,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(bottom = PodroidTokens.Spacing.SM),- )-- if (unavailableReason != null) {- Text(- text = stringResource(R.string.status_vm_load_graph_hint),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- return- }-- val lineColor = MaterialTheme.colorScheme.primary- val fillColor = lineColor.copy(alpha = 0.18f)- val gridColor = MaterialTheme.colorScheme.outlineVariant-- Canvas(- modifier = Modifier- .fillMaxWidth()- .height(140.dp),- ) {- val w = size.width- val h = size.height- val pad = 4f-- for (fraction in listOf(0.25f, 0.5f, 0.75f)) {- val y = h - pad - (h - 2 * pad) * fraction- drawLine(- color = gridColor,- start = Offset(pad, y),- end = Offset(w - pad, y),- strokeWidth = 1f,- )- }-- if (samples.size < 2) return@Canvas-- val stepX = (w - 2 * pad) / (samples.size - 1).coerceAtLeast(1)- val points = samples.mapIndexed { i, pct ->- val x = pad + i * stepX- val y = h - pad - (pct.coerceIn(0f, 100f) / 100f) * (h - 2 * pad)- Offset(x, y)- }-- val fillPath = Path().apply {- moveTo(points.first().x, h - pad)- points.forEach { lineTo(it.x, it.y) }- lineTo(points.last().x, h - pad)- close()- }- drawPath(fillPath, fillColor)-- for (i in 0 until points.lastIndex) {- drawLine(- color = lineColor,- start = points[i],- end = points[i + 1],- strokeWidth = 3f,- cap = StrokeCap.Round,- )- }- }-- Text(- text = stringResource(R.string.status_vm_load_axis),- style = MaterialTheme.typography.labelSmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(top = PodroidTokens.Spacing.XS),- )- }-}diff --git a/app/src/main/java/com/excp/podroid/ui/screens/status/StatusScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/status/StatusScreen.ktindex 48f77b2..5148f31 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/status/StatusScreen.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/status/StatusScreen.kt@@ -1,46 +1,69 @@package com.excp.podroid.ui.screens.statusimport androidx.compose.animation.AnimatedContent+import androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.verticalScrollimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.filled.ArrowBackimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButton-import androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.MaterialTheme+import androidx.compose.material3.PrimaryTabRowimport androidx.compose.material3.Scaffold+import androidx.compose.material3.Tabimport androidx.compose.material3.Textimport androidx.compose.material3.windowsizeclass.WindowSizeClassimport androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipimport androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dpimport androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwnerimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport com.excp.podroid.Rimport com.excp.podroid.engine.EngineSelectionimport com.excp.podroid.engine.VmStateimport com.excp.podroid.ui.components.AdaptiveContainer+import com.excp.podroid.ui.components.ChartSeries+import com.excp.podroid.ui.components.MetricChartCard+import com.excp.podroid.ui.components.MetricLegendimport com.excp.podroid.ui.components.PodroidListRowimport com.excp.podroid.ui.components.PodroidSectionLabelimport com.excp.podroid.ui.components.PodroidTopBar-import com.excp.podroid.ui.components.VmLoadGraphimport com.excp.podroid.ui.theme.PodroidTokensimport com.excp.podroid.util.HostMetrics+private const val TAB_PHONE = 0+private const val TAB_VM = 1++// Reuse the app's own accent palette (PodroidTokens) for chart series rather than+// inventing a new one, so the dashboard stays visually consistent with the rest of+// the Material 3 theme in both light and dark mode.+private val ChartPrimary = PodroidTokens.Accent+private val ChartSecondary = PodroidTokens.Amber+@OptIn(ExperimentalMaterial3Api::class)@Composablefun StatusScreen(@@ -49,10 +72,25 @@ fun StatusScreen(viewModel: StatusViewModel = hiltViewModel(),) {val ui by viewModel.uiState.collectAsStateWithLifecycle()- val metrics = ui.metrics- val phoneRamUsedMb = (metrics.phoneTotalRamMb - metrics.phoneAvailRamMb).coerceAtLeast(0)- val phoneStorageUsedGb = (metrics.phoneStorageTotalGb - metrics.phoneStorageAvailGb)- .coerceAtLeast(0.0)+ var selectedTab by rememberSaveable { mutableIntStateOf(TAB_VM) }+ val lifecycleOwner = LocalLifecycleOwner.current++ // Live sampling only runs while the screen is actually visible, so backgrounding+ // the app (or navigating away) doesn't keep polling /proc and TrafficStats.+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ when (event) {+ Lifecycle.Event.ON_RESUME -> viewModel.setLiveActive(true)+ Lifecycle.Event.ON_PAUSE -> viewModel.setLiveActive(false)+ else -> Unit+ }+ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose {+ viewModel.setLiveActive(false)+ lifecycleOwner.lifecycle.removeObserver(observer)+ }+ }Scaffold(topBar = {@@ -72,205 +110,331 @@ fun StatusScreen(.fillMaxSize().padding(innerPadding),) {- Column(- modifier = Modifier- .fillMaxSize()- .verticalScroll(rememberScrollState())- .padding(horizontal = PodroidTokens.Spacing.XL, vertical = PodroidTokens.Spacing.LG),- verticalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.MD),- ) {- PodroidSectionLabel(stringResource(R.string.status_phone_section))- StatusMetricBar(- label = stringResource(R.string.ram_label),- detail = "${HostMetrics.formatMb(phoneRamUsedMb)} / ${HostMetrics.formatMb(metrics.phoneTotalRamMb)}",- progress = HostMetrics.percent(phoneRamUsedMb, metrics.phoneTotalRamMb),- )- StatusMetricBar(- label = stringResource(R.string.storage),- detail = "${HostMetrics.formatGb(phoneStorageUsedGb)} / ${HostMetrics.formatGb(metrics.phoneStorageTotalGb)}",- progress = HostMetrics.percent(phoneStorageUsedGb, metrics.phoneStorageTotalGb),- )- PodroidListRow(- label = stringResource(R.string.cpu_cores),- value = "${metrics.phoneCpuCores}",- )- // /proc/loadavg is SELinux-blocked for third-party apps on modern- // Android, so this is usually absent; hide the row rather than- // show a permanent placeholder.- if (metrics.loadAvg1 != null) {- PodroidListRow(- label = stringResource(R.string.status_load_average),- value = String.format(- "%.2f · %.2f · %.2f",- metrics.loadAvg1,- metrics.loadAvg5,- metrics.loadAvg15,- ),- mono = true,+ Column(modifier = Modifier.fillMaxSize()) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = PodroidTokens.Spacing.XL, vertical = PodroidTokens.Spacing.SM),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ StatusLiveBadge(active = ui.liveTick > 0L)+ }+ PrimaryTabRow(selectedTabIndex = selectedTab) {+ Tab(+ selected = selectedTab == TAB_PHONE,+ onClick = { selectedTab = TAB_PHONE },+ text = { Text(stringResource(R.string.status_tab_phone)) },)+ Tab(+ selected = selectedTab == TAB_VM,+ onClick = { selectedTab = TAB_VM },+ text = { Text(stringResource(R.string.status_tab_vm)) },+ )+ }+ when (selectedTab) {+ TAB_PHONE -> PhoneStatusTab(ui = ui)+ TAB_VM -> VmStatusTab(ui = ui)}+ }+ }+ }+}- Spacer(Modifier.height(PodroidTokens.Spacing.SM))- PodroidSectionLabel(stringResource(R.string.status_vm_section))- PodroidListRow(- label = stringResource(R.string.vm_status),- rightSlot = {- AnimatedContent(- targetState = vmStatusLabel(ui.vmState, ui.uptimeLabel),- label = "status_vm_status",- ) { text ->- Text(- text = text,- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- textAlign = TextAlign.End,- )- }- },- )- PodroidListRow(- label = stringResource(R.string.backend),- value = backendLabel(ui.engineSelection, ui.backendId),- mono = true,- )- PodroidListRow(- label = stringResource(R.string.phone_ip),- value = ui.phoneIp,- mono = true,- )- // A phone can hold several addresses at once (mobile data plus a WiFi or- // USB tether). Forwards listen on all of them, so listing the rest saves- // the user guessing which one a given PC can actually reach.- ui.phoneAddresses- .filter { it.address != ui.phoneIp }- .forEach { extra ->- PodroidListRow(- label = stringResource(R.string.phone_ip_also, extra.iface),- value = extra.address,- mono = true,- )- }+@Composable+private fun StatusLiveBadge(active: Boolean) {+ if (!active) return+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),+ ) {+ Box(+ modifier = Modifier+ .size(8.dp)+ .clip(CircleShape)+ .background(MaterialTheme.colorScheme.primary),+ )+ Text(+ text = stringResource(R.string.status_live_badge),+ style = MaterialTheme.typography.labelMedium,+ fontWeight = FontWeight.SemiBold,+ color = MaterialTheme.colorScheme.primary,+ )+ Text(+ text = stringResource(R.string.status_live_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}- Text(- text = stringResource(R.string.status_vm_load_graph_title),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurface,- modifier = Modifier.padding(top = PodroidTokens.Spacing.SM),- )- VmLoadGraph(- samples = ui.vmLoadHistory,- currentPercent = ui.vmLoadPercent,- unavailableReason = when {- ui.vmState !is VmState.Running -> stringResource(R.string.status_vm_load_stopped)- ui.vmLoadGraphUnavailable == "avf" -> stringResource(R.string.status_vm_load_avf_only)- else -> null- },- modifier = Modifier.padding(bottom = PodroidTokens.Spacing.SM),- )+@Composable+private fun PhoneStatusTab(ui: StatusUiState) {+ val metrics = ui.metrics+ val charts = ui.charts+ val phoneRamUsedMb = (metrics.phoneTotalRamMb - metrics.phoneAvailRamMb).coerceAtLeast(0)+ val phoneStorageUsedGb = (metrics.phoneStorageTotalGb - metrics.phoneStorageAvailGb).coerceAtLeast(0.0)+ val resource = stringResource(R.string.status_resource_phone)- StatusMetricBar(- label = stringResource(R.string.status_vm_ram_allocated),- detail = HostMetrics.formatMb(ui.vmRamMb.toLong()),- progress = if (metrics.emulatorRssMb != null && ui.vmRamMb > 0) {- HostMetrics.percent(metrics.emulatorRssMb, ui.vmRamMb.toLong())- } else null,- sublabel = metrics.emulatorRssMb?.let {- stringResource(R.string.status_emulator_rss, HostMetrics.formatMb(it))- },- )- PodroidListRow(- label = stringResource(R.string.cpu_cores),- value = "${ui.vmCpus}",- )- StatusMetricBar(- label = stringResource(R.string.status_vm_disk),- detail = "${HostMetrics.formatGb(metrics.vmDiskImageBytes)} / ${ui.storageSizeGb} GB",- progress = HostMetrics.percent(- metrics.vmDiskImageBytes,- ui.storageSizeGb.toLong() * 1024L * 1024L * 1024L,- ),- )- PodroidListRow(- label = stringResource(R.string.bandwidth_limit),- value = if (ui.bandwidthMbps <= 0) {- stringResource(R.string.bandwidth_unlimited)- } else {- "${ui.bandwidthMbps} Mbps"- },- )- PodroidListRow(- label = stringResource(R.string.load_balance),- value = if (ui.loadBalanceEnabled) {- stringResource(R.string.on)- } else {- stringResource(R.string.off)- },- )- PodroidListRow(- label = stringResource(R.string.port_forwards),- value = "${ui.portForwardCount}",- divider = false,- )+ Column(+ modifier = Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = PodroidTokens.Spacing.LG, vertical = PodroidTokens.Spacing.MD),+ verticalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.MD),+ ) {+ MetricChartCard(+ title = stringResource(R.string.status_metric_phone_cpu),+ series = listOf(ChartSeries(charts.phoneCpu, ChartPrimary)),+ yMax = 100f,+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.status_metric_cpu_legend),+ subtitle = resource,+ value = ui.phoneCpuPercent?.let { String.format("%.1f%%", it) }+ ?: stringResource(R.string.status_vm_load_collecting),+ color = ChartPrimary,+ ),+ ),+ )+ MetricChartCard(+ title = stringResource(R.string.status_metric_phone_ram),+ series = listOf(ChartSeries(charts.phoneRam, ChartSecondary)),+ yMax = 100f,+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.ram_label),+ subtitle = resource,+ value = "${HostMetrics.formatMb(phoneRamUsedMb)} / ${HostMetrics.formatMb(metrics.phoneTotalRamMb)}",+ color = ChartSecondary,+ ),+ ),+ )+ MetricChartCard(+ title = stringResource(R.string.status_metric_phone_storage),+ series = listOf(ChartSeries(charts.phoneStorage, ChartPrimary)),+ yMax = 100f,+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.storage),+ subtitle = resource,+ value = "${HostMetrics.formatGb(phoneStorageUsedGb)} / ${HostMetrics.formatGb(metrics.phoneStorageTotalGb)}",+ color = ChartPrimary,+ ),+ ),+ )+ MetricChartCard(+ title = stringResource(R.string.status_metric_network),+ series = listOf(+ ChartSeries(charts.netIn, ChartPrimary),+ ChartSeries(charts.netOut, ChartSecondary),+ ),+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.status_metric_network_in),+ subtitle = resource,+ value = formatRate(ui.netInBps),+ color = ChartPrimary,+ ),+ MetricLegend(+ label = stringResource(R.string.status_metric_network_out),+ subtitle = resource,+ value = formatRate(ui.netOutBps),+ color = ChartSecondary,+ ),+ ),+ )- Text(- text = stringResource(R.string.status_refresh_hint),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(top = PodroidTokens.Spacing.SM),+ PodroidSectionLabel(stringResource(R.string.status_phone_details))+ PodroidListRow(label = stringResource(R.string.cpu_cores), value = "${metrics.phoneCpuCores}")+ // /proc/loadavg is SELinux-blocked for third-party apps on modern Android, so+ // this is usually absent; hide the row rather than show a permanent placeholder.+ if (metrics.loadAvg1 != null) {+ PodroidListRow(+ label = stringResource(R.string.status_load_average),+ value = String.format("%.2f · %.2f · %.2f", metrics.loadAvg1, metrics.loadAvg5, metrics.loadAvg15),+ mono = true,+ )+ }+ PodroidListRow(label = stringResource(R.string.phone_ip), value = ui.phoneIp, mono = true)+ // A phone can hold several addresses at once (mobile data plus a WiFi or USB+ // tether). Forwards listen on all of them, so listing the rest saves the user+ // guessing which one a given PC can actually reach.+ ui.phoneAddresses+ .filter { it.address != ui.phoneIp }+ .forEach { extra ->+ PodroidListRow(+ label = stringResource(R.string.phone_ip_also, extra.iface),+ value = extra.address,+ mono = true,)}- }}}@Composable-private fun StatusMetricBar(- label: String,- detail: String,- progress: Float?,- sublabel: String? = null,-) {+private fun VmStatusTab(ui: StatusUiState) {+ val metrics = ui.metrics+ val charts = ui.charts+ val resource = stringResource(R.string.status_resource_vm)+ val vmCpuUnavailable = when {+ ui.vmState !is VmState.Running -> stringResource(R.string.status_vm_load_stopped)+ ui.vmLoadGraphUnavailable == "avf" -> stringResource(R.string.status_vm_load_avf_only)+ else -> null+ }+ val stopped = if (ui.vmState !is VmState.Running) stringResource(R.string.status_vm_load_stopped) else null+ val diskUsedPct = if (ui.storageSizeGb > 0) {+ metrics.vmDiskImageBytes.toDouble() / (ui.storageSizeGb.toLong() * 1024 * 1024 * 1024) * 100.0+ } else 0.0+ val lastDiskAct = charts.vmDiskActivity.lastOrNull() ?: 0f+ val availValue = if (ui.vmState is VmState.Running) "1" else "0"+Column(modifier = Modifier- .fillMaxWidth()- .padding(vertical = PodroidTokens.Spacing.SM),+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = PodroidTokens.Spacing.LG, vertical = PodroidTokens.Spacing.MD),+ verticalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.MD),) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically,- ) {- Text(label, style = MaterialTheme.typography.bodyMedium)- Text(- detail,- style = MaterialTheme.typography.bodyMedium,- fontFamily = FontFamily.Monospace,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- if (progress != null) {- Spacer(Modifier.height(PodroidTokens.Spacing.XS))- LinearProgressIndicator(- progress = { progress },- modifier = Modifier.fillMaxWidth(),- )- }- if (sublabel != null) {- Spacer(Modifier.height(PodroidTokens.Spacing.XS))- Text(- sublabel,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }+ MetricChartCard(+ title = stringResource(R.string.status_metric_vm_cpu),+ series = listOf(ChartSeries(charts.vmCpu, ChartPrimary)),+ yMax = 100f,+ unavailable = vmCpuUnavailable,+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.status_metric_cpu_legend),+ subtitle = resource,+ value = ui.vmLoadPercent?.let { String.format("%.2f%%", it) }+ ?: stringResource(R.string.status_vm_load_collecting),+ color = ChartPrimary,+ ),+ ),+ )+ MetricChartCard(+ title = stringResource(R.string.status_metric_vm_memory),+ series = listOf(ChartSeries(charts.vmRam, ChartSecondary)),+ unavailable = stopped,+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.status_metric_memory_legend),+ subtitle = resource,+ value = metrics.emulatorRssMb?.let { HostMetrics.formatMb(it) }+ ?: stringResource(R.string.status_unavailable),+ color = ChartSecondary,+ ),+ ),+ )+ MetricChartCard(+ title = stringResource(R.string.status_metric_vm_disk),+ series = listOf(ChartSeries(charts.vmDisk, ChartPrimary)),+ unavailable = stopped,+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.status_vm_disk),+ subtitle = resource,+ value = "${HostMetrics.formatGb(metrics.vmDiskImageBytes)} (${String.format("%.1f%%", diskUsedPct)})",+ color = ChartPrimary,+ ),+ ),+ )+ MetricChartCard(+ title = stringResource(R.string.status_metric_vm_disk_activity),+ series = listOf(ChartSeries(charts.vmDiskActivity, ChartSecondary)),+ unavailable = stopped,+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.status_metric_disk_write_legend),+ subtitle = resource,+ value = String.format("%.1f KB/sample", lastDiskAct),+ color = ChartSecondary,+ ),+ ),+ )+ MetricChartCard(+ title = stringResource(R.string.status_metric_vm_availability),+ series = listOf(ChartSeries(charts.vmAvailability, ChartPrimary)),+ yMax = 1f,+ timeHint = stringResource(R.string.status_chart_window),+ legends = listOf(+ MetricLegend(+ label = stringResource(R.string.status_metric_availability_legend),+ subtitle = resource,+ value = availValue,+ color = ChartPrimary,+ ),+ ),+ )++ PodroidSectionLabel(stringResource(R.string.status_vm_details))+ PodroidListRow(+ label = stringResource(R.string.vm_status),+ rightSlot = {+ AnimatedContent(+ targetState = vmStatusLabel(ui.vmState, ui.uptimeLabel, ui.bootStage),+ label = "status_vm_status",+ ) { text ->+ Text(+ text = text,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.End,+ )+ }+ },+ )+ PodroidListRow(+ label = stringResource(R.string.backend),+ value = backendLabel(ui.engineSelection, ui.backendId),+ mono = true,+ )+ PodroidListRow(label = stringResource(R.string.cpu_cores), value = "${ui.vmCpus}")+ PodroidListRow(+ label = stringResource(R.string.status_vm_ram_allocated),+ value = HostMetrics.formatMb(ui.vmRamMb.toLong()),+ )+ PodroidListRow(+ label = stringResource(R.string.bandwidth_limit),+ value = if (ui.bandwidthMbps <= 0) {+ stringResource(R.string.bandwidth_unlimited)+ } else {+ "${ui.bandwidthMbps} Mbps"+ },+ )+ PodroidListRow(+ label = stringResource(R.string.load_balance),+ value = if (ui.loadBalanceEnabled) stringResource(R.string.on) else stringResource(R.string.off),+ )+ PodroidListRow(+ label = stringResource(R.string.port_forwards),+ value = "${ui.portForwardCount}",+ divider = false,+ )+ }+}++@Composable+private fun formatRate(bytesPerSec: Float?): String {+ if (bytesPerSec == null) return stringResource(R.string.status_vm_load_collecting)+ return when {+ bytesPerSec >= 1024f * 1024f -> String.format("%.2f MiB/s", bytesPerSec / (1024f * 1024f))+ bytesPerSec >= 1024f -> String.format("%.1f KiB/s", bytesPerSec / 1024f)+ else -> String.format("%.0f B/s", bytesPerSec)}}@Composable-private fun vmStatusLabel(vmState: VmState, uptime: String?): String = when (vmState) {+private fun vmStatusLabel(vmState: VmState, uptime: String?, bootStage: String): String = when (vmState) {is VmState.Running -> uptime?.let { "${stringResource(R.string.status_running)} · $it" }?: stringResource(R.string.status_running)- is VmState.Starting -> stringResource(R.string.status_starting)+ is VmState.Starting -> bootStage.ifEmpty { stringResource(R.string.status_starting) }is VmState.Error -> stringResource(R.string.status_error)else -> stringResource(R.string.status_stopped)}@@ -280,8 +444,8 @@ private fun backendLabel(selection: EngineSelection, activeId: String): String {val activeLabel = if (activeId == "avf") stringResource(R.string.avf_kvm) else stringResource(R.string.qemu_tcg)return when (selection) {EngineSelection.AUTO -> "${stringResource(R.string.auto)} ($activeId)"- // Forced AVF but the actual pick fell back to QEMU (device can't run- // AVF) - say so instead of claiming AVF is active.+ // Forced AVF but the actual pick fell back to QEMU (device can't run AVF) -+ // say so instead of claiming AVF is active.EngineSelection.AVF -> if (activeId == "avf") activeLabel else activeLabel + stringResource(R.string.backend_fallback_suffix)EngineSelection.QEMU -> activeLabel}diff --git a/app/src/main/java/com/excp/podroid/ui/screens/status/StatusViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/status/StatusViewModel.ktindex 11d088a..28744f3 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/status/StatusViewModel.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/status/StatusViewModel.kt@@ -10,7 +10,10 @@ import com.excp.podroid.engine.EngineSelectionimport com.excp.podroid.engine.VmStateimport com.excp.podroid.util.HostMetricsimport com.excp.podroid.util.HostMetricsSnapshot+import com.excp.podroid.util.MetricHistory+import com.excp.podroid.util.NetworkRateSamplerimport com.excp.podroid.util.NetworkUtils+import com.excp.podroid.util.PhoneCpuSamplerimport com.excp.podroid.util.UptimeFormatterimport com.excp.podroid.util.VmLoadSamplerimport dagger.hilt.android.lifecycle.HiltViewModel@@ -24,14 +27,30 @@ import kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.stateInimport kotlinx.coroutines.isActiveimport kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextimport java.io.Fileimport javax.inject.Inject+data class StatusChartHistories(+ val phoneCpu: List<Float> = emptyList(),+ val phoneRam: List<Float> = emptyList(),+ val phoneStorage: List<Float> = emptyList(),+ val netIn: List<Float> = emptyList(),+ val netOut: List<Float> = emptyList(),+ val vmCpu: List<Float> = emptyList(),+ val vmRam: List<Float> = emptyList(),+ val vmDisk: List<Float> = emptyList(),+ val vmDiskActivity: List<Float> = emptyList(),+ val vmAvailability: List<Float> = emptyList(),+)+data class StatusUiState(val vmState: VmState = VmState.Idle,val backendId: String = "qemu",val engineSelection: EngineSelection = EngineSelection.AUTO,+ val bootStage: String = "",val uptimeLabel: String? = null,val phoneIp: String = "—",/** Every reachable IPv4 address, so a peer on a tether or second network is not left guessing. */@@ -43,8 +62,12 @@ data class StatusUiState(val loadBalanceEnabled: Boolean = false,val portForwardCount: Int = 0,val vmLoadPercent: Float? = null,- val vmLoadHistory: List<Float> = emptyList(),+ val phoneCpuPercent: Float? = null,+ val netInBps: Float? = null,+ val netOutBps: Float? = null,+ val liveTick: Long = 0L,val vmLoadGraphUnavailable: String? = null,+ val charts: StatusChartHistories = StatusChartHistories(),val metrics: HostMetricsSnapshot = HostMetricsSnapshot(phoneTotalRamMb = 0,phoneAvailRamMb = 0,@@ -70,92 +93,214 @@ class StatusViewModel @Inject constructor(private val _metrics = MutableStateFlow(defaultMetrics())private val _uptimeTick = MutableStateFlow(0L)private val _vmLoadPercent = MutableStateFlow<Float?>(null)- private val _vmLoadHistory = MutableStateFlow<List<Float>>(emptyList())private val _vmLoadUnavailable = MutableStateFlow<String?>(null)+ private val _chartHistories = MutableStateFlow(StatusChartHistories())+ private val _liveTick = MutableStateFlow(0L)+ private val _phoneIp = MutableStateFlow("—")+ private val _phoneAddresses = MutableStateFlow<List<NetworkUtils.LocalAddress>>(emptyList())+ private val _phoneCpuPercent = MutableStateFlow<Float?>(null)+ private val _netInBps = MutableStateFlow<Float?>(null)+ private val _netOutBps = MutableStateFlow<Float?>(null)+ private val _liveActive = MutableStateFlow(false)+ private var lastDiskBytes = 0L+ // Guards pollOnce(): the perpetual loop below and setLiveActive()'s immediate resume poll+ // both dispatch to Dispatchers.IO and would otherwise race on the samplers' unsynchronized+ // lastX fields and on the read-modify-write of _chartHistories.value.+ private val pollMutex = Mutex()private val loadSampler = VmLoadSampler()+ private val phoneCpuSampler = PhoneCpuSampler()+ private val networkSampler = NetworkRateSampler()++ companion object {+ private const val POLL_MS = 500L+ }val uiState: StateFlow<StatusUiState> = combine(combine(engine.state,+ engine.bootStage,settingsRepository.vmRamMb,settingsRepository.vmCpus,settingsRepository.storageSizeGb,- settingsRepository.bandwidthMbps,- ) { vmState, ram, cpus, storage, bandwidth ->- arrayOf(vmState, ram, cpus, storage, bandwidth)+ ) { vmState, bootStage, ram, cpus, storage ->+ arrayOf(vmState, bootStage, ram, cpus, storage)},combine(+ settingsRepository.bandwidthMbps,settingsRepository.loadBalanceEnabled,settingsRepository.engineSelection,portForwardRepository.rules,_metrics,- _uptimeTick,- ) { loadBal, engineSel, rules, metrics, tick ->- arrayOf(loadBal, engineSel, rules, metrics, tick)+ ) { bandwidth, loadBal, engineSel, rules, metrics ->+ arrayOf(bandwidth, loadBal, engineSel, rules, metrics)},combine(+ _uptimeTick,_vmLoadPercent,- _vmLoadHistory,_vmLoadUnavailable,- ) { pct, history, unavailable ->- arrayOf(pct, history, unavailable)+ _chartHistories,+ _phoneCpuPercent,+ ) { tick, pct, unavailable, charts, phoneCpu ->+ arrayOf(tick, pct, unavailable, charts, phoneCpu)+ },+ combine(+ _liveTick,+ _phoneIp,+ _phoneAddresses,+ _netInBps,+ _netOutBps,+ ) { live, ip, addrs, netIn, netOut ->+ arrayOf(live, ip, addrs, netIn, netOut)},engine.backendIdFlow,- ) { a, b, c, backendId ->+ ) { a, b, c, d, backendId ->val vmState = a[0] as VmState- val tick = b[4] as Long- // NetworkUtils enumerates NetworkInterface, which is blocking I/O; keep- // it off the main thread that this combine transform otherwise runs on.- val (phoneIp, phoneAddresses) = withContext(Dispatchers.IO) {- NetworkUtils.localIpv4(context) to NetworkUtils.allLocalIpv4(context)- }+ val tick = c[0] as Long+ val charts = c[3] as StatusChartHistoriesStatusUiState(vmState = vmState,backendId = backendId,- engineSelection = b[1] as EngineSelection,+ bootStage = a[1] as String,+ engineSelection = b[2] as EngineSelection,uptimeLabel = uptimeLabel(vmState, tick),- phoneIp = phoneIp,- phoneAddresses = phoneAddresses,- vmRamMb = a[1] as Int,- vmCpus = a[2] as Int,- storageSizeGb = a[3] as Int,- bandwidthMbps = a[4] as Int,- loadBalanceEnabled = b[0] as Boolean,- portForwardCount = (b[2] as List<*>).size,- vmLoadPercent = c[0] as Float?,- vmLoadHistory = c[1] as List<Float>,+ phoneIp = d[1] as String,+ phoneAddresses = d[2] as List<NetworkUtils.LocalAddress>,+ vmRamMb = a[2] as Int,+ vmCpus = a[3] as Int,+ storageSizeGb = a[4] as Int,+ bandwidthMbps = b[0] as Int,+ loadBalanceEnabled = b[1] as Boolean,+ portForwardCount = (b[3] as List<*>).size,+ vmLoadPercent = c[1] as Float?,+ phoneCpuPercent = c[4] as Float?,+ netInBps = d[3] as Float?,+ netOutBps = d[4] as Float?,+ liveTick = d[0] as Long,vmLoadGraphUnavailable = c[2] as String?,- metrics = b[3] as HostMetricsSnapshot,+ charts = charts,+ metrics = b[4] as HostMetricsSnapshot,)}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), StatusUiState())init {- refreshMetrics()+ // Phone address resolution is blocking I/O (NetworkInterface enumeration); seed it once+ // off the main thread so the IP shows immediately instead of waiting for the first resume.+ viewModelScope.launch(Dispatchers.IO) { refreshPhoneAddresses() }viewModelScope.launch {while (isActive) {- delay(2_000)- withContext(Dispatchers.IO) {- refreshMetrics()- sampleVmLoad()+ if (_liveActive.value) {+ withContext(Dispatchers.IO) { pollMutex.withLock { if (_liveActive.value) pollOnce() } }}- if (engine.state.value is VmState.Running) {- _uptimeTick.value = System.currentTimeMillis()+ delay(POLL_MS)+ }+ }+ }++ /** Starts/stops live sampling with the screen's lifecycle so it never runs in the background. */+ fun setLiveActive(active: Boolean) {+ _liveActive.value = active+ if (active) {+ viewModelScope.launch {+ withContext(Dispatchers.IO) { pollMutex.withLock { if (_liveActive.value) pollOnce() } }+ }+ } else {+ // Same pollMutex as pollOnce(): the pause reset and a resume poll are separate+ // coroutines that acquire this lock in no guaranteed order, so a fast pause-then-resume+ // could otherwise run the stale reset after the fresh poll, or a resume poll could land+ // after the reset. Re-checking _liveActive.value inside the lock makes the latest state+ // win regardless of which coroutine acquired the lock first.+ viewModelScope.launch {+ withContext(Dispatchers.IO) {+ pollMutex.withLock {+ if (!_liveActive.value) {+ loadSampler.reset()+ phoneCpuSampler.reset()+ networkSampler.reset()+ lastDiskBytes = 0L+ _chartHistories.value = StatusChartHistories()+ _vmLoadPercent.value = null+ _phoneCpuPercent.value = null+ _netInBps.value = null+ _netOutBps.value = null+ }+ }}}}}+ private fun pollOnce() {+ refreshMetrics()+ updatePhoneCharts()+ sampleVmLoad()+ sampleNetwork()+ refreshPhoneAddresses()+ _liveTick.value = System.currentTimeMillis()+ if (engine.state.value is VmState.Running) {+ _uptimeTick.value = System.currentTimeMillis()+ }+ }++ private fun refreshPhoneAddresses() {+ _phoneIp.value = NetworkUtils.localIpv4(context)+ _phoneAddresses.value = NetworkUtils.allLocalIpv4(context)+ }++ private fun updatePhoneCharts() {+ val m = _metrics.value+ val ramUsedPct = if (m.phoneTotalRamMb > 0) {+ ((m.phoneTotalRamMb - m.phoneAvailRamMb).toFloat() / m.phoneTotalRamMb * 100f)+ } else 0f+ val storageUsedPct = if (m.phoneStorageTotalGb > 0) {+ ((m.phoneStorageTotalGb - m.phoneStorageAvailGb) / m.phoneStorageTotalGb * 100.0).toFloat()+ } else 0f+ var h = _chartHistories.value.copy(+ phoneRam = MetricHistory.append(_chartHistories.value.phoneRam, ramUsedPct),+ phoneStorage = MetricHistory.append(_chartHistories.value.phoneStorage, storageUsedPct),+ )+ phoneCpuSampler.samplePercent()?.let { pct ->+ _phoneCpuPercent.value = pct+ h = h.copy(phoneCpu = MetricHistory.append(h.phoneCpu, pct))+ }+ _chartHistories.value = h+ }++ private fun sampleNetwork() {+ val sample = networkSampler.sample() ?: return+ _netInBps.value = sample.rxBytesPerSec+ _netOutBps.value = sample.txBytesPerSec+ val h = _chartHistories.value+ _chartHistories.value = h.copy(+ netIn = MetricHistory.append(h.netIn, sample.rxBytesPerSec),+ netOut = MetricHistory.append(h.netOut, sample.txBytesPerSec),+ )+ }+fun refreshMetrics() {val storageImg = File(context.filesDir, "storage.img")- val rss = if (engine.state.value is VmState.Running) engine.emulatorRssMb() else null+ val running = engine.state.value is VmState.Running+ val rss = if (running) engine.emulatorRssMb() else null_metrics.value = HostMetrics.snapshot(context, storageImg, rss)++ val diskBytes = if (storageImg.isFile) HostMetrics.diskFootprintBytes(storageImg) else 0L+ val diskDeltaKb = if (lastDiskBytes > 0L && diskBytes >= lastDiskBytes) {+ (diskBytes - lastDiskBytes) / 1024f+ } else 0f+ lastDiskBytes = diskBytes++ val h = _chartHistories.value+ _chartHistories.value = h.copy(+ vmDisk = if (running) MetricHistory.append(h.vmDisk, diskBytes.toFloat()) else h.vmDisk,+ vmDiskActivity = if (running) MetricHistory.append(h.vmDiskActivity, diskDeltaKb) else h.vmDiskActivity,+ vmRam = if (rss != null) MetricHistory.append(h.vmRam, rss.toFloat()) else h.vmRam,+ vmAvailability = MetricHistory.append(h.vmAvailability, if (running) 1f else 0f),+ )}private fun sampleVmLoad() {if (engine.state.value !is VmState.Running) {loadSampler.reset()_vmLoadPercent.value = null- _vmLoadHistory.value = emptyList()_vmLoadUnavailable.value = nullreturn}@@ -164,7 +309,6 @@ class StatusViewModel @Inject constructor(if (pid == null) {loadSampler.reset()_vmLoadPercent.value = null- _vmLoadHistory.value = emptyList()_vmLoadUnavailable.value = "avf"return}@@ -172,7 +316,8 @@ class StatusViewModel @Inject constructor(_vmLoadUnavailable.value = nullval pct = loadSampler.sampleCpuPercent(pid, uiState.value.vmCpus) ?: return_vmLoadPercent.value = pct- _vmLoadHistory.value = (_vmLoadHistory.value + pct).takeLast(VmLoadSampler.MAX_SAMPLES)+ val h = _chartHistories.value+ _chartHistories.value = h.copy(vmCpu = MetricHistory.append(h.vmCpu, pct))}private fun defaultMetrics(): HostMetricsSnapshot {diff --git a/app/src/main/java/com/excp/podroid/util/MetricHistory.kt b/app/src/main/java/com/excp/podroid/util/MetricHistory.ktnew file mode 100644index 0000000..d7cf5e3--- /dev/null+++ b/app/src/main/java/com/excp/podroid/util/MetricHistory.kt@@ -0,0 +1,12 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ */+package com.excp.podroid.util++object MetricHistory {+ const val MAX_SAMPLES = 120 // ~1 min at 500ms++ fun append(history: List<Float>, value: Float, max: Int = MAX_SAMPLES): List<Float> =+ (history + value).takeLast(max)+}diff --git a/app/src/main/java/com/excp/podroid/util/NetworkRateSampler.kt b/app/src/main/java/com/excp/podroid/util/NetworkRateSampler.ktnew file mode 100644index 0000000..9bc8393--- /dev/null+++ b/app/src/main/java/com/excp/podroid/util/NetworkRateSampler.kt@@ -0,0 +1,59 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * App UID TrafficStats deltas for Status network charts.+ */+package com.excp.podroid.util++import android.net.TrafficStats+import android.os.Process+import android.os.SystemClock++data class NetworkRateSample(+ val rxBytesPerSec: Float,+ val txBytesPerSec: Float,+ val rxTotalBytes: Long,+ val txTotalBytes: Long,+)++class NetworkRateSampler(+ private val nowMs: () -> Long = { SystemClock.elapsedRealtime() },+ private val readBytes: () -> Pair<Long, Long>? = {+ val uid = Process.myUid()+ val rx = TrafficStats.getUidRxBytes(uid)+ val tx = TrafficStats.getUidTxBytes(uid)+ if (rx < 0 || tx < 0) null else rx to tx+ },+) {+ private var lastRx: Long? = null+ private var lastTx: Long? = null+ private var lastTimeMs: Long? = null++ fun reset() {+ lastRx = null+ lastTx = null+ lastTimeMs = null+ }++ fun sample(): NetworkRateSample? {+ val bytes = readBytes() ?: return null+ val (rx, tx) = bytes+ val now = nowMs()+ val prevRx = lastRx+ val prevTx = lastTx+ val prevTime = lastTimeMs+ lastRx = rx+ lastTx = tx+ lastTimeMs = now+ if (prevRx == null || prevTx == null || prevTime == null) return null+ val dt = (now - prevTime) / 1000.0+ if (dt <= 0.0) return null+ return NetworkRateSample(+ rxBytesPerSec = ((rx - prevRx).coerceAtLeast(0) / dt).toFloat(),+ txBytesPerSec = ((tx - prevTx).coerceAtLeast(0) / dt).toFloat(),+ rxTotalBytes = rx,+ txTotalBytes = tx,+ )+ }+}diff --git a/app/src/main/java/com/excp/podroid/util/PhoneCpuSampler.kt b/app/src/main/java/com/excp/podroid/util/PhoneCpuSampler.ktnew file mode 100644index 0000000..8a3c55a--- /dev/null+++ b/app/src/main/java/com/excp/podroid/util/PhoneCpuSampler.kt@@ -0,0 +1,60 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * Samples phone-wide CPU use from /proc/stat for Status charts.+ */+package com.excp.podroid.util++import android.os.SystemClock+import java.io.File++class PhoneCpuSampler(+ private val nowMs: () -> Long = { SystemClock.elapsedRealtime() },+ private val readTotals: () -> Pair<Long, Long>? = { readCpuTotals() },+) {+ private var lastIdle: Long? = null+ private var lastTotal: Long? = null+ private var lastTimeMs: Long? = null++ fun reset() {+ lastIdle = null+ lastTotal = null+ lastTimeMs = null+ }++ /** Phone CPU busy percent 0-100, or null until a second sample exists. */+ fun samplePercent(): Float? {+ val totals = readTotals() ?: return null+ val (idle, total) = totals+ val now = nowMs()+ val prevIdle = lastIdle+ val prevTotal = lastTotal+ lastIdle = idle+ lastTotal = total+ lastTimeMs = now+ if (prevIdle == null || prevTotal == null) return null++ val dIdle = (idle - prevIdle).coerceAtLeast(0)+ val dTotal = (total - prevTotal).coerceAtLeast(0)+ if (dTotal <= 0) return null+ val busy = 1.0 - (dIdle.toDouble() / dTotal.toDouble())+ return (busy * 100.0).toFloat().coerceIn(0f, 100f)+ }++ companion object {+ fun readCpuTotals(): Pair<Long, Long>? {+ return try {+ val line = File("/proc/stat").bufferedReader().use { it.readLine() } ?: return null+ if (!line.startsWith("cpu ")) return null+ val parts = line.split(Regex("\\s+")).drop(1).mapNotNull { it.toLongOrNull() }+ if (parts.size < 4) return null+ val idle = parts[3] + parts.getOrElse(4) { 0L } // idle + iowait+ val total = parts.sum()+ idle to total+ } catch (_: Exception) {+ null+ }+ }+ }+}diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xmlindex 6811d94..0930269 100644--- a/app/src/main/res/values-zh/strings.xml+++ b/app/src/main/res/values-zh/strings.xml@@ -143,18 +143,40 @@<!-- Status monitor --><string name="status_page_title">状态监控</string>+ <string name="status_tab_phone">手机</string>+ <string name="status_tab_vm">虚拟机</string><string name="status_phone_section">手机</string><string name="status_vm_section">虚拟机</string>+ <string name="status_phone_details">详情</string>+ <string name="status_vm_details">详情</string><string name="status_load_average">平均负载(1 / 5 / 15 分钟)</string><string name="status_vm_ram_allocated">虚拟机内存(已分配)</string><string name="status_emulator_rss">模拟器占用 %1$s</string><string name="status_vm_disk">虚拟机磁盘镜像</string>+ <string name="status_unavailable">—</string><string name="status_error">错误</string>- <string name="status_refresh_hint">此页面打开时每 2 秒自动刷新。</string>+ <string name="status_live_badge">实时</string>+ <string name="status_live_hint">每秒更新 2 次</string>+ <string name="status_chart_window">最近约 1 分钟</string>+ <string name="status_resource_phone">手机</string>+ <string name="status_resource_vm">Podroid 虚拟机</string>+ <string name="status_metric_phone_cpu">CPU(平均)</string>+ <string name="status_metric_phone_ram">内存(手机)</string>+ <string name="status_metric_phone_storage">存储(手机)</string>+ <string name="status_metric_network">网络(总量)</string>+ <string name="status_metric_network_in">网络入站</string>+ <string name="status_metric_network_out">网络出站</string>+ <string name="status_metric_vm_cpu">CPU(平均)</string>+ <string name="status_metric_vm_memory">内存(模拟器)</string>+ <string name="status_metric_vm_disk">磁盘字节(总量)</string>+ <string name="status_metric_vm_disk_activity">磁盘活动</string>+ <string name="status_metric_vm_availability">虚拟机可用性</string>+ <string name="status_metric_cpu_legend">CPU 使用率(平均)</string>+ <string name="status_metric_memory_legend">模拟器 RSS</string>+ <string name="status_metric_disk_write_legend">磁盘增长</string>+ <string name="status_metric_availability_legend">虚拟机可用性(平均)</string><string name="status_vm_load_graph_title">虚拟机 CPU 负载</string>- <string name="status_vm_load_current">当前:%1$d%%</string><string name="status_vm_load_collecting">正在采集数据…</string>- <string name="status_vm_load_waiting">启动虚拟机后显示负载</string><string name="status_vm_load_stopped">虚拟机未运行</string><string name="status_vm_load_avf_only">负载图表仅在 QEMU 后端且虚拟机运行时可用</string><string name="status_vm_load_graph_hint">根据手机上模拟器进程的 CPU 占用计算,并按虚拟机分配的核心数归一化。</string>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex a68dbc3..fc35ae0 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -143,18 +143,40 @@<!-- Status monitor --><string name="status_page_title">Status</string>+ <string name="status_tab_phone">Phone</string>+ <string name="status_tab_vm">VM</string><string name="status_phone_section">Phone</string><string name="status_vm_section">Virtual machine</string>+ <string name="status_phone_details">Details</string>+ <string name="status_vm_details">Details</string><string name="status_load_average">Load average (1 / 5 / 15 min)</string><string name="status_vm_ram_allocated">VM RAM (allocated)</string><string name="status_emulator_rss">Emulator using %1$s</string><string name="status_vm_disk">VM disk image</string>+ <string name="status_unavailable">—</string><string name="status_error">Error</string>- <string name="status_refresh_hint">Refreshes every 2 seconds while this screen is open.</string>+ <string name="status_live_badge">LIVE</string>+ <string name="status_live_hint">2 updates per second</string>+ <string name="status_chart_window">Last ~1 min</string>+ <string name="status_resource_phone">Phone</string>+ <string name="status_resource_vm">Podroid VM</string>+ <string name="status_metric_phone_cpu">CPU (average)</string>+ <string name="status_metric_phone_ram">Memory (phone)</string>+ <string name="status_metric_phone_storage">Storage (phone)</string>+ <string name="status_metric_network">Network (total)</string>+ <string name="status_metric_network_in">Network in</string>+ <string name="status_metric_network_out">Network out</string>+ <string name="status_metric_vm_cpu">CPU (average)</string>+ <string name="status_metric_vm_memory">Memory (emulator)</string>+ <string name="status_metric_vm_disk">Disk bytes (total)</string>+ <string name="status_metric_vm_disk_activity">Disk activity</string>+ <string name="status_metric_vm_availability">VM availability</string>+ <string name="status_metric_cpu_legend">CPU use (avg)</string>+ <string name="status_metric_memory_legend">Emulator RSS</string>+ <string name="status_metric_disk_write_legend">Disk growth</string>+ <string name="status_metric_availability_legend">VM availability (avg)</string><string name="status_vm_load_graph_title">VM CPU load</string>- <string name="status_vm_load_current">Current: %1$d%%</string><string name="status_vm_load_collecting">Collecting samples…</string>- <string name="status_vm_load_waiting">Start the VM to see load</string><string name="status_vm_load_stopped">VM is not running</string><string name="status_vm_load_avf_only">Load graph is available on the QEMU backend while the VM is running</string><string name="status_vm_load_graph_hint">Tracks the emulator process CPU use on your phone, normalized to the VM\'s allocated cores.</string>diff --git a/app/src/test/java/com/excp/podroid/util/MetricHistoryTest.kt b/app/src/test/java/com/excp/podroid/util/MetricHistoryTest.ktnew file mode 100644index 0000000..95a9761--- /dev/null+++ b/app/src/test/java/com/excp/podroid/util/MetricHistoryTest.kt@@ -0,0 +1,40 @@+package com.excp.podroid.util++import org.junit.Assert.assertEquals+import org.junit.Test++class MetricHistoryTest {++ @Test+ fun append_growsUntilMaxThenDropsOldest() {+ var history = emptyList<Float>()+ repeat(3) { i -> history = MetricHistory.append(history, i.toFloat(), max = 3) }+ assertEquals(listOf(0f, 1f, 2f), history)++ history = MetricHistory.append(history, 3f, max = 3)+ assertEquals(listOf(1f, 2f, 3f), history)+ }++ @Test+ fun append_keepsRingBufferAtExactlyMaxSamples() {+ var history = emptyList<Float>()+ repeat(200) { i -> history = MetricHistory.append(history, i.toFloat(), max = 120) }+ assertEquals(120, history.size)+ // The newest 120 values survive, in order; older ones are dropped.+ assertEquals(80f, history.first())+ assertEquals(199f, history.last())+ }++ @Test+ fun append_defaultMaxIsOneHundredTwenty() {+ var history = emptyList<Float>()+ repeat(150) { i -> history = MetricHistory.append(history, i.toFloat()) }+ assertEquals(MetricHistory.MAX_SAMPLES, history.size)+ }++ @Test+ fun append_belowMaxKeepsEverySample() {+ val history = MetricHistory.append(listOf(1f, 2f), 3f, max = 5)+ assertEquals(listOf(1f, 2f, 3f), history)+ }+}diff --git a/app/src/test/java/com/excp/podroid/util/NetworkRateSamplerTest.kt b/app/src/test/java/com/excp/podroid/util/NetworkRateSamplerTest.ktnew file mode 100644index 0000000..3dd2de8--- /dev/null+++ b/app/src/test/java/com/excp/podroid/util/NetworkRateSamplerTest.kt@@ -0,0 +1,85 @@+package com.excp.podroid.util++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class NetworkRateSamplerTest {++ /** Sampler with injected clock/byte-counter sources so the math is deterministic off-device. */+ private fun sampler(+ now: () -> Long,+ bytes: () -> Pair<Long, Long>?,+ ) = NetworkRateSampler(nowMs = now, readBytes = bytes)++ @Test+ fun sample_returnsNullOnFirstSample() {+ val s = sampler(now = { 1_000L }, bytes = { 100L to 200L })+ assertNull(s.sample())+ }++ @Test+ fun sample_returnsNullWhenCountersUnreadable() {+ val s = sampler(now = { 1_000L }, bytes = { null })+ assertNull(s.sample())+ }++ @Test+ fun sample_computesRatePerSecond() {+ var now = 0L+ var rx = 0L+ var tx = 0L+ val s = sampler(now = { now }, bytes = { rx to tx })++ assertNull(s.sample()) // warm-up++ now = 1_000L+ rx = 2_000L+ tx = 1_000L+ val sample = s.sample()!!+ assertEquals(2_000f, sample.rxBytesPerSec, 0.01f)+ assertEquals(1_000f, sample.txBytesPerSec, 0.01f)+ assertEquals(2_000L, sample.rxTotalBytes)+ assertEquals(1_000L, sample.txTotalBytes)+ }++ @Test+ fun sample_counterResetGivesNoNegativeRate() {+ var now = 0L+ var rx = 50_000L+ var tx = 50_000L+ val s = sampler(now = { now }, bytes = { rx to tx })++ assertNull(s.sample()) // warm-up++ // Interface counters reset (e.g. reconnect) and now report a smaller value than before.+ now = 1_000L+ rx = 100L+ tx = 100L+ val sample = s.sample()!!+ assertTrue(sample.rxBytesPerSec >= 0f)+ assertTrue(sample.txBytesPerSec >= 0f)+ assertEquals(0f, sample.rxBytesPerSec, 0.01f)+ assertEquals(0f, sample.txBytesPerSec, 0.01f)+ }++ @Test+ fun sample_returnsNullWhenClockDidNotAdvance() {+ val s = sampler(now = { 1_000L }, bytes = { 100L to 100L })+ assertNull(s.sample()) // warm-up+ assertNull(s.sample()) // same timestamp again -> dt <= 0+ }++ @Test+ fun reset_clearsWarmup() {+ var now = 0L+ val s = sampler(now = { now }, bytes = { 100L to 100L })++ assertNull(s.sample()) // warm-up+ now = 1_000L+ s.reset()+ // After reset the next sample is a warm-up again, so it returns null.+ assertNull(s.sample())+ }+}