diff --git a/.fdroid/com.redtermapp.yml b/.fdroid/com.redtermapp.yml
index dd30c4b..167a4f7 100644
--- a/.fdroid/com.redtermapp.yml
+++ b/.fdroid/com.redtermapp.yml
@@ -6,7 +6,7 @@ License: GPL-3.0-or-later
WebSite: https://github.com/GlobalTechInfo/RedTerm
SourceCode: https://github.com/GlobalTechInfo/RedTerm
IssueTracker: https://github.com/GlobalTechInfo/RedTerm/issues
-Changelog: https://github.com/GlobalTechInfo/RedTerm/blob/v2.4.0/CHANGELOG.md
+Changelog: https://github.com/GlobalTechInfo/RedTerm/blob/v2.5.0/CHANGELOG.md
Description: |
RedTerm is a full terminal environment for Android. It installs real Linux
@@ -15,7 +15,7 @@ Description: |
Included:
- * 20 Linux distributions: Alpine, Debian, Ubuntu, Kali, Fedora, Rocky,
+ * 20+ Linux distributions: Alpine, Debian, Ubuntu, Kali, Fedora, Rocky,
AlmaLinux, Void, Arch, Manjaro and openSUSE, for arm64-v8a, armeabi-v7a,
x86_64 and x86.
* A built-in OpenSSH client and server, so you can reach a machine over SSH
@@ -33,9 +33,9 @@ Description: |
# Screenshots are referenced by URL from the release tag, so no copies live in
# the repository and nothing has to be duplicated or rewritten.
Screenshots:
- - 1: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.4.0/screenshots/home.jpg
- - 2: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.4.0/screenshots/main.jpg
- - 3: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.4.0/screenshots/terminal.jpg
- - 4: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.4.0/screenshots/sessions.jpg
- - 5: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.4.0/screenshots/settings.jpg
- - 6: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.4.0/screenshots/notification.jpg
+ - 1: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.5.0/screenshots/home.jpg
+ - 2: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.5.0/screenshots/main.jpg
+ - 3: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.5.0/screenshots/terminal.jpg
+ - 4: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.5.0/screenshots/sessions.jpg
+ - 5: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.5.0/screenshots/settings.jpg
+ - 6: https://raw.githubusercontent.com/GlobalTechInfo/RedTerm/v2.5.0/screenshots/notification.jpg
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e95022..4adf570 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,62 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [v2.5.0]
+
+### Added
+
+- **Amazon and NixOS added to the catalogue**: images built by the rootfs-images pipeline,
+ installable from the Welcome screen, each with its own icon.
+- **NixOS ships nix itself, so a session installs packages over the network**: the image
+ keeps the nix tool family and the nixpkgs registry source, and `nix profile install
+ nixpkgs#nodejs`, `nix shell nixpkgs#git` and `nix run nixpkgs#hello` substitute from
+ cache.nixos.org into the session's writable store. The base tools move with a newer
+ image; in-session installs do not.
+- **The nixpkgs channel is registered on the live alias**: the image's channel table
+ points at nixpkgs-unstable, because the nixpkgs-26.05 alias no longer resolves.
+ The classic channel *update* (the nix-channel/nix-env unpack) cannot finish under
+ proot — it is nix's own privileged unpack step, and a proot session cannot satisfy
+ it — so the registry commands above are the supported install path, and the table's
+ job is environment completeness, not update-ability.
+- **Named the CA bundle, so HTTPS verifies**: the store's openssl was built against a
+ prefix the image prune removes, so its compiled-in certificate paths were dead and
+ standalone `curl` and `git` over HTTPS failed verification (curl rc=60), measured.
+ The session now exports `CURL_CA_BUNDLE` and `SSL_CERT_FILE` to the kept nss-cacert
+ bundle; HTTPS works without anything else.
+
+- **Custom distro installer**: install a distro from a tarball, a URL, or a Docker/OCI image,
+ instead of only the catalogue. Reached from the Welcome screen, the Distro dashboard, and
+ Settings → More tools. Registry images are pulled through the registry-v2 flow (anonymous
+ token, per-arch manifest selection) and the layers unpacked in order; the compression of a
+ file or URL is read from its own magic bytes, never the extension.
+- **Mosh reachability probe**: when a mosh session produces no output, probe whether the host's
+ UDP port is actually reachable, so a blocked-UDP path is told apart from "the server has no
+ mosh" and a working tunnel is suggested.
+- **Recording GIF export and playback speed**: export a session recording to GIF, and step the
+ player through 0.5×/1×/2×/4×.
+- **Workspace pin and split-open**: pin a workspace to the home screen, and open a two-session
+ workspace straight into a split pane.
+- **Scheduled job history and backoff**: each job shows its recent runs (with an output tail in
+ the notification), and consecutive failures back off the next retry before it gives up.
+- **Workspaces**: bundled shells, servers, theme and snippets that open in one tap (Settings → More tools → Workspaces).
+- **Startup-hook GUI**: edit the guest startup hook written into a distro (Settings → More tools → Startup hook).
+- **Snippet library**: save commands and paste them into any session (Settings → More tools → Snippets).
+- **Distro dashboard**: per-distro version, size, updates and disk (Settings → More tools → Distro dashboard).
+- **SSH tunnel manager**: open and close standalone `ssh -N` tunnels that keep a server's saved
+ forwards open with no terminal in front of them. Reached from the SSH screen.
+- **SFTP transfer queue**: parallel, resumable SFTP transfers. Reached from the SFTP browser's menu.
+- **Scheduled guest jobs**: run guest commands on a schedule (Settings → More tools → Scheduled jobs).
+- **Local port forward**: open device ports that reach a target, any number at once and across
+ any servers. A target is either the device itself (a guest service bound to `127.0.0.1` in a
+ proot distro) or a saved SSH server, in which case the forward rides `ssh -N -L` and the
+ remote host:port is reached through the connection. Reached from the SSH screen.
+- **Recording index**: recordings are listed newest-first and searchable on the Recordings screen.
+- **Settings**: eight feature rows consolidated into a single "More tools" hub.
+
+### Fixed
+
+- **RedTerm:API bridge stop**: the redterm-api listener stops cleanly when a session ends instead of lingering.
+
## [v2.4.0]
### Added
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index acc6758..2d52c37 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -14,8 +14,8 @@ android {
applicationId = "com.redtermapp"
minSdk = 24
targetSdk = 37
- versionCode = 8
- versionName = "2.4.0"
+ versionCode = 9
+ versionName = "2.5.0"
}
signingConfigs {
@@ -53,6 +53,10 @@ android {
abortOnError = true
warningsAsErrors = false
checkDependencies = true
+ // UseKtx is a false positive on Bitmap.createBitmap (the GIF exporter's
+ // only use of it): there is no KTX equivalent for that static factory,
+ // so the rule just manufactures a warning it cannot actually be fixed.
+ disable += "UseKtx"
}
packaging {
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 3fd6388..8838e2e 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -147,6 +147,56 @@
android:theme="@style/Theme.RedTermApp"
android:windowSoftInputMode="adjustResize" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Unit
) = withContext(Dispatchers.IO) {
- extractTarball(tarball, dest) { progress -> onProgress("${progress.percent}%") }
+ extractTarball(tarball, dest, { progress -> onProgress("${progress.percent}%") })
}
- private suspend fun extractTarball(
+ /**
+ * Extract a tarball whose compression is not known in advance, by its magic
+ * bytes. The shipped images are all xz, but a local file the user brings in
+ * may be gzip or uncompressed tar, and opening it as xz reads every entry as
+ * garbage. [TarballFormat.detect] picks the wrapper; xz keeps its native
+ * fast path and the rest stream through the JVM.
+ */
+ private suspend fun extractTarballAuto(
tarball: File,
dest: File,
onProgress: (Progress) -> Unit
+ ) = withContext(Dispatchers.IO) {
+ // These sources (a registry layer, a URL tarball, a picked file) are standard
+ // rootfs archives: many top-level directories (bin/, etc/, usr/), never wrapped
+ // in a single directory. The blind prefix-strip off the first entry hoisted the
+ // whole bin/ tree to root and dropped /bin/sh, so stripping is disabled here.
+ // The catalogue path (extractTarball called without this flag) is unchanged.
+ val compression = TarballFormat.detect(TarballFormat.readMagic(tarball))
+ when (compression) {
+ TarballFormat.Compression.XZ -> extractTarball(tarball, dest, onProgress, stripPrefix = false)
+ TarballFormat.Compression.GZIP -> {
+ val total = tarball.length()
+ FileInputStream(tarball).use { fis ->
+ java.util.zip.GZIPInputStream(fis).use { gz ->
+ BufferedInputStream(gz, 65536).use { bis ->
+ TarArchiveInputStream(bis).use { tarIn ->
+ extractTarEntries(tarIn, dest, total, onProgress, stripPrefix = false)
+ }
+ }
+ }
+ }
+ }
+ TarballFormat.Compression.PLAIN -> {
+ val total = tarball.length()
+ FileInputStream(tarball).use { fis ->
+ BufferedInputStream(fis, 65536).use { bis ->
+ TarArchiveInputStream(bis).use { tarIn ->
+ extractTarEntries(tarIn, dest, total, onProgress, stripPrefix = false)
+ }
+ }
+ }
+ }
+ TarballFormat.Compression.UNKNOWN ->
+ throw Exception("This file is not a tarball (not xz, gzip or plain tar).")
+ }
+ }
+
+ /** Where a local-install tarball comes from. */
+ sealed class InstallSource {
+ /** A file the user picked. */
+ data class Local(val uri: android.net.Uri) : InstallSource()
+ /** A tarball hosted somewhere. */
+ data class Url(val url: String) : InstallSource()
+ /** A Docker/OCI image reference, e.g. `ubuntu:22.04`. */
+ data class Registry(val reference: String) : InstallSource()
+ }
+
+ /**
+ * Install a distro from any source the user provides — a picked file, a URL,
+ * or a registry image — instead of the registry's own downloads. The source
+ * decides how the bytes arrive; everything after that is shared: stage to a
+ * file, unpack, record the install. A source that yields bytes that are not
+ * a tarball fails the unpack, not a checksum.
+ */
+ suspend fun installFromSource(
+ name: String,
+ source: InstallSource,
+ onProgress: (String) -> Unit
+ ) = withContext(Dispatchers.IO) {
+ when (source) {
+ is InstallSource.Local -> installFromLocalFile(name, source.uri, onProgress)
+ is InstallSource.Url -> installFromUrl(name, source.url, onProgress)
+ is InstallSource.Registry -> installFromRegistry(name, source.reference, onProgress)
+ }
+ }
+
+ private suspend fun installFromUrl(
+ name: String, url: String, onProgress: (String) -> Unit
+ ) {
+ val key = validateKey(name)
+ prepareFreshRootfs(key, onProgress)
+ val staged = File(tarballDir(), "local-$key.tarball")
+ val partial = File(tarballDir(), "local-$key.tarball.part")
+ onProgress("Downloading $url …")
+ downloadTarball(url, partial, { p -> onProgress("${p.percent}%") })
+ if (!partial.renameTo(staged)) {
+ partial.copyTo(staged, overwrite = true)
+ }
+ partial.delete()
+ onProgress("Extracting…")
+ extractTarballAuto(staged, getRootfsDir(key)) { p -> onProgress("${p.percent}%") }
+ saveInstalled(key)
+ onProgress("Done")
+ }
+
+ private suspend fun installFromRegistry(
+ name: String, reference: String, onProgress: (String) -> Unit
+ ) {
+ val key = validateKey(name)
+ prepareFreshRootfs(key, onProgress)
+ val rootfs = getRootfsDir(key)
+ val layerDir = File(tarballDir(), "registry-$key")
+ val layers = RegistryPuller.pull(reference, deviceAbi, layerDir, onProgress).layers
+ // Unpack in order: a later layer overwrites an earlier file, the way the
+ // registry built the image.
+ layers.forEachIndexed { i, layer ->
+ onProgress("Unpacking layer ${i + 1} of ${layers.size}…")
+ extractTarballAuto(layer, rootfs) { }
+ layer.delete()
+ }
+ layerDir.deleteRecursively()
+ saveInstalled(key)
+ onProgress("Done")
+ }
+
+ private fun validateKey(name: String): String {
+ val key = name.trim().lowercase()
+ require(key.isNotEmpty() && key.matches(Regex("[a-z0-9][a-z0-9._-]{0,31}"))) {
+ "The distro name must be short letters, numbers, dots, dashes or underscores"
+ }
+ return key
+ }
+
+ private fun prepareFreshRootfs(key: String, onProgress: (String) -> Unit) {
+ val rootfsDir = getRootfsDir(key)
+ if (rootfsDir.exists() && !TreeRemoval.remove(rootfsDir)) {
+ throw Exception(
+ "The previous $key installation could not be removed, so a new one " +
+ "cannot be installed over it. Uninstall it first."
+ )
+ }
+ rootfsDir.mkdirs()
+ onProgress("Preparing…")
+ }
+
+ /**
+ * Install a distro from a tarball the user picked, not from the registry:
+ * copy it out of the content resolver, extract it under [name], and record
+ * the install. No download, no sha check against a URL — the file *is* the
+ * image, and a wrong one fails the extraction rather than a checksum.
+ *
+ * [name] is the distro key the session picker and rootfs dir are built from,
+ * so it is validated to safe characters: a key with a slash would escape
+ * the rootfs directory.
+ */
+ suspend fun installFromLocalFile(
+ name: String,
+ uri: android.net.Uri,
+ onProgress: (String) -> Unit
+ ) = withContext(Dispatchers.IO) {
+ val key = validateKey(name)
+ prepareFreshRootfs(key, onProgress)
+ onProgress("Copying the file…")
+ val staged = File(tarballDir(), "local-$key.tarball")
+ context.contentResolver.openInputStream(uri).use { input ->
+ if (input == null) throw Exception("Could not read the chosen file.")
+ input.copyTo(staged.outputStream())
+ }
+ if (staged.length() == 0L) throw Exception("The chosen file is empty.")
+ onProgress("Extracting…")
+ extractTarballAuto(staged, getRootfsDir(key)) { p -> onProgress("${p.percent}%") }
+ saveInstalled(key)
+ onProgress("Done")
+ }
+
+ private suspend fun extractTarball(
+ tarball: File,
+ dest: File,
+ onProgress: (Progress) -> Unit,
+ stripPrefix: Boolean = true
) = withContext(Dispatchers.IO) {
val nativeXz = getNativeXz()
if (nativeXz != null) {
try {
- extractWithNativeXz(nativeXz, tarball, dest, onProgress)
+ extractWithNativeXz(nativeXz, tarball, dest, onProgress, stripPrefix)
} catch (e: CancelledException) {
throw e
} catch (e: Exception) {
Log.w("DistroInstaller", "Native xz failed, falling back to Java", e)
- extractWithJavaXz(tarball, dest, onProgress)
+ extractWithJavaXz(tarball, dest, onProgress, stripPrefix)
}
} else {
- extractWithJavaXz(tarball, dest, onProgress)
+ extractWithJavaXz(tarball, dest, onProgress, stripPrefix)
}
}
private fun extractWithNativeXz(
xzBin: File, tarball: File, dest: File,
- onProgress: (Progress) -> Unit
+ onProgress: (Progress) -> Unit, stripPrefix: Boolean = true
) {
val pb = ProcessBuilder(xzBin.absolutePath, "-dc", tarball.absolutePath)
pb.environment()["LD_LIBRARY_PATH"] = xzBin.parentFile!!.absolutePath
@@ -614,7 +780,7 @@ class DistroInstaller(private val context: Context) {
process.inputStream.use { input ->
BufferedInputStream(input, 65536).use { bis ->
TarArchiveInputStream(bis).use { tarIn ->
- extractTarEntries(tarIn, dest, tarball.length(), onProgress)
+ extractTarEntries(tarIn, dest, tarball.length(), onProgress, stripPrefix)
}
}
}
@@ -640,7 +806,7 @@ class DistroInstaller(private val context: Context) {
private fun extractWithJavaXz(
tarball: File, dest: File,
- onProgress: (Progress) -> Unit
+ onProgress: (Progress) -> Unit, stripPrefix: Boolean = true
) {
try {
val total = tarball.length()
@@ -649,7 +815,7 @@ class DistroInstaller(private val context: Context) {
XZCompressorInputStream(fis).use { xzIn ->
BufferedInputStream(xzIn, 65536).use { bis ->
TarArchiveInputStream(bis).use { tarIn ->
- extractTarEntries(tarIn, dest, total, onProgress)
+ extractTarEntries(tarIn, dest, total, onProgress, stripPrefix)
}
}
}
@@ -661,11 +827,13 @@ class DistroInstaller(private val context: Context) {
private fun extractTarEntries(
tarIn: TarArchiveInputStream, dest: File,
- totalCompressed: Long, onProgress: (Progress) -> Unit
+ totalCompressed: Long, onProgress: (Progress) -> Unit,
+ stripPrefix: Boolean = true
) = RootfsInstallExtractor.extract(
tarIn, dest, totalCompressed, ::checkCancel,
{ pct -> onProgress(Progress(pct, "Extracting")) },
- { message -> Log.i("DistroInstaller", message) }
+ { message -> Log.i("DistroInstaller", message) },
+ stripPrefix = stripPrefix
).also {
// Reported, because an unapplied mode is silent until a package manager
// mentions it several sessions later and names only the directory.
diff --git a/app/src/main/java/com/redtermapp/distro/DistroOsRelease.kt b/app/src/main/java/com/redtermapp/distro/DistroOsRelease.kt
new file mode 100644
index 0000000..2aa2395
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/distro/DistroOsRelease.kt
@@ -0,0 +1,47 @@
+package com.redtermapp.distro
+
+import java.io.File
+
+/**
+ * Reads the version a distro reports about itself, from the /etc/os-release
+ * inside its rootfs — the same file `cat /etc/os-release` shows, so the
+ * dashboard's "version" matches what the user sees in the shell.
+ *
+ * The parse is pure (a map of the file's text) and unit-tested; only the file
+ * read needs the device. Quoted and bare KEY=VALUE forms are both handled,
+ * and comment/blank lines are ignored, which is the shape every distro ships.
+ */
+object DistroOsRelease {
+
+ fun parse(text: String): Map {
+ val out = LinkedHashMap()
+ for (raw in text.lineSequence()) {
+ val line = raw.trim()
+ if (line.isEmpty() || line.startsWith("#")) continue
+ val eq = line.indexOf('=')
+ if (eq <= 0) continue
+ val key = line.substring(0, eq).trim()
+ var value = line.substring(eq + 1).trim()
+ if (value.length >= 2 && (value.startsWith("\"") || value.startsWith("'")) &&
+ value.endsWith(value.first())
+ ) {
+ value = value.substring(1, value.length - 1)
+ }
+ out[key] = value
+ }
+ return out
+ }
+
+ /** The version string to show: VERSION_ID, falling back to VERSION, then blank. */
+ fun versionOf(fields: Map): String =
+ fields["VERSION_ID"]?.takeIf { it.isNotEmpty() }
+ ?: fields["VERSION"]?.takeIf { it.isNotEmpty() }
+ ?: ""
+
+ /** Read and parse a distro's /etc/os-release; empty when the file is missing. */
+ fun read(rootfsDir: File): Map {
+ val f = File(rootfsDir, "etc/os-release")
+ return if (f.isFile) runCatching { parse(f.readText()) }.getOrNull() ?: emptyMap()
+ else emptyMap()
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/distro/DistroRegistry.kt b/app/src/main/java/com/redtermapp/distro/DistroRegistry.kt
index 8f88571..3aa6b66 100644
--- a/app/src/main/java/com/redtermapp/distro/DistroRegistry.kt
+++ b/app/src/main/java/com/redtermapp/distro/DistroRegistry.kt
@@ -63,6 +63,19 @@ object DistroRegistry {
installSizeMb = 13,
packageManager = "apk"
),
+ Distro(
+ name = "amazonlinux",
+ displayName = "Amazon",
+ description = "Amazon's next-generation Linux (the 2027 line); dnf.",
+ baseUrl = "https://github.com/GlobalTechInfo/rootfs-images/releases/download/v1.0.0/amazonlinux-{arch}-rt-v1.0.0.tar.xz",
+ sha256 = mapOf(
+ "aarch64" to "a565f6e2aa6816b466f4da0727d95152608b5e6e97097f34c6dfec6aadf9366d",
+ "x86_64" to "c0a706a5dc17a7487a35da33d6d7530375115df27d5ece30179ec38fb8892b7a"
+ ),
+ prootArchs = listOf("aarch64", "x86_64"),
+ installSizeMb = 200,
+ packageManager = "dnf"
+ ),
Distro(
name = "arch",
displayName = "Arch",
@@ -173,6 +186,19 @@ object DistroRegistry {
installSizeMb = 608,
packageManager = "pacman"
),
+ Distro(
+ name = "nixos",
+ displayName = "NixOS",
+ description = "Functional Linux, config-as-code; its tools ship in an immutable store.",
+ baseUrl = "https://github.com/GlobalTechInfo/rootfs-images/releases/download/v1.0.0/nixos-{arch}-rt-v1.0.0.tar.xz",
+ sha256 = mapOf(
+ "aarch64" to "a14d43f427ca1aba5c25210c57128888b4be592c2ebb85d5b1ee2b3023bd1fa7",
+ "x86_64" to "ade8e72ec2ccf2df3e65a74de13fc7e042113afc6821c47e0186db456f4c8e15"
+ ),
+ prootArchs = listOf("aarch64", "x86_64"),
+ installSizeMb = 1600,
+ packageManager = "nix"
+ ),
Distro(
name = "opensuse",
displayName = "openSUSE",
diff --git a/app/src/main/java/com/redtermapp/distro/DistroSetup.kt b/app/src/main/java/com/redtermapp/distro/DistroSetup.kt
index 62ca453..61388ed 100644
--- a/app/src/main/java/com/redtermapp/distro/DistroSetup.kt
+++ b/app/src/main/java/com/redtermapp/distro/DistroSetup.kt
@@ -12,8 +12,8 @@ object DistroSetup {
/** Every key plan() can return. Anything else gets the empty fallback. */
val KNOWN = setOf(
"alpine", "debian", "ubuntu", "kali", "void", "fedora", "rocky", "almalinux",
- "arch", "armtix", "manjaro", "opensuse", "oracle",
- "pardus", "parrot", "trisquel", "slackware"
+ "arch", "armtix", "manjaro", "opensuse", "oracle", "amzn",
+ "pardus", "parrot", "trisquel", "slackware", "nixos"
)
/**
@@ -58,6 +58,11 @@ object DistroSetup {
// whose baseurls are yum$ociregion.$ocidomain and resolve to nothing outside
// Oracle Cloud, and the session then fell back to whatever it could reach.
"ol", "oracle" -> "oracle"
+ // Amazon Linux 2 reports ID="amzn" (2023 reports "amzn2"). It is a RHEL-family
+ // dnf distro whose own amzn2-* repositories are correct for it, so it gets
+ // its own key: the plan drives dnf but injects no repositories, instead of
+ // being mis-read as fedora through its ID_LIKE="centos rhel fedora" line.
+ "amzn2", "amzn2023", "amazon", "amazonlinux", "amazon-linux" -> "amzn"
else -> when {
key.startsWith("debian") -> "debian"
key.startsWith("opensuse") -> "opensuse"
@@ -605,6 +610,21 @@ object DistroSetup {
"dnf install -y", "-q",
rhelReposOracle(), "", ""
)
+ // Amazon Linux 2027 (the image RedTerm ships) is dnf-only and carries
+ // no repository of its own beyond the al2027 mirrorlist it ships
+ // with: RedTerm injects nothing and deletes nothing, so the repos
+ // element is empty. Treating it as fedora (its ID_LIKE line says
+ // fedora) is what once deleted those repositories and wrote dead
+ // mirrors.kernel.org Fedora URLs into the image. This line is the
+ // bash-rescue path only, and the image ships bash, so it normally
+ // never runs. dnf takes no -q: measured "Unknown option -q", so the
+ // quiet slot is empty, not a flag dnf would reject.
+ "amzn" -> listOf("dnf install -y", "", "", "", "")
+ // NixOS: the tools ship inside the immutable store, the image carries
+ // no channel closure, so there is nothing first start can or should
+ // install. Explicit no-op, not the empty fallback: the fallback is what
+ // an unrecognised ID gets, and this one is recognised.
+ "nixos" -> listOf(":", "", "", "", "")
"void" -> listOf("xbps-install -S", "", xbpsDirs, "", "")
// Adelie and Chimera are apk like Alpine but their images already ship a working
// bash, so they fall through to the empty plan below rather than running apk at all.
@@ -669,12 +689,21 @@ object DistroSetup {
// Overwrites the real sudo: it relies on setuid/setgroups behaviour proot
// cannot emulate and segfaults, and proot already runs as root, so the
// package buys nothing.
+ // The shim has to land in every bin directory that actually exists and
+ // is writable, not only /usr/bin: NixOS has no /usr at all, its /bin and
+ // /sbin are farm links into the store, and its session PATH puts /sbin
+ // before /bin, so a shim in one of them still loses to the real PAM
+ // sudo in the other. rm -f first, because a store-carried sudo is a
+ // read-only file that cannot be overwritten in place.
private const val SUDO_SHIM =
- " printf '%s\\n' '#!/bin/sh' " +
- "'# RedTerm: proot already runs as root, so sudo just runs the command.' " +
- "'while [ \$# -gt 0 ]; do case \"\$1\" in -*) shift ;; *) break ;; esac; done' " +
- "'if [ \$# -eq 0 ]; then exec /bin/sh; fi' 'exec \"\$@\"' " +
- "> /usr/bin/sudo; chmod 755 /usr/bin/sudo\n"
+ " for _d in /bin /usr/bin /sbin /usr/sbin; do " +
+ "if [ -d \"\$_d\" ] && [ -w \"\$_d\" ]; then " +
+ "rm -f \"\$_d/sudo\" 2>/dev/null; " +
+ "printf '%s\\n' '#!/bin/sh' " +
+ "'# RedTerm: proot already runs as root, so sudo just runs the command.' " +
+ "'while [ \$# -gt 0 ]; do case \"\$1\" in -*) shift ;; *) break ;; esac; done' " +
+ "'if [ \$# -eq 0 ]; then exec /bin/sh; fi' 'exec \"\$@\"' " +
+ "> \"\$_d/sudo\" 2>/dev/null && chmod 755 \"\$_d/sudo\"; fi; done\n"
/**
* Identifies the plan a given install has already run.
diff --git a/app/src/main/java/com/redtermapp/distro/PackageUpdater.kt b/app/src/main/java/com/redtermapp/distro/PackageUpdater.kt
index 843b9bc..98eaf3e 100644
--- a/app/src/main/java/com/redtermapp/distro/PackageUpdater.kt
+++ b/app/src/main/java/com/redtermapp/distro/PackageUpdater.kt
@@ -36,7 +36,12 @@ object PackageUpdater {
private fun packageManagerFromName(name: String): String = when (name.lowercase()) {
"alpine" -> "apk"
"arch", "manjaro" -> "pacman"
- "fedora", "rocky", "almalinux" -> "dnf"
+ "fedora", "rocky", "almalinux", "amazonlinux" -> "dnf"
+ // The nix store ships its tools; there is no channel closure in the
+ // image, so there is nothing nix can fetch or install offline. It is
+ // mapped to a name, not "unknown": the activity shows a dedicated
+ // no-updates explanation instead of "could not detect a manager".
+ "nixos" -> "nix"
"opensuse" -> "zypper"
"void" -> "xbps"
"debian", "ubuntu", "kali", "pardus", "parrot", "trisquel" -> "apt"
@@ -78,6 +83,11 @@ object PackageUpdater {
"slackpkg -batch=on -default_answer=yes update && " +
"slackpkg -batch=on -default_answer=yes upgrade-all"
)
+ // The command is empty and the activity refuses to run it: the store is
+ // immutable and carries no channel closure, so an "update" here would
+ // fetch a whole nixpkgs evaluation the image was deliberately built
+ // without. A newer image is the update path.
+ "nix" -> Plan("nix", "")
else -> Plan("unknown", "")
}
}
diff --git a/app/src/main/java/com/redtermapp/distro/RegistryPuller.kt b/app/src/main/java/com/redtermapp/distro/RegistryPuller.kt
new file mode 100644
index 0000000..ba40aa4
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/distro/RegistryPuller.kt
@@ -0,0 +1,189 @@
+package com.redtermapp.distro
+
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+import java.net.HttpURLConnection
+import java.net.URL
+import java.net.URLEncoder
+
+/**
+ * Pulls the layers of a Docker/OCI image so a distro can be installed from a
+ * registry reference.
+ *
+ * A registry image is not one tarball: it is an ordered set of layer blobs,
+ * each a (usually gzip) tar, that must be unpacked in sequence — a later
+ * layer overwrites an earlier file. This client fetches the manifest, picks
+ * the entry that matches the device's architecture when the image is a
+ * multi-arch list, and downloads the layers in order to files the installer
+ * then unpacks one by one.
+ *
+ * Only the pure reference parsing and platform choice are unit-tested; the
+ * network here is a thin, well-known registry v2 flow (anonymous token, then
+ * bearer) and is verified on a real device, the way every other network path
+ * in this app is.
+ */
+object RegistryPuller {
+
+ data class Result(val layers: List)
+
+ /** The layer blobs of [reference] for [abi], in unpack order. */
+ fun pull(
+ reference: String,
+ abi: String,
+ outDir: File,
+ onProgress: (String) -> Unit
+ ): Result {
+ val parsed = RegistryRef.parse(reference)
+ val manifestArch = RegistryRef.manifestArchForAbi(abi)
+ outDir.mkdirs()
+
+ // 1. The manifest, with a token if the registry challenges for one.
+ val manifestBase = "https://${parsed.host}/v2/${parsed.repoPath}/manifests/"
+ var token = ""
+ val first = fetchManifest(manifestBase + parsed.tag, token, parsed)
+ var manifestCode = first.first
+ var manifest: JSONObject? = first.second
+ if (manifest == null) {
+ token = acquireToken(parsed)
+ val retry = fetchManifest(manifestBase + parsed.tag, token, parsed)
+ manifestCode = retry.first
+ manifest = retry.second
+ }
+ if (manifest == null) {
+ throw Exception("Could not read the image manifest for $reference (HTTP $manifestCode).")
+ }
+
+ // 2. A manifest list points at one manifest per architecture; take ours.
+ val mediaType = manifest.optString(
+ "mediaType", "application/vnd.docker.distribution.manifest.v2+json"
+ )
+ val isList = mediaType.endsWith("manifest.list.v2+json") ||
+ mediaType.endsWith("image.index.v1+json")
+ val layersJson = if (isList) {
+ val index = manifest.getJSONArray("manifests")
+ var pick = JSONObject(index.getJSONObject(0).toString())
+ for (i in 0 until index.length()) {
+ val m = JSONObject(index.getJSONObject(i).toString())
+ val arch = m.optJSONObject("platform")?.optString("architecture", "") ?: ""
+ if (RegistryRef.isMatchingArch(arch, manifestArch)) { pick = m; break }
+ }
+ val digest = pick.getString("digest")
+ val (subCode, sub) = fetchManifest(manifestBase + digest, token, parsed)
+ if (sub == null) {
+ throw IllegalStateException("Could not read the per-arch manifest for $reference (HTTP $subCode).")
+ }
+ sub.getJSONArray("layers")
+ } else {
+ manifest.getJSONArray("layers")
+ }
+
+ // 3. The blobs, in unpack order.
+ onProgress("Downloading image layers…")
+ val blobs = ArrayList(layersJson.length())
+ for (i in 0 until layersJson.length()) {
+ val digest = layersJson.getJSONObject(i).getString("digest")
+ val target = File(outDir, "layer-$i")
+ if (!target.exists() || target.length() == 0L) {
+ val blobUrl = "https://${parsed.host}/v2/${parsed.repoPath}/blobs/$digest"
+ check(downloadToFile(blobUrl, token, target)) {
+ "Could not download layer $i of the image."
+ }
+ }
+ blobs.add(target)
+ }
+ return Result(blobs)
+ }
+
+ private fun fetchManifest(
+ url: String, token: String, parsed: RegistryRef.Parsed
+ ): Pair {
+ val resp = get(url, acceptedMediaTypes(), token)
+ if (resp.code != 200) return resp.code to null
+ return resp.code to runCatching { JSONObject(String(resp.body)) }.getOrNull()
+ }
+
+ /** Ask the realm a 401 names for an anonymous pull token. */
+ private fun acquireToken(parsed: RegistryRef.Parsed): String {
+ val conn = openConnection("https://${parsed.host}/v2/")
+ try {
+ val code = conn.responseCode
+ if (code != 401) return ""
+ val challenge = conn.getHeaderField("WWW-Authenticate") ?: return ""
+ if (!challenge.startsWith("Bearer")) return ""
+ // The scheme prefix "Bearer " is glued to the first key ("Bearer realm=..."),
+ // so it must be removed before splitting: otherwise the realm is never found
+ // and no token is ever requested, leaving the manifest on a permanent 401.
+ val params = challenge.removePrefix("Bearer").trim().split(',')
+ fun param(key: String): String? =
+ params.firstOrNull { it.trim().startsWith("$key=") }
+ ?.substringAfter("=")
+ ?.trim()
+ ?.removeSurrounding("\"")
+ val realm = param("realm") ?: return ""
+ val service = param("service") ?: parsed.host
+ val scope = param("scope") ?: "repository:${parsed.repoPath}:pull"
+ val tokenUrl = "$realm?service=${URLEncoder.encode(service, "UTF-8")}" +
+ "&scope=${URLEncoder.encode(scope, "UTF-8")}"
+ val resp = get(tokenUrl, emptyMap(), "")
+ if (resp.code != 200) return ""
+ val body = runCatching { JSONObject(String(resp.body)) }.getOrNull() ?: return ""
+ val t = body.optString("token")
+ return if (t.isNotEmpty()) t else body.optString("access_token")
+ } catch (_: Exception) {
+ return ""
+ } finally {
+ conn.disconnect()
+ }
+ }
+
+ private fun acceptedMediaTypes(): Map = mapOf(
+ "Accept" to "application/vnd.oci.image.index.v1+json, " +
+ "application/vnd.docker.distribution.manifest.list.v2+json, " +
+ "application/vnd.oci.image.manifest.v1+json, " +
+ "application/vnd.docker.distribution.manifest.v2+json"
+ )
+
+ private data class Small(val code: Int, val body: ByteArray)
+
+ private fun get(url: String, headers: Map, token: String): Small {
+ val conn = openConnection(url)
+ headers.forEach { (k, v) -> conn.setRequestProperty(k, v) }
+ if (token.isNotEmpty()) conn.setRequestProperty("Authorization", "Bearer $token")
+ val code = conn.responseCode
+ val stream = if (code in 200..299) conn.inputStream else conn.errorStream
+ val body = stream?.use { it.readBytes() } ?: ByteArray(0)
+ conn.disconnect()
+ return Small(code, body)
+ }
+
+ private fun downloadToFile(url: String, token: String, target: File): Boolean {
+ val conn = openConnection(url)
+ if (token.isNotEmpty()) conn.setRequestProperty("Authorization", "Bearer $token")
+ val code = conn.responseCode
+ if (code != 200) {
+ conn.disconnect()
+ target.delete()
+ return false
+ }
+ target.parentFile?.mkdirs()
+ var ok = true
+ target.outputStream().use { out ->
+ try {
+ conn.inputStream.use { it.copyTo(out) }
+ } catch (_: Exception) {
+ ok = false
+ }
+ }
+ conn.disconnect()
+ if (!ok) target.delete()
+ return ok
+ }
+
+ private fun openConnection(url: String): HttpURLConnection {
+ val conn = URL(url).openConnection() as HttpURLConnection
+ conn.connectTimeout = 30000
+ conn.readTimeout = 120000
+ return conn
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/distro/RegistryRef.kt b/app/src/main/java/com/redtermapp/distro/RegistryRef.kt
new file mode 100644
index 0000000..59f4962
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/distro/RegistryRef.kt
@@ -0,0 +1,68 @@
+package com.redtermapp.distro
+
+/**
+ * A Docker/OCI image reference: `registry/repo[:tag]`, the same grammar registries
+ * accept.
+ *
+ * The default registry is docker.io and the default tag is `latest`, both the way
+ * every registry client resolves an unqualified `ubuntu:22.04` to
+ * `registry-1.docker.io/v2/library/ubuntu/manifests/22.04`. The parsing and the
+ * platform choice are pure, so they are unit-tested: a reference that resolves to
+ * the wrong manifest is a wrong image, and a manifest-list that picks the wrong
+ * architecture is an image that cannot start.
+ */
+object RegistryRef {
+
+ data class Parsed(
+ val registry: String,
+ val repo: String,
+ val tag: String
+ ) {
+ /** The repository path as a registry addresses it: `library/ubuntu` for `ubuntu`. */
+ val repoPath: String get() = if (repo.contains('/')) repo else "library/$repo"
+
+ /** The registry host that actually serves this repository. */
+ val host: String get() = if (registry == "docker.io") "registry-1.docker.io" else registry
+ }
+
+ /**
+ * Split a reference into registry / repository / tag.
+ *
+ * A registry is the first component only when it looks like a host — it has a
+ * dot, is `localhost`, or carries a port. Everything else before a `/` is the
+ * repository, and docker.io is the implicit home for single-component names.
+ */
+ fun parse(reference: String): Parsed {
+ val ref = reference.trim().ifEmpty { throw IllegalArgumentException("empty image reference") }
+ // strip any digest; we pull by tag only
+ val noDigest = ref.substringBefore('@')
+ val slashIdx = noDigest.indexOf('/')
+ // A registry host only appears before a repository, i.e. with a slash in it:
+ // `host/repo`. A bare `repo:tag` with no slash is never a host.
+ val head = if (slashIdx < 0) noDigest else noDigest.substring(0, slashIdx)
+ val looksLikeHost = slashIdx >= 0 &&
+ (head.contains('.') || head == "localhost" || head.contains(':'))
+ val registry = if (looksLikeHost) head else "docker.io"
+ val repoAndTag = if (looksLikeHost) noDigest.substring(slashIdx + 1) else noDigest
+ if (repoAndTag.isEmpty()) throw IllegalArgumentException("no repository in $ref")
+ val tag = if (repoAndTag.contains(':')) repoAndTag.substringAfterLast(':') else "latest"
+ val repo = if (repoAndTag.contains(':')) repoAndTag.substringBeforeLast(':') else repoAndTag
+ if (repo.isEmpty()) throw IllegalArgumentException("no repository in $ref")
+ return Parsed(registry, repo, tag)
+ }
+
+ /**
+ * The architecture name a registry manifest list uses for this device's ABI.
+ * Docker/OCI spell it amd64/arm64/arm; the build ABIs spell it x86_64/aarch64/armv7l.
+ */
+ fun manifestArchForAbi(abi: String): String = when (abi) {
+ "x86_64", "x86" -> "amd64"
+ "aarch64", "arm64" -> "arm64"
+ "armeabi-v7a", "armv7l", "arm" -> "arm"
+ else -> "amd64"
+ }
+
+ /** Whether a manifest entry's platform matches the device's architecture. */
+ fun isMatchingArch(platformArch: String, manifestArch: String): Boolean =
+ platformArch == manifestArch
+}
diff --git a/app/src/main/java/com/redtermapp/distro/RootfsInstallExtractor.kt b/app/src/main/java/com/redtermapp/distro/RootfsInstallExtractor.kt
index c78909c..6578c3f 100644
--- a/app/src/main/java/com/redtermapp/distro/RootfsInstallExtractor.kt
+++ b/app/src/main/java/com/redtermapp/distro/RootfsInstallExtractor.kt
@@ -70,11 +70,12 @@ object RootfsInstallExtractor {
totalCompressed: Long = 0L,
checkCancel: () -> Unit = {},
onProgress: (percent: Int) -> Unit = {},
- onLog: (String) -> Unit = {}
+ onLog: (String) -> Unit = {},
+ stripPrefix: Boolean = true
): Int {
val firstEntry = tarIn.getNextEntry()
var prefixToStrip = ""
- if (firstEntry != null) {
+ if (stripPrefix && firstEntry != null) {
val name = firstEntry.name
val slash = name.indexOf('/')
if (slash > 0) {
diff --git a/app/src/main/java/com/redtermapp/distro/TarballFormat.kt b/app/src/main/java/com/redtermapp/distro/TarballFormat.kt
new file mode 100644
index 0000000..64a59d7
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/distro/TarballFormat.kt
@@ -0,0 +1,50 @@
+package com.redtermapp.distro
+
+/**
+ * The three ways a distro tarball can be compressed, told apart by the first
+ * bytes of the file rather than its name.
+ *
+ * A local tarball's extension is whatever its maker chose — or nothing — so the
+ * only reliable answer to "how do I open this?" is the magic number: xz starts
+ * with `0xFD 37 7A 58 5A 00`, gzip with `0x1F 0x8B`, and a plain tar with the
+ * 512-byte header and neither. Everything else is not a tarball we can open.
+ *
+ * Pure, so the detection is unit-tested with real magic bytes: a tarball that
+ * is really gzip in a `.tar.xz` file must be opened as gzip or every entry
+ * reads as garbage.
+ */
+object TarballFormat {
+
+ enum class Compression { XZ, GZIP, PLAIN, UNKNOWN }
+
+ /** Inspect the first bytes of the file; needs at most six. */
+ fun detect(magic: ByteArray): Compression = when {
+ // xz: FD 37 7A 58 5A 00
+ magic.size >= 6 &&
+ (magic[0].toInt() and 0xFF) == 0xFD && (magic[1].toInt() and 0xFF) == 0x37 &&
+ (magic[2].toInt() and 0xFF) == 0x7A && (magic[3].toInt() and 0xFF) == 0x58 &&
+ (magic[4].toInt() and 0xFF) == 0x5A && (magic[5].toInt() and 0xFF) == 0x00 -> Compression.XZ
+
+ // gzip: 1F 8B
+ magic.size >= 2 &&
+ (magic[0].toInt() and 0xFF) == 0x1F && (magic[1].toInt() and 0xFF) == 0x8B -> Compression.GZIP
+
+ // A tar header is 512 bytes; the very first byte of a real archive is
+ // part of a name and never 0, but we cannot tell tar from random data
+ // by magic alone. Anything not xz or gzip is treated as plain tar and
+ // let the tar reader fail loudly on a file that is not one.
+ magic.isNotEmpty() -> Compression.PLAIN
+
+ else -> Compression.UNKNOWN
+ }
+
+ /** Read the magic bytes of [file] without loading it. */
+ fun readMagic(file: java.io.File, n: Int = 6): ByteArray {
+ if (!file.isFile) return ByteArray(0)
+ return java.io.FileInputStream(file).use { input ->
+ val buf = ByteArray(n)
+ val got = input.read(buf)
+ if (got <= 0) ByteArray(0) else buf.copyOf(got)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/DistroDashboardActivity.kt b/app/src/main/java/com/redtermapp/ui/DistroDashboardActivity.kt
new file mode 100644
index 0000000..bed9c6a
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/DistroDashboardActivity.kt
@@ -0,0 +1,234 @@
+package com.redtermapp.ui
+
+import android.content.Intent
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.edit
+import com.redtermapp.R
+import com.redtermapp.distro.DistroBrand
+import com.redtermapp.distro.DistroInstaller
+import com.redtermapp.distro.DistroOsRelease
+import java.io.File
+import java.util.Locale
+
+/**
+ * One glance at every installed distro: what it is, how much it costs in
+ * storage, and when its packages were last updated. "Update now" deep-links
+ * the package updater for that distro and stamps the time; "Disk" opens the
+ * per-directory breakdown.
+ */
+class DistroDashboardActivity : AppCompatActivity() {
+
+ private val installer by lazy { DistroInstaller(applicationContext) }
+ private lateinit var container: LinearLayout
+ private lateinit var deviceLine: TextView
+ private lateinit var deviceResLine: TextView
+ private val stamps by lazy { getSharedPreferences("distro_updates", android.content.Context.MODE_PRIVATE) }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.distro_dashboard)
+ textSize = 20f
+ })
+ deviceLine = TextView(this).apply {
+ textSize = 12f
+ setPadding(0, 8, 0, 0)
+ }
+ body.addView(deviceLine)
+ deviceResLine = TextView(this).apply {
+ textSize = 12f
+ setPadding(0, 0, 0, 8)
+ }
+ body.addView(deviceResLine)
+ // A custom distro is installed from a file, URL, or registry image, not the
+ // catalogue, so it is its own "Custom…" action opening the source installer,
+ // not a card in this list.
+ val customRow = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ setPadding(0, 0, 0, 8)
+ }
+ customRow.addView(
+ ScreenWidgets.actionButton(this, R.string.distro_dashboard_custom) {
+ startActivity(Intent(this@DistroDashboardActivity, LocalDistroInstallActivity::class.java))
+ }
+ )
+ body.addView(customRow)
+ container = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ body.addView(container)
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.distro_dashboard))
+ setContentView(root)
+ load()
+ }
+
+ private fun load() {
+ Thread({
+ val installed = installer.getInstalledDistros()
+ val device = deviceFree()
+ val mem = com.redtermapp.util.DeviceResources.readMemory()
+ val cpus = com.redtermapp.util.DeviceResources.readCpuCount()
+ val cards = installed.map { distro ->
+ val rootfs = installer.getRootfsDir(distro)
+ val osrel = DistroOsRelease.read(rootfs)
+ Triple(
+ distro,
+ DistroOsRelease.versionOf(osrel),
+ runCatching { treeSize(rootfs) }.getOrDefault(0L)
+ )
+ }
+ runOnUiThread {
+ if (isFinishing || isDestroyed) return@runOnUiThread
+ deviceLine.text = getString(R.string.distro_dashboard_device_free, human(device))
+ val totalBytes = mem?.totalKb?.times(1024L)
+ val availBytes = mem?.availableKb?.times(1024L)
+ deviceResLine.text = if (totalBytes != null && availBytes != null) {
+ getString(
+ R.string.distro_dashboard_device,
+ cpus, human(totalBytes), human(availBytes)
+ )
+ } else {
+ getString(R.string.distro_dashboard_device_cpu, cpus)
+ }
+ container.removeAllViews()
+ if (cards.isEmpty()) {
+ container.addView(TextView(this).apply {
+ setText(R.string.distro_dashboard_none)
+ setTextColor(mutedTextColor())
+ })
+ }
+ for ((distro, version, size) in cards) {
+ container.addView(card(distro, version, size))
+ }
+ }
+ }, "redterm-distro-dashboard").start()
+ }
+
+ private fun card(distro: String, version: String, size: Long): View {
+ val pad = (10 * resources.displayMetrics.density).toInt()
+ val card = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ setBackgroundColor(cardColor())
+ layoutParams = LinearLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
+ ).apply {
+ val b = (8 * resources.displayMetrics.density).toInt()
+ setMargins(0, 0, 0, b)
+ }
+ }
+ val head = ScreenWidgets.headerRow(this).apply {
+ addView(TextView(this@DistroDashboardActivity).apply {
+ text = DistroBrand.displayNameFor(distro)
+ textSize = 16f
+ setTextColor(cardTextColor())
+ })
+ if (version.isNotEmpty()) {
+ addView(TextView(this@DistroDashboardActivity).apply {
+ text = version
+ textSize = 12f
+ setTextColor(mutedTextColor())
+ setPadding((12 * resources.displayMetrics.density).toInt(), 0, 0, 0)
+ })
+ }
+ }
+ card.addView(head)
+
+ val last = stamps.getLong("last_$distro", 0L)
+ val lastText = if (last == 0L) getString(R.string.distro_dashboard_never)
+ else java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(java.util.Date(last))
+ card.addView(factLine(getString(R.string.distro_dashboard_size), human(size)))
+ card.addView(factLine(getString(R.string.distro_dashboard_last_update), lastText))
+
+ val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ row.addView(ScreenWidgets.primaryButton(this, R.string.distro_dashboard_update) {
+ stamps.edit { putLong("last_$distro", System.currentTimeMillis()) }
+ startActivity(
+ Intent(this@DistroDashboardActivity, PackageUpdateActivity::class.java)
+ .putExtra(PackageUpdateActivity.EXTRA_DISTRO, distro)
+ )
+ reload()
+ })
+ row.addView(ScreenWidgets.actionButton(this, R.string.distro_dashboard_disk) {
+ startActivity(Intent(this@DistroDashboardActivity, DiskUsageActivity::class.java))
+ })
+ card.addView(row)
+ return card
+ }
+
+ private fun factLine(label: String, value: String): View =
+ LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ addView(TextView(this@DistroDashboardActivity).apply {
+ text = label
+ textSize = 12f
+ setTextColor(mutedTextColor())
+ })
+ addView(TextView(this@DistroDashboardActivity).apply {
+ text = value
+ textSize = 12f
+ setTextColor(cardTextColor())
+ setPadding((8 * resources.displayMetrics.density).toInt(), 0, 0, 0)
+ })
+ }
+
+ private fun reload() = load()
+
+ private fun deviceFree(): Long {
+ val root = installer.getInstalledDistros().firstOrNull()
+ ?.let { installer.getRootfsDir(it) }?.parentFile
+ ?: File(getExternalFilesDir(null)?.absolutePath ?: android.os.Environment.getExternalStorageDirectory().absolutePath)
+ return try {
+ android.os.StatFs(root.absolutePath).availableBytes
+ } catch (_: Exception) {
+ 0L
+ }
+ }
+
+ private fun treeSize(dir: File): Long {
+ var total = 0L
+ dir.walkTopDown().forEach { total += if (it.isFile) runCatching { it.length() }.getOrDefault(0L) else 0L }
+ return total
+ }
+
+ private fun human(bytes: Long): String =
+ when {
+ bytes >= 1L shl 30 -> String.format(Locale.getDefault(), "%.1f GB", bytes / 1073741824.0)
+ bytes >= 1L shl 20 -> String.format(Locale.getDefault(), "%.1f MB", bytes / 1048576.0)
+ bytes >= 1L shl 10 -> String.format(Locale.getDefault(), "%.1f KB", bytes / 1024.0)
+ else -> "$bytes B"
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", android.content.Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/ForwardManager.kt b/app/src/main/java/com/redtermapp/ui/ForwardManager.kt
new file mode 100644
index 0000000..258282b
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/ForwardManager.kt
@@ -0,0 +1,253 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import com.redtermapp.util.AppLog
+import com.redtermapp.util.SshClient
+import com.redtermapp.util.sftp.SshAskpass
+import java.io.File
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.AtomicInteger
+
+/**
+ * A forward that stays open with no terminal in front of it.
+ *
+ * The old "Port forward" button was a single *device-local* relay and stopped
+ * there. A user working over SSH wants the opposite: a device port that reaches a
+ * remote host's port *through* a server. That is `ssh -N -L from:toHost:toPort`,
+ * exactly the shape TunnelManager already opens for the forwards saved on a server —
+ * but ad-hoc, against a named target, and open for as long as the user says so.
+ *
+ * [Spec] is pure and unit-tested. [ForwardManager] runs them, one entry per
+ * forward, so any number stay open at once and any number of servers are
+ * reachable at the same time.
+ */
+object ForwardManager {
+
+ /** One forward. [forward] is the port mapping the screen shows; [summary] names the
+ * target for the log. */
+ sealed class Spec {
+ abstract val fromPort: Int
+ abstract val toHost: String
+ abstract val toPort: Int
+ abstract val forward: String
+ abstract val summary: String
+ /** True when this forward goes through a server; a local relay is false. */
+ abstract fun viaSsh(): Boolean
+ }
+
+ /** Device port -> [toHost]:[toPort] on the device itself. For a guest service. */
+ data class LocalSpec(
+ override val fromPort: Int,
+ override val toHost: String,
+ override val toPort: Int
+ ) : Spec() {
+ override fun viaSsh() = false
+ override val forward get() = "$fromPort -> $toHost:$toPort"
+ override val summary get() = "device: $forward"
+ }
+
+ /** Device port -> [toHost]:[toPort] on the remote side of [server], via `ssh -L`. */
+ data class SshSpec(
+ override val fromPort: Int,
+ override val toHost: String,
+ override val toPort: Int,
+ val server: SshStore.Server,
+ val identities: List
+ ) : Spec() {
+ override fun viaSsh() = true
+ override val forward get() = "$fromPort -> $toHost:$toPort"
+ override val summary get() = "${server.label}: $forward"
+ }
+
+ /** The [ssh -L] argument that carries one [SshSpec], or null for a local relay. */
+ fun forwardArg(spec: Spec): String? =
+ when (spec) {
+ is LocalSpec -> null
+ is SshSpec -> "-L${spec.fromPort}:${spec.toHost}:${spec.toPort}"
+ }
+
+ private const val TAG = "ForwardManager"
+ private val sequence = AtomicInteger(0)
+
+ private class Running(
+ val id: String,
+ val spec: Spec,
+ val relay: LocalPortForward.LocalPortRelay?,
+ val process: Process?,
+ val script: File?
+ )
+
+ private val active = ConcurrentHashMap()
+
+ fun activeIds(): Set = active.keys.toSet()
+
+ fun specFor(id: String): Spec? = active[id]?.spec
+
+ fun summaryFor(id: String): String? = active[id]?.spec?.summary
+
+ /** Starts a forward. Returns its id, or null when it could not be opened. */
+ fun start(context: Context, spec: Spec): String? {
+ val id = "forward-" + sequence.incrementAndGet()
+ val running = when (spec) {
+ is LocalSpec -> {
+ val relay = LocalPortForward.LocalPortRelay(
+ LocalPortForward.Spec(spec.fromPort, spec.toHost, spec.toPort)
+ )
+ if (relay.start()) Running(id, spec, relay, null, null)
+ else {
+ AppLog.w(context, "port-forward", "local relay ${spec.forward} did not bind")
+ return null
+ }
+ }
+ is SshSpec -> startSsh(context, id, spec) ?: return null
+ }
+ active[id] = running
+ if (spec is SshSpec) persistSsh(context, spec)
+ AppLog.i(context, "port-forward", "forward up: ${spec.summary}")
+ return id
+ }
+
+ /**
+ * Re-opens the ssh forwards the last process was keeping open.
+ *
+ * A dead process orphans its `ssh -N` children; [RedTermApp] reaps those
+ * first, then calls this so the user's "keep this port open" survives the
+ * app dying. A forward whose server is gone is dropped from the record,
+ * which is also how a deleted server cleans up after its forwards.
+ */
+ fun resumeAll(context: Context): Int {
+ val servers = SshStore.load(context).associateBy { it.id }
+ var resumed = 0
+ for (entry in planResume(ForwardPersistence.load(context), servers)) {
+ val identities = SshKeyStore.identitiesFor(context, servers[entry.serverId]!!)
+ val spec = SshSpec(entry.fromPort, entry.toHost, entry.toPort,
+ servers[entry.serverId]!!, identities)
+ if (start(context, spec) != null) resumed++
+ }
+ return resumed
+ }
+
+ /**
+ * Which saved entries can actually be re-opened, given the servers that
+ * still exist. Pure so it is unit-tested: a saved forward whose server the
+ * user deleted must be dropped, not started against a null.
+ */
+ fun planResume(
+ saved: List,
+ servers: Map
+ ): List =
+ saved.filter { servers[it.serverId] != null }
+
+ private fun persistSsh(context: Context, spec: SshSpec) {
+ val entry = ForwardPersistence.SavedForward(
+ spec.server.id, spec.fromPort, spec.toHost, spec.toPort
+ )
+ val entries = ForwardPersistence.load(context).filterNot { it == entry } + entry
+ ForwardPersistence.save(context, entries)
+ }
+
+ /** Builds and runs the `ssh -N -L` process for an [SshSpec]. Null when it cannot. */
+ private fun startSsh(context: Context, id: String, spec: SshSpec): Running? {
+ if (!SshClient.ensureInstalled(context)) {
+ AppLog.w(context, TAG, "ssh is not installed; cannot open ${spec.summary}")
+ return null
+ }
+ val secret = SshPasswordPrompt.available(context, spec.server)
+ val args = mutableListOf("/bin/ssh", "-N", forwardArg(spec))
+ args.addAll(
+ SshLaunchOptions.forServer(
+ server = spec.server,
+ identities = spec.identities,
+ // Only this forward, not the server's saved set: an ad-hoc
+ // forward is one port, and opening every saved forward too is
+ // not what the user asked for.
+ extraOptions = if (secret.isEmpty()) listOf("BatchMode=yes") else emptyList(),
+ withForwards = false
+ )
+ )
+ val script = try {
+ com.redtermapp.distro.ProotLaunch.writeLauncher(
+ context = context,
+ rootfsDir = SshClient.rootfs(context),
+ startInner = "/root",
+ command = args.joinToString(" "),
+ scriptName = "forward-$id.sh"
+ )
+ } catch (e: Exception) {
+ AppLog.w(context, TAG, "could not write the forward launcher: ${e.message}")
+ return null
+ }
+ val process = try {
+ ProcessBuilder("/system/bin/sh", script.absolutePath)
+ .apply {
+ environment().putAll(SshAskpass.environment(context, secret))
+ redirectErrorStream(true)
+ }
+ .start()
+ } catch (e: Exception) {
+ AppLog.w(context, TAG, "forward ${spec.summary} did not start: ${e.message}")
+ runCatching { script.delete() }
+ return null
+ }
+ // The output is drained to a log rather than redirected to a file:
+ // Redirect.appendTo is API 26, and a pipe nobody reads would eventually
+ // fill and kill the very ssh this is standing up for.
+ Thread({
+ runCatching {
+ process.inputStream.copyTo(
+ java.io.FileOutputStream(File(context.cacheDir, "forward-$id.log"), true)
+ )
+ }
+ }, "redterm-forward-output").apply {
+ isDaemon = true
+ start()
+ }
+ return Running(id, spec, null, process, script)
+ }
+
+ fun stop(context: Context, id: String) {
+ val entry = active.remove(id) ?: return
+ entry.relay?.close()
+ entry.process?.destroy()
+ entry.script?.delete()
+ val spec = entry.spec
+ if (spec is SshSpec) {
+ val saved = ForwardPersistence.SavedForward(
+ spec.server.id, spec.fromPort, spec.toHost, spec.toPort
+ )
+ ForwardPersistence.save(
+ context, ForwardPersistence.load(context).filterNot { it == saved }
+ )
+ }
+ AppLog.i(context, "port-forward", "forward stopped: ${spec.summary}")
+ }
+
+ fun stopAll(context: Context) {
+ for (id in active.keys.toList()) stop(context, id)
+ // "Stop all" is a decision about the record too: the next cold start
+ // must not re-open what the user just closed.
+ ForwardPersistence.clear(context)
+ }
+
+ /**
+ * Whether a forward is still standing. An ssh process dies on its own when
+ * the server drops or the port is taken; checked on every read, the way
+ * TunnelManager checks, and the entry is dropped the moment it is not.
+ */
+ fun isAlive(id: String): Boolean {
+ val entry = active[id] ?: return false
+ entry.relay?.let {
+ val alive = it.isRunning()
+ if (!alive) active.remove(id)
+ return alive
+ }
+ val alive = try {
+ entry.process!!.exitValue()
+ false
+ } catch (_: IllegalThreadStateException) {
+ true
+ }
+ if (!alive) active.remove(id)
+ return alive
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/ForwardPersistence.kt b/app/src/main/java/com/redtermapp/ui/ForwardPersistence.kt
new file mode 100644
index 0000000..2750657
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/ForwardPersistence.kt
@@ -0,0 +1,93 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import androidx.core.content.edit
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * The ssh port-forwards the user asked to keep open, written to disk so a
+ * reclaimed process does not silently lose them.
+ *
+ * A forward is a *child process* of the app, and Android reclaims the app
+ * without killing its children: the `ssh -N` outlives the process and is
+ * reparented to init. That is why the record lives here — on a cold start
+ * the previous process's orphans are reaped and this list is re-opened, so
+ * "a port that stays open while nothing is being typed" keeps its promise
+ * across app deaths instead of quietly breaking at the first low-memory kill.
+ *
+ * Local relays are deliberately not persisted: they live in the app's own
+ * process, die with it, and their target (a guest service) may be gone by
+ * the time the app comes back. Only the ssh forwards outlive the app.
+ *
+ * [encode]/[decode] are pure and round-trip tested: a missing writer field
+ * surfaces nowhere else, only as a forward that refuses to resume.
+ */
+object ForwardPersistence {
+
+ private const val PREFS = "port_forwards"
+ private const val KEY = "ssh_forwards"
+
+ /** One ssh forward, keyed by server so a deleted server drops its forwards. */
+ data class SavedForward(
+ val serverId: String,
+ val fromPort: Int,
+ val toHost: String,
+ val toPort: Int
+ )
+
+ fun load(context: Context): List =
+ decode(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null))
+
+ fun save(context: Context, entries: List) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit {
+ putString(KEY, encode(entries))
+ }
+ }
+
+ fun clear(context: Context) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit {
+ remove(KEY)
+ }
+ }
+
+ fun encode(entries: List): String =
+ JSONArray().apply {
+ for (e in entries) {
+ put(
+ JSONObject()
+ .put("serverId", e.serverId)
+ .put("fromPort", e.fromPort)
+ .put("toHost", e.toHost)
+ .put("toPort", e.toPort)
+ )
+ }
+ }.toString()
+
+ /**
+ * Tolerant on purpose: one entry with a missing or out-of-range port is
+ * dropped, the rest resume. An unreadable record is no forwards, not an
+ * exception in the middle of a cold start.
+ */
+ fun decode(json: String?): List {
+ if (json.isNullOrBlank()) return emptyList()
+ return runCatching {
+ val array = JSONArray(json)
+ (0 until array.length()).mapNotNull { i ->
+ val o = array.optJSONObject(i) ?: return@mapNotNull null
+ val serverId = o.optString("serverId", "")
+ val fromPort = o.optInt("fromPort")
+ val toPort = o.optInt("toPort")
+ if (serverId.isBlank() || fromPort !in 1..65535 || toPort !in 1..65535) {
+ return@mapNotNull null
+ }
+ SavedForward(
+ serverId = serverId,
+ fromPort = fromPort,
+ toHost = o.optString("toHost", "127.0.0.1"),
+ toPort = toPort
+ )
+ }
+ }.getOrDefault(emptyList())
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/ForwardPresetStore.kt b/app/src/main/java/com/redtermapp/ui/ForwardPresetStore.kt
new file mode 100644
index 0000000..54500db
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/ForwardPresetStore.kt
@@ -0,0 +1,82 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import androidx.core.content.edit
+import org.json.JSONObject
+
+/**
+ * Saved port-forward settings, one list per server.
+ *
+ * The forward screen re-enters three numbers on every visit; the ones the
+ * user actually uses are the handful they keep using, and those are worth
+ * remembering. A preset is per-server, because the device port is the
+ * device's and the target is the server's: the same pair opened against two
+ * servers is two different forwards.
+ *
+ * [encode]/[decode] are pure and round-trip tested. A deleted server leaves
+ * its presets behind in the record, which is harmless: the picker only
+ * offers presets for servers it lists.
+ */
+object ForwardPresetStore {
+
+ private const val PREFS = "forward_presets"
+ private const val KEY = "presets"
+
+ data class Preset(val fromPort: Int, val toHost: String, val toPort: Int)
+
+ /** Presets per server id. Servers without presets are simply absent. */
+ fun load(context: Context): Map> =
+ decode(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null))
+
+ fun save(context: Context, presets: Map>) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit {
+ putString(KEY, encode(presets))
+ }
+ }
+
+ fun addPreset(context: Context, serverId: String, preset: Preset): List {
+ val all = load(context)
+ val list = (all[serverId] ?: emptyList()).filterNot { it == preset } + preset
+ save(context, all + (serverId to list))
+ return list
+ }
+
+ fun encode(presets: Map>): String =
+ JSONObject().apply {
+ for ((serverId, list) in presets) {
+ val arr = org.json.JSONArray()
+ for (p in list) {
+ arr.put(
+ JSONObject()
+ .put("fromPort", p.fromPort)
+ .put("toHost", p.toHost)
+ .put("toPort", p.toPort)
+ )
+ }
+ put(serverId, arr)
+ }
+ }.toString()
+
+ /** Corrupt entries are dropped, the rest kept: a preset record must never
+ * take the forward screen down with it. */
+ fun decode(json: String?): Map> {
+ if (json.isNullOrBlank()) return emptyMap()
+ return runCatching {
+ val jsonObject = JSONObject(json)
+ val result = HashMap>()
+ for (serverId in jsonObject.keys()) {
+ val arr = jsonObject.optJSONArray(serverId) ?: continue
+ val list = ArrayList()
+ for (i in 0 until arr.length()) {
+ val o = arr.optJSONObject(i) ?: continue
+ val fromPort = o.optInt("fromPort")
+ val toPort = o.optInt("toPort")
+ if (fromPort !in 1..65535 || toPort !in 1..65535) continue
+ list.add(Preset(fromPort, o.optString("toHost", "127.0.0.1"), toPort))
+ }
+ result[serverId] = list
+ }
+ result
+ }.getOrDefault(emptyMap())
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/JobHistoryStore.kt b/app/src/main/java/com/redtermapp/ui/JobHistoryStore.kt
new file mode 100644
index 0000000..a7f9d7c
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/JobHistoryStore.kt
@@ -0,0 +1,121 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import androidx.core.content.edit
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * The record of scheduled-job runs, newest first.
+ *
+ * The worker appends one entry per run and trims the record, so a job that
+ * fires every fifteen minutes for a month stays bounded. A job that has
+ * never run has no entries, which the screen says plainly instead of
+ * showing a stale "last run" it never had.
+ *
+ * [encode]/[decode] and [outputTailOf] are pure and unit-tested; the prefs
+ * round trip around them is the only I/O.
+ */
+object JobHistoryStore {
+
+ /** One execution of a job. [exitCode] is -1 when the run did not start. */
+ data class JobRun(
+ val jobId: String,
+ val jobName: String,
+ val distro: String,
+ val command: String,
+ val atMs: Long,
+ val exitCode: Int,
+ val outputTail: String
+ )
+
+ const val MAX_RUNS = 200
+ const val TAIL_CHARS = 300
+
+ private const val PREFS = "job_history"
+ private const val KEY = "runs"
+
+ fun recent(context: Context, limit: Int = 20): List =
+ decode(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null))
+ .take(limit)
+
+ fun forJob(context: Context, jobId: String, limit: Int = 20): List =
+ recent(context, MAX_RUNS).filter { it.jobId == jobId }.take(limit)
+
+ fun add(context: Context, run: JobRun) {
+ val runs = (decode(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null))
+ .toMutableList()).also { it.add(0, run) }
+ if (runs.size > MAX_RUNS) runs.removeAt(runs.size - 1)
+ save(context, runs)
+ }
+
+ fun clear(context: Context) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { remove(KEY) }
+ }
+
+ /** Drop the record of one job: its runs are meaningless without the job. */
+ fun removeJob(context: Context, jobId: String) {
+ val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ val runs = decode(prefs.getString(KEY, null)).filterNot { it.jobId == jobId }
+ save(context, runs)
+ }
+
+ private fun save(context: Context, runs: List) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit {
+ putString(KEY, encode(runs))
+ }
+ }
+
+ fun encode(runs: List): String =
+ JSONArray().apply {
+ for (r in runs) {
+ put(
+ JSONObject()
+ .put("jobId", r.jobId)
+ .put("jobName", r.jobName)
+ .put("distro", r.distro)
+ .put("command", r.command)
+ .put("atMs", r.atMs)
+ .put("exitCode", r.exitCode)
+ .put("outputTail", r.outputTail)
+ )
+ }
+ }.toString()
+
+ /** A corrupt record is no history, not a crash in the job screen. */
+ fun decode(json: String?): List {
+ if (json.isNullOrBlank()) return emptyList()
+ return runCatching {
+ val arr = JSONArray(json)
+ (0 until arr.length()).mapNotNull { i ->
+ val o = arr.optJSONObject(i) ?: return@mapNotNull null
+ if (o.optString("jobId").isBlank()) return@mapNotNull null
+ JobRun(
+ jobId = o.getString("jobId"),
+ jobName = o.optString("jobName", ""),
+ distro = o.optString("distro", ""),
+ command = o.optString("command", ""),
+ atMs = o.optLong("atMs"),
+ exitCode = o.optInt("exitCode", -1),
+ outputTail = o.optString("outputTail", "")
+ )
+ }
+ }.getOrDefault(emptyList())
+ }
+
+ /**
+ * The end of an output, which is the part that explains a failure.
+ *
+ * The tail, not the head: the interesting thing about a failed run is
+ * what it died doing, and the error is at the end. Trimmed to a few
+ * lines so a notification and a dialog row can carry it without
+ * scrolling.
+ */
+ fun outputTailOf(output: String, maxChars: Int = TAIL_CHARS): String {
+ val text = output.trim()
+ if (text.length <= maxChars) return text
+ val cut = text.substring(text.length - maxChars)
+ // Break at the next line so the tail starts at a line, not mid-word.
+ return "\n" + cut.substringAfter('\n')
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/LocalDistroInstallActivity.kt b/app/src/main/java/com/redtermapp/ui/LocalDistroInstallActivity.kt
new file mode 100644
index 0000000..750d18f
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/LocalDistroInstallActivity.kt
@@ -0,0 +1,303 @@
+package com.redtermapp.ui
+
+import android.net.Uri
+import android.os.Bundle
+import android.provider.OpenableColumns
+import android.view.View
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ProgressBar
+import android.widget.ScrollView
+import android.widget.Spinner
+import android.widget.TextView
+import android.widget.Toast
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.lifecycleScope
+import com.redtermapp.R
+import com.redtermapp.distro.DistroInstaller
+import com.redtermapp.util.AppLog
+import kotlinx.coroutines.launch
+
+/**
+ * Install a distro from a tarball the user holds, not from the registry.
+ *
+ * The registry installs are downloaded and checksummed; this path is the
+ * opposite — a local `.tar.xz`, `.tar.gz` or plain `.tar` brought in from any
+ * file picker. The compression is read from the file's own magic bytes, never
+ * from its extension, because a wrong extension is how a gzip image silently
+ * becomes a wall of garbage. The only real gate is that the tar reader
+ * accepts it; a file that is not a tarball fails the extraction and says so.
+ */
+class LocalDistroInstallActivity : AppCompatActivity() {
+
+ private val installer by lazy { DistroInstaller(applicationContext) }
+
+ private lateinit var root: LinearLayout
+ private lateinit var sourceSpinner: Spinner
+ private lateinit var fileRow: LinearLayout
+ private lateinit var fileName: TextView
+ private lateinit var urlGroup: LinearLayout
+ private lateinit var urlField: EditText
+ private lateinit var regGroup: LinearLayout
+ private lateinit var refField: EditText
+ private lateinit var nameField: EditText
+ private lateinit var installButton: com.google.android.material.button.MaterialButton
+ private lateinit var progressGroup: LinearLayout
+ private lateinit var progressText: TextView
+ private lateinit var progressBar: ProgressBar
+
+ private var chosen: Uri? = null
+
+ // Whether an install is actually running. The install button is gated on this, not on
+ // the progress view's visibility, because after a failure the progress area stays up
+ // to show the error and the user must be able to tap install again to retry.
+ private var installing = false
+
+ private val pickDocument = registerForActivityResult(
+ ActivityResultContracts.OpenDocument()
+ ) { uri ->
+ if (uri == null) return@registerForActivityResult
+ chosen = uri
+ fileName.text = getString(R.string.ldi_chosen, displayName(uri))
+ nameField.setText(suggestName(uri))
+ refreshState()
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+
+ body.addView(TextView(this).apply {
+ text = getString(R.string.ldi_title)
+ textSize = 20f
+ })
+ body.addView(TextView(this).apply {
+ text = getString(R.string.ldi_what)
+ textSize = 13f
+ setTextColor(mutedTextColor())
+ })
+
+ body.addView(TextView(this).apply {
+ text = getString(R.string.ldi_source_label)
+ textSize = 13f
+ setTextColor(mutedTextColor())
+ })
+ sourceSpinner = ScreenWidgets.spinner(this, listOf(
+ getString(R.string.ldi_src_file),
+ getString(R.string.ldi_src_url),
+ getString(R.string.ldi_src_registry)
+ ))
+ body.addView(sourceSpinner)
+
+ // Source-specific input, one visible at a time.
+ fileRow = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ fileRow.addView(ScreenWidgets.actionButton(this, R.string.ldi_choose_file) {
+ pickDocument.launch(arrayOf("*/*"))
+ })
+ fileName = TextView(this).apply {
+ text = getString(R.string.ldi_no_file)
+ textSize = 13f
+ setTextColor(accentColor())
+ setPadding(0, (6 * resources.displayMetrics.density).toInt(), 0, 0)
+ }
+ fileRow.addView(fileName)
+ body.addView(fileRow)
+
+ urlGroup = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; visibility = View.GONE }
+ urlField = EditText(this).apply {
+ hint = getString(R.string.ldi_url_hint)
+ setSingleLine(true)
+ setTextColor(cardTextColor())
+ setHintTextColor(mutedTextColor())
+ }
+ urlGroup.addView(urlField)
+ body.addView(urlGroup)
+
+ regGroup = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; visibility = View.GONE }
+ refField = EditText(this).apply {
+ hint = getString(R.string.ldi_ref_hint)
+ setSingleLine(true)
+ setTextColor(cardTextColor())
+ setHintTextColor(mutedTextColor())
+ }
+ regGroup.addView(refField)
+ body.addView(regGroup)
+
+ sourceSpinner.onItemSelectedListener =
+ object : android.widget.AdapterView.OnItemSelectedListener {
+ override fun onItemSelected(
+ parent: android.widget.AdapterView<*>?, view: View?, position: Int, id: Long
+ ) {
+ fileRow.visibility = if (position == 0) View.VISIBLE else View.GONE
+ urlGroup.visibility = if (position == 1) View.VISIBLE else View.GONE
+ regGroup.visibility = if (position == 2) View.VISIBLE else View.GONE
+ refreshState()
+ }
+
+ override fun onNothingSelected(parent: android.widget.AdapterView<*>?) = Unit
+ }
+
+ // refreshState() is what (dis)enables the install button, and it only ran on a
+ // spinner change. So typing a URL or an image reference left the button disabled
+ // and the tap did nothing: no log, no error, the coroutine never started. The
+ // text fields recompute it on every change.
+ val sourceWatcher = object : android.text.TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { refreshState() }
+ override fun afterTextChanged(s: android.text.Editable?) = Unit
+ }
+ urlField.addTextChangedListener(sourceWatcher)
+ refField.addTextChangedListener(sourceWatcher)
+
+ body.addView(TextView(this).apply {
+ text = getString(R.string.ldi_name_label)
+ textSize = 13f
+ setTextColor(mutedTextColor())
+ setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0)
+ })
+ nameField = EditText(this).apply {
+ hint = getString(R.string.ldi_name_hint)
+ setSingleLine(true)
+ setTextColor(cardTextColor())
+ setHintTextColor(mutedTextColor())
+ }
+ body.addView(nameField)
+
+ installButton = ScreenWidgets.primaryButton(this, R.string.ldi_install) { startInstall() }
+ installButton.isEnabled = false
+ body.addView(installButton)
+
+ progressGroup = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ visibility = View.GONE
+ }
+ progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply {
+ max = 100
+ }
+ progressText = TextView(this).apply {
+ textSize = 13f
+ setTextColor(mutedTextColor())
+ }
+ progressGroup.addView(progressBar)
+ progressGroup.addView(progressText)
+ body.addView(progressGroup)
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.ldi_title))
+ setContentView(root)
+ }
+
+ private fun refreshState() {
+ val ready = when (sourceSpinner.selectedItemPosition) {
+ 0 -> chosen != null
+ 1 -> urlField.text.toString().trim().isNotEmpty()
+ 2 -> refField.text.toString().trim().isNotEmpty()
+ else -> false
+ }
+ installButton.isEnabled = ready && !installing
+ }
+
+ /** The source selected in the spinner, or null when its field is empty. */
+ private fun currentSource(): DistroInstaller.InstallSource? = when (sourceSpinner.selectedItemPosition) {
+ 0 -> chosen?.let { DistroInstaller.InstallSource.Local(it) }
+ 1 -> urlField.text.toString().trim().takeIf { it.isNotEmpty() }
+ ?.let { DistroInstaller.InstallSource.Url(it) }
+ 2 -> refField.text.toString().trim().takeIf { it.isNotEmpty() }
+ ?.let { DistroInstaller.InstallSource.Registry(it) }
+ else -> null
+ }
+
+ private fun startInstall() {
+ val source = currentSource()
+ if (source == null) {
+ Toast.makeText(this, R.string.ldi_source_required, Toast.LENGTH_LONG).show()
+ return
+ }
+ val name = nameField.text.toString().trim()
+ if (name.isEmpty()) {
+ Toast.makeText(this, R.string.ldi_name_required, Toast.LENGTH_SHORT).show()
+ return
+ }
+ installing = true
+ installButton.isEnabled = false
+ progressGroup.visibility = View.VISIBLE
+ progressBar.progress = 0
+ progressText.text = getString(R.string.ldi_starting)
+ lifecycleScope.launch {
+ try {
+ // The install runs on Dispatchers.IO; every progress callback posts back
+ // to the UI thread, because a view touched from its owner's thread is the
+ // whole thing that used to make a URL install die on its first line.
+ installer.installFromSource(name, source) { msg ->
+ runOnUiThread {
+ progressText.text = msg
+ val pct = msg.trimEnd('%').toIntOrNull()
+ if (pct != null && pct in 0..100) progressBar.progress = pct
+ }
+ }
+ progressBar.progress = 100
+ progressText.text = getString(R.string.ldi_done, name)
+ AppLog.i(this@LocalDistroInstallActivity, "LocalInstall", "installed $name from ${sourceSummary(source)}")
+ Toast.makeText(this@LocalDistroInstallActivity, getString(R.string.ldi_done, name), Toast.LENGTH_LONG).show()
+ } catch (e: Exception) {
+ AppLog.e(this@LocalDistroInstallActivity, "LocalInstall", "install failed: ${e::class.java.simpleName}: ${e.message}")
+ progressText.text = e.message ?: getString(R.string.ldi_failed)
+ Toast.makeText(this@LocalDistroInstallActivity, e.message ?: getString(R.string.ldi_failed), Toast.LENGTH_LONG).show()
+ } finally {
+ installing = false
+ refreshState()
+ }
+ }
+ }
+
+ private fun sourceSummary(s: DistroInstaller.InstallSource): String = when (s) {
+ is DistroInstaller.InstallSource.Local -> "a picked file"
+ is DistroInstaller.InstallSource.Url -> s.url
+ is DistroInstaller.InstallSource.Registry -> "registry image ${s.reference}"
+ }
+
+ private fun displayName(uri: Uri): String {
+ var name = uri.lastPathSegment ?: uri.toString()
+ contentResolver.query(uri, null, null, null, null)?.use { c ->
+ val idx = c.getColumnIndex(OpenableColumns.DISPLAY_NAME)
+ if (idx >= 0 && c.moveToFirst()) name = c.getString(idx)
+ }
+ return name
+ }
+
+ /** A usable distro key from the file name: strip the archive suffixes. */
+ private fun suggestName(uri: Uri): String =
+ displayName(uri)
+ .removeSuffix(".tar.xz").removeSuffix(".tar.gz").removeSuffix(".tar")
+ .removeSuffix(".xz").removeSuffix(".gz")
+ .trim()
+
+ private val View.isVisible: Boolean get() = visibility == View.VISIBLE
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", android.content.Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/LocalPortForward.kt b/app/src/main/java/com/redtermapp/ui/LocalPortForward.kt
new file mode 100644
index 0000000..65ada62
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/LocalPortForward.kt
@@ -0,0 +1,95 @@
+package com.redtermapp.ui
+
+import java.io.InputStream
+import java.net.InetAddress
+import java.net.ServerSocket
+import java.net.Socket
+import java.util.concurrent.atomic.AtomicBoolean
+
+/**
+ * A local port forward: a device-side port that relays TCP to the guest's
+ * loopback. A distro service bound to `127.0.0.1:PORT` inside the proot
+ * rootfs is reachable from the device's own apps and browser; this relay is
+ * for when you want a *different* device port (e.g. a port that is free and
+ * memorable) to reach that guest service, or to expose it while the guest is
+ * running.
+ *
+ * [Spec] is pure and unit-tested; [LocalPortRelay] runs the actual sockets and
+ * is exercised by a real local echo server in the test, so the pipe is proven
+ * rather than assumed.
+ */
+object LocalPortForward {
+
+ /** One relay: bytes from [fromPort] on the device go to [toHost]:[toPort]. */
+ data class Spec(val fromPort: Int, val toHost: String, val toPort: Int) {
+ init {
+ require(fromPort in 1..65535) { "from port out of range" }
+ require(toPort in 1..65535) { "to port out of range" }
+ require(toHost.isNotBlank()) { "no target host" }
+ }
+ val isValid: Boolean get() = fromPort in 1..65535 && toPort in 1..65535 && toHost.isNotBlank()
+ }
+
+ class LocalPortRelay(private val spec: Spec) : AutoCloseable {
+ private var server: ServerSocket? = null
+ private var worker: Thread? = null
+ private val running = AtomicBoolean(false)
+
+ /** Bind the relay and start piping connections. Throws when the port is taken. */
+ @Synchronized
+ fun start(): Boolean {
+ if (running.get()) return true
+ val ss = try {
+ ServerSocket(spec.fromPort)
+ } catch (_: Exception) {
+ return false
+ }
+ server = ss
+ running.set(true)
+ worker = Thread({
+ while (running.get()) {
+ val client = try { ss.accept() } catch (_: Exception) { break }
+ Thread({
+ var target: Socket? = null
+ try {
+ target = Socket(InetAddress.getByName(spec.toHost), spec.toPort)
+ val t = target!!
+ // Client -> guest, and guest -> client, each on its own thread.
+ Thread({ pump(client.getInputStream(), t.getOutputStream()) }, "redterm-pf-up").start()
+ pump(t.getInputStream(), client.getOutputStream())
+ } catch (_: Exception) {
+ } finally {
+ runCatching { client.close() }
+ runCatching { target?.close() }
+ }
+ }, "redterm-pf-$client").start()
+ }
+ }, "redterm-pf-accept").also { it.isDaemon = true; it.start() }
+ return true
+ }
+
+ /** The relay answers while its accept loop is up. A loop that breaks on
+ * a dead port reports false here, so a caller can tell a running relay
+ * from a dead one instead of trusting [start] returning true once. */
+ fun isRunning(): Boolean = running.get() && worker?.isAlive == true
+
+ private fun pump(in_: InputStream, out: java.io.OutputStream) {
+ val buf = ByteArray(8192)
+ while (true) {
+ val n = in_.read(buf)
+ if (n < 0) break
+ out.write(buf, 0, n)
+ out.flush()
+ }
+ }
+
+ @Synchronized
+ override fun close() {
+ running.set(false)
+ runCatching { server?.close() }
+ worker?.interrupt()
+ worker = null
+ server = null
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/LocalPortForwardActivity.kt b/app/src/main/java/com/redtermapp/ui/LocalPortForwardActivity.kt
new file mode 100644
index 0000000..901cd06
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/LocalPortForwardActivity.kt
@@ -0,0 +1,374 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.Spinner
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import com.redtermapp.R
+
+/**
+ * Open device ports that reach a target, and manage any number of them at
+ * once.
+ *
+ * The target is either the device itself (a guest service bound to
+ * `127.0.0.1` inside a proot distro) or a saved SSH server, in which case the
+ * forward rides `ssh -N -L` and the remote host:port is reached through the
+ * connection. Forwards are owned by [ForwardManager], so they stay open while
+ * the activity is closed and any mix of servers is reachable at the same time.
+ */
+class LocalPortForwardActivity : AppCompatActivity() {
+
+ private lateinit var active: LinearLayout
+ private lateinit var target: Spinner
+ private lateinit var presetRow: FlowLayout
+ private lateinit var fromPort: EditText
+ private lateinit var toHost: EditText
+ private lateinit var toPort: EditText
+ private lateinit var status: TextView
+ private var servers: List = emptyList()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.local_port_forward)
+ textSize = 20f
+ })
+
+ body.addView(sectionLabel(getString(R.string.lpf_active)))
+ active = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ body.addView(active)
+
+ body.addView(sectionLabel(getString(R.string.lpf_target)))
+ target = Spinner(this)
+ target.layoutParams = spaced()
+ body.addView(target)
+ presetRow = FlowLayout(this)
+ presetRow.layoutParams = spaced()
+ body.addView(presetRow)
+ fromPort = portField(getString(R.string.lpf_from))
+ fromPort.layoutParams = spaced()
+ body.addView(fromPort)
+ toHost = hostField()
+ toHost.layoutParams = spaced()
+ body.addView(toHost)
+ toPort = portField(getString(R.string.lpf_to))
+ toPort.layoutParams = spaced()
+ body.addView(toPort)
+
+ val actions = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ val addButton = ScreenWidgets.primaryButton(this, R.string.lpf_add) { addForward() }
+ addButton.layoutParams = LinearLayout.LayoutParams(
+ 0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f
+ )
+ actions.addView(addButton)
+ val saveButton = ScreenWidgets.actionButton(this, R.string.lpf_save_preset) { savePreset() }
+ saveButton.layoutParams = LinearLayout.LayoutParams(
+ 0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f
+ ).apply { leftMargin = (8 * resources.displayMetrics.density).toInt() }
+ actions.addView(saveButton)
+ actions.layoutParams = spaced()
+ body.addView(actions)
+
+ status = TextView(this).apply {
+ textSize = 12f
+ setPadding(0, 6, 0, 0)
+ setTextColor(mutedTextColor())
+ }
+ body.addView(status)
+ body.addView(laptopCard())
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.local_port_forward))
+ setContentView(root)
+
+ target.onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener {
+ override fun onItemSelected(
+ parent: android.widget.AdapterView<*>?, view: View?, position: Int, id: Long
+ ) {
+ // Position 0 is the device itself; a remote host field is only
+ // meaningful when a server is selected.
+ toHost.visibility = if (position == 0) View.GONE else View.VISIBLE
+ refreshPresets()
+ }
+
+ override fun onNothingSelected(parent: android.widget.AdapterView<*>?) = Unit
+ }
+ }
+
+ override fun onResume() {
+ super.onResume()
+ refreshTargets()
+ refreshActive()
+ refreshPresets()
+ }
+
+ private fun refreshTargets() {
+ servers = SshStore.load(applicationContext)
+ val labels = mutableListOf(getString(R.string.lpf_this_device))
+ labels.addAll(servers.map { it.label })
+ target.adapter = ScreenWidgets.spinner(this, labels).adapter
+ target.setSelection(0)
+ }
+
+ /** The server under the picker, or null when the device itself is chosen. */
+ private fun selectedServer(): SshStore.Server? =
+ if (target.selectedItemPosition == 0) null
+ else servers.getOrNull(target.selectedItemPosition - 1)
+
+ private fun refreshPresets() {
+ presetRow.removeAllViews()
+ val server = selectedServer() ?: return
+ val presets = ForwardPresetStore.load(applicationContext)[server.id] ?: return
+ for (p in presets) {
+ presetRow.addView(
+ presetChip("${p.fromPort} → ${p.toHost}:${p.toPort}") {
+ fromPort.setText(String.format(java.util.Locale.ROOT, "%d", p.fromPort))
+ toHost.setText(p.toHost)
+ toPort.setText(String.format(java.util.Locale.ROOT, "%d", p.toPort))
+ }
+ )
+ }
+ }
+
+ private fun presetChip(text: String, onTap: () -> Unit): View {
+ val d = resources.displayMetrics.density
+ val color = accentColor()
+ return TextView(this).apply {
+ this.text = text
+ textSize = 12f
+ setTextColor(color)
+ setBackgroundColor(withAlpha(color, 0.18f))
+ val px = (10 * d).toInt()
+ val py = (4 * d).toInt()
+ setPadding(px, py, px, py)
+ isClickable = true
+ isFocusable = true
+ setOnClickListener { onTap() }
+ // FlowLayout spaces its children itself, so the chip carries no margins.
+ layoutParams = FlowLayout.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT
+ )
+ }
+ }
+
+ private fun savePreset() {
+ val server = selectedServer()
+ if (server == null) {
+ status.text = getString(R.string.lpf_preset_server_only)
+ return
+ }
+ val from = fromPort.text.toString().toIntOrNull()
+ val to = toPort.text.toString().toIntOrNull()
+ if (from == null || to == null || from !in 1..65535 || to !in 1..65535) {
+ status.text = getString(R.string.lpf_failed, from ?: 0)
+ return
+ }
+ val host = toHost.text.toString().trim().ifEmpty { "127.0.0.1" }
+ ForwardPresetStore.addPreset(
+ applicationContext, server.id,
+ ForwardPresetStore.Preset(from, host, to)
+ )
+ status.text = getString(R.string.lpf_preset_saved)
+ refreshPresets()
+ }
+
+ /**
+ * How a forwarded port reaches a machine the user can type on.
+ *
+ * The forward binds a port on the *device*, so a laptop cannot reach it
+ * by address alone; it goes through adb (USB or over the network) or
+ * the phone's Wi-Fi address. Naming both, with USB first, is the answer
+ * that actually works on a phone that has no public address.
+ */
+ private fun laptopCard(): View {
+ val d = resources.displayMetrics.density
+ val card = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ val p = (10 * d).toInt()
+ setPadding(p, p, p, p)
+ setBackgroundColor(cardColor())
+ layoutParams = spaced()
+ }
+ card.addView(TextView(this).apply {
+ text = getString(R.string.lpf_laptop_title)
+ textSize = 12f
+ setTextColor(accentColor())
+ })
+ card.addView(TextView(this).apply {
+ text = getString(R.string.lpf_laptop_usb)
+ textSize = 11f
+ setTextColor(mutedTextColor())
+ setPadding(0, (4 * d).toInt(), 0, 0)
+ })
+ card.addView(TextView(this).apply {
+ text = getString(R.string.lpf_laptop_wifi)
+ textSize = 11f
+ setTextColor(mutedTextColor())
+ setPadding(0, (2 * d).toInt(), 0, 0)
+ })
+ return card
+ }
+
+ private fun refreshActive() {
+ active.removeAllViews()
+ val ids = ForwardManager.activeIds().filter { ForwardManager.isAlive(it) }
+ if (ids.isEmpty()) {
+ active.addView(TextView(this).apply {
+ setText(R.string.lpf_none_active)
+ setTextColor(mutedTextColor())
+ textSize = 12f
+ })
+ return
+ }
+ for (id in ids) active.addView(activeCard(id))
+ }
+
+ private fun activeCard(id: String): View {
+ val spec = ForwardManager.specFor(id)
+ val mapping = spec?.forward ?: ""
+ // The origin is what tells a device forward apart from a server one:
+ // "This device (guest)" versus the server's own label.
+ val origin = when (spec) {
+ is ForwardManager.SshSpec -> spec.server.label
+ is ForwardManager.LocalSpec -> getString(R.string.lpf_this_device)
+ else -> ""
+ }
+
+ val card = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(10, 10, 10, 10)
+ setBackgroundColor(cardColor())
+ layoutParams = LinearLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
+ ).apply {
+ setMargins(0, 0, 0, (6 * resources.displayMetrics.density).toInt())
+ }
+ }
+ card.addView(TextView(this).apply {
+ text = origin
+ textSize = 11f
+ setTextColor(accentColor())
+ setPadding(0, 0, 0, (4 * resources.displayMetrics.density).toInt())
+ })
+ val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ row.addView(TextView(this).apply {
+ text = mapping
+ textSize = 13f
+ setTextColor(cardTextColor())
+ layoutParams = LinearLayout.LayoutParams(
+ 0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f
+ )
+ })
+ row.addView(ScreenWidgets.dangerButton(this, R.string.lpf_stop) {
+ ForwardManager.stop(applicationContext, id)
+ refreshActive()
+ })
+ card.addView(row)
+ return card
+ }
+
+ private fun addForward() {
+ val from = fromPort.text.toString().toIntOrNull()
+ val to = toPort.text.toString().toIntOrNull()
+ if (from == null || to == null || from !in 1..65535 || to !in 1..65535) {
+ status.text = getString(R.string.lpf_failed, from ?: 0)
+ return
+ }
+ // The picker's first entry is "This device" and the rest are the saved
+ // servers, so position 0 is local and position N is servers[N - 1].
+ val pos = target.selectedItemPosition
+ val server = if (pos == 0) null else servers.getOrNull(pos - 1)
+ val id = if (server == null) {
+ ForwardManager.start(
+ this,
+ ForwardManager.LocalSpec(from, "127.0.0.1", to)
+ )
+ } else {
+ val host = toHost.text.toString().trim().ifEmpty { "127.0.0.1" }
+ ForwardManager.start(
+ this,
+ ForwardManager.SshSpec(
+ from, host, to, server,
+ SshKeyStore.identitiesFor(applicationContext, server)
+ )
+ )
+ }
+ if (id == null) {
+ status.text = getString(R.string.lpf_failed, from)
+ } else {
+ fromPort.text = null
+ toPort.text = null
+ toHost.text = null
+ status.text = ""
+ refreshActive()
+ }
+ }
+
+ /** Full-width, with a top gap so form fields don't crowd the line above. */
+ private fun spaced() = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT
+ ).apply { topMargin = (8 * resources.displayMetrics.density).toInt() }
+
+ private fun portField(hint: String): EditText = EditText(this).apply {
+ this.hint = hint
+ inputType = android.text.InputType.TYPE_CLASS_NUMBER
+ textSize = 14f
+ // Room below the text so the hint sits above the field's underline,
+ // not on it. Scaled by density: a raw pixel value is only a couple of
+ // dp on a phone, which is what left the text crowding the line.
+ val d = resources.displayMetrics.density
+ setPadding(0, (8 * d).toInt(), 0, (18 * d).toInt())
+ setTextColor(cardTextColor())
+ setHintTextColor(mutedTextColor())
+ }
+
+ private fun hostField(): EditText = EditText(this).apply {
+ hint = getString(R.string.lpf_to_host)
+ textSize = 14f
+ val d = resources.displayMetrics.density
+ setPadding(0, (8 * d).toInt(), 0, (18 * d).toInt())
+ setTextColor(cardTextColor())
+ setHintTextColor(mutedTextColor())
+ }
+
+ private fun sectionLabel(text: String) = TextView(this).apply {
+ this.text = text
+ textSize = 13f
+ setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0)
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/MainActivity.kt b/app/src/main/java/com/redtermapp/ui/MainActivity.kt
index 6062f46..4786f25 100644
--- a/app/src/main/java/com/redtermapp/ui/MainActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/MainActivity.kt
@@ -81,6 +81,70 @@ class MainActivity : AppCompatActivity() {
container.removeAllViews()
addDistroCards(container, installer.getInstalledDistros())
addToolCards(container)
+ addPinnedWorkspaces(container)
+ }
+
+ /**
+ * Workspaces the user pinned to the home screen: a named bundle that
+ * opens all of its sessions in one tap. Nothing is shown until one is
+ * pinned, so the default home screen is unchanged.
+ */
+ private fun addPinnedWorkspaces(container: LinearLayout) {
+ val pinned = WorkspaceStore.list(this).filter { it.pinned }
+ if (pinned.isEmpty()) return
+ val header = TextView(this).apply {
+ text = getString(R.string.workspaces_pinned)
+ setTextColor(tc(R.attr.terminalText, 0xFFCDD6F4.toInt()))
+ textSize = 13f
+ alpha = 0.7f
+ val pad = (8 * resources.displayMetrics.density).toInt()
+ setPadding(pad, pad, pad, pad / 2)
+ }
+ container.addView(header)
+ for (w in pinned) {
+ container.addView(pinnedWorkspaceCard(w))
+ }
+ }
+
+ private fun pinnedWorkspaceCard(w: WorkspaceStore.Workspace): View {
+ val card = MaterialCardView(this).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT
+ ).apply { setMargins(0, 0, 0, 12) }
+ setCardBackgroundColor(tc(R.attr.extraKeysBg, 0xFF181825.toInt()))
+ radius = 12f
+ setOnClickListener {
+ startActivity(
+ Intent(this@MainActivity, TerminalActivity::class.java)
+ .putExtra(TerminalActivity.EXTRA_WORKSPACE_ID, w.id)
+ )
+ }
+ addView(LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = android.view.Gravity.CENTER_VERTICAL
+ setPadding(24, 24, 24, 24)
+ addView(TextView(context).apply {
+ text = w.name
+ setTextColor(tc(R.attr.terminalText, 0xFFCDD6F4.toInt()))
+ textSize = 18f
+ setMinimumWidth(dp(140))
+ maxLines = 1
+ ellipsize = android.text.TextUtils.TruncateAt.END
+ })
+ addView(View(context).apply {
+ layoutParams = LinearLayout.LayoutParams(0, 1, 1f)
+ })
+ addView(TextView(context).apply {
+ text = resources.getQuantityString(
+ R.plurals.workspace_sessions, w.sessionCount(), w.sessionCount()
+ )
+ setTextColor(tc(R.attr.terminalText, 0xFFA6E3A1.toInt()))
+ textSize = 14f
+ })
+ })
+ }
+ return card
}
private fun addDistroCards(container: LinearLayout, installed: List) {
diff --git a/app/src/main/java/com/redtermapp/ui/MoreToolsActivity.kt b/app/src/main/java/com/redtermapp/ui/MoreToolsActivity.kt
new file mode 100644
index 0000000..cc3398b
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/MoreToolsActivity.kt
@@ -0,0 +1,108 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import com.redtermapp.R
+
+/**
+ * One place for the secondary screens, grouped the way the bashrc template
+ * button groups its templates. Each row names the tool and opens it; the
+ * settings screen reaches this hub through a single "More tools" row rather
+ * than one row per tool.
+ */
+class MoreToolsActivity : AppCompatActivity() {
+
+ private data class Tool(
+ val titleRes: Int,
+ val descRes: Int,
+ val target: Class<*>
+ )
+
+ private val tools = listOf(
+ Tool(R.string.workspaces, R.string.more_tools_workspaces_desc, WorkspaceActivity::class.java),
+ Tool(R.string.startup_hook, R.string.more_tools_startup_desc, StartupHookActivity::class.java),
+ Tool(R.string.snippets, R.string.more_tools_snippets_desc, SnippetLibraryActivity::class.java),
+ Tool(R.string.distro_dashboard, R.string.more_tools_dashboard_desc, DistroDashboardActivity::class.java),
+ Tool(R.string.scheduled_jobs, R.string.more_tools_jobs_desc, ScheduledJobsActivity::class.java),
+ Tool(R.string.ldi_title, R.string.more_tools_local_install_desc, LocalDistroInstallActivity::class.java)
+ )
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.more_tools)
+ textSize = 20f
+ setTextColor(cardTextColor())
+ })
+ val list = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ for (tool in tools) list.addView(row(tool))
+ body.addView(list)
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.more_tools))
+ setContentView(root)
+ }
+
+ private fun row(tool: Tool): View {
+ val pad = (10 * resources.displayMetrics.density).toInt()
+ val card = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ setBackgroundColor(cardColor())
+ setOnClickListener {
+ startActivity(Intent(this@MoreToolsActivity, tool.target))
+ }
+ layoutParams = LinearLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
+ ).apply {
+ val b = (8 * resources.displayMetrics.density).toInt()
+ setMargins(0, 0, 0, b)
+ }
+ }
+ card.addView(TextView(this).apply {
+ text = getString(tool.titleRes)
+ textSize = 15f
+ setTextColor(cardTextColor())
+ })
+ card.addView(TextView(this).apply {
+ text = getString(tool.descRes)
+ textSize = 12f
+ setTextColor(mutedTextColor())
+ })
+ return card
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/OrphanSweeper.kt b/app/src/main/java/com/redtermapp/ui/OrphanSweeper.kt
new file mode 100644
index 0000000..970eace
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/OrphanSweeper.kt
@@ -0,0 +1,93 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import com.redtermapp.util.AppLog
+import com.redtermapp.util.SshClient
+import java.io.File
+
+/**
+ * Reaps the standalone `ssh -N` processes a dead app left behind.
+ *
+ * A forward or tunnel is a child of the app, and Android's process death does
+ * not reach it: it is reparented to init and keeps holding its device port.
+ * The next cold start therefore has to find it, kill it, and re-open what the
+ * user asked to stay open — or the forwarded port is quietly dead while the
+ * last app process the user saw was "running fine".
+ *
+ * Only same-uid processes are visible in /proc, and every candidate here is
+ * the app's own child, so the kill needs no privilege. The matching and the
+ * kill command are pure and unit-tested; the /proc walk and the exec are the
+ * two things that may only be trusted by running them.
+ */
+object OrphanSweeper {
+
+ /**
+ * Whether [cmdline] is one of ours.
+ *
+ * The launcher script `exec`s proot, so the surviving process's argument
+ * vector is `proot ... -r ... /bin/ssh -N ...`. A distro session
+ * carries no `-N`, an SFTP connection says `-s ... sftp`, and a mosh
+ * client is the mosh binary — `-N` next to *this* rootfs is what makes it
+ * a standalone tunnel or forward, and nothing else.
+ */
+ fun isOrphan(cmdline: String, rootfsPath: String): Boolean =
+ cmdline.contains("-r $rootfsPath") &&
+ cmdline.contains("/bin/ssh") &&
+ cmdline.contains(" -N ")
+
+ /** The pids from [cmdlines] that are ours, never our own. */
+ fun scan(cmdlines: Map, rootfsPath: String, selfPid: Int): List =
+ cmdlines
+ .filter { (pid, cmdline) -> pid != selfPid && isOrphan(cmdline, rootfsPath) }
+ .keys
+ .sorted()
+
+ /** The `sh -c` line that kills [pids]; empty when there is nothing to kill. */
+ fun killCommand(pids: List): String =
+ if (pids.isEmpty()) "" else "kill -9 " + pids.joinToString(" ")
+
+ /**
+ * One pass: kill the orphaned `ssh -N` and clear the stale launcher
+ * scripts.
+ *
+ * Runs only on a cold start, before any forward or tunnel is resumed, so
+ * at that moment there is no live in-process forward whose script must be
+ * kept — every `forward-*.sh` and `tunnel-*.sh` still on disk belongs to
+ * the dead process.
+ */
+ fun sweep(context: Context) {
+ val rootfsPath = SshClient.rootfs(context).absolutePath
+ val pids = scan(procCmdlines(), rootfsPath, android.os.Process.myPid())
+ val command = killCommand(pids)
+ if (command.isNotEmpty()) {
+ runCatching { ProcessBuilder("/system/bin/sh", "-c", command).start() }
+ }
+ val stale = context.filesDir.listFiles()
+ ?.filter { it.name.endsWith(".sh") &&
+ (it.name.startsWith("forward-") || it.name.startsWith("tunnel-")) }
+ val removed = stale?.count { it.delete() } ?: 0
+ AppLog.i(
+ context, "port-forward",
+ "orphan sweep: killed ${pids.size} ssh -N process(es), cleared $removed stale script(s)"
+ )
+ }
+
+ /**
+ * The pids and cmdlines visible to this uid.
+ *
+ * /proc on Android lists a process's own uid only, which is exactly the
+ * set that can be an orphan of ours; an unreadable entry is skipped, not
+ * an error, because a sweep that throws has not killed anything.
+ */
+ private fun procCmdlines(): Map {
+ val proc = File("/proc")
+ val names = proc.list() ?: return emptyMap()
+ val result = HashMap()
+ for (name in names) {
+ val pid = name.toIntOrNull() ?: continue
+ val bytes = runCatching { File(proc, "$name/cmdline").readBytes() }.getOrNull() ?: continue
+ result[pid] = bytes.toString(Charsets.UTF_8).replace('\u0000', ' ')
+ }
+ return result
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/PackageUpdateActivity.kt b/app/src/main/java/com/redtermapp/ui/PackageUpdateActivity.kt
index 48dddcb..6a6906c 100644
--- a/app/src/main/java/com/redtermapp/ui/PackageUpdateActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/PackageUpdateActivity.kt
@@ -26,6 +26,9 @@ class PackageUpdateActivity : AppCompatActivity() {
companion object {
private const val NOTIFICATION_ID = 4201
private const val MAX_LOG_CHARS = 400_000
+
+ /** Pre-selects this distro when a caller (e.g. the dashboard) deep-links in. */
+ const val EXTRA_DISTRO = "distro"
}
private lateinit var distroSpinner: Spinner
@@ -36,6 +39,7 @@ class PackageUpdateActivity : AppCompatActivity() {
private var distros: List = emptyList()
private var running = false
+ private var pendingDistro: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
applyTheme()
@@ -91,6 +95,7 @@ class PackageUpdateActivity : AppCompatActivity() {
setContentView(root)
Notifier.ensureChannel(this)
+ pendingDistro = intent?.getStringExtra(EXTRA_DISTRO)
loadDistros()
distroSpinner.onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener {
override fun onItemSelected(
@@ -112,6 +117,9 @@ class PackageUpdateActivity : AppCompatActivity() {
android.R.layout.simple_spinner_dropdown_item,
installed.map { com.redtermapp.distro.DistroBrand.displayNameFor(it) }
)
+ installed.indexOfFirst { it == pendingDistro }.takeIf { it >= 0 }?.let {
+ distroSpinner.setSelection(it)
+ }
if (installed.isEmpty()) {
planLabel.setText(R.string.no_distros_installed)
runButton.isEnabled = false
@@ -131,10 +139,10 @@ class PackageUpdateActivity : AppCompatActivity() {
val distro = selectedDistro() ?: return
val rootfs = DistroInstaller(applicationContext).getRootfsDir(distro)
val plan = PackageUpdater.planFor(distro, rootfs)
- planLabel.text = if (plan.packageManager == "unknown") {
- getString(R.string.package_manager_unknown, distro)
- } else {
- getString(R.string.package_manager_detected, plan.packageManager)
+ planLabel.text = when (plan.packageManager) {
+ "unknown" -> getString(R.string.package_manager_unknown, distro)
+ "nix" -> getString(R.string.package_manager_nix, distro)
+ else -> getString(R.string.package_manager_detected, plan.packageManager)
}
}
@@ -143,8 +151,8 @@ class PackageUpdateActivity : AppCompatActivity() {
val distro = selectedDistro() ?: return
val rootfs = DistroInstaller(applicationContext).getRootfsDir(distro)
val plan = PackageUpdater.planFor(distro, rootfs)
- if (plan.packageManager == "unknown") {
- planLabel.text = getString(R.string.package_manager_unknown, distro)
+ if (plan.packageManager == "unknown" || plan.packageManager == "nix") {
+ updatePlanLabel()
return
}
running = true
diff --git a/app/src/main/java/com/redtermapp/ui/PlaybackPacing.kt b/app/src/main/java/com/redtermapp/ui/PlaybackPacing.kt
new file mode 100644
index 0000000..e3da00e
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/PlaybackPacing.kt
@@ -0,0 +1,18 @@
+package com.redtermapp.ui
+
+/**
+ * How fast a recording replays.
+ *
+ * The player's pacing is a fixed tick period; the speed only changes how many
+ * bytes are fed per tick. That keeps the tick cheap and the speed switch
+ * instant — no re-reading the file, just a wider or narrower read.
+ */
+object PlaybackPacing {
+
+ /** The offered speeds, slowest first. One is the recording's own pace. */
+ val SPEEDS = floatArrayOf(0.5f, 1f, 2f, 4f)
+
+ /** The bytes fed per tick at [speed] for a base chunk of [baseChunk]. */
+ fun chunkFor(speed: Float, baseChunk: Int): Int =
+ (baseChunk * speed).toInt().coerceAtLeast(1)
+}
diff --git a/app/src/main/java/com/redtermapp/ui/RecordingActivity.kt b/app/src/main/java/com/redtermapp/ui/RecordingActivity.kt
index 953f340..55f2329 100644
--- a/app/src/main/java/com/redtermapp/ui/RecordingActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/RecordingActivity.kt
@@ -2,12 +2,12 @@ package com.redtermapp.ui
import android.os.Bundle
import android.view.View
+import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
-import com.google.android.material.button.MaterialButton
import com.google.android.material.card.MaterialCardView
import androidx.appcompat.app.AppCompatActivity
import com.redtermapp.R
@@ -28,6 +28,7 @@ class RecordingActivity : AppCompatActivity() {
private lateinit var list: LinearLayout
private lateinit var root: LinearLayout
private lateinit var status: TextView
+ private lateinit var search: EditText
private val recorder by lazy { SessionRecorder(applicationContext) }
private val installer by lazy { DistroInstaller(applicationContext) }
private var busy = false
@@ -51,6 +52,21 @@ class RecordingActivity : AppCompatActivity() {
visibility = View.GONE
}
root.addView(status)
+ search = EditText(this).apply {
+ hint = getString(R.string.search)
+ textSize = 13f
+ setPadding(pad, 0, pad, 0)
+ setPadding(0, 6, 0, 6)
+ setTextColor(context.cardTextColor())
+ setHintTextColor(context.mutedTextColor())
+ setOnEditorActionListener { _, _, _ -> reload(); true }
+ }
+ search.addTextChangedListener(object : android.text.TextWatcher {
+ override fun afterTextChanged(s: android.text.Editable?) { reload() }
+ override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ })
+ root.addView(search)
list = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(0, 6, 0, 0)
@@ -89,12 +105,16 @@ class RecordingActivity : AppCompatActivity() {
}
if (busy) return
list.removeAllViews()
- val files = recorder.list()
+ val query = search.text?.toString().orEmpty()
+ val files = recorder.list().filter { RecordingIndex.matches(it.name, query) }
if (files.isEmpty()) {
- list.addView(TextView(this).apply { setText(R.string.record_no_recordings) })
+ list.addView(TextView(this).apply {
+ if (query.isBlank()) setText(R.string.record_no_recordings)
+ else text = getString(R.string.record_no_match, query.trim())
+ })
return
}
- for (file in files) {
+ for (file in RecordingIndex.newestFirst(files)) {
list.addView(row(file))
}
}
@@ -127,46 +147,81 @@ class RecordingActivity : AppCompatActivity() {
textSize = 11f
setPadding(0, 4, 0, 8)
})
- val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
- row.addView(
- MaterialButton(this).apply {
- setText(R.string.play)
- setOnClickListener {
- startActivity(
- android.content.Intent(
- this@RecordingActivity, RecordingPlayerActivity::class.java
- ).putExtra(RecordingPlayerActivity.EXTRA_PATH, file.absolutePath)
- )
- }
- },
- LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
- )
- row.addView(
- MaterialButton(this).apply {
- setText(R.string.share)
- setOnClickListener { shareRecording(file) }
- },
- LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
+ val row = FlowLayout(this).apply {
+ addView(ScreenWidgets.actionButton(this@RecordingActivity, R.string.play) {
+ startActivity(
+ android.content.Intent(
+ this@RecordingActivity, RecordingPlayerActivity::class.java
+ ).putExtra(RecordingPlayerActivity.EXTRA_PATH, file.absolutePath)
+ )
+ })
+ addView(ScreenWidgets.actionButton(this@RecordingActivity, R.string.recording_export_gif) {
+ exportGif(file)
+ })
+ addView(ScreenWidgets.actionButton(this@RecordingActivity, R.string.share) {
+ shareRecording(file)
+ })
+ addView(ScreenWidgets.dangerButton(this@RecordingActivity, R.string.delete) {
+ AlertDialog.Builder(this@RecordingActivity)
+ .setTitle(getString(R.string.delete_item, file.name))
+ .setMessage(R.string.delete_file_warning)
+ .setPositiveButton(R.string.delete) { _, _ ->
+ file.delete()
+ reload()
+ }
+ .setNegativeButton(R.string.cancel, null)
+ .show()
+ })
+ }
+ card.addView(row)
+ return card
+ }
+
+ /** Renders the recording to a GIF on a worker thread, then offers to share it. */
+ private fun exportGif(file: File) {
+ status.visibility = View.VISIBLE
+ status.text = getString(R.string.recording_exporting, file.name)
+ val target = File(file.parentFile, file.nameWithoutExtension + ".gif")
+ // Colours and font are read from the theme on the main thread; only
+ // the render and the LZW run on the worker.
+ val (fg, bg) = com.redtermapp.ui.TerminalTheming.themedColours(this)
+ val typeface = com.redtermapp.ui.TerminalTheming.fontFromPrefs(
+ this,
+ getSharedPreferences("settings", android.content.Context.MODE_PRIVATE)
)
- row.addView(
- MaterialButton(this).apply {
- setText(R.string.delete)
- setOnClickListener {
- AlertDialog.Builder(this@RecordingActivity)
- .setTitle(getString(R.string.delete_item, file.name))
- .setMessage(R.string.delete_file_warning)
- .setPositiveButton(R.string.delete) { _, _ ->
- file.delete()
- reload()
- }
- .setNegativeButton(R.string.cancel, null)
- .show()
+ Thread({
+ val result = try {
+ TerminalGif.export(file, target, fg, bg, typeface)
+ } catch (e: Exception) {
+ TerminalGif.Export(false, 0, null, e.message ?: "the export failed")
+ }
+ runOnUiThread {
+ status.visibility = View.GONE
+ if (result.ok) {
+ shareGif(file, result.file!!)
+ } else {
+ Toast.makeText(this, R.string.recording_export_failed, Toast.LENGTH_LONG).show()
+ com.redtermapp.util.AppLog.e(this, "Recording", "GIF export failed: ${result.detail}")
}
- },
- LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
+ }
+ }, "redterm-gif-export").apply { isDaemon = true }.start()
+ }
+
+ private fun shareGif(recording: File, gif: File) {
+ val uri = androidx.core.content.FileProvider.getUriForFile(
+ this, "${applicationContext.packageName}.fileprovider", gif
)
- card.addView(row)
- return card
+ val intent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
+ type = "image/gif"
+ putExtra(android.content.Intent.EXTRA_STREAM, uri)
+ addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ putExtra(android.content.Intent.EXTRA_SUBJECT, recording.name)
+ }
+ try {
+ startActivity(android.content.Intent.createChooser(intent, getString(R.string.share)))
+ } catch (_: Exception) {
+ Toast.makeText(this, R.string.share_failed, Toast.LENGTH_SHORT).show()
+ }
}
private fun shareRecording(file: File) {
diff --git a/app/src/main/java/com/redtermapp/ui/RecordingIndex.kt b/app/src/main/java/com/redtermapp/ui/RecordingIndex.kt
new file mode 100644
index 0000000..dcecd0f
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/RecordingIndex.kt
@@ -0,0 +1,21 @@
+package com.redtermapp.ui
+
+import java.io.File
+
+/**
+ * Pure ordering and filtering for the recordings list. Kept out of the
+ * Activity so the rules are unit-tested: a query is a case-insensitive
+ * substring of the file name, and an empty query matches everything, so the
+ * box doubles as a "clear the filter" rather than needing a second control.
+ */
+object RecordingIndex {
+
+ fun matches(fileName: String, query: String): Boolean {
+ val q = query.trim()
+ return q.isEmpty() || fileName.contains(q, ignoreCase = true)
+ }
+
+ /** The list as a user reads it: newest recording on top. */
+ fun newestFirst(files: List): List =
+ files.sortedByDescending { it.lastModified() }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/RecordingPlayerActivity.kt b/app/src/main/java/com/redtermapp/ui/RecordingPlayerActivity.kt
index 6177aae..c8e17b0 100644
--- a/app/src/main/java/com/redtermapp/ui/RecordingPlayerActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/RecordingPlayerActivity.kt
@@ -3,12 +3,13 @@ package com.redtermapp.ui
import android.content.Context
import android.graphics.Canvas
import android.os.Bundle
+import android.view.Gravity
+import android.widget.LinearLayout
+import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.redtermapp.R
import com.termux.terminal.TerminalEmulator
-import com.termux.terminal.TerminalOutput
-import com.termux.terminal.TerminalSessionClient
import com.termux.view.TerminalRenderer
import java.io.File
@@ -31,45 +32,19 @@ class RecordingPlayerActivity : AppCompatActivity() {
companion object {
const val EXTRA_PATH = "path"
- const val CHUNK_SIZE = 4096
- const val PACE_MS = 12L
+ // The feed's cadence lives in GifFramePlan so the GIF exporter's
+ // delay and the player's ticks can never disagree about the pace.
+ const val CHUNK_SIZE = com.redtermapp.util.GifFramePlan.CHUNK_SIZE
+ const val PACE_MS = com.redtermapp.util.GifFramePlan.PACE_MS
}
private lateinit var playbackView: PlaybackView
private lateinit var sessionFile: File
private var fontSize = 20
- private val output = object : TerminalOutput() {
- override fun write(data: ByteArray, offset: Int, count: Int) {}
- override fun titleChanged(title: String?, subtitle: String?) {}
- override fun onCopyTextToClipboard(text: String?) {}
- override fun onPasteTextFromClipboard() {}
- override fun onBell() {}
- override fun onColorsChanged() {}
- }
+ private val output: com.termux.terminal.TerminalOutput = TerminalTheming.headlessOutput
- private val client = object : TerminalSessionClient {
- override fun onTextChanged(session: com.termux.terminal.TerminalSession) = Unit
- override fun onTitleChanged(session: com.termux.terminal.TerminalSession) = Unit
- override fun onSessionFinished(session: com.termux.terminal.TerminalSession) = Unit
- override fun onCopyTextToClipboard(
- session: com.termux.terminal.TerminalSession,
- text: String?
- ) = Unit
-
- override fun onPasteTextFromClipboard(session: com.termux.terminal.TerminalSession) = Unit
- override fun onBell(session: com.termux.terminal.TerminalSession) = Unit
- override fun onColorsChanged(session: com.termux.terminal.TerminalSession) = Unit
- override fun onTerminalCursorStateChange(terminalCursorVisible: Boolean) = Unit
- override fun getTerminalCursorStyle(): Int? = null
- override fun logError(tag: String?, message: String?) = Unit
- override fun logWarn(tag: String?, message: String?) = Unit
- override fun logInfo(tag: String?, message: String?) = Unit
- override fun logDebug(tag: String?, message: String?) = Unit
- override fun logVerbose(tag: String?, message: String?) = Unit
- override fun logStackTraceWithMessage(tag: String?, message: String?, e: Exception?) = Unit
- override fun logStackTrace(tag: String?, e: Exception?) = Unit
- }
+ private val client: com.termux.terminal.TerminalSessionClient = TerminalTheming.headlessClient
override fun onCreate(savedInstanceState: Bundle?) {
applyTheme()
@@ -88,23 +63,78 @@ class RecordingPlayerActivity : AppCompatActivity() {
.getInt("font_size", 20)
playbackView = PlaybackView(this).apply { id = R.id.replay_terminal }
- setContentView(playbackView)
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(buildSpeedRow())
+ root.addView(
+ playbackView,
+ LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f
+ )
+ )
+ setContentView(root)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = getString(R.string.recording_replay)
}
/**
- * Feeds the file into [emulator], [CHUNK_SIZE] bytes per [PACE_MS], on a
- * background thread the way a session's own reader feeds its emulator, with
- * invalidation posted to the main thread.
+ * The speed row: one label per [PlaybackPacing.SPEEDS], the active one in
+ * the accent. Tapping a label re-paces the running feed — the worker reads
+ * [speed] every tick, so the switch takes effect on the next one.
+ */
+ private fun buildSpeedRow(): LinearLayout {
+ val row = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ val pad = (8 * resources.displayMetrics.density).toInt()
+ setPadding(pad, pad / 2, pad, pad / 2)
+ }
+ for (s in PlaybackPacing.SPEEDS) {
+ val label = TextView(this).apply {
+ text = getString(R.string.replay_speed_label, speedLabel(s))
+ textSize = 12f
+ val h = (12 * resources.displayMetrics.density).toInt()
+ setPadding(h, 0, h, 0)
+ setOnClickListener { setSpeed(s) }
+ }
+ speedLabels[s] = label
+ row.addView(label)
+ }
+ setSpeed(1f)
+ return row
+ }
+
+ private val speedLabels = HashMap()
+
+ /** The feed speed; the worker reads it every tick. */
+ @Volatile
+ private var speed = 1f
+
+ private fun setSpeed(new: Float) {
+ speed = new
+ for ((s, label) in speedLabels) {
+ label.setTextColor(if (s == new) accentColor() else mutedTextColor())
+ }
+ }
+
+ private fun speedLabel(s: Float): String =
+ if (s == s.toLong().toFloat()) s.toLong().toString() else s.toString()
+
+ /**
+ * Feeds the file into [emulator] on a background thread the way a session's
+ * own reader feeds its emulator, with invalidation posted to the main
+ * thread. Each tick feeds [PlaybackPacing.chunkFor] at the current [speed]
+ * and waits [PACE_MS], so a faster speed is a wider read, not a shorter
+ * sleep.
*/
private fun startPlayback(emulator: TerminalEmulator) {
Thread({
try {
sessionFile.inputStream().use { input ->
- val buffer = ByteArray(CHUNK_SIZE)
+ // The largest speed's chunk, allocated once: a wider read
+ // never needs a bigger buffer.
+ val buffer = ByteArray(PlaybackPacing.chunkFor(PlaybackPacing.SPEEDS.max(), CHUNK_SIZE))
while (true) {
- val read = input.read(buffer)
+ val read = input.read(buffer, 0, PlaybackPacing.chunkFor(speed, CHUNK_SIZE))
if (read <= 0) break
emulator.append(buffer, read)
playbackView.post { playbackView.invalidate() }
diff --git a/app/src/main/java/com/redtermapp/ui/ScheduledJobStore.kt b/app/src/main/java/com/redtermapp/ui/ScheduledJobStore.kt
new file mode 100644
index 0000000..6f735ae
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/ScheduledJobStore.kt
@@ -0,0 +1,149 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import androidx.core.content.edit
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * A guest job to run in a distro's rootfs on a schedule. Repeating jobs run
+ * every [intervalMinutes]; a one-shot job (interval 0) fires at [fireAtMs].
+ *
+ * The model and the "is it due / when is next" rules are pure so they are
+ * unit-tested; only the persistence and the actual running touch the device.
+ */
+data class ScheduledJob(
+ val id: String,
+ val name: String,
+ val distro: String,
+ val command: String,
+ val intervalMinutes: Int,
+ val fireAtMs: Long = 0L,
+ val enabled: Boolean = true,
+ val lastRunMs: Long = 0L,
+ /** Consecutive failed runs; a success resets it to zero. Drives the retry backoff. */
+ val consecutiveFails: Int = 0
+) {
+ val isRepeating: Boolean get() = intervalMinutes > 0
+
+ companion object {
+ fun toJson(j: ScheduledJob): String = JSONObject().apply {
+ put("id", j.id)
+ put("name", j.name)
+ put("distro", j.distro)
+ put("command", j.command)
+ put("interval", j.intervalMinutes)
+ put("fireAt", j.fireAtMs)
+ put("enabled", j.enabled)
+ put("lastRun", j.lastRunMs)
+ put("fails", j.consecutiveFails)
+ }.toString()
+
+ fun fromJson(s: String): ScheduledJob? =
+ runCatching {
+ val o = JSONObject(s)
+ ScheduledJob(
+ id = o.optString("id"),
+ name = o.optString("name"),
+ distro = o.optString("distro"),
+ command = o.optString("command"),
+ intervalMinutes = o.optInt("interval", 0),
+ fireAtMs = o.optLong("fireAt", 0L),
+ enabled = o.optBoolean("enabled", true),
+ lastRunMs = o.optLong("lastRun", 0L),
+ consecutiveFails = o.optInt("fails", 0)
+ )
+ }.getOrNull()
+
+ fun encodeAll(jobs: List): String =
+ JSONArray().apply { jobs.forEach { put(JSONObject(toJson(it))) } }.toString()
+
+ fun decodeAll(s: String): List =
+ runCatching {
+ val arr = JSONArray(s)
+ (0 until arr.length()).mapNotNull { fromJson(arr.optString(it)) }
+ }.getOrDefault(emptyList())
+ }
+}
+
+/** Pure scheduling decisions, independent of the device clock. */
+object JobSchedule {
+
+ private const val MIN_MS = 60_000L
+
+ /** True when a repeating job should run now, or a one-shot is overdue. */
+ fun dueNow(job: ScheduledJob, nowMs: Long): Boolean = when {
+ !job.enabled -> false
+ job.isRepeating -> {
+ val period = job.intervalMinutes.toLong() * MIN_MS
+ period > 0 && nowMs - job.lastRunMs >= period
+ }
+ else -> job.fireAtMs > 0L && job.fireAtMs <= nowMs && job.lastRunMs < job.fireAtMs
+ }
+
+ /** When a job will next run; 0 when it will not (disabled or one-shot already fired). */
+ fun nextRun(job: ScheduledJob, nowMs: Long): Long = when {
+ !job.enabled -> 0L
+ job.isRepeating -> maxOf(nowMs, job.lastRunMs) + job.intervalMinutes.toLong() * MIN_MS
+ else -> if (job.fireAtMs > nowMs) job.fireAtMs else 0L
+ }
+
+ /** A one-shot job that has fired is kept but no longer due. */
+ fun isSatisfied(job: ScheduledJob): Boolean =
+ !job.isRepeating && job.lastRunMs >= job.fireAtMs && job.fireAtMs > 0L
+
+ /**
+ * How many consecutive failures a job retries before falling back to its
+ * schedule and waiting for the user.
+ *
+ * Six: enough to ride out a transient blip (network down, a service
+ * still booting), few enough that a genuinely broken job stops hammering
+ * every few minutes forever.
+ */
+ const val MAX_CONSECUTIVE_FAILURES = 6
+
+ /**
+ * The delay before the Nth retry after consecutive failures.
+ *
+ * Doubling, 1-2-4-8, capped at fifteen: the first retry is quick because
+ * the most common cause is "the distro was still starting", and the cap
+ * means a dead job costs one run every fifteen minutes, not a storm.
+ * [f] is 1-based: the first failure waits one minute.
+ */
+ fun retryDelayMinutes(f: Int): Int = when {
+ f <= 0 -> 0
+ f == 1 -> 1
+ f == 2 -> 2
+ f == 3 -> 4
+ f == 4 -> 8
+ else -> 15
+ }
+
+ /** Whether a failed run still earns an immediate retry, or must wait for the schedule. */
+ fun shouldRetry(consecutiveFails: Int): Boolean =
+ consecutiveFails in 1..MAX_CONSECUTIVE_FAILURES
+}
+
+/** Persistence for scheduled jobs: survives process death, unlike in-memory state. */
+object ScheduledJobs {
+ private const val PREFS = "scheduled_jobs"
+ private const val KEY = "jobs"
+
+ fun load(context: Context): List =
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ .getString(KEY, "")
+ ?.let(ScheduledJob::decodeAll)
+ ?: emptyList()
+
+ fun save(context: Context, jobs: List) =
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ .edit { putString(KEY, ScheduledJob.encodeAll(jobs)) }
+
+ fun update(context: Context, job: ScheduledJob): List {
+ val jobs = load(context).toMutableList()
+ val i = jobs.indexOfFirst { it.id == job.id }
+ if (i >= 0) jobs[i] = job else jobs.add(job)
+ save(context, jobs)
+ return jobs
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/ScheduledJobWorker.kt b/app/src/main/java/com/redtermapp/ui/ScheduledJobWorker.kt
new file mode 100644
index 0000000..0c3c348
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/ScheduledJobWorker.kt
@@ -0,0 +1,109 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import androidx.work.Worker
+import androidx.work.WorkerParameters
+import com.redtermapp.distro.DistroRunner
+import com.redtermapp.util.Notifier
+import java.util.concurrent.TimeUnit
+
+/**
+ * Runs one scheduled guest job. WorkManager enqueues a periodic or one-time
+ * request; this worker loads the job by id, executes the command inside the
+ * distro's rootfs via [DistroRunner], records the run (what, when, the exit
+ * code, and the tail of the output), and tells the user through a
+ * notification.
+ *
+ * A failure retries on its own backoff — [JobSchedule.retryDelayMinutes] —
+ * so "the distro was still booting" does not have to wait a full interval.
+ * A retry is a one-time request under a separate unique tag, so it cannot
+ * replace the schedule itself.
+ */
+class ScheduledJobWorker(
+ context: Context,
+ params: WorkerParameters
+) : Worker(context, params) {
+
+ override fun doWork(): Result {
+ val id = inputData.getString(KEY_ID) ?: return Result.success()
+ val isRetry = inputData.getBoolean(KEY_RETRY, false)
+ val context = applicationContext
+ val job = ScheduledJobs.load(context).firstOrNull { it.id == id }
+ ?: return Result.success()
+ // A scheduled run must still be due; a retry is an explicit "run now".
+ if (!isRetry && !JobSchedule.dueNow(job, System.currentTimeMillis())) {
+ return Result.success()
+ }
+
+ val result = DistroRunner(context).run(job.distro, job.command, timeoutMinutes = 20)
+ val ok = result.succeeded
+ val fails = if (ok) 0 else job.consecutiveFails + 1
+ val now = System.currentTimeMillis()
+ val run = JobHistoryStore.JobRun(
+ jobId = id,
+ jobName = job.name,
+ distro = job.distro,
+ command = job.command,
+ atMs = now,
+ exitCode = if (result.exitCode >= 0) result.exitCode else -1,
+ outputTail = JobHistoryStore.outputTailOf(result.output)
+ )
+ JobHistoryStore.add(context, run)
+ // Both outcomes are recorded, because a "last run" that is not the
+ // last one is a stale one, and the retry count must not outlive a fix.
+ ScheduledJobs.update(
+ context,
+ job.copy(lastRunMs = now, consecutiveFails = fails)
+ )
+
+ val message = if (ok) {
+ "job finished"
+ } else {
+ val tail = run.outputTail
+ buildString {
+ append(if (result.timedOut) "job timed out" else "job exited ${result.exitCode}")
+ if (tail.isNotBlank()) append(" · ").append(tail)
+ }
+ }
+ Notifier.reportCompletion(
+ context,
+ id.hashCode(),
+ job.name,
+ message,
+ showToast = false
+ )
+
+ if (!ok && JobSchedule.shouldRetry(fails)) {
+ scheduleRetry(context, id, JobSchedule.retryDelayMinutes(fails))
+ }
+ return Result.success()
+ }
+
+ /**
+ * A one-time "run again" under its own tag, [delayMinutes] out.
+ *
+ * Separate from the schedule's tag on purpose: replacing the schedule to
+ * carry a retry would drop the interval a job was set on.
+ */
+ private fun scheduleRetry(context: Context, id: String, delayMinutes: Int) {
+ val req = androidx.work.OneTimeWorkRequestBuilder()
+ .setInputData(
+ androidx.work.workDataOf(KEY_ID to id, KEY_RETRY to true)
+ )
+ .setInitialDelay(delayMinutes.toLong(), TimeUnit.MINUTES)
+ .build()
+ androidx.work.WorkManager.getInstance(context).enqueueUniqueWork(
+ retryTagFor(id),
+ androidx.work.ExistingWorkPolicy.REPLACE,
+ req
+ )
+ }
+
+ companion object {
+ const val KEY_ID = "job_id"
+ const val KEY_RETRY = "job_retry"
+
+ fun tagFor(id: String) = "redterm-job-$id"
+ fun retryTagFor(id: String) = "redterm-job-retry-$id"
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/ScheduledJobsActivity.kt b/app/src/main/java/com/redtermapp/ui/ScheduledJobsActivity.kt
new file mode 100644
index 0000000..4da015e
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/ScheduledJobsActivity.kt
@@ -0,0 +1,311 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import androidx.work.ExistingPeriodicWorkPolicy
+import androidx.work.ExistingWorkPolicy
+import androidx.work.PeriodicWorkRequestBuilder
+import androidx.work.OneTimeWorkRequestBuilder
+import androidx.work.WorkManager
+import com.google.android.material.button.MaterialButton
+import com.redtermapp.R
+import com.redtermapp.distro.DistroInstaller
+import java.util.Locale
+import java.util.concurrent.TimeUnit
+
+/**
+ * Schedule guest jobs — commands to run inside a distro's rootfs on an
+ * interval or at a fixed time. Repeating jobs run as a periodic work item,
+ * one-shots as a one-time request; both report through a notification.
+ */
+class ScheduledJobsActivity : AppCompatActivity() {
+
+ private lateinit var container: LinearLayout
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.scheduled_jobs)
+ textSize = 20f
+ })
+ body.addView(ScreenWidgets.actionButton(this, R.string.scheduled_add) { addJob() })
+ container = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ body.addView(container)
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.scheduled_jobs))
+ setContentView(root)
+ load()
+ }
+
+ private fun load() {
+ Thread({
+ val jobs = ScheduledJobs.load(applicationContext)
+ runOnUiThread {
+ if (isFinishing || isDestroyed) return@runOnUiThread
+ container.removeAllViews()
+ if (jobs.isEmpty()) {
+ container.addView(TextView(this).apply {
+ setText(R.string.scheduled_jobs_none)
+ setTextColor(mutedTextColor())
+ })
+ return@runOnUiThread
+ }
+ for (job in jobs) container.addView(card(job))
+ }
+ }, "redterm-jobs-list").start()
+ }
+
+ private fun card(job: ScheduledJob): View {
+ val pad = (10 * resources.displayMetrics.density).toInt()
+ val card = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ setBackgroundColor(cardColor())
+ layoutParams = LinearLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
+ ).apply {
+ val b = (8 * resources.displayMetrics.density).toInt()
+ setMargins(0, 0, 0, b)
+ }
+ }
+ val sched = if (job.isRepeating)
+ getString(R.string.scheduled_every, job.intervalMinutes)
+ else
+ getString(R.string.scheduled_once)
+ val head = ScreenWidgets.headerRow(this).apply {
+ addView(TextView(this@ScheduledJobsActivity).apply {
+ text = job.name
+ textSize = 16f
+ setTextColor(cardTextColor())
+ })
+ addView(TextView(this@ScheduledJobsActivity).apply {
+ text = sched
+ textSize = 12f
+ setTextColor(if (job.enabled) accentColor() else mutedTextColor())
+ })
+ }
+ card.addView(head)
+ card.addView(TextView(this).apply {
+ text = getString(R.string.scheduled_job_line, job.distro, job.command)
+ textSize = 12f
+ setTextColor(mutedTextColor())
+ })
+ val next = JobSchedule.nextRun(job, System.currentTimeMillis())
+ if (next > 0L) {
+ card.addView(TextView(this).apply {
+ text = getString(
+ R.string.scheduled_next,
+ java.text.SimpleDateFormat("HH:mm", Locale.getDefault()).format(java.util.Date(next))
+ )
+ textSize = 11f
+ setTextColor(mutedTextColor())
+ })
+ }
+ val lastRun = JobHistoryStore.recent(this, 1).firstOrNull { it.jobId == job.id }
+ card.addView(TextView(this).apply {
+ text = when {
+ lastRun == null -> getString(R.string.scheduled_never_ran)
+ else -> buildString {
+ append(
+ getString(
+ R.string.scheduled_last_run,
+ java.text.SimpleDateFormat("HH:mm", Locale.getDefault())
+ .format(java.util.Date(lastRun.atMs)),
+ lastRun.exitCode
+ )
+ )
+ if (job.consecutiveFails > 0) {
+ append(" · ")
+ append(
+ resources.getQuantityString(
+ R.plurals.scheduled_failed_streak,
+ job.consecutiveFails,
+ job.consecutiveFails
+ )
+ )
+ }
+ }
+ }
+ textSize = 11f
+ setTextColor(mutedTextColor())
+ })
+ val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ row.addView(ScreenWidgets.actionButton(this,
+ if (job.enabled) R.string.scheduled_disable else R.string.scheduled_enable) {
+ val wm = WorkManager.getInstance(this)
+ if (job.enabled) {
+ wm.cancelUniqueWork(ScheduledJobWorker.tagFor(job.id))
+ wm.cancelUniqueWork(ScheduledJobWorker.retryTagFor(job.id))
+ ScheduledJobs.update(this, job.copy(enabled = false))
+ } else {
+ enqueue(job)
+ ScheduledJobs.update(this, job.copy(enabled = true))
+ }
+ load()
+ })
+ row.addView(ScreenWidgets.actionButton(this, R.string.scheduled_history) {
+ showHistory(job)
+ })
+ row.addView(ScreenWidgets.dangerButton(this, R.string.delete) {
+ val wm = WorkManager.getInstance(this)
+ wm.cancelUniqueWork(ScheduledJobWorker.tagFor(job.id))
+ wm.cancelUniqueWork(ScheduledJobWorker.retryTagFor(job.id))
+ JobHistoryStore.removeJob(this, job.id)
+ ScheduledJobs.save(
+ this,
+ ScheduledJobs.load(this).filter { it.id != job.id }
+ )
+ load()
+ })
+ card.addView(row)
+ return card
+ }
+
+ /** The recent runs of one job, with the end of each output. */
+ private fun showHistory(job: ScheduledJob) {
+ val runs = JobHistoryStore.forJob(this, job.id)
+ val text = if (runs.isEmpty()) {
+ getString(R.string.scheduled_history_empty)
+ } else {
+ runs.joinToString("\n\n") { r ->
+ buildString {
+ append(
+ java.text.SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
+ .format(java.util.Date(r.atMs))
+ )
+ append(" exit ")
+ append(r.exitCode)
+ val tail = r.outputTail.trim()
+ if (tail.isNotEmpty()) {
+ append('\n')
+ append(tail.lineSequence().toList().takeLast(3).joinToString("\n"))
+ }
+ }
+ }
+ }
+ ToolOutputDialog.show(
+ this,
+ getString(R.string.scheduled_history) + " · " + job.name,
+ text
+ )
+ }
+
+ private fun addJob() {
+ val distros = DistroInstaller(applicationContext).getInstalledDistros()
+ val name = EditText(this).apply { hint = getString(R.string.scheduled_job_name); setTextColor(context.cardTextColor()); setHintTextColor(context.mutedTextColor()) }
+ val distro = ScreenWidgets.spinner(
+ this, distros.map { com.redtermapp.distro.DistroBrand.displayNameFor(it) }
+ )
+ val command = EditText(this).apply {
+ hint = getString(R.string.scheduled_job_command)
+ minLines = 2
+ setTextColor(context.cardTextColor())
+ setHintTextColor(context.mutedTextColor())
+ }
+ val interval = EditText(this).apply {
+ hint = getString(R.string.scheduled_job_interval)
+ inputType = android.text.InputType.TYPE_CLASS_NUMBER
+ setTextColor(context.cardTextColor())
+ setHintTextColor(context.mutedTextColor())
+ }
+
+ val panel = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ val p = (12 * resources.displayMetrics.density).toInt()
+ setPadding(p, p, p, p)
+ addView(name)
+ addView(TextView(this@ScheduledJobsActivity).apply {
+ text = getString(R.string.scheduled_distro)
+ setPadding(0, p, 0, 0)
+ })
+ addView(distro)
+ addView(command)
+ addView(interval)
+ }
+ AlertDialog.Builder(this)
+ .setTitle(R.string.scheduled_add)
+ .setView(panel)
+ .setPositiveButton(R.string.save) { _, _ ->
+ val minutes = interval.text?.toString()?.toIntOrNull() ?: 0
+ val job = ScheduledJob(
+ id = System.currentTimeMillis().toString(),
+ name = name.text?.toString()?.takeIf { it.isNotBlank() } ?: "Job",
+ distro = distros.getOrElse(distro.selectedItemPosition) { distros.firstOrNull() ?: "" },
+ command = command.text?.toString()?.takeIf { it.isNotBlank() } ?: "true",
+ intervalMinutes = minutes.coerceAtLeast(0),
+ fireAtMs = if (minutes == 0) System.currentTimeMillis() + 60_000L else 0L
+ )
+ val list = ScheduledJobs.load(this).toMutableList()
+ list.add(job)
+ ScheduledJobs.save(this, list)
+ if (job.enabled) enqueue(job)
+ load()
+ }
+ .setNegativeButton(R.string.cancel, null)
+ .show()
+ }
+
+ private fun enqueue(job: ScheduledJob) {
+ val wm = WorkManager.getInstance(this)
+ val data = androidx.work.workDataOf(ScheduledJobWorker.KEY_ID to job.id)
+ if (job.isRepeating) {
+ // Periodic work cannot run more often than every 15 minutes; clamp so a
+ // shorter user interval still means "as often as the system will allow".
+ val minutes = job.intervalMinutes.toLong().coerceAtLeast(15L)
+ val req = PeriodicWorkRequestBuilder(minutes, TimeUnit.MINUTES)
+ .setInputData(data)
+ .setInitialDelay(minutes, TimeUnit.MINUTES)
+ .build()
+ wm.enqueueUniquePeriodicWork(
+ ScheduledJobWorker.tagFor(job.id),
+ ExistingPeriodicWorkPolicy.REPLACE,
+ req
+ )
+ } else {
+ val req = OneTimeWorkRequestBuilder()
+ .setInputData(data)
+ .build()
+ wm.enqueueUniqueWork(
+ ScheduledJobWorker.tagFor(job.id),
+ ExistingWorkPolicy.REPLACE,
+ req
+ )
+ }
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/ScreenWidgets.kt b/app/src/main/java/com/redtermapp/ui/ScreenWidgets.kt
index d4967ab..11b0045 100644
--- a/app/src/main/java/com/redtermapp/ui/ScreenWidgets.kt
+++ b/app/src/main/java/com/redtermapp/ui/ScreenWidgets.kt
@@ -2,7 +2,11 @@ package com.redtermapp.ui
import android.content.Context
import android.view.Gravity
+import android.view.View
+import android.widget.ArrayAdapter
import android.widget.LinearLayout
+import android.widget.Spinner
+import android.widget.TextView
import androidx.annotation.ColorInt
import com.google.android.material.button.MaterialButton
import com.google.android.material.chip.Chip
@@ -75,6 +79,51 @@ object ScreenWidgets {
setOnClickListener { onClick() }
}
+ /**
+ * [buttons] in a two-column grid, every cell the same width, aligned row on row.
+ *
+ * Natural-width buttons in a wrapping row do not line up: each takes the width its
+ * label asks for, so the second row starts wherever the first row happened to end,
+ * and a button under another sits off to one side. Equal-width cells make every
+ * button the same size and put each directly under the one above it.
+ *
+ * The only thing that would make a half-width cell ugly is a label wrapping to one
+ * word per line — and [actionButton] already forces `maxLines = 1` with an
+ * ellipsize, so a long label shortens instead of stacking. An odd count leaves a
+ * spacer in the last cell so the lone button stays one column wide, not full width.
+ */
+ fun buttonGrid(context: Context, buttons: List): LinearLayout {
+ val grid = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
+ val gap = (6 * context.resources.displayMetrics.density).toInt()
+ val rows = (buttons.size + 1) / 2
+ for (r in 0 until rows) {
+ val row = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL }
+ if (r > 0) {
+ row.layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT
+ ).apply { topMargin = gap }
+ }
+ val first = buttons[r * 2]
+ val second = buttons.getOrNull(r * 2 + 1)
+ first.layoutParams = LinearLayout.LayoutParams(
+ 0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f
+ ).apply { rightMargin = if (second != null) gap else 0 }
+ row.addView(first)
+ if (second != null) {
+ second.layoutParams = LinearLayout.LayoutParams(
+ 0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f
+ )
+ row.addView(second)
+ } else {
+ // Keep the lone button one column wide, not stretched across the row.
+ row.addView(View(context), LinearLayout.LayoutParams(0, 0, 1f))
+ }
+ grid.addView(row)
+ }
+ return grid
+ }
+
/**
* The one thing you came to this card to do.
*
@@ -127,4 +176,43 @@ object ScreenWidgets {
setTextColor(error)
setOnClickListener { onClick() }
}
+
+ /**
+ * A Spinner whose items are painted in the theme's own text colour.
+ *
+ * The framework's `simple_spinner_item` and `simple_spinner_dropdown_item` do not
+ * reliably follow this app's theme pinning, so on a dark theme the selected name and
+ * the drop-down items can render nearly invisible. Painting the text here is what
+ * makes the item readable on every theme rather than depending on a widget default.
+ */
+ fun spinner(context: Context, items: List): Spinner {
+ val color = context.cardTextColor()
+ val density = context.resources.displayMetrics.density
+ val adapter = object : ArrayAdapter(context, android.R.layout.simple_spinner_item, items) {
+ override fun getView(
+ position: Int, convertView: View?, parent: android.view.ViewGroup
+ ): View {
+ val tv = (convertView as? TextView) ?: TextView(context)
+ tv.text = getItem(position)
+ tv.textSize = 14f
+ tv.setTextColor(color)
+ return tv
+ }
+
+ override fun getDropDownView(
+ position: Int, convertView: View?, parent: android.view.ViewGroup
+ ): View {
+ val tv = (convertView as? TextView) ?: TextView(context)
+ tv.text = getItem(position)
+ tv.textSize = 14f
+ tv.setTextColor(color)
+ val p = (12 * density).toInt()
+ tv.setPadding(p, p, p, p)
+ return tv
+ }
+ }
+ val s = Spinner(context)
+ s.adapter = adapter
+ return s
+ }
}
\ No newline at end of file
diff --git a/app/src/main/java/com/redtermapp/ui/SettingsActivity.kt b/app/src/main/java/com/redtermapp/ui/SettingsActivity.kt
index 4587706..e7f7e8f 100644
--- a/app/src/main/java/com/redtermapp/ui/SettingsActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/SettingsActivity.kt
@@ -127,6 +127,10 @@ class SettingsActivity : AppCompatActivity() {
startActivity(Intent(this, BashTemplatesActivity::class.java))
}
+ findViewById(R.id.more_tools_btn).setOnClickListener {
+ startActivity(Intent(this, MoreToolsActivity::class.java))
+ }
+
val fontSlider = findViewById(R.id.font_size_slider)
val wakelockSwitch = findViewById(R.id.wakelock_switch)
val versionInfo = findViewById(R.id.version_info)
diff --git a/app/src/main/java/com/redtermapp/ui/SnippetLibraryActivity.kt b/app/src/main/java/com/redtermapp/ui/SnippetLibraryActivity.kt
new file mode 100644
index 0000000..55648cc
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/SnippetLibraryActivity.kt
@@ -0,0 +1,208 @@
+package com.redtermapp.ui
+
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.redtermapp.R
+
+/**
+ * The snippet library: search, recents, and per-item send/copy/edit/delete.
+ *
+ * "Send to terminal" hands the text to [TerminalActivity] through
+ * [TerminalActivity.EXTRA_TYPE_TEXT] and marks the snippet used, so the next
+ * time it sorts to the top of the list. A copy is also offered, because the
+ * terminal that is focused may not be the one on screen.
+ */
+class SnippetLibraryActivity : AppCompatActivity() {
+
+ private lateinit var search: EditText
+ private lateinit var list: LinearLayout
+ private var shown: List = emptyList()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.snippets)
+ textSize = 20f
+ })
+ search = EditText(this).apply {
+ hint = getString(R.string.snippet_search)
+ setSingleLine(true)
+ setTextColor(context.cardTextColor())
+ setHintTextColor(context.mutedTextColor())
+ }
+ search.addTextChangedListener(object : android.text.TextWatcher {
+ override fun afterTextChanged(s: android.text.Editable?) {
+ filter(search.text.toString())
+ }
+
+ override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) = Unit
+ override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) = Unit
+ })
+ body.addView(search)
+ list = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ body.addView(list)
+ body.addView(ScreenWidgets.primaryButton(this, R.string.snippet_new) { edit(null) })
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.snippets))
+ setContentView(root)
+ filter("")
+ }
+
+ private fun filter(query: String) {
+ shown = SnippetStore.byRecency(SnippetStore.search(SnippetStore.list(this), query))
+ rebuild()
+ }
+
+ private fun rebuild() {
+ list.removeAllViews()
+ if (shown.isEmpty()) {
+ list.addView(TextView(this).apply {
+ setText(R.string.snippet_none)
+ setTextColor(mutedTextColor())
+ })
+ return
+ }
+ for (s in shown) list.addView(row(s))
+ }
+
+ private fun row(s: SnippetStore.Snippet): View {
+ val pad = (10 * resources.displayMetrics.density).toInt()
+ val card = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ setBackgroundColor(cardColor())
+ layoutParams = LinearLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
+ ).apply {
+ val b = (8 * resources.displayMetrics.density).toInt()
+ setMargins(0, 0, 0, b)
+ }
+ }
+ val head = ScreenWidgets.headerRow(this).apply {
+ addView(TextView(this@SnippetLibraryActivity).apply {
+ text = s.name
+ textSize = 15f
+ setTextColor(cardTextColor())
+ })
+ if (s.folder.isNotEmpty()) {
+ addView(ScreenWidgets.chip(this@SnippetLibraryActivity, s.folder, accentColor()))
+ }
+ }
+ card.addView(head)
+ card.addView(TextView(this).apply {
+ text = s.content.take(160)
+ textSize = 12f
+ setTextColor(mutedTextColor())
+ maxLines = 3
+ })
+ val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ row.addView(ScreenWidgets.actionButton(this, R.string.snippet_send) { send(s) })
+ row.addView(ScreenWidgets.actionButton(this, R.string.snippet_copy) { copy(s) })
+ row.addView(ScreenWidgets.actionButton(this, R.string.snippet_edit) { edit(s) })
+ row.addView(ScreenWidgets.dangerButton(this, R.string.snippet_delete) { delete(s) })
+ card.addView(row)
+ return card
+ }
+
+ private fun send(s: SnippetStore.Snippet) {
+ SnippetStore.touch(this, s.id)
+ startActivity(
+ Intent(this, TerminalActivity::class.java)
+ .putExtra(TerminalActivity.EXTRA_TYPE_TEXT, s.content)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ )
+ filter(search.text.toString())
+ }
+
+ private fun copy(s: SnippetStore.Snippet) {
+ runCatching {
+ (getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager)
+ .setPrimaryClip(ClipData.newPlainText(s.name, s.content))
+ }.onSuccess {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.snippets)
+ .setMessage(R.string.snippet_copied)
+ .setPositiveButton(android.R.string.ok, null)
+ .show()
+ }
+ }
+
+ private fun edit(s: SnippetStore.Snippet?) {
+ val name = EditText(this).apply { hint = getString(R.string.snippet_name); setText(s?.name ?: ""); setTextColor(context.cardTextColor()); setHintTextColor(context.mutedTextColor()) }
+ val content = EditText(this).apply { hint = getString(R.string.snippet_content); setText(s?.content ?: ""); setTextColor(context.cardTextColor()); setHintTextColor(context.mutedTextColor()) }
+ val folder = EditText(this).apply { hint = getString(R.string.snippet_folder); setText(s?.folder ?: ""); setTextColor(context.cardTextColor()); setHintTextColor(context.mutedTextColor()) }
+ val box = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ val p = (16 * resources.displayMetrics.density).toInt()
+ setPadding(p, p / 2, p, p / 2)
+ addView(name); addView(content); addView(folder)
+ }
+ AlertDialog.Builder(this)
+ .setTitle(if (s == null) getString(R.string.snippet_new) else s.name)
+ .setView(box)
+ .setPositiveButton(android.R.string.ok) { _, _ ->
+ val nm = name.text.toString().trim()
+ if (nm.isEmpty()) return@setPositiveButton
+ val id = s?.id ?: SnippetStore.newSnippet(nm, "").id
+ SnippetStore.upsert(
+ this,
+ SnippetStore.Snippet(id, nm, content.text.toString(), folder.text.toString().trim())
+ )
+ filter(this.search.text.toString())
+ }
+ .setNegativeButton(android.R.string.cancel, null)
+ .show()
+ }
+
+ private fun delete(s: SnippetStore.Snippet) {
+ AlertDialog.Builder(this)
+ .setTitle(R.string.snippets)
+ .setMessage("Delete \"$s.name\"?")
+ .setPositiveButton(android.R.string.ok) { _, _ ->
+ SnippetStore.delete(this, s.id)
+ filter(search.text.toString())
+ }
+ .setNegativeButton(android.R.string.cancel, null)
+ .show()
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/SnippetStore.kt b/app/src/main/java/com/redtermapp/ui/SnippetStore.kt
new file mode 100644
index 0000000..2de4313
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/SnippetStore.kt
@@ -0,0 +1,145 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import androidx.core.content.edit
+import org.json.JSONArray
+import org.json.JSONObject
+import java.util.UUID
+
+/**
+ * A durable command/text snippet library.
+ *
+ * Supersedes the flat "snippets" list the terminal menu kept in the general
+ * settings prefs: that list could grow duplicate names, had no search, no
+ * folders, and no recency. This store is JSON in its own prefs file, de-dups
+ * by name on save, records last-use for a "recents" ordering, and — so an
+ * upgrade never loses what the user typed in the old dialog — migrates the
+ * legacy flat list on first read.
+ */
+object SnippetStore {
+
+ const val PREFS = "snippets"
+ private const val KEY = "library"
+ private const val LEGACY_PREFS = "settings"
+ private const val LEGACY_KEY = "snippets"
+
+ data class Snippet(
+ val id: String,
+ val name: String,
+ val content: String,
+ val folder: String = "",
+ val lastUsedAt: Long = 0L
+ )
+
+ /** Every snippet; [legacy] (from settings prefs) is folded in once. */
+ fun list(context: Context, migrate: Boolean = true): List {
+ val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null)
+ val current = fromJson(raw)
+ if (!current.isEmpty() || !migrate) return current
+ // First run: rescue the legacy flat list so nothing typed by hand is lost.
+ val legacy = legacyList(context)
+ if (legacy.isEmpty()) return current
+ save(context, legacy)
+ return legacy
+ }
+
+ fun save(context: Context, snippets: List) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit {
+ putString(KEY, toJson(snippets))
+ }
+ }
+
+ /** De-dup by name: editing a snippet keeps its id; adding replaces same-name. */
+ fun upsert(context: Context, snippet: Snippet): List {
+ val all = list(context).filterNot { it.name == snippet.name } + snippet
+ save(context, all)
+ return all
+ }
+
+ fun delete(context: Context, id: String) {
+ save(context, list(context).filterNot { it.id == id })
+ }
+
+ fun touch(context: Context, id: String) {
+ save(context, list(context).map {
+ if (it.id == id) it.copy(lastUsedAt = System.currentTimeMillis()) else it
+ })
+ }
+
+ fun get(context: Context, id: String): Snippet? = list(context).firstOrNull { it.id == id }
+
+ fun newSnippet(name: String, content: String, folder: String = ""): Snippet =
+ Snippet(id = UUID.randomUUID().toString(), name = name, content = content, folder = folder)
+
+ // --- pure, so search/ordering are unit-testable off-device ---
+
+ /** Case-insensitive substring match over name and content. */
+ fun search(snippets: List, query: String): List {
+ val q = query.trim()
+ if (q.isEmpty()) return snippets
+ val needle = q.lowercase()
+ return snippets.filter {
+ it.name.lowercase().contains(needle) || it.content.lowercase().contains(needle)
+ }
+ }
+
+ /** Most-recently-used first; never-used snippets keep their order after them. */
+ fun byRecency(snippets: List): List {
+ val used = snippets.filter { it.lastUsedAt > 0 }.sortedByDescending { it.lastUsedAt }
+ val unused = snippets.filter { it.lastUsedAt == 0L }
+ return used + unused
+ }
+
+ /** Distinct, non-blank folders in first-seen order; blank is "General". */
+ fun folders(snippets: List): List =
+ snippets.map { it.folder }.filter { it.isNotEmpty() }.distinct()
+
+ fun toJson(list: List): String =
+ JSONArray().also { arr ->
+ for (s in list) {
+ arr.put(JSONObject().apply {
+ put("id", s.id)
+ put("name", s.name)
+ put("content", s.content)
+ put("folder", s.folder)
+ put("lastUsedAt", s.lastUsedAt)
+ })
+ }
+ }.toString()
+
+ fun fromJson(raw: String?): List {
+ if (raw.isNullOrBlank()) return emptyList()
+ return try {
+ val arr = JSONArray(raw)
+ (0 until arr.length()).mapNotNull { n ->
+ val o = arr.optJSONObject(n) ?: return@mapNotNull null
+ val name = o.optString("name").takeIf { it.isNotEmpty() } ?: return@mapNotNull null
+ Snippet(
+ id = o.optString("id").takeIf { it.isNotEmpty() } ?: name,
+ name = name,
+ content = o.optString("content"),
+ folder = o.optString("folder"),
+ lastUsedAt = o.optLong("lastUsedAt", 0L)
+ )
+ }
+ } catch (_: Exception) {
+ emptyList()
+ }
+ }
+
+ /** The legacy flat {name,content} array, as current [Snippet]s. */
+ private fun legacyList(context: Context): List {
+ val raw = context.getSharedPreferences(LEGACY_PREFS, Context.MODE_PRIVATE)
+ .getString(LEGACY_KEY, "[]") ?: "[]"
+ return try {
+ val arr = JSONArray(raw)
+ (0 until arr.length()).mapNotNull { n ->
+ val o = arr.optJSONObject(n) ?: return@mapNotNull null
+ val name = o.optString("name").takeIf { it.isNotEmpty() } ?: return@mapNotNull null
+ Snippet(id = UUID.randomUUID().toString(), name = name, content = o.optString("content"))
+ }
+ } catch (_: Exception) {
+ emptyList()
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/SshManagerActivity.kt b/app/src/main/java/com/redtermapp/ui/SshManagerActivity.kt
index 2a0a88d..c74be30 100644
--- a/app/src/main/java/com/redtermapp/ui/SshManagerActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/SshManagerActivity.kt
@@ -54,12 +54,12 @@ class SshManagerActivity : AppCompatActivity() {
)
)
- // A wrapping row, not four equal weights. Weights divide the width before
- // anything is measured, so four of them on a phone give each label a quarter
- // of the screen, and "Trusted hosts" becomes one word per line.
- val buttons = FlowLayout(this)
+ // Two equal-width columns so every button lines up under the one above it,
+ // instead of a wrapping row where each button takes its label's width and the
+ // rows start off to different sides.
+ val topButtons = mutableListOf()
fun topAction(labelRes: Int, onClick: () -> Unit) {
- buttons.addView(ScreenWidgets.actionButton(this, labelRes, onClick))
+ topButtons.add(ScreenWidgets.actionButton(this, labelRes, onClick))
}
topAction(R.string.ssh_add_server) { editServer(null) }
topAction(R.string.ssh_manage_keys) {
@@ -69,8 +69,18 @@ class SshManagerActivity : AppCompatActivity() {
}
topAction(R.string.ssh_trusted_hosts) { showTrustedHosts() }
topAction(R.string.ssh_import_config) { promptImportConfig() }
+ topAction(R.string.tunnel_manager) {
+ startActivity(
+ android.content.Intent(this@SshManagerActivity, TunnelManagerActivity::class.java)
+ )
+ }
+ topAction(R.string.local_port_forward) {
+ startActivity(
+ android.content.Intent(this@SshManagerActivity, LocalPortForwardActivity::class.java)
+ )
+ }
root.addView(
- buttons,
+ ScreenWidgets.buttonGrid(this, topButtons),
LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
@@ -192,17 +202,15 @@ class SshManagerActivity : AppCompatActivity() {
)
}
body.addView(keyRow)
- // A wrapping row rather than rows of equal weights. Weights divide the width
- // before anything is measured, so three buttons on a phone each get a third of
- // the screen and their labels wrap one word per line — which is what this card
- // did with four.
- val actions = FlowLayout(this)
+ // Two equal-width columns so the card's buttons line up under each other,
+ // instead of a wrapping row where each button takes its label's width.
+ val cardButtons = mutableListOf()
fun action(labelRes: Int, onClick: () -> Unit) {
- actions.addView(ScreenWidgets.actionButton(this, labelRes, onClick))
+ cardButtons.add(ScreenWidgets.actionButton(this, labelRes, onClick))
}
// The one button here that is not peer to the others: Connect is what this card is
// for, and five outlined buttons in a row gave no answer to which one to press.
- actions.addView(
+ cardButtons.add(
ScreenWidgets.primaryButton(this, R.string.ssh_connect) { connect(server) }
)
action(R.string.ssh_test) { testConnection(server) }
@@ -237,9 +245,10 @@ class SshManagerActivity : AppCompatActivity() {
.setNegativeButton(R.string.cancel, null)
.show()
}
- actions.addView(
+ cardButtons.add(
ScreenWidgets.dangerButton(this, R.string.delete) { delete() }
)
+ val actions = ScreenWidgets.buttonGrid(this, cardButtons)
body.addView(
actions,
LinearLayout.LayoutParams(
diff --git a/app/src/main/java/com/redtermapp/ui/StartupHookActivity.kt b/app/src/main/java/com/redtermapp/ui/StartupHookActivity.kt
new file mode 100644
index 0000000..b89eb33
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/StartupHookActivity.kt
@@ -0,0 +1,221 @@
+package com.redtermapp.ui
+
+import android.content.Intent
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.Spinner
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.appcompat.app.AlertDialog
+import com.redtermapp.R
+import com.redtermapp.distro.DistroInstaller
+import com.redtermapp.util.AppLog
+import com.redtermapp.util.api.ApiHelper
+import java.io.File
+
+/**
+ * The user-managed /root/.startup.local hook, with a face on it.
+ *
+ * The launcher runs the hook only when it exists and the session is
+ * interactive, and RedTerm never rewrites it — so this screen is the only
+ * place that creates, edits, deletes, or regenerates it. "Write safe
+ * starter" is refusal-aware: a file the user has hand-written (no RedTerm
+ * marker) is never clobbered.
+ */
+class StartupHookActivity : AppCompatActivity() {
+
+ private val installer by lazy { DistroInstaller(applicationContext) }
+ private var distros: List = emptyList()
+ private var current: String? = null
+
+ private lateinit var spinner: Spinner
+ private lateinit var statusLine: TextView
+ private lateinit var preview: TextView
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.startup_hook)
+ textSize = 20f
+ })
+ body.addView(sectionLabel(getString(R.string.startup_hook_distro)))
+ spinner = Spinner(this)
+ body.addView(spinner)
+ statusLine = TextView(this).apply {
+ textSize = 13f
+ setPadding(0, (8 * resources.displayMetrics.density).toInt(), 0, 0)
+ }
+ body.addView(statusLine)
+ body.addView(sectionLabel("/root/.startup.local"))
+ preview = TextView(this).apply {
+ textSize = 12f
+ setPadding(pad / 2, pad / 2, pad / 2, pad / 2)
+ setBackgroundColor(cardColor())
+ setTextColor(cardTextColor())
+ setTypeface(android.graphics.Typeface.MONOSPACE)
+ }
+ body.addView(preview)
+
+ val rowButtons = listOf(
+ ScreenWidgets.primaryButton(this, R.string.startup_hook_write) { writeStarter() },
+ ScreenWidgets.actionButton(this, R.string.startup_hook_edit) { edit() },
+ ScreenWidgets.dangerButton(this, R.string.startup_hook_delete) { delete() },
+ ScreenWidgets.actionButton(this, R.string.startup_hook_refresh) { reload() }
+ )
+ val row = ScreenWidgets.buttonGrid(this, rowButtons)
+ row.layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT
+ ).apply { topMargin = pad }
+ body.addView(row)
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.startup_hook))
+ setContentView(root)
+
+ distros = runCatching { installer.getInstalledDistros() }.getOrDefault(emptyList())
+ spinner.adapter = ScreenWidgets.spinner(this, distros).adapter
+ spinner.onItemSelectedListener =
+ object : android.widget.AdapterView.OnItemSelectedListener {
+ override fun onItemSelected(
+ p: android.widget.AdapterView<*>?,
+ view: View?,
+ position: Int,
+ id: Long,
+ ) {
+ current = distros.getOrNull(position)
+ reload()
+ }
+
+ override fun onNothingSelected(p: android.widget.AdapterView<*>?) = Unit
+ }
+ }
+
+ private fun hookFile(): File? {
+ val d = current ?: return null
+ return File(installer.getRootfsDir(d), "root/.startup.local")
+ }
+
+ private fun reload() {
+ val f = hookFile()
+ when {
+ f == null -> {
+ statusLine.setText(R.string.workspace_none)
+ preview.setText(R.string.startup_hook_preview_empty)
+ }
+ !f.exists() -> {
+ statusLine.text = getString(R.string.startup_hook_status_absent)
+ preview.setText(R.string.startup_hook_preview_empty)
+ }
+ else -> {
+ val content = runCatching { f.readText() }.getOrNull() ?: ""
+ statusLine.text =
+ if (content.contains(MARKER)) getString(R.string.startup_hook_ours)
+ else getString(R.string.startup_hook_user)
+ preview.text = content
+ }
+ }
+ }
+
+ private fun writeStarter() {
+ val f = hookFile() ?: return
+ if (f.exists() && !f.readText().contains(MARKER)) {
+ AlertDialog.Builder(this)
+ .setTitle(R.string.startup_hook)
+ .setMessage(R.string.startup_hook_refused)
+ .setPositiveButton(android.R.string.ok, null)
+ .show()
+ return
+ }
+ try {
+ f.parentFile?.mkdirs()
+ f.writeText(ApiHelper.startupStarter())
+ AppLog.i(this, "startup-hook", "safe starter written to ${f.absolutePath}")
+ AlertDialog.Builder(this)
+ .setTitle(R.string.startup_hook)
+ .setMessage(R.string.startup_hook_written)
+ .setPositiveButton(android.R.string.ok, null)
+ .show()
+ reload()
+ } catch (e: Exception) {
+ AppLog.e(this, "startup-hook", "could not write the hook: ${e.javaClass.simpleName}: ${e.message}")
+ AlertDialog.Builder(this)
+ .setTitle(R.string.startup_hook)
+ .setMessage("Could not write the hook: ${e.message}")
+ .setPositiveButton(android.R.string.ok, null)
+ .show()
+ }
+ }
+
+ private fun edit() {
+ val f = hookFile() ?: return
+ if (!f.exists()) {
+ writeStarter()
+ return
+ }
+ startActivity(
+ Intent(this, TextEditorActivity::class.java)
+ .putExtra(TextEditorActivity.EXTRA_PATH, f.absolutePath)
+ )
+ }
+
+ private fun delete() {
+ val f = hookFile() ?: return
+ if (!f.exists()) return
+ AlertDialog.Builder(this)
+ .setTitle(R.string.startup_hook)
+ .setMessage("Delete /root/.startup.local for ${current}?")
+ .setPositiveButton(android.R.string.ok) { _, _ ->
+ if (f.delete()) {
+ AppLog.i(this, "startup-hook", "hook removed from ${f.absolutePath}")
+ statusLine.setText(R.string.startup_hook_deleted)
+ reload()
+ } else {
+ AppLog.e(this, "startup-hook", "delete of ${f.absolutePath} failed")
+ }
+ }
+ .setNegativeButton(android.R.string.cancel, null)
+ .show()
+ }
+
+ private fun sectionLabel(text: String) = TextView(this).apply {
+ this.text = text
+ textSize = 13f
+ setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0)
+ }
+
+ /** The marker that makes a hook file RedTerm's own to replace. */
+ private companion object {
+ const val MARKER = "RedTerm user startup hook"
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", android.content.Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/TerminalActivity.kt b/app/src/main/java/com/redtermapp/ui/TerminalActivity.kt
index abf9359..dee30d5 100644
--- a/app/src/main/java/com/redtermapp/ui/TerminalActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/TerminalActivity.kt
@@ -83,6 +83,12 @@ class TerminalActivity : AppCompatActivity() {
const val EXTRA_SSH_KEY_ID = "ssh_key_id"
const val EXTRA_SSH_USE_MOSH = "ssh_use_mosh"
+ /** Opens every session a saved workspace names, in one tap. */
+ const val EXTRA_WORKSPACE_ID = "workspace_id"
+
+ /** Text to type into the focused session once it is attached. */
+ const val EXTRA_TYPE_TEXT = "type_text"
+
/**
* Opens a new terminal session for a saved server.
*
@@ -446,14 +452,19 @@ class TerminalActivity : AppCompatActivity() {
if (pendingServer != null) {
createSession(SessionRequest.Ssh(pendingServer.server, pendingServer.keyId))
} else if (sessions.isEmpty()) {
- val intentDistro = intent?.getStringExtra(EXTRA_DISTRO)
- if (intentDistro != null) {
- createSession(SessionRequest.Local(intentDistro, pendingStartDir, pendingCommand))
- } else if (!restoreSessions()) {
- // Nothing was running and nothing was remembered, so there is
- // genuinely nothing to show. Alpine is the app's default target
- // and the error screen explains what to do about it.
- createSession(SessionRequest.Local(distroName))
+ val workspaceId = intent?.getStringExtra(EXTRA_WORKSPACE_ID)
+ if (workspaceId != null) {
+ openWorkspaceSessions(workspaceId)
+ } else {
+ val intentDistro = intent?.getStringExtra(EXTRA_DISTRO)
+ if (intentDistro != null) {
+ createSession(SessionRequest.Local(intentDistro, pendingStartDir, pendingCommand))
+ } else if (!restoreSessions()) {
+ // Nothing was running and nothing was remembered, so there is
+ // genuinely nothing to show. Alpine is the app's default target
+ // and the error screen explains what to do about it.
+ createSession(SessionRequest.Local(distroName))
+ }
}
} else {
// A resumed session must still get a refreshed .startup, because it used to
@@ -516,6 +527,13 @@ class TerminalActivity : AppCompatActivity() {
updateDrawer()
}
}
+ // A snippet library "send" hands the text here; type it into the focused
+ // session once it is attached and laid out, so it lands in the prompt.
+ intent?.getStringExtra(EXTRA_TYPE_TEXT)?.takeIf { it.isNotEmpty() }?.let { text ->
+ terminalView.post {
+ focusedSession()?.write(text.toByteArray(), 0, text.length)
+ }
+ }
startForegroundService()
}
@@ -563,7 +581,21 @@ class TerminalActivity : AppCompatActivity() {
prepared.args, prepared.env, prepared.scrollback, backend
)
session.mSessionName = prepared.descriptor.label
- sessionModel.addSession(session, prepared.descriptor)
+ sessionModel.addSession(session, prepared.descriptor)
+
+ // A workspace that asked for split opens here: when the second live
+ // session lands and the flag is set, enter the two-pane view. Posted
+ // so it runs after this whole attach (and both sessions) are done,
+ // once the split views are laid out.
+ if (pendingWorkspaceSplit && sessionModel.sessions.value.size >= 2) {
+ terminalView.post {
+ if (pendingWorkspaceSplit && !splitActive) {
+ pendingWorkspaceSplit = false
+ enterSplit()
+ }
+ }
+ }
+
if (descriptor.id == wantedId) focusIndex = sessions.size - 1
restored++
}
@@ -944,6 +976,11 @@ class TerminalActivity : AppCompatActivity() {
osRelease.contains("Rocky", ignoreCase = true) -> "rocky"
osRelease.contains("Arch", ignoreCase = true) -> "arch"
osRelease.contains("Void", ignoreCase = true) -> "void"
+ // Amazon Linux's ID ("amzn") is canonicalized now, but if that ever misses,
+ // its os-release carries ID_LIKE="centos rhel fedora" and the next line
+ // would send it to Fedora's plan, overwriting its working amzn2-* repos.
+ // Catch it first and leave its repositories untouched.
+ osRelease.contains("Amazon", ignoreCase = true) -> "amzn"
osRelease.contains("Fedora", ignoreCase = true) -> "fedora"
File(rootfsDir, "etc/fedora-release").exists() -> "fedora"
File(rootfsDir, "etc/debian_version").exists() -> "debian"
@@ -1432,6 +1469,38 @@ class TerminalActivity : AppCompatActivity() {
}
}
+ /**
+ * Open every session a saved workspace names, in one tap: one distro shell
+ * per distro key, one SSH session per saved server. A workspace is a
+ * bundle, not a gate — a distro that was since uninstalled or a server that
+ * was since deleted is skipped rather than failing the whole launch, and a
+ * workspace that names nothing falls back to the default distro.
+ */
+ private fun openWorkspaceSessions(workspaceId: String) {
+ val workspace = WorkspaceStore.get(this, workspaceId)
+ if (workspace == null) {
+ createSession(SessionRequest.Local(distroName))
+ return
+ }
+ val servers = SshStore.load(this).associateBy { it.id }
+ // A split launch is decided up front, on what the workspace *plans* to
+ // open: exactly two live sessions, and the user asked for split. It is
+ // consumed in attachSession once the second one is actually live.
+ val planned = workspace.cleanDistros.size + workspace.serverIds.count { it in servers }
+ pendingWorkspaceSplit = workspace.split && planned == 2
+ var opened = 0
+ for (distro in workspace.cleanDistros) {
+ createSession(SessionRequest.Local(distro))
+ opened++
+ }
+ for (serverId in workspace.serverIds) {
+ val server = servers[serverId] ?: continue
+ createSession(SessionRequest.Ssh(server, server.keyId))
+ opened++
+ }
+ if (opened == 0) createSession(SessionRequest.Local(distroName))
+ }
+
/**
* The size a mosh session is told about before the pty exists.
*
@@ -1885,9 +1954,10 @@ class TerminalActivity : AppCompatActivity() {
// Taking no action leaves a dead terminal that eats keys, which is exactly the
// expectation the user read.
var opensSsh = false
- AlertDialog.Builder(this)
+ val baseMessage = getString(R.string.mosh_no_reply, host)
+ val dialog = AlertDialog.Builder(this)
.setTitle(R.string.mosh_no_reply_title)
- .setMessage(getString(R.string.mosh_no_reply, host))
+ .setMessage(baseMessage)
// Opens a working session now, and stops asking for mosh on this server.
.setPositiveButton(R.string.mosh_stop_trying) { _, _ ->
opensSsh = true
@@ -1908,6 +1978,23 @@ class TerminalActivity : AppCompatActivity() {
}
}
.show()
+
+ // While the user reads, probe the UDP path in the background. The two
+ // causes above are a guess until the probe says which one is real; the
+ // remedy for a blocked path is not the one for an open one, so the
+ // verdict is appended to the message that is already on screen.
+ Thread({
+ val signal = com.redtermapp.util.UdpHoleProbe.probe(host, 2_500L)
+ val verdict = com.redtermapp.util.MoshUdpProbe.classify(signal)
+ runOnUiThread {
+ if (dialog.isShowing) {
+ dialog.setMessage(
+ baseMessage + "\n\n" +
+ com.redtermapp.util.MoshUdpProbe.suggestion(verdict, host)
+ )
+ }
+ }
+ }, "mosh-udp-probe").apply { isDaemon = true }.start()
}
/** The dead mosh session still on screen, and the answer Enter owes it. */
@@ -2076,6 +2163,14 @@ class TerminalActivity : AppCompatActivity() {
private var splitLeftBackend: TerminalBackend? = null
private val splitViewSession = mutableMapOf()
+ /**
+ * A workspace asked to open split: set before its sessions are created and
+ * consumed when the last one attaches. Checked in [attachSession] rather
+ * than watched from a coroutine, because that is the exact moment a
+ * session is live — the same moment a split needs two of them.
+ */
+ private var pendingWorkspaceSplit = false
+
private fun toggleSplit() {
if (splitActive) {
exitSplit()
@@ -2085,6 +2180,12 @@ class TerminalActivity : AppCompatActivity() {
Toast.makeText(this, "Open a second session to use split view", Toast.LENGTH_SHORT).show()
return
}
+ enterSplit()
+ }
+
+ /** Puts the two current sessions side by side. No-ops unless both exist. */
+ private fun enterSplit() {
+ if (splitActive || sessions.size < 2) return
splitActive = true
val container = findViewById(R.id.split_container)
val left = findViewById(R.id.terminal_view_left)
diff --git a/app/src/main/java/com/redtermapp/ui/TerminalGif.kt b/app/src/main/java/com/redtermapp/ui/TerminalGif.kt
new file mode 100644
index 0000000..45f69fe
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/TerminalGif.kt
@@ -0,0 +1,91 @@
+package com.redtermapp.ui
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Typeface
+import com.redtermapp.util.GifFramePlan
+import com.redtermapp.util.GifWriter
+import com.termux.terminal.TerminalEmulator
+import com.termux.view.TerminalRenderer
+import java.io.File
+
+/**
+ * Exports a recorded ANSI session to a looping GIF a phone can show anywhere.
+ *
+ * The recording is fed through a private [TerminalEmulator] exactly as the
+ * player does — no session, no process, no stty — and every [GifFramePlan.
+ * decimation]-th paced chunk is drawn with the library's [TerminalRenderer]
+ * onto a bitmap, quantised into the recording's own colours and written as
+ * one LZW-compressed frame. The GIF's delay is the real time the skipped
+ * chunks took, so it plays at the session's own pace.
+ *
+ * Runs on a worker thread: it reads the file, allocates a bitmap and does the
+ * LZW. Nothing here touches a view.
+ */
+object TerminalGif {
+
+ /** A terminal is a small grid; 80x24 is the size any viewer is used to. */
+ private const val COLS = 80
+ private const val ROWS = 24
+ private const val FONT_SIZE = 20
+ private const val MAX_FRAMES = 240
+
+ class Export(val ok: Boolean, val frames: Int, val file: File?, val detail: String?)
+
+ fun export(recording: File, outGif: File, fg: Int, bg: Int, typeface: Typeface): Export {
+ if (!recording.isFile) {
+ return Export(false, 0, null, "the recording is gone")
+ }
+ val renderer = TerminalRenderer(FONT_SIZE, typeface)
+ val fontWidth = renderer.getFontWidth().toInt().coerceAtLeast(1)
+ val lineHeight = renderer.getFontLineSpacing().toInt().coerceAtLeast(1)
+
+ val emulator = TerminalEmulator(
+ TerminalTheming.headlessOutput,
+ COLS, ROWS, fontWidth, lineHeight, null,
+ TerminalTheming.headlessClient
+ )
+ val totalChunks = ((recording.length() + GifFramePlan.CHUNK_SIZE - 1L)
+ / GifFramePlan.CHUNK_SIZE).toInt().coerceAtLeast(1)
+ val skip = GifFramePlan.decimation(totalChunks, MAX_FRAMES)
+ val delay = GifFramePlan.delayCentiseconds(skip)
+
+ val width = COLS * fontWidth
+ val height = ROWS * lineHeight
+ val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(bitmap)
+ val pixels = IntArray(width * height)
+ val palette = GifWriter.palette(bg, fg, GifWriter.ANSI16)
+ val indices = IntArray(pixels.size)
+
+ var frames = 0
+ outGif.outputStream().use { out ->
+ val gif = GifWriter(out)
+ gif.start(width, height, palette)
+ recording.inputStream().use { input ->
+ val buffer = ByteArray(GifFramePlan.CHUNK_SIZE)
+ var chunk = 0
+ while (true) {
+ val read = input.read(buffer)
+ if (read <= 0) break
+ emulator.append(buffer, read)
+ chunk++
+ if (chunk % skip == 0) {
+ canvas.drawColor(bg)
+ renderer.render(emulator, canvas, 0, -1, -1, 0, 0)
+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
+ for (i in pixels.indices) {
+ indices[i] = GifWriter.nearestIndex(pixels[i], palette)
+ }
+ gif.frame(indices, delay)
+ frames++
+ }
+ }
+ }
+ gif.finish()
+ }
+ if (frames == 0) outGif.delete()
+ return Export(frames > 0, frames, if (frames > 0) outGif else null,
+ if (frames > 0) null else "nothing was drawn from the recording")
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/TerminalTheming.kt b/app/src/main/java/com/redtermapp/ui/TerminalTheming.kt
index e7a42fc..56d2a02 100644
--- a/app/src/main/java/com/redtermapp/ui/TerminalTheming.kt
+++ b/app/src/main/java/com/redtermapp/ui/TerminalTheming.kt
@@ -22,6 +22,44 @@ object TerminalTheming {
private val fontCache = HashMap()
+ /**
+ * The two passengers every headless [com.termux.terminal.TerminalEmulator]
+ * needs: an output that echoes nothing, and a session client that receives
+ * nothing. Shared by the player and the GIF exporter, so a new terminal
+ * surface starts from the shared pair instead of a copy that drifts.
+ */
+ val headlessOutput = object : com.termux.terminal.TerminalOutput() {
+ override fun write(data: ByteArray, offset: Int, count: Int) {}
+ override fun titleChanged(title: String?, subtitle: String?) {}
+ override fun onCopyTextToClipboard(text: String?) {}
+ override fun onPasteTextFromClipboard() {}
+ override fun onBell() {}
+ override fun onColorsChanged() {}
+ }
+
+ val headlessClient = object : com.termux.terminal.TerminalSessionClient {
+ override fun onTextChanged(session: com.termux.terminal.TerminalSession) = Unit
+ override fun onTitleChanged(session: com.termux.terminal.TerminalSession) = Unit
+ override fun onSessionFinished(session: com.termux.terminal.TerminalSession) = Unit
+ override fun onCopyTextToClipboard(
+ session: com.termux.terminal.TerminalSession,
+ text: String?
+ ) = Unit
+
+ override fun onPasteTextFromClipboard(session: com.termux.terminal.TerminalSession) = Unit
+ override fun onBell(session: com.termux.terminal.TerminalSession) = Unit
+ override fun onColorsChanged(session: com.termux.terminal.TerminalSession) = Unit
+ override fun onTerminalCursorStateChange(terminalCursorVisible: Boolean) = Unit
+ override fun getTerminalCursorStyle(): Int? = null
+ override fun logError(tag: String?, message: String?) = Unit
+ override fun logWarn(tag: String?, message: String?) = Unit
+ override fun logInfo(tag: String?, message: String?) = Unit
+ override fun logDebug(tag: String?, message: String?) = Unit
+ override fun logVerbose(tag: String?, message: String?) = Unit
+ override fun logStackTraceWithMessage(tag: String?, message: String?, e: Exception?) = Unit
+ override fun logStackTrace(tag: String?, e: Exception?) = Unit
+ }
+
/** The theme's terminal foreground and background, for the paths that are not a theme switch. */
fun themedColours(activity: android.app.Activity): Pair {
fun color(attr: Int, default: Int): Int {
diff --git a/app/src/main/java/com/redtermapp/ui/TransferPlan.kt b/app/src/main/java/com/redtermapp/ui/TransferPlan.kt
new file mode 100644
index 0000000..8abdd12
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/TransferPlan.kt
@@ -0,0 +1,34 @@
+package com.redtermapp.ui
+
+/**
+ * The queueing and resuming rules for the SFTP transfer queue, kept pure so
+ * they are unit-tested. Only a task whose size is actually smaller than what
+ * already exists can resume; a destination that is already complete is skipped
+ * rather than re-downloaded, and any task whose total is unknown is always run
+ * fresh, because without a size there is nothing to compare an existing file
+ * against.
+ */
+object TransferPlan {
+
+ enum class Kind { UPLOAD, DOWNLOAD }
+
+ enum class Plan { FRESH, RESUME, DONE }
+
+ /**
+ * What to do with a transfer whose destination already holds [existing]
+ * bytes out of [total] bytes total.
+ */
+ fun plan(existing: Long, total: Long): Plan = when {
+ total <= 0L -> Plan.FRESH // unknown size: nothing to compare against
+ existing <= 0L -> Plan.FRESH
+ existing >= total -> Plan.DONE
+ else -> Plan.RESUME
+ }
+
+ /** The byte offset a RESUME transfer should start reading/writing at. */
+ fun startOffset(existing: Long, total: Long): Long =
+ when (plan(existing, total)) {
+ Plan.RESUME -> existing
+ else -> 0L
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/TransferQueue.kt b/app/src/main/java/com/redtermapp/ui/TransferQueue.kt
new file mode 100644
index 0000000..b2773f0
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/TransferQueue.kt
@@ -0,0 +1,90 @@
+package com.redtermapp.ui
+
+import java.util.concurrent.locks.ReentrantLock
+
+/**
+ * The bookkeeping behind the transfer queue. Pure apart from a lock, so the
+ * ordering, the concurrency cap and the resume/done bookkeeping are all
+ * unit-tested; the activity runs the pool, this only decides.
+ *
+ * A task moves PENDING -> RUNNING -> DONE|FAILED|SKIPPED. [nextPending] is
+ * the only way work is handed out and it never exceeds [concurrency], so the
+ * caller can hand each returned batch to its own pool and be sure of the cap.
+ */
+class TransferQueue(
+ val tasks: List,
+ val concurrency: Int
+) {
+ enum class State { PENDING, RUNNING, DONE, FAILED, SKIPPED }
+
+ data class Task(
+ val id: String,
+ val kind: TransferPlan.Kind,
+ val label: String,
+ val total: Long
+ )
+
+ private val lock = ReentrantLock()
+ private val states = HashMap()
+ private var cursor = 0
+
+ init {
+ lock.lock()
+ try { tasks.forEach { states[it.id] = State.PENDING } } finally { lock.unlock() }
+ }
+
+ /**
+ * Up to [n] not-yet-started tasks, in stored order, marked RUNNING. Never
+ * returns more than the queue's [concurrency] allows: the number of RUNNING
+ * tasks it would leave is capped, so the caller's pool can be this size and
+ * still not exceed it.
+ */
+ fun nextPending(n: Int): List = lock.withLock {
+ val slots = (concurrency - states.values.count { it == State.RUNNING }).coerceAtLeast(0)
+ val out = mutableListOf()
+ while (cursor < tasks.size && out.size < n && out.size < slots) {
+ val t = tasks[cursor++]
+ if (states[t.id] == State.PENDING) {
+ states[t.id] = State.RUNNING
+ out.add(t)
+ }
+ }
+ out
+ }
+
+ fun markDone(id: String) = set(id, State.DONE)
+ fun markFailed(id: String) = set(id, State.FAILED)
+ fun markSkipped(id: String) = set(id, State.SKIPPED)
+
+ private fun set(id: String, s: State) {
+ lock.lock()
+ try {
+ val cur = states[id]
+ if (cur == State.RUNNING || cur == State.PENDING) states[id] = s
+ } finally {
+ lock.unlock()
+ }
+ }
+
+ fun state(id: String): State = lock.withLock { states[id] ?: State.PENDING }
+
+ /** True when no task is PENDING or RUNNING, i.e. the pool can drain. */
+ fun allFinished(): Boolean = lock.withLock {
+ states.values.none { it == State.PENDING || it == State.RUNNING }
+ }
+
+ val isComplete: Boolean get() = allFinished()
+
+ fun doneCount(): Int = lock.withLock { states.values.count { it == State.DONE } }
+ fun failedCount(): Int = lock.withLock { states.values.count { it == State.FAILED } }
+ fun skippedCount(): Int = lock.withLock { states.values.count { it == State.SKIPPED } }
+}
+
+private inline fun ReentrantLock.withLock(action: () -> T): T {
+ lock()
+ try {
+ return action()
+ } finally {
+ unlock()
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/TransferQueueActivity.kt b/app/src/main/java/com/redtermapp/ui/TransferQueueActivity.kt
new file mode 100644
index 0000000..a309866
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/TransferQueueActivity.kt
@@ -0,0 +1,284 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import android.net.Uri
+import android.os.Bundle
+import android.view.View
+import android.widget.CheckBox
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.Spinner
+import android.widget.TextView
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.appcompat.app.AppCompatActivity
+import com.google.android.material.button.MaterialButton
+import com.redtermapp.R
+import com.redtermapp.ui.filelist.FileEntry
+import com.redtermapp.ui.filelist.OpResult
+import com.redtermapp.ui.filelist.SftpSource
+import java.io.File
+import java.util.Locale
+import kotlin.concurrent.thread
+
+/**
+ * A parallel, resumable transfer queue over one SFTP server. Files are
+ * handed out in capped batches by [TransferQueue]; each transfer is
+ * [TransferPlan]-checked against the destination so a restarted batch
+ * resumes where it left off instead of redoing work, and a finished file
+ * is skipped.
+ */
+class TransferQueueActivity : AppCompatActivity() {
+
+ private val servers by lazy { SshStore.load(applicationContext) }
+ private var source: SftpSource? = null
+ private lateinit var serverSpinner: Spinner
+ private lateinit var concurrency: Spinner
+ private lateinit var remoteDir: EditText
+ private val selected = LinkedHashMap()
+ private val localPicks = LinkedHashMap()
+ private lateinit var fileContainer: LinearLayout
+ private lateinit var status: TextView
+ private var running = false
+
+ private val pickLocal = registerForActivityResult(
+ ActivityResultContracts.OpenMultipleDocuments()
+ ) { uris ->
+ uris.filterNotNull().forEach { uri -> localPicks[uri.toString()] = pickFile(uri) }
+ renderLocal()
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.transfer_queue)
+ textSize = 20f
+ })
+
+ serverSpinner = ScreenWidgets.spinner(this, servers.map { it.label })
+ serverSpinner.onItemSelectedListener =
+ object : android.widget.AdapterView.OnItemSelectedListener {
+ override fun onItemSelected(
+ p: android.widget.AdapterView<*>?, v: View?, position: Int, id: Long
+ ) {
+ source = SftpSource(this@TransferQueueActivity, servers[position], servers[position].keyId)
+ }
+
+ override fun onNothingSelected(p: android.widget.AdapterView<*>?) = Unit
+ }
+ body.addView(serverSpinner)
+
+ body.addView(ScreenWidgets.actionButton(this, R.string.transfer_list_remote) { refreshRemote() })
+
+ remoteDir = EditText(this).apply {
+ hint = getString(R.string.transfer_remote_dir)
+ textSize = 13f
+ // Density-scaled room below the text so it sits above the field's
+ // underline instead of crowding it.
+ val d = resources.displayMetrics.density
+ setPadding(0, (8 * d).toInt(), 0, (18 * d).toInt())
+ setTextColor(context.cardTextColor())
+ setHintTextColor(context.mutedTextColor())
+ }
+ body.addView(remoteDir)
+
+ concurrency = ScreenWidgets.spinner(this, listOf("1", "2", "3", "4"))
+ body.addView(concurrency)
+
+ body.addView(ScreenWidgets.actionButton(this, R.string.transfer_pick_local) {
+ pickLocal.launch(arrayOf("*/*"))
+ })
+ fileContainer = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ body.addView(fileContainer)
+
+ body.addView(MaterialButton(this).apply {
+ setText(R.string.transfer_run)
+ setOnClickListener { runQueue() }
+ })
+ status = TextView(this).apply {
+ textSize = 12f
+ setPadding(0, 6, 0, 0)
+ }
+ body.addView(status)
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.transfer_queue))
+ setContentView(root)
+ renderLocal()
+ }
+
+ private fun renderLocal() {
+ for (f in localPicks.values) {
+ fileContainer.addView(TextView(this).apply {
+ text = getString(R.string.transfer_file_upload, f.name)
+ textSize = 12f
+ })
+ }
+ }
+
+ private fun refreshRemote() {
+ val s = source ?: return
+ // A listing is a network round trip, and `home` can cost a whole
+ // connection. Running it in the click is what ANR'd, so the round trip
+ // happens on a worker and only the checkbox rebuild happens on main.
+ val requested = remoteDir.text?.toString()?.takeIf { it.isNotBlank() }
+ status.setText(R.string.transfer_listing)
+ thread(name = "redterm-transfer-list") {
+ val dir = requested ?: s.home
+ val entries = s.list(dir)
+ val err = s.lastError
+ runOnUiThread {
+ if (isFinishing || isDestroyed) return@runOnUiThread
+ remoteDir.setText(dir)
+ fileContainer.removeAllViews()
+ selected.clear()
+ for (e in (entries ?: emptyList()).filter { !it.isDirectory }) {
+ val cb = CheckBox(this).apply {
+ text = getString(R.string.transfer_file_download, e.name, human(e.size))
+ textSize = 12f
+ setTextColor(cardTextColor())
+ setOnCheckedChangeListener { _, checked ->
+ if (checked) selected[e.path] = e else selected.remove(e.path)
+ }
+ }
+ fileContainer.addView(cb)
+ }
+ if (entries == null) {
+ status.text = err
+ } else if (selected.isEmpty()) {
+ status.setText(R.string.transfer_pick_files)
+ }
+ }
+ }
+ }
+
+ private fun runQueue() {
+ if (running) return
+ val s = source ?: return
+ // Read the UI state on the main thread, then drop off it. A worker must
+ // not touch views or the live maps, and `s.home` can cost a connection.
+ val downloads = selected.toMap()
+ val remoteJobs = selected.mapValues { (_, e) -> destFor(e) }
+ val uploads = localPicks.values.associateBy { it.name }
+ val n = (concurrency.selectedItem as String).toInt().coerceIn(1, 4)
+ val remoteDirText = remoteDir.text?.toString()?.takeIf { it.isNotBlank() }
+
+ val tasks = selected.values.map { e ->
+ TransferQueue.Task(e.path, TransferPlan.Kind.DOWNLOAD, e.name, e.size)
+ } + localPicks.values.map { f ->
+ TransferQueue.Task(f.name, TransferPlan.Kind.UPLOAD, f.name, f.length())
+ }
+ if (tasks.isEmpty()) {
+ status.setText(R.string.transfer_nothing)
+ return
+ }
+
+ val queue = TransferQueue(tasks, n)
+ running = true
+ status.setText(R.string.transfer_running)
+
+ // The transfers and the join both run on a worker. Joining the pool on
+ // the main thread is what ANR'd the screen: it sat blocked for the
+ // whole transfer while the watchdog timed it out.
+ thread(name = "redterm-transfer-run") {
+ val pool = (1..n).map { i ->
+ thread(start = true, name = "redterm-transfer-$i") {
+ while (true) {
+ val batch = queue.nextPending(1)
+ if (batch.isEmpty()) break
+ val task = batch.single()
+ when (task.kind) {
+ TransferPlan.Kind.DOWNLOAD -> {
+ val remote = downloads[task.id]
+ val dest = remoteJobs[task.id]
+ if (remote == null || dest == null) {
+ queue.markSkipped(task.id)
+ } else {
+ val existing = if (dest.isFile) dest.length() else 0L
+ val plan = TransferPlan.plan(existing, remote.size)
+ if (plan == TransferPlan.Plan.DONE) {
+ queue.markSkipped(task.id)
+ } else {
+ val off = TransferPlan.startOffset(existing, remote.size)
+ val res = s.downloadTo(remote, dest, startOffset = off) { _, _ -> }
+ finish(queue, task, res)
+ }
+ }
+ }
+ TransferPlan.Kind.UPLOAD -> {
+ val src = uploads[task.id]
+ if (src == null) {
+ queue.markSkipped(task.id)
+ } else {
+ val dir = remoteDirText ?: s.home
+ val res = s.uploadFrom(src, "$dir/${src.name}") { _, _ -> }
+ finish(queue, task, res)
+ }
+ }
+ }
+ }
+ }
+ }
+ pool.forEach { it.join() }
+ val done = queue.doneCount()
+ val failed = queue.failedCount()
+ val skipped = queue.skippedCount()
+ running = false
+ runOnUiThread {
+ if (isFinishing || isDestroyed) return@runOnUiThread
+ status.text = getString(R.string.transfer_done, done, failed, skipped)
+ }
+ }
+ }
+
+ private fun finish(queue: TransferQueue, task: TransferQueue.Task, res: OpResult) {
+ if (res is OpResult.Ok) queue.markDone(task.id) else queue.markFailed(task.id)
+ }
+
+ private fun destFor(e: FileEntry): File {
+ val dir = getExternalFilesDir("transfers") ?: filesDir
+ dir.mkdirs()
+ return File(dir, e.name)
+ }
+
+ private fun pickFile(uri: Uri): File {
+ val dir = getExternalFilesDir("transfers") ?: filesDir
+ dir.mkdirs()
+ val out = File(dir, "in-${uri.lastPathSegment ?: "file"}")
+ contentResolver.openInputStream(uri)?.copyTo(out.outputStream())
+ return out
+ }
+
+ private fun human(b: Long): String = when {
+ b >= 1L shl 30 -> String.format(Locale.getDefault(), "%.1f GB", b / 1073741824.0)
+ b >= 1L shl 20 -> String.format(Locale.getDefault(), "%.1f MB", b / 1048576.0)
+ else -> "$b B"
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/TunnelManager.kt b/app/src/main/java/com/redtermapp/ui/TunnelManager.kt
index d87fd20..fde1767 100644
--- a/app/src/main/java/com/redtermapp/ui/TunnelManager.kt
+++ b/app/src/main/java/com/redtermapp/ui/TunnelManager.kt
@@ -2,9 +2,11 @@ package com.redtermapp.ui
import android.content.Context
import android.util.Log
+import androidx.core.content.edit
import com.redtermapp.util.AppLog
import com.redtermapp.util.SshClient
import com.redtermapp.util.sftp.SshAskpass
+import org.json.JSONArray
import java.io.File
import java.util.concurrent.ConcurrentHashMap
@@ -112,10 +114,28 @@ object TunnelManager {
process = process,
script = script
)
+ rememberTunnel(context, server.id)
AppLog.i(context, "ssh", "tunnel to ${server.label} up: ${forwards.joinToString(", ") { it.spec }}")
return true
}
+ /**
+ * Re-opens the tunnels the last process had standing, after [OrphanSweeper]
+ * has reaped the orphans. A server that no longer exists is dropped from
+ * the record rather than started against a hole.
+ */
+ fun resumeAll(context: Context): Int {
+ val servers = SshStore.load(context).associateBy { it.id }
+ var resumed = 0
+ for (serverId in decodeTunnels(context)) {
+ val server = servers[serverId] ?: continue
+ if (start(context, server, SshKeyStore.identitiesFor(context, server))) {
+ resumed++
+ }
+ }
+ return resumed
+ }
+
/**
* Stops a tunnel.
*
@@ -126,11 +146,59 @@ object TunnelManager {
val entry = running.remove(serverId) ?: return
runCatching { entry.process.destroy() }
runCatching { entry.script.delete() }
+ forgetTunnel(context, serverId)
AppLog.i(context, "ssh", "tunnel to ${entry.label} stopped")
}
fun stopAll(context: Context) {
for (id in running.keys.toList()) stop(context, id)
+ clearTunnels(context)
+ }
+
+ // The tunnel record is on disk, not in the map: a dead process orphans its
+ // `ssh -N` and the map is gone with it, so "which tunnels were open" has to
+ // outlive the process to be re-opened on the next start.
+ private const val TUNNEL_PREFS = "ssh_tunnels"
+ private const val TUNNEL_KEY = "active"
+
+ private fun tunnels(context: Context) = decodeTunnels(context)
+
+ private fun rememberTunnel(context: Context, serverId: String) {
+ val ids = tunnels(context).filterNot { it == serverId } + serverId
+ context.getSharedPreferences(TUNNEL_PREFS, Context.MODE_PRIVATE).edit {
+ putString(TUNNEL_KEY, encodeTunnels(ids))
+ }
+ }
+
+ private fun forgetTunnel(context: Context, serverId: String) {
+ context.getSharedPreferences(TUNNEL_PREFS, Context.MODE_PRIVATE).edit {
+ putString(TUNNEL_KEY, encodeTunnels(tunnels(context).filterNot { it == serverId }))
+ }
+ }
+
+ private fun clearTunnels(context: Context) {
+ context.getSharedPreferences(TUNNEL_PREFS, Context.MODE_PRIVATE).edit {
+ remove(TUNNEL_KEY)
+ }
+ }
+
+ fun encodeTunnels(ids: List): String =
+ JSONArray().apply { ids.forEach { put(it) } }.toString()
+
+ /** Tolerant: a record that fails to parse is no tunnels, not a cold-start crash. */
+ fun decodeTunnels(context: Context): List =
+ decodeTunnelIds(
+ context.getSharedPreferences(TUNNEL_PREFS, Context.MODE_PRIVATE)
+ .getString(TUNNEL_KEY, null)
+ )
+
+ /** Pure, so the reader is unit-tested: a corrupt record is no tunnels. */
+ fun decodeTunnelIds(json: String?): List {
+ if (json.isNullOrBlank()) return emptyList()
+ return runCatching {
+ val arr = JSONArray(json)
+ (0 until arr.length()).map { arr.optString(it, "") }.filter { it.isNotBlank() }
+ }.getOrDefault(emptyList())
}
/**
diff --git a/app/src/main/java/com/redtermapp/ui/TunnelManagerActivity.kt b/app/src/main/java/com/redtermapp/ui/TunnelManagerActivity.kt
new file mode 100644
index 0000000..84a0088
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/TunnelManagerActivity.kt
@@ -0,0 +1,150 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import com.redtermapp.R
+import com.redtermapp.util.AppLog
+
+/**
+ * One place to open and close the standalone `ssh -N` tunnels. A forward
+ * rides along with a session, but a tunnel is for when no terminal is open —
+ * a database client on a forwarded port — so it is managed here.
+ */
+class TunnelManagerActivity : AppCompatActivity() {
+
+ private lateinit var container: LinearLayout
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.tunnel_manager)
+ textSize = 20f
+ })
+ container = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ body.addView(container)
+
+ val scroll = ScrollView(this).apply { addView(body) }
+ val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.tunnel_manager))
+ setContentView(root)
+ load()
+ }
+
+ private fun load() {
+ Thread({
+ val servers = TunnelPlan.serversWithTunnels(SshStore.load(applicationContext))
+ runOnUiThread {
+ if (isFinishing || isDestroyed) return@runOnUiThread
+ container.removeAllViews()
+ if (servers.isEmpty()) {
+ container.addView(TextView(this).apply {
+ setText(R.string.tunnel_none)
+ setTextColor(mutedTextColor())
+ })
+ return@runOnUiThread
+ }
+ for (s in servers) container.addView(card(s))
+ }
+ }, "redterm-tunnels").start()
+ }
+
+ private fun card(server: SshStore.Server): View {
+ val pad = (10 * resources.displayMetrics.density).toInt()
+ val card = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ setBackgroundColor(cardColor())
+ layoutParams = LinearLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
+ ).apply {
+ val b = (8 * resources.displayMetrics.density).toInt()
+ setMargins(0, 0, 0, b)
+ }
+ }
+
+ val alive = TunnelManager.isAlive(this, server.id)
+ val head = ScreenWidgets.headerRow(this).apply {
+ addView(TextView(this@TunnelManagerActivity).apply {
+ text = server.label
+ textSize = 16f
+ setTextColor(cardTextColor())
+ })
+ addView(TextView(this@TunnelManagerActivity).apply {
+ text = if (alive) getString(R.string.tunnel_running) else getString(R.string.tunnel_stopped)
+ textSize = 12f
+ setTextColor(if (alive) accentColor() else mutedTextColor())
+ })
+ }
+ card.addView(head)
+
+ val hostLine = TextView(this).apply {
+ text = getString(R.string.tunnel_endpoint, server.user, server.host, server.port)
+ textSize = 12f
+ setTextColor(mutedTextColor())
+ }
+ card.addView(hostLine)
+ for (spec in TunnelPlan.activeSpecs(server)) {
+ card.addView(TextView(this).apply {
+ text = spec
+ textSize = 12f
+ typeface = android.graphics.Typeface.MONOSPACE
+ setTextColor(cardTextColor())
+ })
+ }
+
+ val button = ScreenWidgets.actionButton(this, if (alive) R.string.tunnel_stop else R.string.tunnel_start) {
+ toggle(server)
+ }
+ card.addView(button)
+ return card
+ }
+
+ private fun toggle(server: SshStore.Server) {
+ if (TunnelManager.isAlive(this, server.id)) {
+ TunnelManager.stop(this, server.id)
+ load()
+ return
+ }
+ val identities = SshKeyStore.identitiesFor(applicationContext, server)
+ Thread({
+ val ok = TunnelManager.start(applicationContext, server, identities)
+ runOnUiThread {
+ if (isFinishing || isDestroyed) return@runOnUiThread
+ if (!ok) AppLog.w(applicationContext, "ssh", "tunnel start failed for ${server.label}")
+ load()
+ }
+ }, "redterm-tunnel-toggle").start()
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/TunnelPlan.kt b/app/src/main/java/com/redtermapp/ui/TunnelPlan.kt
new file mode 100644
index 0000000..2379578
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/TunnelPlan.kt
@@ -0,0 +1,24 @@
+package com.redtermapp.ui
+
+/**
+ * Which servers a tunnel manager should show, and what it will actually open.
+ *
+ * Pure so it is unit-tested: a server is eligible only when it has at least
+ * one forward that is both enabled and usable (non-blank, no whitespace, the
+ * way ssh's `-L` reads it). Showing a server that only carries blank or
+ * disabled forwards would hand the user a toggle that does nothing.
+ */
+object TunnelPlan {
+
+ /** Servers that would open at least one local forward on connect. */
+ fun serversWithTunnels(servers: List): List =
+ servers.filter { activeSpecs(it).isNotEmpty() }
+
+ /** The forward specs that would be passed to `ssh -L`, in the order stored. */
+ fun activeSpecs(server: SshStore.Server): List =
+ server.forwards.filter { it.enabled && it.usable }.map { it.spec }
+
+ /** Every forward on a server, enabled or not, for a full read-out. */
+ fun allSpecs(server: SshStore.Server): List =
+ server.forwards.filter { it.usable }.map { it.spec }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/WelcomeActivity.kt b/app/src/main/java/com/redtermapp/ui/WelcomeActivity.kt
index 996ba91..869bf2b 100644
--- a/app/src/main/java/com/redtermapp/ui/WelcomeActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/WelcomeActivity.kt
@@ -258,6 +258,47 @@ class WelcomeActivity : AppCompatActivity() {
return card
}
+ /**
+ * A card that is not a catalogue distro: it opens the source installer (a file, a URL,
+ * or a Docker/OCI image) instead of selecting a distro to download. It is always
+ * offered, even when this architecture has no catalogue entries, because a tarball
+ * or image the user holds works on any of them.
+ */
+ private fun createCustomCard(): MaterialCardView {
+ return MaterialCardView(this).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT
+ ).apply { setMargins(0, 0, 0, 12) }
+ setCardBackgroundColor(tc(R.attr.extraKeysBg, 0xFF181825.toInt()))
+ radius = 12f
+ strokeWidth = 0
+ setOnClickListener {
+ if (!isInstalling) {
+ startActivity(Intent(this@WelcomeActivity, LocalDistroInstallActivity::class.java))
+ }
+ }
+ addView(LinearLayout(this@WelcomeActivity).apply {
+ orientation = LinearLayout.HORIZONTAL
+ setPadding(16, 16, 16, 16)
+ addView(LinearLayout(this@WelcomeActivity).apply {
+ orientation = LinearLayout.VERTICAL
+ addView(TextView(this@WelcomeActivity).apply {
+ text = getString(R.string.distro_dashboard_custom)
+ setTextColor(0xFFCDD6F4.toInt())
+ textSize = 16f
+ })
+ addView(TextView(this@WelcomeActivity).apply {
+ text = getString(R.string.more_tools_local_install_desc)
+ setTextColor(0xFF6C7086.toInt())
+ textSize = 14f
+ setPadding(0, 4, 0, 0)
+ })
+ })
+ })
+ }
+ }
+
private fun showDeleteDialog(distro: Distro) {
AlertDialog.Builder(this)
.setTitle(distro.displayName)
@@ -455,7 +496,13 @@ class WelcomeActivity : AppCompatActivity() {
?: android.os.Build.SUPPORTED_32_BIT_ABIS.firstOrNull()
?: "arm64-v8a"
val available = DistroRegistry.forDevice(abi)
- if (available.isEmpty()) {
+ // Rebuilt in place on rotation (the activity is not recreated, to keep an
+ // in-progress install alive), so the previous rows must be cleared first or
+ // every card would be added a second time.
+ distroList.removeAllViews()
+ distroCardMap.clear()
+ distroStatusText.clear()
+ if (available.isEmpty()) {
distroList.addView(TextView(this).apply {
text = getString(R.string.no_distributions_for_arch, abi)
setTextColor(0xFFFF6B6B.toInt())
@@ -494,6 +541,9 @@ class WelcomeActivity : AppCompatActivity() {
}
}
}
+ // A custom install is available on every architecture, so the card is appended
+ // regardless of whether the catalogue has an entry for this one.
+ distroList.addView(createCustomCard())
refreshDistroStates()
}
diff --git a/app/src/main/java/com/redtermapp/ui/WorkspaceActivity.kt b/app/src/main/java/com/redtermapp/ui/WorkspaceActivity.kt
new file mode 100644
index 0000000..37a51c9
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/WorkspaceActivity.kt
@@ -0,0 +1,318 @@
+package com.redtermapp.ui
+
+import android.content.Intent
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import android.widget.CheckBox
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.Spinner
+import android.widget.ScrollView
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import com.redtermapp.R
+import com.redtermapp.distro.DistroInstaller
+
+/**
+ * Workspaces: a named bundle of the distro shells, SSH servers, theme and
+ * startup-hook a user reaches for together, opened in one tap.
+ *
+ * The screen is built in code like the other tool screens. A workspace's
+ * sessions open through [TerminalActivity] with a single intent extra, which
+ * is the only path that can start a proot session from nothing.
+ */
+class WorkspaceActivity : AppCompatActivity() {
+
+ private lateinit var root: LinearLayout
+ private lateinit var scroll: ScrollView
+ private lateinit var list: LinearLayout
+ private lateinit var editor: LinearLayout
+ private lateinit var nameField: EditText
+ private lateinit var distroGroup: LinearLayout
+ private lateinit var serverGroup: LinearLayout
+ private lateinit var themeSpinner: Spinner
+ private lateinit var hookCheck: CheckBox
+ private lateinit var splitCheck: CheckBox
+ private lateinit var pinCheck: CheckBox
+
+ private val installer by lazy { DistroInstaller(applicationContext) }
+
+ private var workspaces: List = emptyList()
+ private var editing: WorkspaceStore.Workspace? = null
+ private var editingId: String? = null
+ private val distroChecks = mutableListOf()
+ private val serverChecks = mutableListOf()
+
+ /** The theme keys [DiskUsageActivity] cycles; "" is the app default. */
+ private val themes by lazy {
+ listOf(
+ "" to getString(R.string.workspace_theme_default),
+ "red" to "Red",
+ "amoled" to "AMOLED",
+ "green" to "Green",
+ "light" to "Light",
+ "dracula" to "Dracula",
+ "nord" to "Nord",
+ "tokyo" to "Tokyo Night",
+ "gruvbox" to "Gruvbox"
+ )
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ applyTheme()
+ super.onCreate(savedInstanceState)
+
+ val pad = (16 * resources.displayMetrics.density).toInt()
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ }
+ body.addView(TextView(this).apply {
+ setText(R.string.workspaces)
+ textSize = 20f
+ })
+ body.addView(ScreenWidgets.primaryButton(this, R.string.workspace_new) {
+ beginEdit(null)
+ })
+ list = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ body.addView(list)
+ editor = buildEditor()
+ editor.visibility = View.GONE
+ body.addView(editor)
+
+ scroll = ScrollView(this).apply { addView(body) }
+ root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ root.addView(
+ scroll,
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ )
+ ScreenToolbar.install(this, root, getString(R.string.workspaces))
+ setContentView(root)
+ refresh()
+ }
+
+ private fun buildEditor(): LinearLayout {
+ val pad = (8 * resources.displayMetrics.density).toInt()
+ val e = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ setBackgroundColor(cardColor())
+ }
+ nameField = EditText(this).apply {
+ hint = getString(R.string.workspace_name_hint)
+ setSingleLine(true)
+ setTextColor(context.cardTextColor())
+ setHintTextColor(context.mutedTextColor())
+ }
+ e.addView(nameField)
+ e.addView(sectionLabel(getString(R.string.workspace_distros)))
+ distroGroup = group()
+ e.addView(distroGroup)
+ e.addView(sectionLabel(getString(R.string.workspace_servers)))
+ serverGroup = group()
+ e.addView(serverGroup)
+ e.addView(sectionLabel(getString(R.string.workspace_theme)))
+ themeSpinner = Spinner(this)
+ e.addView(themeSpinner)
+ hookCheck = CheckBox(this).apply { setText(R.string.workspace_hook) }
+ e.addView(hookCheck)
+ splitCheck = CheckBox(this).apply {
+ setText(R.string.workspace_split)
+ setTextColor(cardTextColor())
+ }
+ e.addView(splitCheck)
+ pinCheck = CheckBox(this).apply {
+ setText(R.string.workspace_pin)
+ setTextColor(cardTextColor())
+ }
+ e.addView(pinCheck)
+ e.addView(ScreenWidgets.primaryButton(this, R.string.workspace_save) { save() })
+ return e
+ }
+
+ private fun sectionLabel(text: String) = TextView(this).apply {
+ this.text = text
+ textSize = 13f
+ setPadding(0, (8 * resources.displayMetrics.density).toInt(), 0, 0)
+ }
+
+ private fun group() = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding((8 * resources.displayMetrics.density).toInt(), 0, 0, 0)
+ }
+
+ private fun refresh() {
+ workspaces = WorkspaceStore.list(this)
+ list.removeAllViews()
+ if (workspaces.isEmpty()) {
+ list.addView(TextView(this).apply {
+ setText(R.string.workspace_empty)
+ textSize = 14f
+ })
+ }
+ for (w in workspaces) list.addView(card(w))
+ buildGroups()
+ }
+
+ private fun card(w: WorkspaceStore.Workspace): View {
+ val pad = (10 * resources.displayMetrics.density).toInt()
+ val card = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, pad, pad, pad)
+ setBackgroundColor(cardColor())
+ val m = (8 * resources.displayMetrics.density).toInt()
+ layoutParams = LinearLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT
+ ).apply { setMargins(0, 0, 0, m) }
+ }
+ val top = ScreenWidgets.headerRow(this).apply {
+ addView(TextView(this@WorkspaceActivity).apply {
+ text = w.name
+ textSize = 16f
+ setTextColor(cardTextColor())
+ })
+ addView(TextView(this@WorkspaceActivity).apply {
+ text = sessionsLabel(w.sessionCount())
+ textSize = 12f
+ setTextColor(mutedTextColor())
+ val mr = (16 * resources.displayMetrics.density).toInt()
+ setPadding(0, 0, mr, 0)
+ })
+ }
+ card.addView(top)
+ val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ row.addView(ScreenWidgets.actionButton(this, R.string.workspace_launch) { launch(w) })
+ row.addView(ScreenWidgets.actionButton(this, R.string.workspace_edit) { beginEdit(w) })
+ row.addView(ScreenWidgets.dangerButton(this, R.string.workspace_delete) {
+ WorkspaceStore.delete(this@WorkspaceActivity, w.id)
+ refresh()
+ })
+ card.addView(row)
+ return card
+ }
+
+ private fun sessionsLabel(n: Int): String =
+ resources.getQuantityString(R.plurals.workspace_sessions, n, n)
+
+ private fun buildGroups() {
+ val installed = runCatching { installer.getInstalledDistros() }.getOrDefault(emptyList())
+ val servers = SshStore.load(this)
+ distroGroup.removeAllViews()
+ distroChecks.clear()
+ if (installed.isEmpty()) {
+ distroGroup.addView(dim(getString(R.string.workspace_none)))
+ } else {
+ for (d in installed) {
+ distroChecks.add(CheckBox(this).apply {
+ text = d
+ setTextColor(cardTextColor())
+ setOnCheckedChangeListener { _, _ -> }
+ })
+ distroGroup.addView(distroChecks.last())
+ }
+ }
+ serverGroup.removeAllViews()
+ serverChecks.clear()
+ if (servers.isEmpty()) {
+ serverGroup.addView(dim(getString(R.string.workspace_no_servers)))
+ } else {
+ for (s in servers) {
+ serverChecks.add(CheckBox(this).apply {
+ text = s.label
+ setTextColor(cardTextColor())
+ setOnCheckedChangeListener { _, _ -> }
+ })
+ serverGroup.addView(serverChecks.last())
+ }
+ }
+ themeSpinner.adapter = ScreenWidgets.spinner(this, themes.map { it.second }).adapter
+ themeSpinner.setSelection(0)
+ }
+
+ private fun dim(s: String) = TextView(this).apply {
+ text = s
+ setTextColor(mutedTextColor())
+ }
+
+ private fun beginEdit(w: WorkspaceStore.Workspace?) {
+ buildGroups()
+ if (w == null) {
+ editing = null
+ editingId = null
+ nameField.setText("")
+ distroChecks.forEach { it.isChecked = false }
+ serverChecks.forEach { it.isChecked = false }
+ themeSpinner.setSelection(0)
+ hookCheck.isChecked = false
+ splitCheck.isChecked = false
+ pinCheck.isChecked = false
+ } else {
+ editing = w
+ editingId = w.id
+ nameField.setText(w.name)
+ distroChecks.forEach { it.isChecked = it.text.toString() in w.cleanDistros }
+ serverChecks.forEach {
+ it.isChecked = serversId(it) in w.serverIds
+ }
+ val idx = themes.indexOfFirst { it.first == w.theme }.coerceAtLeast(0)
+ themeSpinner.setSelection(idx)
+ hookCheck.isChecked = w.enableStartupHook
+ splitCheck.isChecked = w.split
+ pinCheck.isChecked = w.pinned
+ }
+ editor.visibility = View.VISIBLE
+ scroll.post { scroll.fullScroll(View.FOCUS_DOWN) }
+ }
+
+ private fun serversId(c: CheckBox): String {
+ val label = c.text.toString()
+ return SshStore.load(this).firstOrNull { it.label == label }?.id ?: ""
+ }
+
+ private fun save() {
+ val name = nameField.text.toString().trim().ifEmpty { "Workspace" }
+ val distros = distroChecks.filter { it.isChecked }.map { it.text.toString() }
+ val serverIds = serverChecks.filter { it.isChecked }.map { serversId(it) }.filter { it.isNotEmpty() }
+ val theme = themes[themeSpinner.selectedItemPosition].first.ifEmpty { null }
+ val id = editingId ?: WorkspaceStore.newWorkspace(name).id
+ val updated = WorkspaceStore.Workspace(
+ id = id,
+ name = name,
+ distros = distros,
+ serverIds = serverIds,
+ theme = theme,
+ snippetIds = editing?.snippetIds ?: emptyList(),
+ enableStartupHook = hookCheck.isChecked,
+ split = splitCheck.isChecked,
+ pinned = pinCheck.isChecked
+ )
+ WorkspaceStore.upsert(this, updated)
+ editor.visibility = View.GONE
+ refresh()
+ }
+
+ private fun launch(w: WorkspaceStore.Workspace) {
+ startActivity(
+ Intent(this, TerminalActivity::class.java)
+ .putExtra(TerminalActivity.EXTRA_WORKSPACE_ID, w.id)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ )
+ }
+
+ private fun applyTheme() {
+ val prefs = getSharedPreferences("settings", android.content.Context.MODE_PRIVATE)
+ when (NightModeReceiver.effectiveTheme(prefs)) {
+ "red" -> setTheme(R.style.Theme_RedTermApp_Red)
+ "amoled" -> setTheme(R.style.Theme_RedTermApp_AMOLED)
+ "green" -> setTheme(R.style.Theme_RedTermApp_Green)
+ "light" -> setTheme(R.style.Theme_RedTermApp_Light)
+ "dracula" -> setTheme(R.style.Theme_RedTermApp_Dracula)
+ "nord" -> setTheme(R.style.Theme_RedTermApp_Nord)
+ "tokyo" -> setTheme(R.style.Theme_RedTermApp_Tokyo)
+ "gruvbox" -> setTheme(R.style.Theme_RedTermApp_Gruvbox)
+ else -> setTheme(R.style.Theme_RedTermApp)
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/WorkspaceStore.kt b/app/src/main/java/com/redtermapp/ui/WorkspaceStore.kt
new file mode 100644
index 0000000..5b2c234
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/ui/WorkspaceStore.kt
@@ -0,0 +1,129 @@
+package com.redtermapp.ui
+
+import android.content.Context
+import androidx.core.content.edit
+import org.json.JSONArray
+import org.json.JSONObject
+import java.util.UUID
+
+/**
+ * A named, saved bundle of the things a terminal session is made of: which
+ * distro(s), which SSH server(s), the theme, and the snippets the user
+ * reaches for. Launching a workspace opens every session it names in one
+ * tap, which is what a "I always work in Ubuntu with my two VPSes and these
+ * snippets" loop should cost.
+ *
+ * Like [SshStore] it is JSON in preferences: a workspace is app state, not
+ * anything that outlives the process, and a flat record that can grow without
+ * a migration. A workspace references servers and snippets by id and copies
+ * the distro key; if a referenced server or snippet is later deleted the
+ * launch skips the missing piece rather than failing the whole bundle.
+ */
+object WorkspaceStore {
+
+ const val PREFS = "workspaces"
+ private const val KEY = "list"
+
+ data class Workspace(
+ val id: String,
+ val name: String,
+ val distros: List = emptyList(),
+ val serverIds: List = emptyList(),
+ val theme: String? = null,
+ val snippetIds: List = emptyList(),
+ val enableStartupHook: Boolean = false,
+ /** Open its sessions side by side on launch, when it names exactly two. */
+ val split: Boolean = false,
+ /** Show on the home screen as a quick launch. */
+ val pinned: Boolean = false
+ ) {
+ /** Distinct, non-blank distro keys; order is the user's. */
+ val cleanDistros: List
+ get() = distros.map { it.trim() }.filter { it.isNotEmpty() }.distinct()
+
+ fun sessionCount(): Int = cleanDistros.size + serverIds.size
+ }
+
+ fun list(context: Context): List =
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ .getString(KEY, null)
+ ?.let { WorkspaceStore.fromJson(it) }
+ ?: emptyList()
+
+ fun save(context: Context, workspaces: List) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit {
+ putString(KEY, toJson(workspaces))
+ }
+ }
+
+ fun get(context: Context, id: String): Workspace? = list(context).firstOrNull { it.id == id }
+
+ /** Upsert by id: a list without [workspace] plus the new value, order kept. */
+ fun upsert(context: Context, workspace: Workspace): List {
+ val all = list(context).filterNot { it.id == workspace.id } + workspace
+ save(context, all)
+ return all
+ }
+
+ fun delete(context: Context, id: String) {
+ save(context, list(context).filterNot { it.id == id })
+ }
+
+ fun newWorkspace(name: String): Workspace =
+ Workspace(id = UUID.randomUUID().toString(), name = name)
+
+ // --- pure JSON shape, round-tripped by a test so a missing field is a
+ // test failure, not a silent empty workspace ---
+
+ fun toJson(list: List): String =
+ JSONArray().also { arr ->
+ for (w in list) {
+ arr.put(JSONObject().apply {
+ put("id", w.id)
+ put("name", w.name)
+ put("distros", JSONArray(w.cleanDistros))
+ put("servers", JSONArray(w.serverIds))
+ put("theme", w.theme ?: "")
+ put("snippets", JSONArray(w.snippetIds))
+ put("hook", w.enableStartupHook)
+ put("split", w.split)
+ put("pinned", w.pinned)
+ })
+ }
+ }.toString()
+
+ fun fromJson(raw: String?): List {
+ if (raw.isNullOrBlank()) return emptyList()
+ return try {
+ val arr = JSONArray(raw)
+ (0 until arr.length()).mapNotNull { n ->
+ val o = arr.optJSONObject(n) ?: return@mapNotNull null
+ val id = o.optString("id").takeIf { it.isNotEmpty() } ?: return@mapNotNull null
+ Workspace(
+ id = id,
+ name = o.optString("name", id),
+ distros = jsonStrings(o, "distros"),
+ serverIds = jsonStrings(o, "servers"),
+ theme = o.optString("theme").takeIf { it.isNotEmpty() },
+ snippetIds = jsonStrings(o, "snippets"),
+ enableStartupHook = o.optBoolean("hook", false),
+ split = o.optBoolean("split", false),
+ pinned = o.optBoolean("pinned", false)
+ )
+ }
+ } catch (_: Exception) {
+ emptyList()
+ }
+ }
+
+ /** The non-blank string elements of a JSON array field, in order. */
+ private fun jsonStrings(o: JSONObject, key: String): List {
+ val arr = o.optJSONArray(key) ?: return emptyList()
+ val out = ArrayList(arr.length())
+ for (i in 0 until arr.length()) {
+ val v = arr.optString(i)
+ if (v.isNotEmpty()) out.add(v)
+ }
+ return out
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/ui/filelist/BaseFileBrowserActivity.kt b/app/src/main/java/com/redtermapp/ui/filelist/BaseFileBrowserActivity.kt
index f9636a1..188ae6c 100644
--- a/app/src/main/java/com/redtermapp/ui/filelist/BaseFileBrowserActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/filelist/BaseFileBrowserActivity.kt
@@ -25,6 +25,8 @@ import com.redtermapp.R
import com.redtermapp.ui.FileViewerActivity
import com.redtermapp.ui.NightModeReceiver
import com.redtermapp.ui.TextEditorActivity
+import com.redtermapp.ui.cardTextColor
+import com.redtermapp.ui.mutedTextColor
import java.io.File
/**
@@ -387,6 +389,69 @@ abstract class BaseFileBrowserActivity : AppCompatActivity() {
}
}
+ /**
+ * A recursive search, the answer to "somewhere under here" rather than
+ * "in this folder".
+ *
+ * The query comes from the one-line search bar when it is open, so the
+ * two search modes share the same input and the same result view. The
+ * walk is bounded on the source's side, and the label says so when it was
+ * cut short.
+ */
+ private fun showDeepSearch() {
+ val start = currentPath
+ val edit = EditText(this).apply {
+ setText(searchView?.text?.toString().orEmpty())
+ setSingleLine(true)
+ hint = getString(R.string.search_hint, start)
+ setTextColor(cardTextColor())
+ setHintTextColor(mutedTextColor())
+ requestFocus()
+ }
+ val dialog = AlertDialog.Builder(this)
+ .setTitle(R.string.search_recursive)
+ .setView(edit)
+ .setPositiveButton(R.string.ok, null)
+ .setNegativeButton(R.string.cancel, null)
+ .create()
+ dialog.show()
+ dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
+ val query = edit.text.toString().trim()
+ if (query.isEmpty()) {
+ Toast.makeText(this, R.string.search_empty, Toast.LENGTH_SHORT).show()
+ return@setOnClickListener
+ }
+ dialog.dismiss()
+ runDeepSearch(start, query)
+ }
+ }
+
+ private fun runDeepSearch(start: String, query: String) {
+ searching = true
+ pathLabel.text = getString(R.string.searching_deep, start, query)
+ rowAdapter.submit(emptyList())
+ background {
+ val (found, truncated) = source().searchDeep(start, query, MAX_SEARCH_RESULTS)
+ main {
+ if (found.isEmpty()) {
+ pathLabel.text = getString(R.string.no_matches_deep, query, start)
+ rowAdapter.submit(emptyList())
+ } else {
+ pathLabel.text = if (truncated) {
+ resources.getQuantityString(
+ R.plurals.match_count_deep_capped, found.size, found.size, query, start
+ )
+ } else {
+ resources.getQuantityString(
+ R.plurals.match_count_deep, found.size, found.size, query, start
+ )
+ }
+ rowAdapter.submit(found.map { Row(it, false) })
+ }
+ }
+ }
+ }
+
private fun showSearchBar() {
if (searchView != null) return
val container = findViewById(R.id.file_search_container)
@@ -686,6 +751,7 @@ abstract class BaseFileBrowserActivity : AppCompatActivity() {
return true
}
R.id.action_search -> { showSearchBar(); return true }
+ R.id.action_search_deep -> { showDeepSearch(); return true }
R.id.action_new_folder -> { newFolder(); return true }
R.id.action_paste -> { pasteHere(move = false); return true }
R.id.action_refresh -> { loadDir(currentPath); return true }
diff --git a/app/src/main/java/com/redtermapp/ui/filelist/FileSource.kt b/app/src/main/java/com/redtermapp/ui/filelist/FileSource.kt
index 84cf380..ecbc268 100644
--- a/app/src/main/java/com/redtermapp/ui/filelist/FileSource.kt
+++ b/app/src/main/java/com/redtermapp/ui/filelist/FileSource.kt
@@ -68,6 +68,18 @@ interface FileSource {
* @return the matches and whether the result was cut off at [limit].
*/
fun search(from: String, query: String, limit: Int): Pair, Boolean>
+
+ /**
+ * A bounded recursive search below [from].
+ *
+ * Every level costs a round trip on a server, so the walk is breadth-first,
+ * stops as soon as [limit] matches are in, and reports through the second
+ * element when it was cut short by a match cap or a directory cap rather
+ * than by exhausting the tree.
+ *
+ * @return the matches and whether the walk stopped before it was complete.
+ */
+ fun searchDeep(from: String, query: String, limit: Int): Pair, Boolean>
}
/** Outcome of a change. [Failed.reason] is shown to the user verbatim. */
diff --git a/app/src/main/java/com/redtermapp/ui/filelist/LocalDistroSource.kt b/app/src/main/java/com/redtermapp/ui/filelist/LocalDistroSource.kt
index fc623ed..6c7512e 100644
--- a/app/src/main/java/com/redtermapp/ui/filelist/LocalDistroSource.kt
+++ b/app/src/main/java/com/redtermapp/ui/filelist/LocalDistroSource.kt
@@ -121,6 +121,13 @@ class LocalDistroSource(
return found to truncated
}
+ /**
+ * The local walk already descends every directory, so a deep search is
+ * the same walk: it stops early once [limit] matches are in.
+ */
+ override fun searchDeep(from: String, query: String, limit: Int): Pair, Boolean> =
+ search(from, query, limit)
+
private fun File.toEntry() = FileEntry(
path = absolutePath,
name = name,
diff --git a/app/src/main/java/com/redtermapp/ui/filelist/SftpBrowserActivity.kt b/app/src/main/java/com/redtermapp/ui/filelist/SftpBrowserActivity.kt
index 299fee1..a319af7 100644
--- a/app/src/main/java/com/redtermapp/ui/filelist/SftpBrowserActivity.kt
+++ b/app/src/main/java/com/redtermapp/ui/filelist/SftpBrowserActivity.kt
@@ -10,6 +10,7 @@ import androidx.appcompat.app.AlertDialog
import com.redtermapp.R
import com.redtermapp.ui.ConnectingOverlay
import com.redtermapp.ui.SshStore
+import com.redtermapp.ui.TransferQueueActivity
import com.redtermapp.util.AppLog
import java.io.File
@@ -215,20 +216,92 @@ class SftpBrowserActivity : BaseFileBrowserActivity() {
private fun downloadToDevice(entry: FileEntry) {
if (entry.isDirectory) {
- // sftp can do `get -r`, but it would write into the rootfs staging
- // area, which has nowhere near the room for a large tree and is not
- // where the user expects the result.
- AlertDialog.Builder(this)
- .setTitle(entry.name)
- .setMessage(R.string.sftp_folder_download_note)
- .setPositiveButton(R.string.ok, null)
- .show()
+ downloadFolder(entry)
return
}
pendingDownload = entry
createDocument.launch(entry.name)
}
+ /**
+ * Downloads a whole tree into the app's transfers directory, mirroring the
+ * layout.
+ *
+ * A picked document (the single-file path) is a stream with no directory
+ * structure behind it, so a tree cannot land there; app storage is where
+ * a mirror can be written without a storage permission.
+ */
+ private fun downloadFolder(entry: FileEntry) {
+ val dest = File(getExternalFilesDir("transfers"), entry.name)
+ val dialog = AlertDialog.Builder(this)
+ .setTitle(getString(R.string.sftp_downloading_folder, entry.name))
+ .setMessage(R.string.sftp_transfer_running)
+ .setCancelable(false)
+ .create()
+ dialog.show()
+ transferDialog = dialog
+ transferThread = Thread({
+ val outcome = sftpSource.downloadDir(entry.path, dest) { done, total ->
+ main {
+ dialog.setMessage(
+ if (total > 0) {
+ getString(R.string.sftp_transfer_progress, (done * 100 / total).toInt())
+ } else {
+ getString(R.string.sftp_transfer_bytes, formatSize(done))
+ }
+ )
+ }
+ }
+ main {
+ if (isFinishing || isDestroyed) {
+ dialog.dismiss()
+ return@main
+ }
+ transferDialog = null
+ transferThread = null
+ dialog.dismiss()
+ val message = StringBuilder(
+ resources.getQuantityString(
+ R.plurals.sftp_folder_done,
+ outcome.files,
+ outcome.files,
+ formatSize(outcome.totalBytes),
+ dest.absolutePath
+ )
+ )
+ if (outcome.failed > 0) {
+ message.append('\n')
+ .append(
+ resources.getQuantityString(
+ R.plurals.sftp_folder_failed,
+ outcome.failed,
+ outcome.failed
+ )
+ )
+ }
+ if (outcome.unreadableDirs > 0) {
+ message.append('\n')
+ .append(
+ resources.getQuantityString(
+ R.plurals.sftp_folder_unreadable,
+ outcome.unreadableDirs,
+ outcome.unreadableDirs
+ )
+ )
+ }
+ if (outcome.truncated) {
+ message.append('\n').append(getString(R.string.sftp_folder_truncated))
+ }
+ AlertDialog.Builder(this)
+ .setTitle(R.string.sftp_folder_downloaded)
+ .setMessage(message.toString())
+ .setPositiveButton(R.string.ok, null)
+ .show()
+ loadDir(currentPath)
+ }
+ }, "redterm-sftp-folder").also { it.start() }
+ }
+
private val createDocument =
registerForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { uri ->
val entry = pendingDownload
@@ -242,7 +315,7 @@ class SftpBrowserActivity : BaseFileBrowserActivity() {
// user picked. The picked location is a document, which may have no
// file path behind it at all, so it cannot be written to directly.
val staged = File(cacheDir, "sftp-download-${System.nanoTime()}-${entry.name}")
- val fetched = sftpSource.downloadTo(entry, staged, onProgress)
+ val fetched = sftpSource.downloadTo(entry, staged, onProgress = onProgress)
if (fetched is OpResult.Failed) {
staged.delete()
return@withProgress fetched
@@ -291,7 +364,7 @@ class SftpBrowserActivity : BaseFileBrowserActivity() {
return
}
withProgress(getString(R.string.sftp_uploading, name)) { onProgress ->
- val result = sftpSource.uploadFrom(staged, target, onProgress)
+ val result = sftpSource.uploadFrom(staged, target, onProgress = onProgress)
staged.delete()
result
}
@@ -373,13 +446,24 @@ class SftpBrowserActivity : BaseFileBrowserActivity() {
menu.add(0, MENU_UPLOAD, 0, R.string.sftp_upload).setShowAsAction(
android.view.MenuItem.SHOW_AS_ACTION_NEVER
)
+ menu.add(0, MENU_TRANSFER_QUEUE, 0, R.string.transfer_queue).setShowAsAction(
+ android.view.MenuItem.SHOW_AS_ACTION_NEVER
+ )
return created
}
override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean {
- if (item.itemId == MENU_UPLOAD) {
- pickDocument.launch(arrayOf("*/*"))
- return true
+ when (item.itemId) {
+ MENU_UPLOAD -> {
+ pickDocument.launch(arrayOf("*/*"))
+ return true
+ }
+ MENU_TRANSFER_QUEUE -> {
+ startActivity(
+ android.content.Intent(this@SftpBrowserActivity, TransferQueueActivity::class.java)
+ )
+ return true
+ }
}
return super.onOptionsItemSelected(item)
}
@@ -400,5 +484,6 @@ class SftpBrowserActivity : BaseFileBrowserActivity() {
private const val EXTRA_USER = "ssh_user"
private const val EXTRA_LABEL = "ssh_label"
private const val MENU_UPLOAD = 9001
+ private const val MENU_TRANSFER_QUEUE = 9002
}
}
\ No newline at end of file
diff --git a/app/src/main/java/com/redtermapp/ui/filelist/SftpSource.kt b/app/src/main/java/com/redtermapp/ui/filelist/SftpSource.kt
index b706cde..c95b3c3 100644
--- a/app/src/main/java/com/redtermapp/ui/filelist/SftpSource.kt
+++ b/app/src/main/java/com/redtermapp/ui/filelist/SftpSource.kt
@@ -6,6 +6,8 @@ import com.redtermapp.ui.SshKeyAuthenticator
import com.redtermapp.ui.SshKeyStore
import com.redtermapp.ui.SshStore
import com.redtermapp.util.AppLog
+import com.redtermapp.util.sftp.DirSearch
+import com.redtermapp.util.sftp.DirWalk
import com.redtermapp.util.sftp.SftpAttrs
import com.redtermapp.util.sftp.StatVfs
import com.redtermapp.util.sftp.SftpClient
@@ -66,6 +68,15 @@ class SftpSource(
/** Remote files are fetched before a local viewer can open them. */
override val canOpenLocally: Boolean = false
+ /**
+ * How many directories a deep search may list.
+ *
+ * Each costs a round trip, so an unbounded walk of a big tree is minutes
+ * of nothing; the cap turns "searched the whole server" into an honest
+ * "searched 400 of the top directories", which is what the result says.
+ */
+ private val DEEP_SEARCH_DIRS = 400
+
private var error: String = ""
override val lastError: String get() = error
@@ -326,6 +337,30 @@ class SftpSource(
return if (downloadTo(entry, target) { _, _ -> } is OpResult.Ok) target else null
}
+ /**
+ * A bounded recursive search: breadth-first, so a shallow hit is found
+ * before a deep one, and the walk stops the moment [limit] matches are in
+ * rather than listing every directory the server has.
+ *
+ * The ordering, caps and cutoff rules live in [DirSearch], which is
+ * unit-tested; this is the thin connection behind it.
+ */
+ override fun searchDeep(from: String, query: String, limit: Int): Pair, Boolean> {
+ val result = DirSearch.find(
+ root = from,
+ childrenOf = { dir ->
+ list(dir)?.map { e ->
+ DirSearch.Entry(e.name, e.isDirectory, e.isSymlink, e.path, e)
+ }
+ },
+ query = query,
+ limit = limit,
+ maxDirs = DEEP_SEARCH_DIRS
+ )
+ val sorted = result.matches.sortedBy { it.remotePath.lowercase() }
+ return sorted.map { it.payload } to result.truncated
+ }
+
/**
* Downloads [entry] to [destination], reporting byte progress.
*
@@ -335,11 +370,12 @@ class SftpSource(
fun downloadTo(
entry: FileEntry,
destination: File,
+ startOffset: Long = 0L,
onProgress: (Long, Long) -> Unit
): OpResult {
AppLog.i(context, "sftp", "download ${entry.path} -> ${destination.name}")
return withConnection { client ->
- client.download(entry.path, destination, onProgress)
+ client.download(entry.path, destination, startOffset = startOffset, onProgress = onProgress)
AppLog.i(context, "sftp", "downloaded ${entry.path}, ${destination.length()} bytes")
OpResult.Ok
} ?: OpResult.Failed(error)
@@ -349,6 +385,7 @@ class SftpSource(
fun uploadFrom(
hostFile: File,
remotePath: String,
+ startOffset: Long = 0L,
onProgress: (Long, Long) -> Unit
): OpResult {
AppLog.i(context, "sftp", "upload ${hostFile.name} (${hostFile.length()} bytes) -> $remotePath")
@@ -356,13 +393,117 @@ class SftpSource(
if (hostFile.isDirectory) {
uploadTreeWithProgress(client, hostFile, remotePath, onProgress)
} else {
- client.upload(hostFile, remotePath, onProgress)
+ client.upload(hostFile, remotePath, startOffset = startOffset, onProgress = onProgress)
}
AppLog.i(context, "sftp", "uploaded $remotePath")
OpResult.Ok
} ?: OpResult.Failed(error)
}
+ /**
+ * The outcome of a recursive folder download.
+ *
+ * [ok] is about the walk itself; individual file failures are counted, not
+ * fatal, because a folder transfer that dies on one unreadable file has
+ * still delivered everything else and can be re-run to pick it up.
+ */
+ data class DirOutcome(
+ val ok: Boolean,
+ val files: Int,
+ val failed: Int,
+ val totalBytes: Long,
+ val unreadableDirs: Int,
+ val skippedSymlinks: Int,
+ val truncated: Boolean,
+ val reason: String = ""
+ )
+
+ /**
+ * Downloads a remote directory's whole tree into [localRoot], mirroring the
+ * layout.
+ *
+ * The walk is planned breadth-first by [DirWalk] so parent directories are
+ * created before their children and a cycle cannot walk the server for
+ * hours. Each file is resumed from whatever is already on disk, so a
+ * transfer interrupted by a network drop continues instead of starting
+ * over. Progress is in bytes, which is the only figure the client can
+ * promise: it does the chunking, and the tree's size is known only after
+ * the walk.
+ */
+ fun downloadDir(
+ remoteDir: String,
+ localRoot: File,
+ onProgress: (Long, Long) -> Unit
+ ): DirOutcome {
+ AppLog.i(context, "sftp", "downloading directory $remoteDir -> ${localRoot.name}")
+ val outcome = withConnection { client ->
+ val childrenOf: (String) -> List? = { dir ->
+ client.list(dir).map { n ->
+ DirWalk.Child(
+ n.filename,
+ n.attrs.isDirectory,
+ n.attrs.size ?: 0L,
+ n.attrs.isSymlink
+ )
+ }
+ }
+ val plan = DirWalk.plan(remoteDir, childrenOf)
+ for (d in plan.directories) {
+ DirWalk.mirrorPath(localRoot, d)?.mkdirs()
+ }
+ val total = plan.files.sumOf { it.size }
+ var completed = 0L
+ var filesDone = 0
+ var failed = 0
+ for (f in plan.files) {
+ val dest = DirWalk.mirrorPath(localRoot, f.relativePath)
+ if (dest == null) {
+ failed++
+ continue
+ }
+ val existing = if (dest.exists()) dest.length() else 0L
+ if (dest.exists() && existing >= f.size) {
+ // The mirror is ahead of the transfer: nothing to do.
+ completed += f.size
+ filesDone++
+ continue
+ }
+ val start = minOf(existing, f.size)
+ val base = completed
+ var last = start
+ try {
+ client.download(f.remotePath, dest, startOffset = start) { offset, _ ->
+ last = offset
+ onProgress(minOf(base + offset, total), total)
+ }
+ completed = base + minOf(last, f.size)
+ filesDone++
+ } catch (e: Exception) {
+ // One unreadable file does not sink the folder, and the
+ // partial file stays where it is for the next run.
+ failed++
+ AppLog.e(context, "sftp", "download of ${f.remotePath} failed: ${e.message}")
+ }
+ }
+ DirOutcome(
+ ok = plan.unreadableDirs.isEmpty(),
+ files = filesDone,
+ failed = failed,
+ totalBytes = total,
+ unreadableDirs = plan.unreadableDirs.size,
+ skippedSymlinks = plan.skippedSymlinks.size,
+ truncated = plan.truncated,
+ reason = if (plan.unreadableDirs.isEmpty()) "" else error
+ )
+ } ?: DirOutcome(false, 0, 0, 0L, 0, 0, false, reason = error)
+ AppLog.i(
+ context, "sftp",
+ "directory $remoteDir: ${outcome.files} file(s), ${outcome.failed} failed, " +
+ "${outcome.unreadableDirs} unreadable dir(s)"
+ )
+ return outcome
+ }
+
private fun uploadTreeWithProgress(
client: SftpClient,
localRoot: File,
diff --git a/app/src/main/java/com/redtermapp/util/DeviceResources.kt b/app/src/main/java/com/redtermapp/util/DeviceResources.kt
new file mode 100644
index 0000000..fc59a08
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/util/DeviceResources.kt
@@ -0,0 +1,63 @@
+package com.redtermapp.util
+
+import java.io.File
+
+/**
+ * How much RAM and how many cores the device has, read from /proc.
+ *
+ * A proot distro is not a virtual machine: it shares the device's kernel,
+ * so the resource that decides whether a session will run at all is the
+ * device's free memory and core count, not anything the guest reports.
+ * That is what the dashboard shows.
+ *
+ * The [parseMemInfo]/[cpuCount] functions are pure and unit-tested; the
+ * [read*] wrappers are the thin /proc reads that need a device.
+ */
+object DeviceResources {
+
+ /** /proc/meminfo figures, in kilobytes as the kernel reports them. */
+ data class Memory(val totalKb: Long, val availableKb: Long) {
+ val usedKb: Long get() = (totalKb - availableKb).coerceAtLeast(0L)
+ }
+
+ /**
+ * The lines that matter out of /proc/meminfo.
+ *
+ * Each line is `Key: 12345 kB`. Only MemTotal and MemAvailable are
+ * read; everything else, and any malformed line, is skipped rather than
+ * fatal, because a kernel that omits a field is not an error to report.
+ */
+ fun parseMemInfo(text: String): Memory {
+ var total = 0L
+ var available = 0L
+ for (line in text.lineSequence()) {
+ val sep = line.indexOf(':')
+ if (sep <= 0) continue
+ val key = line.substring(0, sep).trim()
+ val value = line.substring(sep + 1).trim().substringBefore(' ').toLongOrNull() ?: continue
+ when (key) {
+ "MemTotal" -> total = value
+ "MemAvailable" -> available = value
+ }
+ }
+ return Memory(total, available)
+ }
+
+ /**
+ * Core count from /proc/cpuinfo.
+ *
+ * One `processor` line per core is the stable part of the format;
+ * the model-name and flags lines differ per architecture and must not
+ * be counted.
+ */
+ fun cpuCount(cpuinfo: String): Int =
+ cpuinfo.lineSequence().count { it.startsWith("processor") }
+
+ fun readMemory(): Memory? = runCatching {
+ parseMemInfo(File("/proc/meminfo").readText())
+ }.getOrNull()
+
+ fun readCpuCount(): Int = runCatching {
+ cpuCount(File("/proc/cpuinfo").readText())
+ }.getOrNull()?.takeIf { it > 0 } ?: Runtime.getRuntime().availableProcessors()
+}
diff --git a/app/src/main/java/com/redtermapp/util/GifFramePlan.kt b/app/src/main/java/com/redtermapp/util/GifFramePlan.kt
new file mode 100644
index 0000000..bfdae08
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/util/GifFramePlan.kt
@@ -0,0 +1,29 @@
+package com.redtermapp.util
+
+/**
+ * The frame layout of a recording's GIF export.
+ *
+ * A recording is fed to the terminal library in chunks at a fixed pace, the
+ * way the player paces it, and one GIF frame is drawn per [decimation]
+ * chunks. The decimation keeps a long recording under the frame cap, and the
+ * delay is the real time those skipped chunks took — a GIF that plays
+ * faster than the session ran is a misrecording of it.
+ *
+ * Pure, so the layout is unit-tested without a display.
+ */
+object GifFramePlan {
+
+ /** The player's feed: how many bytes per tick, and the tick's duration. */
+ const val CHUNK_SIZE = 4096
+ const val PACE_MS = 12L
+
+ /** How many chunks one GIF frame covers for a recording of [totalChunks]. */
+ fun decimation(totalChunks: Int, maxFrames: Int): Int {
+ if (totalChunks <= 0 || maxFrames <= 0) return 1
+ return ((totalChunks + maxFrames - 1) / maxFrames).coerceAtLeast(1)
+ }
+
+ /** The frame delay in centiseconds: the real time the decimated chunks took. */
+ fun delayCentiseconds(decimation: Int, tickMs: Long = PACE_MS): Int =
+ (decimation.toLong() * tickMs / 10L).toInt().coerceIn(1, 500)
+}
diff --git a/app/src/main/java/com/redtermapp/util/GifWriter.kt b/app/src/main/java/com/redtermapp/util/GifWriter.kt
new file mode 100644
index 0000000..f7d3da0
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/util/GifWriter.kt
@@ -0,0 +1,267 @@
+package com.redtermapp.util
+
+import java.io.OutputStream
+
+/**
+ * A GIF89a writer with a 256-colour global palette and LZW frame compression.
+ *
+ * Only what a terminal recording needs: one global colour table, a looping
+ * image list, and frames whose pixels are already palette indices — the
+ * quantising from terminal colours into those indices is the caller's
+ * problem, and it is pure and testable here in [palette] and [nearestIndex].
+ *
+ * The encoder is byte-exact to the GIF89a spec so the output is a file
+ * any viewer can open; the LZW step is round-tripped by a decoder in the
+ * unit tests, because a compression bug does not produce an error, it
+ * produces a garbled image nobody can name.
+ */
+class GifWriter(private val out: OutputStream) {
+
+ /** One frame: [pixels] are indices into the global palette, [delayCs] in centiseconds. */
+ data class Frame(val pixels: IntArray, val delayCs: Int)
+
+ private var width = 0
+ private var height = 0
+ private var palette: IntArray = IntArray(256)
+
+ fun start(width: Int, height: Int, palette: IntArray) {
+ require(palette.size == 256) { "a GIF global colour table has exactly 256 entries" }
+ this.width = width
+ this.height = height
+ this.palette = palette
+ out.write("GIF89a".toByteArray(Charsets.US_ASCII))
+ // Logical screen descriptor: size, global table (256 = size field 7),
+ // 7-bit colour resolution, background index 0, no aspect ratio.
+ writeLE16(width)
+ writeLE16(height)
+ out.write(0xF7)
+ out.write(0)
+ out.write(0)
+ for (i in 0 until 256) {
+ out.write(palette[i] and 0xFF)
+ out.write((palette[i] shr 8) and 0xFF)
+ out.write((palette[i] shr 16) and 0xFF)
+ }
+ // Netscape looping extension: loop forever.
+ out.write(0x21)
+ out.write(0xFF)
+ out.write("Netscape".toByteArray(Charsets.US_ASCII))
+ out.write(byteArrayOf(0x32, 0x2E, 0x30, 0x03, 0x01, 0x00, 0x00, 0x00))
+ }
+
+ fun frame(pixels: IntArray, delayCs: Int) {
+ require(pixels.size == width * height) { "a frame holds width*height pixels" }
+ // Graphic control: no disposal, delay in centiseconds, no transparent index.
+ out.write(0x21)
+ out.write(0xF9)
+ out.write(0x00)
+ out.write(delayCs and 0xFF)
+ out.write((delayCs shr 8) and 0xFF)
+ out.write(0)
+ // Image descriptor at the top-left corner, no local colour table.
+ out.write(0x2C)
+ writeLE16(0)
+ writeLE16(0)
+ writeLE16(width)
+ writeLE16(height)
+ out.write(0)
+ // LZW minimum code size: the global table holds 256 colours.
+ out.write(8)
+ val compressed = Lzw.encode(8, pixels)
+ // Sub-blocks of at most 255 bytes, then the zero block.
+ var i = 0
+ while (i < compressed.size) {
+ val n = minOf(255, compressed.size - i)
+ out.write(n)
+ out.write(compressed, i, n)
+ i += n
+ }
+ out.write(0)
+ }
+
+ private fun writeLE16(v: Int) {
+ out.write(v and 0xFF)
+ out.write((v shr 8) and 0xFF)
+ }
+
+ fun finish() {
+ out.write(0x3B)
+ out.flush()
+ }
+
+ companion object {
+ /** The sixteen basic colours, xterm's values: the hues a terminal means. */
+ val ANSI16 = intArrayOf(
+ 0x000000, 0xCD0000, 0x00CD00, 0xCDCD00,
+ 0x0000EE, 0xCD00CD, 0x00CDCD, 0xE5E5E5,
+ 0x7F7F7F, 0xFF0000, 0x00FF00, 0xFFFF00,
+ 0x5C5CFF, 0xFF00FF, 0x00FFFF, 0xFFFFFF
+ )
+
+ /**
+ * The 256-entry table a terminal recording quantises into: background,
+ * foreground, the sixteen basic colours, and background again for the
+ * rest — a terminal frame is almost entirely one of those few colours,
+ * so the spare indices are dead weight.
+ *
+ * [fg]/[bg] are 0xRRGGBB; [ansi16] is exactly sixteen 0xRRGGBB values.
+ */
+ fun palette(bg: Int, fg: Int, ansi16: IntArray): IntArray {
+ val table = IntArray(256) { bg }
+ table[0] = bg
+ table[1] = fg
+ ansi16.forEachIndexed { i, c -> table[2 + i] = c }
+ return table
+ }
+
+ /**
+ * The nearest palette entry to an 0xRRGGBB colour.
+ *
+ * Nearest in squared RGB distance; 256 candidates is cheap enough to
+ * do per pixel, and it keeps the exported GIF in the recording's own
+ * colours instead of a dithered caricature of them.
+ */
+ fun nearestIndex(rgb: Int, table: IntArray): Int {
+ val r = (rgb shr 16) and 0xFF
+ val g = (rgb shr 8) and 0xFF
+ val b = rgb and 0xFF
+ var best = 0
+ var bestDist = Int.MAX_VALUE
+ for (i in table.indices) {
+ val dr = r - (table[i] shr 16 and 0xFF)
+ val dg = g - (table[i] shr 8 and 0xFF)
+ val db = b - (table[i] and 0xFF)
+ val dist = dr * dr + dg * dg + db * db
+ if (dist < bestDist) {
+ bestDist = dist
+ best = i
+ }
+ }
+ return best
+ }
+ }
+
+ /**
+ * GIF-style LZW, little-endian bit packing.
+ *
+ * [minCodeSize] is the code size the colour table dictates (eight for
+ * 256 colours); the clear and end codes sit just above it, and the code
+ * size grows one bit at a time up to twelve.
+ *
+ * The string table is open-addressed on (parent, first character), so a
+ * lookup is constant time — the naive scan over the table would make an
+ * export take minutes on a phone. The allocation order (and therefore
+ * the codes) never depends on the hash, so a decoder that walks the
+ * codes in order reconstructs the same strings.
+ */
+ object Lzw {
+
+ private const val HASH_SIZE = 8192
+
+ fun encode(minCodeSize: Int, codes: IntArray): ByteArray {
+ val clear = 1 shl minCodeSize
+ val end = clear + 1
+ var codeSize = minCodeSize + 1
+ var next = end + 1
+ val firstFree = next
+
+ // The string table is open-addressed on (parent, first character);
+ // the slot a code occupies is the code itself, so a decoder that
+ // allocates in the same order rebuilds the same strings. Slots
+ // clear and end are never strings.
+ val hKey = IntArray(HASH_SIZE) { -1 }
+ val hCode = IntArray(HASH_SIZE)
+ val hUsed = IntArray(4096) // the hash slots a live entry occupies
+ var hUsedCount = 0
+
+ fun hashSlot(parent: Int, c: Int): Int =
+ (((parent.toLong() * 2654435761L) xor (c.toLong() * 40503L)) and 8191L).toInt()
+
+ fun lookup(parent: Int, c: Int): Int {
+ var h = hashSlot(parent, c)
+ while (true) {
+ val k = hKey[h]
+ if (k == -1) return -1
+ val code = hCode[h]
+ if (k == parent * 256 + c && code in firstFree..4095) return code
+ h = (h + 1) and (HASH_SIZE - 1)
+ }
+ }
+
+ fun insert(parent: Int, c: Int, slot: Int) {
+ val key = parent * 256 + c
+ var h = hashSlot(parent, c)
+ while (true) {
+ val k = hKey[h]
+ if (k == -1) {
+ hKey[h] = key
+ hCode[h] = slot
+ hUsed[hUsedCount++] = h
+ return
+ }
+ if (k == key && hCode[h] in firstFree..4095) {
+ // The entry already exists under this key.
+ return
+ }
+ h = (h + 1) and (HASH_SIZE - 1)
+ }
+ }
+
+ fun clearTable() {
+ for (i in 0 until hUsedCount) {
+ val h = hUsed[i]
+ if (h >= 0) hKey[h] = -1
+ }
+ hUsedCount = 0
+ }
+
+ var acc = 0
+ var bits = 0
+ val out = java.io.ByteArrayOutputStream()
+
+ fun emit(code: Int) {
+ acc = acc or (code shl bits)
+ bits += codeSize
+ while (bits >= 8) {
+ // The low byte goes out first: GIF packs each code's
+ // least-significant bits into the least-significant bits
+ // of the stream, and the reader relies on the same order.
+ out.write(acc and 0xFF)
+ acc = acc ushr 8
+ bits -= 8
+ }
+ }
+
+ emit(clear)
+ var prev = -1
+ for (c in codes) {
+ if (prev < 0) {
+ prev = c
+ continue
+ }
+ val found = lookup(prev, c)
+ if (found >= 0) {
+ prev = found
+ } else {
+ emit(prev)
+ if (next < 4096) {
+ insert(prev, c, next)
+ next++
+ if (next >= (1 shl codeSize) && codeSize < 12) codeSize++
+ }
+ if (next >= 4096) {
+ emit(clear)
+ clearTable()
+ next = firstFree
+ codeSize = minCodeSize + 1
+ }
+ prev = c
+ }
+ }
+ if (prev >= 0) emit(prev)
+ emit(end)
+ if (bits > 0) out.write(acc and ((1 shl bits) - 1))
+ return out.toByteArray()
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/util/MoshUdpProbe.kt b/app/src/main/java/com/redtermapp/util/MoshUdpProbe.kt
new file mode 100644
index 0000000..b30b54d
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/util/MoshUdpProbe.kt
@@ -0,0 +1,67 @@
+package com.redtermapp.util
+
+/**
+ * What a UDP reachability probe told us, and what it means for a mosh session.
+ *
+ * mosh needs a live UDP path to the server's port range; the app can neither
+ * open one nor confirm it directly, because mosh-server only answers a
+ * correctly-keyed mosh hello. The one thing a phone *can* observe is the
+ * kernel's reaction to a datagram aimed at a port that is surely closed: a
+ * host whose firewall admits UDP answers with ICMP "port unreachable", a
+ * host (or carrier) that swallows UDP answers with nothing. That asymmetry
+ * is the whole signal, and it is why the verdict is phrased as "likely" —
+ * a network that drops ICMP too reads as blocked when UDP is in fact open.
+ *
+ * The classification and the wording of the remedy are pure, so they are
+ * unit-tested; only the datagram send itself touches the network.
+ */
+object MoshUdpProbe {
+
+ /** The three things a probe can observe. */
+ sealed class Signal {
+ /** The host answered "no such port": UDP reached it. */
+ object PortUnreachable : Signal()
+ /** The network or host gave up before an answer: UDP likely dropped. */
+ object NoAnswer : Signal()
+ /** The probe could not be run at all (no route, no socket). */
+ object Unknown : Signal()
+ }
+
+ /** What the signal means for getting mosh to work. */
+ enum class Verdict { UDP_OPEN, UDP_BLOCKED, INCONCLUSIVE }
+
+ /** Map an observation to a verdict. */
+ fun classify(signal: Signal): Verdict = when (signal) {
+ Signal.PortUnreachable -> Verdict.UDP_OPEN
+ Signal.NoAnswer -> Verdict.UDP_BLOCKED
+ Signal.Unknown -> Verdict.INCONCLUSIVE
+ }
+
+ /**
+ * The port to probe: one outside mosh-server's default 60000-61000 range,
+ * so it is closed even while a mosh session holds a port in that range.
+ */
+ const val CLOSED_PROBE_PORT = 65000
+
+ /**
+ * The words the user can act on. This is the whole feature: a silent
+ * mosh session and a working one look identical until someone says which
+ * of the two fixes applies, and the fix that works for a blocked path is
+ * not the one that works for an open one.
+ */
+ fun suggestion(verdict: Verdict, host: String): String = when (verdict) {
+ Verdict.UDP_OPEN ->
+ "UDP to $host appears open, so mosh's silence is not a firewall " +
+ "dropping it: the server may lack mosh-server, or the port it " +
+ "bound is not the one the phone can reach. Plain SSH works either way."
+ Verdict.UDP_BLOCKED ->
+ "UDP to $host appears blocked, which is the common mosh failure: " +
+ "the firewall admits TCP 22 and drops the rest. A tunnel that " +
+ "carries UDP (Tailscale, WireGuard) makes the same server work; " +
+ "until then plain SSH is the working session."
+ Verdict.INCONCLUSIVE ->
+ "The UDP probe could not be run, so this stays a guess: if $host " +
+ "drops ICMP as well as UDP, an open path still reads as blocked. " +
+ "Plain SSH works regardless; a UDP-carrying tunnel makes mosh possible."
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/util/SshClient.kt b/app/src/main/java/com/redtermapp/util/SshClient.kt
index f574825..1b5a5b8 100644
--- a/app/src/main/java/com/redtermapp/util/SshClient.kt
+++ b/app/src/main/java/com/redtermapp/util/SshClient.kt
@@ -37,8 +37,11 @@ object SshClient {
* The stamp used to be the architecture alone, which meant a device that
* installed a client once would never notice a new one: `ssh` worked, so the
* check passed and `sftp`/`scp` stayed absent forever.
+ * v3: rebuilt with `--prefix=/usr --sysconfdir=/etc/ssh` so the client
+ * reads the distro's real /etc/ssh/ssh_config instead of the build host's
+ * work directory (which its own -v trace used to print).
*/
- const val CLIENT_VERSION = 2
+ const val CLIENT_VERSION = 3
/** Without these there is no SSH feature at all, so their absence is fatal. */
val REQUIRED_PROGRAMS = listOf("ssh", "ssh-keygen")
diff --git a/app/src/main/java/com/redtermapp/util/UdpHoleProbe.kt b/app/src/main/java/com/redtermapp/util/UdpHoleProbe.kt
new file mode 100644
index 0000000..ceb0a3d
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/util/UdpHoleProbe.kt
@@ -0,0 +1,55 @@
+package com.redtermapp.util
+
+import java.net.DatagramPacket
+import java.net.DatagramSocket
+import java.net.InetAddress
+
+/**
+ * The one network observation a phone can make about a mosh path: aim a
+ * datagram at a port that is surely closed and watch what the kernel says.
+ *
+ * A host whose firewall admits UDP answers with ICMP "port unreachable", so
+ * [MoshUdpProbe.Signal.PortUnreachable] means the UDP path is open and mosh's
+ * silence has a different cause. A host or carrier that swallows UDP gives no
+ * answer, so [MoshUdpProbe.Signal.NoAnswer] means it is likely blocked.
+ *
+ * Runs on a worker thread: it blocks up to [deadlineMs] waiting for the
+ * kernel's answer, which has no business happening on the main thread.
+ */
+object UdpHoleProbe {
+
+ /** The observed [MoshUdpProbe.Signal] for [host], bounded by [deadlineMs]. */
+ fun probe(host: String, deadlineMs: Long): MoshUdpProbe.Signal =
+ probe(host, MoshUdpProbe.CLOSED_PROBE_PORT, deadlineMs)
+
+ fun probe(host: String, port: Int, deadlineMs: Long): MoshUdpProbe.Signal {
+ val address: InetAddress = try {
+ InetAddress.getByName(host)
+ } catch (_: Exception) {
+ return MoshUdpProbe.Signal.Unknown
+ }
+ val socket = DatagramSocket()
+ try {
+ socket.soTimeout = deadlineMs.toInt().coerceIn(1, 30_000)
+ // One byte is enough: the content is irrelevant, only the
+ // kernel's answer (or its absence) is the signal.
+ socket.send(DatagramPacket(byteArrayOf(0), 1, address, port))
+ val reply = ByteArray(64)
+ val received = try {
+ socket.receive(DatagramPacket(reply, reply.size))
+ } catch (e: java.net.SocketTimeoutException) {
+ null
+ } catch (e: java.net.SocketException) {
+ // The kernel reported the ICMP refusal as an error on the
+ // socket. This is the "UDP reached the host" answer.
+ return MoshUdpProbe.Signal.PortUnreachable
+ }
+ return if (received != null) MoshUdpProbe.Signal.Unknown
+ else MoshUdpProbe.Signal.NoAnswer
+ } catch (_: Exception) {
+ return MoshUdpProbe.Signal.Unknown
+ } finally {
+ socket.close()
+ }
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/util/api/ApiHelper.kt b/app/src/main/java/com/redtermapp/util/api/ApiHelper.kt
index e68b684..8218b63 100644
--- a/app/src/main/java/com/redtermapp/util/api/ApiHelper.kt
+++ b/app/src/main/java/com/redtermapp/util/api/ApiHelper.kt
@@ -770,7 +770,7 @@ object ApiHelper {
mapOf("redterm-startup-local" to STARTUP_LOCAL_SCRIPT)
}
- private const val STARTUP_LOCAL_SCRIPT = """#!/bin/sh
+ private const val STARTUP_LOCAL_HEADER = """#!/bin/sh
# managed by RedTerm (redterm-api bridge v$GUEST_SCRIPT_VERSION); do not edit
# redterm-startup-local — print a safe starter for /root/.startup.local, the
# user-managed hook that runs once per new interactive RedTerm session.
@@ -782,7 +782,14 @@ object ApiHelper {
# line is guarded so it is a no-op wherever run-parts or /etc/update-motd.d
# is absent. Add your own per-session lines in the marked section.
cat <<'STARTER'
-#!/bin/sh
+"""
+
+ /**
+ * The body written to /root/.startup.local. Split from the tool so the
+ * startup-hook GUI and the guest `redterm-startup-local` tool both emit
+ * the exact same starter instead of two drifting copies.
+ */
+ private const val STARTUP_LOCAL_STARTER = """#!/bin/sh
# /root/.startup.local - RedTerm user startup hook.
#
# Runs once per new interactive session, as a separate process, just before
@@ -800,6 +807,11 @@ if command -v run-parts >/dev/null 2>&1 && [ -d /etc/update-motd.d ]; then
fi
# --- your own per-session initialization goes below this line ---
-STARTER
"""
+
+ private val STARTUP_LOCAL_SCRIPT: String =
+ STARTUP_LOCAL_HEADER + STARTUP_LOCAL_STARTER + "STARTER\n"
+
+ /** The safe starter the GUI writes into a new /root/.startup.local. */
+ fun startupStarter(): String = STARTUP_LOCAL_STARTER
}
diff --git a/app/src/main/java/com/redtermapp/util/api/ApiLifecycleApi.kt b/app/src/main/java/com/redtermapp/util/api/ApiLifecycleApi.kt
index 1cb4a9f..50833bd 100644
--- a/app/src/main/java/com/redtermapp/util/api/ApiLifecycleApi.kt
+++ b/app/src/main/java/com/redtermapp/util/api/ApiLifecycleApi.kt
@@ -1,14 +1,15 @@
package com.redtermapp.util.api
import android.content.Context
+import com.redtermapp.util.AppLog
import com.redtermapp.util.api.ApiRequestParser.ApiRequest
/**
- * `termux-api-start` / `termux-api-stop`: bring the bridge's socket
- * listener up or down. The listener is the whole bridge, so "start"
- * reports that it is already running when it is, and "stop" says what
- * will no longer reach it. Both are honest about the listener's actual
- * state rather than pretending.
+ * `termux-api-start` / `termux-api-stop`: enable or disable the bridge.
+ * Stopping never closes the listener — the guest reaches the app only
+ * through this socket, so a stopped bridge stays reachable and answers
+ * every feature request with "stopped" until `start` re-enables it. Both
+ * ops report the bridge's real state rather than pretending.
*/
object ApiLifecycleApi : ApiFeature {
@@ -16,21 +17,30 @@ object ApiLifecycleApi : ApiFeature {
override val permissions = emptySet()
override fun run(context: Context, request: ApiRequest): String {
+ val app = context.applicationContext
val op = request.str("op") ?: "start"
return when (op) {
"start" -> {
- if (ApiSocket.isRunning()) "already running\n" else {
- ApiSocket.start(context)
- if (ApiSocket.isRunning()) "started\n" else "not started (this device's Android is below the bridge's floor)\n"
+ val was = ApiSocket.isEnabled()
+ val up = ApiSocket.start(app)
+ when {
+ !up -> "not started (this device's Android is below the bridge's floor)\n"
+ was -> "already running\n"
+ else -> {
+ AppLog.i(app, "api-socket", "API bridge enabled")
+ "started\n"
+ }
}
}
"stop" -> {
- if (!ApiSocket.isRunning()) "not running\n" else {
+ if (!ApiSocket.isEnabled()) "not running\n"
+ else {
ApiSocket.stop()
+ AppLog.i(app, "api-socket", "API bridge stopped; redterm-api-start re-enables it")
"stopped\n"
}
}
- "status" -> if (ApiSocket.isRunning()) "running\n" else "stopped\n"
+ "status" -> if (ApiSocket.isEnabled()) "running\n" else "stopped\n"
else -> "ERROR: unknown lifecycle op '$op'\n"
}
}
diff --git a/app/src/main/java/com/redtermapp/util/api/ApiSocket.kt b/app/src/main/java/com/redtermapp/util/api/ApiSocket.kt
index 504fa28..af8e643 100644
--- a/app/src/main/java/com/redtermapp/util/api/ApiSocket.kt
+++ b/app/src/main/java/com/redtermapp/util/api/ApiSocket.kt
@@ -41,6 +41,14 @@ object ApiSocket {
*/
private const val MAX_CONCURRENT_REQUESTS = 16
+ /**
+ * Per-request tracing. Off by default: a bridge that works is thousands
+ * of "accepted/answered" lines for a handful of real problems. Flip to
+ * true to bring the connection-level log back; the error and state
+ * lines are never gated by this.
+ */
+ private const val VERBOSE = false
+
private val requestSlots = Semaphore(MAX_CONCURRENT_REQUESTS)
@Volatile
@@ -49,67 +57,80 @@ object ApiSocket {
@Volatile
private var running = false
+ /**
+ * Whether the bridge accepts feature requests. Deliberately separate
+ * from [running]: `api-stop` disables without closing the listener, so
+ * the guest's `redterm-api-start` — which reaches the app through this
+ * very socket — can still reach it and re-enable. Closing the listener
+ * on stop is exactly what made start unreachable after a stop.
+ */
+ @Volatile
+ private var enabled = true
+
/** Whether the listener thread is currently alive. */
fun isRunning(): Boolean = running
+ /** Accepting requests: the listener is up and the bridge not stopped. */
+ fun isEnabled(): Boolean = running && enabled
+
/**
- * Start the bridge. Idempotent; called from the application's create.
- * `api-start` uses it to report a no-op when it is already up, and
- * `api-stop` + this to bring it back after a stop.
+ * Bring the bridge up: bind the listener (once) and accept requests.
+ * Idempotent; called from the application's create and from
+ * `redterm-api-start`, which is exactly the re-enable path — `api-stop`
+ * never closes the listener, so a stopped bridge is still reachable
+ * and this call turns it back on.
+ *
+ * @return whether the bridge accepts requests when this returns.
*/
- fun start(context: Context) {
- if (started && running) return
+ fun start(context: Context): Boolean {
+ if (started && running) {
+ enabled = true
+ return true
+ }
started = true
if (Build.VERSION.SDK_INT < 28) {
// The abstract-namespace LocalServerSocket is API 28+. On
// older devices the bridge never comes up, and the guest
// helper's connect retries say exactly that.
AppLog.w(context, "api-socket", "the termux:API bridge needs Android 9.0 (API 28); it is off on this device")
- return
+ return false
}
val app = context.applicationContext
stopRequested = false
+ enabled = true
// Bind on the calling thread: `api-start` reports the bind result
// right after start() returns, so `running` must be true only once
- // the socket actually holds the name. A failed bind (the previous
- // listener still holding the socket name after a stop) says so
- // instead of clearing the flag a moment later in a finally.
+ // the socket actually holds the name.
val listen = try {
LocalServerSocket(SOCKET_NAME)
} catch (e: Exception) {
AppLog.e(app, "api-socket", "could not bind the API socket: ${e.message}")
- return
+ return false
}
listener = listen
running = true
Thread({
serve(app, listen)
}, "redterm-api-socket").also { it.isDaemon = true; it.start() }
+ return true
}
- /**
- * Stop the listener. The `LocalServerSocket` is closed and the accept
- * loop exits; request threads that are mid-handling finish first.
- * `api-start` brings it back with [start].
- */
+ /** Set true only on the listener teardown path; a user stop never sets it. */
@Volatile
private var stopRequested = false
- /** The bound listener; [stop] closes it so a blocked `accept` returns. */
+ /** The bound listener; held for the process's life. */
@Volatile
private var listener: LocalServerSocket? = null
+ /**
+ * Stop the bridge without closing the listener: the accept loop keeps
+ * running, so the guest's `redterm-api-start` still reaches the app
+ * and can re-enable it. A stopped bridge answers every feature request
+ * with a readable "stopped" instead of a dead connection.
+ */
fun stop() {
- stopRequested = true
- running = false
- // Closing the bound socket is what releases the accept loop; the
- // flag alone leaves it blocked in accept() for the life of the
- // process. The in-flight request threads finish on their own.
- val l = listener
- if (l != null) {
- runCatching { l.close() }
- listener = null
- }
+ enabled = false
}
@RequiresApi(Build.VERSION_CODES.P)
@@ -150,7 +171,7 @@ object ApiSocket {
@RequiresApi(Build.VERSION_CODES.P)
private fun handleConnection(con: LocalSocket, app: Context) {
try {
- AppLog.d(app, "api-socket", "API connection accepted; reading request")
+ if (VERBOSE) AppLog.d(app, "api-socket", "API connection accepted; reading request")
// The bridge only answers the app's own guest: a foreign process
// reaching the abstract socket is refused. The credential read can
// itself throw (LocalSocket.getPeerCredentials declares
@@ -178,7 +199,7 @@ object ApiSocket {
val b0 = input.read()
val b1 = input.read()
if (b0 < 0 || b1 < 0) {
- AppLog.d(app, "api-socket", "API peer closed before a request was read; no answer sent")
+ if (VERBOSE) AppLog.d(app, "api-socket", "API peer closed before a request was read; no answer sent")
return
}
val length = (b1 shl 8) or b0
@@ -193,17 +214,27 @@ object ApiSocket {
while (filled < length) {
val n = input.read(buf, filled, length - filled)
if (n < 0) {
- AppLog.d(app, "api-socket", "API peer closed mid-request at $filled/$length bytes; no answer sent")
+ if (VERBOSE) AppLog.d(app, "api-socket", "API peer closed mid-request at $filled/$length bytes; no answer sent")
return
}
filled += n
}
val result = when (val parsed = ApiRequestParser.parse(String(buf, Charsets.UTF_8))) {
- is ApiRequestParser.Result.Ok -> ApiActions.run(app, parsed.request)
+ is ApiRequestParser.Result.Ok -> {
+ // A stopped bridge still answers the lifecycle action —
+ // it is the only request that can reach the app to
+ // re-enable it. Every other feature gets a readable
+ // refusal, not a dead connection.
+ if (!enabled && parsed.request.extras.strings["action"] != ApiLifecycleApi.name) {
+ "ERROR: the API bridge is stopped; run redterm-api-start to enable it\n"
+ } else {
+ ApiActions.run(app, parsed.request)
+ }
+ }
is ApiRequestParser.Result.Error -> parsed.message
}
writeResponse(con, result, app)
- AppLog.d(app, "api-socket", "API request answered: ${result.length} bytes")
+ if (VERBOSE) AppLog.d(app, "api-socket", "API request answered: ${result.length} bytes")
} catch (e: Exception) {
// An exception here would otherwise leave the guest holding a
// closed pipe with no word: say what happened, to both sides.
diff --git a/app/src/main/java/com/redtermapp/util/api/ui/ApiSafGrantActivity.kt b/app/src/main/java/com/redtermapp/util/api/ui/ApiSafGrantActivity.kt
index f92b3db..d0f3cf7 100644
--- a/app/src/main/java/com/redtermapp/util/api/ui/ApiSafGrantActivity.kt
+++ b/app/src/main/java/com/redtermapp/util/api/ui/ApiSafGrantActivity.kt
@@ -34,9 +34,11 @@ class ApiSafGrantActivity : Activity() {
private fun startPicker() {
pickerStarted = true
- val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
- addCategory(Intent.CATEGORY_OPENABLE)
- }
+ // The tree picker is a bare ACTION_OPEN_DOCUMENT_TREE: the document
+ // UI's tree filter declares the default category, not CATEGORY_OPENABLE
+ // (that one belongs to file-open intents). Attaching OPENABLE made the
+ // intent unresolvable, so the picker failed to start on any device.
+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
runCatching { startActivityForResult(intent, 1) }.onFailure { e ->
ApiUiBridge.postResult(this, "ERROR: the tree picker could not start: ${e.message}\n")
finish()
diff --git a/app/src/main/java/com/redtermapp/util/sftp/DirSearch.kt b/app/src/main/java/com/redtermapp/util/sftp/DirSearch.kt
new file mode 100644
index 0000000..3082b61
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/util/sftp/DirSearch.kt
@@ -0,0 +1,87 @@
+package com.redtermapp.util.sftp
+
+/**
+ * The bounded breadth-first search behind a "search all subfolders" walk.
+ *
+ * Recursive remote search is one round trip per directory, so the walk is
+ * breadth-first (a shallow hit is found before a deep one), stops the moment
+ * [find] has [limit] matches, and is capped at [maxDirs] directories so a
+ * huge or cyclic tree cannot search the server until the hour changes.
+ *
+ * The matching and cutoff rules are pure and unit-tested; only the caller's
+ * [childrenOf] touches a connection.
+ */
+object DirSearch {
+
+ /**
+ * One directory entry. [payload] is the caller's full record (an
+ * [com.redtermapp.ui.filelist.FileEntry] in the app) so the walk can
+ * hand back exactly what it was given, unmodified.
+ */
+ data class Entry(
+ val name: String,
+ val isDirectory: Boolean,
+ val isSymlink: Boolean,
+ val remotePath: String,
+ val payload: T
+ )
+
+ data class Result(
+ val matches: List>,
+ /** True when the walk stopped before it was complete. */
+ val truncated: Boolean,
+ val dirsListed: Int,
+ val unreadableDirs: Int
+ )
+
+ /**
+ * Breadth-first from [root]. Directory symlinks are listed but never
+ * descended into, which is what keeps a cycle from searching forever.
+ *
+ * @return the file matches (names containing [query], case-insensitive)
+ * and whether the walk was cut short by [limit], [maxDirs], or an
+ * unreadable directory.
+ */
+ fun find(
+ root: String,
+ childrenOf: (remoteDir: String) -> List>?,
+ query: String,
+ limit: Int,
+ maxDirs: Int
+ ): Result {
+ val matches = ArrayList>()
+ var dirsListed = 0
+ var unreadable = 0
+ val queue = ArrayDeque()
+ queue.add(root)
+ dirsListed++
+ while (queue.isNotEmpty() && matches.size < limit) {
+ val dir = queue.removeFirst()
+ val children = childrenOf(dir)
+ if (children == null) {
+ unreadable++
+ continue
+ }
+ for (c in children) {
+ if (matches.size >= limit) break
+ if (c.name.isEmpty() || c.name == "." || c.name == "..") continue
+ when {
+ c.isDirectory && !c.isSymlink -> {
+ if (dirsListed < maxDirs) {
+ queue.add(c.remotePath)
+ dirsListed++
+ }
+ }
+ !c.isDirectory -> {
+ if (c.name.contains(query, ignoreCase = true)) matches.add(c)
+ }
+ }
+ }
+ }
+ // Complete only when the queue ran dry with nothing left that would
+ // have been cut off by a cap or an unreadable directory.
+ val truncated = queue.isNotEmpty() || matches.size >= limit ||
+ dirsListed >= maxDirs || unreadable > 0
+ return Result(matches, truncated, dirsListed, unreadable)
+ }
+}
diff --git a/app/src/main/java/com/redtermapp/util/sftp/DirWalk.kt b/app/src/main/java/com/redtermapp/util/sftp/DirWalk.kt
new file mode 100644
index 0000000..3165fde
--- /dev/null
+++ b/app/src/main/java/com/redtermapp/util/sftp/DirWalk.kt
@@ -0,0 +1,143 @@
+package com.redtermapp.util.sftp
+
+import java.io.File
+
+/**
+ * The plan for a recursive folder download, separated from the connection
+ * so the walking rules are unit-testable.
+ *
+ * Walking a remote tree is one round trip per directory, so the planner is
+ * breadth-first: siblings are enumerated before descendants, which means
+ * [Result.directories] come out shallowest first (a parent must exist before
+ * its child is created locally) and a deep tree cannot eat the caps before
+ * the shallow files are collected. The caps themselves keep a symlink cycle
+ * or a pathologically deep server from walking until the hour changes.
+ *
+ * [childrenOf] is the only I/O in the picture and it is injected: the real
+ * one is a [SftpClient.list] behind a connection, and the tests drive it with
+ * a scripted map, the way the SFTP protocol tests drive a fake server.
+ */
+object DirWalk {
+
+ /** One directory's child. [isSymlink] matters: links are never followed. */
+ data class Child(
+ val name: String,
+ val isDirectory: Boolean,
+ val size: Long,
+ val isSymlink: Boolean
+ )
+
+ /** A file to download. [relativePath] mirrors it under the local root. */
+ data class RemoteFile(val remotePath: String, val relativePath: String, val size: Long)
+
+ data class Result(
+ val files: List,
+ /** Local directories to create, shallowest first. */
+ val directories: List,
+ /** Directories that could not be listed; their subtrees are missing. */
+ val unreadableDirs: List,
+ /** Symlinked directories, which are neither followed nor downloadable. */
+ val skippedSymlinks: List,
+ /** True when [maxFiles] or [maxDepth] cut the walk short. */
+ val truncated: Boolean
+ )
+
+ const val DEFAULT_MAX_FILES = 10_000
+ const val DEFAULT_MAX_DEPTH = 64
+
+ fun plan(
+ root: String,
+ childrenOf: (remoteDir: String) -> List?,
+ maxFiles: Int = DEFAULT_MAX_FILES,
+ maxDepth: Int = DEFAULT_MAX_DEPTH
+ ): Result {
+ val files = ArrayList()
+ val directories = ArrayList()
+ val unreadable = ArrayList()
+ val skippedSymlinks = ArrayList()
+ var truncated = false
+
+ data class Pending(val remote: String, val relative: String, val depth: Int)
+ val queue = ArrayDeque()
+ queue.add(Pending(root, "", 0))
+
+ outer@ while (queue.isNotEmpty()) {
+ val pending = queue.removeFirst()
+ val children = childrenOf(pending.remote)
+ if (children == null) {
+ // A directory that cannot be listed is reported, not fatal:
+ // the rest of the tree still downloads.
+ unreadable.add(pending.remote)
+ continue
+ }
+ for (child in children) {
+ // Names are untrusted input: a child that is not a bare name
+ // would let the walk leave the tree entirely.
+ if (child.name.isEmpty() || child.name == "." || child.name == ".." ||
+ child.name.contains('/')
+ ) continue
+ val relative =
+ if (pending.relative.isEmpty()) child.name else "${pending.relative}/${child.name}"
+ when {
+ child.isSymlink && child.isDirectory -> {
+ // Following a link is how a cycle walks the server
+ // forever; downloading it would read the target as a
+ // file. Neither is what a mirror wants, so it is named
+ // and skipped.
+ skippedSymlinks.add(joinPath(pending.remote, child.name))
+ }
+ child.isDirectory -> {
+ directories.add(relative)
+ if (pending.depth + 1 < maxDepth) {
+ queue.add(
+ Pending(
+ joinPath(pending.remote, child.name),
+ relative,
+ pending.depth + 1
+ )
+ )
+ } else {
+ truncated = true
+ }
+ }
+ else -> {
+ if (files.size >= maxFiles) {
+ truncated = true
+ break@outer
+ }
+ files.add(
+ RemoteFile(
+ remotePath = joinPath(pending.remote, child.name),
+ relativePath = relative,
+ size = child.size
+ )
+ )
+ }
+ }
+ }
+ }
+ return Result(files, directories, unreadable, skippedSymlinks, truncated)
+ }
+
+ /**
+ * The local file for [relativePath] under [localRoot].
+ *
+ * Remote names are untrusted, so the result is refused when it would
+ * escape the root: a crafted `..` segment must not turn a folder
+ * download into a write anywhere on the device.
+ */
+ fun mirrorPath(localRoot: File, relativePath: String): File? {
+ if (relativePath.isBlank()) return null
+ val target = File(localRoot, relativePath)
+ val root = localRoot.absoluteFile.normalize()
+ val resolved = target.absoluteFile.normalize()
+ val rootPath = root.absolutePath
+ val inside =
+ resolved.absolutePath == rootPath || resolved.absolutePath.startsWith("$rootPath/")
+ return if (inside) target else null
+ }
+
+ /** [SftpClient.join] without the companion, so the planner stays pure. */
+ fun joinPath(dir: String, name: String): String =
+ if (dir.endsWith("/")) "$dir$name" else "$dir/$name"
+}
diff --git a/app/src/main/java/com/redtermapp/util/sftp/SftpClient.kt b/app/src/main/java/com/redtermapp/util/sftp/SftpClient.kt
index b6341c9..00ccccd 100644
--- a/app/src/main/java/com/redtermapp/util/sftp/SftpClient.kt
+++ b/app/src/main/java/com/redtermapp/util/sftp/SftpClient.kt
@@ -128,21 +128,30 @@ class SftpClient internal constructor(
* @param onProgress receives bytes done and total, where total is -1 when the
* server did not report a size.
*/
- fun download(remotePath: String, destination: File, onProgress: (Long, Long) -> Unit) {
+ fun download(
+ remotePath: String,
+ destination: File,
+ startOffset: Long = 0L,
+ onProgress: (Long, Long) -> Unit
+ ) {
val total = stat(remotePath)?.size ?: -1L
val handle = session.open(normalise(remotePath), write = false)
destination.parentFile?.mkdirs()
try {
- destination.outputStream().use { out ->
- var offset = 0L
+ // Resume opens the local file in append mode so the partial file is
+ // kept and continued, not truncated; a fresh download overwrites.
+ val out = if (startOffset > 0L) java.io.FileOutputStream(destination, true)
+ else destination.outputStream()
+ out.use { stream ->
+ var offset = startOffset
while (true) {
val chunk = session.read(handle, offset, Sftp.MAX_CHUNK) ?: break
if (chunk.isEmpty()) break
- out.write(chunk)
+ stream.write(chunk)
offset += chunk.size
onProgress(offset, total)
}
- out.flush()
+ stream.flush()
}
} finally {
runCatching { session.close(handle) }
@@ -155,17 +164,33 @@ class SftpClient internal constructor(
* @param onProgress receives bytes done and the file's own size, which is
* known even though the server has nothing to report yet.
*/
- fun upload(source: File, remotePath: String, onProgress: (Long, Long) -> Unit) {
+ fun upload(
+ source: File,
+ remotePath: String,
+ startOffset: Long = 0L,
+ onProgress: (Long, Long) -> Unit
+ ) {
val total = source.length()
+ // A resume leaves the remote's existing bytes in place (no truncate) and
+ // skips the source's bytes that are already there before continuing.
val handle = session.open(
normalise(remotePath),
write = true,
create = true,
- truncate = true
+ truncate = startOffset == 0L
)
try {
source.inputStream().use { input ->
- var offset = 0L
+ var skipped = 0L
+ if (startOffset > 0L) {
+ val skipBuffer = ByteArray(8192)
+ while (skipped < startOffset) {
+ val r = input.read(skipBuffer)
+ if (r <= 0) break
+ skipped += r
+ }
+ }
+ var offset = startOffset
val buffer = ByteArray(Sftp.MAX_CHUNK)
while (true) {
val read = input.read(buffer)
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 3b7be5e..078aa67 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -125,6 +125,38 @@
android:textSize="18sp" />
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/menu/file_browser_menu.xml b/app/src/main/res/menu/file_browser_menu.xml
index c8ee48d..aad2116 100644
--- a/app/src/main/res/menu/file_browser_menu.xml
+++ b/app/src/main/res/menu/file_browser_menu.xml
@@ -12,6 +12,11 @@
android:title="@string/search_files"
app:showAsAction="never" />
+
+
- Folder
%1$s · %2$s
Search all subfolders of %1$s
+ Type a name to search for
Show hidden files
Hide hidden files
Go to /root
@@ -175,6 +176,7 @@
Clear log
Package manager: %1$s
Could not detect a package manager for %1$s. Run the update command from the terminal instead.
+ %1$s ships its tools in an immutable Nix store and carries the nix tools themselves: in a session, install packages over the network with `nix profile install nixpkgs#nodejs` or `nix shell nixpkgs#git`. The nixpkgs channel ships registered (nixpkgs-unstable), but its classic update (nix-channel, nix-env) cannot finish under proot, so the registry commands above are the supported path. The base tools move with a newer image, not an in-place update.
Updating %1$s
Started — this can take a while
Packages updated
@@ -214,9 +216,35 @@
Recording saved to Recordings
Recordings cannot be written to. Storage is unavailable on this device.
No recordings yet
+ No recordings match “%1$s”
+ Search recordings
Play
Share
+ Export GIF
+ Exporting %1$s to GIF…
+ GIF export failed
+ Install from file
+ Installs a distro tarball you provide, instead of downloading one. The compression is read from the file itself, so .tar.xz, .tar.gz and plain .tar all work.
+ Choose a tarball…
+ No file chosen
+ Chosen: %1$s
+ Source
+ File on this device
+ Download from a URL
+ Docker / OCI image
+ https://example.com/distros/myarch.tar.xz
+ e.g. docker.io/ubuntu:22.04
+ Install a distro from a file, a URL, or a Docker image
+ Distro name
+ e.g. arch
+ Install
+ Give the distro a name first
+ Provide a source — a file, a URL, or an image reference
+ Starting…
+ Installed %1$s
+ Install failed
Replaying recording
+ %1$s×
Base image update
Check for update
A newer base image is available: %1$s
@@ -409,7 +437,25 @@
Transfer finished
Could not write to the chosen location.
Could not read the file that was selected.
- Downloading a whole folder is not supported here. Open it and download the files inside it.
+ Downloading %1$s
+ Folder downloaded
+
+ - %1$d file, %2$s — saved to %3$s
+ - %1$d files, %2$s — saved to %3$s
+
+
+ - %1$d file could not be read.
+ - %1$d files could not be read.
+
+
+ - %1$d folder could not be listed.
+ - %1$d folders could not be listed.
+
+
+ - %1$d failed run in a row
+ - %1$d failed runs in a row
+
+ The walk stopped early: the tree is too large or too deep for one pass.
That did not work
%1$s — %2$s
@@ -499,6 +545,17 @@
- %1$d match for \'%2$s\'
- %1$d matches for \'%2$s\'
+ Search recursively
+ Searching under %1$s for \"%2$s\"…
+ No matches for \'%1$s\' under %2$s
+
+ - %1$d match for \'%2$s\' under %3$s
+ - %1$d matches for \'%2$s\' under %3$s
+
+
+ - First %1$d match for \'%2$s\' under %3$s — the search stopped early
+ - First %1$d matches for \'%2$s\' under %3$s — the search stopped early
+
No distributions installed.\nTap + to install one.
Files
Launch ›
@@ -556,4 +613,142 @@
not granted
used by %1$s
Notifications
+
+
+ Workspaces
+ New workspace
+ e.g. Daily
+ No workspaces yet. A workspace bundles the distro shells, SSH servers, theme and snippets you reach for, so a whole setup opens in one tap.
+
+ - %1$d session
+ - %1$d sessions
+
+ Launch
+ Edit
+ Delete
+ Distro shells
+ SSH servers
+ Theme
+ App default
+ Run /root/.startup.local hook
+ Open in split view
+ Pin to home screen
+ Pinned workspaces
+ Save
+ none installed
+ no servers saved
+
+
+ Startup hook
+ Distribution
+ not present
+ Write safe starter
+ Edit
+ Delete
+ Refresh
+ carries the RedTerm marker; it can be replaced
+ user-written; RedTerm will not overwrite it
+ Safe starter written to /root/.startup.local.
+ A user-written hook is in place, so it was not overwritten. Delete it, or edit it by hand.
+ Hook removed; interactive sessions now skip it.
+ (no hook file yet — write the safe starter to create one)
+
+
+ Snippets
+ Search snippets
+ New snippet
+ Name
+ Content
+ Folder (optional)
+ Run
+ Copy
+ Edit
+ Delete
+ No snippets yet. Add one with New snippet.
+ Copied to clipboard
+
+
+ Distributions
+ No distros installed yet.
+ Size
+ Last update
+ never
+ Update now
+ Disk
+ %1$s free on device
+ %1$d CPU · %2$s RAM (%3$s free)
+ %1$d CPU
+ Custom…
+
+
+ SSH Tunnels
+ No servers with local forwards
+ running
+ stopped
+ Start
+ Stop
+
+
+ Transfer Queue
+ List remote files
+ Remote directory
+ Pick local files to upload
+ Run
+ Listing…
+ Tick files to download, or pick local files to upload.
+ Nothing selected
+ Transferring…
+ Finished %1$d · failed %2$d · skipped %3$d
+
+
+ Scheduled Jobs
+ No jobs scheduled
+ Add job
+ %1$d min
+ one-shot
+ next: %1$s
+ never ran
+ last run %1$s, exit %2$d
+ History
+ No runs recorded yet
+ Enable
+ Pause
+ Name
+ Command to run in the distro
+ Every (minutes, 0 = one-shot)
+ Distro
+ Save
+
+
+ Port forward
+ Device port
+ Port
+ Stop
+ Could not bind port %1$d
+ Target
+ This device (guest)
+ Host (e.g. 127.0.0.1)
+ Active forwards
+ No forwards open
+ Add
+ Save preset
+ Preset saved
+ Presets are saved per SSH server — pick a server first
+ Reach this port from a laptop
+ Over USB: adb reverse tcp:PORT tcp:PORT (PORT is the device port)
+ Over Wi-Fi: use the phone\'s address:PORT, when the network allows it
+
+
+ ⬇ %1$s · %2$s
+ ⬆ %1$s
+ %1$s@%2$s:%3$d
+ %1$s · %2$s
+
+
+ More tools
+ Bundled shells, servers, theme and snippets that open in one tap.
+ Edit the guest startup hook written into a distro.
+ Save commands and paste them into any session.
+ Per-distro version, size, updates and disk.
+ Run guest commands on a schedule.
diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml
index 619f5b2..82f21a4 100644
--- a/app/src/main/res/values/themes.xml
+++ b/app/src/main/res/values/themes.xml
@@ -13,6 +13,9 @@
- @color/terminal_text
- @color/extra_keys_bg
- @color/extra_keys_text
+ - ?attr/extraKeysText
+ - ?attr/extraKeysText
+ - ?attr/extraKeysText
@@ -29,6 +32,9 @@
- @color/amoled_text
- @color/amoled_extra_keys_bg
- @color/amoled_extra_keys_text
+ - ?attr/extraKeysText
+ - ?attr/extraKeysText
+ - ?attr/extraKeysText