Skip to content

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

fix(x11): serialize all RFB writes, release held buttons on exit, debounce custom resolution

ExTvc9b722207dff
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 4438470..d2f73b4 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
@@ -217,6 +217,11 @@ fun X11Screen(
var svWidth by remember { mutableIntStateOf(1) }
var svHeight by remember { mutableIntStateOf(1) }
+ // Largest surface height seen for the current width: the "genuine" surface
+ // size with no IME inset. An IME dismiss grows the surface back UP TO this
+ // value, which must NOT trigger a desktop-size renegotiation; only a height
+ // beyond this baseline (or a width change) is a real surface resize.
+ var svGenuineHeight by remember { mutableIntStateOf(0) }
// Letterbox / pillarbox dst rect, pinned to top so the soft keyboard
// (and the extra-keys row) live in the empty bottom strip.
@@ -255,15 +260,21 @@ fun X11Screen(
var altActive by remember { mutableStateOf(false) }
fun sendWithModifiers(keysym: Int) {
- if (ctrlActive) viewModel.sendKey(XK_Control_L, down = true)
- if (altActive) viewModel.sendKey(XK_Alt_L, down = true)
- viewModel.sendKey(keysym, down = true)
- viewModel.sendKey(keysym, down = false)
- if (altActive) viewModel.sendKey(XK_Alt_L, down = false)
- if (ctrlActive) viewModel.sendKey(XK_Control_L, down = false)
- // One-shot: clear modifiers after one press.
+ // Snapshot then clear the one-shot modifiers BEFORE emitting, so the
+ // wrap decision and the flag reset are atomic from the caller's view: a
+ // re-entrant call (e.g. an IME diff arriving while a hardware key is mid-
+ // emit) can't observe the flag still set and double-wrap, and the up
+ // events are computed from the same snapshot that produced the downs.
+ val ctrl = ctrlActive
+ val alt = altActive
ctrlActive = false
altActive = false
+ 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)
}
fun onExtraKey(label: String) {
@@ -433,6 +444,12 @@ fun X11Screen(
) {
fun fbX(px: Float) = ((px - currentDstX) / currentDstW.coerceAtLeast(1) * currentFbW).toInt().coerceIn(0, currentFbW - 1)
fun fbY(py: Float) = ((py - currentDstY) / currentDstH.coerceAtLeast(1) * currentFbH).toInt().coerceIn(0, currentFbH - 1)
+ // True only inside the letterbox/pillarbox content rect. Used to
+ // reject DIRECT-touch taps that land in the black bars instead of
+ // clamping them to an edge pixel (which produced a phantom edge click).
+ fun inContent(px: Float, py: Float) =
+ px >= currentDstX && px < currentDstX + currentDstW &&
+ py >= currentDstY && py < currentDstY + currentDstH
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
@@ -488,6 +505,18 @@ fun X11Screen(
continue
}
+ // DIRECT touch maps absolute screen coords to the framebuffer,
+ // so a tap in the letterbox bars has no valid target: drain it
+ // as a no-op rather than clamping to an edge click. (TRACKPAD is
+ // relative: any start point is valid, so it's exempt.)
+ if (s.touchMode == TouchMode.DIRECT && !inContent(sx, sy)) {
+ 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.
@@ -572,14 +601,18 @@ fun X11Screen(
holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(h: SurfaceHolder) {}
override fun surfaceChanged(h: SurfaceHolder, f: Int, w: Int, hh: Int) {
- // Ignore height-only shrinks caused by the IME appearing;
- // those don't require a desktop resize (only a layout reflow).
- // Only send a resolution request when width changes or height
- // grows (genuine surface resize, not just keyboard insets).
+ // Ignore height changes caused by the IME opening/closing;
+ // those reflow the layout but don't change the genuine surface
+ // size. A width change resets the baseline (rotation/relayout);
+ // otherwise only a height BEYOND the largest non-IME height seen
+ // counts as a real resize. An IME dismiss grows hh back up to the
+ // baseline and is correctly skipped.
val widthChanged = w != svWidth
- val heightGrew = hh > svHeight
+ if (widthChanged) svGenuineHeight = 0
+ val heightGrew = hh > svGenuineHeight
svWidth = w
svHeight = hh
+ if (heightGrew) svGenuineHeight = hh
if (widthChanged || heightGrew) {
viewModel.requestResolution(w, hh)
}
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
index 1caa31a..4bdbc9b 100644
--- 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
@@ -17,6 +17,7 @@ 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.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -33,6 +34,8 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -251,35 +254,41 @@ private fun CustomResolutionFields(
var wText by remember(initialW) { mutableStateOf(initialW.toString()) }
var hText by remember(initialH) { mutableStateOf(initialH.toString()) }
+ // Commit only on IME Done or focus loss, not on every keystroke. Typing
+ // "1920" used to fire four SetDesktopSize renegotiations (1, 19, 192, 1920);
+ // a partial value also produced a tiny intermediate desktop. The downstream
+ // setter clamps width/height (sane max and <= 0xFFFF) so a wrap is impossible.
+ fun commit() {
+ val w = wText.toIntOrNull() ?: return
+ val h = hText.toIntOrNull() ?: return
+ onCommit(w, h)
+ }
+
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)
- },
+ onValueChange = { wText = it },
label = { Text("Width") },
singleLine = true,
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
- modifier = Modifier.weight(1f),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
+ keyboardActions = KeyboardActions(onDone = { commit() }),
+ modifier = Modifier
+ .weight(1f)
+ .onFocusChanged { if (!it.isFocused) commit() },
)
OutlinedTextField(
value = hText,
- onValueChange = { v ->
- hText = v
- val w = wText.toIntOrNull() ?: return@OutlinedTextField
- val h = v.toIntOrNull() ?: return@OutlinedTextField
- onCommit(w, h)
- },
+ onValueChange = { hText = it },
label = { Text("Height") },
singleLine = true,
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
- modifier = Modifier.weight(1f),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
+ keyboardActions = KeyboardActions(onDone = { commit() }),
+ modifier = Modifier
+ .weight(1f)
+ .onFocusChanged { if (!it.isFocused) commit() },
)
}
}
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 3a2fa80..fe5a827 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
@@ -22,7 +22,9 @@ 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.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -43,6 +45,7 @@ sealed interface X11ConnectionState {
data class Failed(val message: String) : X11ConnectionState
}
+@OptIn(ExperimentalCoroutinesApi::class)
@HiltViewModel
class X11ViewModel @Inject constructor(
val engine: VmEngine,
@@ -77,51 +80,90 @@ class X11ViewModel @Inject constructor(
private val audio = AudioStreamer()
private var sessionJob: Job? = null
- private var rfbOut: OutputStream? = null
+ @Volatile private var rfbOut: OutputStream? = null
+ @Volatile private var rfbSocket: Socket? = null
+
+ // All post-handshake RFB output (pointer, key, SetDesktopSize, and the
+ // recurring FramebufferUpdateRequest from the read loop) flows through this
+ // single-parallelism dispatcher. limitedParallelism(1) runs each launched
+ // body one-at-a-time in dispatch (submission) order; because each body is a
+ // non-suspending blocking write+flush, every RFB message is written
+ // atomically and messages keep submission order (key-down before key-up,
+ // press before release). Without this, writes on the multi-thread IO pool
+ // and the read coroutine interleaved at byte granularity, desyncing the
+ // VNC server. (The initial handshake/negotiate/first-update writes run
+ // directly before Connected, where no concurrent write is possible yet.)
+ private val rfbDispatcher: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1)
+
+ /** Submit a blocking RFB write onto the serialized writer (never blocks the caller). */
+ private fun submitRfb(block: (OutputStream) -> Unit) {
+ val out = rfbOut ?: return
+ viewModelScope.launch(rfbDispatcher) { runCatching { block(out) } }
+ }
fun connect() {
if (sessionJob?.isActive == true) return
_connection.value = X11ConnectionState.Connecting
sessionJob = viewModelScope.launch(Dispatchers.IO) {
+ val sock = Socket()
try {
- Socket().use { sock ->
- sock.connect(InetSocketAddress("127.0.0.1", X11Constants.VNC_PORT), 2000)
- val inp = sock.getInputStream()
- val out = sock.getOutputStream()
- rfbOut = out
-
- VncClient.handshake(inp, out)
- VncClient.negotiatePixelFormat(out)
- 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) {
- 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(fbLock) { 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(fbLock) {
- System.arraycopy(scratch, 0, framebuffer, 0, framebuffer.size)
- lastDamage = upd.damage
+ rfbSocket = sock
+ sock.connect(InetSocketAddress("127.0.0.1", X11Constants.VNC_PORT), 2000)
+ val inp = sock.getInputStream()
+ val out = sock.getOutputStream()
+ rfbOut = out
+ // Each RFB session is a fresh zlib stream; reset the ZRLE inflater
+ // before the read loop so a reconnect doesn't feed a finished/leftover
+ // inflater (which yields corrupt output or DataFormatException).
+ zrle.reset()
+
+ VncClient.handshake(inp, out)
+ VncClient.negotiatePixelFormat(out)
+ 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) {
+ 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)
+ // Clear damage in the same critical section that swaps the
+ // framebuffer so a recomposition between resize and the next
+ // full frame can't blit stale damage rects against the new size.
+ synchronized(fbLock) { framebuffer = fresh; lastDamage = emptyList() }
+ scratch = IntArray(fbW * fbH)
+ _fbSize.value = ns
+ cursor.value = android.graphics.Point(fbW / 2, fbH / 2)
+ // Route through the serialized writer so this full-update
+ // request can't byte-interleave with a concurrent input
+ // write. Capture the just-resized dimensions explicitly.
+ val rw = fbW; val rh = fbH
+ submitRfb { VncClient.requestFramebufferUpdate(it, w = rw, h = rh, incremental = false) }
+ return@let
}
- _frameCounter.value = _frameCounter.value + 1
- VncClient.requestFramebufferUpdate(out, w = fbW, h = fbH, incremental = true)
}
+ synchronized(fbLock) {
+ System.arraycopy(scratch, 0, framebuffer, 0, framebuffer.size)
+ lastDamage = upd.damage
+ }
+ _frameCounter.value = _frameCounter.value + 1
+ // Same serialized path as input writes: queued FIFO behind any
+ // in-flight pointer/key message rather than colliding with it on
+ // the socket. Cadence is unchanged (one request per frame); the
+ // next read() blocks until this flushes and the server responds.
+ submitRfb { VncClient.requestFramebufferUpdate(it, w = fbW, h = fbH, incremental = true) }
}
} catch (e: Exception) {
_connection.value = X11ConnectionState.Failed(e.message ?: "unknown")
} finally {
rfbOut = null
+ rfbSocket = null
+ // Close the socket on the serialized writer, queued AFTER any pending
+ // RFB writes (e.g. the button-up from disconnect()), so a teardown
+ // can't tear the socket down before a final message has flushed.
+ viewModelScope.launch(rfbDispatcher) { runCatching { sock.close() } }
audio.stop()
if (_connection.value !is X11ConnectionState.Failed) {
_connection.value = X11ConnectionState.Disconnected
@@ -131,6 +173,15 @@ class X11ViewModel @Inject constructor(
}
fun disconnect() {
+ // If a button is still held (e.g. leaving mid-drag-lock), tell the server
+ // to release it BEFORE the session/socket is torn down, otherwise the
+ // guest X server keeps the button held forever. This button-up is queued
+ // on the serialized writer; the socket close (in connect()'s finally) is
+ // queued after it, so the up flushes before the socket goes away.
+ if (heldButtons != 0) {
+ val c = cursor.value
+ submitRfb { VncClient.sendPointer(it, c.x, c.y, 0) }
+ }
heldButtons = 0
sessionJob?.cancel()
sessionJob = null
@@ -145,8 +196,7 @@ class X11ViewModel @Inject constructor(
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) } }
+ submitRfb { VncClient.requestDesktopSize(it, screenId, t.w, t.h) }
}
fun setResolutionMode(m: ResolutionMode) {
@@ -162,8 +212,13 @@ class X11ViewModel @Inject constructor(
}
fun setCustom(w: Int, h: Int) {
- viewModelScope.launch { settings.setX11Custom(w, h) }
- val explicit = x11Settings.value.copy(resolutionMode = ResolutionMode.CUSTOM, customW = w, customH = h)
+ // Clamp to a sane desktop max that also stays within the 16-bit field
+ // requestDesktopSize truncates to, so a value entered in the sheet can
+ // never wrap (e.g. 70000 -> 4464). Lower bound 1 avoids a 0-sized desktop.
+ val cw = w.coerceIn(1, MAX_RESOLUTION)
+ val ch = h.coerceIn(1, MAX_RESOLUTION)
+ viewModelScope.launch { settings.setX11Custom(cw, ch) }
+ val explicit = x11Settings.value.copy(resolutionMode = ResolutionMode.CUSTOM, customW = cw, customH = ch)
reapplyResolution(explicit)
}
@@ -199,22 +254,15 @@ class X11ViewModel @Inject constructor(
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) } }
+ submitRfb { VncClient.requestDesktopSize(it, screenId, t.w, t.h) }
}
fun sendPointer(x: Int, y: Int, buttonMask: Int) {
- val out = rfbOut ?: return
- viewModelScope.launch(Dispatchers.IO) {
- runCatching { VncClient.sendPointer(out, x, y, buttonMask) }
- }
+ submitRfb { VncClient.sendPointer(it, x, y, buttonMask) }
}
fun sendKey(keysym: Int, down: Boolean) {
- val out = rfbOut ?: return
- viewModelScope.launch(Dispatchers.IO) {
- runCatching { VncClient.sendKey(out, keysym, down) }
- }
+ submitRfb { VncClient.sendKey(it, keysym, down) }
}
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) }
@@ -238,4 +286,10 @@ class X11ViewModel @Inject constructor(
disconnect()
super.onCleared()
}
+
+ private companion object {
+ // Sane desktop ceiling; also <= 0xFFFF so a custom value never wraps the
+ // 16-bit width/height fields of the SetDesktopSize wire message.
+ const val MAX_RESOLUTION = 7680
+ }
}
diff --git a/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt b/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt
index a07f181..9c2b5ff 100644
--- a/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt
+++ b/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt
@@ -60,8 +60,7 @@ class ZrleDecoder {
* inflater produces corrupt output or a DataFormatException.
*
* Call this from the session-level connect path (X11ViewModel.connect()), not
- * from the per-rect decode path. The call site lives in a WS-2 file; this method
- * is intentionally unused after this change and will be wired in a follow-up.
+ * from the per-rect decode path.
*/
fun reset() {
inflater.reset()