Skip to content

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

Bump version to 1.0.3 with terminal fixes and boot progress indicator

ExTve1f1197c98f0
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 47cb501..54088c0 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -23,8 +23,8 @@ android {
applicationId = "com.excp.podroid"
minSdk = 34
targetSdk = 36
- versionCode = 3
- versionName = "1.0.2"
+ versionCode = 6
+ versionName = "1.0.3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
diff --git a/app/src/main/java/com/excp/podroid/data/repository/PortForwardRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/PortForwardRepository.kt
index 1078ea4..4c0fc3d 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/PortForwardRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/PortForwardRepository.kt
@@ -11,6 +11,7 @@ import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringSetPreferencesKey
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
@@ -71,13 +72,10 @@ class PortForwardRepository @Inject constructor(
}
}
- suspend fun getRulesSnapshot(): List<PortForwardRule> {
- var result: List<PortForwardRule> = emptyList()
- context.dataStore.edit { prefs ->
- result = prefs[KEY_PORT_FORWARDS]
+ suspend fun getRulesSnapshot(): List<PortForwardRule> =
+ context.dataStore.data.map { prefs ->
+ prefs[KEY_PORT_FORWARDS]
?.mapNotNull { PortForwardRule.deserialize(it) }
?: emptyList()
- }
- return result
- }
+ }.first()
}
diff --git a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt b/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt
index d3c6ea4..a97ab73 100644
--- a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt
+++ b/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt
@@ -2,21 +2,29 @@
* Podroid - Rootless Podman for Android
* Copyright (C) 2024 Podroid contributors
*
- * QEMU configuration for Podroid (Podman on Android).
- * Uses initrd approach with persistent overlay for Alpine Linux VM.
+ * QEMU engine for Podroid. Manages the VM lifecycle, serial console I/O,
+ * and a persistent terminal emulator that handles terminal queries (DA, DSR,
+ * window size) even when the UI is detached.
*/
package com.excp.podroid.engine
import android.content.Context
import android.util.Log
import com.excp.podroid.data.repository.PortForwardRule
+import com.termux.terminal.TerminalEmulator
+import com.termux.terminal.TerminalOutput
+import com.termux.terminal.TerminalSession
+import com.termux.terminal.TerminalSessionClient
import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
@@ -27,39 +35,55 @@ class PodroidQemu @Inject constructor(
private val _state = MutableStateFlow<VmState>(VmState.Idle)
val state: StateFlow<VmState> = _state.asStateFlow()
- /** Accumulated serial console output (for fallback / logging) */
private val _consoleText = MutableStateFlow("")
val consoleText: StateFlow<String> = _consoleText.asStateFlow()
- /** Current boot stage for UI feedback */
private val _bootStage = MutableStateFlow("")
val bootStage: StateFlow<String> = _bootStage.asStateFlow()
- var process: Process? = null
+ /** Persistent terminal emulator that outlives the UI. */
+ var terminalEmulator: TerminalEmulator? = null
private set
- /** Stream to write to VM serial console (QEMU stdin) */
- var consoleOutput: OutputStream? = null
+ @Volatile
+ var process: Process? = null
private set
- /**
- * Callback for raw console output bytes. When set, each chunk read from
- * QEMU stdout is forwarded here (used by TerminalViewModel).
- */
+ @Volatile
+ private var consoleOutputStream: OutputStream? = null
+
+ private val writeQueue = LinkedBlockingQueue<ByteArray>()
+
+ /** Current terminal dimensions for responding to size queries. */
+ @Volatile var terminalRows = 24
+ @Volatile var terminalCols = 80
+
+ /** Coroutine scope for I/O threads — cancelled on stop(). */
+ private var ioScope: CoroutineScope? = null
+
+ fun writeToConsole(data: ByteArray) {
+ writeQueue.offer(data)
+ }
+
+ fun updateTerminalSize(cols: Int, rows: Int) {
+ terminalCols = cols
+ terminalRows = rows
+ terminalEmulator?.resize(cols, rows)
+ }
+
+ /** Callback for raw console output. Used by TerminalViewModel for UI refresh. */
+ @Volatile
var onConsoleOutput: ((ByteArray, Int) -> Unit)? = null
- /** QMP client for runtime VM management */
val qmpClient: QmpClient by lazy {
QmpClient("${context.filesDir.absolutePath}/qmp.sock")
}
- fun start() {
- start(emptyList())
- }
+ fun start() = start(emptyList())
fun start(portForwards: List<PortForwardRule>, ramMb: Int = 1024, cpus: Int = 4) {
if (_state.value is VmState.Starting || _state.value is VmState.Running) {
- Log.w(TAG, "start() called while VM is in state ${_state.value}, ignoring")
+ Log.w(TAG, "start() called while VM is ${_state.value}, ignoring")
return
}
@@ -68,7 +92,6 @@ class PodroidQemu @Inject constructor(
return
}
- // Ensure storage image exists (may have been deleted by reset)
ensureStorageImage()
_state.value = VmState.Starting
@@ -81,53 +104,90 @@ class PodroidQemu @Inject constructor(
val nativeDir = context.applicationInfo.nativeLibraryDir
val filesDir = context.filesDir.absolutePath
- Log.d(TAG, "nativeDir: $nativeDir, filesDir: $filesDir")
- val pb = ProcessBuilder(cmd)
- .directory(context.filesDir)
+ val pb = ProcessBuilder(cmd).directory(context.filesDir)
pb.environment()["LD_LIBRARY_PATH"] = "$nativeDir:$filesDir"
val proc = pb.start()
process = proc
- consoleOutput = proc.outputStream
- Log.d(TAG, "Process started")
+ consoleOutputStream = proc.outputStream
_bootStage.value = "Booting kernel..."
- // Read serial console output (stdout), log to file, and forward to listeners
+ // Create coroutine scope for I/O
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ ioScope = scope
+
+ // Writer coroutine — drains writeQueue to QEMU stdin
+ scope.launch {
+ try {
+ while (isActive && process?.isAlive == true) {
+ val data = writeQueue.poll(500, TimeUnit.MILLISECONDS)
+ if (data != null) {
+ consoleOutputStream?.write(data)
+ consoleOutputStream?.flush()
+ }
+ }
+ } catch (e: Exception) {
+ Log.d(TAG, "Console writer ended: ${e.message}")
+ }
+ }
+
+ // Initialize persistent terminal emulator.
+ // write() routes emulator responses (DA, DSR, cursor position) back
+ // to the VM so TUI apps like nvim receive the answers they need.
+ val qemuOutput = object : TerminalOutput() {
+ override fun write(data: ByteArray, offset: Int, count: Int) {
+ writeToConsole(data.copyOfRange(offset, offset + count))
+ }
+ override fun titleChanged(oldTitle: String?, newTitle: String?) {}
+ override fun onCopyTextToClipboard(text: String?) {}
+ override fun onPasteTextFromClipboard() {}
+ override fun onBell() {}
+ override fun onColorsChanged() {}
+ }
+ terminalEmulator = TerminalEmulator(
+ qemuOutput, 80, 24, 2000, NoOpSessionClient
+ )
+
+ // Console reader — reads stdout, feeds emulator, detects boot stages
val logFile = File(context.filesDir, "console.log")
logFile.delete()
- Thread({
+ scope.launch {
FileOutputStream(logFile, true).use { logOut ->
val buf = ByteArray(4096)
+ val consoleBuilder = StringBuilder()
val input = proc.inputStream
try {
- while (true) {
+ while (isActive) {
val n = input.read(buf)
if (n < 0) break
val chunk = buf.copyOf(n)
- _consoleText.value += String(chunk)
+ val text = String(chunk)
+
+ consoleBuilder.append(text)
+ _consoleText.value = consoleBuilder.toString()
+
logOut.write(chunk, 0, n)
logOut.flush()
- // Detect boot stages from console output
- detectBootStage(String(chunk))
- // Forward to terminal session if attached
+
+ // Feed persistent emulator (renders screen buffer)
+ terminalEmulator?.append(chunk, n)
+
+ detectBootStage(text)
onConsoleOutput?.invoke(chunk, n)
}
} catch (e: Exception) {
Log.d(TAG, "Console reader ended: ${e.message}")
}
}
- }, "qemu-console-reader").apply {
- isDaemon = true
- start()
}
- // Drain stderr separately
- Thread({
+ // Stderr drain
+ scope.launch {
try {
val buf = ByteArray(4096)
val err = proc.errorStream
- while (true) {
+ while (isActive) {
val n = err.read(buf)
if (n < 0) break
Log.d("PodroidVM-err", String(buf, 0, n).trimEnd().take(300))
@@ -135,36 +195,29 @@ class PodroidQemu @Inject constructor(
} catch (e: Exception) {
Log.d(TAG, "Stderr drain ended: ${e.message}")
}
- }, "qemu-stderr-drain").apply {
- isDaemon = true
- start()
}
- // After a short delay, mark as running if process is still alive
+ // Wait briefly, then mark as running if alive
Thread.sleep(2000)
if (proc.isAlive) {
- Log.d(TAG, "QEMU is running!")
+ Log.d(TAG, "QEMU is running")
_state.value = VmState.Running
} else {
- Log.e(TAG, "QEMU died immediately")
val exitCode = proc.waitFor()
- Log.e(TAG, "Exit code: $exitCode")
+ Log.e(TAG, "QEMU died immediately, exit code: $exitCode")
_state.value = VmState.Error("QEMU exited with code $exitCode")
+ cleanup()
return
}
- // Wait for process to exit
val exitCode = proc.waitFor()
Log.d(TAG, "QEMU exited with code: $exitCode")
- process = null
- consoleOutput = null
-
+ cleanup()
_state.value = if (exitCode == 0) VmState.Stopped else VmState.Error("Exit code $exitCode")
} catch (e: Exception) {
Log.e(TAG, "Failed to start QEMU", e)
_state.value = VmState.Error(e.message ?: "Unknown error")
- process = null
- consoleOutput = null
+ cleanup()
}
}
@@ -182,23 +235,21 @@ class PodroidQemu @Inject constructor(
_bootStage.value = "Configuring containers..."
"Waiting for network" in text ->
_bootStage.value = "Waiting for network..."
- "Found eth0" in text || "Found" in text ->
+ "Found" in text && "eth" in text ->
_bootStage.value = "Network found"
+ "Internet:" in text ->
+ _bootStage.value = "Checking internet..."
"Podroid" in text && "Alpine" in text ->
_bootStage.value = "Almost ready..."
- "Internet: OK" in text || "Ready!" in text ->
+ "Ready!" in text ->
_bootStage.value = "Ready"
}
}
fun stop() {
- // Send sync via serial console for graceful shutdown
try {
- consoleOutput?.let { out ->
- out.write("sync\n".toByteArray())
- out.flush()
- Thread.sleep(500)
- }
+ writeToConsole("sync\n".toByteArray())
+ Thread.sleep(500)
} catch (e: Exception) {
Log.d(TAG, "Failed to send sync: ${e.message}")
}
@@ -208,28 +259,37 @@ class PodroidQemu @Inject constructor(
if (process?.isAlive == true) {
process?.destroyForcibly()
}
+ cleanup()
+ _state.value = VmState.Stopped
+ }
+
+ private fun cleanup() {
+ ioScope?.cancel()
+ ioScope = null
process = null
- consoleOutput = null
+ consoleOutputStream = null
+ writeQueue.clear()
+ terminalEmulator = null
onConsoleOutput = null
_bootStage.value = ""
- _state.value = VmState.Stopped
}
- private fun buildCommand(qemuExe: File, portForwards: List<PortForwardRule>, ramMb: Int, cpus: Int): List<String> {
+ private fun buildCommand(
+ qemuExe: File,
+ portForwards: List<PortForwardRule>,
+ ramMb: Int,
+ cpus: Int,
+ ): List<String> {
val args = mutableListOf<String>()
- // Machine & CPU
args += "-M"; args += "virt"
args += "-cpu"; args += "max"
args += "-smp"; args += "$cpus"
args += "-m"; args += "$ramMb"
args += "-accel"; args += "tcg,thread=multi"
- // Kernel & Initrd (Podroid Core)
val kernelPath = File(context.filesDir, "vmlinuz-virt")
val initrdPath = File(context.filesDir, "initrd.img")
- Log.d(TAG, "kernelPath: $kernelPath, exists: ${kernelPath.exists()}")
- Log.d(TAG, "initrdPath: $initrdPath, exists: ${initrdPath.exists()}")
if (kernelPath.exists()) {
args += "-kernel"; args += kernelPath.absolutePath
@@ -244,14 +304,12 @@ class PodroidQemu @Inject constructor(
Log.w(TAG, "Initrd not found!")
}
- // Storage (Persistent)
val storagePath = File(context.filesDir, "storage.img")
if (storagePath.exists()) {
args += "-device"; args += "virtio-blk-pci,drive=drive1"
args += "-drive"; args += "file=${storagePath.absolutePath},if=none,id=drive1,format=raw"
}
- // Network with port forwarding
val netdevArg = buildString {
append("user,id=net0")
for (rule in portForwards) {
@@ -261,17 +319,10 @@ class PodroidQemu @Inject constructor(
args += "-netdev"; args += netdevArg
args += "-device"; args += "virtio-net,netdev=net0"
- // Serial console via stdio
args += "-serial"; args += "stdio"
-
- // Display (headless)
args += "-display"; args += "none"
-
- // QMP socket for management
args += "-qmp"
args += "unix:${context.filesDir.absolutePath}/qmp.sock,server,nowait"
-
- // Misc
args += "-overcommit"; args += "mem-lock=off"
return listOf(qemuExe.absolutePath) + args
@@ -282,7 +333,7 @@ class PodroidQemu @Inject constructor(
if (!storageFile.exists()) {
try {
java.io.RandomAccessFile(storageFile, "rw").use { raf ->
- raf.setLength(2L * 1024 * 1024 * 1024) // 2GB sparse
+ raf.setLength(2L * 1024 * 1024 * 1024)
}
Log.d(TAG, "Created storage.img")
} catch (e: Exception) {
@@ -301,3 +352,23 @@ class PodroidQemu @Inject constructor(
private const val TAG = "PodroidQemu"
}
}
+
+/** No-op TerminalSessionClient for the persistent emulator (no UI attached). */
+private object NoOpSessionClient : TerminalSessionClient {
+ override fun onTextChanged(changedSession: TerminalSession) {}
+ override fun onTitleChanged(changedSession: TerminalSession) {}
+ override fun onSessionFinished(finishedSession: TerminalSession) {}
+ override fun onCopyTextToClipboard(session: TerminalSession, text: String?) {}
+ override fun onPasteTextFromClipboard(session: TerminalSession?) {}
+ override fun onBell(session: TerminalSession) {}
+ override fun onColorsChanged(session: TerminalSession) {}
+ override fun onTerminalCursorStateChange(state: Boolean) {}
+ override fun getTerminalCursorStyle(): Int = 0
+ override fun logError(tag: String?, message: String?) {}
+ override fun logWarn(tag: String?, message: String?) {}
+ override fun logInfo(tag: String?, message: String?) {}
+ override fun logDebug(tag: String?, message: String?) {}
+ override fun logVerbose(tag: String?, message: String?) {}
+ override fun logStackTraceWithMessage(tag: String?, message: String?, e: Exception?) {}
+ override fun logStackTrace(tag: String?, e: Exception?) {}
+}
diff --git a/app/src/main/java/com/excp/podroid/engine/VmState.kt b/app/src/main/java/com/excp/podroid/engine/VmState.kt
index 77e4c5d..e897512 100644
--- a/app/src/main/java/com/excp/podroid/engine/VmState.kt
+++ b/app/src/main/java/com/excp/podroid/engine/VmState.kt
@@ -35,7 +35,7 @@ sealed class VmState {
/** QEMU process is initializing. */
data object Starting : VmState()
- /** VM is running and the VNC display is available. */
+ /** VM is running and the serial console is available. */
data object Running : VmState()
/** VM execution is paused (CPU halted, state preserved). */
diff --git a/app/src/main/java/com/excp/podroid/service/PodroidService.kt b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
index af77b0b..405edfb 100644
--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt
+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
@@ -3,6 +3,7 @@
* Copyright (C) 2024 Podroid contributors
*
* Foreground service that hosts the QEMU process for Podroid.
+ * Holds a WakeLock to prevent the device from sleeping while the VM runs.
*/
package com.excp.podroid.service
@@ -14,6 +15,7 @@ import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
+import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import com.excp.podroid.MainActivity
@@ -34,6 +36,7 @@ class PodroidService : Service() {
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private var launchJob: Job? = null
+ private var wakeLock: PowerManager.WakeLock? = null
override fun onBind(intent: Intent?): IBinder? = null
@@ -46,6 +49,7 @@ class PodroidService : Service() {
when (intent?.action) {
ACTION_START -> {
startForeground(NOTIFICATION_ID, buildNotification("Starting Podman..."))
+ acquireWakeLock()
launchPodroid()
}
ACTION_STOP -> {
@@ -57,9 +61,33 @@ class PodroidService : Service() {
override fun onDestroy() {
super.onDestroy()
+ releaseWakeLock()
serviceScope.cancel()
}
+ private fun acquireWakeLock() {
+ if (wakeLock == null) {
+ val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
+ wakeLock = pm.newWakeLock(
+ PowerManager.PARTIAL_WAKE_LOCK,
+ "Podroid::VmWakeLock"
+ ).apply {
+ acquire()
+ }
+ Log.d(TAG, "WakeLock acquired")
+ }
+ }
+
+ private fun releaseWakeLock() {
+ wakeLock?.let {
+ if (it.isHeld) {
+ it.release()
+ Log.d(TAG, "WakeLock released")
+ }
+ }
+ wakeLock = null
+ }
+
private fun launchPodroid() {
launchJob?.cancel()
launchJob = serviceScope.launch {
@@ -76,6 +104,7 @@ class PodroidService : Service() {
}
}
+ releaseWakeLock()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
index 780975e..969a7da 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
@@ -51,6 +51,7 @@ fun HomeScreen(
viewModel: HomeViewModel = hiltViewModel(),
) {
val vmState by viewModel.vmState.collectAsStateWithLifecycle()
+ val bootStage by viewModel.bootStage.collectAsStateWithLifecycle()
val isRunning = vmState is VmState.Running
val isStarting = vmState is VmState.Starting
@@ -121,6 +122,15 @@ fun HomeScreen(
},
)
+ // Boot stage indicator
+ if (isStarting && bootStage.isNotEmpty()) {
+ Text(
+ text = bootStage,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+
// Start/Stop Button
Button(
onClick = {
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
index df6986b..356eef9 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
@@ -17,6 +17,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
@@ -25,10 +26,12 @@ class HomeViewModel @Inject constructor(
private val podroidQemu: PodroidQemu,
) : ViewModel() {
- /** Current QEMU lifecycle state — used to disable Start button while a VM is running. */
val vmState: StateFlow<VmState> = podroidQemu.state
.stateIn(viewModelScope, SharingStarted.Eagerly, VmState.Idle)
+ val bootStage: StateFlow<String> = podroidQemu.bootStage
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), "")
+
/** Start Podroid (the Podman VM). */
fun startPodroid() {
PodroidService.start(context)
@@ -39,12 +42,11 @@ class HomeViewModel @Inject constructor(
PodroidService.stop(context)
}
- /** Restart the VM (stop then start). */
fun restartVm() {
PodroidService.stop(context)
- // Start after a brief delay to allow stop to complete
- android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
+ viewModelScope.launch {
+ kotlinx.coroutines.delay(2000)
PodroidService.start(context)
- }, 2000)
+ }
}
}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
index d915101..a58551b 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
@@ -290,9 +290,9 @@ fun SettingsScreen(
SettingsInfoRow("Version", BuildConfig.VERSION_NAME)
SettingsInfoRow("QEMU", "10.2.1")
SettingsInfoRow("Guest", "AArch64 (ARM64)")
- SettingsInfoRow("Distro", "Alpine Linux")
- SettingsInfoRow("Container", "Podman")
- SettingsInfoRow("Storage", "Persistent (overlay)")
+ SettingsInfoRow("Distro", "Alpine Linux 3.23")
+ SettingsInfoRow("Container", "Podman + crun")
+ SettingsInfoRow("Storage", "2GB persistent (overlay)")
Spacer(Modifier.height(32.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 3812055..77e0320 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
@@ -8,9 +8,8 @@ package com.excp.podroid.ui.screens.terminal
import android.app.Activity
import android.graphics.Typeface
+import android.util.Log
import android.view.WindowManager
-import androidx.compose.animation.core.animateFloatAsState
-import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
@@ -26,6 +25,8 @@ import androidx.compose.foundation.layout.height
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
@@ -56,6 +57,7 @@ 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.termux.terminal.TerminalSession
import com.termux.view.TerminalView
@OptIn(ExperimentalMaterial3Api::class)
@@ -69,7 +71,6 @@ fun TerminalScreen(
val bootStage by viewModel.bootStage.collectAsState()
val fontSize by viewModel.terminalFontSize.collectAsState()
- // Keep screen on and adjust for soft keyboard
DisposableEffect(Unit) {
val activity = context as? Activity
activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
@@ -86,15 +87,15 @@ fun TerminalScreen(
.windowInsetsPadding(WindowInsets.navigationBars)
.windowInsetsPadding(WindowInsets.ime)
) {
- // Top bar
TopAppBar(
title = { Text("Terminal", color = Color.White) },
navigationIcon = {
IconButton(onClick = {
- // Hide keyboard before navigating back
val imm = context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)
as android.view.inputmethod.InputMethodManager
- (context as? Activity)?.currentFocus?.let { imm.hideSoftInputFromWindow(it.windowToken, 0) }
+ (context as? Activity)?.currentFocus?.let {
+ imm.hideSoftInputFromWindow(it.windowToken, 0)
+ }
onNavigateBack()
}) {
Icon(
@@ -111,41 +112,35 @@ fun TerminalScreen(
when (vmState) {
is VmState.Idle, is VmState.Stopped -> {
- // VM not running
Box(
- modifier = Modifier
- .weight(1f)
- .fillMaxWidth(),
- contentAlignment = Alignment.Center
+ modifier = Modifier.weight(1f).fillMaxWidth(),
+ contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "VM Not Running",
color = Color.Red,
fontSize = 18.sp,
- fontWeight = FontWeight.Bold
+ fontWeight = FontWeight.Bold,
)
Text(
text = "Start the VM from Home screen first",
color = Color.Gray,
fontSize = 14.sp,
- modifier = Modifier.padding(top = 8.dp)
+ modifier = Modifier.padding(top = 8.dp),
)
}
}
}
is VmState.Starting -> {
- // Loading screen with boot stage feedback
Box(
- modifier = Modifier
- .weight(1f)
- .fillMaxWidth(),
- contentAlignment = Alignment.Center
+ modifier = Modifier.weight(1f).fillMaxWidth(),
+ contentAlignment = Alignment.Center,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
- modifier = Modifier.padding(32.dp)
+ modifier = Modifier.padding(32.dp),
) {
CircularProgressIndicator(
color = Color(0xFF4FC3F7),
@@ -156,7 +151,7 @@ fun TerminalScreen(
text = "Starting VM...",
color = Color.White,
fontSize = 18.sp,
- fontWeight = FontWeight.Bold
+ fontWeight = FontWeight.Bold,
)
Spacer(modifier = Modifier.height(12.dp))
Text(
@@ -179,36 +174,31 @@ fun TerminalScreen(
is VmState.Error -> {
Box(
- modifier = Modifier
- .weight(1f)
- .fillMaxWidth(),
- contentAlignment = Alignment.Center
+ modifier = Modifier.weight(1f).fillMaxWidth(),
+ contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Error",
color = Color.Red,
fontSize = 18.sp,
- fontWeight = FontWeight.Bold
+ fontWeight = FontWeight.Bold,
)
Text(
text = (vmState as VmState.Error).message,
color = Color.Gray,
fontSize = 14.sp,
modifier = Modifier.padding(top = 8.dp, start = 16.dp, end = 16.dp),
- textAlign = TextAlign.Center
+ textAlign = TextAlign.Center,
)
}
}
}
is VmState.Paused, is VmState.Saving, is VmState.Resuming -> {
- // Treat like Starting — show progress
Box(
- modifier = Modifier
- .weight(1f)
- .fillMaxWidth(),
- contentAlignment = Alignment.Center
+ modifier = Modifier.weight(1f).fillMaxWidth(),
+ contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
CircularProgressIndicator(
@@ -232,58 +222,70 @@ fun TerminalScreen(
}
is VmState.Running -> {
- // Terminal view
- AndroidView(
- factory = { ctx ->
- TerminalView(ctx, null).apply {
- setTextSize(fontSize)
- setTypeface(Typeface.MONOSPACE)
- keepScreenOn = true
- isFocusable = true
- isFocusableInTouchMode = true
+ Box(modifier = Modifier.weight(1f).fillMaxWidth()) {
+ AndroidView(
+ factory = { ctx ->
+ TerminalView(ctx, null).apply {
+ setTextSize(fontSize)
+ setTypeface(Typeface.MONOSPACE)
+ keepScreenOn = true
+ isFocusable = true
+ isFocusableInTouchMode = true
- // Create session wired to QEMU I/O (no host binaries)
- viewModel.createSession()
- viewModel.attachView(this)
- setTerminalViewClient(viewModel.viewClient)
+ viewModel.createSession()
+ viewModel.attachView(this)
+ setTerminalViewClient(viewModel.viewClient)
- // Set session and emulator directly on the view
- val sess = viewModel.session ?: return@apply
- mTermSession = sess
- mEmulator = sess.emulator
+ val sess = viewModel.session ?: return@apply
+ mTermSession = sess
+ mEmulator = sess.emulator
- // Request focus so keyboard works
- requestFocus()
+ requestFocus()
+ post { syncTerminalSize(this, sess, viewModel) }
+ }
+ },
+ update = { view ->
+ view.setTextSize(fontSize)
+ val sess = viewModel.session
+ if (sess != null) {
+ view.post { syncTerminalSize(view, sess, viewModel) }
+ }
+ },
+ modifier = Modifier.fillMaxSize(),
+ )
- // Resize emulator to match view after layout
- post {
- if (width > 0 && height > 0 && mRenderer != null) {
- try {
- val rendererClass = mRenderer.javaClass
- val fw = rendererClass.getDeclaredField("mFontWidth").apply { isAccessible = true }.getFloat(mRenderer)
- val fls = rendererClass.getDeclaredField("mFontLineSpacing").apply { isAccessible = true }.getInt(mRenderer)
- val flsa = rendererClass.getDeclaredField("mFontLineSpacingAndAscent").apply { isAccessible = true }.getInt(mRenderer)
- val cols = (width / fw).toInt().coerceAtLeast(4)
- val rows = ((height - flsa) / fls).coerceAtLeast(4)
- sess.emulator?.resize(cols, rows)
- onScreenUpdated()
- } catch (_: Exception) {}
- }
+ // Boot progress overlay — shown while VM is still initializing
+ if (bootStage.isNotEmpty() && bootStage != "Ready") {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .align(Alignment.BottomCenter)
+ .background(Color(0xDD000000))
+ .padding(12.dp),
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.Center,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ CircularProgressIndicator(
+ color = Color(0xFF4FC3F7),
+ strokeWidth = 2.dp,
+ modifier = Modifier.size(16.dp),
+ )
+ Spacer(modifier = Modifier.width(12.dp))
+ Text(
+ text = bootStage,
+ color = Color(0xFF4FC3F7),
+ fontSize = 13.sp,
+ )
}
}
- },
- update = { view ->
- view.setTextSize(fontSize)
- view.onScreenUpdated()
- },
- modifier = Modifier
- .weight(1f)
- .fillMaxWidth(),
- )
+ }
+ }
}
}
- // Extra keys row
ExtraKeysRow(
onKey = { viewModel.sendExtraKey(it) },
ctrlActive = viewModel.extraCtrl,
@@ -292,6 +294,41 @@ fun TerminalScreen(
}
}
+private fun syncTerminalSize(
+ view: TerminalView,
+ session: TerminalSession,
+ viewModel: TerminalViewModel,
+) {
+ if (view.width <= 0 || view.height <= 0) return
+ try {
+ val renderer = view.javaClass.getDeclaredField("mRenderer")
+ .apply { isAccessible = true }.get(view) ?: return
+ val rendererClass = renderer.javaClass
+ val fw = rendererClass.getDeclaredField("mFontWidth")
+ .apply { isAccessible = true }.getFloat(renderer)
+ val fls = rendererClass.getDeclaredField("mFontLineSpacing")
+ .apply { isAccessible = true }.getInt(renderer)
+ val flsa = rendererClass.getDeclaredField("mFontLineSpacingAndAscent")
+ .apply { isAccessible = true }.getInt(renderer)
+
+ if (fw <= 0) return
+
+ val cols = (view.width / fw).toInt().coerceAtLeast(4)
+ val rows = ((view.height - flsa) / fls).coerceAtLeast(4)
+
+ if (session.emulator?.mColumns != cols || session.emulator?.mRows != rows) {
+ Log.d("TerminalScreen", "Resizing to ${cols}x${rows}")
+ session.updateSize(cols, rows)
+ viewModel.updateSize(cols, rows)
+ view.onScreenUpdated()
+ // Send stty to the VM so programs get SIGWINCH with correct size.
+ viewModel.syncSize()
+ }
+ } catch (e: Exception) {
+ Log.w("TerminalScreen", "Resize failed: ${e.message}")
+ }
+}
+
@Composable
private fun ExtraKeysRow(
onKey: (String) -> Unit,
@@ -309,11 +346,12 @@ private fun ExtraKeysRow(
) {
ExtraKey("ESC", onKey)
ExtraKey("TAB", onKey)
+ ExtraKey("SYNC", 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("\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)
@@ -322,6 +360,18 @@ private fun ExtraKeysRow(
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)
}
}
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 c4fe1b1..dc744a6 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
@@ -2,13 +2,12 @@
* Podroid - Rootless Podman for Android
* Copyright (C) 2024 Podroid contributors
*
- * No host binaries used — TerminalSession is created but its subprocess
- * is bypassed via reflection. Keyboard I/O goes to QEMU serial console.
+ * Keyboard I/O is intercepted at the View level and forwarded to QEMU.
+ * The TerminalSession's local subprocess is a benign dummy.
*/
package com.excp.podroid.ui.screens.terminal
import android.content.Context
-import android.system.Os
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
@@ -27,7 +26,6 @@ import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
-import java.io.OutputStream
import javax.inject.Inject
@HiltViewModel
@@ -44,7 +42,6 @@ class TerminalViewModel @Inject constructor(
private var terminalView: TerminalView? = null
private var emulator: TerminalEmulator? = null
- private var qemuStdin: OutputStream? = null
private var attached = false
var session: TerminalSession? = null
private set
@@ -60,22 +57,18 @@ class TerminalViewModel @Inject constructor(
override fun onSessionFinished(finishedSession: TerminalSession) {}
override fun onCopyTextToClipboard(session: TerminalSession, text: String?) {
if (text != null) {
- val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE)
+ as android.content.ClipboardManager
clipboard.setPrimaryClip(android.content.ClipData.newPlainText("Terminal", text))
}
}
override fun onPasteTextFromClipboard(session: TerminalSession?) {
- val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE)
+ as android.content.ClipboardManager
val clip = clipboard.primaryClip
if (clip != null && clip.itemCount > 0) {
val text = clip.getItemAt(0).coerceToText(context).toString()
- val bytes = text.toByteArray()
- try {
- qemuStdin?.write(bytes)
- qemuStdin?.flush()
- } catch (e: Exception) {
- Log.e(TAG, "Failed to paste", e)
- }
+ qemu.writeToConsole(text.toByteArray())
}
}
override fun onBell(session: TerminalSession) {}
@@ -109,50 +102,84 @@ class TerminalViewModel @Inject constructor(
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
override fun isTerminalViewSelected(): Boolean = true
override fun copyModeChanged(copyMode: Boolean) {}
- override fun onKeyDown(keyCode: Int, e: KeyEvent?, session: TerminalSession?): Boolean = false
- override fun onKeyUp(keyCode: Int, e: KeyEvent?): Boolean {
- // Reset Ctrl/Alt toggles after a key is processed
- if (extraCtrl || extraAlt) {
- extraCtrl = false
- extraAlt = false
+
+ override fun onKeyDown(keyCode: Int, e: KeyEvent?, session: TerminalSession?): Boolean {
+ if (e == null) return false
+
+ val bytes = when (keyCode) {
+ KeyEvent.KEYCODE_ENTER -> byteArrayOf(13) // CR — getty translates to LF
+ KeyEvent.KEYCODE_DEL -> byteArrayOf(127) // Backspace
+ KeyEvent.KEYCODE_FORWARD_DEL -> "\u001b[3~".toByteArray() // Delete key
+ KeyEvent.KEYCODE_TAB -> 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_PAGE_UP -> "\u001b[5~".toByteArray()
+ KeyEvent.KEYCODE_PAGE_DOWN -> "\u001b[6~".toByteArray()
+ KeyEvent.KEYCODE_INSERT -> "\u001b[2~".toByteArray()
+ // Function keys F1-F12
+ KeyEvent.KEYCODE_F1 -> "\u001bOP".toByteArray()
+ KeyEvent.KEYCODE_F2 -> "\u001bOQ".toByteArray()
+ KeyEvent.KEYCODE_F3 -> "\u001bOR".toByteArray()
+ KeyEvent.KEYCODE_F4 -> "\u001bOS".toByteArray()
+ KeyEvent.KEYCODE_F5 -> "\u001b[15~".toByteArray()
+ KeyEvent.KEYCODE_F6 -> "\u001b[17~".toByteArray()
+ KeyEvent.KEYCODE_F7 -> "\u001b[18~".toByteArray()
+ KeyEvent.KEYCODE_F8 -> "\u001b[19~".toByteArray()
+ KeyEvent.KEYCODE_F9 -> "\u001b[20~".toByteArray()
+ KeyEvent.KEYCODE_F10 -> "\u001b[21~".toByteArray()
+ KeyEvent.KEYCODE_F11 -> "\u001b[23~".toByteArray()
+ KeyEvent.KEYCODE_F12 -> "\u001b[24~".toByteArray()
+ else -> null
+ }
+
+ if (bytes != null) {
+ qemu.writeToConsole(bytes)
+ return true
}
return false
}
+
+ override fun onKeyUp(keyCode: Int, e: KeyEvent?): Boolean = false
+
override fun onLongPress(event: MotionEvent?): Boolean = false
override fun readControlKey(): Boolean = extraCtrl
override fun readAltKey(): Boolean = extraAlt
override fun readShiftKey(): Boolean = false
override fun readFnKey(): Boolean = false
+
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession?): Boolean {
- // If CTRL extra key is active, send the control character directly
- if (extraCtrl && codePoint in 64..127) {
- // Ctrl+A=1, Ctrl+B=2, ..., Ctrl+Z=26, etc.
- val ctrlByte = (codePoint and 0x1f).toByte()
- try {
- qemuStdin?.write(byteArrayOf(ctrlByte))
- qemuStdin?.flush()
- } catch (e: Exception) {
- Log.e(TAG, "Failed to send ctrl key", e)
- }
+ if ((ctrlDown || extraCtrl) && codePoint in 64..127) {
+ qemu.writeToConsole(byteArrayOf((codePoint and 0x1f).toByte()))
extraCtrl = false
extraAlt = false
- return true // consumed
+ return true
}
- if (extraCtrl && codePoint in 96..122) {
- // lowercase ctrl+a through ctrl+z
- val ctrlByte = (codePoint - 96).toByte()
- try {
- qemuStdin?.write(byteArrayOf(ctrlByte))
- qemuStdin?.flush()
- } catch (e: Exception) {
- Log.e(TAG, "Failed to send ctrl key", e)
- }
+ if ((ctrlDown || extraCtrl) && codePoint in 96..122) {
+ qemu.writeToConsole(byteArrayOf((codePoint - 96).toByte()))
extraCtrl = false
extraAlt = false
return true
}
- return false
+
+ val chars = Character.toChars(codePoint)
+ val charBytes = String(chars).toByteArray()
+ if (extraAlt) {
+ // Alt sends ESC prefix followed by the character
+ qemu.writeToConsole(byteArrayOf(27) + charBytes)
+ } else {
+ qemu.writeToConsole(charBytes)
+ }
+
+ extraCtrl = false
+ extraAlt = false
+ return true
}
+
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 ?: "") }
@@ -171,159 +198,59 @@ class TerminalViewModel @Inject constructor(
terminalView = view
}
- /**
- * Create a TerminalSession wired to QEMU I/O instead of a local subprocess.
- *
- * We create a real pipe fd so JNI.setPtyWindowSize() doesn't crash,
- * inject our emulator via reflection, and drain the session's keyboard
- * queue to forward input to QEMU stdin.
- */
+ fun updateSize(cols: Int, rows: Int) {
+ qemu.updateTerminalSize(cols, rows)
+ }
+
+ fun syncSize() {
+ val rows = qemu.terminalRows
+ val cols = qemu.terminalCols
+ // Send SIGWINCH to all processes on the serial TTY by updating stty.
+ // Ctrl-U clears the line first so it doesn't corrupt running apps.
+ val cmd = "\u0015stty rows $rows cols $cols\n"
+ qemu.writeToConsole(cmd.toByteArray())
+ }
+
fun createSession() {
if (attached) return
attached = true
- qemuStdin = qemu.consoleOutput
-
- // Create session — constructor just stores fields, no subprocess started
val sess = TerminalSession(
- "/dev/null",
+ "/system/bin/tail",
context.filesDir.absolutePath,
- emptyArray(),
- emptyArray(),
+ arrayOf("tail", "-f", "/dev/null"),
+ null,
2000,
sessionClient,
)
session = sess
- // Create emulator that sends keyboard output to QEMU stdin
- val qemuOutput = object : com.termux.terminal.TerminalOutput() {
- override fun write(data: ByteArray, offset: Int, count: Int) {
- try {
- val snippet = String(data, offset, count)
- Log.d(TAG, "TerminalOutput.write (${count}b): ${snippet.take(200).replace("\u001b", "ESC")}")
- qemuStdin?.let {
- it.write(data, offset, count)
- it.flush()
- }
- } catch (e: Exception) {
- Log.e(TAG, "Failed to write to QEMU", e)
- }
- }
- override fun titleChanged(oldTitle: String?, newTitle: String?) {}
- override fun onCopyTextToClipboard(text: String?) {}
- override fun onPasteTextFromClipboard() {}
- override fun onBell() {}
- override fun onColorsChanged() {}
- }
-
- val emu = TerminalEmulator(qemuOutput, 80, 24, 2000, sessionClient)
+ val emu = qemu.terminalEmulator
emulator = emu
- // Create a real pipe so JNI.setPtyWindowSize() gets a valid fd
- // (ioctl will fail with ENOTTY but won't crash)
- var pipeFd = -1
- try {
- val fds = Os.pipe()
- // Get raw int fd via reflection (FileDescriptor doesn't expose it directly)
- val fdIntField = java.io.FileDescriptor::class.java.getDeclaredField("descriptor")
- fdIntField.isAccessible = true
- pipeFd = fdIntField.getInt(fds[1])
- Os.close(fds[0]) // close read end
- } catch (e: Exception) {
- Log.w(TAG, "Failed to create pipe: ${e.message}")
+ if (emu == null) {
+ Log.e(TAG, "Cannot attach: VM terminal emulator is null")
+ return
}
- // Inject our emulator and fake pid into session via reflection
- try {
- val cls = TerminalSession::class.java
+ sess.updateSize(qemu.terminalCols, qemu.terminalRows)
- val emulatorField = cls.getDeclaredField("mEmulator")
+ // Inject persistent emulator into the session via reflection
+ try {
+ val emulatorField = TerminalSession::class.java.getDeclaredField("mEmulator")
emulatorField.isAccessible = true
emulatorField.set(sess, emu)
-
- val pidField = cls.getDeclaredField("mShellPid")
- pidField.isAccessible = true
- pidField.setInt(sess, 1)
-
- val fdField = cls.getDeclaredField("mTerminalFileDescriptor")
- fdField.isAccessible = true
- fdField.setInt(sess, pipeFd)
-
- Log.d(TAG, "Session reflection setup OK, pipeFd=$pipeFd")
+ Log.d(TAG, "Session emulator injected OK")
} catch (e: Exception) {
Log.e(TAG, "Reflection setup failed", e)
}
- // Thread to drain keyboard input from session's queue → QEMU stdin
- try {
- val queueField = TerminalSession::class.java.getDeclaredField("mTerminalToProcessIOQueue")
- queueField.isAccessible = true
- val queue = queueField.get(sess)!!
-
- val readMethod = queue.javaClass.getDeclaredMethod(
- "read", ByteArray::class.java, Boolean::class.javaPrimitiveType
- )
- readMethod.isAccessible = true
+ // Don't syncSize() here — the view hasn't been measured yet.
+ // syncTerminalSize() in TerminalScreen will detect the real dimensions
+ // and call syncSize() with the correct values after layout.
- Thread({
- val buf = ByteArray(4096)
- try {
- while (true) {
- val n = readMethod.invoke(queue, buf, true) as Int
- if (n > 0) {
- if (extraCtrl) {
- // Apply Ctrl modifier: a-z → 1-26, A-Z → 1-26
- val out = ByteArray(n)
- for (i in 0 until n) {
- val b = buf[i].toInt() and 0xFF
- out[i] = if (b in 0x40..0x7F) (b and 0x1F).toByte() else buf[i]
- }
- qemuStdin?.write(out, 0, n)
- extraCtrl = false
- extraAlt = false
- } else {
- qemuStdin?.write(buf, 0, n)
- }
- qemuStdin?.flush()
- }
- }
- } catch (e: Exception) {
- Log.d(TAG, "Keyboard→QEMU thread ended: ${e.message}")
- }
- }, "keyboard-to-qemu").apply {
- isDaemon = true
- start()
- }
- Log.d(TAG, "Keyboard→QEMU thread started")
- } catch (e: Exception) {
- Log.e(TAG, "Failed to start keyboard→QEMU thread", e)
- }
-
- // QEMU output → feed to emulator
- qemu.onConsoleOutput = { data, len ->
- // Scan for Device Attributes queries that the emulator doesn't handle
- // and inject responses so TUI apps like nvim don't hang
- val text = String(data, 0, len)
- // Primary DA: ESC[c or ESC[0c → respond as VT220
- if (text.contains("\u001b[c") || text.contains("\u001b[0c")) {
- val response = "\u001b[?62;4c" // VT220 with sixel
- try {
- qemuStdin?.write(response.toByteArray())
- qemuStdin?.flush()
- Log.d(TAG, "Injected DA1 response")
- } catch (_: Exception) {}
- }
- // Secondary DA: ESC[>c or ESC[>0c → respond with version
- if (text.contains("\u001b[>c") || text.contains("\u001b[>0c")) {
- val response = "\u001b[>0;95;0c" // xterm version 95
- try {
- qemuStdin?.write(response.toByteArray())
- qemuStdin?.flush()
- Log.d(TAG, "Injected DA2 response")
- } catch (_: Exception) {}
- }
-
- emu.append(data, len)
+ // QEMU output → trigger UI refresh
+ qemu.onConsoleOutput = { _, _ ->
terminalView?.let { view ->
view.post {
view.onScreenUpdated()
@@ -331,16 +258,13 @@ class TerminalViewModel @Inject constructor(
}
}
}
-
- // Feed buffered output
- val existing = qemu.consoleText.value
- if (existing.isNotEmpty()) {
- val bytes = existing.toByteArray()
- emu.append(bytes, bytes.size)
- }
}
fun sendExtraKey(key: String) {
+ if (key == "SYNC") {
+ syncSize()
+ return
+ }
when (key) {
"CTRL" -> { extraCtrl = !extraCtrl; return }
"ALT" -> { extraAlt = !extraAlt; return }
@@ -356,17 +280,24 @@ class TerminalViewModel @Inject constructor(
"END" -> "\u001b[F".toByteArray()
"PGUP" -> "\u001b[5~".toByteArray()
"PGDN" -> "\u001b[6~".toByteArray()
+ "F1" -> "\u001bOP".toByteArray()
+ "F2" -> "\u001bOQ".toByteArray()
+ "F3" -> "\u001bOR".toByteArray()
+ "F4" -> "\u001bOS".toByteArray()
+ "F5" -> "\u001b[15~".toByteArray()
+ "F6" -> "\u001b[17~".toByteArray()
+ "F7" -> "\u001b[18~".toByteArray()
+ "F8" -> "\u001b[19~".toByteArray()
+ "F9" -> "\u001b[20~".toByteArray()
+ "F10" -> "\u001b[21~".toByteArray()
+ "F11" -> "\u001b[23~".toByteArray()
+ "F12" -> "\u001b[24~".toByteArray()
"-" -> "-".toByteArray()
"|" -> "|".toByteArray()
"/" -> "/".toByteArray()
else -> return
}
- try {
- qemuStdin?.write(bytes)
- qemuStdin?.flush()
- } catch (e: Exception) {
- Log.e(TAG, "Failed to send extra key", e)
- }
+ qemu.writeToConsole(bytes)
extraCtrl = false
extraAlt = false
}
@@ -376,7 +307,6 @@ class TerminalViewModel @Inject constructor(
qemu.onConsoleOutput = null
emulator = null
terminalView = null
- qemuStdin = null
session = null
attached = false
}
diff --git a/init-podroid b/init-podroid
index f219a54..e0c65a1 100644
--- a/init-podroid
+++ b/init-podroid
@@ -157,14 +157,16 @@ export CONTAINERS_REGISTRIES_CONF=/etc/containers/registries.conf
# ── Console settings ──
dmesg -n 1 2>/dev/null
-stty rows 24 cols 80 2>/dev/null
+# Set a sane default size. The Android app will update it via stty
+# after the terminal view is measured, but serial TTYs start at 0x0
+# which breaks TUI apps (btop, nvim) that use TIOCGWINSZ.
+stty rows 24 cols 80 -ixon -ixoff -iexten 2>/dev/null
# ── Graceful shutdown handler ──
shutdown_handler() {
echo ""
echo "[init] Shutting down..."
sync
- # Stop all running containers gracefully
podman stop -a -t 5 2>/dev/null
sync
echo "[init] Goodbye."
@@ -194,9 +196,7 @@ echo ""
echo " Ready! Try: podman run --rm alpine echo hello"
echo ""
-# ── Shell ──
-
-# Create a profile for the login shell
+# ── Profile configuration ──
cat > /etc/profile <<'PROF'
export HOME=/root
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
@@ -208,22 +208,30 @@ export PODMAN_IGNORE_CGROUPSV1_WARNING=1
export CONTAINERS_CONF=/etc/containers/containers.conf
export CONTAINERS_STORAGE_CONF=/etc/containers/storage.conf
export CONTAINERS_REGISTRIES_CONF=/etc/containers/registries.conf
-# Auto-detect terminal size from emulator
-if command -v resize >/dev/null 2>&1; then
- eval "$(resize)" 2>/dev/null
-else
- stty rows 24 cols 80 2>/dev/null
-fi
+
+# Sane terminal settings for serial console
+# Don't hardcode rows/cols — the Android app sends stty with actual dimensions.
+stty -ixon -ixoff -iexten -echoctl 2>/dev/null
cd /root
PROF
+# ── Login wrapper ──
+# getty -n -l /bin/sh doesn't source /etc/profile.
+# This wrapper ensures the profile is always sourced (sets HOME, TERM, cd /root).
+cat > /usr/local/bin/podroid-login <<'LOGIN'
+#!/bin/sh
+. /etc/profile
+exec /bin/sh
+LOGIN
+chmod +x /usr/local/bin/podroid-login
+
# Set root shell and create passwd entry if missing
grep -q '^root:' /etc/passwd 2>/dev/null || echo "root:x:0:0:root:/root:/bin/sh" > /etc/passwd
# Use getty to spawn a proper login shell on the serial console.
# getty sets up the controlling TTY correctly, enabling job control + Ctrl+C.
while true; do
- /sbin/getty -n -l /bin/sh 0 ttyAMA0 xterm-256color
+ /sbin/getty -n -l /usr/local/bin/podroid-login 0 ttyAMA0 xterm-256color
sleep 1
done
fi