Skip to content

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

refactor: core architecture cleanup and lifecycle-aware state

ExTv3d0c6e3a3c7c
diff --git a/app/src/main/java/com/excp/podroid/MainActivity.kt b/app/src/main/java/com/excp/podroid/MainActivity.kt
index 39d0656..7864708 100644
--- a/app/src/main/java/com/excp/podroid/MainActivity.kt
+++ b/app/src/main/java/com/excp/podroid/MainActivity.kt
@@ -1,7 +1,5 @@
package com.excp.podroid
-import android.Manifest
-import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
@@ -11,45 +9,34 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass
-import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
-import androidx.core.app.ActivityCompat
-import androidx.core.content.ContextCompat
-import com.excp.podroid.data.repository.SettingsRepository
+import androidx.hilt.navigation.compose.hiltViewModel
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.excp.podroid.ui.navigation.NavGraphViewModel
import com.excp.podroid.ui.navigation.PodroidNavGraph
import com.excp.podroid.ui.theme.PodroidTheme
import dagger.hilt.android.AndroidEntryPoint
-import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
- @Inject lateinit var settingsRepository: SettingsRepository
-
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
enableEdgeToEdge()
+ super.onCreate(savedInstanceState)
setContent {
val windowSizeClass = calculateWindowSizeClass(this)
- val darkTheme by settingsRepository.darkTheme.collectAsState(initial = true)
+ val navVm: NavGraphViewModel = hiltViewModel()
+ val darkTheme by navVm.darkTheme.collectAsStateWithLifecycle(initialValue = null)
PodroidTheme(darkTheme = darkTheme) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
- PodroidNavGraph(
- settingsRepository = settingsRepository,
- windowSizeClass = windowSizeClass
- )
+ PodroidNavGraph(windowSizeClass = windowSizeClass)
}
}
}
}
-
- @Deprecated("Deprecated in Java")
- override fun onBackPressed() {
- super.onBackPressed()
- }
}
diff --git a/app/src/main/java/com/excp/podroid/PodroidApplication.kt b/app/src/main/java/com/excp/podroid/PodroidApplication.kt
index 755bb3d..93e5f00 100644
--- a/app/src/main/java/com/excp/podroid/PodroidApplication.kt
+++ b/app/src/main/java/com/excp/podroid/PodroidApplication.kt
@@ -2,19 +2,16 @@
* Podroid - Rootless Podman for Android
* Copyright (C) 2024 Podroid contributors
*
- * Application class for Podroid.
+ * Application class — extracts QEMU, kernel, and initrd assets on first run
+ * (and on app upgrade when an asset's size changes).
*/
package com.excp.podroid
import android.app.Application
+import android.util.Log
import dagger.hilt.android.HiltAndroidApp
import java.io.File
-/**
- * Application class for Podroid.
- *
- * Extracts QEMU, kernel, and initrd assets on first run.
- */
@HiltAndroidApp
class PodroidApplication : Application() {
@@ -24,34 +21,37 @@ class PodroidApplication : Application() {
}
private fun extractAssets() {
- // Extract QEMU BIOS/firmware files
copyAssetDir("qemu", filesDir)
-
- // Extract kernel and initrd
copyAssetIfNeeded("vmlinuz-virt", filesDir)
copyAssetIfNeeded("initrd.img", filesDir)
}
+ /**
+ * Copies an asset to destDir if missing or size-different.
+ * Uses openFd() for an O(1) size lookup; that throws for compressed
+ * assets, in which case we fall back to always copying.
+ */
private fun copyAssetIfNeeded(assetName: String, destDir: File) {
val destFile = File(destDir, assetName)
-
try {
- // Try to get the uncompressed asset size for a cheap up-to-date check.
- // openFd() throws for compressed entries — fall back to always copying in that case.
val assetSize = try { assets.openFd(assetName).use { it.length } } catch (_: Exception) { -1L }
if (assetSize >= 0 && destFile.exists() && destFile.length() == assetSize) return
assets.open(assetName).use { input ->
destFile.parentFile?.mkdirs()
- destFile.outputStream().use { output ->
- input.copyTo(output)
- }
+ destFile.outputStream().use { output -> input.copyTo(output) }
}
} catch (e: Exception) {
- // Asset might not exist - that's OK, we'll handle missing files at runtime
+ Log.w(TAG, "Failed to extract $assetName", e)
}
}
+ /**
+ * Walks an asset directory tree and mirrors it under destDir.
+ * Each file is copied if missing OR if its size differs (handles app
+ * upgrades that ship modified BIOS/keymap files — pre-1.1.6 this used
+ * !exists() and silently kept stale copies).
+ */
private fun copyAssetDir(assetPath: String, destDir: File) {
val entries = assets.list(assetPath) ?: return
for (entry in entries) {
@@ -62,20 +62,25 @@ class PodroidApplication : Application() {
dest.mkdirs()
copyAssetDir(src, dest)
} else {
- if (!dest.exists()) {
- try {
- assets.open(src).use { input ->
- dest.outputStream().use { output ->
- input.copyTo(output)
- }
- }
- } catch (e: Exception) {
- // Skip if asset doesn't exist
- }
- }
+ copyAssetFileIfNeeded(src, dest)
}
}
}
+ private fun copyAssetFileIfNeeded(assetPath: String, destFile: File) {
+ try {
+ val assetSize = try { assets.openFd(assetPath).use { it.length } } catch (_: Exception) { -1L }
+ if (assetSize >= 0 && destFile.exists() && destFile.length() == assetSize) return
+
+ assets.open(assetPath).use { input ->
+ destFile.outputStream().use { output -> input.copyTo(output) }
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "Failed to extract $assetPath", e)
+ }
+ }
+ companion object {
+ private const val TAG = "PodroidApp"
+ }
}
diff --git a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
index 1dcd58a..5a94ce5 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
@@ -11,8 +11,8 @@ import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
-import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
+import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
@@ -29,18 +29,20 @@ class SettingsRepository @Inject constructor(
) {
companion object {
- val KEY_DARK_THEME = booleanPreferencesKey("dark_theme")
- val KEY_VM_RAM = intPreferencesKey("vm_ram_mb")
- val KEY_VM_CPUS = intPreferencesKey("vm_cpus")
- val KEY_FONT_SIZE = intPreferencesKey("terminal_font_size")
- val KEY_STORAGE_GB = intPreferencesKey("storage_gb")
+ val KEY_DARK_THEME = booleanPreferencesKey("dark_theme")
+ val KEY_VM_RAM = intPreferencesKey("vm_ram_mb")
+ val KEY_VM_CPUS = intPreferencesKey("vm_cpus")
+ val KEY_FONT_SIZE = intPreferencesKey("terminal_font_size")
+ val KEY_STORAGE_GB = intPreferencesKey("storage_gb")
val KEY_STORAGE_ACCESS_ENABLED = booleanPreferencesKey("storage_access_enabled")
- val KEY_SETUP_DONE = booleanPreferencesKey("setup_done")
- val KEY_SSH_ENABLED = booleanPreferencesKey("ssh_enabled")
- val KEY_TERMINAL_COLOR_THEME = stringPreferencesKey("terminal_color_theme")
- val KEY_TERMINAL_FONT = stringPreferencesKey("terminal_font")
- val KEY_QEMU_EXTRA_ARGS = stringPreferencesKey("qemu_extra_args")
- val KEY_KERNEL_EXTRA_CMDLINE = stringPreferencesKey("kernel_extra_cmdline")
+ val KEY_SETUP_DONE = booleanPreferencesKey("setup_done")
+ val KEY_SSH_ENABLED = booleanPreferencesKey("ssh_enabled")
+ val KEY_TERMINAL_COLOR_THEME = stringPreferencesKey("terminal_color_theme")
+ val KEY_TERMINAL_FONT = stringPreferencesKey("terminal_font")
+ val KEY_QEMU_EXTRA_ARGS = stringPreferencesKey("qemu_extra_args")
+ val KEY_KERNEL_EXTRA_CMDLINE = stringPreferencesKey("kernel_extra_cmdline")
+ val KEY_SHOW_EXTRA_KEYS = booleanPreferencesKey("show_extra_keys")
+ val KEY_HAPTICS_ENABLED = booleanPreferencesKey("haptics_enabled")
/** Default tunable QEMU args — CPU model, accel tuning, RNG source, overcommit. */
const val DEFAULT_QEMU_EXTRA_ARGS =
@@ -54,108 +56,51 @@ class SettingsRepository @Inject constructor(
const val DEFAULT_KERNEL_EXTRA_CMDLINE = "loglevel=1 quiet mitigations=off elevator=mq-deadline"
}
- val darkTheme: Flow<Boolean> = context.dataStore.data
- .map { it[KEY_DARK_THEME] ?: true }
-
- val vmRamMb: Flow<Int> = context.dataStore.data
- .map { it[KEY_VM_RAM] ?: 512 }
-
- val vmCpus: Flow<Int> = context.dataStore.data
- .map { it[KEY_VM_CPUS] ?: 1 }
-
- val terminalFontSize: Flow<Int> = context.dataStore.data
- .map { it[KEY_FONT_SIZE] ?: 20 }
-
- val storageSizeGb: Flow<Int> = context.dataStore.data
- .map { it[KEY_STORAGE_GB] ?: 2 }
-
- val storageAccessEnabled: Flow<Boolean> = context.dataStore.data
- .map { it[KEY_STORAGE_ACCESS_ENABLED] ?: false }
-
- val isSetupDone: Flow<Boolean> = context.dataStore.data
- .map { it[KEY_SETUP_DONE] ?: false }
-
- val sshEnabled: Flow<Boolean> = context.dataStore.data
- .map { it[KEY_SSH_ENABLED] ?: false }
-
- // Terminal appearance flows
- val terminalColorTheme: Flow<String> = context.dataStore.data
- .map { it[KEY_TERMINAL_COLOR_THEME] ?: "default" }
-
- val terminalFont: Flow<String> = context.dataStore.data
- .map { it[KEY_TERMINAL_FONT] ?: "default" }
-
- val qemuExtraArgs: Flow<String> = context.dataStore.data
- .map { it[KEY_QEMU_EXTRA_ARGS] ?: DEFAULT_QEMU_EXTRA_ARGS }
-
- val kernelExtraCmdline: Flow<String> = context.dataStore.data
- .map { it[KEY_KERNEL_EXTRA_CMDLINE] ?: DEFAULT_KERNEL_EXTRA_CMDLINE }
-
- suspend fun setDarkTheme(value: Boolean) =
- context.dataStore.edit { it[KEY_DARK_THEME] = value }
-
- suspend fun setVmRamMb(value: Int) =
- context.dataStore.edit { it[KEY_VM_RAM] = value }
-
- suspend fun setVmCpus(value: Int) =
- context.dataStore.edit { it[KEY_VM_CPUS] = value }
-
- suspend fun setTerminalFontSize(value: Int) =
- context.dataStore.edit { it[KEY_FONT_SIZE] = value }
-
- suspend fun setStorageSizeGb(value: Int) =
- context.dataStore.edit { it[KEY_STORAGE_GB] = value }
-
- suspend fun setStorageAccessEnabled(value: Boolean) =
- context.dataStore.edit { it[KEY_STORAGE_ACCESS_ENABLED] = value }
-
- suspend fun markSetupDone() =
- context.dataStore.edit { it[KEY_SETUP_DONE] = true }
-
- suspend fun setSshEnabled(value: Boolean) =
- context.dataStore.edit { it[KEY_SSH_ENABLED] = value }
-
- // Terminal appearance setters
- suspend fun setTerminalColorTheme(value: String) =
- context.dataStore.edit { it[KEY_TERMINAL_COLOR_THEME] = value }
-
- suspend fun setTerminalFont(value: String) =
- context.dataStore.edit { it[KEY_TERMINAL_FONT] = value }
-
- suspend fun setQemuExtraArgs(value: String) =
- context.dataStore.edit { it[KEY_QEMU_EXTRA_ARGS] = value }
-
- suspend fun setKernelExtraCmdline(value: String) =
- context.dataStore.edit { it[KEY_KERNEL_EXTRA_CMDLINE] = value }
-
- suspend fun getSshEnabledSnapshot(): Boolean =
- context.dataStore.data.map { it[KEY_SSH_ENABLED] ?: false }.first()
-
- suspend fun getVmRamMbSnapshot(): Int =
- context.dataStore.data.map { it[KEY_VM_RAM] ?: 512 }.first()
-
- suspend fun getVmCpusSnapshot(): Int =
- context.dataStore.data.map { it[KEY_VM_CPUS] ?: 1 }.first()
-
- suspend fun getStorageSizeGbSnapshot(): Int =
- context.dataStore.data.map { it[KEY_STORAGE_GB] ?: 2 }.first()
-
- suspend fun getStorageAccessEnabledSnapshot(): Boolean =
- context.dataStore.data.map { it[KEY_STORAGE_ACCESS_ENABLED] ?: false }.first()
-
- suspend fun isSetupDoneSnapshot(): Boolean =
- context.dataStore.data.map { it[KEY_SETUP_DONE] ?: false }.first()
-
- // Terminal appearance snapshots
- suspend fun getTerminalColorThemeSnapshot(): String =
- context.dataStore.data.map { it[KEY_TERMINAL_COLOR_THEME] ?: "default" }.first()
-
- suspend fun getTerminalFontSnapshot(): String =
- context.dataStore.data.map { it[KEY_TERMINAL_FONT] ?: "default" }.first()
-
- suspend fun getQemuExtraArgsSnapshot(): String =
- context.dataStore.data.map { it[KEY_QEMU_EXTRA_ARGS] ?: DEFAULT_QEMU_EXTRA_ARGS }.first()
-
- suspend fun getKernelExtraCmdlineSnapshot(): String =
- context.dataStore.data.map { it[KEY_KERNEL_EXTRA_CMDLINE] ?: DEFAULT_KERNEL_EXTRA_CMDLINE }.first()
+ private fun <T> pref(key: Preferences.Key<T>, default: T): Flow<T> =
+ context.dataStore.data.map { it[key] ?: default }
+
+ private suspend fun <T> set(key: Preferences.Key<T>, value: T) =
+ context.dataStore.edit { it[key] = value }
+
+ val darkTheme = pref(KEY_DARK_THEME, true)
+ val vmRamMb = pref(KEY_VM_RAM, 512)
+ val vmCpus = pref(KEY_VM_CPUS, 1)
+ val terminalFontSize = pref(KEY_FONT_SIZE, 20)
+ val storageSizeGb = pref(KEY_STORAGE_GB, 2)
+ val storageAccessEnabled = pref(KEY_STORAGE_ACCESS_ENABLED, false)
+ val isSetupDone = pref(KEY_SETUP_DONE, false)
+ val sshEnabled = pref(KEY_SSH_ENABLED, false)
+ val terminalColorTheme = pref(KEY_TERMINAL_COLOR_THEME, "default")
+ val terminalFont = pref(KEY_TERMINAL_FONT, "default")
+ val qemuExtraArgs = pref(KEY_QEMU_EXTRA_ARGS, DEFAULT_QEMU_EXTRA_ARGS)
+ val kernelExtraCmdline = pref(KEY_KERNEL_EXTRA_CMDLINE, DEFAULT_KERNEL_EXTRA_CMDLINE)
+ val showExtraKeys = pref(KEY_SHOW_EXTRA_KEYS, true)
+ val hapticsEnabled = pref(KEY_HAPTICS_ENABLED, true)
+
+ suspend fun setDarkTheme(value: Boolean) = set(KEY_DARK_THEME, value)
+ suspend fun setVmRamMb(value: Int) = set(KEY_VM_RAM, value)
+ suspend fun setVmCpus(value: Int) = set(KEY_VM_CPUS, value)
+ suspend fun setTerminalFontSize(value: Int) = set(KEY_FONT_SIZE, value)
+ suspend fun setStorageSizeGb(value: Int) = set(KEY_STORAGE_GB, value)
+ suspend fun setStorageAccessEnabled(value: Boolean) = set(KEY_STORAGE_ACCESS_ENABLED, value)
+ suspend fun markSetupDone() = set(KEY_SETUP_DONE, true)
+ suspend fun setSshEnabled(value: Boolean) = set(KEY_SSH_ENABLED, value)
+ suspend fun setTerminalColorTheme(value: String) = set(KEY_TERMINAL_COLOR_THEME, value)
+ suspend fun setTerminalFont(value: String) = set(KEY_TERMINAL_FONT, value)
+ suspend fun setQemuExtraArgs(value: String) = set(KEY_QEMU_EXTRA_ARGS, value)
+ suspend fun setKernelExtraCmdline(value: String) = set(KEY_KERNEL_EXTRA_CMDLINE, value)
+ suspend fun setShowExtraKeys(value: Boolean) = set(KEY_SHOW_EXTRA_KEYS, value)
+ suspend fun setHapticsEnabled(value: Boolean) = set(KEY_HAPTICS_ENABLED, value)
+
+ // Snapshots used by non-Compose call sites (PodroidService, exporters).
+ suspend fun getSshEnabledSnapshot() = sshEnabled.first()
+ suspend fun getVmRamMbSnapshot() = vmRamMb.first()
+ suspend fun getVmCpusSnapshot() = vmCpus.first()
+ suspend fun getStorageSizeGbSnapshot() = storageSizeGb.first()
+ suspend fun getStorageAccessEnabledSnapshot() = storageAccessEnabled.first()
+ suspend fun isSetupDoneSnapshot() = isSetupDone.first()
+ suspend fun getTerminalColorThemeSnapshot() = terminalColorTheme.first()
+ suspend fun getTerminalFontSnapshot() = terminalFont.first()
+ suspend fun getQemuExtraArgsSnapshot() = qemuExtraArgs.first()
+ suspend fun getKernelExtraCmdlineSnapshot() = kernelExtraCmdline.first()
}
diff --git a/app/src/main/java/com/excp/podroid/data/repository/UpdateRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/UpdateRepository.kt
index c7be87b..8ec4166 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/UpdateRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/UpdateRepository.kt
@@ -67,10 +67,16 @@ class UpdateRepository @Inject constructor(
context.dataStore.edit { it[dismissedKey] = version }
}
- /** Returns true if `latest` is a higher version than `current`. */
+ /**
+ * Returns true if `latest` is a higher version than `current`. Compares the
+ * numeric core (`1.2.3`) first; if those are equal, treats a prerelease
+ * suffix (`-rc2`) as lower than a release, and falls back to lexicographic
+ * comparison of the suffixes themselves so 1.2.0-rc2 > 1.2.0-rc1.
+ */
private fun isNewer(latest: String, current: String): Boolean {
- val l = latest.substringBefore("-").split(".").map { it.toIntOrNull() ?: 0 }
- val c = current.substringBefore("-").split(".").map { it.toIntOrNull() ?: 0 }
+ fun split(v: String) = v.substringBefore("-").split(".").map { it.toIntOrNull() ?: 0 }
+ val l = split(latest)
+ val c = split(current)
val maxLen = maxOf(l.size, c.size)
for (i in 0 until maxLen) {
val lv = l.getOrElse(i) { 0 }
@@ -78,6 +84,14 @@ class UpdateRepository @Inject constructor(
if (lv > cv) return true
if (lv < cv) return false
}
- return false
+ // Numeric cores match — break ties by suffix. Empty suffix > any prerelease suffix.
+ val ls = latest.substringAfter("-", "")
+ val cs = current.substringAfter("-", "")
+ return when {
+ ls == cs -> false
+ ls.isEmpty() -> true // "1.2.0" is newer than "1.2.0-rc1"
+ cs.isEmpty() -> false // "1.2.0-rc1" is older than "1.2.0"
+ else -> ls > cs // lexicographic compare for ordered prereleases
+ }
}
}
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 d8466a7..2d9b997 100644
--- a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt
+++ b/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt
@@ -30,6 +30,7 @@ import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.util.Log
import com.excp.podroid.data.repository.PortForwardRule
+import com.excp.podroid.util.LogProxy
import com.termux.terminal.TerminalSession
import com.termux.terminal.TerminalSessionClient
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -39,7 +40,11 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
import java.io.FileOutputStream
+import java.nio.ByteBuffer
+import java.nio.CharBuffer
+import java.nio.charset.CodingErrorAction
import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import javax.inject.Singleton
@@ -47,7 +52,6 @@ import javax.inject.Singleton
@Singleton
class PodroidQemu @Inject constructor(
@ApplicationContext private val context: Context,
- private val settingsRepository: com.excp.podroid.data.repository.SettingsRepository,
) {
private val _state = MutableStateFlow<VmState>(VmState.Idle)
val state: StateFlow<VmState> = _state.asStateFlow()
@@ -58,10 +62,8 @@ class PodroidQemu @Inject constructor(
private val _bootStage = MutableStateFlow("")
private var _terminalSession: TerminalSession? = null
- private var _terminalSessionAttached = false
val terminalSession: TerminalSession? get() = _terminalSession
- val terminalSessionAttached: Boolean get() = _terminalSessionAttached
val bootStage: StateFlow<String> = _bootStage.asStateFlow()
@Volatile
@@ -86,6 +88,9 @@ class PodroidQemu @Inject constructor(
private val consoleBuilder = StringBuilder()
private val maxConsoleSize = 64 * 1024
+ /** Set once cleanup() has run for the current VM lifetime; reset by start(). */
+ private val cleanedUp = AtomicBoolean(true)
+
/**
* Proxy TerminalSessionClient — delegates to whatever real client is set.
* Lets us create the bridge session at boot-complete time (before the
@@ -104,13 +109,14 @@ class PodroidQemu @Inject constructor(
override fun onColorsChanged(s: TerminalSession) { sessionClientDelegate?.onColorsChanged(s) }
override fun onTerminalCursorStateChange(state: Boolean) { sessionClientDelegate?.onTerminalCursorStateChange(state) }
override fun getTerminalCursorStyle(): Int = sessionClientDelegate?.terminalCursorStyle ?: 0
- override fun logError(tag: String?, msg: String?) { Log.e(tag ?: TAG, msg ?: "") }
- override fun logWarn(tag: String?, msg: String?) { Log.w(tag ?: TAG, msg ?: "") }
- override fun logInfo(tag: String?, msg: String?) { Log.i(tag ?: TAG, msg ?: "") }
- override fun logDebug(tag: String?, msg: String?) { Log.d(tag ?: TAG, msg ?: "") }
- override fun logVerbose(tag: String?, msg: String?) { Log.v(tag ?: TAG, msg ?: "") }
- override fun logStackTraceWithMessage(tag: String?, msg: String?, e: Exception?) { Log.e(tag ?: TAG, msg, e) }
- override fun logStackTrace(tag: String?, e: Exception?) { Log.e(tag ?: TAG, "Stack trace", e) }
+ override fun logError(tag: String?, msg: String?) = LogProxy.error(tag, TAG, msg)
+ override fun logWarn(tag: String?, msg: String?) = LogProxy.warn(tag, TAG, msg)
+ override fun logInfo(tag: String?, msg: String?) = LogProxy.info(tag, TAG, msg)
+ override fun logDebug(tag: String?, msg: String?) = LogProxy.debug(tag, TAG, msg)
+ override fun logVerbose(tag: String?, msg: String?) = LogProxy.verbose(tag, TAG, msg)
+ override fun logStackTraceWithMessage(tag: String?, msg: String?, e: Exception?) =
+ LogProxy.stackTraceWithMessage(tag, TAG, msg, e)
+ override fun logStackTrace(tag: String?, e: Exception?) = LogProxy.stackTrace(tag, TAG, e)
}
/**
@@ -152,7 +158,6 @@ class PodroidQemu @Inject constructor(
)
sess.updateSize(80, 24)
_terminalSession = sess
- _terminalSessionAttached = false
Log.d(TAG, "Bridge auto-started on terminal.sock")
}
}
@@ -162,7 +167,6 @@ class PodroidQemu @Inject constructor(
// Session already auto-started during boot — just return it
if (_terminalSession != null) {
- _terminalSessionAttached = true
Log.d(TAG, "Returning pre-started terminal session")
return _terminalSession!!
}
@@ -185,24 +189,33 @@ class PodroidQemu @Inject constructor(
sess.updateSize(80, 24)
_terminalSession = sess
- _terminalSessionAttached = true
Log.d(TAG, "Terminal session created in Qemu singleton")
return sess
}
- fun attachTerminalView() {
- _terminalSessionAttached = true
- }
-
fun start() = start(emptyList())
+ /** All snapshotted settings the engine needs for a single VM launch. */
+ data class LaunchConfig(
+ val ramMb: Int = 512,
+ val cpus: Int = 1,
+ val sshEnabled: Boolean = false,
+ val androidIp: String = "unknown",
+ val storageSizeGb: Int = 2,
+ val storageAccessEnabled: Boolean = false,
+ val qemuExtraArgs: String = "",
+ val kernelExtraCmdline: String = "",
+ )
+
fun start(
portForwards: List<PortForwardRule>,
ramMb: Int = 512,
cpus: Int = 1,
sshEnabled: Boolean = false,
androidIp: String = "unknown",
- ) {
+ ) = start(portForwards, LaunchConfig(ramMb = ramMb, cpus = cpus, sshEnabled = sshEnabled, androidIp = androidIp))
+
+ fun start(portForwards: List<PortForwardRule>, config: LaunchConfig) {
if (_state.value is VmState.Starting || _state.value is VmState.Running) {
Log.w(TAG, "start() called while VM is ${_state.value}, ignoring")
return
@@ -213,8 +226,9 @@ class PodroidQemu @Inject constructor(
return
}
- ensureStorageImage()
+ ensureStorageImage(config.storageSizeGb)
+ cleanedUp.set(false)
_state.value = VmState.Starting
consoleBuilder.clear()
_consoleText.value = ""
@@ -229,8 +243,8 @@ class PodroidQemu @Inject constructor(
File(qmpSocketPath).delete()
try {
- val cmd = buildCommand(qemuExe, portForwards, ramMb, cpus, sshEnabled, androidIp)
- Log.d(TAG, "Launching: ${cmd.joinToString(" ")}")
+ val cmd = buildCommand(qemuExe, portForwards, config)
+ Log.d(TAG, "Launching QEMU with ${cmd.size} args: $cmd")
val nativeDir = context.applicationInfo.nativeLibraryDir
val pb = ProcessBuilder(cmd).directory(context.filesDir)
@@ -261,9 +275,8 @@ class PodroidQemu @Inject constructor(
scope.launch { monitorBootSerial(proc) }
val startMs = System.currentTimeMillis()
- val timeoutMs = 10_000L
var socketsReady = false
- while (System.currentTimeMillis() - startMs < timeoutMs) {
+ while (System.currentTimeMillis() - startMs < SOCKET_READY_TIMEOUT_MS) {
if (!proc.isAlive) {
val exitCode = proc.exitValue()
Log.e(TAG, "QEMU died during startup, exit code: $exitCode")
@@ -279,9 +292,9 @@ class PodroidQemu @Inject constructor(
Thread.sleep(200)
}
if (!socketsReady) {
- Log.e(TAG, "Socket timeout — QEMU sockets not ready after ${timeoutMs}ms")
+ Log.e(TAG, "Socket timeout — QEMU sockets not ready after ${SOCKET_READY_TIMEOUT_MS}ms")
proc.destroyForcibly()
- throw RuntimeException("QEMU failed to create sockets within ${timeoutMs / 1000}s")
+ throw RuntimeException("QEMU failed to create sockets within ${SOCKET_READY_TIMEOUT_MS / 1000}s")
}
// State stays Starting — boot monitor will set Running when "Ready!" is detected
@@ -299,7 +312,8 @@ class PodroidQemu @Inject constructor(
val exitCode = proc.waitFor()
Log.d(TAG, "QEMU exited: $exitCode")
cleanup()
- _state.value = if (exitCode == 0) VmState.Stopped else VmState.Error("Exit code $exitCode")
+ _state.value = if (exitCode == 0) VmState.Stopped
+ else VmState.Error(formatExitError(exitCode, config.storageAccessEnabled))
} catch (e: Exception) {
Log.e(TAG, "Failed to start QEMU", e)
_state.value = VmState.Error(e.message ?: "Unknown error")
@@ -322,9 +336,10 @@ class PodroidQemu @Inject constructor(
private suspend fun monitorBootSerial(proc: Process) {
val sockFile = File(serialSockPath)
- // Wait up to 8s for QEMU to create the socket
- var waited = 0
- while (waited < 8000 && !sockFile.exists() && proc.isAlive) {
+ // Share the same socket-readiness deadline used by start() so a slow
+ // QEMU startup doesn't get inconsistent grace periods.
+ var waited = 0L
+ while (waited < SOCKET_READY_TIMEOUT_MS && !sockFile.exists() && proc.isAlive) {
delay(100)
waited += 100
}
@@ -347,29 +362,46 @@ class PodroidQemu @Inject constructor(
val logFile = File(context.filesDir, "console.log")
logFile.delete()
+ // Streaming UTF-8 decoder — kept across read() calls so multi-byte
+ // sequences split between chunks decode correctly instead of
+ // surfacing as U+FFFD replacement chars in the in-memory console
+ // and breaking detectBootStage() matches.
+ val decoder = Charsets.UTF_8.newDecoder()
+ .onMalformedInput(CodingErrorAction.REPLACE)
+ .onUnmappableCharacter(CodingErrorAction.REPLACE)
+ val byteBuf = ByteBuffer.allocate(8192)
+ val charBuf = CharBuffer.allocate(8192)
+
try {
FileOutputStream(logFile, false).use { logOut ->
- val buf = ByteArray(4096)
+ val readBuf = ByteArray(4096)
val input = sock.inputStream
while (true) {
val n = try {
- input.read(buf)
+ input.read(readBuf)
} catch (_: Exception) {
break // socket closed by releaseSerial() or VM exit
}
if (n < 0) break
- val chunk = buf.copyOf(n)
- val text = String(chunk, Charsets.UTF_8)
+ // Raw bytes go straight to disk for the diagnostic log.
+ logOut.write(readBuf, 0, n)
+ logOut.flush()
- consoleBuilder.append(text)
- if (consoleBuilder.length > maxConsoleSize) {
- consoleBuilder.delete(0, consoleBuilder.length - maxConsoleSize)
+ // Feed the decoder; carry leftover undecoded bytes via compact().
+ byteBuf.put(readBuf, 0, n)
+ byteBuf.flip()
+ decoder.decode(byteBuf, charBuf, false)
+ byteBuf.compact()
+ charBuf.flip()
+ if (charBuf.hasRemaining()) {
+ consoleBuilder.append(charBuf)
+ if (consoleBuilder.length > maxConsoleSize) {
+ consoleBuilder.delete(0, consoleBuilder.length - maxConsoleSize)
+ }
+ _consoleText.value = consoleBuilder.toString()
}
- _consoleText.value = consoleBuilder.toString()
-
- logOut.write(chunk, 0, n)
- logOut.flush()
+ charBuf.clear()
if (_bootStage.value != "Ready") {
detectBootStage()
@@ -409,32 +441,34 @@ class PodroidQemu @Inject constructor(
}
}
+ /**
+ * Signal the VM to stop. Destroys the QEMU process; the start() coroutine's
+ * proc.waitFor() will fall through and run cleanup() + set the final state.
+ * Avoids the historical race where stop() and the start() exit-path both
+ * called cleanup() concurrently and fought over _state.value.
+ */
fun stop() {
- val proc = process
- if (proc != null) {
- proc.destroy()
- try {
- val exited = proc.waitFor(3, TimeUnit.SECONDS)
- if (!exited) {
- proc.destroyForcibly()
- proc.waitFor(2, TimeUnit.SECONDS)
- }
- } catch (_: Exception) {
+ val proc = process ?: return
+ proc.destroy()
+ try {
+ if (!proc.waitFor(3, TimeUnit.SECONDS)) {
proc.destroyForcibly()
+ proc.waitFor(2, TimeUnit.SECONDS)
}
+ } catch (_: Exception) {
+ proc.destroyForcibly()
}
- cleanup()
- _state.value = VmState.Stopped
}
+ @Synchronized
private fun cleanup() {
+ if (cleanedUp.getAndSet(true)) return
releaseSerial()
ioScope?.cancel()
ioScope = null
process = null
_terminalSession?.finishIfRunning()
_terminalSession = null
- _terminalSessionAttached = false
sessionClientDelegate = null
consoleBuilder.clear()
_consoleText.value = ""
@@ -447,25 +481,15 @@ class PodroidQemu @Inject constructor(
private fun buildCommand(
qemuExe: File,
portForwards: List<PortForwardRule>,
- ramMb: Int,
- cpus: Int,
- sshEnabled: Boolean,
- androidIp: String,
+ config: LaunchConfig,
): List<String> {
val args = mutableListOf<String>()
-
- // User-tunable extras (CPU model, accel tuning, RNG, overcommit, kernel cmdline extras).
- // Pulled from SettingsRepository; falls back to the documented defaults.
- val userQemuExtras = kotlinx.coroutines.runBlocking {
- settingsRepository.getQemuExtraArgsSnapshot()
- }.trim()
- val userKernelExtras = kotlinx.coroutines.runBlocking {
- settingsRepository.getKernelExtraCmdlineSnapshot()
- }.trim()
+ val userQemuExtras = config.qemuExtraArgs.trim()
+ val userKernelExtras = config.kernelExtraCmdline.trim()
args += "-M"; args += "virt,gic-version=3"
- args += "-smp"; args += "$cpus"
- args += "-m"; args += "$ramMb"
+ args += "-smp"; args += "${config.cpus}"
+ args += "-m"; args += "${config.ramMb}"
val kernelPath = File(context.filesDir, "vmlinuz-virt")
val initrdPath = File(context.filesDir, "initrd.img")
@@ -475,8 +499,8 @@ class PodroidQemu @Inject constructor(
val cmdline = buildString {
append("console=ttyAMA0")
if (userKernelExtras.isNotEmpty()) append(" ").append(userKernelExtras)
- append(" androidip=$androidIp")
- if (sshEnabled) append(" ssh=1")
+ append(" androidip=").append(config.androidIp)
+ if (config.sshEnabled) append(" ssh=1")
}
args += "-append"; args += cmdline
} else {
@@ -492,7 +516,7 @@ class PodroidQemu @Inject constructor(
val storagePath = File(context.filesDir, "storage.img")
if (storagePath.exists()) {
args += "-object"; args += "iothread,id=iothread0"
- args += "-device"; args += "virtio-blk-pci,drive=drive1,num-queues=$cpus,iothread=iothread0"
+ args += "-device"; args += "virtio-blk-pci,drive=drive1,num-queues=${config.cpus},iothread=iothread0"
args += "-drive"; args += "file=${storagePath.absolutePath},if=none,id=drive1,format=raw,cache=writeback,aio=threads"
}
@@ -500,15 +524,17 @@ class PodroidQemu @Inject constructor(
val downloadsDir = android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS
)
- val storageAccessEnabled = kotlinx.coroutines.runBlocking {
- settingsRepository.getStorageAccessEnabledSnapshot()
- }
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R &&
- storageAccessEnabled &&
+ config.storageAccessEnabled &&
android.os.Environment.isExternalStorageManager() &&
downloadsDir.exists()) {
+ // security_model=mapped-xattr keeps QEMU's 9p worker out of the
+ // chmod/chown syscall path that has triggered SIGILL on Tensor /
+ // ARMv9.2 PAC devices (Pixel 10) — uid/gid/mode are stored as
+ // xattrs on the host file instead of being applied directly.
+ // Falls back gracefully on filesystems without xattr support.
args += "-fsdev"
- args += "local,id=fsdev0,path=${downloadsDir.absolutePath},security_model=none"
+ args += "local,id=fsdev0,path=${downloadsDir.absolutePath},security_model=mapped-xattr"
args += "-device"
args += "virtio-9p-pci,fsdev=fsdev0,mount_tag=downloads"
}
@@ -537,8 +563,7 @@ class PodroidQemu @Inject constructor(
args += "-display"; args += "none"
args += "-qmp"; args += "unix:$qmpSocketPath,server,nowait"
- // User extras appended last so they can override earlier args where
- // QEMU allows it (later -cpu / -accel overrides earlier ones).
+ // User extras appended last so later -cpu / -accel overrides earlier ones.
if (userQemuExtras.isNotEmpty()) {
args += userQemuExtras.split(Regex("\\s+"))
}
@@ -546,12 +571,9 @@ class PodroidQemu @Inject constructor(
return listOf(qemuExe.absolutePath) + args
}
- private fun ensureStorageImage() {
+ private fun ensureStorageImage(storageSizeGb: Int) {
val storageFile = File(context.filesDir, "storage.img")
- val gb = kotlinx.coroutines.runBlocking {
- settingsRepository.getStorageSizeGbSnapshot().toLong()
- }
- val desiredBytes = gb * 1024L * 1024L * 1024L
+ val desiredBytes = storageSizeGb.toLong() * 1024L * 1024L * 1024L
if (storageFile.exists()) {
if (storageFile.length() == desiredBytes) return
@@ -561,7 +583,7 @@ class PodroidQemu @Inject constructor(
try {
java.io.RandomAccessFile(storageFile, "rw").use { it.setLength(desiredBytes) }
- Log.d(TAG, "Created storage.img (${gb}GB)")
+ Log.d(TAG, "Created storage.img (${storageSizeGb}GB)")
} catch (e: Exception) {
Log.e(TAG, "Failed to create storage.img", e)
}
@@ -572,7 +594,41 @@ class PodroidQemu @Inject constructor(
return if (exe.exists()) exe else null
}
+ /**
+ * Decode a QEMU process exit code into a user-facing error string. Process
+ * exit codes ≥128 are POSIX-encoded signals (128 + signum). On some devices
+ * (notably Tensor / ARMv9.2 PAC) virtio-9p crashes the QEMU worker with
+ * SIGILL — surface that as a Downloads-sharing hint rather than "Exit 132".
+ */
+ private fun formatExitError(exitCode: Int, storageSharingEnabled: Boolean): String {
+ if (exitCode < 128) return "QEMU exited with code $exitCode"
+ val sig = exitCode - 128
+ val name = when (sig) {
+ 4 -> "SIGILL"
+ 6 -> "SIGABRT"
+ 7 -> "SIGBUS"
+ 8 -> "SIGFPE"
+ 9 -> "SIGKILL"
+ 11 -> "SIGSEGV"
+ 13 -> "SIGPIPE"
+ 15 -> "SIGTERM"
+ 31 -> "SIGSYS"
+ else -> "signal $sig"
+ }
+ // SIGILL/SIGBUS/SIGSEGV with Downloads sharing on points at virtio-9p
+ // on PAC-enforcing kernels — by far the most common crash path here.
+ val crashSignals = setOf(4, 7, 11)
+ return if (storageSharingEnabled && sig in crashSignals) {
+ "QEMU crashed ($name). Downloads sharing is unstable on this device — disable it in Settings and try again."
+ } else {
+ "QEMU crashed ($name)"
+ }
+ }
+
companion object {
private const val TAG = "PodroidQemu"
+
+ /** Shared deadline for both start()'s socket-readiness loop and monitorBootSerial's wait. */
+ private const val SOCKET_READY_TIMEOUT_MS = 10_000L
}
}
diff --git a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt b/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
index 1eaedc5..63bc79e 100644
--- a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
@@ -36,15 +36,15 @@ class QmpClient(private val socketPath: String) {
val reader = BufferedReader(InputStreamReader(socket.inputStream))
val writer = OutputStreamWriter(socket.outputStream)
- // Read QMP greeting
+ // Read QMP greeting (verbose-only: noisy and uninteresting on every command)
val greeting = reader.readLine()
- Log.d(TAG, "QMP greeting: $greeting")
+ Log.v(TAG, "QMP greeting: $greeting")
// Send qmp_capabilities to enter command mode
writer.write("{\"execute\":\"qmp_capabilities\"}\n")
writer.flush()
val capResponse = reader.readLine()
- Log.d(TAG, "Capabilities response: $capResponse")
+ Log.v(TAG, "Capabilities response: $capResponse")
// Send the actual command
val cmd = JSONObject().apply {
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 e897512..598c9a8 100644
--- a/app/src/main/java/com/excp/podroid/engine/VmState.kt
+++ b/app/src/main/java/com/excp/podroid/engine/VmState.kt
@@ -10,50 +10,19 @@
package com.excp.podroid.engine
/**
- * Lifecycle state of a running (or stopped) virtual machine.
- *
- * State transitions:
+ * Lifecycle state of the QEMU VM.
*
* ```
- * Idle ──► Starting ──► Running ──► Paused
- * │ │
- * ▼ ▼
- * Saving Resuming ──► Running
- * │
- * ▼
- * Stopped ──► Idle
- * │
- * ▼
- * Error
+ * Idle ──► Starting ──► Running
+ * ▲ │
+ * │ ▼
+ * Error Stopped
* ```
*/
sealed class VmState {
-
- /** No VM is active. */
- data object Idle : VmState()
-
- /** QEMU process is initializing. */
+ data object Idle : VmState()
data object Starting : VmState()
-
- /** VM is running and the serial console is available. */
- data object Running : VmState()
-
- /** VM execution is paused (CPU halted, state preserved). */
- data object Paused : VmState()
-
- /** Saving VM state to disk via QEMU migration. */
- data object Saving : VmState()
-
- /** Restoring VM from a saved state snapshot. */
- data object Resuming : VmState()
-
- /** QEMU process has exited cleanly. */
- data object Stopped : VmState()
-
- /**
- * An error occurred.
- *
- * @param message Human-readable description of what went wrong.
- */
- data class Error(val message: String) : VmState()
+ data object Running : VmState()
+ data object Stopped : VmState()
+ data class Error(val message: String) : VmState()
}
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 5bb27f5..5162795 100644
--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt
+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
@@ -28,8 +28,10 @@ import com.excp.podroid.data.repository.PortForwardRepository
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.engine.PodroidQemu
import com.excp.podroid.engine.VmState
+import com.excp.podroid.util.NetworkUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.combine
import javax.inject.Inject
@AndroidEntryPoint
@@ -121,55 +123,42 @@ class PodroidService : Service() {
private fun startNotificationUpdates() {
notificationJob?.cancel()
notificationJob = serviceScope.launch {
- launch {
- podroidQemu.state.collect { state ->
- when (state) {
- is VmState.Running -> updateNotification("VM is running")
- is VmState.Starting -> {
- val stage = podroidQemu.bootStage.value
- updateNotification(stage.ifEmpty { "Starting VM..." })
- }
- is VmState.Stopped, is VmState.Idle, is VmState.Error -> return@collect
- else -> {}
- }
- }
- }
- launch {
- podroidQemu.bootStage.collect { stage ->
- if (podroidQemu.state.value is VmState.Starting && stage.isNotEmpty()) {
- updateNotification(stage)
- }
+ launch { observeStateForNotification() }
+ launch { observeStateForShutdown() }
+ }
+ }
+
+ /** Updates the notification text from a combined view of state + bootStage. */
+ private suspend fun observeStateForNotification() {
+ combine(podroidQemu.state, podroidQemu.bootStage) { state, stage -> state to stage }
+ .collect { (state, stage) ->
+ when (state) {
+ is VmState.Running -> updateNotification("VM is running")
+ is VmState.Starting -> updateNotification(stage.ifEmpty { "Starting VM..." })
+ else -> {} // Terminal states handled by the shutdown observer
}
}
- launch {
- // Terminal states: release resources and shut down the service.
- // Error must be included here — otherwise a failed boot leaves the
- // wakelock held and the foreground notification stuck on "Starting...".
- //
- // StateFlow replays its current value on subscription, so this
- // collector fires immediately with whatever state is already set.
- // At service-start time the current state is Idle (QEMU hasn't
- // been launched yet), which used to match this branch and
- // instantly release the wakelock we just acquired. Guard with
- // a "seenActive" flag so cleanup only runs on a real
- // active → terminal transition.
- var seenActive = false
- podroidQemu.state.collect { state ->
- when (state) {
- is VmState.Starting, is VmState.Running -> seenActive = true
- is VmState.Stopped, is VmState.Idle, is VmState.Error -> {
- if (seenActive) {
- releaseWakeLock()
- if (Build.VERSION.SDK_INT >= 33) {
- stopForeground(STOP_FOREGROUND_REMOVE)
- } else {
- @Suppress("DEPRECATION") stopForeground(true)
- }
- stopSelf()
- }
- }
- else -> {}
+ }
+
+ /**
+ * Releases the wakelock and stops the service when the VM reaches a
+ * terminal state. The seenActive guard avoids tearing down on the initial
+ * Idle replay before QEMU has even been launched.
+ */
+ private suspend fun observeStateForShutdown() {
+ var seenActive = false
+ podroidQemu.state.collect { state ->
+ when (state) {
+ is VmState.Starting, is VmState.Running -> seenActive = true
+ is VmState.Stopped, is VmState.Idle, is VmState.Error -> {
+ if (!seenActive) return@collect
+ releaseWakeLock()
+ if (Build.VERSION.SDK_INT >= 33) {
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ } else {
+ @Suppress("DEPRECATION") stopForeground(true)
}
+ stopSelf()
}
}
}
@@ -182,8 +171,6 @@ class PodroidService : Service() {
withContext(Dispatchers.IO) {
try {
val rules = portForwardRepository.getRulesSnapshot().toMutableList()
- val ramMb = settingsRepository.getVmRamMbSnapshot()
- val cpus = settingsRepository.getVmCpusSnapshot()
val sshEnabled = settingsRepository.getSshEnabledSnapshot()
// Auto-inject SSH port forward when SSH is enabled
@@ -191,8 +178,17 @@ class PodroidService : Service() {
rules.add(com.excp.podroid.data.repository.PortForwardRule(SSH_HOST_PORT, 22, "tcp"))
}
- val androidIp = getAndroidLocalIp()
- podroidQemu.start(rules, ramMb, cpus, sshEnabled, androidIp)
+ val config = com.excp.podroid.engine.PodroidQemu.LaunchConfig(
+ ramMb = settingsRepository.getVmRamMbSnapshot(),
+ cpus = settingsRepository.getVmCpusSnapshot(),
+ sshEnabled = sshEnabled,
+ androidIp = NetworkUtils.localIpv4(),
+ storageSizeGb = settingsRepository.getStorageSizeGbSnapshot(),
+ storageAccessEnabled = settingsRepository.getStorageAccessEnabledSnapshot(),
+ qemuExtraArgs = settingsRepository.getQemuExtraArgsSnapshot(),
+ kernelExtraCmdline = settingsRepository.getKernelExtraCmdlineSnapshot(),
+ )
+ podroidQemu.start(rules, config)
} catch (e: Exception) {
Log.e(TAG, "QEMU failed to start", e)
}
@@ -200,16 +196,6 @@ class PodroidService : Service() {
}
}
- private fun getAndroidLocalIp(): String {
- return try {
- java.net.NetworkInterface.getNetworkInterfaces()
- ?.asSequence()
- ?.flatMap { it.inetAddresses.asSequence() }
- ?.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
- ?.hostAddress ?: "unknown"
- } catch (_: Exception) { "unknown" }
- }
-
private fun createNotificationChannel() {
val channel = NotificationChannel(
CHANNEL_ID,
diff --git a/app/src/main/java/com/excp/podroid/ui/navigation/NavGraph.kt b/app/src/main/java/com/excp/podroid/ui/navigation/NavGraph.kt
index b428fec..3289ac3 100644
--- a/app/src/main/java/com/excp/podroid/ui/navigation/NavGraph.kt
+++ b/app/src/main/java/com/excp/podroid/ui/navigation/NavGraph.kt
@@ -2,14 +2,13 @@ package com.excp.podroid.ui.navigation
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.runtime.Composable
-import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.hilt.navigation.compose.hiltViewModel
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
-import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.ui.screens.home.HomeScreen
import com.excp.podroid.ui.screens.settings.SettingsScreen
import com.excp.podroid.ui.screens.setup.SetupScreen
@@ -25,11 +24,14 @@ object Routes {
@Composable
fun PodroidNavGraph(
- settingsRepository: SettingsRepository,
windowSizeClass: WindowSizeClass,
navController: NavHostController = rememberNavController(),
) {
- val isSetupDone by settingsRepository.isSetupDone.collectAsState(initial = null)
+ // Read isSetupDone from a Hilt-scoped helper so MainActivity doesn't need
+ // a field-injected SettingsRepository just to drive the start destination.
+ val isSetupDone by hiltViewModel<NavGraphViewModel>()
+ .isSetupDone
+ .collectAsStateWithLifecycle(initialValue = null)
// Scoped to PodroidNavGraph composable — survives all navigation including popUpTo(0)
val terminalViewModel: TerminalViewModel = hiltViewModel()
diff --git a/app/src/main/java/com/excp/podroid/ui/navigation/NavGraphViewModel.kt b/app/src/main/java/com/excp/podroid/ui/navigation/NavGraphViewModel.kt
new file mode 100644
index 0000000..cc777ae
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/ui/navigation/NavGraphViewModel.kt
@@ -0,0 +1,15 @@
+package com.excp.podroid.ui.navigation
+
+import androidx.lifecycle.ViewModel
+import com.excp.podroid.data.repository.SettingsRepository
+import dagger.hilt.android.lifecycle.HiltViewModel
+import javax.inject.Inject
+
+/** Exposes only the bits NavGraph itself needs — keeps MainActivity free of repo wiring. */
+@HiltViewModel
+class NavGraphViewModel @Inject constructor(
+ settingsRepository: SettingsRepository,
+) : ViewModel() {
+ val isSetupDone = settingsRepository.isSetupDone
+ val darkTheme = settingsRepository.darkTheme
+}
diff --git a/app/src/main/java/com/excp/podroid/util/LogProxy.kt b/app/src/main/java/com/excp/podroid/util/LogProxy.kt
new file mode 100644
index 0000000..02caaec
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/util/LogProxy.kt
@@ -0,0 +1,26 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024 Podroid contributors
+ *
+ * Tiny shim for the seven log methods every Termux TerminalSessionClient and
+ * TerminalViewClient implementation has to override. Both PodroidQemu's proxy
+ * client and TerminalViewModel's clients used to stamp the same boilerplate
+ * twice — this is the single source of truth.
+ */
+package com.excp.podroid.util
+
+import android.util.Log
+
+object LogProxy {
+ fun error(tag: String?, fallback: String, msg: String?) { Log.e(tag ?: fallback, msg ?: "") }
+ fun warn(tag: String?, fallback: String, msg: String?) { Log.w(tag ?: fallback, msg ?: "") }
+ fun info(tag: String?, fallback: String, msg: String?) { Log.i(tag ?: fallback, msg ?: "") }
+ fun debug(tag: String?, fallback: String, msg: String?) { Log.d(tag ?: fallback, msg ?: "") }
+ fun verbose(tag: String?, fallback: String, msg: String?) { Log.v(tag ?: fallback, msg ?: "") }
+ fun stackTraceWithMessage(tag: String?, fallback: String, msg: String?, e: Exception?) {
+ Log.e(tag ?: fallback, msg, e)
+ }
+ fun stackTrace(tag: String?, fallback: String, e: Exception?) {
+ Log.e(tag ?: fallback, "Stack trace", e)
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/util/NetworkUtils.kt b/app/src/main/java/com/excp/podroid/util/NetworkUtils.kt
new file mode 100644
index 0000000..1a1e03f
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/util/NetworkUtils.kt
@@ -0,0 +1,23 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024 Podroid contributors
+ *
+ * Tiny shared helper for resolving the device's primary IPv4 address.
+ * Used by both PodroidService (when launching QEMU) and the Settings UI
+ * (to display "Phone IP: …" next to port-forward rules).
+ */
+package com.excp.podroid.util
+
+import java.net.Inet4Address
+import java.net.NetworkInterface
+
+object NetworkUtils {
+ /** First non-loopback IPv4 address, or "unknown" if none / on error. */
+ fun localIpv4(): String = try {
+ NetworkInterface.getNetworkInterfaces()
+ ?.asSequence()
+ ?.flatMap { it.inetAddresses.asSequence() }
+ ?.firstOrNull { !it.isLoopbackAddress && it is Inet4Address }
+ ?.hostAddress ?: "unknown"
+ } catch (_: Exception) { "unknown" }
+}