Restore Chinese input for Android and Steam keyboards (#1529)

Commit Android IME text through the focused renderer and submit only after delivery is confirmed. Restore Steam pinyin on Ubuntu rc7 and allow older runtimes to start normally without IBus.
This commit is contained in:
danyi authored and GitHub committed 2026-12-03 07:36:55 -05:00
1 parent e935263ccb
commit eeb10e02fd
46 files changed
+5582 -104

No files matched your search

@@ -76,6 +76,7 @@ import com.droiddeck.launcher.input.InputSpace
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.SessionClipboard
import com.droiddeck.launcher.input.SessionTextInput
import com.droiddeck.launcher.input.OnScreenControls
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.InputRouter
@@ -349,6 +350,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
}
}
private val sessionTextInput by lazy {
SessionTextInput(this) {
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
}
}
private var watching = true
private lateinit var touchpad: TouchpadGestures
private lateinit var directTouchHold: DirectTouchHold
@@ -997,7 +1003,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
root.addView(controls)
}
keyboard = KeyboardHost(this).also { host ->
keyboard = KeyboardHost(this, sendKeyEvent = ::dispatchImeKeyEvent, sendText = WaylandCompositor::textInputCommit).also { host ->
host.onImeChanged = ::onPrimaryImeChanged
root.addView(host)
}
@@ -3801,16 +3807,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
internal fun dispatchImeKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = true)
override fun dispatchKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = false)
private fun dispatchKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event)
if (normalized === event) return dispatchSessionKeyEvent(event)
if (normalized === event) return dispatchSessionKeyEvent(event, orderedImeKey)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}")
}
return dispatchSessionKeyEvent(normalized)
return dispatchSessionKeyEvent(normalized, orderedImeKey)
}
private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean {
private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
@@ -3893,7 +3903,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
return true
}
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
if (pad !== event) return dispatchKeyEvent(pad, orderedImeKey)
val fromController = PadBridge.isControllerKeyEvent(event)
if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
padBridge?.setInputEnabled(false)
@@ -3976,7 +3986,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val down = event.action == KeyEvent.ACTION_DOWN
if (down && event.repeatCount > 0) return true
val owner = if (event.deviceId <= 0) 16 else 8
if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner) }) return true
if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner, orderedImeKey) }) return true
}
return super.dispatchKeyEvent(event)
}
@@ -5270,27 +5280,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else {
endGameField()
}
host.type(text)
host.tap(KeyEvent.KEYCODE_ENTER)
if (text.isEmpty()) host.tap(KeyEvent.KEYCODE_ENTER)
else WaylandCompositor.textInputCommitAndSubmit(text)
uiHandler.postDelayed({
if (AgentGuest.gameTextField && com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) endGameField()
}, FIELD_SETTLE_MS)
}
private fun endGameField() {
WaylandCompositor.nativeSendKey(KEY_END, 1)
WaylandCompositor.nativeSendKey(KEY_END, 0)
orderedImeKeySender(KEY_END, true)
orderedImeKeySender(KEY_END, false)
}
private fun selectGameField(vararg then: Int) {
heldKeys.set(256, KEY_LEFTCTRL, true)
try {
for (key in intArrayOf(KEY_A) + then) {
heldKeys.set(256, key, true)
heldKeys.set(256, key, false)
}
} finally { heldKeys.release(256) }
}
private fun selectGameField(copy: Boolean = false) { WaylandCompositor.nativeSelectGameField(copy) }
private fun readGameField(done: (String?) -> Unit) {
val opened = wowChat.request
@@ -5299,7 +5301,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (text != null && stillOpen()) endGameField()
done(text)
}
selectGameField(KEY_C)
selectGameField(copy = true)
}
private fun cancelWowChat() {
@@ -6202,11 +6204,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
releaseHeldKeys()
}
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1, orderedImeKey: Boolean = false) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
if (owner == 1) { if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) }
heldKeys.set(owner, code, down)
val orderedSender = if (orderedImeKey) orderedImeKeySender else null
heldKeys.set(owner, code, down, orderedSender)
}
private val orderedImeKeySender: (Int, Boolean) -> Unit = { code, down ->
WaylandCompositor.nativeSendKeyOrdered(code, if (down) 1 else 0)
}
private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) {
@@ -6389,6 +6396,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldButtons.clear()
hidePrimaryKeyboard()
sessionClipboard.stop()
sessionTextInput.stop()
padMotion?.stop()
cursorVisible = false
closeSecondScreen(reset = false)
@@ -6404,7 +6412,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (!isFinishing && !isDestroyed) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
updateOnScreenControls()
if (resumed) { sessionClipboard.start(); updatePadMotion() }
if (resumed) { sessionClipboard.start(); sessionTextInput.start(); updatePadMotion() }
if (started) {
settleDualScreenControls()
refreshSecondScreenDisplays()
@@ -6475,6 +6483,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
contentResolver.unregisterContentObserver(refreshSettingObserver)
if (!screenIsOff()) closeSecondScreen(reset = false)
sessionTextInput.stop()
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
updateBottomGame()
@@ -6554,7 +6563,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onCancel = { padBridge?.cancelHomeGuide() },
)
updatePointerCapture()
if (!pipUi) sessionClipboard.start()
if (!pipUi) { sessionClipboard.start(); sessionTextInput.start() }
updatePadMotion()
ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener)
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener)
@@ -7285,6 +7294,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
gamescopeConvarRequests.shutdownNow()
backQamInput.cancel()
steamVrRecovery.close()
sessionTextInput.stop()
uiHandler.removeCallbacks(steamTouchRetry)
uiHandler.removeCallbacks(cursorResync)
uiHandler.removeCallbacks(usbMouseFallback)
@@ -2,14 +2,24 @@ package com.droiddeck.launcher.input
class HeldInput(private val emit: (Int, Boolean) -> Unit) {
private val owners = IntArray(768)
private val ordered = arrayOfNulls<(Int, Boolean) -> Unit>(768)
@Synchronized
fun set(source: Int, code: Int, down: Boolean) {
fun set(source: Int, code: Int, down: Boolean, orderedEmit: ((Int, Boolean) -> Unit)? = null) {
if (code !in owners.indices) return
val before = owners[code]
val after = if (down) before or source else before and source.inv()
owners[code] = after
if ((before == 0) != (after == 0)) emit(code, after != 0)
if ((before == 0) != (after == 0)) {
if (after != 0) {
ordered[code] = orderedEmit
orderedEmit?.invoke(code, true) ?: emit(code, true)
} else {
val fn = ordered[code]
ordered[code] = null
fn?.invoke(code, false) ?: emit(code, false)
}
}
}
@Synchronized
@@ -21,7 +31,9 @@ class HeldInput(private val emit: (Int, Boolean) -> Unit) {
fun clear() {
for (code in owners.indices) if (owners[code] != 0) {
owners[code] = 0
emit(code, false)
val fn = ordered[code]
ordered[code] = null
fn?.invoke(code, false) ?: emit(code, false)
}
}
}
@@ -4,7 +4,6 @@ import android.app.Activity
import android.content.Context
import android.os.Build
import android.text.InputType
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.WindowInsets
@@ -12,15 +11,17 @@ import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
import com.droiddeck.launcher.wayland.WaylandCompositor
class KeyboardHost(
context: Context,
private val sendKeyEvent: (KeyEvent) -> Boolean,
private val sendText: (String) -> Unit,
) : View(context) {
constructor(activity: Activity) : this(activity, { activity.dispatchKeyEvent(it) })
constructor(activity: Activity) :
this(activity, { activity.dispatchKeyEvent(it) }, { WaylandCompositor.textInputCommit(it) })
private val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
var shown = false
private set
var imeShowing = false
@@ -40,8 +41,7 @@ class KeyboardHost(
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
if (!shown) return null
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
outAttrs.inputType = InputType.TYPE_CLASS_TEXT
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_FULLSCREEN or
EditorInfo.IME_FLAG_NO_EXTRACT_UI
return KeyConnection()
@@ -93,45 +93,153 @@ class KeyboardHost(
fun type(text: CharSequence?) {
if (text.isNullOrEmpty()) return
val events = map.getEvents(text.toString().toCharArray())
if (events != null) {
for (event in events) sendKeyEvent(event)
} else {
for (ch in text) {
val t = System.currentTimeMillis()
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
sendKeyEvent(CharKeyEvent(down, ch))
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
}
}
// Text and soft editing actions share this queue to preserve IME ordering.
sendText(text.toString())
}
fun tap(keyCode: Int) {
val control = softControl(keyCode)
if (control != null) {
sendText(control.toString())
return
}
val t = System.currentTimeMillis()
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
}
private inner class KeyConnection : BaseInputConnection(this, false) {
// A press keeps the route chosen on its first down across repeats and the matching up.
private val controlRoutes = HashMap<Int, Boolean>()
private var composingText = ""
private var composingCursor = 0
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
composingText = ""
composingCursor = 0
type(text)
return true
}
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = true
override fun finishComposingText(): Boolean = true
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
repeat(beforeLength) { tap(KeyEvent.KEYCODE_DEL) }
repeat(afterLength) { tap(KeyEvent.KEYCODE_FORWARD_DEL) }
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
composingText = text?.toString().orEmpty()
val rawCursor = if (newCursorPosition > 0) {
composingText.length.toLong() + newCursorPosition - 1L
} else {
newCursorPosition.toLong()
}
composingCursor = rawCursor.coerceIn(0L, composingText.length.toLong()).toInt()
return true
}
override fun sendKeyEvent(event: KeyEvent): Boolean = this@KeyboardHost.sendKeyEvent(event)
override fun finishComposingText(): Boolean {
val text = composingText
composingText = ""
composingCursor = 0
type(text)
return true
}
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
val before = beforeLength.coerceAtLeast(0)
val after = afterLength.coerceAtLeast(0)
if (before == 0 && after == 0) return true
val consumedBefore = minOf(before, composingCursor)
val consumedAfter = minOf(after, composingText.length - composingCursor)
val guestBefore = before - consumedBefore
val guestAfter = after - consumedAfter
if (guestBefore > 1 || guestAfter > 1) return false
return applyDeletion(
composingCursor - consumedBefore,
composingCursor + consumedAfter,
guestBefore,
guestAfter,
)
}
override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean {
val before = beforeLength.coerceAtLeast(0)
val after = afterLength.coerceAtLeast(0)
if (before == 0 && after == 0) return true
if (splitsPair(composingCursor)) return false
val text = composingText
val beforePoints = Character.codePointCount(text, 0, composingCursor)
val afterPoints = Character.codePointCount(text, composingCursor, text.length)
val consumedBefore = minOf(before, beforePoints)
val consumedAfter = minOf(after, afterPoints)
val start = Character.offsetByCodePoints(text, composingCursor, -consumedBefore)
val end = Character.offsetByCodePoints(text, composingCursor, consumedAfter)
if (hasUnpairedSurrogate(text, start, end)) return false
return applyDeletion(
start,
end,
before - consumedBefore,
after - consumedAfter,
)
}
private fun applyDeletion(start: Int, end: Int, guestBefore: Int, guestAfter: Int): Boolean {
if (guestBefore > 64 || guestAfter > 64) return false
if (splitsPair(start) || splitsPair(end)) return false
if (start < end) {
composingText = composingText.removeRange(start, end)
composingCursor = start
}
val controls = StringBuilder()
repeat(guestBefore) { controls.append(BACKSPACE) }
repeat(guestAfter) { controls.append(FORWARD_DELETE) }
if (controls.isNotEmpty()) sendText(controls.toString())
return true
}
private fun splitsPair(index: Int): Boolean =
index > 0 && index < composingText.length &&
composingText[index - 1].isHighSurrogate() && composingText[index].isLowSurrogate()
private fun hasUnpairedSurrogate(text: CharSequence, start: Int, end: Int): Boolean {
var i = start
while (i < end) {
val c = text[i]
if (c.isHighSurrogate()) {
if (i + 1 >= end || !text[i + 1].isLowSurrogate()) return true
i += 2
} else if (c.isLowSurrogate()) {
return true
} else {
i++
}
}
return false
}
override fun sendKeyEvent(event: KeyEvent): Boolean {
val control = softControl(event.keyCode)
if (control == null) return this@KeyboardHost.sendKeyEvent(event)
if (event.action == KeyEvent.ACTION_DOWN) {
val soft = if (event.repeatCount == 0) {
val route = !event.isModified()
controlRoutes[event.keyCode] = route
route
} else {
controlRoutes[event.keyCode] ?: !event.isModified()
}
if (!soft) return this@KeyboardHost.sendKeyEvent(event)
if (control == ENTER) finishComposingText()
sendText(control.toString())
return true
}
if (event.action == KeyEvent.ACTION_UP) {
val soft = controlRoutes.remove(event.keyCode) ?: !event.isModified()
if (soft) return true
return this@KeyboardHost.sendKeyEvent(event)
}
return this@KeyboardHost.sendKeyEvent(event)
}
override fun performEditorAction(actionCode: Int): Boolean {
tap(KeyEvent.KEYCODE_ENTER)
finishComposingText()
sendText(ENTER.toString())
return true
}
@@ -140,8 +248,22 @@ class KeyboardHost(
override fun getSelectedText(flags: Int): CharSequence? = null
}
private class CharKeyEvent(origin: KeyEvent, private val ch: Char) : KeyEvent(origin) {
override fun getUnicodeChar(): Int = ch.code
override fun getUnicodeChar(metaState: Int): Int = ch.code
private fun softControl(keyCode: Int): Char? = when (keyCode) {
KeyEvent.KEYCODE_DEL -> BACKSPACE
KeyEvent.KEYCODE_FORWARD_DEL -> FORWARD_DELETE
KeyEvent.KEYCODE_ENTER -> ENTER
KeyEvent.KEYCODE_TAB -> TAB
else -> null
}
private fun KeyEvent.isModified(): Boolean =
isCtrlPressed || isShiftPressed || isAltPressed || isMetaPressed
private companion object {
// Control characters represent editing keys on the guest text channel.
const val ENTER = '\r'
const val BACKSPACE = '\b'
const val FORWARD_DELETE = '\u007f'
const val TAB = '\t'
}
}
@@ -0,0 +1,327 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.IOException
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
private enum class TextDelivery(val result: Int) {
NOT_DELIVERED(WaylandCompositor.TEXT_NOT_DELIVERED),
DELIVERED(WaylandCompositor.TEXT_DELIVERED),
UNRESOLVED(WaylandCompositor.TEXT_UNRESOLVED),
}
class SessionTextInput(context: Context, private val hasFocus: () -> Boolean) {
private val delivery = deliveryFor(context)
private val owner = Any()
fun start() = delivery.start(owner, hasFocus)
fun stop() = delivery.stop(owner)
private companion object {
private var instance: SessionTextDelivery? = null
@Synchronized private fun deliveryFor(context: Context): SessionTextDelivery =
instance ?: SessionTextDelivery(context.applicationContext).also { instance = it }
}
}
private class SessionTextDelivery(private val appContext: Context) {
private val handler = Handler(Looper.getMainLooper())
private val lock = Any()
private var generation = 0L
@Volatile private var active = false
private var owner: Any? = null
private var focusCheck: (() -> Boolean)? = null
private var executor: ScheduledThreadPoolExecutor? = null
private var socket: LocalSocket? = null
private var pendingToken = 0
private var runningToken = 0
private var failedToken = 0
private val guestListener = object : WaylandCompositor.TextInputFallbackListener {
override fun onTextInputFallback(text: String, token: Int): Boolean {
synchronized(lock) {
if (!active || pendingToken != 0 || failedToken != 0 || token <= 0) return false
val received = generation
pendingToken = token
val posted = try {
handler.post { enqueue(text, received, token) }
} catch (e: RuntimeException) {
false
}
if (!posted) pendingToken = 0
return posted
}
}
}
fun start(nextOwner: Any, hasFocus: () -> Boolean) {
val previous = synchronized(lock) {
if (owner === nextOwner) return
owner
}
if (previous != null) stop(previous)
val queue = ScheduledThreadPoolExecutor(1) { runnable ->
Thread(runnable, "session-text-input").apply { isDaemon = true }
}
queue.executeExistingDelayedTasksAfterShutdownPolicy = false
synchronized(lock) {
this.owner = nextOwner
focusCheck = hasFocus
active = true
executor = queue
if (failedToken != 0) scheduleRetryLocked(failedToken, INITIAL_DELAY_MS)
}
WaylandCompositor.setTextInputFallbackListener(guestListener)
}
fun stop(oldOwner: Any) {
val detached = synchronized(lock) {
if (owner !== oldOwner) return
owner = null
focusCheck = null
active = false
generation += 1
val queue = executor
val open = socket
val token = if (runningToken == 0 && failedToken == 0) pendingToken else 0
executor = null
socket = null
Triple(queue, open, token)
}
WaylandCompositor.clearTextInputFallbackListener(guestListener)
handler.removeCallbacksAndMessages(null)
detached.second?.let { requestCancel(it) }
detached.first?.shutdown()
if (detached.third != 0) complete(detached.third)
}
private fun enqueue(text: String, received: Long, token: Int) {
val currentFocus = synchronized(lock) { if (active && generation == received) focusCheck else null }
if (currentFocus == null || !currentFocus() || !WaylandCompositor.isTextInputFallbackListener(guestListener)) {
Log.d(TAG, "guest text fallback skipped outside the active focused session")
complete(token)
return
}
val bytes = text.toByteArray(Charsets.UTF_8)
if (bytes.isEmpty() || bytes.size > MAX_BYTES) {
complete(token)
return
}
val queue = synchronized(lock) {
if (active && generation == received) executor else null
}
if (queue == null) {
complete(token)
return
}
try {
queue.execute {
try {
val delivery = send(bytes, received, token)
if (delivery == TextDelivery.UNRESOLVED) recover(token)
else complete(token, delivery)
} finally {
releaseRunning(token)
}
}
} catch (e: RejectedExecutionException) {
complete(token)
}
}
private fun recover(token: Int) {
if (probe()) {
complete(token)
return
}
val marked = synchronized(lock) {
if (pendingToken == token && failedToken == 0) {
failedToken = token
WaylandCompositor.completeTextInputFallback(token, TextDelivery.UNRESOLVED.result)
scheduleRetryLocked(token, INITIAL_DELAY_MS)
true
} else {
false
}
}
if (marked) Log.w(TAG, "text injection could not be confirmed")
}
private fun scheduleRetryLocked(token: Int, delayMs: Long) {
if (!active || failedToken != token || pendingToken != token) return
val queue = executor ?: return
val current = generation
try {
queue.schedule({ retryProbe(current, token, delayMs) }, delayMs, TimeUnit.MILLISECONDS)
} catch (e: RejectedExecutionException) {
}
}
private fun retryProbe(received: Long, token: Int, delayMs: Long) {
val ready = synchronized(lock) {
active && generation == received && failedToken == token && pendingToken == token
}
if (!ready) return
val proven = probe()
val owned = synchronized(lock) {
if (proven) {
if (active && generation == received && failedToken == token && pendingToken == token) {
pendingToken = 0
runningToken = 0
failedToken = 0
true
} else {
false
}
} else {
if (active && generation == received && failedToken == token && pendingToken == token) {
val next = (delayMs * 2).coerceAtMost(MAX_DELAY_MS)
scheduleRetryLocked(token, next)
}
false
}
}
if (owned) WaylandCompositor.completeTextInputFallback(token, TextDelivery.NOT_DELIVERED.result)
}
private fun probe(): Boolean {
val live = LocalSocket()
return try {
live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM))
live.soTimeout = TIMEOUT_MS
val out = live.outputStream
out.write(lengthPrefix(0))
out.flush()
live.inputStream.read() == 0
} catch (e: IOException) {
Log.w(TAG, "could not probe guest text input state", e)
false
} finally {
close(live)
}
}
private fun complete(token: Int, delivery: TextDelivery = TextDelivery.NOT_DELIVERED) {
val owned = synchronized(lock) {
if (pendingToken == token) {
pendingToken = 0
runningToken = 0
failedToken = 0
true
} else {
false
}
}
if (owned) WaylandCompositor.completeTextInputFallback(token, delivery.result)
}
private fun releaseRunning(token: Int) {
synchronized(lock) {
if (runningToken == token) runningToken = 0
}
}
private fun send(bytes: ByteArray, received: Long, token: Int): TextDelivery {
val live = LocalSocket()
if (!claim(live, received, token)) {
close(live)
return TextDelivery.NOT_DELIVERED
}
var requested = false
try {
live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM))
live.soTimeout = TIMEOUT_MS
if (!isCurrent(received)) return TextDelivery.NOT_DELIVERED
val out = live.outputStream
out.write(lengthPrefix(bytes.size))
requested = true
out.write(bytes)
out.flush()
val input = live.inputStream
val ack = try {
input.read()
} catch (e: IOException) {
// Android may report a socket read timeout as a plain IOException.
requestCancel(live)
input.read()
}
if (ack == 0) Log.d(TAG, "guest did not complete text delivery")
if (ack != 0 && ack != 1 && isCurrent(received)) Log.w(TAG, "guest did not acknowledge text delivery")
return when (ack) {
1 -> TextDelivery.DELIVERED
0 -> TextDelivery.NOT_DELIVERED
else -> TextDelivery.UNRESOLVED
}
} catch (e: IOException) {
if (isCurrent(received)) Log.w(TAG, "could not hand text to the guest", e)
if (!requested) return TextDelivery.NOT_DELIVERED
return TextDelivery.UNRESOLVED
} finally {
release(live)
close(live)
}
}
private fun requestCancel(live: LocalSocket) {
try {
live.shutdownOutput()
} catch (e: IOException) {
Log.w(TAG, "could not request guest text input cancellation", e)
}
}
private fun isCurrent(received: Long) = synchronized(lock) { active && generation == received }
private fun claim(live: LocalSocket, received: Long, token: Int) = synchronized(lock) {
if (!active || generation != received || pendingToken != token || runningToken != 0 || failedToken != 0) {
false
} else {
runningToken = token
socket = live
true
}
}
private fun release(live: LocalSocket) {
synchronized(lock) {
if (socket === live) socket = null
}
}
private fun endpoint(): File = File(LinuxRuntime.sessionRoot(appContext), "text-input.sock")
private fun lengthPrefix(size: Int): ByteArray {
val flagged = if (size == 0) size else size or Int.MIN_VALUE
return byteArrayOf(
(flagged ushr 24).toByte(),
(flagged ushr 16).toByte(),
(flagged ushr 8).toByte(),
flagged.toByte(),
)
}
private fun close(sock: LocalSocket) {
try {
sock.close()
} catch (e: IOException) {
}
}
private companion object {
const val TAG = "SessionTextInput"
const val MAX_BYTES = 65536
const val TIMEOUT_MS = 3000
const val INITIAL_DELAY_MS = 500L
const val MAX_DELAY_MS = 5000L
}
}
@@ -219,6 +219,19 @@ object BottomDesktop {
fun sendText(text: String) {
val target = service ?: return
if (text.isNotEmpty() && text.all { it == '\r' || it == '\n' || it == '\b' || it == '\u007f' || it == '\t' }) {
for (c in text) {
val evdev = when (c) {
'\r', '\n' -> 28
'\b' -> 14
'\u007f' -> 111
else -> 15
}
sendKey(evdev, true)
sendKey(evdev, false)
}
return
}
send(target, Message.obtain(null, Comp.MSG_TEXT).apply { data = Bundle().apply { putString(Comp.KEY_TEXT, text) } })
}
@@ -11,6 +11,7 @@ import com.droiddeck.launcher.runtime.DesktopCatalog
import com.droiddeck.launcher.runtime.LegacyNames
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import org.json.JSONObject
import java.io.File
object SessionFiles {
@@ -21,6 +22,8 @@ object SessionFiles {
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json"
private const val IME_DEFAULT_MODE = 420
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
internal val DESKTOP_FILES = arrayOf(
@@ -133,6 +136,8 @@ object SessionFiles {
"usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
"usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer",
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-text-input" to "usr/local/bin/droiddeck-text-input",
"usr/local/bin/droiddeck-steam-ime" to "usr/local/bin/droiddeck-steam-ime",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply",
@@ -335,6 +340,7 @@ object SessionFiles {
if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged")
}
for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger)
stageImeFiles(context, root, ledger)
ledger.save()
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
@@ -421,6 +427,42 @@ object SessionFiles {
seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
private fun stageImeFiles(context: Context, root: File, ledger: StageLedger) {
val entries = LinkedHashMap<String, Int>()
try {
val text = context.assets.open("linuxfs/$IME_MANIFEST").bufferedReader().use { it.readText() }
val files = JSONObject(text).getJSONObject("files")
for (name in files.keys()) {
entries[name] = files.optJSONObject(name)?.optString("mode").orEmpty().toIntOrNull(8) ?: IME_DEFAULT_MODE
}
entries[IME_MANIFEST] = IME_DEFAULT_MODE
} catch (e: Exception) {
Log.w(TAG, "the Chinese input payload is not bundled; Steam sessions start without it", e)
return
}
for ((relative, mode) in entries) {
val target = File(root, relative)
if (ledger.current(relative, target)) continue
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
context.assets.open("linuxfs/$relative").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setReadable(true, false) &&
staged.setWritable((mode and 0x80) != 0, true) &&
staged.setExecutable((mode and 0x49) != 0, false) &&
staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage $relative", e)
} finally {
if (!installed) staged.delete()
}
if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
}
}
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
synchronized(STEAM_CONFIG) {
if (!config.isFile) return true
@@ -46,7 +46,11 @@ class BottomDesktopPanel(
private val status = ComposeView(context).apply {
setContent { DroidDeckTheme { BottomDesktopStatus(state.value, ::startAgain) } }
}
private val keyboardHost = KeyboardHost(context) { event -> sendKey(event) }
private val keyboardHost = KeyboardHost(
context,
sendKeyEvent = { event -> sendKey(event) },
sendText = BottomDesktop::sendText,
)
private var directTouch = SessionPrefs.bottomDesktopDirectTouch(context)
private val touchMode = mutableStateOf(directTouch)
private val trackpad = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), TrackpadInput()).apply {
@@ -25,6 +25,7 @@ import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.wayland.WaylandCompositor
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.BottomDesktop
@@ -490,12 +491,19 @@ class SecondScreenPresentation(
}
private fun attachKeyboard() {
val host = KeyboardHost(context) { event ->
val handled = sessionActivity.dispatchKeyEvent(event)
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
handled
}
val host = KeyboardHost(
context,
sendKeyEvent = { event ->
val handled = sessionActivity.dispatchImeKeyEvent(event)
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
handled
},
sendText = { text ->
WaylandCompositor.textInputCommit(text)
if (fieldKeyboard && text == "\r") root.post { closeFieldKeyboard() }
},
)
host.onImeChanged = { visible -> if (!visible && keyboardShown.value) keyboardClosed() }
keyboardHost = host
root.addView(host, ViewGroup.LayoutParams(1, 1))
@@ -31,7 +31,7 @@ class BottomDesktopCompositorService : Service() {
MSG_RESIZE -> resize(msg.arg1, msg.arg2)
MSG_TOUCH -> WaylandCompositor.nativeSendTouch(msg.arg1 and 0xff, msg.arg1 shr 8,
msg.arg2 ushr 16, msg.arg2 and 0xffff)
MSG_KEY -> WaylandCompositor.nativeSendKey(msg.arg1, msg.arg2)
MSG_KEY -> WaylandCompositor.nativeSendKeyOrdered(msg.arg1, msg.arg2)
MSG_POINTER -> WaylandCompositor.nativeSendPointer(1, msg.arg1, msg.arg2)
MSG_SCENE -> WaylandCompositor.nativeSendSceneInput(msg.arg1, msg.arg2, msg.peekData()?.getInt(KEY_B) ?: 0)
MSG_CURSOR -> if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(msg.arg1 != 0)
@@ -202,6 +202,27 @@ public final class WaylandCompositor {
if (l != null) l.onTextInput(enabled, program, x, y, w, h);
}
public interface TextInputFallbackListener {
boolean onTextInputFallback(String text, int token);
}
private static volatile TextInputFallbackListener textInputFallbackListener;
public static void setTextInputFallbackListener(TextInputFallbackListener l) { textInputFallbackListener = l; }
public static boolean isTextInputFallbackListener(TextInputFallbackListener l) { return textInputFallbackListener == l; }
public static void clearTextInputFallbackListener(TextInputFallbackListener l) {
if (textInputFallbackListener == l) textInputFallbackListener = null;
}
@SuppressWarnings("unused")
static boolean onTextInputFallback(byte[] utf8, int token) {
TextInputFallbackListener l = textInputFallbackListener;
if (l == null || utf8 == null) return false;
return l.onTextInputFallback(new String(utf8, java.nio.charset.StandardCharsets.UTF_8), token);
}
private static byte[] utf8(String s) {
return s == null ? new byte[0] : s.getBytes(java.nio.charset.StandardCharsets.UTF_8);
}
@@ -210,14 +231,28 @@ public final class WaylandCompositor {
public static void textInputCommit(String text) { if (text != null && !text.isEmpty()) nativeTextInputCommit(utf8(text)); }
public static void textInputCommitAndSubmit(String text) {
if (text != null && !text.isEmpty()) nativeTextInputCommitAndSubmit(utf8(text));
}
public static void textInputPreedit(String text, int cursor) { nativeTextInputPreedit(utf8(text), cursor, cursor); }
public static void textInputDelete(int before, int after) { nativeTextInputDelete(before, after); }
public static final int TEXT_NOT_DELIVERED = 0;
public static final int TEXT_DELIVERED = 1;
public static final int TEXT_UNRESOLVED = 2;
public static void completeTextInputFallback(int token, int result) {
nativeCompleteTextInputFallback(token, result);
}
private static native void nativeSetClipboardText(byte[] utf8);
private static native void nativeTextInputCommit(byte[] utf8);
private static native void nativeTextInputCommitAndSubmit(byte[] utf8);
private static native void nativeTextInputPreedit(byte[] utf8, int cursorBegin, int cursorEnd);
private static native void nativeTextInputDelete(int before, int after);
private static native void nativeCompleteTextInputFallback(int token, int result);
public static native void nativeStart(String xdgRuntimeDir);
@@ -248,6 +283,10 @@ public final class WaylandCompositor {
public static native void nativeSendKey(int evdev, int state);
// Ordered delivery: key events share the host queue with text commits so keys cannot overtake pending text.
public static native void nativeSendKeyOrdered(int evdev, int state);
public static native void nativeSelectGameField(boolean copy);
public static native boolean nativeFocusTakesTouch();
public static native boolean nativeCursorInputPos(int[] out);