A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
feat(terminal): minimal top-sheet quick settings; custom font + theme import
ExTv0fca17612e5c
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.ktindex ddf15ff..2c39cde 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt@@ -2,8 +2,10 @@ package com.excp.podroid.ui.screens.terminalimport android.app.Activityimport android.view.WindowManager+import androidx.compose.foundation.ExperimentalFoundationApiimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.horizontalScrollimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.PaddingValues@@ -17,6 +19,7 @@ import androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.height@@ -30,21 +33,43 @@ import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.filled.ArrowBackimport androidx.compose.material3.AlertDialog-import androidx.compose.material3.FilterChip-import androidx.compose.material3.FilterChipDefaults-import androidx.compose.material3.HorizontalDivider-import androidx.compose.material3.MaterialThemeimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.FilterChip+import androidx.compose.material3.FilterChipDefaults+import androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Sliderimport androidx.compose.material3.Switchimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.material3.TopAppBarimport androidx.compose.material3.TopAppBarDefaults+import androidx.compose.material3.rememberModalBottomSheetStateimport androidx.compose.material3.windowsizeclass.WindowSizeClass+import androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.filled.Search+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.wrapContentSize+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.ui.graphics.toArgb+import androidx.compose.foundation.text.BasicText+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.LaunchedEffect as ComposeLaunchedEffect+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.TextUnitimport androidx.compose.foundation.gestures.awaitEachGestureimport androidx.compose.foundation.gestures.awaitFirstDownimport androidx.compose.foundation.gestures.waitForUpOrCancellation@@ -67,6 +92,7 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.draw.scaleimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.geometry.Sizeimport androidx.compose.ui.graphics.BlendMode@@ -444,6 +470,11 @@ private fun KeyButton()}+/**+ * Quick Settings — minimal top-anchored sheet. Shows a few items per section+ * with "More" buttons that open full pickers (with search) on demand.+ */+@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)@Composableprivate fun QuickSettingsDialog(fontSize: Int,@@ -459,119 +490,600 @@ private fun QuickSettingsDialog(onFontChange: (String) -> Unit,viewModel: TerminalViewModel = hiltViewModel(),) {- val themes = remember { viewModel.listAssetNames("colors", ".properties") }- val fonts = remember { viewModel.listAssetNames("fonts", ".ttf") }- val fontSizes = listOf(12, 14, 16, 18, 20, 22, 24, 28, 32)+ var bump by remember { mutableStateOf(0) }+ val themes = remember(bump) { viewModel.listAvailableThemes() }+ val fonts = remember(bump) { viewModel.listAvailableFonts() }- val scrollState = rememberScrollState()- val scrollbarColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.55f)- val scrollTrackColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.08f)+ // SAF for fonts.+ val fontImport = androidx.activity.compose.rememberLauncherForActivityResult(+ androidx.activity.result.contract.ActivityResultContracts.OpenDocument()+ ) { uri ->+ if (uri != null) {+ val name = viewModel.importCustomFont(uri)+ if (name != null) { onFontChange(name); bump++ }+ }+ }+ val fontMimes = remember { arrayOf("font/ttf", "application/x-font-ttf", "application/octet-stream") }- AlertDialog(+ // Sub-dialogs.+ var showThemePicker by remember { mutableStateOf(false) }+ var showFontPicker by remember { mutableStateOf(false) }+ var showThemeImport by remember { mutableStateOf(false) }+ var fontToDelete by remember { mutableStateOf<String?>(null) }+ var themeToDelete by remember { mutableStateOf<String?>(null) }++ if (showThemePicker) {+ FullPickerDialog(+ title = "Color themes",+ items = themes,+ selected = colorTheme,+ onPick = { onColorThemeChange(it); showThemePicker = false },+ onDismiss = { showThemePicker = false },+ isCustom = { viewModel.isCustomTheme(it) },+ onLongPressCustom = { themeToDelete = it },+ renderChip = { name, selected, onClick, onLongClick ->+ ThemeSwatch(name, selected, onClick, onLongClick, viewModel)+ },+ extraTrailingChip = {+ AddSwatch(label = "Import",+ subLabel = "Paste URL",+ onClick = { showThemeImport = true })+ },+ )+ }++ if (showFontPicker) {+ FullPickerDialog(+ title = "Fonts",+ items = fonts,+ selected = terminalFont,+ onPick = { onFontChange(it); showFontPicker = false },+ onDismiss = { showFontPicker = false },+ isCustom = { viewModel.isCustomFont(it) },+ onLongPressCustom = { fontToDelete = it },+ renderChip = { name, selected, onClick, onLongClick ->+ FontSwatch(+ name, viewModel.isCustomFont(name), selected, onClick, onLongClick, viewModel,+ )+ },+ extraTrailingChip = {+ AddSwatch(label = "+ Add", subLabel = ".ttf", onClick = { fontImport.launch(fontMimes) })+ },+ )+ }++ if (showThemeImport) {+ ThemeImportDialog(+ onDismiss = { showThemeImport = false },+ onImported = { name ->+ onColorThemeChange(name)+ bump+++ showThemeImport = false+ },+ viewModel = viewModel,+ )+ }++ fontToDelete?.let { name ->+ AlertDialog(+ onDismissRequest = { fontToDelete = null },+ title = { Text("Remove font?") },+ text = { Text("\"${prettyName(name)}\" will be deleted.") },+ confirmButton = {+ TextButton(onClick = {+ if (viewModel.deleteCustomFont(name)) {+ if (terminalFont == name) onFontChange("default")+ bump+++ }+ fontToDelete = null+ }) { Text("Delete") }+ },+ dismissButton = { TextButton(onClick = { fontToDelete = null }) { Text("Cancel") } },+ )+ }+ themeToDelete?.let { name ->+ AlertDialog(+ onDismissRequest = { themeToDelete = null },+ title = { Text("Remove theme?") },+ text = { Text("\"${prettyName(name)}\" will be deleted.") },+ confirmButton = {+ TextButton(onClick = {+ if (viewModel.deleteCustomTheme(name)) {+ if (colorTheme == name) onColorThemeChange("default")+ bump+++ }+ themeToDelete = null+ }) { Text("Delete") }+ },+ dismissButton = { TextButton(onClick = { themeToDelete = null }) { Text("Cancel") } },+ )+ }++ // Top sheet.+ androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss,- title = { Text("Quick Settings") },- text = {- Box(- modifier = Modifier.verticalScrollbar(- state = scrollState,- thumbColor = scrollbarColor,- trackColor = scrollTrackColor,- ),- ) {- Column(+ properties = androidx.compose.ui.window.DialogProperties(+ usePlatformDefaultWidth = false,+ dismissOnBackPress = true,+ dismissOnClickOutside = true,+ ),+ ) {+ Box(modifier = Modifier.fillMaxSize()) {+ // Cap sheet height at ~92% of the screen so it can never push toggles+ // off the visible area in landscape (where height ≈ 360dp). The inner+ // Column is scrollable so any overflow becomes a swipe instead of a clip.+ val configuration = LocalConfiguration.current+ val maxSheetHeight = (configuration.screenHeightDp * 0.92f).dp+ androidx.compose.material3.Surface(modifier = Modifier- .verticalScroll(scrollState)- .padding(start = 10.dp),- verticalArrangement = Arrangement.spacedBy(20.dp),+ .align(Alignment.TopCenter)+ .fillMaxWidth()+ .heightIn(max = maxSheetHeight),+ shape = RoundedCornerShape(bottomStart = 24.dp, bottomEnd = 24.dp),+ color = MaterialTheme.colorScheme.surface,+ tonalElevation = 4.dp,) {- // ── Font size ──────────────────────────────────────- val sizeIdx = fontSizes.indexOf(fontSize).coerceAtLeast(0)- val sizeListState = rememberLazyListState(sizeIdx)- QuickSettingsRow(label = "Font size", value = "$fontSize sp") {- LazyRow(- state = sizeListState,- horizontalArrangement = Arrangement.spacedBy(8.dp),- contentPadding = PaddingValues(horizontal = 4.dp),- modifier = Modifier.fadingEdges(sizeListState),+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 16.dp)+ .padding(top = 6.dp, bottom = 12.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ // Drag handle+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 4.dp),+ contentAlignment = Alignment.Center,) {- items(fontSizes.size) { i ->- val sz = fontSizes[i]- QuickChip(- label = "$sz",- selected = sz == fontSize,- onClick = { onFontSizeChange(sz) },- )+ Box(+ modifier = Modifier+ .size(width = 36.dp, height = 4.dp)+ .clip(RoundedCornerShape(2.dp))+ .background(MaterialTheme.colorScheme.outlineVariant),+ )+ }++ // Compact header+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(+ "Settings",+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.SemiBold,+ modifier = Modifier.weight(1f),+ )+ IconButton(onClick = onDismiss, modifier = Modifier.size(36.dp)) {+ Icon(Icons.Default.Close, contentDescription = "Close")}}- }- // ── Color theme ────────────────────────────────────- val themeIdx = themes.indexOf(colorTheme).coerceAtLeast(0)- val themeListState = rememberLazyListState(themeIdx)- QuickSettingsRow(label = "Color theme", value = prettyName(colorTheme)) {- LazyRow(- state = themeListState,- horizontalArrangement = Arrangement.spacedBy(8.dp),- contentPadding = PaddingValues(horizontal = 4.dp),- modifier = Modifier.fadingEdges(themeListState),+ // Font size — continuous slider, rounded in callback (no visible ticks)+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth(),) {- items(themes.size) { i ->- val t = themes[i]- QuickChip(- label = prettyName(t),- selected = t == colorTheme,- onClick = { onColorThemeChange(t) },- )- }+ Text("Size",+ style = MaterialTheme.typography.labelLarge,+ modifier = Modifier.width(56.dp))+ Slider(+ value = fontSize.toFloat(),+ onValueChange = { v ->+ val rounded = v.toInt()+ if (rounded != fontSize) onFontSizeChange(rounded)+ },+ valueRange = 10f..36f,+ modifier = Modifier.weight(1f),+ )+ Text(+ "$fontSize",+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.primary,+ modifier = Modifier.width(36.dp),+ textAlign = TextAlign.End,+ )}++ // Theme strip — 4 chips + More + Import-by-URL+ QuickStripRow(+ label = "Theme",+ selectedName = prettyName(colorTheme),+ items = themes,+ selected = colorTheme,+ onSelect = onColorThemeChange,+ onMore = { showThemePicker = true },+ onImport = { showThemeImport = true },+ importLabel = "URL",+ ) { name, sel, click ->+ ThemeSwatch(name, sel, click, null, viewModel)+ }++ // Font strip — 4 chips + More + Import .ttf+ QuickStripRow(+ label = "Font",+ selectedName = prettyName(terminalFont),+ items = fonts,+ selected = terminalFont,+ onSelect = onFontChange,+ onMore = { showFontPicker = true },+ onImport = { fontImport.launch(fontMimes) },+ importLabel = ".ttf",+ ) { name, sel, click ->+ FontSwatch(name, viewModel.isCustomFont(name), sel, click, null, viewModel)+ }++ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant,+ modifier = Modifier.padding(vertical = 4.dp))++ // Toggles — single line each, no subtitles+ CompactToggle("Extra keys", showExtraKeys, onToggleExtraKeys)+ CompactToggle("Haptics", hapticsEnabled, onToggleHaptics)}+ }+ }+ }+}++/**+ * Compact strip: label + selected name + 4 preview chips + [More] [+ Import].+ * The selected item is pinned first, then up to 3 alphabetical neighbors.+ */+@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun QuickStripRow(+ label: String,+ selectedName: String,+ items: List<String>,+ selected: String,+ onSelect: (String) -> Unit,+ onMore: () -> Unit,+ onImport: () -> Unit,+ importLabel: String,+ chip: @Composable (name: String, selected: Boolean, onClick: () -> Unit) -> Unit,+) {+ val visible = remember(items, selected) {+ val sel = if (selected in items) selected else items.firstOrNull()+ if (sel == null) emptyList()+ else listOf(sel) + items.filter { it != sel }.take(3)+ }+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(label, style = MaterialTheme.typography.labelLarge,+ modifier = Modifier.width(56.dp))+ Text(selectedName,+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.primary,+ modifier = Modifier.weight(1f),+ maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ FlowRow(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ visible.forEach { name ->+ chip(name, name == selected) { onSelect(name) }+ }+ AddSwatch(label = "More", subLabel = "${items.size}", onClick = onMore)+ AddSwatch(label = "+ Add", subLabel = importLabel, onClick = onImport)+ }+ }+}++/**+ * Theme preview chip — painted in the theme's actual background color so the+ * user sees the look at a glance. Foreground color is the theme's foreground.+ * If the theme can't be parsed we fall back to neutral colors.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun ThemeSwatch(+ name: String,+ selected: Boolean,+ onClick: () -> Unit,+ onLongClick: (() -> Unit)?,+ viewModel: TerminalViewModel,+) {+ val colors = remember(name) {+ viewModel.peekThemeColors(name) ?: (0xFF101010.toInt() to 0xFFE0E0E0.toInt())+ }+ SwatchBox(+ selected = selected,+ onClick = onClick,+ onLongClick = onLongClick,+ backgroundColor = Color(colors.first),+ ) {+ Text(+ prettyName(name),+ color = Color(colors.second),+ style = MaterialTheme.typography.labelMedium,+ fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ textAlign = TextAlign.Center,+ )+ }+}++/**+ * Font preview chip — shows "Aa" rendered in the actual font, plus the name.+ * Custom (user-imported) fonts get a "•" suffix and a long-press → delete.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun FontSwatch(+ name: String,+ isCustom: Boolean,+ selected: Boolean,+ onClick: () -> Unit,+ onLongClick: (() -> Unit)?,+ viewModel: TerminalViewModel,+) {+ val typeface = remember(name) { viewModel.loadFont(name) }+ val previewColor = MaterialTheme.colorScheme.onSurface.toArgb()+ SwatchBox(+ selected = selected,+ onClick = onClick,+ onLongClick = onLongClick,+ backgroundColor = MaterialTheme.colorScheme.surfaceContainerHighest,+ ) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ // "Aa" in the actual typeface — uses AndroidView for direct Typeface support.+ androidx.compose.ui.viewinterop.AndroidView(+ factory = { ctx ->+ android.widget.TextView(ctx).apply {+ text = "Aa"+ textSize = 18f+ gravity = android.view.Gravity.CENTER+ includeFontPadding = false+ }+ },+ update = { tv ->+ tv.typeface = typeface+ tv.setTextColor(previewColor)+ },+ )+ Text(+ if (isCustom) "${prettyName(name)} •" else prettyName(name),+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurface,+ fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+}++/** Generic outline chip used for "More" / "+ Add" / "Import" actions. */+@Composable+private fun AddSwatch(+ label: String,+ subLabel: String,+ onClick: () -> Unit,+) {+ Box(+ modifier = Modifier+ .size(width = 104.dp, height = 76.dp)+ .clip(RoundedCornerShape(12.dp))+ .border(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.4f), RoundedCornerShape(12.dp))+ .clickable(onClick = onClick),+ contentAlignment = Alignment.Center,+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(label,+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.primary,+ fontWeight = FontWeight.SemiBold)+ Text(subLabel,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ }+}- // ── Font family ────────────────────────────────────- val fontIdx = fonts.indexOf(terminalFont).coerceAtLeast(0)- val fontListState = rememberLazyListState(fontIdx)- QuickSettingsRow(label = "Font family", value = prettyName(terminalFont)) {- LazyRow(- state = fontListState,+@Composable+private fun CompactToggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .clip(RoundedCornerShape(8.dp))+ .clickable { onChange(!checked) }+ .padding(start = 4.dp, end = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(label, style = MaterialTheme.typography.labelLarge,+ modifier = Modifier.weight(1f))+ Switch(+ checked = checked,+ onCheckedChange = onChange,+ modifier = Modifier.scale(0.85f),+ )+ }+}++/**+ * Full-screen picker shown when the user taps "More" — search field + grid of+ * preview swatches. Long-press a custom item to delete it.+ */+@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun FullPickerDialog(+ title: String,+ items: List<String>,+ selected: String,+ onPick: (String) -> Unit,+ onDismiss: () -> Unit,+ isCustom: (String) -> Boolean,+ onLongPressCustom: (String) -> Unit,+ renderChip: @Composable (+ name: String, selected: Boolean,+ onClick: () -> Unit, onLongClick: (() -> Unit)?,+ ) -> Unit,+ extraTrailingChip: @Composable () -> Unit,+) {+ var query by remember { mutableStateOf("") }+ val filtered = remember(items, query) {+ if (query.isBlank()) items+ else items.filter { it.contains(query, ignoreCase = true) }+ }+ androidx.compose.ui.window.Dialog(+ onDismissRequest = onDismiss,+ properties = androidx.compose.ui.window.DialogProperties(+ usePlatformDefaultWidth = false,+ ),+ ) {+ androidx.compose.material3.Surface(+ modifier = Modifier+ .fillMaxWidth()+ .fillMaxHeight(0.92f)+ .padding(8.dp),+ shape = RoundedCornerShape(20.dp),+ tonalElevation = 6.dp,+ color = MaterialTheme.colorScheme.surface,+ ) {+ Column(modifier = Modifier+ .fillMaxSize()+ .padding(horizontal = 16.dp, vertical = 12.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(title, style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.SemiBold,+ modifier = Modifier.weight(1f))+ IconButton(onClick = onDismiss, modifier = Modifier.size(36.dp)) {+ Icon(Icons.Default.Close, contentDescription = "Close")+ }+ }+ OutlinedTextField(+ value = query,+ onValueChange = { query = it },+ placeholder = { Text("Search ${items.size}") },+ leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },+ singleLine = true,+ modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+ )+ Spacer(modifier = Modifier.height(8.dp))+ Box(modifier = Modifier+ .fillMaxWidth()+ .weight(1f)+ .verticalScroll(rememberScrollState())) {+ FlowRow(+ modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.spacedBy(8.dp),- contentPadding = PaddingValues(horizontal = 4.dp),- modifier = Modifier.fadingEdges(fontListState),+ verticalArrangement = Arrangement.spacedBy(8.dp),) {- items(fonts.size) { i ->- val f = fonts[i]- QuickChip(- label = prettyName(f),- selected = f == terminalFont,- onClick = { onFontChange(f) },+ filtered.forEach { name ->+ val custom = isCustom(name)+ renderChip(+ name,+ name == selected,+ { onPick(name) },+ if (custom) ({ onLongPressCustom(name) }) else null,)}+ extraTrailingChip()}}+ }+ }+ }+}- HorizontalDivider()+/**+ * Theme-import dialog. Accepts a `terminalcolors.com/themes/<name>/<variant>/` URL+ * (or a direct .toml URL); calls the suspend importer in a coroutine; shows+ * loading + error states.+ */+@Composable+private fun ThemeImportDialog(+ onDismiss: () -> Unit,+ onImported: (String) -> Unit,+ viewModel: TerminalViewModel,+) {+ var url by remember { mutableStateOf("") }+ var busy by remember { mutableStateOf(false) }+ var error by remember { mutableStateOf<String?>(null) }+ val scope = rememberCoroutineScope()- // ── Switches ───────────────────────────────────────- Row(+ AlertDialog(+ onDismissRequest = { if (!busy) onDismiss() },+ title = { Text("Import theme") },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(+ "Paste a terminalcolors.com theme URL.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ OutlinedTextField(+ value = url,+ onValueChange = { url = it; error = null },+ placeholder = { Text("https://terminalcolors.com/themes/dracula/default/") },+ singleLine = true,modifier = Modifier.fillMaxWidth(),- verticalAlignment = Alignment.CenterVertically,- ) {- Text("Show extra keys", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))- Switch(checked = showExtraKeys, onCheckedChange = onToggleExtraKeys)+ )+ if (error != null) {+ Text(error!!, color = MaterialTheme.colorScheme.error,+ style = MaterialTheme.typography.bodySmall)}- Row(- modifier = Modifier.fillMaxWidth(),- verticalAlignment = Alignment.CenterVertically,- ) {- Text("Haptic feedback", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))- Switch(checked = hapticsEnabled, onCheckedChange = onToggleHaptics)+ if (busy) {+ CircularProgressIndicator(modifier = Modifier.size(20.dp))}}- }},confirmButton = {- TextButton(onClick = onDismiss) {- Text("Done")- }- }+ TextButton(+ enabled = !busy && url.isNotBlank(),+ onClick = {+ busy = true+ error = null+ scope.launch {+ val name = viewModel.importThemeFromUrl(url)+ busy = false+ if (name != null) onImported(name)+ else error = "Couldn't import — check the URL."+ }+ },+ ) { Text(if (busy) "Importing…" else "Import") }+ },+ dismissButton = {+ TextButton(onClick = onDismiss, enabled = !busy) { Text("Cancel") }+ },+ )+}++@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun SwatchBox(+ selected: Boolean,+ onClick: () -> Unit,+ backgroundColor: Color,+ onLongClick: (() -> Unit)? = null,+ content: @Composable BoxScope.() -> Unit,+) {+ val ring = if (selected) MaterialTheme.colorScheme.primary else Color.Transparent+ val clickModifier = if (onLongClick != null) {+ Modifier.combinedClickable(onClick = onClick, onLongClick = onLongClick)+ } else {+ Modifier.clickable(onClick = onClick)+ }+ Box(+ modifier = Modifier+ .size(width = 104.dp, height = 76.dp)+ .clip(RoundedCornerShape(12.dp))+ .background(backgroundColor)+ .then(clickModifier)+ .border(+ width = if (selected) 2.dp else 0.dp,+ color = ring,+ shape = RoundedCornerShape(12.dp),+ )+ .padding(6.dp),+ contentAlignment = Alignment.Center,+ content = content,)}@@ -603,12 +1115,38 @@ private fun QuickSettingsRow(}}+@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)@Composableprivate fun QuickChip(label: String,selected: Boolean,onClick: () -> Unit,+ onLongClick: (() -> Unit)? = null,) {+ // FilterChip doesn't expose onLongClick, so when a long-press handler is+ // supplied we wrap it in a combinedClickable Box that mimics the chip's+ // rounded shape + selected colors.+ if (onLongClick != null) {+ val bg = if (selected) MaterialTheme.colorScheme.primaryContainer+ else MaterialTheme.colorScheme.surfaceContainerHighest+ val fg = if (selected) MaterialTheme.colorScheme.onPrimaryContainer+ else MaterialTheme.colorScheme.onSurface+ Box(+ modifier = Modifier+ .clip(RoundedCornerShape(14.dp))+ .background(bg)+ .combinedClickable(onClick = onClick, onLongClick = onLongClick)+ .padding(horizontal = 16.dp, vertical = 8.dp),+ ) {+ Text(+ label,+ style = MaterialTheme.typography.labelLarge,+ color = fg,+ fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,+ )+ }+ return+ }FilterChip(selected = selected,onClick = onClick,diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.ktindex 9d5ba52..44ba5e1 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt@@ -1,6 +1,6 @@/** Podroid - Rootless Podman for Android- * Copyright (C) 2024 Podroid contributors+ * Copyright (C) 2024-2026 Podroid contributors** Terminal ViewModel — wires TerminalView to the podroid-bridge binary.*@@ -50,8 +50,10 @@ import com.termux.view.TerminalViewimport com.termux.view.TerminalViewClientimport dagger.hilt.android.lifecycle.HiltViewModelimport dagger.hilt.android.qualifiers.ApplicationContext+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.SharingStartedimport kotlinx.coroutines.launch+import kotlinx.coroutines.withContextimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.stateInimport java.io.File@@ -128,19 +130,44 @@ class TerminalViewModel @Inject constructor(viewRef = view?.let { java.lang.ref.WeakReference(it) }}+ /**+ * Peek a theme's bg+fg ARGB ints without mutating the active palette.+ * Used by the Settings sheet to render theme preview swatches.+ * Returns null for `default` (caller falls back to neutral colors).+ */+ fun peekThemeColors(theme: String): Pair<Int, Int>? {+ if (theme == "default") return null+ val props = readThemeProperties(theme) ?: return null+ val bg = (props["background"] as? String)?.let { parseColor(it) } ?: return null+ val fg = (props["foreground"] as? String)?.let { parseColor(it) } ?: 0xFFE0E0E0.toInt()+ return bg to fg+ }+/*** Resolve a theme name to the (background, Properties) pair, also pushing* the palette into TerminalColors.COLOR_SCHEME so the renderer picks it up.* Returns null background for the built-in default.*/- fun loadColorTheme(theme: String): Int? = if (theme == "default") {- null- } else try {- val props = java.util.Properties()- context.assets.open("colors/$theme.properties").use { props.load(it) }+ fun loadColorTheme(theme: String): Int? {+ if (theme == "default") return null+ val props = readThemeProperties(theme) ?: return nullTerminalColors.COLOR_SCHEME.updateWith(props)- (props["background"] as? String)?.let { parseColor(it) }- } catch (_: Exception) { null }+ return (props["background"] as? String)?.let { parseColor(it) }+ }++ /** User dir wins over bundled when names collide. */+ private fun readThemeProperties(theme: String): java.util.Properties? {+ val props = java.util.Properties()+ val userFile = java.io.File(userThemesDir, "$theme.properties")+ return try {+ if (userFile.isFile) {+ userFile.inputStream().use { props.load(it) }+ } else {+ context.assets.open("colors/$theme.properties").use { props.load(it) }+ }+ props+ } catch (_: Exception) { null }+ }/** Lists asset files in `dir` whose name ends with `suffix`, with the suffix stripped. */fun listAssetNames(dir: String, suffix: String): List<String> {@@ -150,21 +177,250 @@ class TerminalViewModel @Inject constructor(return listOf("default") + items.filter { it.endsWith(suffix) }.map { it.removeSuffix(suffix) }.sorted()}+ /**+ * Where user-imported fonts live. App-private external dir means no permission+ * prompts and a clean uninstall, but it's not visible to third-party file+ * managers on Android 11+ — so we drive imports via SAF (`importCustomFont`)+ * rather than asking users to "drop a .ttf into a folder".+ */+ private val userFontsDir: java.io.File by lazy {+ java.io.File(context.getExternalFilesDir(null), "fonts").apply { mkdirs() }+ }++ /** Where user-imported themes live. Same rationale as userFontsDir. */+ private val userThemesDir: java.io.File by lazy {+ java.io.File(context.getExternalFilesDir(null), "colors").apply { mkdirs() }+ }++ /** Bundled .properties themes ∪ user-imported. */+ fun listAvailableThemes(): List<String> {+ val bundled = runCatching { context.assets.list("colors")?.toList() }+ .getOrNull().orEmpty()+ val user = (userThemesDir.listFiles() ?: emptyArray())+ .filter { it.isFile }.map { it.name }+ val names = (bundled + user)+ .filter { it.endsWith(".properties", ignoreCase = true) }+ .map { it.substringBeforeLast('.') }+ .toSortedSet(String.CASE_INSENSITIVE_ORDER)+ return listOf("default") + names.toList()+ }++ fun isCustomTheme(name: String): Boolean =+ java.io.File(userThemesDir, "$name.properties").isFile++ fun deleteCustomTheme(name: String): Boolean {+ val f = java.io.File(userThemesDir, "$name.properties")+ return f.exists() && f.delete()+ }++ /**+ * Import a theme from a terminalcolors.com URL.+ * Accepts pages like `https://terminalcolors.com/themes/dracula/default/` —+ * we transform the slug into the predictable Alacritty TOML download URL,+ * fetch it, and convert to our `.properties` format.+ *+ * Returns the saved theme name, or null on any failure.+ */+ suspend fun importThemeFromUrl(input: String): String? = withContext(Dispatchers.IO) {+ val url = input.trim()+ // Extract slug from the page URL or accept the .toml URL directly.+ val tomlUrl: String = when {+ url.endsWith(".toml") -> url+ else -> {+ val match = Regex("""terminalcolors\.com/themes/([^/]+)/([^/?#]+)""").find(url)+ ?: return@withContext null+ val (name, variant) = match.groupValues[1] to match.groupValues[2]+ "https://terminalcolors.com/downloads/alacritty/$name-$variant.toml"+ }+ }+ val toml = runCatching {+ val conn = (java.net.URL(tomlUrl).openConnection() as java.net.HttpURLConnection).apply {+ connectTimeout = 8000+ readTimeout = 8000+ setRequestProperty(+ "User-Agent",+ "Podroid/${com.excp.podroid.BuildConfig.VERSION_NAME}"+ )+ }+ try {+ if (conn.responseCode != 200) return@runCatching null+ conn.inputStream.bufferedReader().readText()+ } finally { conn.disconnect() }+ }.getOrNull() ?: return@withContext null++ val themeName = sanitizeFontName(+ tomlUrl.substringAfterLast('/').substringBeforeLast('.')+ ) ?: return@withContext null++ val properties = parseAlacrittyToml(toml) ?: return@withContext null++ val dest = java.io.File(userThemesDir, "$themeName.properties")+ dest.bufferedWriter().use { w ->+ for ((k, v) in properties) w.write("$k=$v\n")+ }+ themeName+ }++ /**+ * Parse an Alacritty TOML color export into our `.properties` keys.+ * Returns null if required keys (background/foreground/16 ANSI colors) aren't found.+ */+ private fun parseAlacrittyToml(toml: String): Map<String, String>? {+ // [colors.<section>] key = "#xxxxxx"+ val sectionRe = Regex("""\[colors\.(\w+)]""")+ val kvRe = Regex("""(\w+)\s*=\s*"(#[0-9a-fA-F]{3,8})"""")+ var section = ""+ val byKey = LinkedHashMap<String, String>()+ for (raw in toml.lines()) {+ val line = raw.trim()+ sectionRe.find(line)?.let { section = it.groupValues[1]; return@let }+ val kv = kvRe.find(line) ?: continue+ val key = kv.groupValues[1]+ val value = kv.groupValues[2]+ val mapped = when (section) {+ "primary" -> when (key) {+ "foreground" -> "foreground"+ "background" -> "background"+ else -> null+ }+ "cursor" -> when (key) {+ "cursor" -> "cursor"+ "text" -> null // foreground-of-cursor — emulator doesn't store separately+ else -> null+ }+ "normal" -> when (key) {+ "black" -> "color0"; "red" -> "color1"+ "green" -> "color2"; "yellow" -> "color3"+ "blue" -> "color4"; "magenta" -> "color5"+ "cyan" -> "color6"; "white" -> "color7"+ else -> null+ }+ "bright" -> when (key) {+ "black" -> "color8"; "red" -> "color9"+ "green" -> "color10"; "yellow" -> "color11"+ "blue" -> "color12"; "magenta" -> "color13"+ "cyan" -> "color14"; "white" -> "color15"+ else -> null+ }+ else -> null+ } ?: continue+ byKey[mapped] = value+ }+ // Sanity: must have FG + BG and at least 8 ANSI colors.+ if (!byKey.containsKey("foreground") || !byKey.containsKey("background")) return null+ if ((0..7).any { !byKey.containsKey("color$it") }) return null+ return byKey+ }++ /** Bundled assets ∪ user-imported TTFs (case-insensitive dedupe — user wins). */+ fun listAvailableFonts(): List<String> {+ val bundled = runCatching { context.assets.list("fonts")?.toList() }+ .getOrNull().orEmpty()+ val user = (userFontsDir.listFiles() ?: emptyArray())+ .filter { it.isFile }.map { it.name }+ val names = (bundled + user)+ .filter { it.endsWith(".ttf", ignoreCase = true) }+ .map { it.substringBeforeLast('.') }+ .toSortedSet(String.CASE_INSENSITIVE_ORDER)+ return listOf("default") + names.toList()+ }++ /** True if `name` was imported by the user (overrides any bundled font of the same name). */+ fun isCustomFont(name: String): Boolean =+ java.io.File(userFontsDir, "$name.ttf").isFile+/** Resolve a font name to a Typeface. Returns Typeface.MONOSPACE for default or on error. */- fun loadFont(font: String): Typeface = if (font == "default") {- Typeface.MONOSPACE- } else try {- // assets.openFd is a file descriptor — Typeface.createFromFile needs a real path,- // so we copy on demand into a per-launch cache file. Same disk hit as before but- // no DataStore-shadowed state on filesDir.- val cacheFile = java.io.File(context.cacheDir, "font_$font.ttf")- if (!cacheFile.exists()) {- context.assets.open("fonts/$font.ttf").use { inp ->- cacheFile.outputStream().use { out -> inp.copyTo(out) }+ fun loadFont(font: String): Typeface {+ if (font == "default") return Typeface.MONOSPACE+ // User imports win over bundled with the same name.+ val userFile = java.io.File(userFontsDir, "$font.ttf")+ if (userFile.isFile) {+ return runCatching { Typeface.createFromFile(userFile) }+ .getOrDefault(Typeface.MONOSPACE)+ }+ return try {+ // assets.openFd is a file descriptor — Typeface.createFromFile needs a real path,+ // so we copy on demand into a per-launch cache file.+ val cacheFile = java.io.File(context.cacheDir, "font_$font.ttf")+ if (!cacheFile.exists()) {+ context.assets.open("fonts/$font.ttf").use { inp ->+ cacheFile.outputStream().use { out -> inp.copyTo(out) }+ }}+ Typeface.createFromFile(cacheFile)+ } catch (_: Exception) { Typeface.MONOSPACE }+ }++ /**+ * Import a `.ttf` from a SAF `Uri` into the user fonts dir.+ * Returns the sanitized font name (no extension) on success, null on failure.+ *+ * Safety:+ * - Filename sanitized to ASCII alnum + dash/underscore (max 48 chars).+ * - Capped at 16 MiB; legitimate TTFs are well under 1 MB.+ * - Validates by constructing a Typeface; rejects unloadable files.+ * - Writes to `.tmp` then renames so a partial copy never wins picker enumeration.+ */+ fun importCustomFont(uri: android.net.Uri): String? {+ val rawName = displayNameOf(uri) ?: return null+ val name = sanitizeFontName(rawName) ?: return null+ val tmp = java.io.File(userFontsDir, "$name.ttf.tmp")+ val dest = java.io.File(userFontsDir, "$name.ttf")+ return try {+ context.contentResolver.openInputStream(uri).use { input ->+ if (input == null) return null+ tmp.outputStream().use { out ->+ val maxBytes = 16L * 1024 * 1024+ val buf = ByteArray(8192)+ var written = 0L+ while (true) {+ val n = input.read(buf)+ if (n <= 0) break+ written += n+ if (written > maxBytes) return cleanup(tmp, null)+ out.write(buf, 0, n)+ }+ }+ }+ // Validate by trying to load it.+ val tf = runCatching { Typeface.createFromFile(tmp) }.getOrNull()+ if (tf == null || tf === Typeface.DEFAULT) return cleanup(tmp, null)+ // Atomic-ish swap.+ if (dest.exists()) dest.delete()+ if (!tmp.renameTo(dest)) return cleanup(tmp, null)+ // Invalidate the asset-cache copy in case a bundled font of the same+ // name was previously loaded — next loadFont() should see the new file.+ java.io.File(context.cacheDir, "font_$name.ttf").delete()+ name+ } catch (_: Exception) {+ cleanup(tmp, null)}- Typeface.createFromFile(cacheFile)- } catch (_: Exception) { Typeface.MONOSPACE }+ }++ /** Remove a previously-imported custom font. Returns true if it existed and was removed. */+ fun deleteCustomFont(name: String): Boolean {+ val f = java.io.File(userFontsDir, "$name.ttf")+ val ok = f.exists() && f.delete()+ if (ok) java.io.File(context.cacheDir, "font_$name.ttf").delete()+ return ok+ }++ private fun <T> cleanup(tmp: java.io.File, result: T?): T? {+ runCatching { if (tmp.exists()) tmp.delete() }+ return result+ }++ private fun displayNameOf(uri: android.net.Uri): String? = runCatching {+ context.contentResolver.query(+ uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null+ )?.use { if (it.moveToFirst()) it.getString(0) else null }+ }.getOrNull()++ private fun sanitizeFontName(filename: String): String? {+ val base = filename.substringBeforeLast('.').trim()+ val safe = base.replace(Regex("[^A-Za-z0-9_-]"), "-").trim('-').take(48)+ return safe.takeIf { it.isNotEmpty() }+ }private fun parseColor(hex: String): Int {val clean = hex.removePrefix("#")@@ -238,7 +494,10 @@ class TerminalViewModel @Inject constructor(}override fun onColorsChanged(session: TerminalSession) {}override fun onTerminalCursorStateChange(state: Boolean) {}+ override fun setTerminalShellPid(session: TerminalSession, pid: Int) {}override fun getTerminalCursorStyle(): Int = 0+ override fun getTerminalVersionString(): String =+ "Podroid ${com.excp.podroid.BuildConfig.VERSION_NAME}"override fun logError(tag: String?, message: String?) = LogProxy.error(tag, TAG, message)override fun logWarn(tag: String?, message: String?) = LogProxy.warn(tag, TAG, message)override fun logInfo(tag: String?, message: String?) = LogProxy.info(tag, TAG, message)@@ -253,6 +512,18 @@ class TerminalViewModel @Inject constructor(override fun onScale(scale: Float): Float = scaleoverride fun onSingleTapUp(e: MotionEvent?) {val view = viewRef?.get() ?: return+ // OSC 8: tap on a hyperlinked region launches the URL instead of the keyboard.+ if (e != null) {+ val url = view.getHyperlinkAt(e.x, e.y)+ if (!url.isNullOrEmpty()) {+ runCatching {+ val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))+ .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)+ context.startActivity(intent)+ }+ return+ }+ }val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE)as android.view.inputmethod.InputMethodManagerimm.showSoftInput(view, 0)@@ -398,7 +669,7 @@ class TerminalViewModel @Inject constructor(val cols = (w / charWidth).toInt().coerceAtLeast(20)val rows = (h / lineHeight).toInt().coerceAtLeast(8)Log.d(TAG, "forceUpdateSize: view=${w}x${h}px cell=${charWidth}x${lineHeight}px → ${cols}x${rows} chars")- sess.updateSize(cols, rows)+ sess.updateSize(cols, rows, charWidth.toInt(), lineHeight.toInt())}/**