A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
fix(terminal): use public emulator API for cursor/focus modes; recover dead sessions
ExTvba99f686f637
diff --git a/app/proguard-rules.pro b/app/proguard-rules.proindex 57bedda..947276e 100644--- a/app/proguard-rules.pro+++ b/app/proguard-rules.pro@@ -6,8 +6,11 @@public com.termux.terminal.TerminalEmulator mEmulator;}-# TerminalSession.mEmulator replaced via reflection in TerminalViewModel-# to install a no-op TerminalOutput (prevents CPR garbage in the VM shell).+# TerminalSession.mEmulator: read via the public getEmulator() to wire the+# emulator into TerminalView. The app no longer reflects on this field (the old+# DECSET-flag reflection was replaced by the public isCursorKeysApplicationMode+# / isFocusEventsEnabled accessors), so this keep rule is belt-and-suspenders+# against R8 stripping the field behind the getter.-keepclassmembers class com.termux.terminal.TerminalSession {com.termux.terminal.TerminalEmulator mEmulator;}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 8f01468..1ac1707 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@@ -99,6 +99,10 @@ import androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.unit.Dpimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.onClick+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.unit.dp@@ -209,7 +213,7 @@ fun TerminalScreen(}Spacer(Modifier.width(PodroidTokens.Spacing.XS))IconButton(onClick = onNavigateToX11) {- Icon(Icons.Default.DesktopWindows, contentDescription = "X11 screen")+ Icon(Icons.Default.DesktopWindows, contentDescription = stringResource(R.string.x11_open))}Spacer(Modifier.width(PodroidTokens.Spacing.XS))IconButton(onClick = { viewModel.openQuickSettings() }) {@@ -417,6 +421,26 @@ private fun TerminalSurface(onDispose { viewModel.bindView(null) }}+ // Dead-session auto-reconnect: when the bridge dies while the VM stays+ // Running, the ViewModel bumps reconnectSignal. Re-create the session and+ // re-attach it to this same view so the user isn't stranded on a dead+ // "[Process completed]" buffer. Skips the initial 0 (the DisposableEffect+ // above owns the first attach).+ val reconnectSignal by viewModel.reconnectSignal.collectAsStateWithLifecycle()+ LaunchedEffect(view, reconnectSignal) {+ if (reconnectSignal == 0) return@LaunchedEffect+ viewModel.resetOnRestart()+ viewModel.createSession()+ val sess = viewModel.session ?: return@LaunchedEffect+ view.mTermSession = sess+ view.mEmulator = sess.emulator+ view.onScreenUpdated()+ view.post {+ view.updateSize()+ view.onScreenUpdated()+ }+ }+// Pause the blinker when the activity is backgrounded. Without this// the Choreographer FrameCallback keeps firing every VSYNC in// paused-without-detach states (split-screen, dialog occlusion, PiP).@@ -512,6 +536,7 @@ private fun ExtraKeysRow(KeyButton("\u2193", onKey, sendKey = "DOWN", repeatable = true)KeyButton("\u2192", onKey, sendKey = "RIGHT", repeatable = true)KeyButton("ALT", onKey, isActive = altActive)+ KeyButton("PASTE", onKey)KeyButton("-", onKey); KeyButton("/", onKey); KeyButton("|", onKey)KeyButton("HOME", onKey); KeyButton("END", onKey)KeyButton("PGUP", onKey); KeyButton("PGDN", onKey)@@ -540,27 +565,35 @@ private fun KeyButton(}}val tapModifier = if (repeatable) {- Modifier.pointerInput(sendKey) {- awaitEachGesture {- awaitFirstDown(requireUnconsumed = false)- onKey(sendKey)- pressed = true- try { waitForUpOrCancellation() } finally { pressed = false }+ // The raw pointerInput path is invisible to accessibility services; add+ // button semantics + an onClick action so TalkBack can announce and+ // activate repeatable keys (arrows) like the clickable ones.+ Modifier+ .semantics {+ role = Role.Button+ onClick(label = sendKey) { onKey(sendKey); true }+ }+ .pointerInput(sendKey) {+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ onKey(sendKey)+ pressed = true+ try { waitForUpOrCancellation() } finally { pressed = false }+ }}- }} else {- Modifier.clickable { onKey(sendKey) }+ Modifier.clickable(role = Role.Button) { onKey(sendKey) }}Text(text = label,- color = if (isActive) PodroidTokens.AccentInk else MaterialTheme.colorScheme.onSurface,+ color = if (isActive) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurface,fontSize = 13.sp,fontWeight = FontWeight.Medium,fontFamily = PodroidTokens.mono(),textAlign = TextAlign.Center,modifier = Modifier.clip(RoundedCornerShape(PodroidTokens.Radius.Chip))- .background(if (isActive) PodroidTokens.Accent else MaterialTheme.colorScheme.surfaceVariant)+ .background(if (isActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant).border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(PodroidTokens.Radius.Chip)).then(tapModifier).padding(horizontal = 13.dp, vertical = 9.dp),@@ -959,7 +992,7 @@ private fun AddSwatch(Column(horizontalAlignment = Alignment.CenterHorizontally) {Text(label,style = MaterialTheme.typography.labelLarge,- color = PodroidTokens.Accent,+ color = MaterialTheme.colorScheme.primary,fontWeight = FontWeight.SemiBold)Text(subLabel,style = MaterialTheme.typography.labelSmall,@@ -1141,7 +1174,7 @@ private fun SwatchBox(.then(clickModifier).border(width = if (selected) 2.dp else 1.dp,- color = if (selected) PodroidTokens.Accent else MaterialTheme.colorScheme.outline,+ color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,shape = RoundedCornerShape(PodroidTokens.Radius.Card),).padding(6.dp),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 89fd1d9..bdd8252 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@@ -92,6 +92,11 @@ class TerminalViewModel @Inject constructor(private val _showQuickSettings = kotlinx.coroutines.flow.MutableStateFlow(false)val showQuickSettings = _showQuickSettings+ // Bumped when the session dies while the VM is still Running, so the screen+ // re-creates and re-attaches a fresh session (dead-session auto-reconnect).+ private val _reconnectSignal = kotlinx.coroutines.flow.MutableStateFlow(0)+ val reconnectSignal: StateFlow<Int> = _reconnectSignal+// Quick settings helpers (non-persistent)fun openQuickSettings() { _showQuickSettings.value = true }fun closeQuickSettings() { _showQuickSettings.value = false }@@ -488,7 +493,16 @@ class TerminalViewModel @Inject constructor(viewRef?.get()?.onScreenUpdated()}override fun onTitleChanged(changedSession: TerminalSession) {}- override fun onSessionFinished(finishedSession: TerminalSession) {}+ override fun onSessionFinished(finishedSession: TerminalSession) {+ // Bridge/session died while the VM is still Running (a socket hiccup,+ // a bridge crash) — not a VM shutdown. Signal the screen to drop the+ // dead session and reconnect so the user isn't stranded on a+ // "[Process completed]" buffer. On a real VM shutdown vmState is no+ // longer Running, so we leave teardown to the normal path.+ if (vmState.value is VmState.Running) {+ _reconnectSignal.value += 1+ }+ }override fun onCopyTextToClipboard(session: TerminalSession, text: String?) {if (text == null) returnval cb = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager@@ -525,7 +539,19 @@ class TerminalViewModel @Inject constructor(}val viewClient = object : TerminalViewClient {- override fun onScale(scale: Float): Float = scale+ // Pinch-to-zoom → font size. TerminalView accumulates the gesture into+ // the scale passed here; once it crosses ±10% we bump the persisted font+ // size by one step and return 1.0f to reset the accumulator (Termux's+ // canonical pattern). Below the threshold we pass it through unchanged.+ override fun onScale(scale: Float): Float {+ if (scale < 0.9f || scale > 1.1f) {+ val step = if (scale < 1f) -1 else 1+ val next = (terminalFontSize.value + step).coerceIn(MIN_FONT_SIZE, MAX_FONT_SIZE)+ if (next != terminalFontSize.value) setTerminalFontSize(next)+ return 1.0f+ }+ return scale+ }override fun onSingleTapUp(e: MotionEvent?) {val view = viewRef?.get() ?: return// OSC 8: tap on a hyperlinked region launches the URL instead of the keyboard.@@ -558,9 +584,10 @@ class TerminalViewModel @Inject constructor(// 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)+ val appCursor = cursorKeysApplicationMode(session?.emulator)fun arrow(final: Char): ByteArray =if (mod == 1) {- if (isDecsetSet(session?.emulator, 1)) "\u001bO$final".toByteArray()+ if (cursorKeysApplicationMode(session?.emulator)) "\u001bO$final".toByteArray()else "\u001b[$final".toByteArray()} else {"\u001b[1;$mod$final".toByteArray()@@ -659,40 +686,12 @@ class TerminalViewModel @Inject constructor(session = null}- /**- * 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, typeface: Typeface = Typeface.MONOSPACE) {- 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- }- // 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 {- this.typeface = typeface- 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, charWidth.toInt(), lineHeight.toInt())- }+ // forceUpdateSizeFromView was removed deliberately: every call site was+ // replaced by view.updateSize() (whose row math subtracts+ // mFontLineSpacingAndAscent). The two disagreed by ±1 row, causing a+ // double-resize and cursor flicker on first paint and keyboard slides. Don't+ // reintroduce a paint-metrics size computation here — see the comments at the+ // TerminalView.updateSize() call sites in TerminalScreen./*** Emit xterm focus-in/out (CSI I / CSI O) when the app gains/loses focus.@@ -706,44 +705,35 @@ class TerminalViewModel @Inject constructor(fun sendFocusEvent(focused: Boolean) {val sess = session ?: returnval emu = sess.emulator ?: return- if (!isDecsetSet(emu, 1004)) return+ if (!emu.isFocusEventsEnabled) returnval seq = if (focused) "\u001b[I".toByteArray() else "\u001b[O".toByteArray()sess.write(seq, 0, seq.size)}- /**- * Check if a DECSET mode is enabled in the emulator (e.g. 1 for DECCKM,- * 1004 for focus reporting). Uses reflection to access private fields- * and mapper methods in the Termux AAR.- */- private fun isDecsetSet(emu: TerminalEmulator?, bit: Int): Boolean {- if (emu == null) return false- return try {- val cls = TerminalEmulator::class.java- val mapper = cls.getDeclaredMethod("mapDecSetBitToInternalBit", Int::class.javaPrimitiveType)- .apply { isAccessible = true }- val internalBit = mapper.invoke(null, bit) as Int- val flagsField = cls.getDeclaredField("mCurrentDecSetFlags")- .apply { isAccessible = true }- val flags = flagsField.getInt(emu)- (flags and internalBit) != 0- } catch (_: Throwable) { false }- }+ /** True when DECCKM (application cursor keys) is on, so arrows send SS3+ * (ESC O x) instead of CSI (ESC [ x). Public emulator accessor — no+ * reflection, so it keeps working under R8 in release (the private DECSET+ * field the old reflection read is not kept by proguard). */+ private fun cursorKeysApplicationMode(emu: TerminalEmulator?): Boolean =+ emu?.isCursorKeysApplicationMode == truefun sendExtraKey(key: String) {when (key) {"CTRL" -> { extraCtrl = !extraCtrl; return }"ALT" -> { extraAlt = !extraAlt; return }+ // Route through the same bracketed-paste-aware path as the long-press+ // menu / middle-click, so the extra-keys row can paste too.+ "PASTE" -> { sessionClient.onPasteTextFromClipboard(session); return }}val bytes = when (key) {"ESC" -> byteArrayOf(27)"TAB" -> byteArrayOf(9)- "UP" -> if (isDecsetSet(session?.emulator, 1)) "\u001bOA".toByteArray() else "\u001b[A".toByteArray()- "DOWN" -> if (isDecsetSet(session?.emulator, 1)) "\u001bOB".toByteArray() else "\u001b[B".toByteArray()- "LEFT" -> if (isDecsetSet(session?.emulator, 1)) "\u001bOD".toByteArray() else "\u001b[D".toByteArray()- "RIGHT"-> if (isDecsetSet(session?.emulator, 1)) "\u001bOC".toByteArray() else "\u001b[C".toByteArray()- "HOME" -> if (isDecsetSet(session?.emulator, 1)) "\u001bOH".toByteArray() else "\u001b[H".toByteArray()- "END" -> if (isDecsetSet(session?.emulator, 1)) "\u001bOF".toByteArray() else "\u001b[F".toByteArray()+ "UP" -> if (cursorKeysApplicationMode(session?.emulator)) "\u001bOA".toByteArray() else "\u001b[A".toByteArray()+ "DOWN" -> if (cursorKeysApplicationMode(session?.emulator)) "\u001bOB".toByteArray() else "\u001b[B".toByteArray()+ "LEFT" -> if (cursorKeysApplicationMode(session?.emulator)) "\u001bOD".toByteArray() else "\u001b[D".toByteArray()+ "RIGHT"-> if (cursorKeysApplicationMode(session?.emulator)) "\u001bOC".toByteArray() else "\u001b[C".toByteArray()+ "HOME" -> if (cursorKeysApplicationMode(session?.emulator)) "\u001bOH".toByteArray() else "\u001b[H".toByteArray()+ "END" -> if (cursorKeysApplicationMode(session?.emulator)) "\u001bOF".toByteArray() else "\u001b[F".toByteArray()"PGUP" -> "\u001b[5~".toByteArray()"PGDN" -> "\u001b[6~".toByteArray()"F1" -> "\u001bOP".toByteArray()@@ -780,5 +770,9 @@ class TerminalViewModel @Inject constructor(companion object {private const val TAG = "TerminalVM"+ // Pinch-to-zoom font bounds (px). Matches the practical terminal range;+ // keep in sync with the Quick Settings font slider.+ private const val MIN_FONT_SIZE = 8+ private const val MAX_FONT_SIZE = 48}}diff --git a/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java b/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.javaindex 615c9fd..fec7790 100644--- a/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java+++ b/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java@@ -706,6 +706,13 @@ public final class TerminalEmulator {return isDecsetInternalBitSet(DECSET_BIT_APPLICATION_CURSOR_KEYS);}+ /** True when the app enabled xterm focus reporting (DECSET 1004). Callers+ * must only emit CSI I / CSI O focus events when this is set, or literal+ * "^[[I" noise leaks into a shell that didn't ask for it. */+ public boolean isFocusEventsEnabled() {+ return isDecsetInternalBitSet(DECSET_BIT_SEND_FOCUS_EVENTS);+ }+/** If mouse events are being sent as escape codes to the terminal. */public boolean isMouseTrackingActive() {return isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE) || isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT);