Skip to content

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

feat: AVF backend selection and a configurable X11 viewer

ExTvfa45cdb6f2af
diff --git a/README.md b/README.md
index 01762f1..68e09bf 100644
--- a/README.md
+++ b/README.md
@@ -77,11 +77,13 @@ Default login: **root / podroid**.
- **Linux 7.0.5 kernel**, custom-built. Every container option compiled `=y`; the build fails if any get demoted.
- **Podman, Docker and LXC pre-installed.** Rootless Podman wired up with crun + netavark + slirp4netns; `rc-service docker start` or `lxc-create …` work out of the box.
- **OpenRC as PID 1.** `apk add` whatever you want, `rc-service ... start`, and it persists across reboots.
-- **In-app X11 viewer** (Xvnc + PulseAudio) with touch→mouse, soft-keyboard input, and PCM audio over loopback.
+- **In-app X11 viewer** (Xvnc + PulseAudio): live-resizable display (match-device, or 720p–1440p / custom presets), direct-touch and trackpad pointer modes with scroll, fullscreen, rotation lock, external-keyboard and mouse-wheel support, soft-keyboard input, and PCM audio over loopback.
- **Built-in terminal** powered by the Termux engine: xterm-256color, mouse tracking, debounced resize, customizable extra-keys row.
- **Persistent ext4 overlay** on a read-only Alpine squashfs. Installs and configs survive every reboot.
- **Adaptive Material 3 UI** for phone, tablet and landscape, with dynamic color and a foreground service that keeps the VM alive.
+> **Known limitation (X11 viewer):** with an external mouse, right-click currently exits fullscreen instead of reaching the desktop — Android maps a mouse right-click to the Back action. Two-finger right-click via touch works. A fix is planned.
+
## Themes & fonts
Open the terminal's **Quick Settings** (top sheet) for both pickers.
diff --git a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
index 92eeb40..e10646d 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
@@ -48,7 +48,20 @@ class SettingsRepository @Inject constructor(
val KEY_DYNAMIC_COLOR_ENABLED = booleanPreferencesKey("dynamic_color_enabled")
val KEY_LAST_BOOT_DURATION_MS = longPreferencesKey("last_boot_duration_ms")
val KEY_ENGINE_SELECTION = stringPreferencesKey("engine_selection")
- val KEY_AVF_HINT_DISMISSED = booleanPreferencesKey("avf_hint_dismissed")
+ val KEY_AVF_HINT_DISMISSED = booleanPreferencesKey("avf_hint_dismissed")
+ val KEY_AVF_VERBOSE_LOGGING = booleanPreferencesKey("avf_verbose_logging")
+
+ val KEY_X11_RES_MODE = stringPreferencesKey("x11_resolution_mode")
+ val KEY_X11_RES_PRESET = stringPreferencesKey("x11_resolution_preset")
+ val KEY_X11_CUSTOM_W = intPreferencesKey("x11_custom_w")
+ val KEY_X11_CUSTOM_H = intPreferencesKey("x11_custom_h")
+ val KEY_X11_TOUCH_MODE = stringPreferencesKey("x11_touch_mode")
+ val KEY_X11_TP_SENSITIVITY = stringPreferencesKey("x11_tp_sensitivity") // float as string, DataStore has no float key helper used here
+ val KEY_X11_TP_ACCEL = booleanPreferencesKey("x11_tp_accel")
+ val KEY_X11_FULLSCREEN = booleanPreferencesKey("x11_fullscreen_default")
+ val KEY_X11_ROTATION = stringPreferencesKey("x11_rotation_lock")
+ val KEY_X11_SHOW_EXTRA_KEYS = booleanPreferencesKey("x11_show_extra_keys")
+ val KEY_X11_DPI = intPreferencesKey("x11_dpi")
/**
* Default tunable QEMU args — CPU model, accel tuning, RNG source, overcommit.
@@ -107,6 +120,9 @@ class SettingsRepository @Inject constructor(
val dynamicColorEnabled = pref(KEY_DYNAMIC_COLOR_ENABLED, false)
val lastBootDurationMs = pref(KEY_LAST_BOOT_DURATION_MS, 0L)
val avfHintDismissed = pref(KEY_AVF_HINT_DISMISSED, false)
+ val avfVerboseLogging: Flow<Boolean> = context.dataStore.data.map { prefs ->
+ prefs[KEY_AVF_VERBOSE_LOGGING] ?: false
+ }
val engineSelection: Flow<EngineSelection> = context.dataStore.data.map { prefs ->
runCatching { EngineSelection.valueOf(prefs[KEY_ENGINE_SELECTION] ?: "AUTO") }
.getOrDefault(EngineSelection.AUTO)
@@ -130,6 +146,35 @@ class SettingsRepository @Inject constructor(
suspend fun setLastBootDurationMs(value: Long) = set(KEY_LAST_BOOT_DURATION_MS, value)
suspend fun setEngineSelection(value: EngineSelection) = set(KEY_ENGINE_SELECTION, value.name)
suspend fun setAvfHintDismissed(value: Boolean) = set(KEY_AVF_HINT_DISMISSED, value)
+ suspend fun setAvfVerboseLogging(value: Boolean) = set(KEY_AVF_VERBOSE_LOGGING, value)
+
+ val x11Settings: kotlinx.coroutines.flow.Flow<com.excp.podroid.x11.X11Settings> = context.dataStore.data.map { p ->
+ com.excp.podroid.x11.X11Settings(
+ resolutionMode = runCatching { com.excp.podroid.x11.ResolutionMode.valueOf(p[KEY_X11_RES_MODE] ?: "MATCH") }.getOrDefault(com.excp.podroid.x11.ResolutionMode.MATCH),
+ preset = runCatching { com.excp.podroid.x11.ResolutionPreset.valueOf(p[KEY_X11_RES_PRESET] ?: "R1080P") }.getOrDefault(com.excp.podroid.x11.ResolutionPreset.R1080P),
+ customW = p[KEY_X11_CUSTOM_W] ?: 1280,
+ customH = p[KEY_X11_CUSTOM_H] ?: 720,
+ touchMode = runCatching { com.excp.podroid.x11.TouchMode.valueOf(p[KEY_X11_TOUCH_MODE] ?: "DIRECT") }.getOrDefault(com.excp.podroid.x11.TouchMode.DIRECT),
+ trackpadSensitivity = (p[KEY_X11_TP_SENSITIVITY]?.toFloatOrNull() ?: 1.5f),
+ trackpadAccel = p[KEY_X11_TP_ACCEL] ?: true,
+ fullscreenDefault = p[KEY_X11_FULLSCREEN] ?: false,
+ rotationLock = runCatching { com.excp.podroid.x11.RotationLock.valueOf(p[KEY_X11_ROTATION] ?: "AUTO") }.getOrDefault(com.excp.podroid.x11.RotationLock.AUTO),
+ showExtraKeys = p[KEY_X11_SHOW_EXTRA_KEYS] ?: true,
+ dpi = p[KEY_X11_DPI] ?: 96,
+ )
+ }
+
+ suspend fun setX11ResolutionMode(v: String) = set(KEY_X11_RES_MODE, v)
+ suspend fun setX11Preset(v: String) = set(KEY_X11_RES_PRESET, v)
+ suspend fun setX11Custom(w: Int, h: Int) { set(KEY_X11_CUSTOM_W, w); set(KEY_X11_CUSTOM_H, h) }
+ suspend fun setX11TouchMode(v: String) = set(KEY_X11_TOUCH_MODE, v)
+ suspend fun setX11TrackpadSensitivity(v: Float) = set(KEY_X11_TP_SENSITIVITY, v.toString())
+ suspend fun setX11TrackpadAccel(v: Boolean) = set(KEY_X11_TP_ACCEL, v)
+ suspend fun setX11Fullscreen(v: Boolean) = set(KEY_X11_FULLSCREEN, v)
+ suspend fun setX11Rotation(v: String) = set(KEY_X11_ROTATION, v)
+ suspend fun setX11ShowExtraKeys(v: Boolean) = set(KEY_X11_SHOW_EXTRA_KEYS, v)
+ suspend fun setX11Dpi(v: Int) = set(KEY_X11_DPI, v)
+ suspend fun getX11DpiSnapshot() = (x11Settings.first()).dpi
// Snapshots used by non-Compose call sites (PodroidService, exporters).
suspend fun getSshEnabledSnapshot() = sshEnabled.first()
@@ -143,4 +188,5 @@ class SettingsRepository @Inject constructor(
suspend fun getQemuExtraArgsSnapshot() = qemuExtraArgs.first()
suspend fun getKernelExtraCmdlineSnapshot() = kernelExtraCmdline.first()
suspend fun getEngineSelectionSnapshot() = engineSelection.first()
+ suspend fun getAvfVerboseLoggingSnapshot() = avfVerboseLogging.first()
}
diff --git a/app/src/main/java/com/excp/podroid/engine/EngineHolder.kt b/app/src/main/java/com/excp/podroid/engine/EngineHolder.kt
index f91e773..2a5e6e0 100644
--- a/app/src/main/java/com/excp/podroid/engine/EngineHolder.kt
+++ b/app/src/main/java/com/excp/podroid/engine/EngineHolder.kt
@@ -18,6 +18,7 @@ import android.content.Context
import com.excp.podroid.data.repository.PortForwardRepository
import com.excp.podroid.data.repository.PortForwardRule
import com.excp.podroid.data.repository.SettingsRepository
+import com.excp.podroid.engine.avf.AvfCapabilities
import com.excp.podroid.engine.avf.AvfDiagnostics
import com.excp.podroid.engine.avf.AvfEngine
import com.termux.terminal.TerminalSession
@@ -100,19 +101,31 @@ class EngineHolder @Inject constructor(
private fun pick(sel: EngineSelection): VmEngine {
val probe = AvfDiagnostics.probe(context)
+ val avfUsable = probe.featureSupported &&
+ probe.managePermissionGranted &&
+ probe.customPermissionGranted &&
+ AvfCapabilities.choose(probe.capabilitiesRaw) !is
+ AvfCapabilities.ProtectedVmChoice.Unsupported
return when {
sel == EngineSelection.QEMU -> qemuProvider.get()
- // AVF forced: no capability check; if unsupported, AvfEngine surfaces the error.
- sel == EngineSelection.AVF -> avfProvider.get()
- probe.featureSupported &&
- probe.managePermissionGranted &&
- probe.customPermissionGranted -> avfProvider.get()
+ sel == EngineSelection.AVF && AvfCapabilities.choose(probe.capabilitiesRaw) is
+ AvfCapabilities.ProtectedVmChoice.Unsupported -> {
+ android.util.Log.w(
+ TAG,
+ "AVF forced but device is protected-only; falling back to QEMU. " +
+ "caps=${probe.capabilitiesRaw}(${probe.capabilitiesDecoded})"
+ )
+ qemuProvider.get()
+ }
+ sel == EngineSelection.AVF -> avfProvider.get()
+ avfUsable -> avfProvider.get()
else -> qemuProvider.get()
}.also {
android.util.Log.i(
TAG,
"pick: selection=$sel feature=${probe.featureSupported} " +
- "perms=${probe.managePermissionGranted}/${probe.customPermissionGranted} → ${it.backendId}"
+ "perms=${probe.managePermissionGranted}/${probe.customPermissionGranted} " +
+ "caps=${probe.capabilitiesRaw}(${probe.capabilitiesDecoded}) → ${it.backendId}"
)
}
}
diff --git a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
index 0441ff4..249a73f 100644
--- a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
@@ -502,6 +502,7 @@ class QemuEngine @Inject constructor(
if (userKernelExtras.isNotEmpty()) append(" ").append(userKernelExtras)
append(" androidip=").append(config.androidIp)
if (config.sshEnabled) append(" ssh=1")
+ append(" podroid.x11.dpi=").append(config.x11Dpi)
}
args += "-append"; args += cmdline
} else {
diff --git a/app/src/main/java/com/excp/podroid/engine/VmEngine.kt b/app/src/main/java/com/excp/podroid/engine/VmEngine.kt
index 189115d..9ffb002 100644
--- a/app/src/main/java/com/excp/podroid/engine/VmEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/VmEngine.kt
@@ -67,4 +67,6 @@ data class VmConfig(
val storageAccessEnabled: Boolean = false,
val qemuExtraArgs: String = "",
val kernelExtraCmdline: String = "",
+ val verboseLogging: Boolean = false,
+ val x11Dpi: Int = 96,
)
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfCapabilities.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfCapabilities.kt
new file mode 100644
index 0000000..c524736
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfCapabilities.kt
@@ -0,0 +1,44 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Pure decode of VirtualMachineManager.getCapabilities() bitmask + the
+ * protected-VM selection policy. Podroid runs a raw custom kernel/initrd
+ * image, which AVF can only boot as a NON-protected VM (protected VMs need a
+ * pvmfw-signed payload). So: prefer non-protected; if the device only supports
+ * protected VMs we cannot run here and the caller must fall back to QEMU.
+ * Pure (no Android deps) so it unit-tests on the JVM.
+ */
+package com.excp.podroid.engine.avf
+
+object AvfCapabilities {
+ const val CAPABILITY_PROTECTED_VM = 1
+ const val CAPABILITY_NON_PROTECTED_VM = 2
+
+ sealed interface ProtectedVmChoice {
+ /** Apply setProtectedVm(false) and proceed - the common path. */
+ data object NonProtected : ProtectedVmChoice
+ /** getCapabilities() was unavailable; try non-protected and let any throw surface. */
+ data object Unknown : ProtectedVmChoice
+ /** Device can't run our custom image; caller must fall back to QEMU. */
+ data class Unsupported(val reason: String) : ProtectedVmChoice
+ }
+
+ fun decode(capabilities: Int): String {
+ if (capabilities == 0) return "none/unknown"
+ val parts = mutableListOf<String>()
+ if (capabilities and CAPABILITY_PROTECTED_VM != 0) parts += "PROTECTED"
+ if (capabilities and CAPABILITY_NON_PROTECTED_VM != 0) parts += "NON_PROTECTED"
+ return if (parts.isEmpty()) "0x${capabilities.toString(16)}" else parts.joinToString("+")
+ }
+
+ fun choose(capabilities: Int): ProtectedVmChoice = when {
+ capabilities == 0 -> ProtectedVmChoice.Unknown
+ capabilities and CAPABILITY_NON_PROTECTED_VM != 0 -> ProtectedVmChoice.NonProtected
+ capabilities and CAPABILITY_PROTECTED_VM != 0 -> ProtectedVmChoice.Unsupported(
+ "This device's hypervisor only supports protected VMs; AVF can't run " +
+ "Podroid's custom Linux image here. Falling back to QEMU."
+ )
+ else -> ProtectedVmChoice.Unknown
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfDiagnostics.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfDiagnostics.kt
index 95701e1..efdd73d 100644
--- a/app/src/main/java/com/excp/podroid/engine/avf/AvfDiagnostics.kt
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfDiagnostics.kt
@@ -31,6 +31,8 @@ data class AvfReport(
val managerClassPresent: Boolean,
val serviceReachable: Boolean,
val smokeTestResult: String?,
+ val capabilitiesRaw: Int = 0,
+ val capabilitiesDecoded: String = "n/a",
val activeBackend: String = "?",
) {
fun pretty(): String = buildString {
@@ -54,6 +56,9 @@ data class AvfReport(
appendLine()
appendLine("Service")
appendLine(" reachable via system service = $serviceReachable")
+ appendLine()
+ appendLine("Hypervisor capabilities")
+ appendLine(" raw = $capabilitiesRaw ($capabilitiesDecoded)")
if (smokeTestResult != null) {
appendLine()
appendLine("Smoke test")
@@ -113,6 +118,10 @@ object AvfDiagnostics {
val serviceReachable = managerClassPresent && managePermissionGranted &&
runCatching { getVirtualizationManager(context) != null }.getOrDefault(false)
+ val capabilitiesRaw = if (serviceReachable) {
+ runCatching { AvfReflect.getCapabilities(AvfReflect.manager(context)) }.getOrDefault(0)
+ } else 0
+
return AvfReport(
featureSupported = featureSupported,
managePermissionGranted = managePermissionGranted,
@@ -121,6 +130,8 @@ object AvfDiagnostics {
managerClassPresent = managerClassPresent,
serviceReachable = serviceReachable,
smokeTestResult = null,
+ capabilitiesRaw = capabilitiesRaw,
+ capabilitiesDecoded = AvfCapabilities.decode(capabilitiesRaw),
)
}
@@ -150,7 +161,7 @@ object AvfDiagnostics {
?: return "FAILED: VirtualMachineManager system service returned null"
val customCfg = buildCustomImageConfig(kernel.absolutePath, initrd.absolutePath)
- val config = buildVirtualMachineConfig(context, customCfg)
+ val config = buildVirtualMachineConfig(vmm, context, customCfg)
val name = "podroid-avf-smoke"
val vm = invokeOrCreate(vmm, name, config)
@@ -200,15 +211,16 @@ object AvfDiagnostics {
return buildM.invoke(builder)
}
- private fun buildVirtualMachineConfig(context: Context, customCfg: Any): Any {
+ private fun buildVirtualMachineConfig(vmm: Any, context: Context, customCfg: Any): Any {
val builderCls = Class.forName("$CLS_CONFIG\$Builder")
val ctor = builderCls.getDeclaredConstructor(Context::class.java).apply { isAccessible = true }
val builder = ctor.newInstance(context)
val customCfgCls = Class.forName(CLS_CUSTOM_CFG)
invokeSetter(builderCls, builder, "setCustomImageConfig", customCfgCls, customCfg)
- runCatching {
- invokeSetter(builderCls, builder, "setProtectedVm",
- Boolean::class.javaPrimitiveType!!, false)
+ when (val choice = AvfReflect.applyProtectedVm(vmm, builder)) {
+ is AvfCapabilities.ProtectedVmChoice.Unsupported ->
+ throw UnsupportedOperationException(choice.reason)
+ else -> Unit // NonProtected/Unknown: setter already applied (or threw, which surfaces)
}
runCatching {
invokeSetter(builderCls, builder, "setMemoryBytes",
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
index cc654cb..a5d07a0 100644
--- a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
@@ -176,7 +176,7 @@ class AvfEngine @Inject constructor(
try {
val mgr = AvfReflect.manager(context)
- val vmConfigObj = buildConfig(config)
+ val vmConfigObj = buildConfig(mgr, config)
// AOSP canonical pattern: get-or-create, then attempt to update the
// config on the existing VM. If AVF rejects the new config as
@@ -197,20 +197,23 @@ class AvfEngine @Inject constructor(
val cb = AvfReflect.newVmCallback(
onError = { code, msg ->
- Log.e(TAG, "VM onError code=$code msg=$msg")
- _state.value = VmState.Error("AVF onError($code): ${msg ?: "no message"}")
+ Log.e(TAG, "VM onError ${AvfReasonCodes.errorCode(code)} msg=$msg")
+ _state.value = VmState.Error(
+ "AVF onError(${AvfReasonCodes.errorCode(code)}): ${msg ?: "no message"}"
+ )
},
onStopped = { reason ->
- Log.i(TAG, "VM onStopped reason=$reason")
+ Log.i(TAG, "VM onStopped ${AvfReasonCodes.stopReason(reason)}")
if (_state.value is VmState.Running) {
_state.value = VmState.Stopped
} else if (_state.value is VmState.Starting) {
- // Stopped during boot — surface as error so the UI shows it.
- _state.value = VmState.Error("VM exited during boot (reason=$reason)")
+ _state.value = VmState.Error(
+ "VM exited during boot (${AvfReasonCodes.stopReason(reason)})"
+ )
}
},
onDied = { reason ->
- Log.w(TAG, "VM onDied reason=$reason")
+ Log.w(TAG, "VM onDied ${AvfReasonCodes.stopReason(reason)}")
},
)
AvfReflect.setCallback(vm, java.util.concurrent.ForkJoinPool.commonPool(), cb)
@@ -488,7 +491,7 @@ class AvfEngine @Inject constructor(
return raw
}
- private fun buildConfig(config: VmConfig): Any {
+ private fun buildConfig(mgr: Any, config: VmConfig): Any {
val kernelSrc = File(context.filesDir, "vmlinuz-virt").also {
require(it.exists()) { "kernel missing at ${it.absolutePath}" }
}
@@ -523,11 +526,16 @@ class AvfEngine @Inject constructor(
// wire an RTC the way QEMU TCG does, so without this the guest
// boots at 1970-01-01 and TLS fails on every cert.
val epoch = System.currentTimeMillis() / 1000
- AvfReflect.addParams(cb,
- "console=hvc0 root=/dev/ram0 mitigations=off elevator=mq-deadline " +
+ val resolvedCmdline = ("console=hvc0 root=/dev/ram0 mitigations=off elevator=mq-deadline " +
"podroid.tty=hvc0 podroid.backend=avf podroid.epoch=$epoch " +
- "${config.kernelExtraCmdline}".trim()
- )
+ "podroid.x11.dpi=${config.x11Dpi} " +
+ config.kernelExtraCmdline).trim()
+ AvfReflect.addParams(cb, resolvedCmdline)
+ if (config.verboseLogging) {
+ Log.i(TAG, "verbose: resolved cmdline = $resolvedCmdline")
+ Log.i(TAG, "verbose: ramMb=${config.ramMb} cpus=${config.cpus} " +
+ "storageAccess=${config.storageAccessEnabled}")
+ }
AvfReflect.addDisk(cb, storage.absolutePath, writable = true)
AvfReflect.addDisk(cb, squashfs.absolutePath, writable = false)
if (config.storageAccessEnabled) {
@@ -569,7 +577,14 @@ class AvfEngine @Inject constructor(
val customCfg = AvfReflect.build(cb)
val vb = AvfReflect.newVmConfigBuilder(context)
- AvfReflect.setProtectedVm(vb, false)
+ when (val choice = AvfReflect.applyProtectedVm(mgr, vb)) {
+ is AvfCapabilities.ProtectedVmChoice.Unsupported ->
+ throw UnsupportedOperationException(choice.reason)
+ is AvfCapabilities.ProtectedVmChoice.NonProtected ->
+ Log.i(TAG, "protectedVm=false (device supports non-protected VMs)")
+ is AvfCapabilities.ProtectedVmChoice.Unknown ->
+ Log.w(TAG, "getCapabilities() unavailable; attempted protectedVm=false")
+ }
AvfReflect.setMemoryBytes(vb, config.ramMb.toLong() * 1024 * 1024)
AvfReflect.setNumCpus(vb, config.cpus)
AvfReflect.setDebugLevel(vb, AvfReflect.DEBUG_LEVEL_FULL)
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfReasonCodes.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfReasonCodes.kt
new file mode 100644
index 0000000..a4f361b
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfReasonCodes.kt
@@ -0,0 +1,41 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Decodes android.system.virtualmachine.VirtualMachineCallback STOP_REASON_*
+ * and ERROR_* integer codes to their constant names. Values verified against
+ * the official AOSP source. Pure (no Android deps) so it unit-tests on the JVM.
+ */
+package com.excp.podroid.engine.avf
+
+object AvfReasonCodes {
+ private val STOP = mapOf(
+ -1 to "STOP_REASON_VIRTUALIZATION_SERVICE_DIED",
+ 0 to "STOP_REASON_INFRASTRUCTURE_ERROR",
+ 1 to "STOP_REASON_KILLED",
+ 2 to "STOP_REASON_UNKNOWN",
+ 3 to "STOP_REASON_SHUTDOWN",
+ 4 to "STOP_REASON_START_FAILED",
+ 5 to "STOP_REASON_REBOOT",
+ 6 to "STOP_REASON_CRASH",
+ 7 to "STOP_REASON_PVM_FIRMWARE_PUBLIC_KEY_MISMATCH",
+ 8 to "STOP_REASON_PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED",
+ 9 to "STOP_REASON_BOOTLOADER_PUBLIC_KEY_MISMATCH",
+ 10 to "STOP_REASON_BOOTLOADER_INSTANCE_IMAGE_CHANGED",
+ 11 to "STOP_REASON_MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE",
+ 12 to "STOP_REASON_MICRODROID_PAYLOAD_HAS_CHANGED",
+ 13 to "STOP_REASON_MICRODROID_PAYLOAD_VERIFICATION_FAILED",
+ 14 to "STOP_REASON_MICRODROID_INVALID_PAYLOAD_CONFIG",
+ 15 to "STOP_REASON_MICRODROID_UNKNOWN_RUNTIME_ERROR",
+ 16 to "STOP_REASON_HANGUP",
+ )
+ private val ERROR = mapOf(
+ 0 to "ERROR_UNKNOWN",
+ 1 to "ERROR_PAYLOAD_VERIFICATION_FAILED",
+ 2 to "ERROR_PAYLOAD_CHANGED",
+ 3 to "ERROR_PAYLOAD_INVALID_CONFIG",
+ )
+
+ fun stopReason(code: Int): String = STOP[code]?.let { "$code $it" } ?: "$code (unmapped)"
+ fun errorCode(code: Int): String = ERROR[code]?.let { "$code $it" } ?: "$code (unmapped)"
+}
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt
index c0b1fc9..fe7786c 100644
--- a/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt
@@ -63,6 +63,37 @@ object AvfReflect {
invokeDecl(b, "setProtectedVm", Boolean::class.javaPrimitiveType!! to value)
}
+ /**
+ * VirtualMachineManager.getCapabilities() — bitmask of
+ * AvfCapabilities.CAPABILITY_*. Returns 0 if the method is absent on an
+ * older AVF revision; that 0 maps to ProtectedVmChoice.Unknown (we then
+ * attempt non-protected and let any framework exception surface). This
+ * runCatching tolerates a MISSING method only — it is not used to hide a
+ * failure on a method that exists.
+ */
+ fun getCapabilities(mgr: Any): Int =
+ runCatching { invokeDecl(mgr, "getCapabilities") as? Int ?: 0 }.getOrDefault(0)
+
+ /**
+ * Applies the capability-driven protected-VM choice to a VM config builder.
+ * Returns the choice so the caller can fall back to QEMU on Unsupported.
+ *
+ * On the Unknown path we call setProtectedVm(false) WITHOUT catching: if the
+ * framework throws UnsupportedOperationException("Non-protected VMs are not
+ * supported on this device.") that is the real #31 signal and must surface.
+ * On Unsupported we do NOT call the setter — the caller must not proceed to
+ * build() (which would throw the misleading "must be called explicitly").
+ */
+ fun applyProtectedVm(mgr: Any, builder: Any): AvfCapabilities.ProtectedVmChoice {
+ val choice = AvfCapabilities.choose(getCapabilities(mgr))
+ when (choice) {
+ is AvfCapabilities.ProtectedVmChoice.NonProtected -> setProtectedVm(builder, false)
+ is AvfCapabilities.ProtectedVmChoice.Unknown -> setProtectedVm(builder, false)
+ is AvfCapabilities.ProtectedVmChoice.Unsupported -> Unit
+ }
+ return choice
+ }
+
fun setMemoryBytes(b: Any, bytes: Long) {
invokeDecl(b, "setMemoryBytes", Long::class.javaPrimitiveType!! to bytes)
}
diff --git a/app/src/main/java/com/excp/podroid/service/PodroidService.kt b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
index e528481..930dcbd 100644
--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt
+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
@@ -200,6 +200,8 @@ class PodroidService : Service() {
storageAccessEnabled = settingsRepository.getStorageAccessEnabledSnapshot(),
qemuExtraArgs = settingsRepository.getQemuExtraArgsSnapshot(),
kernelExtraCmdline = settingsRepository.getKernelExtraCmdlineSnapshot(),
+ verboseLogging = settingsRepository.getAvfVerboseLoggingSnapshot(),
+ x11Dpi = settingsRepository.getX11DpiSnapshot(),
)
engine.start(rules, config)
} catch (e: Exception) {
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
index 7c84efe..6d54502 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt
@@ -54,6 +54,7 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
+import androidx.compose.runtime.collectAsState
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.excp.podroid.BuildConfig
import com.excp.podroid.data.repository.PortForwardRule
@@ -271,6 +272,16 @@ fun SettingsScreen(
onClick = { viewModel.exportConsoleLogs() },
)
Spacer(Modifier.height(PodroidTokens.Spacing.SM))
+ val avfVerbose by viewModel.avfVerboseLogging.collectAsState()
+ PodroidListRow(
+ label = "Verbose AVF logging",
+ rightSlot = {
+ PodroidSwitch(
+ checked = avfVerbose,
+ onCheckedChange = { viewModel.setAvfVerboseLogging(it) },
+ )
+ },
+ )
PodroidGhostButton(
text = if (avfRunning) "Running AVF diagnostic…" else "AVF (pKVM) diagnostic",
onClick = {
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt
index 01f93d5..854224c 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt
@@ -162,6 +162,13 @@ class SettingsViewModel @Inject constructor(
viewModelScope.launch { settingsRepository.setEngineSelection(value) }
}
+ val avfVerboseLogging: StateFlow<Boolean> = settingsRepository.avfVerboseLogging
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
+
+ fun setAvfVerboseLogging(value: Boolean) {
+ viewModelScope.launch { settingsRepository.setAvfVerboseLogging(value) }
+ }
+
fun setVmRamMb(value: Int) {
viewModelScope.launch { settingsRepository.setVmRamMb(value) }
}
@@ -340,6 +347,13 @@ class SettingsViewModel @Inject constructor(
}
appendLine()
+ val avf = com.excp.podroid.engine.avf.AvfDiagnostics.probe(context)
+ appendLine("== AVF ==")
+ appendLine("backend = ${activeBackendId()}")
+ appendLine("capabilities = ${avf.capabilitiesRaw} (${avf.capabilitiesDecoded})")
+ appendLine("verboseLogging = ${settingsRepository.getAvfVerboseLoggingSnapshot()}")
+ appendLine()
+
appendLine("=== App Logcat (this process) ===")
append(captureAppLogcat())
appendLine()
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
index a79dbb8..d1cd2ed 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
@@ -4,13 +4,18 @@
*/
package com.excp.podroid.ui.screens.x11
+import android.app.Activity
+import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.Rect
-import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
+import android.view.View
+import android.view.WindowManager
+import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
+import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.waitForUpOrCancellation
@@ -34,7 +39,9 @@ import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.DesktopWindows
+import androidx.compose.material.icons.filled.Fullscreen
import androidx.compose.material.icons.filled.Keyboard
+import androidx.compose.material.icons.filled.Tune
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
@@ -42,6 +49,7 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -61,9 +69,19 @@ import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
+import androidx.compose.ui.input.pointer.PointerEventType
+import androidx.compose.ui.input.pointer.PointerType
+import androidx.compose.ui.input.pointer.changedToDown
+import androidx.compose.ui.input.pointer.isPrimaryPressed
+import androidx.compose.ui.input.pointer.isSecondaryPressed
+import androidx.compose.ui.input.pointer.isTertiaryPressed
import androidx.compose.ui.input.pointer.pointerInput
-import androidx.compose.ui.input.pointer.pointerInteropFilter
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
+import androidx.compose.ui.platform.LocalView
+import androidx.core.view.WindowCompat
+import androidx.core.view.WindowInsetsCompat
+import androidx.core.view.WindowInsetsControllerCompat
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
@@ -75,8 +93,11 @@ import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.excp.podroid.ui.components.PodroidTopBar
-import com.excp.podroid.x11.X11Constants
import kotlinx.coroutines.delay
+import kotlinx.coroutines.withTimeoutOrNull
+import kotlin.math.abs
+import com.excp.podroid.x11.TouchMode
+import com.excp.podroid.x11.VncClient
// X11 keysyms used outside the label table.
private const val XK_BackSpace = 0xFF08
@@ -87,6 +108,7 @@ private const val XK_Left = 0xFF51
private const val XK_Up = 0xFF52
private const val XK_Right = 0xFF53
private const val XK_Down = 0xFF54
+private const val XK_Shift_L = 0xFFE1
private const val XK_Control_L = 0xFFE3
private const val XK_Alt_L = 0xFFE9
@@ -136,21 +158,55 @@ fun X11Screen(
) {
val connection by viewModel.connection.collectAsStateWithLifecycle()
val frameCount by viewModel.frameCounter.collectAsStateWithLifecycle()
-
+ val fb by viewModel.fbSize.collectAsStateWithLifecycle()
+ val bitmap = remember(fb) { Bitmap.createBitmap(fb.w, fb.h, Bitmap.Config.ARGB_8888) }
+ val s by viewModel.x11Settings.collectAsStateWithLifecycle()
LaunchedEffect(Unit) { viewModel.connect() }
- val bitmap = remember {
- Bitmap.createBitmap(X11Constants.FB_WIDTH, X11Constants.FB_HEIGHT, Bitmap.Config.ARGB_8888)
+ val activity = LocalContext.current as? Activity
+ LaunchedEffect(s.rotationLock) {
+ activity?.requestedOrientation = when (s.rotationLock) {
+ com.excp.podroid.x11.RotationLock.LANDSCAPE -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
+ com.excp.podroid.x11.RotationLock.PORTRAIT -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
+ com.excp.podroid.x11.RotationLock.AUTO -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
+ }
+ }
+
+ val view = LocalView.current
+ var fullscreen by remember { mutableStateOf(s.fullscreenDefault) }
+ LaunchedEffect(fullscreen) {
+ val window = activity?.window ?: return@LaunchedEffect
+ val ctrl = WindowInsetsControllerCompat(window, view)
+ if (fullscreen) {
+ ctrl.hide(WindowInsetsCompat.Type.systemBars())
+ ctrl.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
+ } else {
+ ctrl.show(WindowInsetsCompat.Type.systemBars())
+ }
+ }
+
+ // Keep the display awake while the X11 viewer is open, matching the
+ // terminal (TerminalScreen adds the same flag). The VM-lifetime WakeLock in
+ // PodroidService is partial/CPU-only; this is the screen-on counterpart.
+ DisposableEffect(Unit) {
+ activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ onDispose { activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) }
}
+ // Back exits fullscreen first (no on-screen exit button); a second Back
+ // leaves the viewer through normal navigation.
+ BackHandler(enabled = fullscreen) { fullscreen = false }
+
+ var showSettings by remember { mutableStateOf(false) }
+
var svWidth by remember { mutableIntStateOf(1) }
var svHeight by remember { mutableIntStateOf(1) }
// Letterbox / pillarbox dst rect, pinned to top so the soft keyboard
// (and the extra-keys row) live in the empty bottom strip.
- val (dstX, dstY, dstW, dstH) = remember(svWidth, svHeight) {
- val fbW = X11Constants.FB_WIDTH.toFloat()
- val fbH = X11Constants.FB_HEIGHT.toFloat()
+ val (dstX, dstY, dstW, dstH) = remember(svWidth, svHeight, fb) {
+ val fbW = fb.w.toFloat()
+ val fbH = fb.h.toFloat()
val viewW = svWidth.toFloat().coerceAtLeast(1f)
val viewH = svHeight.toFloat().coerceAtLeast(1f)
val scale = minOf(viewW / fbW, viewH / fbH)
@@ -162,12 +218,23 @@ fun X11Screen(
}
val focusRequester = remember { FocusRequester() }
+ val viewerFocus = remember { FocusRequester() }
+ // Hold focus on the (non-editable) viewer while connected so a hardware
+ // keyboard's keys reach onPreviewKeyEvent WITHOUT popping the soft keyboard
+ // (a focused editable field would). The on-screen keyboard is summoned
+ // explicitly via the keyboard button.
+ LaunchedEffect(connection) {
+ if (connection == X11ConnectionState.Connected) runCatching { viewerFocus.requestFocus() }
+ }
val keyboardController = LocalSoftwareKeyboardController.current
var imeBuf by remember { mutableStateOf(TextFieldValue("")) }
// Sticky modifier state — tap CTRL once, the next key is sent with
// Control_L held; the modifier auto-clears after that one keypress
// (one-shot semantics, matches Termux convention).
+ // Drag-lock: a long-press engages a held left button that persists across
+ // gestures until the next tap drops it (move heavy GUI windows one-handed).
+ var dragLocked by remember { mutableStateOf(false) }
var ctrlActive by remember { mutableStateOf(false) }
var altActive by remember { mutableStateOf(false) }
@@ -191,38 +258,119 @@ fun X11Screen(
}
}
- Column(
+ Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
- // Push the bottom of the layout up by the IME height when the
- // soft keyboard opens. Effect: extra-keys row rides above the
- // keyboard, AndroidView (weight=1) shrinks to fill the gap.
- .windowInsetsPadding(WindowInsets.ime)
- ) {
- PodroidTopBar(
- title = "X11",
- navigationIcon = {
- IconButton(onClick = onNavigateBack) {
- Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
+ .focusRequester(viewerFocus)
+ .focusable()
+ .onPreviewKeyEvent { ev ->
+ // Hardware/external keyboard. Lives on the (non-editable) Box so
+ // it never pops the soft keyboard; the preview pass means it
+ // fires for all key events while focus is anywhere in this
+ // subtree (including when the on-screen keyboard field is up).
+ val native = ev.nativeKeyEvent
+ // Mouse right-click makes Android synthesize a BACK key. The
+ // pointer handler already sent it to X as button 3, so swallow
+ // the mouse-sourced Back (both down + up) to stop it exiting
+ // fullscreen. A real Back (gesture/keyboard) passes through to
+ // the BackHandler.
+ if (ev.key == Key.Back) {
+ return@onPreviewKeyEvent (native.source and android.view.InputDevice.SOURCE_MOUSE) ==
+ android.view.InputDevice.SOURCE_MOUSE
}
- },
- actions = {
- IconButton(onClick = {
- focusRequester.requestFocus()
- keyboardController?.show()
- }) {
- Icon(Icons.Default.Keyboard, contentDescription = "Keyboard")
+ if (android.view.KeyEvent.isModifierKey(native.keyCode)) {
+ return@onPreviewKeyEvent true
+ }
+ if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
+ val special = when (ev.key) {
+ Key.Backspace -> XK_BackSpace
+ Key.Enter, Key.NumPadEnter -> XK_Return
+ Key.Tab -> XK_Tab
+ Key.Escape -> XK_Escape
+ Key.DirectionLeft -> XK_Left
+ Key.DirectionRight -> XK_Right
+ Key.DirectionUp -> XK_Up
+ Key.DirectionDown -> XK_Down
+ Key.MoveHome -> 0xFF50
+ Key.MoveEnd -> 0xFF57
+ Key.PageUp -> 0xFF55
+ Key.PageDown -> 0xFF56
+ Key.Delete -> 0xFFFF
+ else -> null
}
- IconButton(onClick = onNavigateToTerminal) {
- Icon(
- Icons.Default.DesktopWindows,
- contentDescription = "Terminal",
- tint = MaterialTheme.colorScheme.primary,
+ val ctrl = native.isCtrlPressed || ctrlActive
+ val alt = native.isAltPressed || altActive
+ val keysym: Int
+ val shiftWrap: Boolean
+ if (special != null) {
+ keysym = special
+ shiftWrap = native.isShiftPressed
+ } else {
+ val cased = native.getUnicodeChar(
+ native.metaState and
+ (android.view.KeyEvent.META_SHIFT_ON or android.view.KeyEvent.META_CAPS_LOCK_ON)
)
+ if (cased == 0) return@onPreviewKeyEvent false
+ keysym = cased
+ shiftWrap = false
}
+ if (shiftWrap) viewModel.sendKey(XK_Shift_L, down = true)
+ if (ctrl) viewModel.sendKey(XK_Control_L, down = true)
+ if (alt) viewModel.sendKey(XK_Alt_L, down = true)
+ viewModel.sendKey(keysym, down = true)
+ viewModel.sendKey(keysym, down = false)
+ if (alt) viewModel.sendKey(XK_Alt_L, down = false)
+ if (ctrl) viewModel.sendKey(XK_Control_L, down = false)
+ if (shiftWrap) viewModel.sendKey(XK_Shift_L, down = false)
+ ctrlActive = false
+ altActive = false
+ true
},
- )
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ // Push the bottom of the layout up by the IME height when the
+ // soft keyboard opens. Effect: extra-keys row rides above the
+ // keyboard, AndroidView (weight=1) shrinks to fill the gap.
+ .windowInsetsPadding(WindowInsets.ime),
+ ) {
+ if (!fullscreen) {
+ PodroidTopBar(
+ title = "X11",
+ navigationIcon = {
+ IconButton(onClick = onNavigateBack) {
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
+ }
+ },
+ actions = {
+ IconButton(onClick = { fullscreen = true }) {
+ Icon(Icons.Default.Fullscreen, contentDescription = "Fullscreen")
+ }
+ IconButton(onClick = { showSettings = true }) {
+ Icon(Icons.Default.Tune, contentDescription = "Settings")
+ }
+ IconButton(onClick = {
+ focusRequester.requestFocus()
+ keyboardController?.show()
+ }) {
+ Icon(Icons.Default.Keyboard, contentDescription = "Keyboard")
+ }
+ IconButton(onClick = onNavigateToTerminal) {
+ Icon(
+ Icons.Default.DesktopWindows,
+ contentDescription = "Terminal",
+ tint = MaterialTheme.colorScheme.primary,
+ )
+ }
+ },
+ )
+ }
+
+ if (showSettings) {
+ X11SettingsSheet(viewModel = viewModel, onDismiss = { showSettings = false })
+ }
when (val state = connection) {
X11ConnectionState.Connecting,
@@ -249,19 +397,131 @@ fun X11Screen(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
- .pointerInteropFilter { ev ->
- val w = dstW.coerceAtLeast(1)
- val h = dstH.coerceAtLeast(1)
- val sx = ((ev.x - dstX) / w * X11Constants.FB_WIDTH)
- .toInt().coerceIn(0, X11Constants.FB_WIDTH - 1)
- val sy = ((ev.y - dstY) / h * X11Constants.FB_HEIGHT)
- .toInt().coerceIn(0, X11Constants.FB_HEIGHT - 1)
- val mask = when (ev.actionMasked) {
- MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> 1
- else -> 0
+ .pointerInput(
+ s.touchMode, dstX, dstY, dstW, dstH, fb.w, fb.h,
+ s.trackpadSensitivity, s.trackpadAccel,
+ ) {
+ fun fbX(px: Float) = ((px - dstX) / dstW.coerceAtLeast(1) * fb.w).toInt().coerceIn(0, fb.w - 1)
+ fun fbY(py: Float) = ((py - dstY) / dstH.coerceAtLeast(1) * fb.h).toInt().coerceIn(0, fb.h - 1)
+ awaitPointerEventScope {
+ while (true) {
+ val event = awaitPointerEvent()
+ val change = event.changes.firstOrNull() ?: continue
+
+ // Physical-mouse scroll wheel → X wheel (buttons 4/5).
+ if (event.type == PointerEventType.Scroll) {
+ val dy = change.scrollDelta.y
+ if (dy != 0f) {
+ viewModel.moveTo(fbX(change.position.x), fbY(change.position.y))
+ viewModel.scroll(up = dy < 0f, ticks = abs(dy).toInt().coerceAtLeast(1))
+ }
+ event.changes.forEach { it.consume() }
+ continue
+ }
+
+ // Physical mouse → absolute move + native buttons.
+ // Consuming keeps right-click from falling through to
+ // Android Back (which exited fullscreen) and sends it
+ // to X as button 3 instead.
+ if (change.type == PointerType.Mouse) {
+ var mask = 0
+ if (event.buttons.isPrimaryPressed) mask = mask or VncClient.BTN_LEFT
+ if (event.buttons.isSecondaryPressed) mask = mask or VncClient.BTN_RIGHT
+ if (event.buttons.isTertiaryPressed) mask = mask or VncClient.BTN_MIDDLE
+ viewModel.mouseUpdate(fbX(change.position.x), fbY(change.position.y), mask)
+ event.changes.forEach { it.consume() }
+ continue
+ }
+
+ // Touch → finger-gesture state machine (one gesture).
+ if (change.type != PointerType.Touch || !change.changedToDown()) continue
+ viewerFocus.requestFocus()
+ change.consume()
+ val sx = change.position.x; val sy = change.position.y
+ var lastX = sx; var lastY = sy
+ var moved = 0f
+ var maxPointers = 1
+ var scrollAcc = 0f
+ var leftHeld = false
+
+ // A new touch while drag-locked drops the lock.
+ if (dragLocked) {
+ viewModel.release(VncClient.BTN_LEFT)
+ dragLocked = false
+ while (true) {
+ val e = awaitPointerEvent(); e.changes.forEach { it.consume() }
+ if (e.changes.none { it.pressed }) break
+ }
+ continue
+ }
+
+ if (s.touchMode == TouchMode.DIRECT) viewModel.moveTo(fbX(sx), fbY(sy))
+
+ // Long-press (single finger, no move, ~500ms) => drag-lock.
+ var outcome = "move"
+ val completed = withTimeoutOrNull(500L) {
+ while (true) {
+ val e = awaitPointerEvent()
+ val pressed = e.changes.filter { it.pressed }
+ if (pressed.isEmpty()) { outcome = "tap"; return@withTimeoutOrNull Unit }
+ if (pressed.size >= 2) { maxPointers = 2; outcome = "multi"; return@withTimeoutOrNull Unit }
+ val p = pressed.first().position
+ if (abs(p.x - sx) + abs(p.y - sy) > 16f) {
+ lastX = p.x; lastY = p.y; outcome = "move"
+ e.changes.forEach { it.consume() }
+ return@withTimeoutOrNull Unit
+ }
+ e.changes.forEach { it.consume() }
+ }
+ @Suppress("UNREACHABLE_CODE") Unit
+ }
+ if (completed == null) {
+ dragLocked = true; viewModel.press(VncClient.BTN_LEFT); leftHeld = true
+ } else if (outcome == "tap") {
+ viewModel.click(VncClient.BTN_LEFT)
+ continue
+ }
+
+ while (true) {
+ val e = awaitPointerEvent()
+ val pressed = e.changes.filter { it.pressed }
+ maxPointers = maxOf(maxPointers, pressed.size)
+ if (pressed.isEmpty()) break
+ val p = pressed.first().position
+ val dx = p.x - lastX; val dy = p.y - lastY
+ moved += abs(dx) + abs(dy)
+ if (pressed.size >= 2) {
+ scrollAcc += dy
+ while (abs(scrollAcc) >= 60f) {
+ viewModel.scroll(scrollAcc < 0, 1)
+ scrollAcc += if (scrollAcc < 0) 60f else -60f
+ }
+ } else when (s.touchMode) {
+ TouchMode.DIRECT -> {
+ viewModel.moveTo(fbX(p.x), fbY(p.y))
+ if (!leftHeld) { viewModel.press(VncClient.BTN_LEFT); leftHeld = true }
+ }
+ TouchMode.TRACKPAD -> {
+ val accel = if (s.trackpadAccel) (1f + (abs(dx) + abs(dy)) * 0.01f) else 1f
+ val c = viewModel.cursor.value
+ viewModel.moveTo(
+ (c.x + dx * s.trackpadSensitivity * accel).toInt(),
+ (c.y + dy * s.trackpadSensitivity * accel).toInt(),
+ )
+ }
+ }
+ lastX = p.x; lastY = p.y
+ e.changes.forEach { it.consume() }
+ }
+
+ if (maxPointers >= 2) {
+ if (moved < 28f) viewModel.click(VncClient.BTN_RIGHT)
+ } else if (s.touchMode == TouchMode.TRACKPAD && !dragLocked && moved < 16f) {
+ viewModel.click(VncClient.BTN_LEFT)
+ }
+ if (!dragLocked && leftHeld) { viewModel.release(VncClient.BTN_LEFT); leftHeld = false }
+ }
}
- viewModel.sendPointer(sx, sy, mask)
- true
},
factory = { ctx ->
SurfaceView(ctx).apply {
@@ -270,6 +530,7 @@ fun X11Screen(
override fun surfaceChanged(h: SurfaceHolder, f: Int, w: Int, hh: Int) {
svWidth = w
svHeight = hh
+ viewModel.requestResolution(w, hh)
}
override fun surfaceDestroyed(h: SurfaceHolder) {}
})
@@ -283,12 +544,31 @@ fun X11Screen(
// decoder thread (paired with synchronized(framebuffer)
// in X11ViewModel.connect).
synchronized(viewModel.framebuffer) {
- bitmap.setPixels(
- viewModel.framebuffer, 0,
- X11Constants.FB_WIDTH,
- 0, 0,
- X11Constants.FB_WIDTH, X11Constants.FB_HEIGHT,
- )
+ val src = viewModel.framebuffer
+ val bw = bitmap.width
+ val bh = bitmap.height
+ // During a resolution change the framebuffer array is
+ // reallocated on the RFB thread while the Bitmap is
+ // recreated on a (slightly later) recomposition. Blit
+ // only when array and Bitmap agree in size, and clamp
+ // against the Bitmap's OWN dimensions — otherwise skip
+ // this frame (the next is consistent). Guards the
+ // "y + height must be <= bitmap.height()" crash on open.
+ if (src.size == bw * bh) {
+ val damage = viewModel.lastDamage
+ if (damage.isEmpty()) {
+ bitmap.setPixels(src, 0, bw, 0, 0, bw, bh)
+ } else {
+ for (r in damage) {
+ val rx = r.x.coerceIn(0, bw)
+ val ry = r.y.coerceIn(0, bh)
+ val rw = (r.x + r.w).coerceAtMost(bw) - rx
+ val rh = (r.y + r.h).coerceAtMost(bh) - ry
+ if (rw <= 0 || rh <= 0) continue
+ bitmap.setPixels(src, ry * bw + rx, bw, rx, ry, rw, rh)
+ }
+ }
+ }
}
val holder = sv.holder
val canvas = holder.lockCanvas() ?: return@AndroidView
@@ -302,18 +582,29 @@ fun X11Screen(
},
)
- X11ExtraKeysRow(
- onKey = ::onExtraKey,
- ctrlActive = ctrlActive,
- altActive = altActive,
- )
+ if (s.showExtraKeys && !fullscreen) {
+ X11ExtraKeysRow(
+ onKey = ::onExtraKey,
+ ctrlActive = ctrlActive,
+ altActive = altActive,
+ )
+ }
// Hidden IME hook (must stay in the layout while connected so
// the requestFocus/show sequence has a target).
BasicTextField(
value = imeBuf,
onValueChange = { new ->
- forwardImeDiff(imeBuf.text, new.text, viewModel)
+ val added = if (new.text.length > imeBuf.text.length)
+ new.text.substring(imeBuf.text.length) else ""
+ if ((ctrlActive || altActive) && added.length == 1) {
+ // Combine the sticky CTRL/ALT with the typed character
+ // (e.g. tap CTRL then type L → Ctrl+L to clear the
+ // terminal). sendWithModifiers clears the one-shot after.
+ sendWithModifiers(added[0].code)
+ } else {
+ forwardImeDiff(imeBuf.text, new.text, viewModel)
+ }
imeBuf = TextFieldValue("")
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
@@ -326,29 +617,13 @@ fun X11Screen(
modifier = Modifier
.size(1.dp)
.alpha(0f)
- .focusRequester(focusRequester)
- .onPreviewKeyEvent { ev ->
- if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
- val keysym = when (ev.key) {
- Key.Backspace -> XK_BackSpace
- Key.Enter,
- Key.NumPadEnter -> XK_Return
- Key.Tab -> XK_Tab
- Key.Escape -> XK_Escape
- Key.DirectionLeft -> XK_Left
- Key.DirectionRight -> XK_Right
- Key.DirectionUp -> XK_Up
- Key.DirectionDown -> XK_Down
- else -> return@onPreviewKeyEvent false
- }
- viewModel.sendKey(keysym, down = true)
- viewModel.sendKey(keysym, down = false)
- true
- },
+ .focusRequester(focusRequester),
)
}
- }
- }
+ } // end when
+ } // end Column
+
+ } // end Box
}
/**
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11SettingsSheet.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11SettingsSheet.kt
new file mode 100644
index 0000000..1caa31a
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11SettingsSheet.kt
@@ -0,0 +1,285 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Bottom sheet for X11 viewer settings: resolution mode/preset/custom
+ * and rotation lock. TOUCH (Phase 4) and DISPLAY (Phase 5) sections
+ * will be appended to the Column below the rotation section.
+ */
+package com.excp.podroid.ui.screens.x11
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.FilterChip
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Slider
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.excp.podroid.ui.components.PodroidChipColors
+import com.excp.podroid.ui.components.PodroidSectionLabel
+import com.excp.podroid.ui.components.PodroidSwitch
+import com.excp.podroid.ui.theme.PodroidTokens
+import com.excp.podroid.x11.ResolutionMode
+import com.excp.podroid.x11.ResolutionPreset
+import com.excp.podroid.x11.RotationLock
+import com.excp.podroid.x11.TouchMode
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun X11SettingsSheet(viewModel: X11ViewModel, onDismiss: () -> Unit) {
+ val s by viewModel.x11Settings.collectAsStateWithLifecycle()
+
+ ModalBottomSheet(onDismissRequest = onDismiss) {
+ Column(
+ modifier = Modifier
+ .padding(horizontal = PodroidTokens.Spacing.XL)
+ .verticalScroll(rememberScrollState()),
+ ) {
+ // ── RESOLUTION ────────────────────────────────────────────
+ PodroidSectionLabel("Resolution")
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ ResolutionMode.entries.forEach { mode ->
+ FilterChip(
+ selected = s.resolutionMode == mode,
+ onClick = { viewModel.setResolutionMode(mode) },
+ label = {
+ Text(
+ when (mode) {
+ ResolutionMode.MATCH -> "Match viewport"
+ ResolutionMode.PRESET -> "Preset"
+ ResolutionMode.CUSTOM -> "Custom"
+ }
+ )
+ },
+ shape = RoundedCornerShape(PodroidTokens.Radius.Chip),
+ colors = PodroidChipColors(),
+ )
+ }
+ }
+
+ if (s.resolutionMode == ResolutionMode.PRESET) {
+ Spacer(Modifier.height(PodroidTokens.Spacing.SM))
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ ResolutionPreset.entries.forEach { preset ->
+ FilterChip(
+ selected = s.preset == preset,
+ onClick = { viewModel.setPreset(preset) },
+ label = {
+ Text(
+ when (preset) {
+ ResolutionPreset.R720P -> "720p"
+ ResolutionPreset.R900P -> "900p"
+ ResolutionPreset.R1080P -> "1080p"
+ ResolutionPreset.R1440P -> "1440p"
+ }
+ )
+ },
+ shape = RoundedCornerShape(PodroidTokens.Radius.Chip),
+ colors = PodroidChipColors(),
+ )
+ }
+ }
+ }
+
+ if (s.resolutionMode == ResolutionMode.CUSTOM) {
+ Spacer(Modifier.height(PodroidTokens.Spacing.SM))
+ CustomResolutionFields(
+ initialW = s.customW,
+ initialH = s.customH,
+ onCommit = { w, h -> viewModel.setCustom(w, h) },
+ )
+ }
+
+ // ── ROTATION ──────────────────────────────────────────────
+ PodroidSectionLabel("Rotation")
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ RotationLock.entries.forEach { lock ->
+ FilterChip(
+ selected = s.rotationLock == lock,
+ onClick = { viewModel.setRotation(lock) },
+ label = {
+ Text(
+ when (lock) {
+ RotationLock.AUTO -> "Auto"
+ RotationLock.LANDSCAPE -> "Landscape"
+ RotationLock.PORTRAIT -> "Portrait"
+ }
+ )
+ },
+ shape = RoundedCornerShape(PodroidTokens.Radius.Chip),
+ colors = PodroidChipColors(),
+ )
+ }
+ }
+
+ // ── TOUCH ─────────────────────────────────────────────────
+ PodroidSectionLabel("Touch")
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ TouchMode.entries.forEach { mode ->
+ FilterChip(
+ selected = s.touchMode == mode,
+ onClick = { viewModel.setTouchMode(mode) },
+ label = { Text(if (mode == TouchMode.DIRECT) "Direct touch" else "Trackpad") },
+ shape = RoundedCornerShape(PodroidTokens.Radius.Chip),
+ colors = PodroidChipColors(),
+ )
+ }
+ }
+
+ Spacer(Modifier.height(PodroidTokens.Spacing.SM))
+ Text(
+ "Pointer speed: ${"%.1f".format(s.trackpadSensitivity)}x",
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Slider(
+ value = s.trackpadSensitivity,
+ onValueChange = { viewModel.setTrackpadSensitivity(it) },
+ valueRange = 0.5f..3.0f,
+ enabled = s.touchMode == TouchMode.TRACKPAD,
+ )
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text("Pointer acceleration", color = MaterialTheme.colorScheme.onSurface)
+ PodroidSwitch(
+ checked = s.trackpadAccel,
+ onCheckedChange = { viewModel.setTrackpadAccel(it) },
+ enabled = s.touchMode == TouchMode.TRACKPAD,
+ )
+ }
+
+ // ── DISPLAY ───────────────────────────────────────────────
+ PodroidSectionLabel("Display")
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text("Show extra keys", color = MaterialTheme.colorScheme.onSurface)
+ PodroidSwitch(
+ checked = s.showExtraKeys,
+ onCheckedChange = { viewModel.setShowExtraKeys(it) },
+ )
+ }
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text("Start in fullscreen", color = MaterialTheme.colorScheme.onSurface)
+ PodroidSwitch(
+ checked = s.fullscreenDefault,
+ onCheckedChange = { viewModel.setFullscreenDefault(it) },
+ )
+ }
+
+ Spacer(Modifier.height(PodroidTokens.Spacing.SM))
+ Text("Server DPI", color = MaterialTheme.colorScheme.onSurface)
+ Spacer(Modifier.height(PodroidTokens.Spacing.XS))
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ listOf(96, 120, 144, 168, 192).forEach { dpi ->
+ FilterChip(
+ selected = s.dpi == dpi,
+ onClick = { viewModel.setDpi(dpi) },
+ label = { Text("${dpi}") },
+ shape = RoundedCornerShape(PodroidTokens.Radius.Chip),
+ colors = PodroidChipColors(),
+ )
+ }
+ }
+ Text(
+ "Applies on next VM start",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+
+ Spacer(Modifier.height(PodroidTokens.Spacing.XL2))
+ }
+ }
+}
+
+@Composable
+private fun CustomResolutionFields(
+ initialW: Int,
+ initialH: Int,
+ onCommit: (Int, Int) -> Unit,
+) {
+ var wText by remember(initialW) { mutableStateOf(initialW.toString()) }
+ var hText by remember(initialH) { mutableStateOf(initialH.toString()) }
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.MD),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ OutlinedTextField(
+ value = wText,
+ onValueChange = { v ->
+ wText = v
+ val w = v.toIntOrNull() ?: return@OutlinedTextField
+ val h = hText.toIntOrNull() ?: return@OutlinedTextField
+ onCommit(w, h)
+ },
+ label = { Text("Width") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
+ modifier = Modifier.weight(1f),
+ )
+ OutlinedTextField(
+ value = hText,
+ onValueChange = { v ->
+ hText = v
+ val w = wText.toIntOrNull() ?: return@OutlinedTextField
+ val h = v.toIntOrNull() ?: return@OutlinedTextField
+ onCommit(w, h)
+ },
+ label = { Text("Height") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
+ modifier = Modifier.weight(1f),
+ )
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
index 0434c73..a405af7 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
@@ -6,17 +6,29 @@ package com.excp.podroid.ui.screens.x11
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.engine.VmEngine
import com.excp.podroid.engine.VmState
import com.excp.podroid.x11.AudioStreamer
+import com.excp.podroid.x11.ResolutionMode
+import com.excp.podroid.x11.ResolutionPolicy
+import com.excp.podroid.x11.ResolutionPreset
+import com.excp.podroid.x11.RotationLock
+import com.excp.podroid.x11.TouchMode
import com.excp.podroid.x11.VncClient
+import com.excp.podroid.x11.VncRect
+import com.excp.podroid.x11.VncSize
import com.excp.podroid.x11.X11Constants
+import com.excp.podroid.x11.X11Settings
+import com.excp.podroid.x11.ZrleDecoder
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.io.OutputStream
@@ -34,6 +46,7 @@ sealed interface X11ConnectionState {
@HiltViewModel
class X11ViewModel @Inject constructor(
val engine: VmEngine,
+ private val settings: SettingsRepository,
) : ViewModel() {
val vmState: StateFlow<VmState> = engine.state
@@ -41,21 +54,21 @@ class X11ViewModel @Inject constructor(
private val _connection = MutableStateFlow<X11ConnectionState>(X11ConnectionState.Disconnected)
val connection: StateFlow<X11ConnectionState> = _connection.asStateFlow()
- /**
- * Backing pixel buffer the SurfaceView blits to a Bitmap.
- *
- * Threading: written by the RFB I/O coroutine in [connect] and read by the
- * UI thread in `X11Screen.update`. Both sides MUST `synchronized(framebuffer)`
- * around the read/write to avoid torn pixels (one frame mid-write being
- * blitted, producing transient horizontal tearing visible as banding).
- */
- val framebuffer: IntArray = IntArray(X11Constants.FB_WIDTH * X11Constants.FB_HEIGHT)
-
- // Scratch buffer the RFB decoder writes into off the UI thread. We swap
- // it into [framebuffer] under a short lock so the UI never blocks on a
- // socket read (holding the framebuffer lock across recvfrom deadlocks
- // the main thread → ANR on screen open).
- private val scratch: IntArray = IntArray(X11Constants.FB_WIDTH * X11Constants.FB_HEIGHT)
+ val x11Settings = settings.x11Settings.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), X11Settings())
+
+ private val _fbSize = MutableStateFlow(VncSize(X11Constants.FB_WIDTH, X11Constants.FB_HEIGHT))
+ val fbSize: StateFlow<VncSize> = _fbSize.asStateFlow()
+
+ val cursor = MutableStateFlow(android.graphics.Point(X11Constants.FB_WIDTH / 2, X11Constants.FB_HEIGHT / 2))
+
+ @Volatile private var fbW = X11Constants.FB_WIDTH
+ @Volatile private var fbH = X11Constants.FB_HEIGHT
+ @Volatile var framebuffer: IntArray = IntArray(fbW * fbH); private set
+ @Volatile private var scratch: IntArray = IntArray(fbW * fbH)
+ private val zrle = ZrleDecoder()
+ @Volatile private var screenId = 0
+ @Volatile private var desiredW = 0; @Volatile private var desiredH = 0
+ @Volatile var lastDamage: List<VncRect> = emptyList(); private set
private val _frameCounter = MutableStateFlow(0)
val frameCounter: StateFlow<Int> = _frameCounter.asStateFlow()
@@ -77,26 +90,30 @@ class X11ViewModel @Inject constructor(
VncClient.handshake(inp, out)
VncClient.negotiatePixelFormat(out)
- VncClient.requestFramebufferUpdate(out, incremental = false)
-
+ if (desiredW > 0) VncClient.requestDesktopSize(out, screenId, desiredW, desiredH)
+ VncClient.requestFramebufferUpdate(out, w = fbW, h = fbH, incremental = false)
_connection.value = X11ConnectionState.Connected
audio.start(viewModelScope)
-
while (isActive) {
- // Decode into scratch off-lock so a blocking socket read
- // never holds the framebuffer lock (would deadlock the
- // UI thread → ANR). Swap under a short lock; the copy
- // is fast and uncontended.
- VncClient.readFramebufferUpdate(
- inp = inp,
- targetArgb = scratch,
- stride = X11Constants.FB_WIDTH,
- )
+ val upd = VncClient.readFramebufferUpdate(inp, scratch, fbW, zrle)
+ upd.newSize?.let { ns ->
+ if (ns.w != fbW || ns.h != fbH) {
+ fbW = ns.w; fbH = ns.h
+ val fresh = IntArray(fbW * fbH)
+ synchronized(framebuffer) { framebuffer = fresh }
+ scratch = IntArray(fbW * fbH)
+ _fbSize.value = ns
+ cursor.value = android.graphics.Point(fbW / 2, fbH / 2)
+ VncClient.requestFramebufferUpdate(out, w = fbW, h = fbH, incremental = false)
+ return@let
+ }
+ }
synchronized(framebuffer) {
System.arraycopy(scratch, 0, framebuffer, 0, framebuffer.size)
+ lastDamage = upd.damage
}
_frameCounter.value = _frameCounter.value + 1
- VncClient.requestFramebufferUpdate(out, incremental = true)
+ VncClient.requestFramebufferUpdate(out, w = fbW, h = fbH, incremental = true)
}
}
} catch (e: Exception) {
@@ -116,6 +133,73 @@ class X11ViewModel @Inject constructor(
sessionJob = null
}
+ @Volatile private var lastViewportW = 0
+ @Volatile private var lastViewportH = 0
+
+ fun requestResolution(viewportW: Int, viewportH: Int) {
+ lastViewportW = viewportW
+ lastViewportH = viewportH
+ val s = x11Settings.value
+ val t = ResolutionPolicy.target(s, viewportW, viewportH)
+ desiredW = t.w; desiredH = t.h
+ val out = rfbOut ?: return
+ viewModelScope.launch(Dispatchers.IO) { runCatching { VncClient.requestDesktopSize(out, screenId, t.w, t.h) } }
+ }
+
+ fun setResolutionMode(m: ResolutionMode) {
+ viewModelScope.launch { settings.setX11ResolutionMode(m.name) }
+ val explicit = x11Settings.value.copy(resolutionMode = m)
+ reapplyResolution(explicit)
+ }
+
+ fun setPreset(p: ResolutionPreset) {
+ viewModelScope.launch { settings.setX11Preset(p.name) }
+ val explicit = x11Settings.value.copy(resolutionMode = ResolutionMode.PRESET, preset = p)
+ reapplyResolution(explicit)
+ }
+
+ fun setCustom(w: Int, h: Int) {
+ viewModelScope.launch { settings.setX11Custom(w, h) }
+ val explicit = x11Settings.value.copy(resolutionMode = ResolutionMode.CUSTOM, customW = w, customH = h)
+ reapplyResolution(explicit)
+ }
+
+ fun setRotation(r: RotationLock) {
+ viewModelScope.launch { settings.setX11Rotation(r.name) }
+ }
+
+ fun setTouchMode(m: TouchMode) {
+ viewModelScope.launch { settings.setX11TouchMode(m.name) }
+ }
+
+ fun setTrackpadSensitivity(v: Float) {
+ viewModelScope.launch { settings.setX11TrackpadSensitivity(v) }
+ }
+
+ fun setTrackpadAccel(v: Boolean) {
+ viewModelScope.launch { settings.setX11TrackpadAccel(v) }
+ }
+
+ fun setShowExtraKeys(v: Boolean) {
+ viewModelScope.launch { settings.setX11ShowExtraKeys(v) }
+ }
+
+ fun setFullscreenDefault(v: Boolean) {
+ viewModelScope.launch { settings.setX11Fullscreen(v) }
+ }
+
+ fun setDpi(v: Int) {
+ viewModelScope.launch { settings.setX11Dpi(v) }
+ }
+
+ private fun reapplyResolution(explicit: X11Settings) {
+ if (lastViewportW <= 0) return
+ val t = ResolutionPolicy.target(explicit, lastViewportW, lastViewportH)
+ desiredW = t.w; desiredH = t.h
+ val out = rfbOut ?: return
+ viewModelScope.launch(Dispatchers.IO) { runCatching { VncClient.requestDesktopSize(out, screenId, t.w, t.h) } }
+ }
+
fun sendPointer(x: Int, y: Int, buttonMask: Int) {
val out = rfbOut ?: return
viewModelScope.launch(Dispatchers.IO) {
@@ -130,6 +214,20 @@ class X11ViewModel @Inject constructor(
}
}
+ fun moveTo(x: Int, y: Int) { cursor.value = android.graphics.Point(x.coerceIn(0, fbW - 1), y.coerceIn(0, fbH - 1)); sendPointer(cursor.value.x, cursor.value.y, heldButtons) }
+ @Volatile private var heldButtons = 0
+ fun press(button: Int) { heldButtons = heldButtons or button; sendPointer(cursor.value.x, cursor.value.y, heldButtons) }
+ fun release(button: Int) { heldButtons = heldButtons and button.inv(); sendPointer(cursor.value.x, cursor.value.y, heldButtons) }
+ fun click(button: Int) { press(button); release(button) }
+ /** Physical-mouse update: absolute position + the full button mask in one event. */
+ fun mouseUpdate(x: Int, y: Int, mask: Int) {
+ val nx = x.coerceIn(0, fbW - 1); val ny = y.coerceIn(0, fbH - 1)
+ cursor.value = android.graphics.Point(nx, ny)
+ heldButtons = mask
+ sendPointer(nx, ny, mask)
+ }
+ fun scroll(up: Boolean, ticks: Int = 1) { val b = if (up) VncClient.BTN_WHEEL_UP else VncClient.BTN_WHEEL_DOWN; repeat(ticks) { sendPointer(cursor.value.x, cursor.value.y, heldButtons or b); sendPointer(cursor.value.x, cursor.value.y, heldButtons) } }
+
override fun onCleared() {
disconnect()
super.onCleared()
diff --git a/app/src/main/java/com/excp/podroid/x11/VncClient.kt b/app/src/main/java/com/excp/podroid/x11/VncClient.kt
index 1590b87..4f67660 100644
--- a/app/src/main/java/com/excp/podroid/x11/VncClient.kt
+++ b/app/src/main/java/com/excp/podroid/x11/VncClient.kt
@@ -3,8 +3,7 @@
* Copyright (C) 2024-2026 Podroid contributors
*
* Minimal RFB 3.8 client. Supports SecurityType None, Raw + CopyRect +
- * Cursor pseudo encodings. Designed for loopback (SLIRP) so we don't
- * bother with Tight / ZRLE / TLS.
+ * ExtendedDesktopSize + ZRLE encodings. Designed for loopback (SLIRP).
*/
package com.excp.podroid.x11
@@ -68,6 +67,8 @@ object VncClient {
private const val MSG_FRAMEBUFFER_UPDATE: Int = 0
private const val ENC_RAW: Int = 0
private const val ENC_COPY_RECT: Int = 1
+ private const val ENC_ZRLE = 16
+ private const val ENC_EXTENDED_DESKTOP_SIZE = -308
/**
* Sends SetPixelFormat to lock the server to 32-bit BGRA, then SetEncodings
@@ -85,15 +86,18 @@ object VncClient {
)
out.write(pf)
- // SetEncodings (msg=2): num-encodings=2, [Raw, CopyRect]
- val se = byteArrayOf(
- 0x02, 0x00, // msg + pad
- 0x00, 0x02, // count = 2
- 0x00, 0x00, 0x00, 0x00, // Raw
- 0x00, 0x00, 0x00, 0x01, // CopyRect
- )
- out.write(se)
- out.flush()
+ // SetEncodings (msg=2): CopyRect, Raw, ExtendedDesktopSize(-308).
+ // ZRLE is intentionally NOT advertised: the decoder desyncs its
+ // continuous zlib stream on complex content (Firefox/xfce send palette/
+ // RLE tiles), producing "invalid distance code" which kills the whole
+ // VNC session. Raw has no zlib state so it can't desync. Re-enable only
+ // after the ZrleDecoder is fixed + verified against real captured tiles.
+ val se = java.nio.ByteBuffer.allocate(4 + 3 * 4)
+ se.put(2.toByte()); se.put(0.toByte()); se.putShort(3)
+ se.putInt(1) // CopyRect
+ se.putInt(0) // Raw
+ se.putInt(-308) // ExtendedDesktopSize
+ out.write(se.array()); out.flush()
}
/**
@@ -118,104 +122,83 @@ object VncClient {
out.flush()
}
- /**
- * Reads a FramebufferUpdate message and copies decoded pixels into `targetArgb`
- * at row stride `stride`. Only Raw and CopyRect encodings are handled.
- */
- fun readFramebufferUpdate(inp: InputStream, targetArgb: IntArray, stride: Int) {
+ data class RfbUpdate(val newSize: VncSize?, val damage: List<VncRect>)
+
+ fun readFramebufferUpdate(inp: InputStream, targetArgb: IntArray, stride: Int, zrle: ZrleDecoder): RfbUpdate {
val din = DataInputStream(inp)
- // RFB servers interleave non-rect messages (Bell, ColourMap, ClipBoard)
- // with FramebufferUpdates. Older versions of this client `require`'d
- // type==0 and bailed on type 3 (ServerCutText, clipboard share) which
- // Xvnc sends opportunistically — that's the "unexpected msg 3" the
- // user saw mid-Firefox-video. Skip the bytes for each non-fatal type
- // and loop until a FramebufferUpdate actually arrives.
var msgType: Int
while (true) {
msgType = din.readUnsignedByte()
when (msgType) {
- MSG_FRAMEBUFFER_UPDATE -> break // fall through to rect parsing
- 1 -> { // SetColourMapEntries: pad(1) + first(2) + n(2) + n*6
- din.skipBytes(1)
- din.readUnsignedShort()
- val n = din.readUnsignedShort()
- din.skipBytes(n * 6)
- }
- 2 -> { /* Bell: no body */ }
- 3 -> { // ServerCutText: pad(3) + length(4) + text[length]
- din.skipBytes(3)
- val len = din.readInt()
- if (len in 0..(1 shl 20)) din.skipBytes(len)
- else throw java.io.IOException("ServerCutText absurd length=$len")
- }
+ MSG_FRAMEBUFFER_UPDATE -> break
+ 1 -> { din.skipBytes(1); din.readUnsignedShort(); val n = din.readUnsignedShort(); din.skipBytes(n * 6) }
+ 2 -> { }
+ 3 -> { din.skipBytes(3); val len = din.readInt(); if (len in 0..(1 shl 20)) din.skipBytes(len) else throw java.io.IOException("ServerCutText absurd length=$len") }
else -> throw java.io.IOException("unexpected RFB server msg type $msgType")
}
}
din.skipBytes(1)
val numRects = din.readUnsignedShort()
-
- // Reused row scratch — only reallocated when a wider rect arrives.
- // Without this, a 1280x720 frame at 60 fps allocates 720 ByteArrays
- // per refresh (~300 KB/s GC pressure).
var rowBuf: ByteArray? = null
+ var newSize: VncSize? = null
+ val damage = ArrayList<VncRect>(numRects)
repeat(numRects) {
- val x = din.readUnsignedShort()
- val y = din.readUnsignedShort()
- val w = din.readUnsignedShort()
- val h = din.readUnsignedShort()
+ val x = din.readUnsignedShort(); val y = din.readUnsignedShort()
+ val w = din.readUnsignedShort(); val h = din.readUnsignedShort()
val enc = din.readInt()
-
when (enc) {
+ ENC_EXTENDED_DESKTOP_SIZE -> { // -308: w/h are the new fb dims
+ val screens = din.readUnsignedByte(); din.skipBytes(3)
+ din.skipBytes(screens * 16) // we use a single-screen model; dims come from w/h
+ newSize = VncSize(w, h)
+ }
ENC_RAW -> {
- // 4 bytes BGRA per pixel.
val needed = w * 4
- val existing = rowBuf
- val rowPixels = if (existing == null || existing.size < needed) {
- ByteArray(needed).also { rowBuf = it }
- } else {
- existing
- }
+ val rowPixels = rowBuf?.takeIf { it.size >= needed } ?: ByteArray(needed).also { rowBuf = it }
for (row in 0 until h) {
din.readFully(rowPixels, 0, needed)
- var off = 0
- val baseIdx = (y + row) * stride + x
+ var off = 0; val base = (y + row) * stride + x
for (col in 0 until w) {
val b = rowPixels[off].toInt() and 0xFF
val g = rowPixels[off + 1].toInt() and 0xFF
val r = rowPixels[off + 2].toInt() and 0xFF
- // Alpha byte from server is ignored — RFB true-color
- // doesn't really have alpha; we force opaque.
- targetArgb[baseIdx + col] = (0xFF shl 24) or (r shl 16) or (g shl 8) or b
+ targetArgb[base + col] = (0xFF shl 24) or (r shl 16) or (g shl 8) or b
off += 4
}
}
+ damage.add(VncRect(x, y, w, h))
}
ENC_COPY_RECT -> {
- val srcX = din.readUnsignedShort()
- val srcY = din.readUnsignedShort()
- // Copy with downward/upward order awareness.
- if (srcY < y) {
- for (row in h - 1 downTo 0) {
- System.arraycopy(
- targetArgb, (srcY + row) * stride + srcX,
- targetArgb, (y + row) * stride + x,
- w,
- )
- }
- } else {
- for (row in 0 until h) {
- System.arraycopy(
- targetArgb, (srcY + row) * stride + srcX,
- targetArgb, (y + row) * stride + x,
- w,
- )
- }
- }
+ val srcX = din.readUnsignedShort(); val srcY = din.readUnsignedShort()
+ if (srcY < y) for (row in h - 1 downTo 0) System.arraycopy(targetArgb, (srcY + row) * stride + srcX, targetArgb, (y + row) * stride + x, w)
+ else for (row in 0 until h) System.arraycopy(targetArgb, (srcY + row) * stride + srcX, targetArgb, (y + row) * stride + x, w)
+ damage.add(VncRect(x, y, w, h))
+ }
+ ENC_ZRLE -> {
+ zrle.decode(din, x, y, w, h, targetArgb, stride)
+ damage.add(VncRect(x, y, w, h))
}
else -> error("unsupported encoding $enc")
}
}
+ return RfbUpdate(newSize, damage)
+ }
+
+ const val BTN_LEFT = 1; const val BTN_MIDDLE = 2; const val BTN_RIGHT = 4
+ const val BTN_WHEEL_UP = 8; const val BTN_WHEEL_DOWN = 16
+
+ /** SetDesktopSize (msg 251): request a single-screen desktop of width x height. */
+ fun requestDesktopSize(out: OutputStream, screenId: Int, width: Int, height: Int) {
+ val buf = java.nio.ByteBuffer.allocate(24) // 8 header + 16 screen
+ buf.put(251.toByte()); buf.put(0.toByte())
+ buf.putShort(width.toShort()); buf.putShort(height.toShort())
+ buf.put(1.toByte()); buf.put(0.toByte()) // number-of-screens=1, pad
+ buf.putInt(screenId) // id
+ buf.putShort(0); buf.putShort(0) // x, y
+ buf.putShort(width.toShort()); buf.putShort(height.toShort())
+ buf.putInt(0) // flags
+ out.write(buf.array()); out.flush()
}
private const val MSG_KEY_EVENT: Byte = 4
diff --git a/app/src/main/java/com/excp/podroid/x11/X11Settings.kt b/app/src/main/java/com/excp/podroid/x11/X11Settings.kt
new file mode 100644
index 0000000..e338d83
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/x11/X11Settings.kt
@@ -0,0 +1,52 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * X11 viewer settings model + the pure resolution-selection policy. Pure
+ * Kotlin (no Android deps) so the policy unit-tests without a device.
+ */
+package com.excp.podroid.x11
+
+/** Pure size/rect types so VncClient + ResolutionPolicy unit-test on the JVM. */
+data class VncSize(val w: Int, val h: Int)
+data class VncRect(val x: Int, val y: Int, val w: Int, val h: Int)
+
+enum class ResolutionMode { MATCH, PRESET, CUSTOM }
+enum class ResolutionPreset(val w: Int, val h: Int) {
+ R720P(1280, 720), R900P(1600, 900), R1080P(1920, 1080), R1440P(2560, 1440)
+}
+enum class TouchMode { DIRECT, TRACKPAD }
+enum class RotationLock { AUTO, LANDSCAPE, PORTRAIT }
+
+data class X11Settings(
+ val resolutionMode: ResolutionMode = ResolutionMode.MATCH,
+ val preset: ResolutionPreset = ResolutionPreset.R1080P,
+ val customW: Int = 1280,
+ val customH: Int = 720,
+ val touchMode: TouchMode = TouchMode.DIRECT,
+ val trackpadSensitivity: Float = 1.5f,
+ val trackpadAccel: Boolean = true,
+ val fullscreenDefault: Boolean = false,
+ val rotationLock: RotationLock = RotationLock.AUTO,
+ val showExtraKeys: Boolean = true,
+ val dpi: Int = 96,
+)
+
+object ResolutionPolicy {
+ private const val MIN = 320
+
+ /** Even-rounds a dimension (RandR/virtio prefer even) and clamps to a minimum. */
+ private fun norm(v: Int, min: Int) = (v - (v % 2)).coerceAtLeast(min)
+
+ /** Target X-desktop size for the given settings + current viewport (device px). */
+ fun target(s: X11Settings, viewportW: Int, viewportH: Int): VncSize = when (s.resolutionMode) {
+ ResolutionMode.MATCH -> VncSize(norm(viewportW, MIN), norm(viewportH, 240))
+ ResolutionMode.CUSTOM -> VncSize(norm(s.customW, MIN), norm(s.customH, 240))
+ ResolutionMode.PRESET -> {
+ val landscape = viewportW >= viewportH
+ val long = maxOf(s.preset.w, s.preset.h)
+ val short = minOf(s.preset.w, s.preset.h)
+ if (landscape) VncSize(long, short) else VncSize(short, long)
+ }
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt b/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt
new file mode 100644
index 0000000..4d67ed0
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt
@@ -0,0 +1,236 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * ZRLE (RFB encoding 16) decoder.
+ *
+ * Wire format per rect:
+ * 4 bytes big-endian compressed-data length
+ * N bytes zlib-compressed tile stream (standard zlib header, nowrap=false)
+ *
+ * The zlib stream is continuous across rects for the lifetime of the RFB session,
+ * so a single Inflater is held as instance state and must NOT be re-created per call.
+ *
+ * Tiles are 64x64 max, row-major (left to right, top to bottom) covering the w*h rect.
+ * Each tile begins with 1 subencoding byte:
+ * 0 raw: tw*th CPIXELs in raster order
+ * 1 solid: 1 CPIXEL fills the whole tile
+ * 2..16 packed-palette: N CPIXELs palette, then packed indices (1/2/4 bpp), row-aligned
+ * 128 plain RLE: sequence of (CPIXEL, run-length); run-length = sum-of-bytes+1
+ * (each 0xFF means +255 and continue; final <0xFF byte ends the run)
+ * 130..255 palette RLE: palette of (subenc-128) CPIXELs; then index bytes:
+ * bit7=0 -> single pixel palette[index]; bit7=1 -> palette[index&0x7F]
+ * repeated run-length times (same sum-of-bytes+1 encoding)
+ *
+ * CPIXEL = 3 bytes in wire order B, G, R (matching the negotiated 32bpp/depth-24/LE/R16-G8-B0
+ * pixel format). Decoded to ARGB: 0xFF_000000 | R<<16 | G<<8 | B.
+ */
+package com.excp.podroid.x11
+
+import java.io.DataInputStream
+import java.io.IOException
+import java.util.zip.Inflater
+
+class ZrleDecoder {
+
+ private val inflater = Inflater(/*nowrap=*/false)
+
+ // Scratch buffer for compressed input read from the socket.
+ private var inputScratch = ByteArray(4096)
+ // Decompressed output buffer; re-used across inflate calls within one decode() call.
+ private var outputBuf = ByteArray(4096)
+
+ // Remaining compressed bytes in the current rect that have not yet been fed to the inflater.
+ private var remaining = 0
+ private var inputStream: DataInputStream? = null
+
+ /**
+ * Decodes one ZRLE-encoded rectangle into [target].
+ *
+ * @param din source stream positioned at the 4-byte length prefix of the ZRLE data
+ * @param x left edge of the rectangle in the framebuffer
+ * @param y top edge of the rectangle in the framebuffer
+ * @param w rectangle width
+ * @param h rectangle height
+ * @param target ARGB framebuffer array
+ * @param stride row stride of [target] (pixels per row)
+ */
+ fun decode(din: DataInputStream, x: Int, y: Int, w: Int, h: Int, target: IntArray, stride: Int) {
+ // Read and decompress the rect's zlib block.
+ val compLen = din.readInt()
+ if (compLen < 0 || compLen > 64 * 1024 * 1024) throw IOException("ZRLE: absurd compressed length $compLen")
+
+ // Feed the entire compressed block to the inflater.
+ var bytesLeft = compLen
+ while (bytesLeft > 0) {
+ val chunk = minOf(bytesLeft, inputScratch.size)
+ din.readFully(inputScratch, 0, chunk)
+ inflater.setInput(inputScratch, 0, chunk)
+ bytesLeft -= chunk
+ // Drain any output the inflater can produce now so its internal buffer stays free.
+ // We don't store it here; ZInput pulls on demand.
+ }
+
+ // Wrap the inflater so tile-level code just calls readByte()/readBytes().
+ val zi = ZInput(inflater)
+
+ // Tile loop: 64x64 tiles in row-major order.
+ var ty = 0
+ while (ty < h) {
+ val th = minOf(64, h - ty)
+ var tx = 0
+ while (tx < w) {
+ val tw = minOf(64, w - tx)
+ decodeTile(zi, x + tx, y + ty, tw, th, target, stride)
+ tx += 64
+ }
+ ty += 64
+ }
+ }
+
+ private fun decodeTile(zi: ZInput, tx: Int, ty: Int, tw: Int, th: Int, target: IntArray, stride: Int) {
+ val subenc = zi.readByte()
+ when {
+ subenc == 0 -> {
+ // Raw: tw*th CPIXELs.
+ for (row in 0 until th) {
+ val base = (ty + row) * stride + tx
+ for (col in 0 until tw) {
+ target[base + col] = zi.readCpixel()
+ }
+ }
+ }
+ subenc == 1 -> {
+ // Solid: 1 CPIXEL, fill the whole tile.
+ val color = zi.readCpixel()
+ for (row in 0 until th) {
+ val base = (ty + row) * stride + tx
+ for (col in 0 until tw) target[base + col] = color
+ }
+ }
+ subenc in 2..16 -> {
+ // Packed palette.
+ val n = subenc
+ val palette = IntArray(n) { zi.readCpixel() }
+ val bitsPerIndex = when {
+ n == 2 -> 1
+ n <= 4 -> 2
+ else -> 4
+ }
+ for (row in 0 until th) {
+ val base = (ty + row) * stride + tx
+ // Each row is bit-packed, byte-aligned.
+ var col = 0
+ var accumByte = 0
+ var bitsInAccum = 0
+ while (col < tw) {
+ if (bitsInAccum == 0) {
+ accumByte = zi.readByte()
+ bitsInAccum = 8
+ }
+ val idx = (accumByte ushr (8 - bitsPerIndex)) and ((1 shl bitsPerIndex) - 1)
+ accumByte = (accumByte shl bitsPerIndex) and 0xFF
+ bitsInAccum -= bitsPerIndex
+ target[base + col] = palette[idx]
+ col++
+ }
+ // Discard any padding bits at end of row (bitsInAccum may be > 0 but
+ // we already read the full byte; nothing extra to consume).
+ }
+ }
+ subenc == 128 -> {
+ // Plain RLE: sequence of runs until tile is full.
+ val total = tw * th
+ var filled = 0
+ while (filled < total) {
+ val color = zi.readCpixel()
+ val runLen = zi.readRunLength()
+ repeat(runLen) {
+ val pos = filled + it
+ val row = pos / tw; val col = pos % tw
+ target[(ty + row) * stride + (tx + col)] = color
+ }
+ filled += runLen
+ }
+ }
+ subenc in 130..255 -> {
+ // Palette RLE.
+ val n = subenc - 128
+ val palette = IntArray(n) { zi.readCpixel() }
+ val total = tw * th
+ var filled = 0
+ while (filled < total) {
+ val indexByte = zi.readByte()
+ if (indexByte and 0x80 == 0) {
+ // Single pixel.
+ val pos = filled
+ val row = pos / tw; val col = pos % tw
+ target[(ty + row) * stride + (tx + col)] = palette[indexByte]
+ filled++
+ } else {
+ // Run of palette[index & 0x7F].
+ val color = palette[indexByte and 0x7F]
+ val runLen = zi.readRunLength()
+ repeat(runLen) {
+ val pos = filled + it
+ val row = pos / tw; val col = pos % tw
+ target[(ty + row) * stride + (tx + col)] = color
+ }
+ filled += runLen
+ }
+ }
+ }
+ else -> throw IOException("ZRLE: unsupported subencoding $subenc")
+ }
+ }
+
+ /**
+ * Thin wrapper around [Inflater] that provides byte-level and CPIXEL reads.
+ * The inflater's input was already loaded by [decode]; this just drains output.
+ */
+ private inner class ZInput(private val inf: Inflater) {
+ private val buf = ByteArray(256)
+ private var pos = 0
+ private var avail = 0
+
+ private fun fill() {
+ while (avail == 0) {
+ if (inf.finished()) throw IOException("ZRLE: inflater finished early")
+ val n = inf.inflate(buf)
+ if (n > 0) { pos = 0; avail = n }
+ // n == 0 with needsInput means all input was consumed; if finished() is false
+ // but no output and needsInput, the caller overfed or the stream is malformed.
+ else if (inf.needsInput()) throw IOException("ZRLE: inflater needs more input but none queued")
+ }
+ }
+
+ fun readByte(): Int {
+ fill()
+ return buf[pos++].toInt().also { avail-- } and 0xFF
+ }
+
+ /** Read 3-byte CPIXEL (B, G, R) and return as ARGB int. */
+ fun readCpixel(): Int {
+ val b = readByte()
+ val g = readByte()
+ val r = readByte()
+ return (0xFF shl 24) or (r shl 16) or (g shl 8) or b
+ }
+
+ /**
+ * Read a ZRLE run-length (sum-of-bytes + 1).
+ * Each byte 0xFF contributes 255 and reading continues;
+ * the first byte < 0xFF ends the sequence, contributing its value.
+ * The actual run count = sum + 1.
+ */
+ fun readRunLength(): Int {
+ var total = 0
+ while (true) {
+ val b = readByte()
+ total += b
+ if (b != 0xFF) break
+ }
+ return total + 1
+ }
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/engine/avf/AvfCapabilitiesTest.kt b/app/src/test/java/com/excp/podroid/engine/avf/AvfCapabilitiesTest.kt
new file mode 100644
index 0000000..c386855
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/avf/AvfCapabilitiesTest.kt
@@ -0,0 +1,31 @@
+package com.excp.podroid.engine.avf
+
+import com.excp.podroid.engine.avf.AvfCapabilities.ProtectedVmChoice
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class AvfCapabilitiesTest {
+ @Test fun `non-protected supported chooses NonProtected`() {
+ assertEquals(ProtectedVmChoice.NonProtected, AvfCapabilities.choose(2))
+ }
+
+ @Test fun `both bits set still chooses NonProtected`() {
+ assertEquals(ProtectedVmChoice.NonProtected, AvfCapabilities.choose(3))
+ }
+
+ @Test fun `protected-only is Unsupported`() {
+ assertTrue(AvfCapabilities.choose(1) is ProtectedVmChoice.Unsupported)
+ }
+
+ @Test fun `zero capabilities is Unknown`() {
+ assertEquals(ProtectedVmChoice.Unknown, AvfCapabilities.choose(0))
+ }
+
+ @Test fun `decode formats present bits`() {
+ assertEquals("PROTECTED+NON_PROTECTED", AvfCapabilities.decode(3))
+ assertEquals("NON_PROTECTED", AvfCapabilities.decode(2))
+ assertEquals("PROTECTED", AvfCapabilities.decode(1))
+ assertEquals("none/unknown", AvfCapabilities.decode(0))
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/engine/avf/AvfReasonCodesTest.kt b/app/src/test/java/com/excp/podroid/engine/avf/AvfReasonCodesTest.kt
new file mode 100644
index 0000000..5b92971
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/avf/AvfReasonCodesTest.kt
@@ -0,0 +1,26 @@
+package com.excp.podroid.engine.avf
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class AvfReasonCodesTest {
+ @Test fun `reboot decodes to STOP_REASON_REBOOT`() {
+ assertEquals("5 STOP_REASON_REBOOT", AvfReasonCodes.stopReason(5))
+ }
+
+ @Test fun `start-failed decodes`() {
+ assertEquals("4 STOP_REASON_START_FAILED", AvfReasonCodes.stopReason(4))
+ }
+
+ @Test fun `service-died negative code decodes`() {
+ assertEquals("-1 STOP_REASON_VIRTUALIZATION_SERVICE_DIED", AvfReasonCodes.stopReason(-1))
+ }
+
+ @Test fun `unmapped stop reason is labelled`() {
+ assertEquals("99 (unmapped)", AvfReasonCodes.stopReason(99))
+ }
+
+ @Test fun `error code decodes`() {
+ assertEquals("3 ERROR_PAYLOAD_INVALID_CONFIG", AvfReasonCodes.errorCode(3))
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/x11/ResolutionPolicyTest.kt b/app/src/test/java/com/excp/podroid/x11/ResolutionPolicyTest.kt
new file mode 100644
index 0000000..ad55bee
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/x11/ResolutionPolicyTest.kt
@@ -0,0 +1,27 @@
+package com.excp.podroid.x11
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class ResolutionPolicyTest {
+ @Test fun `match returns viewport rounded to even`() {
+ assertEquals(VncSize(1080, 2336), ResolutionPolicy.target(
+ X11Settings(resolutionMode = ResolutionMode.MATCH), viewportW = 1080, viewportH = 2337))
+ }
+ @Test fun `preset returns chosen size in landscape`() {
+ val s = X11Settings(resolutionMode = ResolutionMode.PRESET, preset = ResolutionPreset.R1440P)
+ assertEquals(VncSize(2560, 1440), ResolutionPolicy.target(s, viewportW = 2337, viewportH = 1080))
+ }
+ @Test fun `preset orients to match portrait viewport`() {
+ val s = X11Settings(resolutionMode = ResolutionMode.PRESET, preset = ResolutionPreset.R1080P)
+ assertEquals(VncSize(1080, 1920), ResolutionPolicy.target(s, viewportW = 1080, viewportH = 2337))
+ }
+ @Test fun `custom returns custom dims`() {
+ val s = X11Settings(resolutionMode = ResolutionMode.CUSTOM, customW = 1600, customH = 900)
+ assertEquals(VncSize(1600, 900), ResolutionPolicy.target(s, viewportW = 1080, viewportH = 2337))
+ }
+ @Test fun `match clamps to sane minimum`() {
+ assertEquals(VncSize(320, 240), ResolutionPolicy.target(
+ X11Settings(resolutionMode = ResolutionMode.MATCH), viewportW = 10, viewportH = 8))
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt b/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
index cf80ef0..c212f72 100644
--- a/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
+++ b/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
@@ -72,10 +72,39 @@ class VncClientTest {
inp = java.io.ByteArrayInputStream(msg),
targetArgb = target,
stride = 2,
+ zrle = ZrleDecoder(),
)
// ARGB packed: 0xAARRGGBB
assertEquals(0xFFFF0000.toInt(), target[0]) // red
assertEquals(0xFF00FF00.toInt(), target[1]) // green
}
+
+ @Test fun `requestDesktopSize serializes type 251 single-screen layout`() {
+ val out = java.io.ByteArrayOutputStream()
+ VncClient.requestDesktopSize(out, screenId = 7, width = 1920, height = 1080)
+ val b = out.toByteArray()
+ assertEquals(24, b.size)
+ assertEquals(251, b[0].toInt() and 0xFF) // msg-type
+ // width @ offset 2..3, height @ 4..5 (big-endian)
+ assertEquals(1920, ((b[2].toInt() and 0xFF) shl 8) or (b[3].toInt() and 0xFF))
+ assertEquals(1080, ((b[4].toInt() and 0xFF) shl 8) or (b[5].toInt() and 0xFF))
+ assertEquals(1, b[6].toInt() and 0xFF) // number-of-screens
+ // screen id @ 8..11
+ assertEquals(7, ((b[8].toInt() and 0xFF) shl 24) or ((b[9].toInt() and 0xFF) shl 16) or ((b[10].toInt() and 0xFF) shl 8) or (b[11].toInt() and 0xFF))
+ }
+
+ @Test fun `ExtendedDesktopSize rect reports new size and writes no pixels`() {
+ // FramebufferUpdate: type=0, pad, numRects=1; rect x=0 y=0 w=800 h=600 enc=-308;
+ // body: screens=1 pad[3]; screen{id=1,x=0,y=0,w=800,h=600,flags=0}
+ val bos = java.io.ByteArrayOutputStream()
+ val d = java.io.DataOutputStream(bos)
+ d.writeByte(0); d.writeByte(0); d.writeShort(1) // msg, pad, numRects
+ d.writeShort(0); d.writeShort(0); d.writeShort(800); d.writeShort(600); d.writeInt(-308)
+ d.writeByte(1); d.writeByte(0); d.writeByte(0); d.writeByte(0) // screens=1 + pad3
+ d.writeInt(1); d.writeShort(0); d.writeShort(0); d.writeShort(800); d.writeShort(600); d.writeInt(0)
+ val target = IntArray(800 * 600)
+ val r = VncClient.readFramebufferUpdate(java.io.ByteArrayInputStream(bos.toByteArray()), target, 800, ZrleDecoder())
+ assertEquals(VncSize(800, 600), r.newSize)
+ }
}
diff --git a/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.kt b/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.kt
new file mode 100644
index 0000000..6a88e96
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.kt
@@ -0,0 +1,49 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.x11
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.io.DataInputStream
+import java.util.zip.Deflater
+
+class ZrleDecoderTest {
+ /** Encode 3-byte CPIXEL from an ARGB int: order is B, G, R (little-endian channels). */
+ private fun cpixel(argb: Int) = byteArrayOf(
+ (argb and 0xFF).toByte(), // B
+ ((argb shr 8) and 0xFF).toByte(), // G
+ ((argb shr 16) and 0xFF).toByte() // R
+ )
+
+ /** Compress plain bytes with zlib (nowrap=false = standard zlib header) and prepend 4-byte big-endian length. */
+ private fun zrleRect(plain: ByteArray): ByteArray {
+ val def = Deflater(Deflater.DEFAULT_COMPRESSION, /*nowrap=*/false)
+ def.setInput(plain); def.finish()
+ val out = java.io.ByteArrayOutputStream(); val buf = ByteArray(4096)
+ while (!def.finished()) { val n = def.deflate(buf); out.write(buf, 0, n) }
+ val z = out.toByteArray()
+ val hdr = java.nio.ByteBuffer.allocate(4).putInt(z.size).array()
+ return hdr + z
+ }
+
+ @Test fun `solid tile fills with its color`() {
+ val red = 0xFFFF0000.toInt()
+ val plain = byteArrayOf(1) + cpixel(red) // subencoding 1 = solid
+ val din = DataInputStream(ByteArrayInputStream(zrleRect(plain)))
+ val target = IntArray(4 * 4)
+ ZrleDecoder().decode(din, 0, 0, 4, 4, target, 4)
+ assertEquals(red, target[0]); assertEquals(red, target[15])
+ }
+
+ @Test fun `raw tile copies pixels`() {
+ val a = 0xFF010203.toInt(); val b = 0xFF040506.toInt()
+ val plain = byteArrayOf(0) + cpixel(a) + cpixel(b) + cpixel(a) + cpixel(b) // 2x2 raw
+ val din = DataInputStream(ByteArrayInputStream(zrleRect(plain)))
+ val target = IntArray(2 * 2)
+ ZrleDecoder().decode(din, 0, 0, 2, 2, target, 2)
+ assertEquals(a, target[0]); assertEquals(b, target[1]); assertEquals(a, target[2]); assertEquals(b, target[3])
+ }
+}
diff --git a/build-rootfs/files/etc/init.d/podroid-x11 b/build-rootfs/files/etc/init.d/podroid-x11
index f226fb9..b9da3a6 100644
--- a/build-rootfs/files/etc/init.d/podroid-x11
+++ b/build-rootfs/files/etc/init.d/podroid-x11
@@ -17,6 +17,10 @@ XVNC_LOGFILE=/var/log/xvnc.log
start() {
ebegin "Starting X11 server (Xvnc + pulseaudio)"
+ # Read per-boot DPI from the kernel cmdline token written by the Android app.
+ XVNC_DPI=$(awk -v RS=' ' -F= '/^podroid.x11.dpi=/{print $2}' /proc/cmdline 2>/dev/null)
+ [ -z "$XVNC_DPI" ] && XVNC_DPI=96
+
# /tmp lives on the persistent ext4 overlay, so a stale X server lock
# from a previous boot will block Xvnc with "Server is already active
# for display 0". Wipe both the .X0-lock file and the X11 unix socket
@@ -39,7 +43,9 @@ start() {
-SecurityTypes None \
-localhost no \
-rfbport $XVNC_PORT \
- -AlwaysShared
+ -AlwaysShared \
+ -dpi $XVNC_DPI \
+ -AcceptSetDesktopSize
# PulseAudio: system-wide-style daemon writing raw S16LE PCM to TCP 4713.
# We use --system=no with explicit XDG_RUNTIME_DIR so it runs as root