Skip to content

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

refactor(terminal): extract appearance storage and share bridge setup across engines

ExTv0f167a774709
diff --git a/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt b/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt
index e6eb2f3..8492500 100644
--- a/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt
+++ b/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt
@@ -52,27 +52,30 @@ class BootStageDetector(
val from = (scannedLen - overlap).coerceAtLeast(0)
val tail = buf.substring(from)
scannedLen = buf.length
- when {
- tail.contains("Ready!") -> { ready = true; bootStage.value = "Ready"; state.value = VmState.Running; onReady() }
- tail.contains("Almost ready") -> bootStage.value = "Almost ready..."
- tail.contains("Starting SSH") -> bootStage.value = "Starting SSH..."
- tail.contains("Configuring containers") -> bootStage.value = "Configuring containers..."
- tail.contains("Network found") -> bootStage.value = "Network found"
- tail.contains("Loading kernel modules") -> bootStage.value = "Loading kernel modules..."
- tail.contains("Mounting storage") -> bootStage.value = "Mounting storage..."
- tail.contains("Booting kernel") -> bootStage.value = "Booting kernel..."
+ // First matching marker wins, in MARKERS order (same priority as the
+ // old `when` chain). "Ready!" keeps its one-shot + state + onReady
+ // side effects; every other marker only updates bootStage.
+ val marker = MARKERS.firstOrNull { tail.contains(it.first) } ?: return
+ if (marker.first == READY_MARKER) {
+ ready = true
+ bootStage.value = marker.second
+ state.value = VmState.Running
+ onReady()
+ } else {
+ bootStage.value = marker.second
}
}
private companion object {
+ private const val READY_MARKER = "Ready!"
+
/**
- * The exact substrings the `when` above scans for. Used ONLY to size
- * the cross-feed [overlap]; the `when` remains the authoritative
- * matcher. Keep this list in sync with the `when` search strings —
- * the longest one drives how much prior text is re-scanned.
+ * The exact substrings [feed] scans for, in priority order (first
+ * match wins) and used to size the cross-feed [overlap] (the longest
+ * marker drives how much prior text is re-scanned).
*/
val MARKERS = listOf(
- "Ready!" to "Ready",
+ READY_MARKER to "Ready",
"Almost ready" to "Almost ready...",
"Starting SSH" to "Starting SSH...",
"Configuring containers" to "Configuring containers...",
diff --git a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
index 5390ba9..1e982f7 100644
--- a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
@@ -29,7 +29,6 @@ import android.content.Context
import android.util.Log
import com.excp.podroid.data.repository.PortForwardRule
import com.excp.podroid.util.HostMetrics
-import com.excp.podroid.util.LogProxy
import com.termux.terminal.TerminalSession
import com.termux.terminal.TerminalSessionClient
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -169,30 +168,11 @@ class QemuEngine @Inject constructor(
* Lets us create the bridge session at boot-complete time (before the
* terminal UI exists) and plug in the real ViewModel client later.
*/
- @Volatile
- override var sessionClientDelegate: TerminalSessionClient? = null
-
- private val proxySessionClient = object : TerminalSessionClient {
- override fun onTextChanged(s: TerminalSession) { sessionClientDelegate?.onTextChanged(s) }
- override fun onTitleChanged(s: TerminalSession) { sessionClientDelegate?.onTitleChanged(s) }
- override fun onSessionFinished(s: TerminalSession) { sessionClientDelegate?.onSessionFinished(s) }
- override fun onCopyTextToClipboard(s: TerminalSession, text: String?) { sessionClientDelegate?.onCopyTextToClipboard(s, text) }
- override fun onPasteTextFromClipboard(s: TerminalSession?) { sessionClientDelegate?.onPasteTextFromClipboard(s) }
- override fun onBell(s: TerminalSession) { sessionClientDelegate?.onBell(s) }
- override fun onColorsChanged(s: TerminalSession) { sessionClientDelegate?.onColorsChanged(s) }
- override fun onTerminalCursorStateChange(state: Boolean) { sessionClientDelegate?.onTerminalCursorStateChange(state) }
- override fun setTerminalShellPid(s: TerminalSession, pid: Int) { sessionClientDelegate?.setTerminalShellPid(s, pid) }
- override fun getTerminalCursorStyle(): Int = sessionClientDelegate?.terminalCursorStyle ?: 0
- override fun getTerminalVersionString(): String? = sessionClientDelegate?.terminalVersionString
- 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)
- }
+ private val proxySessionClient = ProxySessionClient(TAG)
+
+ override var sessionClientDelegate: TerminalSessionClient?
+ get() = proxySessionClient.delegate
+ set(value) { proxySessionClient.delegate = value }
private fun persistBootDuration() {
if (bootStartTime == 0L) return
@@ -213,19 +193,12 @@ class QemuEngine @Inject constructor(
// Bridge connects to terminal.sock (virtio-console, separate from serial).
// No handoff with the boot monitor needed — they use different sockets.
- val bridgeExe = File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")
+ val bridgeExe = TerminalBridge.executable(context)
if (!bridgeExe.exists()) return@post
- val sess = TerminalSession(
- bridgeExe.absolutePath,
- context.filesDir.absolutePath,
- arrayOf(bridgeExe.absolutePath, terminalSockPath, ctrlSockPath),
- null,
- 2000,
- proxySessionClient,
+ val sess = TerminalBridge.newSession(
+ context, terminalSockPath, ctrlSockPath, proxySessionClient, onResize = null,
)
- // Cell pixel dims default to 0 — TerminalView.updateSize() pushes real values once measured.
- sess.updateSize(80, 24, 0, 0)
_terminalSession = sess
Log.d(TAG, "Bridge auto-started on terminal.sock")
}
@@ -250,28 +223,33 @@ class QemuEngine @Inject constructor(
}
// Fallback: create session now
- val bridgeExe = File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")
+ val bridgeExe = TerminalBridge.executable(context)
if (!bridgeExe.exists()) {
throw IllegalStateException("podroid-bridge not found at ${bridgeExe.absolutePath}")
}
- val sess = TerminalSession(
- bridgeExe.absolutePath,
- context.filesDir.absolutePath,
- arrayOf(bridgeExe.absolutePath, terminalSockPath, ctrlSockPath),
- null,
- 2000,
- proxySessionClient,
+ val sess = TerminalBridge.newSession(
+ context, terminalSockPath, ctrlSockPath, proxySessionClient, onResize = null,
)
- // Cell pixel dims default to 0 — TerminalView.updateSize() pushes real values once measured.
- sess.updateSize(80, 24, 0, 0)
-
_terminalSession = sess
Log.d(TAG, "Terminal session created in Qemu singleton")
return sess
}
+ /**
+ * Common early-error path in start(), before a process or scope exists:
+ * restores the "cleanedUp=false ⟺ a VM lifetime is in progress" invariant
+ * that the startMutex block already broke by setting cleanedUp=false and
+ * bootStartTime, matching the other error paths (which run cleanup()).
+ * Callers still `return` right after calling this.
+ */
+ private fun failEarlyStart(message: String) {
+ cleanedUp.set(true)
+ bootStartTime = 0L
+ _state.value = VmState.Error(message)
+ }
+
override suspend fun start(portForwards: List<PortForwardRule>, config: VmConfig) {
// Atomically check the re-entrancy guard AND claim Starting before any
// I/O, so two concurrent ACTION_STARTs can't both pass the guard and
@@ -288,24 +266,14 @@ class QemuEngine @Inject constructor(
}
val qemuExe = qemuExecutable() ?: run {
- // The startMutex block already set cleanedUp=false and bootStartTime;
- // restore the "cleanedUp=false ⟺ a VM lifetime is in progress"
- // invariant on this early-error return, matching the other error
- // paths (which run cleanup()). No process/scope exists yet.
- cleanedUp.set(true)
- bootStartTime = 0L
- _state.value = VmState.Error("QEMU binary not found.")
+ failEarlyStart("QEMU binary not found.")
return
}
try {
ensureStorageImage(config.storageSizeGb)
} catch (e: java.io.IOException) {
- // Restore the "cleanedUp=false ⟺ VM lifetime in progress" invariant
- // (same as the qemuExecutable() path); no process/scope exists yet.
- cleanedUp.set(true)
- bootStartTime = 0L
- _state.value = VmState.Error(e.message ?: "Could not prepare the VM disk image.")
+ failEarlyStart(e.message ?: "Could not prepare the VM disk image.")
return
}
diff --git a/app/src/main/java/com/excp/podroid/engine/TerminalBridge.kt b/app/src/main/java/com/excp/podroid/engine/TerminalBridge.kt
new file mode 100644
index 0000000..1ccaccb
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/engine/TerminalBridge.kt
@@ -0,0 +1,94 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Shared bridge-session plumbing for QemuEngine and AvfEngine: the proxy
+ * TerminalSessionClient that lets an engine create the bridge session before
+ * the terminal UI exists, and the TerminalSession construction the two
+ * engines otherwise duplicated at four call sites.
+ */
+package com.excp.podroid.engine
+
+import android.content.Context
+import com.excp.podroid.util.LogProxy
+import com.termux.terminal.TerminalSession
+import com.termux.terminal.TerminalSessionClient
+import java.io.File
+
+/**
+ * Proxy TerminalSessionClient - delegates to whatever real client is set.
+ * Lets an engine create the bridge session at boot-complete time (before the
+ * terminal UI exists) and plug in the real ViewModel client later.
+ */
+class ProxySessionClient(private val tag: String) : TerminalSessionClient {
+ @Volatile var delegate: TerminalSessionClient? = null
+
+ override fun onTextChanged(s: TerminalSession) { delegate?.onTextChanged(s) }
+ override fun onTitleChanged(s: TerminalSession) { delegate?.onTitleChanged(s) }
+ override fun onSessionFinished(s: TerminalSession) { delegate?.onSessionFinished(s) }
+ override fun onCopyTextToClipboard(s: TerminalSession, text: String?) { delegate?.onCopyTextToClipboard(s, text) }
+ override fun onPasteTextFromClipboard(s: TerminalSession?) { delegate?.onPasteTextFromClipboard(s) }
+ override fun onBell(s: TerminalSession) { delegate?.onBell(s) }
+ override fun onColorsChanged(s: TerminalSession) { delegate?.onColorsChanged(s) }
+ override fun onTerminalCursorStateChange(state: Boolean) { delegate?.onTerminalCursorStateChange(state) }
+ override fun setTerminalShellPid(s: TerminalSession, pid: Int) { delegate?.setTerminalShellPid(s, pid) }
+ override fun getTerminalCursorStyle(): Int = delegate?.terminalCursorStyle ?: 0
+ override fun getTerminalVersionString(): String? = delegate?.terminalVersionString
+ override fun logError(tag: String?, msg: String?) = LogProxy.error(tag, this.tag, msg)
+ override fun logWarn(tag: String?, msg: String?) = LogProxy.warn(tag, this.tag, msg)
+ override fun logInfo(tag: String?, msg: String?) = LogProxy.info(tag, this.tag, msg)
+ override fun logDebug(tag: String?, msg: String?) = LogProxy.debug(tag, this.tag, msg)
+ override fun logVerbose(tag: String?, msg: String?) = LogProxy.verbose(tag, this.tag, msg)
+ override fun logStackTraceWithMessage(tag: String?, msg: String?, e: Exception?) =
+ LogProxy.stackTraceWithMessage(tag, this.tag, msg, e)
+ override fun logStackTrace(tag: String?, e: Exception?) = LogProxy.stackTrace(tag, this.tag, e)
+}
+
+/**
+ * Builds the podroid-bridge TerminalSession shared by both engines: same
+ * executable lookup, argv, cwd, transcript size and initial size push. Each
+ * call site keeps its own existence-check and missing-exe handling (silent
+ * return, log, or throw) - this only covers the part that was identical.
+ */
+object TerminalBridge {
+ fun executable(context: Context): File =
+ File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")
+
+ /**
+ * [onResize] non-null builds a [ResizeNotifyingSession] (AVF); null builds
+ * a plain [TerminalSession] (QEMU, which has no resize channel here).
+ */
+ fun newSession(
+ context: Context,
+ terminalSock: String,
+ ctrlSock: String,
+ client: TerminalSessionClient,
+ onResize: ((rows: Int, cols: Int) -> Unit)?,
+ ): TerminalSession {
+ val bridgeExe = executable(context)
+ val args = arrayOf(bridgeExe.absolutePath, terminalSock, ctrlSock)
+ val sess = if (onResize != null) {
+ ResizeNotifyingSession(
+ shellPath = bridgeExe.absolutePath,
+ cwd = context.filesDir.absolutePath,
+ args = args,
+ env = null,
+ transcriptRows = 2000,
+ client = client,
+ onResize = onResize,
+ )
+ } else {
+ TerminalSession(
+ bridgeExe.absolutePath,
+ context.filesDir.absolutePath,
+ args,
+ null,
+ 2000,
+ client,
+ )
+ }
+ // Cell pixel dims default to 0 - TerminalView.updateSize() pushes real values once measured.
+ sess.updateSize(80, 24, 0, 0)
+ return sess
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
index 6460a16..0849a5d 100644
--- a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
@@ -22,11 +22,12 @@ import androidx.annotation.RequiresApi
import com.excp.podroid.data.repository.PortForwardRule
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.engine.BootStageDetector
+import com.excp.podroid.engine.ProxySessionClient
import com.excp.podroid.engine.QmpClient
+import com.excp.podroid.engine.TerminalBridge
import com.excp.podroid.engine.VmConfig
import com.excp.podroid.engine.VmEngine
import com.excp.podroid.engine.VmState
-import com.excp.podroid.util.LogProxy
import com.termux.terminal.TerminalSession
import com.termux.terminal.TerminalSessionClient
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -112,29 +113,11 @@ class AvfEngine @Inject constructor(
/** AVF has no QMP socket; port forwarding is deferred to a future milestone. */
override val qmpClient: QmpClient? = null
- override var sessionClientDelegate: TerminalSessionClient? = null
+ private val proxySessionClient = ProxySessionClient(TAG)
- private val proxySessionClient = object : TerminalSessionClient {
- override fun onTextChanged(s: TerminalSession) { sessionClientDelegate?.onTextChanged(s) }
- override fun onTitleChanged(s: TerminalSession) { sessionClientDelegate?.onTitleChanged(s) }
- override fun onSessionFinished(s: TerminalSession) { sessionClientDelegate?.onSessionFinished(s) }
- override fun onCopyTextToClipboard(s: TerminalSession, text: String?) { sessionClientDelegate?.onCopyTextToClipboard(s, text) }
- override fun onPasteTextFromClipboard(s: TerminalSession?) { sessionClientDelegate?.onPasteTextFromClipboard(s) }
- override fun onBell(s: TerminalSession) { sessionClientDelegate?.onBell(s) }
- override fun onColorsChanged(s: TerminalSession) { sessionClientDelegate?.onColorsChanged(s) }
- override fun onTerminalCursorStateChange(state: Boolean) { sessionClientDelegate?.onTerminalCursorStateChange(state) }
- override fun setTerminalShellPid(s: TerminalSession, pid: Int) { sessionClientDelegate?.setTerminalShellPid(s, pid) }
- override fun getTerminalCursorStyle(): Int = sessionClientDelegate?.terminalCursorStyle ?: 0
- override fun getTerminalVersionString(): String? = sessionClientDelegate?.terminalVersionString
- 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)
- }
+ override var sessionClientDelegate: TerminalSessionClient?
+ get() = proxySessionClient.delegate
+ set(value) { proxySessionClient.delegate = value }
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
// Serializes the check-and-claim in start(). Two near-simultaneous
@@ -591,21 +574,15 @@ class AvfEngine @Inject constructor(
private fun spawnBridge() {
android.os.Handler(android.os.Looper.getMainLooper()).post {
if (terminalSession != null) return@post
- val bridgeExe = File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")
+ val bridgeExe = TerminalBridge.executable(context)
if (!bridgeExe.exists()) {
Log.e(TAG, "bridge missing at ${bridgeExe.absolutePath}")
return@post
}
- val sess = com.excp.podroid.engine.ResizeNotifyingSession(
- shellPath = bridgeExe.absolutePath,
- cwd = context.filesDir.absolutePath,
- args = arrayOf(bridgeExe.absolutePath, terminalSockPath, ctrlSockPath),
- env = null,
- transcriptRows = 2000,
- client = proxySessionClient,
+ val sess = TerminalBridge.newSession(
+ context, terminalSockPath, ctrlSockPath, proxySessionClient,
onResize = { rows, cols -> sendResizeDebounced(rows, cols) },
)
- sess.updateSize(80, 24, 0, 0)
terminalSession = sess
Log.d(TAG, "AVF bridge auto-spawned (resize-notifying)")
}
@@ -782,20 +759,14 @@ class AvfEngine @Inject constructor(
Log.w(TAG, "createTerminalSession called before bridge auto-spawn; spawning now")
}
- val bridgeExe = File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")
+ val bridgeExe = TerminalBridge.executable(context)
if (!bridgeExe.exists()) {
throw IllegalStateException("podroid-bridge not found at ${bridgeExe.absolutePath}")
}
- val sess = com.excp.podroid.engine.ResizeNotifyingSession(
- shellPath = bridgeExe.absolutePath,
- cwd = context.filesDir.absolutePath,
- args = arrayOf(bridgeExe.absolutePath, terminalSockPath, ctrlSockPath),
- env = null,
- transcriptRows = 2000,
- client = proxySessionClient,
+ val sess = TerminalBridge.newSession(
+ context, terminalSockPath, ctrlSockPath, proxySessionClient,
onResize = { rows, cols -> sendResizeDebounced(rows, cols) },
)
- sess.updateSize(80, 24, 0, 0)
terminalSession = sess
return sess
}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalAppearanceStore.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalAppearanceStore.kt
new file mode 100644
index 0000000..a9b3361
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalAppearanceStore.kt
@@ -0,0 +1,245 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Theme and font file handling for the terminal: bundled assets plus
+ * user-imported themes/fonts under getExternalFilesDir. Moved out of
+ * TerminalViewModel so the ViewModel stays focused on session wiring;
+ * TerminalViewModel keeps one-line delegates to the public methods here so
+ * TerminalScreen/TerminalQuickSettings call sites are unchanged.
+ */
+package com.excp.podroid.ui.screens.terminal
+
+import android.content.Context
+import android.graphics.Typeface
+import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class TerminalAppearanceStore @Inject constructor(
+ @ApplicationContext private val context: Context,
+) {
+ /**
+ * Where user-imported fonts live. App-private external dir means no permission
+ * prompts and a clean uninstall, but it's not visible to third-party file
+ * managers on Android 11+ - so we drive imports via SAF (`importCustomFont`)
+ * rather than asking users to "drop a .ttf into a folder".
+ */
+ private val userFontsDir: java.io.File by lazy {
+ java.io.File(context.getExternalFilesDir(null), "fonts").apply { mkdirs() }
+ }
+
+ /** Where user-imported themes live. Same rationale as userFontsDir. */
+ private val userThemesDir: java.io.File by lazy {
+ java.io.File(context.getExternalFilesDir(null), "colors").apply { mkdirs() }
+ }
+
+ /** User dir wins over bundled when names collide. */
+ fun readThemeProperties(theme: String): java.util.Properties? {
+ val props = java.util.Properties()
+ val userFile = java.io.File(userThemesDir, "$theme.properties")
+ return try {
+ if (userFile.isFile) {
+ userFile.inputStream().use { props.load(it) }
+ } else {
+ context.assets.open("colors/$theme.properties").use { props.load(it) }
+ }
+ props
+ } catch (_: Exception) { null }
+ }
+
+ /**
+ * Peek a theme's bg+fg ARGB ints without mutating the active palette.
+ * Used by the Settings sheet to render theme preview swatches.
+ * Returns null for `default` (caller falls back to neutral colors).
+ */
+ fun peekThemeColors(theme: String): Pair<Int, Int>? {
+ if (theme == "default") return null
+ val props = readThemeProperties(theme) ?: return null
+ val bg = (props["background"] as? String)?.let { parseHexColor(it) } ?: return null
+ val fg = (props["foreground"] as? String)?.let { parseHexColor(it) } ?: 0xFFE0E0E0.toInt()
+ return bg to fg
+ }
+
+ /** Bundled .properties themes union user-imported. */
+ fun listAvailableThemes(): List<String> {
+ val bundled = runCatching { context.assets.list("colors")?.toList() }
+ .getOrNull().orEmpty()
+ val user = (userThemesDir.listFiles() ?: emptyArray())
+ .filter { it.isFile }.map { it.name }
+ val names = (bundled + user)
+ .filter { it.endsWith(".properties", ignoreCase = true) }
+ .map { it.substringBeforeLast('.') }
+ .toSortedSet(String.CASE_INSENSITIVE_ORDER)
+ return listOf("default") + names.toList()
+ }
+
+ fun isCustomTheme(name: String): Boolean =
+ java.io.File(userThemesDir, "$name.properties").isFile
+
+ fun deleteCustomTheme(name: String): Boolean {
+ val f = java.io.File(userThemesDir, "$name.properties")
+ return f.exists() && f.delete()
+ }
+
+ /**
+ * Import a theme from a terminalcolors.com URL.
+ * Accepts pages like `https://terminalcolors.com/themes/dracula/default/` -
+ * we transform the slug into the predictable Alacritty TOML download URL,
+ * fetch it, and convert to our `.properties` format.
+ *
+ * Returns the saved theme name, or null on any failure.
+ */
+ suspend fun importThemeFromUrl(input: String): String? = withContext(Dispatchers.IO) {
+ val url = input.trim()
+ // Extract slug from the page URL or accept the .toml URL directly.
+ val tomlUrl: String = when {
+ url.endsWith(".toml") -> url
+ else -> {
+ val match = Regex("""terminalcolors\.com/themes/([^/]+)/([^/?#]+)""").find(url)
+ ?: return@withContext null
+ val (name, variant) = match.groupValues[1] to match.groupValues[2]
+ "https://terminalcolors.com/downloads/alacritty/$name-$variant.toml"
+ }
+ }
+ val toml = runCatching {
+ val conn = (java.net.URL(tomlUrl).openConnection() as java.net.HttpURLConnection).apply {
+ connectTimeout = 8000
+ readTimeout = 8000
+ setRequestProperty(
+ "User-Agent",
+ "Podroid/${com.excp.podroid.BuildConfig.VERSION_NAME}"
+ )
+ }
+ try {
+ if (conn.responseCode != 200) return@runCatching null
+ conn.inputStream.bufferedReader().readText()
+ } finally { conn.disconnect() }
+ }.getOrNull() ?: return@withContext null
+
+ val themeName = sanitizeFontName(
+ tomlUrl.substringAfterLast('/').substringBeforeLast('.')
+ ) ?: return@withContext null
+
+ val properties = parseAlacrittyToml(toml) ?: return@withContext null
+
+ val dest = java.io.File(userThemesDir, "$themeName.properties")
+ dest.bufferedWriter().use { w ->
+ for ((k, v) in properties) w.write("$k=$v\n")
+ }
+ themeName
+ }
+
+ /** Bundled assets union user-imported TTFs (case-insensitive dedupe - user wins). */
+ fun listAvailableFonts(): List<String> {
+ val bundled = runCatching { context.assets.list("fonts")?.toList() }
+ .getOrNull().orEmpty()
+ val user = (userFontsDir.listFiles() ?: emptyArray())
+ .filter { it.isFile }.map { it.name }
+ val names = (bundled + user)
+ .filter { it.endsWith(".ttf", ignoreCase = true) }
+ .map { it.substringBeforeLast('.') }
+ .toSortedSet(String.CASE_INSENSITIVE_ORDER)
+ return listOf("default") + names.toList()
+ }
+
+ /** True if `name` was imported by the user (overrides any bundled font of the same name). */
+ fun isCustomFont(name: String): Boolean =
+ java.io.File(userFontsDir, "$name.ttf").isFile
+
+ /** Resolve a font name to a Typeface. Returns Typeface.MONOSPACE for default or on error. */
+ fun loadFont(font: String): Typeface {
+ if (font == "default") return Typeface.MONOSPACE
+ // User imports win over bundled with the same name.
+ val userFile = java.io.File(userFontsDir, "$font.ttf")
+ if (userFile.isFile) {
+ return runCatching { Typeface.createFromFile(userFile) }
+ .getOrDefault(Typeface.MONOSPACE)
+ }
+ return try {
+ // assets.openFd is a file descriptor - Typeface.createFromFile needs a real path,
+ // so we copy on demand into a per-launch cache file.
+ val cacheFile = java.io.File(context.cacheDir, "font_$font.ttf")
+ if (!cacheFile.exists()) {
+ context.assets.open("fonts/$font.ttf").use { inp ->
+ cacheFile.outputStream().use { out -> inp.copyTo(out) }
+ }
+ }
+ Typeface.createFromFile(cacheFile)
+ } catch (_: Exception) { Typeface.MONOSPACE }
+ }
+
+ /**
+ * Import a `.ttf` from a SAF `Uri` into the user fonts dir.
+ * Returns the sanitized font name (no extension) on success, null on failure.
+ *
+ * Safety:
+ * - Filename sanitized to ASCII alnum + dash/underscore (max 48 chars).
+ * - Capped at 16 MiB; legitimate TTFs are well under 1 MB.
+ * - Validates by constructing a Typeface; rejects unloadable files.
+ * - Writes to `.tmp` then renames so a partial copy never wins picker enumeration.
+ */
+ fun importCustomFont(uri: android.net.Uri): String? {
+ val rawName = displayNameOf(uri) ?: return null
+ val name = sanitizeFontName(rawName) ?: return null
+ val tmp = java.io.File(userFontsDir, "$name.ttf.tmp")
+ val dest = java.io.File(userFontsDir, "$name.ttf")
+ return try {
+ context.contentResolver.openInputStream(uri).use { input ->
+ if (input == null) return null
+ tmp.outputStream().use { out ->
+ val maxBytes = 16L * 1024 * 1024
+ val buf = ByteArray(8192)
+ var written = 0L
+ while (true) {
+ val n = input.read(buf)
+ if (n <= 0) break
+ written += n
+ if (written > maxBytes) return cleanup(tmp, null)
+ out.write(buf, 0, n)
+ }
+ }
+ }
+ // Validate by trying to load it.
+ val tf = runCatching { Typeface.createFromFile(tmp) }.getOrNull()
+ if (tf == null || tf === Typeface.DEFAULT) return cleanup(tmp, null)
+ // Atomic-ish swap.
+ if (dest.exists()) dest.delete()
+ if (!tmp.renameTo(dest)) return cleanup(tmp, null)
+ // Invalidate the asset-cache copy in case a bundled font of the same
+ // name was previously loaded - next loadFont() should see the new file.
+ java.io.File(context.cacheDir, "font_$name.ttf").delete()
+ name
+ } catch (_: Exception) {
+ cleanup(tmp, null)
+ }
+ }
+
+ /** Remove a previously-imported custom font. Returns true if it existed and was removed. */
+ fun deleteCustomFont(name: String): Boolean {
+ val f = java.io.File(userFontsDir, "$name.ttf")
+ val ok = f.exists() && f.delete()
+ if (ok) java.io.File(context.cacheDir, "font_$name.ttf").delete()
+ return ok
+ }
+
+ private fun <T> cleanup(tmp: java.io.File, result: T?): T? {
+ runCatching { if (tmp.exists()) tmp.delete() }
+ return result
+ }
+
+ private fun displayNameOf(uri: android.net.Uri): String? = runCatching {
+ context.contentResolver.query(
+ uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null
+ )?.use { if (it.moveToFirst()) it.getString(0) else null }
+ }.getOrNull()
+
+ private fun sanitizeFontName(filename: String): String? {
+ val base = filename.substringBeforeLast('.').trim()
+ val safe = base.replace(Regex("[^A-Za-z0-9_-]"), "-").trim('-').take(48)
+ return safe.takeIf { it.isNotEmpty() }
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalThemeParsing.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalThemeParsing.kt
new file mode 100644
index 0000000..5496582
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalThemeParsing.kt
@@ -0,0 +1,99 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Pure theme-file parsing shared by TerminalAppearanceStore, with no Android
+ * framework dependency so it runs in a plain JVM unit test.
+ */
+package com.excp.podroid.ui.screens.terminal
+
+/**
+ * Parse an Alacritty TOML color export into our `.properties` keys.
+ * Returns null if required keys (background/foreground/16 ANSI colors) aren't found.
+ */
+fun parseAlacrittyToml(toml: String): Map<String, String>? {
+ // [colors.<section>] key = "#xxxxxx"
+ val sectionRe = Regex("""\[colors\.(\w+)]""")
+ val kvRe = Regex("""(\w+)\s*=\s*"(#[0-9a-fA-F]{3,8})"""")
+ var section = ""
+ val byKey = LinkedHashMap<String, String>()
+ for (raw in toml.lines()) {
+ val line = raw.trim()
+ sectionRe.find(line)?.let { section = it.groupValues[1]; return@let }
+ val kv = kvRe.find(line) ?: continue
+ val key = kv.groupValues[1]
+ val value = kv.groupValues[2]
+ val mapped = when (section) {
+ "primary" -> when (key) {
+ "foreground" -> "foreground"
+ "background" -> "background"
+ else -> null
+ }
+ "cursor" -> when (key) {
+ "cursor" -> "cursor"
+ "text" -> null // foreground-of-cursor, emulator doesn't store separately
+ else -> null
+ }
+ "normal" -> when (key) {
+ "black" -> "color0"; "red" -> "color1"
+ "green" -> "color2"; "yellow" -> "color3"
+ "blue" -> "color4"; "magenta" -> "color5"
+ "cyan" -> "color6"; "white" -> "color7"
+ else -> null
+ }
+ "bright" -> when (key) {
+ "black" -> "color8"; "red" -> "color9"
+ "green" -> "color10"; "yellow" -> "color11"
+ "blue" -> "color12"; "magenta" -> "color13"
+ "cyan" -> "color14"; "white" -> "color15"
+ else -> null
+ }
+ else -> null
+ } ?: continue
+ byKey[mapped] = value
+ }
+ // Sanity: must have FG + BG and at least 8 ANSI colors.
+ if (!byKey.containsKey("foreground") || !byKey.containsKey("background")) return null
+ if ((0..7).any { !byKey.containsKey("color$it") }) return null
+ return byKey
+}
+
+/** ARGB black, matching android.graphics.Color.BLACK (0xFF000000). */
+private const val BLACK = 0xFF000000.toInt()
+
+private fun rgb(red: Int, green: Int, blue: Int): Int =
+ 0xff000000.toInt() or (red shl 16) or (green shl 8) or blue
+
+private fun argb(alpha: Int, red: Int, green: Int, blue: Int): Int =
+ (alpha shl 24) or (red shl 16) or (green shl 8) or blue
+
+/**
+ * Parse a `#rgb` / `#rrggbb` / `#aarrggbb` hex color into an ARGB int,
+ * computed with bit math so it matches android.graphics.Color.rgb/argb
+ * exactly without depending on the Android framework (unmocked in a plain
+ * JVM unit test). Falls back to BLACK on an unrecognized length or a bad
+ * hex digit in the 3-digit form.
+ */
+fun parseHexColor(hex: String): Int {
+ val clean = hex.removePrefix("#")
+ return when (clean.length) {
+ 3 -> {
+ val r = clean[0].digitToIntOrNull(16) ?: return BLACK
+ val g = clean[1].digitToIntOrNull(16) ?: return BLACK
+ val b = clean[2].digitToIntOrNull(16) ?: return BLACK
+ rgb(r * 17, g * 17, b * 17)
+ }
+ 6 -> rgb(
+ clean.substring(0, 2).toInt(16),
+ clean.substring(2, 4).toInt(16),
+ clean.substring(4, 6).toInt(16)
+ )
+ 8 -> argb(
+ clean.substring(0, 2).toInt(16),
+ clean.substring(2, 4).toInt(16),
+ clean.substring(4, 6).toInt(16),
+ clean.substring(6, 8).toInt(16)
+ )
+ else -> BLACK
+ }
+}
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 0b9b5cc..c78c04b 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
@@ -50,10 +50,8 @@ import com.termux.view.TerminalView
import com.termux.view.TerminalViewClient
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
-import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import java.io.File
@@ -65,6 +63,7 @@ class TerminalViewModel @Inject constructor(
private val engine: VmEngine,
private val settingsRepository: SettingsRepository,
private val headlessModeManager: com.excp.podroid.engine.hostbridge.HeadlessModeManager,
+ private val appearanceStore: TerminalAppearanceStore,
) : ViewModel() {
val vmState: StateFlow<VmState> = engine.state
@@ -177,18 +176,8 @@ class TerminalViewModel @Inject constructor(
viewRef = view?.let { java.lang.ref.WeakReference(it) }
}
- /**
- * Peek a theme's bg+fg ARGB ints without mutating the active palette.
- * Used by the Settings sheet to render theme preview swatches.
- * Returns null for `default` (caller falls back to neutral colors).
- */
- fun peekThemeColors(theme: String): Pair<Int, Int>? {
- if (theme == "default") return null
- val props = readThemeProperties(theme) ?: return null
- val bg = (props["background"] as? String)?.let { parseColor(it) } ?: return null
- val fg = (props["foreground"] as? String)?.let { parseColor(it) } ?: 0xFFE0E0E0.toInt()
- return bg to fg
- }
+ /** Peek a theme's bg+fg ARGB ints. See [TerminalAppearanceStore.peekThemeColors]. */
+ fun peekThemeColors(theme: String): Pair<Int, Int>? = appearanceStore.peekThemeColors(theme)
/**
* Resolve a theme name to the (background, Properties) pair, also pushing
@@ -204,7 +193,7 @@ class TerminalViewModel @Inject constructor(
val props = if (theme == "default") {
java.util.Properties()
} else {
- readThemeProperties(theme) ?: return null
+ appearanceStore.readThemeProperties(theme) ?: return null
}
TerminalColors.COLOR_SCHEME.updateWith(props)
// updateWith refreshes the static defaults, but the live session's
@@ -212,295 +201,35 @@ class TerminalViewModel @Inject constructor(
// and on `\ec` (RIS). Without this push, theme changes only took
// effect after the user typed `reset` in the shell.
session?.emulator?.mColors?.reset()
- return (props["background"] as? String)?.let { parseColor(it) }
+ return (props["background"] as? String)?.let { parseHexColor(it) }
}
- /** User dir wins over bundled when names collide. */
- private fun readThemeProperties(theme: String): java.util.Properties? {
- val props = java.util.Properties()
- val userFile = java.io.File(userThemesDir, "$theme.properties")
- return try {
- if (userFile.isFile) {
- userFile.inputStream().use { props.load(it) }
- } else {
- context.assets.open("colors/$theme.properties").use { props.load(it) }
- }
- props
- } catch (_: Exception) { null }
- }
+ /** List available themes. See [TerminalAppearanceStore.listAvailableThemes]. */
+ fun listAvailableThemes(): List<String> = appearanceStore.listAvailableThemes()
- /**
- * Where user-imported fonts live. App-private external dir means no permission
- * prompts and a clean uninstall, but it's not visible to third-party file
- * managers on Android 11+ — so we drive imports via SAF (`importCustomFont`)
- * rather than asking users to "drop a .ttf into a folder".
- */
- private val userFontsDir: java.io.File by lazy {
- java.io.File(context.getExternalFilesDir(null), "fonts").apply { mkdirs() }
- }
+ /** True if `name` was imported by the user. See [TerminalAppearanceStore.isCustomTheme]. */
+ fun isCustomTheme(name: String): Boolean = appearanceStore.isCustomTheme(name)
- /** Where user-imported themes live. Same rationale as userFontsDir. */
- private val userThemesDir: java.io.File by lazy {
- java.io.File(context.getExternalFilesDir(null), "colors").apply { mkdirs() }
- }
+ /** Remove a previously-imported theme. See [TerminalAppearanceStore.deleteCustomTheme]. */
+ fun deleteCustomTheme(name: String): Boolean = appearanceStore.deleteCustomTheme(name)
- /** Bundled .properties themes ∪ user-imported. */
- fun listAvailableThemes(): List<String> {
- val bundled = runCatching { context.assets.list("colors")?.toList() }
- .getOrNull().orEmpty()
- val user = (userThemesDir.listFiles() ?: emptyArray())
- .filter { it.isFile }.map { it.name }
- val names = (bundled + user)
- .filter { it.endsWith(".properties", ignoreCase = true) }
- .map { it.substringBeforeLast('.') }
- .toSortedSet(String.CASE_INSENSITIVE_ORDER)
- return listOf("default") + names.toList()
- }
+ /** Import a theme from a terminalcolors.com URL. See [TerminalAppearanceStore.importThemeFromUrl]. */
+ suspend fun importThemeFromUrl(input: String): String? = appearanceStore.importThemeFromUrl(input)
- fun isCustomTheme(name: String): Boolean =
- java.io.File(userThemesDir, "$name.properties").isFile
+ /** List available fonts. See [TerminalAppearanceStore.listAvailableFonts]. */
+ fun listAvailableFonts(): List<String> = appearanceStore.listAvailableFonts()
- fun deleteCustomTheme(name: String): Boolean {
- val f = java.io.File(userThemesDir, "$name.properties")
- return f.exists() && f.delete()
- }
+ /** True if `name` was imported by the user. See [TerminalAppearanceStore.isCustomFont]. */
+ fun isCustomFont(name: String): Boolean = appearanceStore.isCustomFont(name)
- /**
- * Import a theme from a terminalcolors.com URL.
- * Accepts pages like `https://terminalcolors.com/themes/dracula/default/` —
- * we transform the slug into the predictable Alacritty TOML download URL,
- * fetch it, and convert to our `.properties` format.
- *
- * Returns the saved theme name, or null on any failure.
- */
- suspend fun importThemeFromUrl(input: String): String? = withContext(Dispatchers.IO) {
- val url = input.trim()
- // Extract slug from the page URL or accept the .toml URL directly.
- val tomlUrl: String = when {
- url.endsWith(".toml") -> url
- else -> {
- val match = Regex("""terminalcolors\.com/themes/([^/]+)/([^/?#]+)""").find(url)
- ?: return@withContext null
- val (name, variant) = match.groupValues[1] to match.groupValues[2]
- "https://terminalcolors.com/downloads/alacritty/$name-$variant.toml"
- }
- }
- val toml = runCatching {
- val conn = (java.net.URL(tomlUrl).openConnection() as java.net.HttpURLConnection).apply {
- connectTimeout = 8000
- readTimeout = 8000
- setRequestProperty(
- "User-Agent",
- "Podroid/${com.excp.podroid.BuildConfig.VERSION_NAME}"
- )
- }
- try {
- if (conn.responseCode != 200) return@runCatching null
- conn.inputStream.bufferedReader().readText()
- } finally { conn.disconnect() }
- }.getOrNull() ?: return@withContext null
+ /** Resolve a font name to a Typeface. See [TerminalAppearanceStore.loadFont]. */
+ fun loadFont(font: String): Typeface = appearanceStore.loadFont(font)
- val themeName = sanitizeFontName(
- tomlUrl.substringAfterLast('/').substringBeforeLast('.')
- ) ?: return@withContext null
+ /** Import a `.ttf` from a SAF `Uri`. See [TerminalAppearanceStore.importCustomFont]. */
+ fun importCustomFont(uri: android.net.Uri): String? = appearanceStore.importCustomFont(uri)
- val properties = parseAlacrittyToml(toml) ?: return@withContext null
-
- val dest = java.io.File(userThemesDir, "$themeName.properties")
- dest.bufferedWriter().use { w ->
- for ((k, v) in properties) w.write("$k=$v\n")
- }
- themeName
- }
-
- /**
- * Parse an Alacritty TOML color export into our `.properties` keys.
- * Returns null if required keys (background/foreground/16 ANSI colors) aren't found.
- */
- private fun parseAlacrittyToml(toml: String): Map<String, String>? {
- // [colors.<section>] key = "#xxxxxx"
- val sectionRe = Regex("""\[colors\.(\w+)]""")
- val kvRe = Regex("""(\w+)\s*=\s*"(#[0-9a-fA-F]{3,8})"""")
- var section = ""
- val byKey = LinkedHashMap<String, String>()
- for (raw in toml.lines()) {
- val line = raw.trim()
- sectionRe.find(line)?.let { section = it.groupValues[1]; return@let }
- val kv = kvRe.find(line) ?: continue
- val key = kv.groupValues[1]
- val value = kv.groupValues[2]
- val mapped = when (section) {
- "primary" -> when (key) {
- "foreground" -> "foreground"
- "background" -> "background"
- else -> null
- }
- "cursor" -> when (key) {
- "cursor" -> "cursor"
- "text" -> null // foreground-of-cursor — emulator doesn't store separately
- else -> null
- }
- "normal" -> when (key) {
- "black" -> "color0"; "red" -> "color1"
- "green" -> "color2"; "yellow" -> "color3"
- "blue" -> "color4"; "magenta" -> "color5"
- "cyan" -> "color6"; "white" -> "color7"
- else -> null
- }
- "bright" -> when (key) {
- "black" -> "color8"; "red" -> "color9"
- "green" -> "color10"; "yellow" -> "color11"
- "blue" -> "color12"; "magenta" -> "color13"
- "cyan" -> "color14"; "white" -> "color15"
- else -> null
- }
- else -> null
- } ?: continue
- byKey[mapped] = value
- }
- // Sanity: must have FG + BG and at least 8 ANSI colors.
- if (!byKey.containsKey("foreground") || !byKey.containsKey("background")) return null
- if ((0..7).any { !byKey.containsKey("color$it") }) return null
- return byKey
- }
-
- /** Bundled assets ∪ user-imported TTFs (case-insensitive dedupe — user wins). */
- fun listAvailableFonts(): List<String> {
- val bundled = runCatching { context.assets.list("fonts")?.toList() }
- .getOrNull().orEmpty()
- val user = (userFontsDir.listFiles() ?: emptyArray())
- .filter { it.isFile }.map { it.name }
- val names = (bundled + user)
- .filter { it.endsWith(".ttf", ignoreCase = true) }
- .map { it.substringBeforeLast('.') }
- .toSortedSet(String.CASE_INSENSITIVE_ORDER)
- return listOf("default") + names.toList()
- }
-
- /** True if `name` was imported by the user (overrides any bundled font of the same name). */
- fun isCustomFont(name: String): Boolean =
- java.io.File(userFontsDir, "$name.ttf").isFile
-
- /** Resolve a font name to a Typeface. Returns Typeface.MONOSPACE for default or on error. */
- fun loadFont(font: String): Typeface {
- if (font == "default") return Typeface.MONOSPACE
- // User imports win over bundled with the same name.
- val userFile = java.io.File(userFontsDir, "$font.ttf")
- if (userFile.isFile) {
- return runCatching { Typeface.createFromFile(userFile) }
- .getOrDefault(Typeface.MONOSPACE)
- }
- return try {
- // assets.openFd is a file descriptor — Typeface.createFromFile needs a real path,
- // so we copy on demand into a per-launch cache file.
- val cacheFile = java.io.File(context.cacheDir, "font_$font.ttf")
- if (!cacheFile.exists()) {
- context.assets.open("fonts/$font.ttf").use { inp ->
- cacheFile.outputStream().use { out -> inp.copyTo(out) }
- }
- }
- Typeface.createFromFile(cacheFile)
- } catch (_: Exception) { Typeface.MONOSPACE }
- }
-
- /**
- * Import a `.ttf` from a SAF `Uri` into the user fonts dir.
- * Returns the sanitized font name (no extension) on success, null on failure.
- *
- * Safety:
- * - Filename sanitized to ASCII alnum + dash/underscore (max 48 chars).
- * - Capped at 16 MiB; legitimate TTFs are well under 1 MB.
- * - Validates by constructing a Typeface; rejects unloadable files.
- * - Writes to `.tmp` then renames so a partial copy never wins picker enumeration.
- */
- fun importCustomFont(uri: android.net.Uri): String? {
- val rawName = displayNameOf(uri) ?: return null
- val name = sanitizeFontName(rawName) ?: return null
- val tmp = java.io.File(userFontsDir, "$name.ttf.tmp")
- val dest = java.io.File(userFontsDir, "$name.ttf")
- return try {
- context.contentResolver.openInputStream(uri).use { input ->
- if (input == null) return null
- tmp.outputStream().use { out ->
- val maxBytes = 16L * 1024 * 1024
- val buf = ByteArray(8192)
- var written = 0L
- while (true) {
- val n = input.read(buf)
- if (n <= 0) break
- written += n
- if (written > maxBytes) return cleanup(tmp, null)
- out.write(buf, 0, n)
- }
- }
- }
- // Validate by trying to load it.
- val tf = runCatching { Typeface.createFromFile(tmp) }.getOrNull()
- if (tf == null || tf === Typeface.DEFAULT) return cleanup(tmp, null)
- // Atomic-ish swap.
- if (dest.exists()) dest.delete()
- if (!tmp.renameTo(dest)) return cleanup(tmp, null)
- // Invalidate the asset-cache copy in case a bundled font of the same
- // name was previously loaded — next loadFont() should see the new file.
- java.io.File(context.cacheDir, "font_$name.ttf").delete()
- name
- } catch (_: Exception) {
- cleanup(tmp, null)
- }
- }
-
- /** Remove a previously-imported custom font. Returns true if it existed and was removed. */
- fun deleteCustomFont(name: String): Boolean {
- val f = java.io.File(userFontsDir, "$name.ttf")
- val ok = f.exists() && f.delete()
- if (ok) java.io.File(context.cacheDir, "font_$name.ttf").delete()
- return ok
- }
-
- private fun <T> cleanup(tmp: java.io.File, result: T?): T? {
- runCatching { if (tmp.exists()) tmp.delete() }
- return result
- }
-
- private fun displayNameOf(uri: android.net.Uri): String? = runCatching {
- context.contentResolver.query(
- uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null
- )?.use { if (it.moveToFirst()) it.getString(0) else null }
- }.getOrNull()
-
- private fun sanitizeFontName(filename: String): String? {
- val base = filename.substringBeforeLast('.').trim()
- val safe = base.replace(Regex("[^A-Za-z0-9_-]"), "-").trim('-').take(48)
- return safe.takeIf { it.isNotEmpty() }
- }
-
- private fun parseColor(hex: String): Int {
- val clean = hex.removePrefix("#")
- return when (clean.length) {
- 3 -> {
- val r = clean[0].digitToIntOrNull(16) ?: return android.graphics.Color.BLACK
- val g = clean[1].digitToIntOrNull(16) ?: return android.graphics.Color.BLACK
- val b = clean[2].digitToIntOrNull(16) ?: return android.graphics.Color.BLACK
- android.graphics.Color.rgb(r * 17, g * 17, b * 17)
- }
- 6 -> {
- android.graphics.Color.rgb(
- clean.substring(0, 2).toInt(16),
- clean.substring(2, 4).toInt(16),
- clean.substring(4, 6).toInt(16)
- )
- }
- 8 -> {
- android.graphics.Color.argb(
- clean.substring(0, 2).toInt(16),
- clean.substring(2, 4).toInt(16),
- clean.substring(4, 6).toInt(16),
- clean.substring(6, 8).toInt(16)
- )
- }
- else -> android.graphics.Color.BLACK
- }
- }
+ /** Remove a previously-imported custom font. See [TerminalAppearanceStore.deleteCustomFont]. */
+ fun deleteCustomFont(name: String): Boolean = appearanceStore.deleteCustomFont(name)
var session: TerminalSession? = null
private set
diff --git a/app/src/test/java/com/excp/podroid/ui/screens/terminal/TerminalThemeParsingTest.kt b/app/src/test/java/com/excp/podroid/ui/screens/terminal/TerminalThemeParsingTest.kt
new file mode 100644
index 0000000..6963b37
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/ui/screens/terminal/TerminalThemeParsingTest.kt
@@ -0,0 +1,81 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.ui.screens.terminal
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class TerminalThemeParsingTest {
+
+ private val validToml = """
+ [colors.primary]
+ background = "#101010"
+ foreground = "#e0e0e0"
+
+ [colors.normal]
+ black = "#000000"
+ red = "#ff0000"
+ green = "#00ff00"
+ yellow = "#ffff00"
+ blue = "#0000ff"
+ magenta = "#ff00ff"
+ cyan = "#00ffff"
+ white = "#ffffff"
+
+ [colors.bright]
+ black = "#111111"
+ red = "#ff1111"
+ green = "#11ff11"
+ yellow = "#ffff11"
+ blue = "#1111ff"
+ magenta = "#ff11ff"
+ cyan = "#11ffff"
+ white = "#eeeeee"
+ """.trimIndent()
+
+ @Test fun `minimal valid toml parses background foreground and ansi colors`() {
+ val parsed = parseAlacrittyToml(validToml)
+ assertEquals("#101010", parsed?.get("background"))
+ assertEquals("#e0e0e0", parsed?.get("foreground"))
+ assertEquals("#000000", parsed?.get("color0"))
+ assertEquals("#ffffff", parsed?.get("color7"))
+ }
+
+ @Test fun `missing background returns null`() {
+ val toml = validToml.replace("background = \"#101010\"\n", "")
+ assertNull(parseAlacrittyToml(toml))
+ }
+
+ @Test fun `missing a normal color returns null`() {
+ val toml = validToml.replace("white = \"#ffffff\"\n", "")
+ assertNull(parseAlacrittyToml(toml))
+ }
+
+ @Test fun `bright colors mapped to color8 through color15`() {
+ val parsed = parseAlacrittyToml(validToml)
+ assertEquals("#111111", parsed?.get("color8"))
+ assertEquals("#ff1111", parsed?.get("color9"))
+ assertEquals("#eeeeee", parsed?.get("color15"))
+ }
+
+ @Test fun `parseHexColor expands 3-digit hex by x17`() {
+ // r=0, g=15*17=255, b=8*17=136
+ assertEquals(0xFF00FF88.toInt(), parseHexColor("#0f8"))
+ }
+
+ @Test fun `parseHexColor reads 6-digit hex as rgb`() {
+ assertEquals(0xFF112233.toInt(), parseHexColor("#112233"))
+ }
+
+ @Test fun `parseHexColor reads 8-digit hex as aarrggbb`() {
+ assertEquals(0x80112233.toInt(), parseHexColor("#80112233"))
+ }
+
+ @Test fun `parseHexColor falls back to black on junk input`() {
+ assertEquals(0xFF000000.toInt(), parseHexColor("#zzz"))
+ assertEquals(0xFF000000.toInt(), parseHexColor("#12"))
+ }
+}