A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
refactor(x11): move key mapping and pointer gestures out of the viewer screen
ExTv59cb7a064ab6
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11PointerInput.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11PointerInput.ktnew file mode 100644index 0000000..ae59f18--- /dev/null+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11PointerInput.kt@@ -0,0 +1,217 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * The touch/mouse/scroll gesture state machine for the X11 viewer surface.+ * Moved out of X11Screen.kt's AndroidView(pointerInput) as-is; see that file+ * for wiring (geometry callbacks, drag-lock state ownership).+ */+package com.excp.podroid.ui.screens.x11++import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerEventType+import androidx.compose.ui.input.pointer.PointerId+import androidx.compose.ui.input.pointer.PointerInputScope+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 com.excp.podroid.x11.TouchMode+import com.excp.podroid.x11.VncClient+import com.excp.podroid.x11.X11Settings+import kotlinx.coroutines.withTimeoutOrNull+import kotlin.math.abs++/**+ * Holds the drag-lock flag across pointerInput coroutine restarts (a+ * touch-mode / trackpad-setting change restarts the gesture coroutine; the+ * lock must survive that, same as the remembered Compose state it+ * replaces). Owned by the caller via `remember`.+ */+internal class X11PointerLockState {+ var dragLocked: Boolean = false+}++private enum class GestureOutcome { MOVE, TAP, MULTI }++/**+ * Reads events until every pointer has lifted, consuming each one. Used+ * both when a new touch arrives while drag-locked and when a DIRECT-mode+ * touch starts outside the content rect.+ */+private suspend fun AwaitPointerEventScope.drainUntilAllPointersUp() {+ while (true) {+ val e = awaitPointerEvent()+ e.changes.forEach { it.consume() }+ if (e.changes.none { it.pressed }) break+ }+}++/**+ * Runs the gesture state machine on the surface's pointerInput scope.+ * Behavior is unchanged from the original inline version: same thresholds+ * (16f move slop, 500ms long press, 60f scroll step, 28f two-finger tap+ * slop), same consume() calls, same focus-on-touch-down, same letterbox+ * rejection in DIRECT mode, same `finally` release, same order of VM calls.+ *+ * [fbX]/[fbY]/[inContent] read the caller's rememberUpdatedState-backed+ * geometry and framebuffer size fresh on every call, so a resize mid-+ * gesture updates coordinate mapping instead of being stuck with stale+ * values from when the gesture started.+ */+internal suspend fun PointerInputScope.x11PointerLoop(+ s: X11Settings,+ lockState: X11PointerLockState,+ viewModel: X11ViewModel,+ requestFocus: () -> Unit,+ fbX: (Float) -> Int,+ fbY: (Float) -> Int,+ inContent: (Float, Float) -> Boolean,+) {+ 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+ requestFocus()+ change.consume()+ // Pin the primary pointer by ID so finger-order changes don't+ // jump the cursor to a different finger.+ val primaryId: PointerId = change.id+ 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 (lockState.dragLocked) {+ viewModel.release(VncClient.BTN_LEFT)+ lockState.dragLocked = false+ drainUntilAllPointersUp()+ 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)) {+ drainUntilAllPointersUp()+ continue+ }++ if (s.touchMode == TouchMode.DIRECT) viewModel.moveTo(fbX(sx), fbY(sy))++ // Long-press (single finger, no move, ~500ms) => drag-lock.+ var outcome = GestureOutcome.MOVE+ val completed = withTimeoutOrNull(500L) {+ loop@ while (true) {+ val e = awaitPointerEvent()+ val pressed = e.changes.filter { it.pressed }+ if (pressed.isEmpty()) { outcome = GestureOutcome.TAP; break@loop }+ if (pressed.size >= 2) { maxPointers = 2; outcome = GestureOutcome.MULTI; break@loop }+ val p = (pressed.firstOrNull { it.id == primaryId } ?: pressed.first()).position+ if (abs(p.x - sx) + abs(p.y - sy) > 16f) {+ lastX = p.x+ lastY = p.y+ outcome = GestureOutcome.MOVE+ e.changes.forEach { it.consume() }+ break@loop+ }+ e.changes.forEach { it.consume() }+ }+ }+ if (completed == null) {+ lockState.dragLocked = true+ viewModel.press(VncClient.BTN_LEFT)+ leftHeld = true+ } else if (outcome == GestureOutcome.TAP) {+ viewModel.click(VncClient.BTN_LEFT)+ continue+ }++ try {+ while (true) {+ val e = awaitPointerEvent()+ val pressed = e.changes.filter { it.pressed }+ maxPointers = maxOf(maxPointers, pressed.size)+ if (pressed.isEmpty()) break+ // Track the pinned primary pointer, falling back to+ // first if it lifted (e.g. swapped fingers).+ val p = (pressed.firstOrNull { it.id == primaryId } ?: pressed.first()).position+ val dx = p.x - lastX+ val dy = p.y - lastY+ moved += abs(dx) + abs(dy)+ if (pressed.size >= 2) {+ // Transitioning 1->2 fingers: release left if held+ // so we don't send a left+scroll chord.+ if (leftHeld) { viewModel.release(VncClient.BTN_LEFT); leftHeld = false }+ 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() }+ }+ } finally {+ // Release left button on cancellation (e.g. settings-change+ // restarts the pointerInput coroutine mid-drag).+ if (leftHeld && !lockState.dragLocked) { viewModel.release(VncClient.BTN_LEFT); leftHeld = false }+ }++ if (maxPointers >= 2) {+ if (moved < 28f) viewModel.click(VncClient.BTN_RIGHT)+ } else if (s.touchMode == TouchMode.TRACKPAD && !lockState.dragLocked && moved < 16f) {+ viewModel.click(VncClient.BTN_LEFT)+ }+ if (!lockState.dragLocked && leftHeld) { viewModel.release(VncClient.BTN_LEFT); leftHeld = false }+ }+ }+}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.ktindex 9eb1fad..2720c45 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@@ -71,13 +71,6 @@ import androidx.compose.ui.input.key.KeyEventTypeimport androidx.compose.ui.input.key.keyimport androidx.compose.ui.input.key.onPreviewKeyEventimport androidx.compose.ui.input.key.type-import androidx.compose.ui.input.pointer.PointerId-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.isTertiaryPressedimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.platform.LocalView@@ -102,59 +95,15 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycleimport com.excp.podroid.Rimport com.excp.podroid.ui.components.PodroidTopBarimport kotlinx.coroutines.delay-import kotlinx.coroutines.withTimeoutOrNull-import kotlin.math.absimport com.excp.podroid.x11.RenderGeometry-import com.excp.podroid.x11.TouchMode-import com.excp.podroid.x11.VncClient+import com.excp.podroid.x11.X11Keysymimport com.excp.podroid.x11.X11SurfaceRenderer--// X11 keysyms used outside the label table.-private const val XK_BackSpace = 0xFF08-private const val XK_Tab = 0xFF09-private const val XK_Return = 0xFF0D-private const val XK_Escape = 0xFF1B-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--/**- * Maps the human-readable label used by [X11ExtraKeysRow] (matching the- * terminal's ExtraKeysRow vocabulary) to an X11 keysym. Returns null for- * pure modifier labels (CTRL/ALT) — those are handled as toggles.- */-private fun labelToKeysym(label: String): Int? = when (label) {- "ESC" -> XK_Escape- "TAB" -> XK_Tab- "LEFT" -> XK_Left- "RIGHT" -> XK_Right- "UP" -> XK_Up- "DOWN" -> XK_Down- "HOME" -> 0xFF50- "END" -> 0xFF57- "PGUP" -> 0xFF55- "PGDN" -> 0xFF56- "F1" -> 0xFFBE- "F2" -> 0xFFBF- "F3" -> 0xFFC0- "F4" -> 0xFFC1- "F5" -> 0xFFC2- "F6" -> 0xFFC3- "F7" -> 0xFFC4- "F8" -> 0xFFC5- "F9" -> 0xFFC6- "F10" -> 0xFFC7- "F11" -> 0xFFC8- "F12" -> 0xFFC9- "-" -> 0x2D- "/" -> 0x2F- "|" -> 0x7C- else -> null // CTRL / ALT handled by toggles-}+import com.excp.podroid.x11.imeDiffStrokes+import com.excp.podroid.x11.keysymForCodePoint+import com.excp.podroid.x11.keysymForHardwareChar+import com.excp.podroid.x11.labelToKeysym+import com.excp.podroid.x11.specialKeysymForKeyCode+import com.excp.podroid.x11.wrapWithModifiers@OptIn(ExperimentalMaterial3Api::class,@@ -267,7 +216,10 @@ fun X11Screen(// (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) }+ // Held in a small state holder (not a Compose mutableStateOf) because it+ // must survive x11PointerLoop's pointerInput coroutine restarts, same as+ // the remembered state it replaces.+ val pointerLockState = remember { X11PointerLockState() }var ctrlActive by remember { mutableStateOf(false) }var altActive by remember { mutableStateOf(false) }@@ -281,12 +233,9 @@ fun X11Screen(val alt = altActivectrlActive = falsealtActive = 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)+ wrapWithModifiers(keysym, shift = false, ctrl = ctrl, alt = alt).forEach {+ viewModel.sendKey(it.keysym, it.down)+ }}fun onExtraKey(label: String) {@@ -323,22 +272,7 @@ fun X11Screen(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- }+ val special = specialKeysymForKeyCode(native.keyCode)val ctrl = native.isCtrlPressed || ctrlActiveval alt = native.isAltPressed || altActiveval keysym: Int@@ -352,19 +286,12 @@ fun X11Screen((android.view.KeyEvent.META_SHIFT_ON or android.view.KeyEvent.META_CAPS_LOCK_ON))if (cased == 0) return@onPreviewKeyEvent false- // X keysyms 0x20-0x7E match ASCII verbatim; non-ASCII Unicode- // maps to 0x01000000 | codepoint (X11 protocol extension).- keysym = if (cased > 0x7E) 0x01000000 or cased else cased+ keysym = keysymForHardwareChar(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)+ wrapWithModifiers(keysym, shiftWrap, ctrl, alt).forEach {+ viewModel.sendKey(it.keysym, it.down)+ }ctrlActive = falsealtActive = falsetrue@@ -467,159 +394,21 @@ fun X11Screen(s.touchMode,s.trackpadSensitivity, s.trackpadAccel,) {- 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()- 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()- // Pin the primary pointer by ID so finger-order changes- // don't jump the cursor to a different finger.- val primaryId: PointerId = change.id- 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- }-- // 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.- 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.firstOrNull { it.id == primaryId } ?: 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- }-- try {- while (true) {- val e = awaitPointerEvent()- val pressed = e.changes.filter { it.pressed }- maxPointers = maxOf(maxPointers, pressed.size)- if (pressed.isEmpty()) break- // Track the pinned primary pointer, falling back to- // first if it lifted (e.g. swapped fingers).- val p = (pressed.firstOrNull { it.id == primaryId } ?: pressed.first()).position- val dx = p.x - lastX; val dy = p.y - lastY- moved += abs(dx) + abs(dy)- if (pressed.size >= 2) {- // Transitioning 1→2 fingers: release left if held- // so we don't send a left+scroll chord.- if (leftHeld) { viewModel.release(VncClient.BTN_LEFT); leftHeld = false }- 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() }- }- } finally {- // Release left button on cancellation (e.g. settings-change- // restarts the pointerInput coroutine mid-drag).- if (leftHeld && !dragLocked) { viewModel.release(VncClient.BTN_LEFT); leftHeld = false }- }-- 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 }- }- }+ x11PointerLoop(+ s = s,+ lockState = pointerLockState,+ viewModel = viewModel,+ requestFocus = { viewerFocus.requestFocus() },+ fbX = { px -> ((px - currentDstX) / currentDstW.coerceAtLeast(1) * currentFbW).toInt().coerceIn(0, currentFbW - 1) },+ fbY = { py -> ((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).+ inContent = { px, py ->+ px >= currentDstX && px < currentDstX + currentDstW &&+ py >= currentDstY && py < currentDstY + currentDstH+ },+ )},factory = { ctx ->SurfaceView(ctx).apply {@@ -696,11 +485,11 @@ fun X11Screen(// (e.g. tap CTRL then type L → Ctrl+L to clear the// terminal). sendWithModifiers clears the one-shot after.val cp = addedText[0].code- sendWithModifiers(if (cp in 0x20..0x7E) cp else 0x01000000 or cp)+ sendWithModifiers(keysymForCodePoint(cp))// Reset buffer after ctrl/alt combo to keep it short.imeBuf = TextFieldValue("")} else {- forwardImeDiff(old.text, new.text, viewModel)+ imeDiffStrokes(old.text, new.text).forEach { viewModel.sendKey(it.keysym, it.down) }// Keep the rolling buffer so future deletions are// observable, but cap it to avoid accumulating without bound.imeBuf = if (new.text.length > 128) TextFieldValue(new.text.takeLast(64)) else new@@ -709,8 +498,8 @@ fun X11Screen(keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),keyboardActions = KeyboardActions(onSend = {- viewModel.sendKey(XK_Return, down = true)- viewModel.sendKey(XK_Return, down = false)+ viewModel.sendKey(X11Keysym.Return, down = true)+ viewModel.sendKey(X11Keysym.Return, down = false)},),modifier = Modifier@@ -834,43 +623,3 @@ private fun X11KeyButton(.padding(horizontal = 10.dp, vertical = 8.dp),)}--/**- * Diffs old vs new IME buffer content and fires synthetic X11 key events for- * the change. ASCII 0x20-0x7E maps to the same keysym value; non-ASCII Unicode- * codepoints map to 0x01000000 | codepoint (X11 protocol extension).- *- * Works off the longest common prefix (by codepoint), not a raw length- * difference: a CJK IME REPLACES composing text on commit (pinyin "nihao" ->- * "你好"), so the new buffer shares no prefix with the old. Emitting only- * (oldCp - newCp) backspaces — the old behaviour — left the composing text in- * the guest and never sent the commit. Backspacing the whole divergent suffix- * and re-typing the new one keeps the guest buffer in sync with the IME.- */-private fun forwardImeDiff(old: String, new: String, vm: X11ViewModel) {- // Length (in chars) and codepoint count of the shared leading run.- var common = 0- var commonCp = 0- while (common < old.length && common < new.length) {- val cp = old.codePointAt(common)- if (cp != new.codePointAt(common)) break- common += Character.charCount(cp)- commonCp++- }- // Delete everything in old past the shared prefix.- val oldCp = old.codePointCount(0, old.length)- repeat(oldCp - commonCp) {- vm.sendKey(XK_BackSpace, down = true)- vm.sendKey(XK_BackSpace, down = false)- }- // Type everything in new past the shared prefix (codepoint-wise so a- // surrogate pair is sent as a single keysym).- var i = common- while (i < new.length) {- val cp = new.codePointAt(i)- val keysym = if (cp in 0x20..0x7E) cp else 0x01000000 or cp- vm.sendKey(keysym, down = true)- vm.sendKey(keysym, down = false)- i += Character.charCount(cp)- }-}diff --git a/app/src/main/java/com/excp/podroid/x11/X11Keys.kt b/app/src/main/java/com/excp/podroid/x11/X11Keys.ktnew file mode 100644index 0000000..76777ec--- /dev/null+++ b/app/src/main/java/com/excp/podroid/x11/X11Keys.kt@@ -0,0 +1,178 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * Pure key-mapping helpers for the X11 viewer: X11 keysym constants, the+ * extra-keys-row label table, the hardware-key/IME keycode-to-keysym maps,+ * and the modifier-wrapping / IME-diff logic shared by X11Screen's key paths.+ */+package com.excp.podroid.x11++import android.view.KeyEvent++/** X11 keysyms used outside the label table, and by [labelToKeysym]. */+object X11Keysym {+ const val BackSpace = 0xFF08+ const val Tab = 0xFF09+ const val Return = 0xFF0D+ const val Escape = 0xFF1B+ const val Home = 0xFF50+ const val Left = 0xFF51+ const val Up = 0xFF52+ const val Right = 0xFF53+ const val Down = 0xFF54+ const val PageUp = 0xFF55+ const val PageDown = 0xFF56+ const val End = 0xFF57+ const val Delete = 0xFFFF+ const val F1 = 0xFFBE+ const val F2 = 0xFFBF+ const val F3 = 0xFFC0+ const val F4 = 0xFFC1+ const val F5 = 0xFFC2+ const val F6 = 0xFFC3+ const val F7 = 0xFFC4+ const val F8 = 0xFFC5+ const val F9 = 0xFFC6+ const val F10 = 0xFFC7+ const val F11 = 0xFFC8+ const val F12 = 0xFFC9+ const val Shift_L = 0xFFE1+ const val Control_L = 0xFFE3+ const val Alt_L = 0xFFE9+}++/**+ * Maps the human-readable label used by X11ExtraKeysRow (matching the+ * terminal's ExtraKeysRow vocabulary) to an X11 keysym. Returns null for+ * pure modifier labels (CTRL/ALT) - those are handled as toggles.+ */+fun labelToKeysym(label: String): Int? = when (label) {+ "ESC" -> X11Keysym.Escape+ "TAB" -> X11Keysym.Tab+ "LEFT" -> X11Keysym.Left+ "RIGHT" -> X11Keysym.Right+ "UP" -> X11Keysym.Up+ "DOWN" -> X11Keysym.Down+ "HOME" -> X11Keysym.Home+ "END" -> X11Keysym.End+ "PGUP" -> X11Keysym.PageUp+ "PGDN" -> X11Keysym.PageDown+ "F1" -> X11Keysym.F1+ "F2" -> X11Keysym.F2+ "F3" -> X11Keysym.F3+ "F4" -> X11Keysym.F4+ "F5" -> X11Keysym.F5+ "F6" -> X11Keysym.F6+ "F7" -> X11Keysym.F7+ "F8" -> X11Keysym.F8+ "F9" -> X11Keysym.F9+ "F10" -> X11Keysym.F10+ "F11" -> X11Keysym.F11+ "F12" -> X11Keysym.F12+ "-" -> 0x2D+ "/" -> 0x2F+ "|" -> 0x7C+ else -> null // CTRL / ALT handled by toggles+}++/**+ * Maps a Compose/IME codepoint to an X11 keysym: ASCII 0x20-0x7E matches+ * verbatim, non-ASCII Unicode maps to 0x01000000 | codepoint (X11 protocol+ * extension). Used by the IME path and the sticky-CTRL/ALT + IME-char combo.+ */+fun keysymForCodePoint(cp: Int): Int = if (cp in 0x20..0x7E) cp else 0x01000000 or cp++/**+ * Same X11 protocol extension as [keysymForCodePoint], but for the hardware-+ * keyboard path, which derives its char from `KeyEvent.getUnicodeChar` and+ * historically lets control characters below 0x20 pass through raw (that+ * input never produces a value in 0x20..0x7E for those chars, so the two+ * functions diverge only below 0x20). Kept separate rather than merged so a+ * future change to one path doesn't silently change the other.+ */+fun keysymForHardwareChar(cased: Int): Int = if (cased > 0x7E) 0x01000000 or cased else cased++/**+ * Hardware/external-keyboard special keys that map to a fixed X11 keysym+ * regardless of layout, keyed by the underlying Android keycode (the value+ * behind the Compose `Key` constants X11Screen used to switch on).+ */+fun specialKeysymForKeyCode(keyCode: Int): Int? = when (keyCode) {+ KeyEvent.KEYCODE_DEL -> X11Keysym.BackSpace+ KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> X11Keysym.Return+ KeyEvent.KEYCODE_TAB -> X11Keysym.Tab+ KeyEvent.KEYCODE_ESCAPE -> X11Keysym.Escape+ KeyEvent.KEYCODE_DPAD_LEFT -> X11Keysym.Left+ KeyEvent.KEYCODE_DPAD_RIGHT -> X11Keysym.Right+ KeyEvent.KEYCODE_DPAD_UP -> X11Keysym.Up+ KeyEvent.KEYCODE_DPAD_DOWN -> X11Keysym.Down+ KeyEvent.KEYCODE_MOVE_HOME -> X11Keysym.Home+ KeyEvent.KEYCODE_MOVE_END -> X11Keysym.End+ KeyEvent.KEYCODE_PAGE_UP -> X11Keysym.PageUp+ KeyEvent.KEYCODE_PAGE_DOWN -> X11Keysym.PageDown+ KeyEvent.KEYCODE_FORWARD_DEL -> X11Keysym.Delete+ else -> null+}++/** One synthetic X11 key event: [keysym] going down or up. */+data class KeyStroke(val keysym: Int, val down: Boolean)++/**+ * Wraps [keysym] with the requested modifiers in today's order: Shift down,+ * Ctrl down, Alt down, key down, key up, Alt up, Ctrl up, Shift up (absent+ * modifiers are omitted). Used by both the extra-keys/sticky-modifier path+ * (shift is always false there) and the hardware-key handler.+ */+fun wrapWithModifiers(keysym: Int, shift: Boolean, ctrl: Boolean, alt: Boolean): List<KeyStroke> {+ val strokes = mutableListOf<KeyStroke>()+ if (shift) strokes += KeyStroke(X11Keysym.Shift_L, down = true)+ if (ctrl) strokes += KeyStroke(X11Keysym.Control_L, down = true)+ if (alt) strokes += KeyStroke(X11Keysym.Alt_L, down = true)+ strokes += KeyStroke(keysym, down = true)+ strokes += KeyStroke(keysym, down = false)+ if (alt) strokes += KeyStroke(X11Keysym.Alt_L, down = false)+ if (ctrl) strokes += KeyStroke(X11Keysym.Control_L, down = false)+ if (shift) strokes += KeyStroke(X11Keysym.Shift_L, down = false)+ return strokes+}++/**+ * Diffs old vs new IME buffer content into the key strokes needed to bring+ * the guest buffer in sync. Works off the longest common prefix (by+ * codepoint), not a raw length difference: a CJK IME REPLACES composing+ * text on commit (pinyin "nihao" -> "你好"), so the new buffer shares no+ * prefix with the old. Emitting only (oldCp - newCp) backspaces - the old+ * behaviour - left the composing text in the guest and never sent the+ * commit. Backspacing the whole divergent suffix and re-typing the new one+ * keeps the guest buffer in sync with the IME.+ */+fun imeDiffStrokes(old: String, new: String): List<KeyStroke> {+ // Length (in chars) and codepoint count of the shared leading run.+ var common = 0+ var commonCp = 0+ while (common < old.length && common < new.length) {+ val cp = old.codePointAt(common)+ if (cp != new.codePointAt(common)) break+ common += Character.charCount(cp)+ commonCp+++ }+ val strokes = mutableListOf<KeyStroke>()+ // Delete everything in old past the shared prefix.+ val oldCp = old.codePointCount(0, old.length)+ repeat(oldCp - commonCp) {+ strokes += KeyStroke(X11Keysym.BackSpace, down = true)+ strokes += KeyStroke(X11Keysym.BackSpace, down = false)+ }+ // Type everything in new past the shared prefix (codepoint-wise so a+ // surrogate pair is sent as a single keysym).+ var i = common+ while (i < new.length) {+ val cp = new.codePointAt(i)+ val keysym = keysymForCodePoint(cp)+ strokes += KeyStroke(keysym, down = true)+ strokes += KeyStroke(keysym, down = false)+ i += Character.charCount(cp)+ }+ return strokes+}diff --git a/app/src/test/java/com/excp/podroid/x11/X11KeysTest.kt b/app/src/test/java/com/excp/podroid/x11/X11KeysTest.ktnew file mode 100644index 0000000..4e47c55--- /dev/null+++ b/app/src/test/java/com/excp/podroid/x11/X11KeysTest.kt@@ -0,0 +1,106 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ */+package com.excp.podroid.x11++import android.view.KeyEvent+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class X11KeysTest {++ @Test fun `labelToKeysym maps named labels to their X11 keysym`() {+ assertEquals(X11Keysym.Escape, labelToKeysym("ESC"))+ assertEquals(X11Keysym.F12, labelToKeysym("F12"))+ assertEquals(0x7C, labelToKeysym("|"))+ }++ @Test fun `labelToKeysym returns null for the sticky-modifier labels`() {+ assertNull(labelToKeysym("CTRL"))+ }++ @Test fun `specialKeysymForKeyCode maps the hardware special keys`() {+ assertEquals(X11Keysym.BackSpace, specialKeysymForKeyCode(KeyEvent.KEYCODE_DEL))+ assertEquals(X11Keysym.Delete, specialKeysymForKeyCode(KeyEvent.KEYCODE_FORWARD_DEL))+ assertEquals(X11Keysym.Return, specialKeysymForKeyCode(KeyEvent.KEYCODE_NUMPAD_ENTER))+ }++ @Test fun `specialKeysymForKeyCode returns null for an unmapped keycode`() {+ assertNull(specialKeysymForKeyCode(KeyEvent.KEYCODE_A))+ }++ @Test fun `keysymForCodePoint passes ASCII through and maps non-ASCII to the extension range`() {+ assertEquals('a'.code, keysymForCodePoint('a'.code))+ assertEquals('~'.code, keysymForCodePoint('~'.code))+ assertEquals(0x01000000 or 0xE9, keysymForCodePoint(0xE9))+ assertEquals(0x01000000 or 0x1F600, keysymForCodePoint(0x1F600))+ }++ @Test fun `wrapWithModifiers with no modifiers is just down then up`() {+ val strokes = wrapWithModifiers(0x61, shift = false, ctrl = false, alt = false)++ assertEquals(listOf(KeyStroke(0x61, true), KeyStroke(0x61, false)), strokes)+ }++ @Test fun `wrapWithModifiers with all three modifiers wraps in shift ctrl alt order`() {+ val strokes = wrapWithModifiers(0x61, shift = true, ctrl = true, alt = true)++ assertEquals(+ listOf(+ KeyStroke(X11Keysym.Shift_L, true),+ KeyStroke(X11Keysym.Control_L, true),+ KeyStroke(X11Keysym.Alt_L, true),+ KeyStroke(0x61, true),+ KeyStroke(0x61, false),+ KeyStroke(X11Keysym.Alt_L, false),+ KeyStroke(X11Keysym.Control_L, false),+ KeyStroke(X11Keysym.Shift_L, false),+ ),+ strokes,+ )+ }++ @Test fun `imeDiffStrokes for an append only types the added suffix`() {+ val strokes = imeDiffStrokes("ab", "abc")++ assertEquals(listOf(KeyStroke('c'.code, true), KeyStroke('c'.code, false)), strokes)+ }++ @Test fun `imeDiffStrokes for a backspace sends one backspace pair`() {+ val strokes = imeDiffStrokes("abc", "ab")++ assertEquals(listOf(KeyStroke(X11Keysym.BackSpace, true), KeyStroke(X11Keysym.BackSpace, false)), strokes)+ }++ @Test fun `imeDiffStrokes for a CJK commit backspaces the whole old run then types the new one`() {+ // Pinyin "nihao" (5 chars, no shared prefix) commits to "你好" (2 chars).+ val strokes = imeDiffStrokes("nihao", "你好")++ val backspaces = strokes.take(10)+ assertEquals(List(10) { KeyStroke(X11Keysym.BackSpace, it % 2 == 0) }, backspaces)+ assertEquals(+ listOf(+ KeyStroke(0x01000000 or 0x4f60, true),+ KeyStroke(0x01000000 or 0x4f60, false),+ KeyStroke(0x01000000 or 0x597d, true),+ KeyStroke(0x01000000 or 0x597d, false),+ ),+ strokes.drop(10),+ )+ }++ @Test fun `imeDiffStrokes counts an appended surrogate pair as a single keysym`() {+ val emoji = String(Character.toChars(0x1F600))+ val strokes = imeDiffStrokes("", emoji)++ val keysym = 0x01000000 or 0x1F600+ assertEquals(listOf(KeyStroke(keysym, true), KeyStroke(keysym, false)), strokes)+ }++ @Test fun `imeDiffStrokes for identical strings is empty`() {+ assertTrue(imeDiffStrokes("same", "same").isEmpty())+ }+}