Yokan / rebuild
Course 1 8624561

DeveloperSettingsScreen.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/developer/DeveloperSettingsScreen.kt

implementation203 lines
1package eu.friedcutlet.yokan.ui.screens.settings.developer23import androidx.compose.foundation.Canvas4import androidx.compose.foundation.layout.Arrangement5import androidx.compose.foundation.layout.FlowRow6import androidx.compose.foundation.layout.Column7import androidx.compose.foundation.layout.Row8import androidx.compose.foundation.layout.fillMaxWidth9import androidx.compose.foundation.layout.height10import androidx.compose.foundation.layout.padding11import androidx.compose.foundation.lazy.items12import androidx.compose.material3.FilterChip13import androidx.compose.material3.MaterialTheme14import androidx.compose.material3.Text15import androidx.compose.material3.TextButton16import androidx.compose.runtime.Composable17import androidx.compose.runtime.getValue18import androidx.compose.runtime.mutableStateOf19import androidx.compose.runtime.saveable.rememberSaveable20import androidx.compose.runtime.setValue21import androidx.compose.ui.Alignment22import androidx.compose.ui.Modifier23import androidx.compose.ui.geometry.Offset24import androidx.compose.ui.graphics.Path25import androidx.compose.ui.graphics.drawscope.Stroke26import androidx.compose.ui.semantics.contentDescription27import androidx.compose.ui.semantics.semantics28import androidx.compose.ui.text.style.TextAlign29import androidx.compose.ui.text.font.FontFamily30import androidx.compose.ui.unit.dp31import androidx.lifecycle.compose.collectAsStateWithLifecycle32import androidx.lifecycle.viewmodel.compose.viewModel33import eu.friedcutlet.yokan.database.DbSettings34import eu.friedcutlet.yokan.services.logging.LogEntry35import eu.friedcutlet.yokan.services.logging.LogSink36import eu.friedcutlet.yokan.services.logging.formatLogTimestamp37import eu.friedcutlet.yokan.services.system.ProcessMemoryUsage38import eu.friedcutlet.yokan.ui.screens.settings.InfoRow39import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold40import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection41import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile42import eu.friedcutlet.yokan.ui.screens.settings.data.formatBytes43import org.jetbrains.compose.resources.stringResource44import yokan.composeapp.generated.resources.Res45import yokan.composeapp.generated.resources.ui_clear4647@Composable48internal fun DeveloperSettingsRoute(49    title: String,50    settings: DbSettings,51    onUpdate: ((DbSettings) -> DbSettings) -> Unit,52    onBack: () -> Unit,53) {54    val model = viewModel { DeveloperSettingsViewModel() }55    val state by model.state.collectAsStateWithLifecycle()56    DeveloperSettingsScreen(title, settings, state, onUpdate, onClearLogs = model::clearLogs, onBack = onBack)57}5859@Composable60internal fun DeveloperSettingsScreen(61    title: String,62    settings: DbSettings,63    state: DeveloperDiagnosticsState,64    onUpdate: ((DbSettings) -> DbSettings) -> Unit,65    onClearLogs: () -> Unit,66    onBack: () -> Unit,67) {68    var problemsOnly by rememberSaveable { mutableStateOf(false) }69    SettingsScaffold(title, onBack) {70        item {71            SwitchTile(72                "Developer mode",73                "Allow recipe catalogs served from http://127.0.0.1 for local testing",74                settings.developerMode,75                { value -> onUpdate { it.copy(developerMode = value) } },76            )77        }78        item { StatRow("Uptime", formatDuration(state.uptimeMillis)) }7980        item { SettingsSection("Memory") }81        if (state.memorySupported) {82            item(key = "memory-graph") { MemoryGraph(state.memory) }83        } else {84            item { InfoRow("This platform does not report heap usage.") }85        }8687        item { SettingsSection("Network") }88        item { StatRow("Requests", state.network.requests.toString()) }89        item { StatRow("Transport failures", state.network.failures.toString()) }90        item { StatRow("HTTP errors (4xx/5xx)", state.network.httpErrors.toString()) }91        item { StatRow("Received", formatBytes(state.network.bytesReceived)) }9293        item { SettingsSection("Image cache") }94        val images = state.images95        item { StatRow("Memory-cache hits", "${images.memoryHits} (${percent(images.memoryHits, images.loads)})") }96        item { StatRow("Disk-cache hits", "${images.diskHits} (${percent(images.diskHits, images.loads)})") }97        item { StatRow("Network loads", "${images.networkLoads} (${percent(images.networkLoads, images.loads)})") }98        item { StatRow("Failed loads", images.errors.toString()) }99        state.imageCache?.let { cache ->100            item { StatRow("Memory cache", "${formatBytes(cache.memoryBytes)} of ${formatBytes(cache.memoryMaxBytes)}") }101            cache.diskBytes?.let { disk -> item { StatRow("Disk cache", "${formatBytes(disk)} of ${formatBytes(cache.diskMaxBytes ?: 0)}") } }102        }103104        item { SettingsSection("Logs") }105        item {106            StatRow(107                "Log file",108                if (settings.enableFileLogging) {109                    "${formatBytes(state.logFileBytes)} (max ${formatBytes(LogSink.MaxLogFileBytes * 2)}) · ${state.logFilePath.orEmpty()}"110                } else {111                    "Off (enable \"Logs on\" in About)"112                },113            )114        }115        item {116            FlowRow(117                modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),118                horizontalArrangement = Arrangement.spacedBy(8.dp),119            ) {120                FilterChip(selected = !problemsOnly, onClick = { problemsOnly = false }, label = { Text("All (${state.logs.size})") })121                FilterChip(selected = problemsOnly, onClick = { problemsOnly = true }, label = { Text("Errors & warnings (${state.problems.size})") })122                TextButton(onClick = onClearLogs) { Text(stringResource(Res.string.ui_clear)) }123            }124        }125        val entries = if (problemsOnly) state.problems else state.logs126        if (entries.isEmpty()) item { InfoRow("No log lines yet.") }127        items(entries, key = { it.seq }) { entry -> LogLine(entry) }128    }129}130131@Composable132private fun StatRow(label: String, value: String) {133    Row(134        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),135        horizontalArrangement = Arrangement.spacedBy(16.dp),136    ) {137        Text(label, style = MaterialTheme.typography.bodyMedium)138        Text(139            value,140            style = MaterialTheme.typography.bodyMedium,141            color = MaterialTheme.colorScheme.onSurfaceVariant,142            textAlign = TextAlign.End,143            modifier = Modifier.weight(1f),144        )145    }146}147148@Composable149private fun MemoryGraph(samples: List<ProcessMemoryUsage>) {150    val latest = samples.lastOrNull()151    val lineColor = MaterialTheme.colorScheme.primary152    val gridColor = MaterialTheme.colorScheme.outlineVariant153    val summary = latest?.let { "${formatBytes(it.usedBytes)} used of ${formatBytes(it.maxBytes)} max" } ?: "Sampling…"154    Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {155        Text(summary, style = MaterialTheme.typography.bodyMedium)156        Canvas(157            Modifier158                .fillMaxWidth()159                .height(120.dp)160                .padding(top = 8.dp)161                .semantics { contentDescription = "Heap usage over the last two minutes. $summary" },162        ) {163            drawLine(gridColor, Offset(0f, size.height), Offset(size.width, size.height))164            drawLine(gridColor, Offset(0f, 0f), Offset(size.width, 0f))165            val max = samples.maxOfOrNull { it.maxBytes }?.takeIf { it > 0 } ?: return@Canvas166            if (samples.size < 2) return@Canvas167            val step = size.width / (DeveloperSettingsViewModel.MemorySamples - 1)168            val startX = size.width - step * (samples.size - 1)169            val path = Path()170            samples.forEachIndexed { index, sample ->171                val x = startX + step * index172                val y = size.height * (1f - sample.usedBytes.toFloat() / max)173                if (index == 0) path.moveTo(x, y) else path.lineTo(x, y)174            }175            drawPath(path, lineColor, style = Stroke(width = 2.dp.toPx()))176        }177        Text(178            "Scale: 0 – ${formatBytes(samples.maxOfOrNull { it.maxBytes } ?: 0)} · last two minutes",179            style = MaterialTheme.typography.labelSmall,180            color = MaterialTheme.colorScheme.onSurfaceVariant,181        )182    }183}184185@Composable186private fun LogLine(entry: LogEntry) {187    val color = when (entry.level) {188        "ERROR" -> MaterialTheme.colorScheme.error189        "WARN" -> MaterialTheme.colorScheme.tertiary190        else -> MaterialTheme.colorScheme.onSurfaceVariant191    }192    Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)) {193        Text("${formatLogTimestamp(entry.timeMillis)} ${entry.level}", style = MaterialTheme.typography.labelSmall, color = color)194        Text(entry.message, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace)195    }196}197198private fun percent(part: Long, total: Long): String = if (total == 0L) "–" else "${part * 100 / total}%"199200private fun formatDuration(millis: Long): String {201    val seconds = millis / 1_000202    return "${seconds / 3_600}h ${(seconds % 3_600) / 60}m ${seconds % 60}s"203}204

Search chapters, reference and source filenames.