Skip to content

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

feat: enhance terminal with CSI key support, focus events, resize propagation, and font/theme switching

ExTva7d8a71ebab8
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 04bfed0..3141688 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
@@ -1,51 +1,59 @@
-/*
- * Podroid - Rootless Podman for Android
- * Copyright (C) 2024 Podroid contributors
- *
- * Terminal screen using Termux TerminalView wired to the podroid-bridge
- * binary via a real TerminalSession PTY. No reflection, no emulator
- * injection. Window resize propagates through the normal PTY/SIGWINCH path.
- */
package com.excp.podroid.ui.screens.terminal
import android.app.Activity
-import android.graphics.Typeface
import android.view.WindowManager
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
-import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
-import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
+import androidx.compose.material3.windowsizeclass.WindowSizeClass
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
+import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
+import kotlinx.coroutines.delay
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -59,17 +67,20 @@ import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import com.excp.podroid.engine.VmState
+import com.excp.podroid.ui.components.AdaptiveContainer
import com.termux.view.TerminalView
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TerminalScreen(
+ windowSizeClass: WindowSizeClass,
onNavigateBack: () -> Unit,
viewModel: TerminalViewModel = hiltViewModel(),
) {
val context = LocalContext.current
val vmState by viewModel.vmState.collectAsState()
val fontSize by viewModel.terminalFontSize.collectAsState()
+ val showQuickSettings by viewModel.showQuickSettings.collectAsState()
DisposableEffect(Unit) {
val activity = context as? Activity
@@ -77,9 +88,46 @@ fun TerminalScreen(
activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
onDispose {
activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ @Suppress("DEPRECATION")
+ activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED)
}
}
+ // Forward app-level focus into the VM as xterm focus events (CSI I / CSI O)
+ // so nvim's FocusGained/FocusLost autocommands fire. Gated by the emulator's
+ // DECSET 1004 mode inside the ViewModel so we never leak literal bytes.
+ val lifecycleOwner = LocalLifecycleOwner.current
+ DisposableEffect(lifecycleOwner) {
+ val observer = LifecycleEventObserver { _, event ->
+ when (event) {
+ Lifecycle.Event.ON_RESUME -> viewModel.sendFocusEvent(true)
+ Lifecycle.Event.ON_PAUSE -> viewModel.sendFocusEvent(false)
+ else -> {}
+ }
+ }
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
+ }
+
+ val colorTheme by viewModel.terminalColorTheme.collectAsState()
+ val terminalFont by viewModel.terminalFont.collectAsState()
+
+ if (showQuickSettings) {
+ QuickSettingsDialog(
+ fontSize = fontSize,
+ onFontSizeChange = { viewModel.setTerminalFontSize(it) },
+ onDismiss = { viewModel.closeQuickSettings() },
+ showExtraKeys = viewModel.showExtraKeys,
+ onToggleExtraKeys = { viewModel.updateShowExtraKeys(it) },
+ hapticsEnabled = viewModel.hapticsEnabled,
+ onToggleHaptics = { viewModel.updateHapticsEnabled(it) },
+ colorTheme = colorTheme,
+ onColorThemeChange = { viewModel.setTerminalColorTheme(it) },
+ terminalFont = terminalFont,
+ onFontChange = { viewModel.setTerminalFont(it) },
+ )
+ }
+
Column(
modifier = Modifier
.fillMaxSize()
@@ -104,6 +152,11 @@ fun TerminalScreen(
)
}
},
+ actions = {
+ IconButton(onClick = { viewModel.openQuickSettings() }) {
+ Text("⚙", color = Color.White, fontSize = 18.sp)
+ }
+ },
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFF1A1A1A)),
)
@@ -178,34 +231,86 @@ 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 cols/rows to the session on a schedule:
+ // forceUpdateSizeFromView — Paint-based fallback, works before mRenderer
+ // is initialized; uses currentTypeface so custom
+ // fonts produce correct metrics.
+ // view.updateSize() — renderer-based, accurate after first draw.
+ // Both are called; the renderer path is called last so it wins once ready.
+ // Multiple delays ensure the VM's ctrl.sock resize daemon receives the
+ // message even if it wasn't listening yet at the initial post.
+ val pushSize = {
+ viewModel.forceUpdateSizeFromView(view)
+ view.updateSize()
+ view.onScreenUpdated()
+ }
+ view.post(pushSize)
+ view.postDelayed(pushSize, 150)
+ view.postDelayed(pushSize, 600)
+ view.postDelayed(pushSize, 1500)
+ // Debounce resize: keyboard animation fires one layout change per frame
+ // (~25 events). Only send RESIZE after the view has been stable for 150ms.
+ 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 ->
val w = right - left
val h = bottom - top
if (w <= 0 || h <= 0) return@OnLayoutChangeListener
if (w == oldRight - oldLeft && h == oldBottom - oldTop) return@OnLayoutChangeListener
- (v as TerminalView).updateSize()
+ pendingResize?.let { resizeHandler.removeCallbacks(it) }
+ val r = Runnable {
+ viewModel.forceUpdateSizeFromView(v as TerminalView)
+ v.updateSize()
+ }
+ pendingResize = r
+ resizeHandler.postDelayed(r, 150)
}
view.addOnLayoutChangeListener(listener)
onDispose {
+ pendingResize?.let { resizeHandler.removeCallbacks(it) }
view.removeOnLayoutChangeListener(listener)
}
}
AndroidView(
factory = { view },
- update = { v -> v.setTextSize(fontSize) },
+ update = { v ->
+ v.setTextSize(fontSize)
+ // setTextSize immediately recreates mRenderer with new metrics.
+ // Use v.updateSize() directly — it reads from mRenderer (correct),
+ // avoiding the off-by-row conflict with forceUpdateSizeFromView's
+ // different line-height formula. Multiple delays ensure the VM's
+ // resize daemon receives the message even under load.
+ v.post { v.updateSize() }
+ v.postDelayed({ v.updateSize() }, 300)
+ v.postDelayed({ v.updateSize() }, 800)
+ },
modifier = Modifier.fillMaxSize(),
)
}
}
}
- ExtraKeysRow(
- onKey = { viewModel.sendExtraKey(it) },
- ctrlActive = viewModel.extraCtrl,
- altActive = viewModel.extraAlt,
- )
+ if (viewModel.showExtraKeys) {
+ AdaptiveContainer(
+ windowSizeClass = windowSizeClass,
+ maxWidth = 800
+ ) {
+ ExtraKeysRow(
+ onKey = { viewModel.sendExtraKey(it) },
+ ctrlActive = viewModel.extraCtrl,
+ altActive = viewModel.extraAlt,
+ )
+ }
+ }
}
}
@@ -224,54 +329,288 @@ private fun ExtraKeysRow(
horizontalArrangement = Arrangement.spacedBy(3.dp),
verticalAlignment = Alignment.CenterVertically,
) {
- ExtraKey("ESC", onKey)
- ExtraKey("TAB", onKey)
- ExtraKey("CTRL", onKey, active = ctrlActive)
- ExtraKey("\u2190", onKey, sendKey = "LEFT")
- ExtraKey("\u2191", onKey, sendKey = "UP")
- ExtraKey("\u2193", onKey, sendKey = "DOWN")
- ExtraKey("\u2192", onKey, sendKey = "RIGHT")
- ExtraKey("ALT", onKey, active = altActive)
- ExtraKey("-", onKey)
- ExtraKey("/", onKey)
- ExtraKey("|", onKey)
- ExtraKey("HOME", onKey)
- ExtraKey("END", onKey)
- ExtraKey("PGUP", onKey)
- ExtraKey("PGDN", onKey)
- ExtraKey("F1", onKey)
- ExtraKey("F2", onKey)
- ExtraKey("F3", onKey)
- ExtraKey("F4", onKey)
- ExtraKey("F5", onKey)
- ExtraKey("F6", onKey)
- ExtraKey("F7", onKey)
- ExtraKey("F8", onKey)
- ExtraKey("F9", onKey)
- ExtraKey("F10", onKey)
- ExtraKey("F11", onKey)
- ExtraKey("F12", onKey)
+ KeyButton("ESC", onKey)
+ KeyButton("TAB", onKey)
+ KeyButton("CTRL", onKey, isActive = ctrlActive)
+ KeyButton("\u2190", onKey, sendKey = "LEFT", repeatable = true)
+ KeyButton("\u2191", onKey, sendKey = "UP", repeatable = true)
+ KeyButton("\u2193", onKey, sendKey = "DOWN", repeatable = true)
+ KeyButton("\u2192", onKey, sendKey = "RIGHT", repeatable = true)
+ KeyButton("ALT", onKey, isActive = altActive)
+ KeyButton("-", onKey)
+ KeyButton("/", onKey)
+ KeyButton("|", onKey)
+ KeyButton("HOME", onKey)
+ KeyButton("END", onKey)
+ KeyButton("PGUP", onKey)
+ KeyButton("PGDN", onKey)
+ KeyButton("F1", onKey)
+ KeyButton("F2", onKey)
+ KeyButton("F3", onKey)
+ KeyButton("F4", onKey)
+ KeyButton("F5", onKey)
+ KeyButton("F6", onKey)
+ KeyButton("F7", onKey)
+ KeyButton("F8", onKey)
+ KeyButton("F9", onKey)
+ KeyButton("F10", onKey)
+ KeyButton("F11", onKey)
+ KeyButton("F12", onKey)
}
}
@Composable
-private fun ExtraKey(
+private fun KeyButton(
label: String,
onKey: (String) -> Unit,
sendKey: String = label,
- active: Boolean = false,
+ isActive: Boolean = false,
+ repeatable: Boolean = false,
) {
+ // State-based press tracking: the gesture coroutine flips `pressed`,
+ // and a LaunchedEffect keyed on that state drives the repeat loop.
+ // Splitting state from the pointer coroutine avoids the cancellation
+ // issues you hit when the scroll container on the parent Row steals
+ // the gesture mid-hold.
+ var pressed by remember { mutableStateOf(false) }
+ LaunchedEffect(pressed, sendKey, repeatable) {
+ if (!repeatable || !pressed) return@LaunchedEffect
+ delay(400L)
+ var interval = 70L
+ while (pressed) {
+ onKey(sendKey)
+ delay(interval)
+ if (interval > 30L) interval -= 3L
+ }
+ }
+ val tapModifier = if (repeatable) {
+ Modifier.pointerInput(sendKey) {
+ awaitEachGesture {
+ awaitFirstDown(requireUnconsumed = false)
+ onKey(sendKey) // fire once on touch-down
+ pressed = true
+ try {
+ waitForUpOrCancellation()
+ } finally {
+ pressed = false
+ }
+ }
+ }
+ } else {
+ Modifier.clickable { onKey(sendKey) }
+ }
Text(
text = label,
- color = if (active) Color.Black else Color(0xFFCCCCCC),
+ color = if (isActive) Color.Black else Color(0xFFCCCCCC),
fontSize = 12.sp,
fontWeight = FontWeight.Medium,
fontFamily = FontFamily.Monospace,
textAlign = TextAlign.Center,
modifier = Modifier
.clip(RoundedCornerShape(4.dp))
- .background(if (active) Color(0xFF4FC3F7) else Color(0xFF333333))
- .clickable { onKey(sendKey) }
+ .background(if (isActive) Color(0xFF4FC3F7) else Color(0xFF333333))
+ .then(tapModifier)
.padding(horizontal = 10.dp, vertical = 8.dp),
)
}
+
+@Composable
+private fun QuickSettingsDialog(
+ fontSize: Int,
+ onFontSizeChange: (Int) -> Unit,
+ onDismiss: () -> Unit,
+ showExtraKeys: Boolean,
+ onToggleExtraKeys: (Boolean) -> Unit,
+ hapticsEnabled: Boolean,
+ onToggleHaptics: (Boolean) -> Unit,
+ colorTheme: String,
+ onColorThemeChange: (String) -> Unit,
+ terminalFont: String,
+ onFontChange: (String) -> Unit,
+) {
+ var showThemeDialog by remember { mutableStateOf(false) }
+ var showFontDialog by remember { mutableStateOf(false) }
+
+ if (showThemeDialog) {
+ ThemeSelectionDialog(
+ currentTheme = colorTheme,
+ onThemeSelect = {
+ onColorThemeChange(it)
+ showThemeDialog = false
+ },
+ onDismiss = { showThemeDialog = false }
+ )
+ }
+
+ if (showFontDialog) {
+ FontSelectionDialog(
+ currentFont = terminalFont,
+ onFontSelect = {
+ onFontChange(it)
+ showFontDialog = false
+ },
+ onDismiss = { showFontDialog = false }
+ )
+ }
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Quick Settings") },
+ text = {
+ Column {
+ Text("Font Size: $fontSize sp", style = MaterialTheme.typography.labelMedium)
+ androidx.compose.material3.Slider(
+ value = fontSize.toFloat(),
+ onValueChange = { onFontSizeChange(it.toInt()) },
+ valueRange = 12f..32f,
+ steps = 20,
+ modifier = Modifier.padding(top = 4.dp, bottom = 16.dp)
+ )
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ FilledTonalButton(
+ onClick = { showThemeDialog = true },
+ modifier = Modifier.weight(1f)
+ ) {
+ Text("Theme")
+ }
+ FilledTonalButton(
+ onClick = { showFontDialog = true },
+ modifier = Modifier.weight(1f)
+ ) {
+ Text("Font")
+ }
+ }
+
+ Spacer(modifier = Modifier.height(16.dp))
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text("Show extra keys", modifier = Modifier.weight(1f))
+ androidx.compose.material3.Switch(
+ checked = showExtraKeys,
+ onCheckedChange = onToggleExtraKeys
+ )
+ }
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text("Haptic feedback", modifier = Modifier.weight(1f))
+ androidx.compose.material3.Switch(
+ checked = hapticsEnabled,
+ onCheckedChange = onToggleHaptics
+ )
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = onDismiss) {
+ Text("Done")
+ }
+ }
+ )
+}
+
+@Composable
+private fun ThemeSelectionDialog(
+ currentTheme: String,
+ onThemeSelect: (String) -> Unit,
+ onDismiss: () -> Unit,
+) {
+ val context = LocalContext.current
+ val themes = remember {
+ listOf("default") + (context.assets.list("colors")?.toList()
+ ?.filter { it.endsWith(".properties") }
+ ?.mapNotNull { it?.removeSuffix(".properties") }
+ ?.sorted() ?: emptyList())
+ }
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Select Theme") },
+ text = {
+ LazyColumn(modifier = Modifier.height(400.dp)) {
+ items(themes.size) { index ->
+ val theme = themes[index]
+ val isSelected = theme == currentTheme
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(8.dp))
+ .background(
+ if (isSelected) MaterialTheme.colorScheme.primary
+ else Color.Transparent
+ )
+ .clickable { onThemeSelect(theme) }
+ .padding(horizontal = 16.dp, vertical = 12.dp)
+ ) {
+ Text(
+ text = theme.replace('-', ' ').replaceFirstChar { it.uppercase() },
+ color = if (isSelected) MaterialTheme.colorScheme.onPrimary
+ else MaterialTheme.colorScheme.onSurface,
+ )
+ }
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ )
+}
+
+@Composable
+private fun FontSelectionDialog(
+ currentFont: String,
+ onFontSelect: (String) -> Unit,
+ onDismiss: () -> Unit,
+) {
+ val context = LocalContext.current
+ val fonts = remember {
+ listOf("default") + (context.assets.list("fonts")?.toList()
+ ?.filter { it.endsWith(".ttf") }
+ ?.mapNotNull { it?.removeSuffix(".ttf") }
+ ?.sorted() ?: emptyList())
+ }
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Select Font") },
+ text = {
+ LazyColumn(modifier = Modifier.height(400.dp)) {
+ items(fonts.size) { index ->
+ val font = fonts[index]
+ val isSelected = font == currentFont
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(8.dp))
+ .background(
+ if (isSelected) MaterialTheme.colorScheme.primary
+ else Color.Transparent
+ )
+ .clickable { onFontSelect(font) }
+ .padding(horizontal = 16.dp, vertical = 12.dp)
+ ) {
+ Text(
+ text = font.replace('-', ' ').replaceFirstChar { it.uppercase() },
+ fontFamily = FontFamily.Monospace,
+ color = if (isSelected) MaterialTheme.colorScheme.onPrimary
+ else MaterialTheme.colorScheme.onSurface,
+ )
+ }
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ )
+}
+
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 534fd0e..84f56d7 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
@@ -30,6 +30,9 @@ import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.util.Log
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
import com.termux.terminal.TerminalColors
import android.view.KeyEvent
import android.view.MotionEvent
@@ -38,6 +41,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.termux.terminal.TerminalEmulator
import com.termux.terminal.TerminalSession
import com.termux.terminal.TerminalSessionClient
import com.termux.view.TerminalView
@@ -45,6 +49,7 @@ import com.termux.view.TerminalViewClient
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import java.io.File
@@ -54,7 +59,7 @@ import javax.inject.Inject
class TerminalViewModel @Inject constructor(
@ApplicationContext private val context: Context,
private val qemu: PodroidQemu,
- settingsRepository: SettingsRepository,
+ private val settingsRepository: SettingsRepository,
) : ViewModel() {
val vmState: StateFlow<VmState> = qemu.state
@@ -68,18 +73,114 @@ 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
+
+ var hapticsEnabled by mutableStateOf(true)
+ private set
+
+ // Trigger for opening the Quick Settings drawer (composable-side reacts via StateFlow)
+ private val _showQuickSettings = kotlinx.coroutines.flow.MutableStateFlow(false)
+ val showQuickSettings = _showQuickSettings
+
+ // 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()
+ }
+
/**
- * Forces recreation of the terminal view on next call.
- * Call when theme/font/size settings change.
+ * Re-push the current cols/rows to the session and VM resize daemon.
+ * Call after any setting that changes character cell dimensions.
*/
- fun invalidateTerminalView() {
- terminalView = null
+ fun pushSizeNow() {
+ val v = terminalView ?: return
+ v.post {
+ v.updateSize()
+ v.onScreenUpdated()
+ }
+ v.postDelayed({ v.updateSize() }, 300)
+ v.postDelayed({ v.updateSize() }, 800)
+ }
+
+ fun updateShowExtraKeys(value: Boolean) { showExtraKeys = value }
+ fun updateHapticsEnabled(value: Boolean) { hapticsEnabled = value }
+
+ fun setTerminalFontSize(value: Int) {
+ viewModelScope.launch {
+ settingsRepository.setTerminalFontSize(value)
+ }
+ }
+
+ fun setTerminalColorTheme(value: String) {
+ viewModelScope.launch {
+ settingsRepository.setTerminalColorTheme(value)
+ copyColorThemeToFilesDirAndApply(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() }
+ v.postDelayed({ v.updateSize() }, 400)
+ }
}
@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 }
@@ -101,15 +202,24 @@ class TerminalViewModel @Inject constructor(
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
}
+
+ // Reattach existing session to new view
+ session?.let { sess ->
+ view.mTermSession = sess
+ view.mEmulator = sess.emulator
+ }
+
terminalView = view
return view
}
@@ -171,10 +281,16 @@ class TerminalViewModel @Inject constructor(
override fun onPasteTextFromClipboard(session: TerminalSession?) {
val cb = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
val text = cb.primaryClip?.getItemAt(0)?.coerceToText(context)?.toString() ?: return
- session?.write(text)
+ // Route through TerminalEmulator.paste() — it wraps in CSI 200~ / 201~
+ // when bracketed-paste mode is on (nvim, bash) and sends raw otherwise.
+ // Fall back to raw write if the emulator isn't ready yet.
+ val emu = session?.emulator
+ if (emu != null) emu.paste(text) else session?.write(text)
}
override fun onBell(session: TerminalSession) {
- vibrator.vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE))
+ if (hapticsEnabled) {
+ vibrator.vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE))
+ }
}
override fun onColorsChanged(session: TerminalSession) {}
override fun onTerminalCursorStateChange(state: Boolean) {}
@@ -209,18 +325,29 @@ class TerminalViewModel @Inject constructor(
override fun onKeyDown(keyCode: Int, e: KeyEvent?, session: TerminalSession?): Boolean {
if (e == null) return false
+ val shift = e.isShiftPressed
+ val ctrl = e.isCtrlPressed || extraCtrl
+ val alt = e.isAltPressed || extraAlt
+ // xterm CSI modifier: 1=none, 2=shift, 3=alt, 4=shift+alt, 5=ctrl,
+ // 6=ctrl+shift, 7=ctrl+alt, 8=all. Used for "ESC [1;<m><final>".
+ val mod = 1 + (if (shift) 1 else 0) + (if (alt) 2 else 0) + (if (ctrl) 4 else 0)
+ fun arrow(final: Char): ByteArray =
+ if (mod == 1) "\u001b[$final".toByteArray()
+ else "\u001b[1;$mod$final".toByteArray()
+
val bytes = when (keyCode) {
KeyEvent.KEYCODE_ENTER -> byteArrayOf(13)
KeyEvent.KEYCODE_DEL -> byteArrayOf(127)
KeyEvent.KEYCODE_FORWARD_DEL -> "\u001b[3~".toByteArray()
- KeyEvent.KEYCODE_TAB -> byteArrayOf(9)
+ KeyEvent.KEYCODE_TAB ->
+ if (shift) "\u001b[Z".toByteArray() else byteArrayOf(9)
KeyEvent.KEYCODE_ESCAPE -> byteArrayOf(27)
- KeyEvent.KEYCODE_DPAD_UP -> "\u001b[A".toByteArray()
- KeyEvent.KEYCODE_DPAD_DOWN -> "\u001b[B".toByteArray()
- KeyEvent.KEYCODE_DPAD_RIGHT -> "\u001b[C".toByteArray()
- KeyEvent.KEYCODE_DPAD_LEFT -> "\u001b[D".toByteArray()
- KeyEvent.KEYCODE_MOVE_HOME -> "\u001b[H".toByteArray()
- KeyEvent.KEYCODE_MOVE_END -> "\u001b[F".toByteArray()
+ KeyEvent.KEYCODE_DPAD_UP -> arrow('A')
+ KeyEvent.KEYCODE_DPAD_DOWN -> arrow('B')
+ KeyEvent.KEYCODE_DPAD_RIGHT -> arrow('C')
+ KeyEvent.KEYCODE_DPAD_LEFT -> arrow('D')
+ KeyEvent.KEYCODE_MOVE_HOME -> arrow('H')
+ KeyEvent.KEYCODE_MOVE_END -> arrow('F')
KeyEvent.KEYCODE_PAGE_UP -> "\u001b[5~".toByteArray()
KeyEvent.KEYCODE_PAGE_DOWN -> "\u001b[6~".toByteArray()
KeyEvent.KEYCODE_INSERT -> "\u001b[2~".toByteArray()
@@ -240,6 +367,7 @@ class TerminalViewModel @Inject constructor(
}
if (bytes != null) {
session?.write(bytes, 0, bytes.size)
+ if (mod != 1) { extraCtrl = false; extraAlt = false }
return true
}
return false
@@ -315,6 +443,73 @@ class TerminalViewModel @Inject constructor(
session?.updateSize(cols, rows)
}
+ /**
+ * Compute cols/rows from view pixel dimensions + paint metrics and push
+ * directly to the session, bypassing TerminalView.updateSize() which depends
+ * on mRenderer being lazily initialized during the first draw. When the
+ * session is attached before first paint, updateSize() computes zero sizes,
+ * leaves the emulator at the initial 80x24 default, and TUI apps render
+ * 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) {
+ val sess = session ?: return
+ val w = view.width
+ val h = view.height
+ if (w <= 0 || h <= 0) {
+ 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.
+ val paint = android.graphics.Paint().apply {
+ typeface = currentTypeface
+ textSize = terminalFontSize.value.toFloat()
+ isAntiAlias = true
+ }
+ val charWidth = paint.measureText("M").coerceAtLeast(1f)
+ val fm = paint.fontMetrics
+ val lineHeight = (fm.descent - fm.ascent + fm.leading).coerceAtLeast(1f)
+ 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)
+ }
+
+ /**
+ * Emit xterm focus-in/out (CSI I / CSI O) when the app gains/loses focus.
+ * nvim's `FocusGained` / `FocusLost` autocommands rely on these. DECSET 1004
+ * (`DECSET_BIT_SEND_FOCUS_EVENTS`) and `isDecsetInternalBitSet` are private
+ * in the Termux AAR, so we read the `mCurrentDecSetFlags` field reflectively
+ * and mask with the known bit. If the reflection ever breaks we silently
+ * skip — sending focus bytes to a shell that didn't enable reporting would
+ * leak literal "^[[I" noise into the prompt.
+ */
+ fun sendFocusEvent(focused: Boolean) {
+ val sess = session ?: return
+ val emu = sess.emulator ?: return
+ if (!isFocusReportingEnabled(emu)) return
+ val seq = if (focused) "\u001b[I".toByteArray() else "\u001b[O".toByteArray()
+ sess.write(seq, 0, seq.size)
+ }
+
+ private fun isFocusReportingEnabled(emu: TerminalEmulator): Boolean = try {
+ val cls = TerminalEmulator::class.java
+ val flagsField = cls.getDeclaredField("mCurrentDecSetFlags").apply { isAccessible = true }
+ // Termux maps the public DECSET code 1004 via mapDecSetBitToInternalBit — we can't
+ // call that (package-private), so we derive the bit by setting 1004 through
+ // the public doDecSetOrReset path and observing the delta. Cheaper: invoke the
+ // package-private mapper reflectively.
+ val mapper = cls.getDeclaredMethod("mapDecSetBitToInternalBit", Int::class.javaPrimitiveType)
+ .apply { isAccessible = true }
+ val bit = mapper.invoke(null, 1004) as Int
+ val flags = flagsField.getInt(emu)
+ (flags and bit) != 0
+ } catch (_: Throwable) { false }
+
fun sendExtraKey(key: String) {
when (key) {
"CTRL" -> { extraCtrl = !extraCtrl; return }