Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

refactor: terminal layer cleanup and memory leak fixes

ExTv736423d633a1
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/DefaultKeyLayouts.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/DefaultKeyLayouts.kt
deleted file mode 100644
index ac8f275..0000000
--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/DefaultKeyLayouts.kt
+++ /dev/null
@@ -1,77 +0,0 @@
-package com.excp.podroid.ui.screens.terminal
-
-/**
- * Default key layouts for the terminal extra keys bar.
- */
-object DefaultKeyLayouts {
-
- /**
- * Minimal layout: ESC, TAB, CTRL, ALT, arrow cluster
- */
- val minimal = listOf(
- ExtraKey("ESC", KeyAction.SendEscape("\u001B")),
- ExtraKey("TAB", KeyAction.SendEscape("\u0009")),
- ExtraKey("CTRL", KeyAction.ModifierOnly(Modifier.CTRL)),
- ExtraKey("ALT", KeyAction.ModifierOnly(Modifier.ALT)),
- ExtraKey("↑", KeyAction.SendEscape("\u001B[A")),
- ExtraKey("↓", KeyAction.SendEscape("\u001B[B")),
- ExtraKey("←", KeyAction.SendEscape("\u001B[D")),
- ExtraKey("→", KeyAction.SendEscape("\u001B[C"))
- )
-
- /**
- * Full layout: all keys including function keys and page navigation
- */
- val full = listOf(
- // Row 1 - Basic controls
- ExtraKey("ESC", KeyAction.SendEscape("\u001B")),
- ExtraKey("TAB", KeyAction.SendEscape("\u0009")),
- ExtraKey("CTRL", KeyAction.ModifierOnly(Modifier.CTRL)),
- ExtraKey("ALT", KeyAction.ModifierOnly(Modifier.ALT)),
- ExtraKey("↑", KeyAction.SendEscape("\u001B[A")),
- ExtraKey("↓", KeyAction.SendEscape("\u001B[B")),
- ExtraKey("←", KeyAction.SendEscape("\u001B[D")),
- ExtraKey("→", KeyAction.SendEscape("\u001B[C")),
-
- // Row 2 - Navigation
- ExtraKey("HOME", KeyAction.SendEscape("\u001B[H")),
- ExtraKey("END", KeyAction.SendEscape("\u001B[F")),
- ExtraKey("PgUp", KeyAction.SendEscape("\u001B[5~")),
- ExtraKey("PgDn", KeyAction.SendEscape("\u001B[6~")),
-
- // Row 3 - Function keys F1-F4
- ExtraKey("F1", KeyAction.SendEscape("\u001BOP")),
- ExtraKey("F2", KeyAction.SendEscape("\u001BOQ")),
- ExtraKey("F3", KeyAction.SendEscape("\u001BOR")),
- ExtraKey("F4", KeyAction.SendEscape("\u001BOS")),
-
- // Row 4 - F5-F12
- ExtraKey("F5", KeyAction.SendEscape("\u001B[15~")),
- ExtraKey("F6", KeyAction.SendEscape("\u001B[17~")),
- ExtraKey("F7", KeyAction.SendEscape("\u001B[18~")),
- ExtraKey("F8", KeyAction.SendEscape("\u001B[19~")),
- ExtraKey("F9", KeyAction.SendEscape("\u001B[20~")),
- ExtraKey("F10", KeyAction.SendEscape("\u001B[21~")),
- ExtraKey("F11", KeyAction.SendEscape("\u001B[23~")),
- ExtraKey("F12", KeyAction.SendEscape("\u001B[24~")),
-
- // Row 5 - Symbols
- ExtraKey("-", KeyAction.SendEscape("-")),
- ExtraKey("/", KeyAction.SendEscape("/")),
- ExtraKey("|", KeyAction.SendEscape("|")),
-
- // Row 6 - Special
- ExtraKey("^C", KeyAction.CtrlC),
- ExtraKey("^D", KeyAction.CtrlD),
- ExtraKey("^Z", KeyAction.CtrlZ)
- )
-
- /**
- * Get layout by name.
- */
- fun getLayout(name: String): List<ExtraKey> = when (name) {
- "minimal" -> minimal
- "full" -> full
- else -> minimal
- }
-}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/ExtraKey.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/ExtraKey.kt
deleted file mode 100644
index e5714a8..0000000
--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/ExtraKey.kt
+++ /dev/null
@@ -1,138 +0,0 @@
-package com.excp.podroid.ui.screens.terminal
-
-import android.util.Base64
-
-/**
- * Data model for customizable extra keys in the terminal toolbar.
- */
-data class ExtraKey(
- val label: String,
- val action: KeyAction,
- val modifier: Modifier? = null
-)
-
-/**
- * Actions that an extra key can perform.
- */
-sealed class KeyAction {
- /** Send an escape sequence */
- data class SendEscape(val sequence: String) : KeyAction()
-
- /** Send Ctrl+C */
- object CtrlC : KeyAction()
-
- /** Send Ctrl+D */
- object CtrlD : KeyAction()
-
- /** Send Ctrl+Z */
- object CtrlZ : KeyAction()
-
- /** Send raw bytes */
- data class Custom(val bytes: ByteArray) : KeyAction()
-
- /** Toggle modifier only (Ctrl, Alt, Shift) */
- data class ModifierOnly(val modifier: Modifier) : KeyAction()
-
- override fun equals(other: Any?): Boolean {
- if (this === other) return true
- if (javaClass != other?.javaClass) return false
- other as KeyAction
- return when (this) {
- is SendEscape -> other is SendEscape && sequence == other.sequence
- is CtrlC -> other is CtrlC
- is CtrlD -> other is CtrlD
- is CtrlZ -> other is CtrlZ
- is Custom -> other is Custom && bytes.contentEquals(other.bytes)
- is ModifierOnly -> other is ModifierOnly && modifier == other.modifier
- }
- }
-
- override fun hashCode(): Int {
- return when (this) {
- is SendEscape -> sequence.hashCode()
- is CtrlC -> CtrlC.hashCode()
- is CtrlD -> CtrlD.hashCode()
- is CtrlZ -> CtrlZ.hashCode()
- is Custom -> bytes.contentHashCode()
- is ModifierOnly -> modifier.hashCode()
- }
- }
-}
-
-/**
- * Modifier keys that can be toggled.
- */
-enum class Modifier { CTRL, ALT, SHIFT }
-
-/**
- * Serialization helpers for ExtraKey to/from JSON.
- */
-object ExtraKeySerde {
-
- /**
- * Parse a JSON string into a list of ExtraKeys.
- */
- fun fromJson(json: String): List<ExtraKey> {
- if (json.isBlank()) return emptyList()
- return try {
- val arr = org.json.JSONArray(json)
- val list = mutableListOf<ExtraKey>()
- for (i in 0 until arr.length()) {
- val obj = arr.getJSONObject(i)
- val label = obj.getString("label")
- val mod = if (obj.has("modifier")) {
- Modifier.valueOf(obj.getString("modifier"))
- } else null
-
- val actionObj = obj.getJSONObject("action")
- val action: KeyAction = when (actionObj.getString("type")) {
- "SendEscape" -> KeyAction.SendEscape(actionObj.getString("sequence"))
- "CtrlC" -> KeyAction.CtrlC
- "CtrlD" -> KeyAction.CtrlD
- "CtrlZ" -> KeyAction.CtrlZ
- "Custom" -> KeyAction.Custom(Base64.decode(actionObj.getString("bytes"), Base64.NO_WRAP))
- "ModifierOnly" -> KeyAction.ModifierOnly(Modifier.valueOf(actionObj.getString("modifier")))
- else -> KeyAction.CtrlC
- }
- list.add(ExtraKey(label, action, mod))
- }
- list
- } catch (e: Exception) {
- emptyList()
- }
- }
-
- /**
- * Serialize a list of ExtraKeys to JSON string.
- */
- fun toJson(keys: List<ExtraKey>): String {
- val arr = org.json.JSONArray()
- for (k in keys) {
- val obj = org.json.JSONObject()
- obj.put("label", k.label)
- k.modifier?.let { obj.put("modifier", it.name) }
-
- val actionObj = org.json.JSONObject()
- when (val a = k.action) {
- is KeyAction.SendEscape -> {
- actionObj.put("type", "SendEscape")
- actionObj.put("sequence", a.sequence)
- }
- is KeyAction.CtrlC -> actionObj.put("type", "CtrlC")
- is KeyAction.CtrlD -> actionObj.put("type", "CtrlD")
- is KeyAction.CtrlZ -> actionObj.put("type", "CtrlZ")
- is KeyAction.Custom -> {
- actionObj.put("type", "Custom")
- actionObj.put("bytes", Base64.encodeToString(a.bytes, Base64.NO_WRAP))
- }
- is KeyAction.ModifierOnly -> {
- actionObj.put("type", "ModifierOnly")
- actionObj.put("modifier", a.modifier.name)
- }
- }
- obj.put("action", actionObj)
- arr.put(obj)
- }
- return arr.toString()
- }
-}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/QuickSettingsDrawer.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/QuickSettingsDrawer.kt
deleted file mode 100644
index ed186a6..0000000
--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/QuickSettingsDrawer.kt
+++ /dev/null
@@ -1,132 +0,0 @@
-package com.excp.podroid.ui.screens.terminal
-
-import androidx.compose.foundation.background
-import androidx.compose.foundation.clickable
-import androidx.compose.foundation.horizontalScroll
-import androidx.compose.foundation.layout.*
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material3.*
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.unit.dp
-import androidx.compose.ui.unit.sp
-import androidx.compose.material3.Slider
-import androidx.compose.material3.Switch
-import androidx.compose.material3.SwitchDefaults
-import androidx.compose.material3.Text
-import androidx.compose.ui.text.style.TextAlign
-import androidx.compose.foundation.lazy.LazyRow
-import androidx.compose.foundation.lazy.items
-
-/**
- * Quick Settings Drawer content for the Terminal screen.
- * This composable is used as the sheet content of a bottom sheet.
- */
-@Composable
-fun QuickSettingsDrawer(
- isVisible: Boolean,
- onDismiss: () -> Unit,
- // Settings from SettingsRepository via ViewModel
- fontSize: Int,
- colorTheme: String,
- onFontSizeChange: (Int) -> Unit,
- onColorThemeChange: (String) -> Unit,
- onToggleExtraKeys: (Boolean) -> Unit,
- onToggleHaptics: (Boolean) -> Unit,
- onToggleKeepScreen: (Boolean) -> Unit,
- // Additional ephemeral UI state (from ViewModel)
- showExtraKeys: Boolean,
- hapticsEnabled: Boolean,
- keepScreenOnEnabled: Boolean,
-){
- // Only render when sheet is visible; the ModalBottomSheetLayout handles visibility, but we keep a guard for safety
- if (!isVisible) return
-
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(16.dp)
- ) {
- Text(text = "Quick Settings", fontSize = 18.sp, fontWeight = FontWeight.Bold)
- Spacer(modifier = Modifier.height(12.dp))
-
- // Font size slider
- Text(text = "Font size", fontSize = 14.sp, color = Color(0xFFCCCCCC))
- Spacer(modifier = Modifier.height(6.dp))
- Slider(
- value = fontSize.toFloat(),
- onValueChange = { onFontSizeChange(it.toInt()) },
- valueRange = 16f..32f,
- steps = 16
- )
- Spacer(modifier = Modifier.height(12.dp))
-
- // Theme chips
- Text(text = "Theme", fontSize = 14.sp, color = Color(0xFFCCCCCC))
- Spacer(modifier = Modifier.height(6.dp))
- val themes = listOf("default","Dracula","Nord","Gruvbox","Solarized","Tokyo Night")
- LazyRow(
- modifier = Modifier.fillMaxWidth(),
- contentPadding = PaddingValues(horizontal = 4.dp)
- ) {
- items(themes) { t ->
- val selected = t == colorTheme
- Box(
- modifier = Modifier
- .padding(end = 8.dp)
- .background(if (selected) Color(0xFF4FC3F7) else Color(0xFF333333), RoundedCornerShape(999.dp))
- .clickable { onColorThemeChange(t) }
- .padding(horizontal = 12.dp, vertical = 8.dp)
- ) {
- Text(text = t, fontSize = 12.sp, color = Color.White)
- }
- }
- }
- Spacer(modifier = Modifier.height(12.dp))
-
- // Extra keys bar toggle
- Row(
- verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier.fillMaxWidth()
- ) {
- Text("Show extra keys bar", fontSize = 14.sp, color = Color(0xFFCCCCCC), modifier = Modifier.weight(1f))
- Switch(
- checked = showExtraKeys,
- onCheckedChange = { checked -> onToggleExtraKeys(checked) },
- colors = SwitchDefaults.colors(checkedThumbColor = Color.White)
- )
- }
- Spacer(modifier = Modifier.height(8.dp))
-
- // Haptic feedback
- Row(
- verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier.fillMaxWidth()
- ) {
- Text("Haptic feedback", fontSize = 14.sp, color = Color(0xFFCCCCCC), modifier = Modifier.weight(1f))
- Switch(
- checked = hapticsEnabled,
- onCheckedChange = { enabled -> onToggleHaptics(enabled) },
- )
- }
- Spacer(modifier = Modifier.height(8.dp))
-
- // Keep screen on
- Row(
- verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier.fillMaxWidth()
- ) {
- Text("Keep screen on", fontSize = 14.sp, color = Color(0xFFCCCCCC), modifier = Modifier.weight(1f))
- Switch(
- checked = keepScreenOnEnabled,
- onCheckedChange = { enabled -> onToggleKeepScreen(enabled) }
- )
- }
- Spacer(modifier = Modifier.height(4.dp))
- }
-}
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.kt
index 60c436a..cb948fb 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
@@ -48,7 +48,9 @@ import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
+import kotlinx.coroutines.launch
import androidx.compose.ui.input.pointer.pointerInput
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
@@ -81,6 +83,8 @@ fun TerminalScreen(
val vmState by viewModel.vmState.collectAsState()
val fontSize by viewModel.terminalFontSize.collectAsState()
val showQuickSettings by viewModel.showQuickSettings.collectAsState()
+ val showExtraKeys by viewModel.showExtraKeysFlow.collectAsState()
+ val hapticsEnabled by viewModel.hapticsEnabledFlow.collectAsState()
DisposableEffect(Unit) {
val activity = context as? Activity
@@ -112,14 +116,20 @@ fun TerminalScreen(
val colorTheme by viewModel.terminalColorTheme.collectAsState()
val terminalFont by viewModel.terminalFont.collectAsState()
+ // Resolve the typeface and background palette from settings. Both run on
+ // recomposition because they're cheap (asset reads, font cache lookup) and
+ // the result drives the View setters in LaunchedEffect below.
+ val typeface = remember(terminalFont) { viewModel.loadFont(terminalFont) }
+ val themeBg = remember(colorTheme) { viewModel.loadColorTheme(colorTheme) }
+
if (showQuickSettings) {
QuickSettingsDialog(
fontSize = fontSize,
onFontSizeChange = { viewModel.setTerminalFontSize(it) },
onDismiss = { viewModel.closeQuickSettings() },
- showExtraKeys = viewModel.showExtraKeys,
+ showExtraKeys = showExtraKeys,
onToggleExtraKeys = { viewModel.updateShowExtraKeys(it) },
- hapticsEnabled = viewModel.hapticsEnabled,
+ hapticsEnabled = hapticsEnabled,
onToggleHaptics = { viewModel.updateHapticsEnabled(it) },
colorTheme = colorTheme,
onColorThemeChange = { viewModel.setTerminalColorTheme(it) },
@@ -135,7 +145,7 @@ fun TerminalScreen(
.windowInsetsPadding(WindowInsets.ime)
) {
TopAppBar(
- title = { Text("Terminal", color = Color.White) },
+ title = { Text("Terminal") },
navigationIcon = {
IconButton(onClick = {
val imm = context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)
@@ -145,29 +155,30 @@ fun TerminalScreen(
}
onNavigateBack()
}) {
- Icon(
- Icons.AutoMirrored.Filled.ArrowBack,
- contentDescription = "Back",
- tint = Color.White,
- )
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = { viewModel.openQuickSettings() }) {
- Text("⚙", color = Color.White, fontSize = 18.sp)
+ Text("⚙", fontSize = 18.sp)
}
},
- colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFF1A1A1A)),
)
when (vmState) {
is VmState.Idle, is VmState.Stopped -> {
Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
- Text("VM Not Running", color = Color.Red, fontSize = 18.sp, fontWeight = FontWeight.Bold)
+ Text(
+ "VM Not Running",
+ color = MaterialTheme.colorScheme.error,
+ fontSize = 18.sp,
+ fontWeight = FontWeight.Bold,
+ )
Text(
"Start the VM from Home screen first",
- color = Color.Gray, fontSize = 14.sp,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ fontSize = 14.sp,
modifier = Modifier.padding(top = 8.dp),
)
}
@@ -177,52 +188,63 @@ fun TerminalScreen(
is VmState.Error -> {
Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
- Text("Error", color = Color.Red, fontSize = 18.sp, fontWeight = FontWeight.Bold)
+ Text(
+ "Error",
+ color = MaterialTheme.colorScheme.error,
+ fontSize = 18.sp,
+ fontWeight = FontWeight.Bold,
+ )
Text(
(vmState as VmState.Error).message,
- color = Color.Gray, fontSize = 14.sp,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ fontSize = 14.sp,
modifier = Modifier.padding(top = 8.dp, start = 16.dp, end = 16.dp),
textAlign = TextAlign.Center,
)
Spacer(modifier = Modifier.height(16.dp))
- Text(
- "Tap to Retry",
- color = Color(0xFF4FC3F7), fontSize = 14.sp, fontWeight = FontWeight.Bold,
- modifier = Modifier
- .clip(RoundedCornerShape(8.dp))
- .background(Color(0xFF333333))
- .clickable { onNavigateBack() }
- .padding(horizontal = 24.dp, vertical = 12.dp),
- )
+ FilledTonalButton(onClick = onNavigateBack) {
+ Text("Tap to Retry")
+ }
}
}
}
- is VmState.Starting, is VmState.Paused, is VmState.Saving, is VmState.Resuming -> {
+ is VmState.Starting -> {
Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
- Column(horizontalAlignment = Alignment.CenterHorizontally) {
- CircularProgressIndicator(color = Color(0xFF4FC3F7), strokeWidth = 3.dp)
- Spacer(modifier = Modifier.height(16.dp))
- Text(
- when (vmState) {
- is VmState.Paused -> "VM Paused"
- is VmState.Saving -> "Saving state..."
- is VmState.Resuming -> "Resuming..."
- else -> ""
- },
- color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,
- )
- }
+ CircularProgressIndicator(
+ color = MaterialTheme.colorScheme.primary,
+ strokeWidth = 3.dp,
+ )
}
}
is VmState.Running -> {
Box(modifier = Modifier.weight(1f).fillMaxSize()) {
- val view = viewModel.getOrCreateTerminalView()
+ // The View is created per-Composition-context (i.e. per Activity).
+ // Caching it across config changes used to leak the destroyed Activity.
+ val view = remember(context) {
+ TerminalView(context, null).apply {
+ setTextSize(fontSize)
+ keepScreenOn = true
+ isFocusable = true
+ isFocusableInTouchMode = true
+ }
+ }
+
+ LaunchedEffect(view, themeBg) {
+ view.setBackgroundColor(themeBg ?: android.graphics.Color.BLACK)
+ }
+ LaunchedEffect(view, typeface) {
+ view.setTypeface(typeface)
+ view.post {
+ viewModel.forceUpdateSizeFromView(view, typeface)
+ view.updateSize()
+ }
+ }
- DisposableEffect(vmState) {
+ DisposableEffect(view, vmState) {
viewModel.resetOnRestart()
- viewModel.attachView(view)
+ viewModel.bindView(view)
viewModel.createSession()
view.setTerminalViewClient(viewModel.viewClient)
val sess = viewModel.session
@@ -231,45 +253,38 @@ fun TerminalScreen(
view.mEmulator = sess.emulator
}
view.requestFocus()
-
- // Session may have buffered MOTD + prompt bytes before the view
- // attached (the proxy SessionClient's onTextChanged no-ops when
- // the delegate is null). Force a repaint so the emulator's
- // existing state draws on first layout.
view.onScreenUpdated()
- // Push initial cols/rows once the view has laid out.
- // forceUpdateSizeFromView is the Paint-based fallback that works
- // before mRenderer is initialized; view.updateSize() is the renderer
- // path called last so it wins once metrics are ready.
view.post {
- viewModel.forceUpdateSizeFromView(view)
+ viewModel.forceUpdateSizeFromView(view, typeface)
view.updateSize()
view.onScreenUpdated()
}
+ onDispose { viewModel.bindView(null) }
+ }
- // Keyboard animation fires one layout change per frame (~25 events).
- // Debounce so SIGWINCH only fires once after the view has been stable
- // for 150 ms — turns 25 prompt-redraw flashes into one.
- val resizeHandler = android.os.Handler(android.os.Looper.getMainLooper())
- var pendingResize: Runnable? = null
- val listener = android.view.View.OnLayoutChangeListener { v, left, top, right, bottom,
- oldLeft, oldTop, oldRight, oldBottom ->
+ // Layout-change debounce: keyboard slide animation fires ~25 layout
+ // events. Coroutine debounce collapses them to one SIGWINCH.
+ val scope = rememberCoroutineScope()
+ DisposableEffect(view) {
+ var pending: kotlinx.coroutines.Job? = null
+ val listener = android.view.View.OnLayoutChangeListener {
+ v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
val w = right - left
val h = bottom - top
if (w <= 0 || h <= 0) return@OnLayoutChangeListener
if (w == oldRight - oldLeft && h == oldBottom - oldTop) return@OnLayoutChangeListener
- pendingResize?.let { resizeHandler.removeCallbacks(it) }
- val r = Runnable {
- viewModel.forceUpdateSizeFromView(v as TerminalView)
- v.updateSize()
+ pending?.cancel()
+ pending = scope.launch {
+ kotlinx.coroutines.delay(150)
+ val tv = v as TerminalView
+ viewModel.forceUpdateSizeFromView(tv, typeface)
+ tv.updateSize()
}
- pendingResize = r
- resizeHandler.postDelayed(r, 150)
}
view.addOnLayoutChangeListener(listener)
onDispose {
- pendingResize?.let { resizeHandler.removeCallbacks(it) }
+ pending?.cancel()
view.removeOnLayoutChangeListener(listener)
}
}
@@ -278,9 +293,6 @@ fun TerminalScreen(
factory = { view },
update = { v ->
v.setTextSize(fontSize)
- // setTextSize recreates mRenderer with new metrics; one updateSize
- // post-layout is enough because virtio-console reliably delivers
- // RESIZE to the VM (no need for the old multi-shot retries).
v.post { v.updateSize() }
},
modifier = Modifier.fillMaxSize(),
@@ -289,7 +301,7 @@ fun TerminalScreen(
}
}
- if (viewModel.showExtraKeys) {
+ if (showExtraKeys) {
AdaptiveContainer(
windowSizeClass = windowSizeClass,
maxWidth = 800
@@ -313,7 +325,7 @@ private fun ExtraKeysRow(
Row(
modifier = Modifier
.fillMaxWidth()
- .background(Color(0xFF1A1A1A))
+ .background(MaterialTheme.colorScheme.surfaceVariant)
.horizontalScroll(rememberScrollState())
.padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(3.dp),
@@ -391,14 +403,14 @@ private fun KeyButton(
}
Text(
text = label,
- color = if (isActive) Color.Black else Color(0xFFCCCCCC),
+ color = if (isActive) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurface,
fontSize = 12.sp,
fontWeight = FontWeight.Medium,
fontFamily = FontFamily.Monospace,
textAlign = TextAlign.Center,
modifier = Modifier
.clip(RoundedCornerShape(4.dp))
- .background(if (isActive) Color(0xFF4FC3F7) else Color(0xFF333333))
+ .background(if (isActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surface)
.then(tapModifier)
.padding(horizontal = 10.dp, vertical = 8.dp),
)
@@ -512,14 +524,9 @@ private fun ThemeSelectionDialog(
currentTheme: String,
onThemeSelect: (String) -> Unit,
onDismiss: () -> Unit,
+ viewModel: TerminalViewModel = hiltViewModel(),
) {
- val context = LocalContext.current
- val themes = remember {
- listOf("default") + (context.assets.list("colors")?.toList()
- ?.filter { it.endsWith(".properties") }
- ?.mapNotNull { it?.removeSuffix(".properties") }
- ?.sorted() ?: emptyList())
- }
+ val themes = remember { viewModel.listAssetNames("colors", ".properties") }
AlertDialog(
onDismissRequest = onDismiss,
@@ -560,14 +567,9 @@ private fun FontSelectionDialog(
currentFont: String,
onFontSelect: (String) -> Unit,
onDismiss: () -> Unit,
+ viewModel: TerminalViewModel = hiltViewModel(),
) {
- val context = LocalContext.current
- val fonts = remember {
- listOf("default") + (context.assets.list("fonts")?.toList()
- ?.filter { it.endsWith(".ttf") }
- ?.mapNotNull { it?.removeSuffix(".ttf") }
- ?.sorted() ?: emptyList())
- }
+ val fonts = remember { viewModel.listAssetNames("fonts", ".ttf") }
AlertDialog(
onDismissRequest = onDismiss,
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.kt
index 681210e..eb3edae 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
@@ -24,9 +24,7 @@
*/
package com.excp.podroid.ui.screens.terminal
-import android.annotation.SuppressLint
import android.content.Context
-import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.VibrationEffect
@@ -44,6 +42,7 @@ import androidx.lifecycle.viewModelScope
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.engine.PodroidQemu
import com.excp.podroid.engine.VmState
+import com.excp.podroid.util.LogProxy
import com.termux.terminal.TerminalEmulator
import com.termux.terminal.TerminalSession
import com.termux.terminal.TerminalSessionClient
@@ -76,12 +75,15 @@ class TerminalViewModel @Inject constructor(
val terminalFont: StateFlow<String> = settingsRepository.terminalFont
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), "default")
- // Quick-UI state (non-persistent for now)
- var showExtraKeys by mutableStateOf(true)
- private set
+ // Persisted across sessions — was previously transient in-memory only.
+ val showExtraKeysFlow: StateFlow<Boolean> = settingsRepository.showExtraKeys
+ .stateIn(viewModelScope, SharingStarted.Eagerly, true)
+ val hapticsEnabledFlow: StateFlow<Boolean> = settingsRepository.hapticsEnabled
+ .stateIn(viewModelScope, SharingStarted.Eagerly, true)
- var hapticsEnabled by mutableStateOf(true)
- private set
+ /** Mirrors of the persisted flows for callers that want a synchronous read. */
+ val showExtraKeys: Boolean get() = showExtraKeysFlow.value
+ val hapticsEnabled: Boolean get() = hapticsEnabledFlow.value
// Trigger for opening the Quick Settings drawer (composable-side reacts via StateFlow)
private val _showQuickSettings = kotlinx.coroutines.flow.MutableStateFlow(false)
@@ -89,27 +91,14 @@ class TerminalViewModel @Inject constructor(
// Quick settings helpers (non-persistent)
fun openQuickSettings() { _showQuickSettings.value = true }
- fun closeQuickSettings() {
- _showQuickSettings.value = false
- // Push the final terminal size now that settings are committed.
- // Covers the case where rapid slider drags sent stale intermediate sizes to the VM.
- pushSizeNow()
- }
+ fun closeQuickSettings() { _showQuickSettings.value = false }
- /**
- * Re-push the current cols/rows to the session and VM resize daemon.
- * Call after any setting that changes character cell dimensions.
- */
- fun pushSizeNow() {
- val v = terminalView ?: return
- v.post {
- v.updateSize()
- v.onScreenUpdated()
- }
+ fun updateShowExtraKeys(value: Boolean) {
+ viewModelScope.launch { settingsRepository.setShowExtraKeys(value) }
+ }
+ fun updateHapticsEnabled(value: Boolean) {
+ viewModelScope.launch { settingsRepository.setHapticsEnabled(value) }
}
-
- fun updateShowExtraKeys(value: Boolean) { showExtraKeys = value }
- fun updateHapticsEnabled(value: Boolean) { hapticsEnabled = value }
fun setTerminalFontSize(value: Int) {
viewModelScope.launch {
@@ -118,112 +107,65 @@ class TerminalViewModel @Inject constructor(
}
fun setTerminalColorTheme(value: String) {
- viewModelScope.launch {
- settingsRepository.setTerminalColorTheme(value)
- copyColorThemeToFilesDirAndApply(value)
- }
+ viewModelScope.launch { settingsRepository.setTerminalColorTheme(value) }
}
fun setTerminalFont(value: String) {
- viewModelScope.launch {
- settingsRepository.setTerminalFont(value)
- copyFontToFilesDirAndApply(value)
- }
- }
-
- private suspend fun copyColorThemeToFilesDirAndApply(theme: String) {
- val colorFile = java.io.File(context.filesDir, "colors.properties")
- var bgColor = android.graphics.Color.BLACK
- if (theme == "default") {
- colorFile.delete()
- } else {
- try {
- val bytes = context.assets.open("colors/$theme.properties").use { it.readBytes() }
- val props = java.util.Properties()
- props.load(bytes.inputStream())
- TerminalColors.COLOR_SCHEME.updateWith(props)
- val bgHex = props["background"] as? String
- bgColor = bgHex?.let { parseColor(it) } ?: android.graphics.Color.BLACK
- colorFile.writeBytes(bytes)
- } catch (_: Exception) {
- colorFile.delete()
- }
- }
- terminalView?.setBackgroundColor(bgColor)
- }
-
- private suspend fun copyFontToFilesDirAndApply(font: String) {
- val fontFile = java.io.File(context.filesDir, "font.ttf")
- var typeface: Typeface = Typeface.MONOSPACE
- if (font == "default") {
- fontFile.delete()
- } else {
- try {
- context.assets.open("fonts/$font.ttf").use { inp ->
- fontFile.outputStream().use { out -> inp.copyTo(out) }
- }
- typeface = Typeface.createFromFile(fontFile)
- } catch (_: Exception) {
- fontFile.delete()
- }
- }
- currentTypeface = typeface
- terminalView?.setTypeface(typeface)
- terminalView?.let { v ->
- v.post { forceUpdateSizeFromView(v); v.updateSize() }
- }
+ viewModelScope.launch { settingsRepository.setTerminalFont(value) }
}
- @SuppressLint("StaticFieldLeak") // created once per ViewModel lifetime; ViewModel is nav-scoped
- private var terminalView: TerminalView? = null
private var attached = false
- // Tracks the active terminal typeface so forceUpdateSizeFromView uses correct char metrics.
- private var currentTypeface: Typeface = Typeface.MONOSPACE
-
- fun getOrCreateTerminalView(): TerminalView {
- Log.d(TAG, "getOrCreateTerminalView called, current view: $terminalView, this: ${System.identityHashCode(this)}")
- terminalView?.let { return it }
-
- val colorFile = java.io.File(context.filesDir, "colors.properties")
- val bgColor = if (colorFile.exists()) {
- try {
- val props = java.util.Properties()
- colorFile.inputStream().use { props.load(it) }
- TerminalColors.COLOR_SCHEME.updateWith(props)
- val bgHex = props["background"] as? String
- if (bgHex != null) parseColor(bgHex) else android.graphics.Color.BLACK
- } catch (_: Exception) { android.graphics.Color.BLACK }
- } else {
- android.graphics.Color.BLACK
- }
-
- val fontFile = java.io.File(context.filesDir, "font.ttf")
- val typeface = if (fontFile.exists()) {
- try { Typeface.createFromFile(fontFile) } catch (_: Exception) { Typeface.MONOSPACE }
- } else { Typeface.MONOSPACE }
- currentTypeface = typeface
-
- val view = TerminalView(context, null).apply {
- setBackgroundColor(bgColor)
- setTextSize(terminalFontSize.value)
- setTypeface(typeface)
- setTerminalViewClient(viewClient)
- keepScreenOn = true
- isFocusable = true
- isFocusableInTouchMode = true
- }
+ /**
+ * Weak handle to the currently-attached TerminalView. Used only by client
+ * callbacks that need to call onScreenUpdated() / showSoftInput(), which
+ * fire from non-UI threads. WeakReference prevents leaking the destroyed
+ * Activity across config changes.
+ */
+ private var viewRef: java.lang.ref.WeakReference<TerminalView>? = null
- // Reattach existing session to new view
- session?.let { sess ->
- view.mTermSession = sess
- view.mEmulator = sess.emulator
- }
+ fun bindView(view: TerminalView?) {
+ viewRef = view?.let { java.lang.ref.WeakReference(it) }
+ }
- terminalView = view
- return view
+ /**
+ * 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) }
+ TerminalColors.COLOR_SCHEME.updateWith(props)
+ (props["background"] as? String)?.let { parseColor(it) }
+ } 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> {
+ val items = try {
+ context.assets.list(dir)?.toList() ?: emptyList()
+ } catch (_: Exception) { emptyList() }
+ return listOf("default") + items.filter { it.endsWith(suffix) }.map { it.removeSuffix(suffix) }.sorted()
}
+ /** 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) }
+ }
+ }
+ Typeface.createFromFile(cacheFile)
+ } catch (_: Exception) { Typeface.MONOSPACE }
+
private fun parseColor(hex: String): Int {
val clean = hex.removePrefix("#")
return when (clean.length) {
@@ -255,8 +197,10 @@ class TerminalViewModel @Inject constructor(
var session: TerminalSession? = null
private set
- var extraCtrl = false
- var extraAlt = false
+ var extraCtrl by mutableStateOf(false)
+ private set
+ var extraAlt by mutableStateOf(false)
+ private set
private val vibrator: Vibrator by lazy {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
@@ -269,7 +213,7 @@ class TerminalViewModel @Inject constructor(
val sessionClient = object : TerminalSessionClient {
override fun onTextChanged(changedSession: TerminalSession) {
- terminalView?.onScreenUpdated()
+ viewRef?.get()?.onScreenUpdated()
}
override fun onTitleChanged(changedSession: TerminalSession) {}
override fun onSessionFinished(finishedSession: TerminalSession) {}
@@ -295,27 +239,23 @@ class TerminalViewModel @Inject constructor(
override fun onColorsChanged(session: TerminalSession) {}
override fun onTerminalCursorStateChange(state: Boolean) {}
override fun getTerminalCursorStyle(): Int = 0
- override fun logError(tag: String?, message: String?) { Log.e(tag ?: TAG, message ?: "") }
- override fun logWarn(tag: String?, message: String?) { Log.w(tag ?: TAG, message ?: "") }
- override fun logInfo(tag: String?, message: String?) { Log.i(tag ?: TAG, message ?: "") }
- override fun logDebug(tag: String?, message: String?) { Log.d(tag ?: TAG, message ?: "") }
- override fun logVerbose(tag: String?, message: String?) { Log.v(tag ?: TAG, message ?: "") }
- override fun logStackTraceWithMessage(tag: String?, message: String?, e: Exception?) {
- Log.e(tag ?: TAG, message, e)
- }
- override fun logStackTrace(tag: String?, e: Exception?) {
- Log.e(tag ?: TAG, "Stack trace", e)
- }
+ 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)
+ override fun logDebug(tag: String?, message: String?) = LogProxy.debug(tag, TAG, message)
+ override fun logVerbose(tag: String?, message: String?) = LogProxy.verbose(tag, TAG, message)
+ override fun logStackTraceWithMessage(tag: String?, message: String?, e: Exception?) =
+ LogProxy.stackTraceWithMessage(tag, TAG, message, e)
+ override fun logStackTrace(tag: String?, e: Exception?) = LogProxy.stackTrace(tag, TAG, e)
}
val viewClient = object : TerminalViewClient {
override fun onScale(scale: Float): Float = scale
override fun onSingleTapUp(e: MotionEvent?) {
- terminalView?.let { view ->
- val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE)
- as android.view.inputmethod.InputMethodManager
- imm.showSoftInput(view, 0)
- }
+ val view = viewRef?.get() ?: return
+ val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE)
+ as android.view.inputmethod.InputMethodManager
+ imm.showSoftInput(view, 0)
}
override fun shouldBackButtonBeMappedToEscape(): Boolean = false
override fun shouldEnforceCharBasedInput(): Boolean = true
@@ -395,21 +335,14 @@ class TerminalViewModel @Inject constructor(
}
override fun onEmulatorSet() {}
- override fun logError(tag: String?, message: String?) { Log.e(tag ?: TAG, message ?: "") }
- override fun logWarn(tag: String?, message: String?) { Log.w(tag ?: TAG, message ?: "") }
- override fun logInfo(tag: String?, message: String?) { Log.i(tag ?: TAG, message ?: "") }
- override fun logDebug(tag: String?, message: String?) { Log.d(tag ?: TAG, message ?: "") }
- override fun logVerbose(tag: String?, message: String?) { Log.v(tag ?: TAG, message ?: "") }
- override fun logStackTraceWithMessage(tag: String?, message: String?, e: Exception?) {
- Log.e(tag ?: TAG, message, e)
- }
- override fun logStackTrace(tag: String?, e: Exception?) {
- Log.e(tag ?: TAG, "Stack trace", e)
- }
- }
-
- fun attachView(view: TerminalView) {
- terminalView = view
+ 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)
+ override fun logDebug(tag: String?, message: String?) = LogProxy.debug(tag, TAG, message)
+ override fun logVerbose(tag: String?, message: String?) = LogProxy.verbose(tag, TAG, message)
+ override fun logStackTraceWithMessage(tag: String?, message: String?, e: Exception?) =
+ LogProxy.stackTraceWithMessage(tag, TAG, message, e)
+ override fun logStackTrace(tag: String?, e: Exception?) = LogProxy.stackTrace(tag, TAG, e)
}
fun createSession() {
@@ -429,20 +362,6 @@ class TerminalViewModel @Inject constructor(
session = null
}
- /**
- * Triggered by the layout listener in TerminalScreen when the view dimensions
- * change (initial layout, keyboard open/close, rotation).
- *
- * Calls TerminalSession.updateSize which:
- * 1. Resizes the local terminal emulator buffer.
- * 2. Calls ioctl(pty_master_fd, TIOCSWINSZ) via Termux JNI.
- * 3. The kernel sends SIGWINCH to the bridge process.
- * 4. The bridge sends RESIZE to ctrl.sock → VM gets proper SIGWINCH.
- */
- fun updateSize(cols: Int, rows: Int) {
- session?.updateSize(cols, rows)
- }
-
/**
* Compute cols/rows from view pixel dimensions + paint metrics and push
* directly to the session, bypassing TerminalView.updateSize() which depends
@@ -452,7 +371,7 @@ class TerminalViewModel @Inject constructor(
* into the wrong grid (visible symptom: btop draws in the top-left only,
* because the emulator is larger than the visible viewport).
*/
- fun forceUpdateSizeFromView(view: TerminalView) {
+ fun forceUpdateSizeFromView(view: TerminalView, typeface: Typeface = Typeface.MONOSPACE) {
val sess = session ?: return
val w = view.width
val h = view.height
@@ -460,13 +379,12 @@ class TerminalViewModel @Inject constructor(
Log.d(TAG, "forceUpdateSize: view not measured yet (${w}x${h})")
return
}
- // Use the same typeface + raw pixel size as TerminalView.setTextSize(int) —
- // which passes the int straight to Paint.setTextSize() without scaledDensity.
- // Must use currentTypeface (not Typeface.MONOSPACE) so that custom fonts
- // (JetBrains Mono, Fira Code, etc.) with different cell metrics produce the
- // correct cols/rows — otherwise TUI apps render in the wrong grid area.
+ // Same typeface + raw pixel size as TerminalView.setTextSize(int) — which passes
+ // the int straight to Paint.setTextSize() without scaledDensity. Custom fonts
+ // (JetBrains Mono, Fira Code, etc.) have different cell metrics from monospace,
+ // so honor the view's actual typeface or TUI apps render in the wrong grid.
val paint = android.graphics.Paint().apply {
- typeface = currentTypeface
+ this.typeface = typeface
textSize = terminalFontSize.value.toFloat()
isAntiAlias = true
}
@@ -550,7 +468,11 @@ class TerminalViewModel @Inject constructor(
override fun onCleared() {
super.onCleared()
- terminalView = null
+ // Drop the proxy's pointer to this dead ViewModel — otherwise the singleton
+ // PodroidQemu keeps forwarding session events into a tombstoned client.
+ if (qemu.sessionClientDelegate === sessionClient) {
+ qemu.sessionClientDelegate = null
+ }
attached = false
}