Move the Linux runtime to Ubuntu 26.04 LTS with a separate Kubuntu desktop (#1733)

This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-10-29 09:05:20 -04:00
1 parent 5de690ef39
commit 29c83976d0
305 files changed
+9383 -462

No files matched your search

@@ -46,6 +46,7 @@ class App : Application() {
com.droiddeck.launcher.glasses.Glasses.init(this)
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
BwrapSpawner.start(this)
com.droiddeck.launcher.runtime.RootSpawner.start(this)
com.droiddeck.launcher.frontend.GameFileSync.start(this)
com.droiddeck.launcher.stores.StoresState.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
@@ -189,7 +189,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val steamTouchRetry = Runnable { updateOnScreenControls() }
private var steamTouchOptions: com.droiddeck.launcher.input.SteamTouchConfig.Options? = null
private var routedTouchMode = SessionPrefs.TOUCH_AUTO
private var touchRoute: com.droiddeck.launcher.input.TouchRouter.Route? = null
private var keyboard: KeyboardHost? = null
private var desktopKeyboardButton: com.droiddeck.launcher.input.DesktopKeyboardButton? = null
private var lastUserPressMs = 0L
private var pressDownX = 0f
private var pressDownY = 0f
private var pressTravel = 0f
private var pressMoved = false
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
private val sessionClipboard by lazy {
SessionClipboard(this) {
@@ -199,11 +206,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var watching = true
private lateinit var touchpad: TouchpadGestures
private lateinit var directTouchHold: DirectTouchHold
private lateinit var twoFingerGestures: com.droiddeck.launcher.input.TwoFingerGestures
private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap
private lateinit var touchscreenGestures: TouchscreenGestures
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null
private var gestureSettingsOpen by mutableStateOf(false)
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
private var screenKeyPickerOpen by mutableStateOf(false)
private var screenKeyBind: List<Int>? = null
private var screenKeyDir: Int? = null
@@ -234,6 +243,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val cursorHide = Runnable { cursorVisible = false }
private var lastPadInputMs = 0L
private val cursorBuf = IntArray(WaylandCompositor.CURSOR_BUF_INTS)
private val cursorPosBuf = IntArray(2)
private var cursorSerial = 0
private var clientHidesCursor = false
private var pointerLocked = false
@@ -243,6 +253,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
gesturePointerReady = false
pointerLocked = locked
Log.i(TAG, "pointer lock " + if (locked) "taken by a program" else "released")
if (locked) openEvdevMouse() else closeEvdevMouse()
padMouseCheckedAt = 0L
if (::padMouse.isInitialized) padMouseMode()
// Touchpad deltas are measured from the middle while locked (moveLockedPointer).
@@ -257,7 +268,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var cursorHotX by mutableStateOf(0)
private var cursorHotY by mutableStateOf(0)
private var cursorImageScale by mutableStateOf(1f)
private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false }
private var cursorResyncIdle = 0
private val cursorResync = object : Runnable {
override fun run() {
if (syncClientCursor() && clientHidesCursor) {
cursorVisible = false
return
}
if (touchDrivesPointer()) return
cursorResyncIdle = if (alignCursorToGuest()) 0 else cursorResyncIdle + 1
if (!cursorVisible || pointerLocked) return
if (cursorResyncIdle > CURSOR_RESYNC_IDLE_TICKS) return
uiHandler.postDelayed(this, 60)
}
}
private fun alignCursorToGuest(): Boolean {
if (pointerLocked || !CompositorHost.isStarted) return false
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return false
if (surfaceView.width <= 0 || surfaceView.height <= 0) return false
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * surfaceView.width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * surfaceView.height
if (kotlin.math.abs(x - cursorPos.x) < 0.75f && kotlin.math.abs(y - cursorPos.y) < 0.75f) return false
cursorPos = androidx.compose.ui.geometry.Offset(x, y)
return true
}
private val uiHandler = Handler(Looper.getMainLooper())
private var pendingBackAction: Runnable? = null
private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
@@ -342,6 +377,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var backActionsInverted by mutableStateOf(false)
private var backDoubleTapMs by mutableStateOf(500)
private var lowLatency by mutableStateOf(true)
private var evdevMouseOn by mutableStateOf(false)
private var directCursorOn by mutableStateOf(false)
private var mouseWriter: com.droiddeck.launcher.input.FakeInputWriter? = null
private var evdevMouseActive = false
private var lastMouseX = Float.NaN
private var lastMouseY = Float.NaN
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var pcKeyboardOpen by mutableStateOf(false)
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
@@ -605,12 +646,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
keys.visibility = if (screenKeysShown) View.VISIBLE else View.GONE
root.addView(keys)
}
keyboard = KeyboardHost(this).also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener) {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
keyboard = KeyboardHost(this).also { host ->
host.onImeChanged = { updateDesktopKeyboardButton() }
root.addView(host)
}
desktopKeyboardButton = com.droiddeck.launcher.input.DesktopKeyboardButton(this) { keyboard?.show() }
.also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener, directTouchSink)
threeFingerTap = com.droiddeck.launcher.input.ThreeFingerTap(PointerGestures.slop(this) * 2)
twoFingerGestures = com.droiddeck.launcher.input.TwoFingerGestures(PointerGestures.slop(this) * 2,
object : com.droiddeck.launcher.input.TwoFingerGestures.Listener {
override fun cancelTouch() {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
directTouchHold.cancel()
scrollRestX = 0f
scrollRestY = 0f
}
override fun replay(event: MotionEvent) {
drawnRect()?.let { forwardTouch(event, it) }
}
override fun rightClick(x: Float, y: Float) {
pointerListener.onLongPress()
pointerListener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
surfaceView.postDelayed({ pointerListener.onButton(PointerGestures.BTN_RIGHT, false, x, y) }, 50L)
}
override fun scrollStart(x: Float, y: Float) = scrollListener.onMove(x, y)
override fun scroll(dx: Float, dy: Float) = fingerScroll(dx, dy)
override fun scrollEnd() = fingerScrollEnd()
})
touchscreenGestures = TouchscreenGestures(
ViewConfiguration.get(this).scaledTouchSlop.toFloat(), gestureOutput,
)
@@ -746,6 +810,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() }
androidx.compose.runtime.LaunchedEffect(pipUi) { hud.setHidden(pipUi) }
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
androidx.compose.runtime.LaunchedEffect(AgentGuest.desktopTextField) { onDesktopTextField(AgentGuest.desktopTextField) }
androidx.compose.runtime.LaunchedEffect(pipUi, pcKeyboardOpen) { updateDesktopKeyboardButton() }
val keyboardRequestsSeen = androidx.compose.runtime.remember { intArrayOf(AgentGuest.keyboardRequests) }
androidx.compose.runtime.LaunchedEffect(AgentGuest.keyboardRequests) {
if (AgentGuest.keyboardRequests != keyboardRequestsSeen[0]) {
@@ -1133,6 +1199,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
lowLatency = on
applyLowLatency()
},
evdevMouse = evdevMouseOn,
onEvdevMouse = { on ->
SessionPrefs.setEvdevMouse(this@SessionActivity, on)
evdevMouseOn = on
if (on) { if (pointerLocked) openEvdevMouse() } else releaseEvdevMouse()
},
directCursor = directCursorOn,
onDirectCursor = { on ->
SessionPrefs.setDirectCursor(this@SessionActivity, on)
directCursorOn = on
if (!on && directTouchCursorHidden()) cursorVisible = false
},
onOsc = { v ->
SessionPrefs.setOscMode(this@SessionActivity, v)
readPrefs()
@@ -1156,6 +1234,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
touchActive = drawerTouchMode(),
directHoldBehavior = directHoldBehavior,
onDirectHoldBehavior = { value ->
val base = com.droiddeck.launcher.input.GesturePrefs.read(this@SessionActivity, gestureGame)
com.droiddeck.launcher.input.GesturePrefs.save(this@SessionActivity, gestureGame, base.copy(directHoldBehavior = value))
refreshGestureConfig()
},
onScreenKeys = { drawerOpen = false; screenKeys?.startEditing() },
screenKeysShown = screenKeysShown,
onScreenKeysShown = { shown ->
@@ -1683,6 +1768,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (touchMode != nextTouchMode) {
if (::touchpad.isInitialized) touchpad.cancel()
if (::directTouchHold.isInitialized) directTouchHold.cancel()
if (::twoFingerGestures.isInitialized) twoFingerGestures.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (CompositorHost.isStarted) {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
@@ -1704,6 +1790,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
backActionsInverted = SessionPrefs.backActionsInverted(this)
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
lowLatency = SessionPrefs.lowLatency(this)
evdevMouseOn = SessionPrefs.evdevMouse(this)
if (!evdevMouseOn) releaseEvdevMouse()
directCursorOn = SessionPrefs.directCursor(this)
padType = SessionPrefs.steamController(this)
}
@@ -2418,6 +2507,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (pipUi) return true
notePress(event)
if (drawerOpen && PadBridge.isControllerMotionEvent(event)) {
if (!drawerControllerActive) focusDrawer()
drawerControllerActive = true
@@ -2458,6 +2548,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (pipUi) return true
notePress(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
drawerControllerActive = false
gestureTouchStreamGate.reset()
@@ -2585,6 +2676,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun refreshGestureConfig() {
gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame)
directHoldBehavior = gestureConfig.directHoldBehavior
gestureTouchStreamGate.reset()
if (::touchscreenGestures.isInitialized) touchscreenGestures.configure(gestureConfig)
if (::directTouchHold.isInitialized) directTouchHold.configure(gestureConfig)
@@ -2606,12 +2698,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {
val rect = drawnRect() ?: return
if (relative || pointerLocked) {
val scale = SessionState.outputSize.first / rect.width()
WaylandCompositor.sendPointerDelta(dx * scale, dy * scale)
val scale = sceneScale(rect)
sendSceneDelta(dx * scale, dy * scale)
} else moveTo(gesturePointerX + dx, gesturePointerY + dy)
}
override fun button(code: Int, down: Boolean) {
WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0)
sendSceneButton(code, down)
}
override fun prepareRelativePan() {
if (pointerLocked) return
@@ -2625,7 +2717,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (down) gestureKeysDown.add(code) else gestureKeysDown.remove(code)
if (code !in guestKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
}
override fun wheel(steps: Int) { WaylandCompositor.nativeSendSceneInput(4, steps, 0) }
override fun wheel(steps: Int) { sendSceneWheel(steps) }
override fun showKeyboard() { uiHandler.post { touchscreenGestures.cancel(); togglePcKeyboard() } }
override fun gesture(gesture: TouchscreenGestures.Gesture) {
recognizedGesture = gesture
@@ -2640,9 +2732,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
if (!pointerLocked) movePointer(x, y)
WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
sendSceneButton(button, pressed)
}
override fun onWheel(steps: Int) { sendSceneWheel(steps) }
override fun onScroll(dx: Float, dy: Float) = fingerScroll(dx, dy)
override fun onScrollEnd() = fingerScrollEnd()
override fun onZoom(steps: Int) {
WaylandCompositor.nativeSendKey(KEY_LEFTCTRL, 1)
sendSceneWheel(steps)
WaylandCompositor.nativeSendKey(KEY_LEFTCTRL, 0)
}
override fun onWheel(steps: Int) { WaylandCompositor.nativeSendSceneInput(4, steps, 0) }
override fun onLongPress() {
@Suppress("DEPRECATION")
(getSystemService(VIBRATOR_SERVICE) as? android.os.Vibrator)?.vibrate(15)
@@ -2710,10 +2809,37 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun scrollTouchMode(): Boolean =
(routedTouchMode == SessionPrefs.TOUCH_AUTO || routedTouchMode == SessionPrefs.TOUCH_DIRECT) && padMouseMode()
private fun fingerScroll(dx: Float, dy: Float) {
val rect = drawnRect() ?: return
val out = SessionState.outputSize
scrollRestX += dx * out.first / rect.width() * AXIS_UNITS_PER_PIXEL
scrollRestY += dy * out.second / rect.height() * AXIS_UNITS_PER_PIXEL
val h = scrollRestX.toInt()
val v = scrollRestY.toInt()
if (h == 0 && v == 0) return
scrollRestX -= h
scrollRestY -= v
WaylandCompositor.nativeSendSceneInput(12, v, h)
}
private fun fingerScrollEnd() {
scrollRestX = 0f
scrollRestY = 0f
WaylandCompositor.nativeSendSceneInput(12, 0, 0)
}
private fun placeTouchpadAtGuest(rect: android.graphics.RectF) {
if (pointerLocked || !CompositorHost.isStarted || surfaceView.width <= 0 || surfaceView.height <= 0) return
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * surfaceView.width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * surfaceView.height
if (rect.contains(x, y)) touchpad.place(x, y)
}
private fun moveLockedPointer(x: Float, y: Float) {
val rect = drawnRect() ?: return
val scale = SessionState.outputSize.first / rect.width()
WaylandCompositor.sendPointerDelta((x - rect.centerX()) * scale, (y - rect.centerY()) * scale)
val scale = sceneScale(rect)
sendSceneDelta((x - rect.centerX()) * scale, (y - rect.centerY()) * scale)
touchpad.place(rect.centerX(), rect.centerY())
cursorVisible = false
}
@@ -2730,14 +2856,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cursorPos = androidx.compose.ui.geometry.Offset(x, y)
syncClientCursor()
uiHandler.removeCallbacks(cursorResync)
uiHandler.postDelayed(cursorResync, 60)
cursorResyncIdle = 0
if (!touchDrivesPointer()) uiHandler.postDelayed(cursorResync, 60)
if (clientHidesCursor) { cursorVisible = false; return }
if (directTouchCursorHidden()) { cursorVisible = false; return }
if (android.os.SystemClock.uptimeMillis() - lastPadInputMs < CURSOR_PAD_HOLD_MS) return
cursorVisible = true
uiHandler.removeCallbacks(cursorHide)
if (SessionState.mode == SessionService.MODE_STEAM && SessionState.steamUi != "desktop") uiHandler.postDelayed(cursorHide, 2500)
}
private fun touchDrivesPointer(): Boolean =
routedTouchMode == SessionPrefs.TOUCH_DIRECT ||
(routedTouchMode == SessionPrefs.TOUCH_AUTO && !usingTouchpad())
private fun directTouchCursorHidden(): Boolean = !directCursorOn && touchDrivesPointer()
private fun syncClientCursor(): Boolean {
if (!CompositorHost.isStarted) return false
if (WaylandCompositor.nativeCursorSerial() == cursorSerial) return false
@@ -3021,22 +3155,95 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
gesturePointerReady = false
if (::touchpad.isInitialized) touchpad.cancel()
if (::directTouchHold.isInitialized) directTouchHold.cancel()
if (::twoFingerGestures.isInitialized) twoFingerGestures.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
if (CompositorHost.isStarted &&
(deliversTouches(routedTouchMode) || deliversTouches(next)))
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
gestureTouchStreamGate.reset()
routedTouchMode = next
if (directTouchCursorHidden()) cursorVisible = false
}
private fun deliversTouches(mode: String) =
mode == SessionPrefs.TOUCH_DIRECT || mode == SessionPrefs.TOUCH_AUTO
private fun usingTouchpad(): Boolean = when (routedTouchMode) {
SessionPrefs.TOUCH_PAD -> true
SessionPrefs.TOUCH_DIRECT -> false
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
}
private fun drawerTouchMode(): String = when (routedTouchMode) {
SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT,
SessionPrefs.TOUCH_OFF, SessionPrefs.TOUCH_PAD -> routedTouchMode
else -> if (usingTouchpad()) SessionPrefs.TOUCH_PAD else SessionPrefs.TOUCH_DIRECT
}
private val gamePictureBounds = FloatArray(4)
private var topPictureMapped = false
private fun sceneScale(rect: android.graphics.RectF): Float =
SessionState.outputSize.first / rect.width()
private fun openEvdevMouse() {
if (evdevMouseActive || !evdevMouseOn) return
val writer = mouseWriter ?: com.droiddeck.launcher.input.FakeInputWriter(
File(LinuxRuntime.sessionRoot(this), "dev/input").absolutePath,
com.droiddeck.launcher.input.FakeInputWriter.MOUSE_SLOT,
).also { mouseWriter = it }
if (!writer.open()) return
evdevMouseActive = true
lastMouseX = Float.NaN
lastMouseY = Float.NaN
Log.i(TAG, "raw mouse channel active (pointer locked)")
}
private fun closeEvdevMouse() {
if (!evdevMouseActive) return
mouseWriter?.softRelease()
evdevMouseActive = false
Log.i(TAG, "raw mouse channel idle")
}
private fun releaseEvdevMouse() {
evdevMouseActive = false
mouseWriter?.destroy()
mouseWriter = null
Log.i(TAG, "raw mouse channel removed")
}
private fun sendSceneDelta(dx: Float, dy: Float) {
val writer = if (evdevMouseActive) mouseWriter else null
if (writer != null) writer.writeMouseDelta(dx, dy)
else WaylandCompositor.sendPointerDelta(dx, dy)
}
private fun sendSceneButton(code: Int, down: Boolean) {
val writer = if (evdevMouseActive) mouseWriter else null
if (writer != null) writer.writeMouseButton(code.toShort(), down)
else WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0)
}
private fun sendSceneWheel(steps: Int) {
val writer = if (evdevMouseActive) mouseWriter else null
if (writer != null) writer.writeMouseWheel(-steps, 0, 120)
else WaylandCompositor.nativeSendSceneInput(4, steps, 0)
}
private fun sendMouseDelta(x: Float, y: Float) {
cursorVisible = false
val previousX = lastMouseX
val previousY = lastMouseY
lastMouseX = x
lastMouseY = y
val rect = drawnRect() ?: return
if (previousX.isNaN() || previousY.isNaN()) return
val scale = sceneScale(rect)
sendSceneDelta((x - previousX) * scale, (y - previousY) * scale)
}
private fun drawnRect(): android.graphics.RectF? {
val width = surfaceView.width.takeIf { it > 0 } ?: return null
val height = surfaceView.height.takeIf { it > 0 } ?: return null
@@ -3065,84 +3272,125 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) dismissTouch = false
return true
}
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) return true
if (routedTouchMode == SessionPrefs.TOUCH_GESTURES) {
if (event.actionMasked == MotionEvent.ACTION_DOWN) gesturePointerReady = false
return touchscreenGestures.onTouch(event)
}
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
val uiBlocking = drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended
if (event.actionMasked == MotionEvent.ACTION_DOWN && !uiBlocking && routedTouchMode != SessionPrefs.TOUCH_GESTURES) {
scrollTouchGesture = scrollTouchMode()
scrollRestX = 0f
scrollRestY = 0f
}
if (scrollTouchGesture) return scrollTouch.onTouch(event)
if (routedTouchMode == SessionPrefs.TOUCH_OFF) return true
if (SessionState.mode == SessionService.MODE_STEAM && SessionState.steamUi != "desktop") {
val wasActive = threeFingerTap.active
if (threeFingerTap.onTouch(event)) padBridge?.triggerSteamKeyboard()
if (threeFingerTap.active && !wasActive) {
if (usingTouchpad()) touchpad.cancel() else WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
}
if (threeFingerTap.active || wasActive) return true
val snapshot = com.droiddeck.launcher.input.TouchRouter.Snapshot(
uiBlocking = uiBlocking,
mode = routedTouchMode,
scrollLayer = scrollTouchGesture,
steamSession = SessionState.mode == SessionService.MODE_STEAM,
steamDesktopUi = SessionState.steamUi == "desktop",
)
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
if (route != touchRoute) {
Log.i(TAG, "touch route $touchRoute -> $route (mode=$routedTouchMode steamUi=${SessionState.steamUi} scrollLayer=$scrollTouchGesture)")
touchRoute = route
}
if (usingTouchpad()) {
val rect = drawnRect() ?: return false
if (touchpad.bounds != rect) {
val fresh = touchpad.bounds.width() <= 1f
touchpad.bounds = rect
if (fresh) touchpad.place(rect.centerX(), rect.centerY())
return when (route) {
com.droiddeck.launcher.input.TouchRouter.Route.BLOCKED,
com.droiddeck.launcher.input.TouchRouter.Route.OFF -> true
com.droiddeck.launcher.input.TouchRouter.Route.GESTURES -> {
if (event.actionMasked == MotionEvent.ACTION_DOWN) gesturePointerReady = false
touchscreenGestures.onTouch(event)
}
com.droiddeck.launcher.input.TouchRouter.Route.SCROLL -> scrollTouch.onTouch(event)
else -> {
if (com.droiddeck.launcher.input.TouchRouter.steamKeyboardZone(snapshot)) {
val wasActive = threeFingerTap.active
if (threeFingerTap.onTouch(event)) padBridge?.triggerSteamKeyboard()
if (threeFingerTap.active && !wasActive) {
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD) touchpad.cancel()
else {
directTouchHold.cancel()
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
}
}
if (threeFingerTap.active || wasActive) return true
}
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD) {
val rect = drawnRect() ?: return false
if (touchpad.bounds != rect) {
val fresh = touchpad.bounds.width() <= 1f
touchpad.bounds = rect
if (fresh) touchpad.place(rect.centerX(), rect.centerY())
}
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
touchpad.desktop = SessionState.mode == SessionService.MODE_DESKTOP
placeTouchpadAtGuest(rect)
}
touchpad.onTouch(event)
} else {
dispatchDirectTouch(event)
}
}
return touchpad.onTouch(event)
}
}
private val directTouchSink = object : DirectTouchHold.Touch {
override fun down(pointerId: Int, x: Float, y: Float) = sendDirectTouch(0, pointerId, x, y)
override fun move(pointerId: Int, x: Float, y: Float) = sendDirectTouch(1, pointerId, x, y)
override fun up(pointerId: Int, x: Float, y: Float) = sendDirectTouch(2, pointerId, x, y)
override fun cancel() = WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
}
private fun sendDirectTouch(action: Int, pointerId: Int, x: Float, y: Float) {
val rect = drawnRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendTouch(action, pointerId,
InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
showCursor(cx, cy)
}
private fun dispatchDirectTouch(event: MotionEvent): Boolean {
val rect = drawnRect() ?: return false
if (event.actionMasked == MotionEvent.ACTION_DOWN)
ignoreGameTouch = topPictureMapped && !rect.contains(event.x, event.y)
if (ignoreGameTouch) {
if (event.actionMasked == MotionEvent.ACTION_DOWN)
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
directTouchHold.cancel()
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
}
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) ignoreGameTouch = false
return true
}
if (directTouchHold.onTouch(event)) return true
fun sendTouch(action: Int, index: Int) {
val x = event.getX(index).coerceIn(rect.left, rect.right)
val y = event.getY(index).coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendTouch(action, event.getPointerId(index),
InputSpace.x(x, surfaceView.width), InputSpace.y(y, surfaceView.height))
}
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
if (SessionState.mode == SessionService.MODE_DESKTOP && twoFingerGestures.onTouch(event)) return true
return forwardTouch(event, rect)
}
private fun forwardTouch(event: MotionEvent, rect: android.graphics.RectF): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
showCursor(event.x.coerceIn(rect.left, rect.right), event.y.coerceIn(rect.top, rect.bottom))
if (WaylandCompositor.nativeFocusTakesTouch()) {
listOf(PointerGestures.BTN_LEFT, PointerGestures.BTN_RIGHT, PointerGestures.BTN_MIDDLE).forEach {
WaylandCompositor.nativeSendSceneInput(3, it, 0)
}
sendTouch(0, event.actionIndex)
}
MotionEvent.ACTION_POINTER_DOWN -> sendTouch(0, event.actionIndex)
MotionEvent.ACTION_MOVE -> for (index in 0 until event.pointerCount) sendTouch(1, index)
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> sendTouch(2, event.actionIndex)
MotionEvent.ACTION_CANCEL -> WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
else -> return false
}
directTouchHold.onTouch(event)
return true
}
private fun onMouse(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_HOVER_MOVE, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_HOVER_ENTER ->
movePointer(event.x, event.y)
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y)
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
movePointer(event.x, event.y)
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y)
val button = when (event.actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
else -> PointerGestures.BTN_LEFT
}
WaylandCompositor.nativeSendSceneInput(3, button, if (event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) 1 else 0)
sendSceneButton(button, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS)
}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) WaylandCompositor.nativeSendSceneInput(4, -Math.round(v), 0)
if (v != 0f) sendSceneWheel(-Math.round(v))
}
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP -> {}
else -> return false
@@ -3165,6 +3413,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun onCapturedPointer(event: MotionEvent): Boolean {
if (!pointerLocked || !event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)) return false
notePress(event)
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> {
var dx = event.x
@@ -3173,7 +3422,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
dx += event.getHistoricalX(i)
dy += event.getHistoricalY(i)
}
WaylandCompositor.sendPointerDelta(dx, dy)
sendSceneDelta(dx, dy)
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
val button = when (event.actionButton) {
@@ -3181,11 +3430,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
else -> PointerGestures.BTN_LEFT
}
WaylandCompositor.nativeSendSceneInput(3, button, if (event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) 1 else 0)
sendSceneButton(button, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS)
}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) WaylandCompositor.nativeSendSceneInput(4, -Math.round(v), 0)
if (v != 0f) sendSceneWheel(-Math.round(v))
}
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP -> {}
else -> return false
@@ -3309,6 +3558,60 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
})
}
private fun desktopTextInput() =
SessionState.mode == SessionService.MODE_DESKTOP && SessionState.running && !pipUi
private fun notePress(event: MotionEvent) {
val touch = event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_BUTTON_PRESS -> {
pressDownX = event.x
pressDownY = event.y
pressTravel = 0f
pressMoved = false
if (!touch) lastUserPressMs = android.os.SystemClock.uptimeMillis()
}
MotionEvent.ACTION_POINTER_DOWN -> pressMoved = true
MotionEvent.ACTION_MOVE -> if (touch || event.buttonState != 0) {
val moved = if (event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)) {
pressTravel += kotlin.math.hypot(event.x, event.y)
pressTravel
} else {
kotlin.math.hypot(event.x - pressDownX, event.y - pressDownY)
}
if (moved >= android.view.ViewConfiguration.get(this).scaledTouchSlop * 2f) {
pressMoved = true
if (!touch) lastUserPressMs = 0L
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_BUTTON_RELEASE -> {
val quick = !touch || event.eventTime - event.downTime < android.view.ViewConfiguration.getLongPressTimeout()
if (!pressMoved && quick) lastUserPressMs = android.os.SystemClock.uptimeMillis()
}
}
}
private fun onDesktopTextField(focused: Boolean) {
val host = keyboard
if (host != null && desktopTextInput()) {
val tapped = android.os.SystemClock.uptimeMillis() - lastUserPressMs < TEXT_FIELD_TAP_MS
if (focused && tapped && resumed && !pcKeyboardOpen &&
resources.configuration.hardKeyboardHidden != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO) host.show()
else if (!focused && host.shown) host.hide()
}
updateDesktopKeyboardButton()
}
private fun updateDesktopKeyboardButton() {
val button = desktopKeyboardButton ?: return
val show = desktopTextInput() && AgentGuest.desktopTextField && !pcKeyboardOpen &&
!(keyboard?.let { it.shown && (Build.VERSION.SDK_INT < 30 || it.imeShowing) } ?: false)
val visibility = if (show) View.VISIBLE else View.GONE
if (button.visibility == visibility) return
if (show) button.applyColors()
button.visibility = visibility
}
private fun keyboardCoversPad() =
SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard
@@ -3398,6 +3701,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
touchpad.cancel()
scrollTouch.cancel()
directTouchHold.cancel()
twoFingerGestures.cancel()
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
keyboard?.hide()
sessionClipboard.stop()
@@ -3525,6 +3829,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onScreenControls?.reload()
controllerSettings = ControllerPrefs.read(this)
resumed = true
updateDesktopKeyboardButton()
com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this,
enabled = {
resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen &&
@@ -3553,7 +3858,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
if (::directTouchHold.isInitialized) directTouchHold.cancel()
if (::twoFingerGestures.isInitialized) twoFingerGestures.cancel()
uiHandler.removeCallbacks(clearRecognizedGesture)
uiHandler.removeCallbacks(cursorResync)
gestureSettingsOpen = false
drawerOpen = false
pcKeyboardOpen = false
@@ -3985,6 +4292,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
backQamInput.cancel()
steamVrRecovery.close()
uiHandler.removeCallbacks(steamTouchRetry)
uiHandler.removeCallbacks(cursorResync)
releaseEvdevMouse()
if (runtimeRemovalBlocked) { super.onDestroy(); return }
watching = false
releaseDrawerDirection()
@@ -4074,6 +4383,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_REPAIR_RUNTIME = "repairRuntime"
private const val LEAVE_TIMEOUT_MS = 1_500L
private const val TEXT_FIELD_TAP_MS = 1_000L
private const val PAUSED_FRAME_MAX_EDGE = 1920f
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val TAG = "SessionActivity"
@@ -4082,9 +4392,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need"
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
private const val CURSOR_PAD_HOLD_MS = 1200L
private const val CURSOR_RESYNC_IDLE_TICKS = 33
private const val PAD_MOUSE_CHECK_MS = 500L
private const val PAD_SCROLL_POINTER_X = 0.985f
private const val PAD_SCROLL_HEIGHTS_PER_S = 3f
private const val AXIS_UNITS_PER_PIXEL = 3f
private const val KEY_LEFTCTRL = 29
private const val DRAWER_HAT_THRESHOLD = 0.5f
private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f
private const val DRAWER_STICK_EXIT_THRESHOLD = 0.35f
@@ -22,6 +22,8 @@ object AgentGuest {
private set
var steamKeyboard by mutableStateOf(false)
private set
var desktopTextField by mutableStateOf(false)
private set
var keyboardRequests by mutableIntStateOf(0)
private set
var keyboardDismissals by mutableIntStateOf(0)
@@ -41,7 +43,7 @@ object AgentGuest {
observer?.stopWatching()
observer = null
lastFocusKey = null
main.post { steamKeyboard = false }
main.post { steamKeyboard = false; desktopTextField = false }
val dir = dir(context)
dir.deleteRecursively()
dir.mkdirs()
@@ -56,6 +58,7 @@ object AgentGuest {
}
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
"keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) }
"ime.json" -> readJson(File(dir, path))?.let { recordTextField(this, it) }
"keyboard-request.json" -> readJson(File(dir, path))?.let { recordKeyboardRequest(this) }
"keyboard-dismiss.json" -> readJson(File(dir, path))?.let { recordKeyboardDismiss(this) }
}
@@ -68,7 +71,7 @@ object AgentGuest {
synchronized(lock) {
observer?.stopWatching()
observer = null
main.post { steamKeyboard = false }
main.post { steamKeyboard = false; desktopTextField = false }
}
}
@@ -117,6 +120,15 @@ object AgentGuest {
SessionEvents.record("keyboard.changed", mapOf("steamKeyboard" to showing, "seq" to snapshot.optInt("seq")))
}
private fun recordTextField(source: FileObserver, snapshot: JSONObject) {
val focused = snapshot.optBoolean("textField")
synchronized(lock) {
if (source !== observer) return
main.post { desktopTextField = focused }
}
SessionEvents.record("ime.changed", mapOf("textField" to focused, "seq" to snapshot.optInt("seq")))
}
private fun recordFocus(snapshot: JSONObject) {
val fields = linkedMapOf<String, Any?>(
"focusedApp" to snapshot.opt("focusedApp"),
@@ -274,7 +274,7 @@ object Library {
Spec("duckstation", "DuckStation", "PS1", "/opt/appimages/duckstation.AppImage", listOf("ps1", "psx"), setOf("cue", "chd", "pbp", "iso", "bin", "img", "ecm", "m3u")),
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi"), atPanel = true),
Spec("cemu", "Cemu", "Wii U", "/opt/appimages/cemu.AppImage", listOf("wiiu", "wii u"), setOf("wua", "wud", "wux", "rpx")),
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
Spec("ppsspp", "PPSSPP", "PSP", "/usr/local/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
)
private fun displayTitle(name: String): String =
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.input
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Build
import android.view.Gravity
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.R
@SuppressLint("ViewConstructor")
class DesktopKeyboardButton(context: Context, private val onTap: () -> Unit) : View(context) {
private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = dp(1.5f) }
private val box = RectF()
private var idleFill = 0
private var idleStroke = 0
private var heldStroke = 0
private var pressed = false
init {
contentDescription = context.getString(R.string.second_show_keyboard)
isClickable = true
visibility = GONE
layoutParams = FrameLayout.LayoutParams(dp(SIZE).toInt(), dp(SIZE).toInt(), Gravity.BOTTOM or Gravity.START)
place(0, 0)
applyColors()
}
private fun dp(value: Float) = value * resources.displayMetrics.density
fun applyColors() {
val settings = ControllerPrefs.read(context)
val tint = settings.tint
val alpha = settings.opacity / 100f
fun light(a: Int, f: Float) = Color.argb(
(a * alpha).toInt(),
(Color.red(tint) + (255 - Color.red(tint)) * f).toInt(),
(Color.green(tint) + (255 - Color.green(tint)) * f).toInt(),
(Color.blue(tint) + (255 - Color.blue(tint)) * f).toInt(),
)
idleFill = Color.argb(190, (Color.red(tint) * 0.12f).toInt(), (Color.green(tint) * 0.12f).toInt(), (Color.blue(tint) * 0.12f).toInt())
idleStroke = light(150, 0.25f)
heldStroke = light(230, 0.7f)
invalidate()
}
private fun place(left: Int, bottom: Int) {
val params = layoutParams as FrameLayout.LayoutParams
val marginStart = left + (dp(CENTER_X) - dp(SIZE) / 2f).toInt()
val marginBottom = bottom + (dp(CENTER_Y) - dp(SIZE) / 2f).toInt()
if (params.leftMargin == marginStart && params.bottomMargin == marginBottom) return
params.leftMargin = marginStart
params.bottomMargin = marginBottom
layoutParams = params
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
place(cutout?.safeInsetLeft ?: 0, cutout?.safeInsetBottom ?: 0)
return super.onApplyWindowInsets(insets)
}
override fun onDraw(canvas: Canvas) {
val x = width / 2f
val y = height / 2f
fill.color = idleFill
canvas.drawCircle(x, y, dp(18f), fill)
stroke.color = if (pressed) heldStroke else idleStroke
canvas.drawCircle(x, y, dp(18f), stroke)
box.set(x - dp(10f), y - dp(7f), x + dp(10f), y + dp(7f))
canvas.drawRoundRect(box, dp(2f), dp(2f), stroke)
for (row in 0..1) for (col in 0..2) {
val kx = x + dp(-6f + col * 5f)
val ky = y + dp(-3f + row * 4f)
canvas.drawLine(kx, ky, kx + dp(2f), ky, stroke)
}
canvas.drawLine(x - dp(5f), y + dp(4f), x + dp(5f), y + dp(4f), stroke)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> { pressed = true; invalidate() }
MotionEvent.ACTION_UP -> {
val inside = event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()
pressed = false
invalidate()
if (inside) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
performClick()
}
}
MotionEvent.ACTION_CANCEL -> { pressed = false; invalidate() }
}
return true
}
override fun performClick(): Boolean {
super.performClick()
onTap()
return true
}
private companion object {
const val SIZE = 52f
const val CENTER_X = 90f
const val CENTER_Y = 34f
}
}
@@ -8,52 +8,125 @@ import kotlin.math.abs
class DirectTouchHold(
private val slopPx: Float,
private val listener: PointerGestures.Listener,
private val cancelTouch: () -> Unit,
private val touch: Touch,
) {
interface Touch {
fun down(pointerId: Int, x: Float, y: Float)
fun move(pointerId: Int, x: Float, y: Float)
fun up(pointerId: Int, x: Float, y: Float)
fun cancel()
}
private val handler = Handler(Looper.getMainLooper())
private var x = 0f
private var y = 0f
private var consumed = false
private var pressed = false
private var downX = 0f
private var downY = 0f
private var downId = 0
private var delayMs = 0L
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK
private var forwarded = false
private var held = false
private var pressing = false
private var upX = 0f
private var upY = 0f
private var liftId = 0
private var liftPending = false
private val lift = Runnable {
liftPending = false
if (forwarded) {
touch.up(liftId, upX, upY)
forwarded = false
}
}
private val release = Runnable {
if (pressed) listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
pressed = false
if (pressing) listener.onButton(PointerGestures.BTN_RIGHT, false, downX, downY)
pressing = false
}
private val hold = Runnable {
cancelTouch()
consumed = true
held = true
listener.onLongPress()
listener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
pressed = true
handler.postDelayed(release, 50L)
listener.onButton(PointerGestures.BTN_RIGHT, true, downX, downY)
pressing = true
if (holdBehavior != TouchGestureConfig.MOUSE_BEHAVIOR_HOLD) handler.postDelayed(release, 50L)
}
fun configure(config: TouchGestureConfig) {
cancel()
delayMs = if (config.longPressEnabled) config.longPressDelay.toLong().coerceAtLeast(1L) else 0L
delayMs = config.longPressDelay.toLong().coerceAtLeast(1L)
holdBehavior = config.directHoldBehavior
}
fun cancel() {
handler.removeCallbacks(hold)
handler.removeCallbacks(release)
handler.removeCallbacks(lift)
liftPending = false
release.run()
consumed = false
if (forwarded) touch.cancel()
forwarded = false
held = false
}
fun onTouch(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
if (liftPending) {
handler.removeCallbacks(lift)
lift.run()
}
cancel()
downX = event.x
downY = event.y
downId = event.getPointerId(0)
if (holdBehavior == TouchGestureConfig.MOUSE_BEHAVIOR_NONE) forwardDown()
else handler.postDelayed(hold, delayMs)
return true
}
if (held) {
when (event.actionMasked) {
MotionEvent.ACTION_UP -> { release.run(); held = false }
MotionEvent.ACTION_CANCEL -> cancel()
}
return true
}
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
cancel()
x = event.x; y = event.y
if (delayMs > 0L) handler.postDelayed(hold, delayMs)
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(hold)
if (!forwarded) forwardDown()
val index = event.actionIndex
touch.down(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_MOVE -> {
if (!forwarded && (event.pointerCount > 1 ||
abs(event.x - downX) > slopPx || abs(event.y - downY) > slopPx)) {
handler.removeCallbacks(hold)
forwardDown()
}
if (forwarded) for (index in 0 until event.pointerCount)
touch.move(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_POINTER_UP -> {
val index = event.actionIndex
touch.up(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_UP -> {
handler.removeCallbacks(hold)
if (!forwarded) forwardDown()
upX = event.x
upY = event.y
liftId = event.getPointerId(event.actionIndex)
liftPending = true
handler.postDelayed(lift, LIFT_MS)
}
MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1 ||
abs(event.x - x) > slopPx || abs(event.y - y) > slopPx) handler.removeCallbacks(hold)
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_POINTER_UP,
MotionEvent.ACTION_UP -> handler.removeCallbacks(hold)
MotionEvent.ACTION_CANCEL -> cancel()
}
return consumed
return true
}
private fun forwardDown() {
touch.down(downId, downX, downY)
forwarded = true
}
private companion object {
const val LIFT_MS = 50L
}
}
@@ -14,6 +14,7 @@ public class FakeInputWriter {
public static final short EV_SYN = 0x00;
public static final short EV_KEY = 0x01;
public static final short EV_REL = 0x02;
public static final short EV_ABS = 0x03;
public static final short EV_MSC = 0x04;
@@ -52,7 +53,8 @@ public class FakeInputWriter {
private static final int EVENT_SIZE = 24;
static final int MAX_EVENTS_PER_UPDATE = 32;
private static final int BUFFER_SIZE = EVENT_SIZE * MAX_EVENTS_PER_UPDATE;
private static final int MAX_FAKE_INPUT_SLOTS = 4;
private static final int MAX_FAKE_INPUT_SLOTS = 5;
public static final int MOUSE_SLOT = 4;
private static final int RING_CAPACITY_EVENTS = 4096;
private static final int RING_HEADER_SIZE = 64;
@@ -88,6 +90,17 @@ public class FakeInputWriter {
public static final int PAD_TYPE_XBOX = 2;
public static final int PAD_TYPE_DS4 = 3;
public static final int PAD_TYPE_DUALSENSE = 4;
public static final int PAD_TYPE_MOUSE = 5;
public static final short REL_X = 0x00;
public static final short REL_Y = 0x01;
public static final short REL_HWHEEL = 0x06;
public static final short REL_WHEEL = 0x08;
public static final short REL_WHEEL_HI_RES = 0x0b;
public static final short REL_HWHEEL_HI_RES = 0x0c;
public static final short MOUSE_BTN_LEFT = 0x110;
public static final short MOUSE_BTN_RIGHT = 0x111;
public static final short MOUSE_BTN_MIDDLE = 0x112;
private static volatile int padType = -1;
private static volatile boolean tritonConnected = false;
private static final int TRITON_OFFSET = RING_SIZE + 64;
@@ -136,6 +149,8 @@ public class FakeInputWriter {
private int prevThumbLX, prevThumbLY, prevThumbRX, prevThumbRY;
private int prevTriggerL, prevTriggerR;
private int prevHatX, prevHatY;
private final boolean[] prevMouseButtons = new boolean[3];
private float pendingMouseX, pendingMouseY;
private boolean hasChanges = false;
private boolean pendingFullResend = false;
private boolean forceResend = false;
@@ -201,7 +216,7 @@ public class FakeInputWriter {
return FakeInputRingPaths.ringFile(fakeInputDir, slot);
}
private static void initializeRingHeader(ByteBuffer data) {
private static void initializeRingHeader(int slot, ByteBuffer data) {
data.order(ByteOrder.LITTLE_ENDIAN);
data.putInt(RING_MAGIC_OFFSET, RING_MAGIC);
data.putInt(RING_VERSION_OFFSET, RING_VERSION);
@@ -221,7 +236,7 @@ public class FakeInputWriter {
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
}
data.putInt(DECK_CONTROLS_OFFSET, 0);
int type = padType;
int type = slot == MOUSE_SLOT ? PAD_TYPE_MOUSE : padType;
data.putInt(PAD_TYPE_OFFSET, type >= 0 ? PAD_TYPE_SET | type : 0);
data.putInt(LATENCY_OFFSET, latency);
data.putInt(TRITON_OFFSET, TRITON_MAGIC);
@@ -312,7 +327,7 @@ public class FakeInputWriter {
raf.setLength(RING_FILE_SIZE);
channel = raf.getChannel();
ByteBuffer data = channel.map(FileChannel.MapMode.READ_WRITE, 0, RING_FILE_SIZE);
initializeRingHeader(data);
initializeRingHeader(slot, data);
RingSlot ringSlot = new RingSlot();
ringSlot.data = data;
@@ -745,6 +760,14 @@ public class FakeInputWriter {
prevHatY = 0;
writeEvent(EV_ABS, ABS_HAT0Y, 0);
}
for (int i = 0; i < prevMouseButtons.length; i++) {
if (prevMouseButtons[i]) {
prevMouseButtons[i] = false;
writeEvent(EV_KEY, (short) (MOUSE_BTN_LEFT + i), 0);
}
}
pendingMouseX = 0;
pendingMouseY = 0;
if (hasChanges) {
writeEvent(EV_SYN, SYN_REPORT, 0);
@@ -874,4 +897,64 @@ public class FakeInputWriter {
public boolean isOpen() {
return isOpen;
}
public synchronized void writeMouseDelta(float dx, float dy) {
if (!isOpen && !open())
return;
pendingMouseX += dx;
pendingMouseY += dy;
int x = (int) Math.floor(pendingMouseX);
int y = (int) Math.floor(pendingMouseY);
if (x == 0 && y == 0)
return;
pendingMouseX -= x;
pendingMouseY -= y;
buffer.clear();
hasChanges = false;
if (x != 0) writeEvent(EV_REL, REL_X, x);
if (y != 0) writeEvent(EV_REL, REL_Y, y);
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse delta write error: fake input mmap ring unavailable");
}
public synchronized void writeMouseButton(short code, boolean pressed) {
if (code < MOUSE_BTN_LEFT || code > MOUSE_BTN_MIDDLE)
return;
int idx = code - MOUSE_BTN_LEFT;
if (!isOpen && !open())
return;
if (prevMouseButtons[idx] == pressed)
return;
prevMouseButtons[idx] = pressed;
buffer.clear();
hasChanges = false;
writeEvent(EV_KEY, code, pressed ? 1 : 0);
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse button write error: fake input mmap ring unavailable");
}
public synchronized void writeMouseWheel(int verticalClicks, int horizontalClicks, int value120) {
if (verticalClicks == 0 && horizontalClicks == 0)
return;
if (!isOpen && !open())
return;
buffer.clear();
hasChanges = false;
if (verticalClicks != 0) {
writeEvent(EV_REL, REL_WHEEL, verticalClicks);
writeEvent(EV_REL, REL_WHEEL_HI_RES, verticalClicks * value120);
}
if (horizontalClicks != 0) {
writeEvent(EV_REL, REL_HWHEEL, horizontalClicks);
writeEvent(EV_REL, REL_HWHEEL_HI_RES, horizontalClicks * value120);
}
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse wheel write error: fake input mmap ring unavailable");
}
}
@@ -23,6 +23,9 @@ class KeyboardHost(
private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
var shown = false
private set
var imeShowing = false
private set
var onImeChanged: ((Boolean) -> Unit)? = null
init {
isFocusable = false
@@ -42,6 +45,28 @@ class KeyboardHost(
return KeyConnection()
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val visible = insets.isVisible(WindowInsets.Type.ime())
if (visible != imeShowing) {
imeShowing = visible
onImeChanged?.invoke(visible)
}
}
return super.onApplyWindowInsets(insets)
}
override fun onKeyPreIme(keyCode: Int, event: KeyEvent): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R || keyCode != KeyEvent.KEYCODE_BACK || !shown) {
return super.onKeyPreIme(keyCode, event)
}
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) {
hide()
onImeChanged?.invoke(false)
}
return true
}
fun toggle() = if (shown && imeVisible()) hide() else show()
private fun imeVisible() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R ||
@@ -1,104 +1,22 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.ViewConfiguration
import kotlin.math.abs
import kotlin.math.roundToInt
class PointerGestures(
private val slopPx: Float,
private val listener: Listener,
) {
class PointerGestures {
interface Listener {
fun onMove(x: Float, y: Float)
fun onButton(button: Int, pressed: Boolean, x: Float, y: Float)
fun onWheel(steps: Int)
fun onLongPress()
}
private val handler = Handler(Looper.getMainLooper())
private var downX = 0f
private var downY = 0f
private var downAt = 0L
private var moved = false
private var held = false
private var dragging = false
private var scrolling = false
private var scrollAnchorY = 0f
private val longPress = Runnable {
held = true
listener.onLongPress()
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = event.x; downY = event.y; downAt = event.eventTime
moved = false; held = false; dragging = false; scrolling = false
listener.onMove(event.x, event.y)
handler.postDelayed(longPress, HOLD_MS)
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(longPress)
if (dragging) { listener.onButton(BTN_LEFT, false, event.x, event.y); dragging = false }
scrolling = true
scrollAnchorY = event.getY(0)
return true
}
MotionEvent.ACTION_MOVE -> {
if (scrolling) {
val dy = event.getY(0) - scrollAnchorY
val steps = (dy / SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * SCROLL_STEP_PX
}
return true
}
if (!moved && (abs(event.x - downX) > slopPx || abs(event.y - downY) > slopPx)) {
moved = true
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(BTN_LEFT, true, downX, downY)
}
}
if (moved) listener.onMove(event.x, event.y)
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(longPress)
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL
when {
scrolling -> {}
dragging -> listener.onButton(BTN_LEFT, false, event.x, event.y)
held && !moved && !cancelled -> {
listener.onButton(BTN_RIGHT, true, downX, downY)
listener.onButton(BTN_RIGHT, false, downX, downY)
}
!moved && !cancelled && event.eventTime - downAt < TAP_MS -> {
listener.onButton(BTN_LEFT, true, downX, downY)
listener.onButton(BTN_LEFT, false, downX, downY)
}
}
scrolling = false; dragging = false; held = false
return true
}
MotionEvent.ACTION_POINTER_UP -> return true
}
return false
fun onScroll(dx: Float, dy: Float) {}
fun onScrollEnd() {}
fun onZoom(steps: Int) {}
}
companion object {
const val BTN_LEFT = 0x110
const val BTN_RIGHT = 0x111
const val BTN_MIDDLE = 0x112
private const val HOLD_MS = 450L
private const val TAP_MS = 350L
private const val SCROLL_STEP_PX = 40f
fun slop(context: android.content.Context) = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
}
@@ -86,27 +86,14 @@ class ScrollTouchGestures(
lastY = startY
tracker = VelocityTracker.obtain().also { it.addMovement(event) }
listener.onMove(startX, startY)
handler.postDelayed(longPress, HOLD_MS)
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
MotionEvent.ACTION_MOVE -> {
val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true
tracker?.addMovement(event)
val x = event.getX(index)
val y = event.getY(index)
if (!scrolling && !dragging && hypot(x - startX, y - startY) > slopPx) {
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true)
} else {
scrolling = true
vertical = abs(y - startY) >= abs(x - startX)
lastX = startX
lastY = startY
}
}
if (dragging) listener.onMove(x, y)
follow(event, x, y)
for (h in 0 until event.historySize)
sample(event.getHistoricalX(index, h), event.getHistoricalY(index, h), event.getHistoricalEventTime(h))
sample(event.getX(index), event.getY(index), event.eventTime)
}
MotionEvent.ACTION_POINTER_UP -> {
if (event.getPointerId(event.actionIndex) == pointerId) cancel()
@@ -115,7 +102,7 @@ class ScrollTouchGestures(
handler.removeCallbacks(longPress)
if (pointerId == -1 || event.getPointerId(0) != pointerId) return true
tracker?.addMovement(event)
follow(event, event.x, event.y)
follow(event.x, event.y, event.eventTime)
when {
scrolling -> tracker?.takeIf { event.eventTime - movedAt <= FLING_STILL_MS }?.let { t ->
t.computeCurrentVelocity(1000)
@@ -139,9 +126,26 @@ class ScrollTouchGestures(
return true
}
private fun follow(event: MotionEvent, x: Float, y: Float) {
private fun sample(x: Float, y: Float, t: Long) {
if (!scrolling && !dragging && hypot(x - startX, y - startY) > slopPx) {
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true)
} else {
scrolling = true
vertical = abs(y - startY) >= abs(x - startX)
lastX = startX
lastY = startY
}
}
if (dragging) listener.onMove(x, y)
follow(x, y, t)
}
private fun follow(x: Float, y: Float, t: Long) {
if (!scrolling || (x == lastX && y == lastY)) return
movedAt = event.eventTime
movedAt = t
if (vertical) listener.onScroll(0f, lastY - y) else listener.onScroll(lastX - x, 0f)
lastX = x
lastY = y
@@ -151,7 +155,7 @@ class ScrollTouchGestures(
releaseClick()
listener.onButton(button, true)
clicked = button
handler.postDelayed(clickUp, CLICK_MS)
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
}
private fun releaseClick() {
@@ -181,8 +185,6 @@ class ScrollTouchGestures(
return if (pixels < 0) -units else units
}
private const val HOLD_MS = 500L
private const val CLICK_MS = 50L
private const val FLING_TIME_S = 0.45f
private const val FLING_STOP_PX = 40f
private const val FLING_STILL_MS = 60L
@@ -16,13 +16,19 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
private val handler = Handler(Looper.getMainLooper())
private val hostFile = File(context.filesDir, "session/android-clipboard")
private var active = false
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh() }
private var published = false
private var shared: String? = null
private var echo: String? = null
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh(changed = true) }
private val guestListener = object : WaylandCompositor.ClipboardListener {
override fun onGuestClipboardText(text: String) {
handler.post {
if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
val current = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
shared = text
published = true
if (current?.toString() != text) {
echo = text
clipboard.setPrimaryClip(ClipData.newPlainText("DroidDeck", text))
}
}
@@ -46,17 +52,23 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
handler.removeCallbacksAndMessages(null)
}
fun refresh() {
fun refresh(changed: Boolean = false) {
if (!active || !hasFocus()) return
val clip = clipboard.primaryClip
if (clip == null) {
publish(null)
} else if (clip.itemCount > 0) {
publish(clip.getItemAt(0).text?.toString())
if (clip != null && clip.itemCount == 0) return
val text = clip?.getItemAt(0)?.text?.toString()
if (echo != null && text == echo) {
echo = null
return
}
echo = null
if (!changed && published && text == shared) return
publish(text)
}
private fun publish(text: String?) {
published = true
shared = text
WaylandCompositor.setClipboardText(text)
val pending = File(hostFile.parentFile, "android-clipboard.pending")
try {
@@ -15,6 +15,7 @@ data class TouchGestureConfig(
val longPressAction: String = ACTION_RIGHT_CLICK,
val longPressMouseBehavior: String = MOUSE_BEHAVIOR_HOLD,
val longPressDelay: Int = DEFAULT_DELAY_MS,
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
val doubleTapEnabled: Boolean = true,
val doubleTapDelay: Int = DEFAULT_DELAY_MS,
val twoFingerDragEnabled: Boolean = true,
@@ -50,6 +51,7 @@ data class TouchGestureConfig(
put(KEY_LONG_PRESS_ACTION, longPressAction)
put(KEY_LONG_PRESS_MOUSE_BEHAVIOR, longPressMouseBehavior)
put(KEY_LONG_PRESS_DELAY, longPressDelay)
put(KEY_DIRECT_HOLD_BEHAVIOR, directHoldBehavior)
put(KEY_DOUBLE_TAP_ENABLED, doubleTapEnabled)
put(KEY_DOUBLE_TAP_DELAY, doubleTapDelay)
put(KEY_TWO_FINGER_DRAG_ENABLED, twoFingerDragEnabled)
@@ -85,6 +87,7 @@ data class TouchGestureConfig(
const val MOUSE_BEHAVIOR_HOLD = "hold"
const val MOUSE_BEHAVIOR_CLICK = "click"
const val MOUSE_BEHAVIOR_NONE = "none"
const val MOUSE_DRAG_MOVEMENT_DIRECT = "direct"
const val MOUSE_DRAG_MOVEMENT_RELATIVE = "relative"
@@ -110,6 +113,7 @@ data class TouchGestureConfig(
private const val KEY_LONG_PRESS_ACTION = "longPressAction"
private const val KEY_LONG_PRESS_MOUSE_BEHAVIOR = "longPressMouseBehavior"
private const val KEY_LONG_PRESS_DELAY = "longPressDelay"
private const val KEY_DIRECT_HOLD_BEHAVIOR = "directHoldBehavior"
private const val KEY_DOUBLE_TAP_ENABLED = "doubleTapEnabled"
private const val KEY_DOUBLE_TAP_DELAY = "doubleTapDelay"
private const val KEY_TWO_FINGER_DRAG_ENABLED = "twoFingerDragEnabled"
@@ -155,6 +159,9 @@ data class TouchGestureConfig(
obj.optString(KEY_LONG_PRESS_MOUSE_BEHAVIOR, MOUSE_BEHAVIOR_HOLD)
),
longPressDelay = obj.optInt(KEY_LONG_PRESS_DELAY, DEFAULT_DELAY_MS),
directHoldBehavior = normalizeDirectHoldBehavior(
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_CLICK)
),
doubleTapEnabled = obj.optBoolean(KEY_DOUBLE_TAP_ENABLED, true),
doubleTapDelay = obj.optInt(KEY_DOUBLE_TAP_DELAY, DEFAULT_DELAY_MS),
twoFingerDragEnabled = obj.optBoolean(KEY_TWO_FINGER_DRAG_ENABLED, true),
@@ -190,6 +197,10 @@ data class TouchGestureConfig(
}
}
private fun normalizeDirectHoldBehavior(value: String): String {
return if (value == MOUSE_BEHAVIOR_CLICK || value == MOUSE_BEHAVIOR_NONE) value else MOUSE_BEHAVIOR_HOLD
}
private fun normalizeMouseBehavior(value: String): String {
return if (value == MOUSE_BEHAVIOR_CLICK) MOUSE_BEHAVIOR_CLICK else MOUSE_BEHAVIOR_HOLD
}
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
object TouchRouter {
enum class Route { BLOCKED, GESTURES, SCROLL, OFF, TOUCHPAD, DIRECT }
data class Snapshot(
val uiBlocking: Boolean,
val mode: String,
val scrollLayer: Boolean,
val steamSession: Boolean,
val steamDesktopUi: Boolean,
)
fun decide(s: Snapshot): Route {
if (s.uiBlocking) return Route.BLOCKED
if (s.mode == SessionPrefs.TOUCH_GESTURES) return Route.GESTURES
if (s.scrollLayer) return Route.SCROLL
if (s.mode == SessionPrefs.TOUCH_OFF) return Route.OFF
return if (touchpad(s)) Route.TOUCHPAD else Route.DIRECT
}
fun steamKeyboardZone(s: Snapshot): Boolean = s.steamSession && !s.steamDesktopUi
private fun touchpad(s: Snapshot): Boolean = when (s.mode) {
SessionPrefs.TOUCH_PAD -> true
SessionPrefs.TOUCH_DIRECT -> false
else -> !s.steamSession || s.steamDesktopUi
}
}
@@ -0,0 +1,9 @@
package com.droiddeck.launcher.input
object TouchTiming {
const val HOLD_MS = 500L
const val TAP_MS = 300L
const val CLICK_MS = 30L
const val DOUBLE_TAP_MS = 300L
const val SCROLL_STEP_PX = 36f
}
@@ -4,6 +4,7 @@ import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import kotlin.math.abs
import kotlin.math.hypot
class TouchpadGestures(
private val slopPx: Float,
@@ -15,6 +16,7 @@ class TouchpadGestures(
private set
var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f)
var sensitivity = 1.15f
var desktop = false
private val handler = Handler(Looper.getMainLooper())
private var lastX = 0f
@@ -27,7 +29,11 @@ class TouchpadGestures(
private var secondDownAt = 0L
private var secondWasTap = false
private var twoFingers = false
private var scrollAnchorX = 0f
private var scrollAnchorY = 0f
private var fingers = 0
private var pinching = false
private var pinchSpan = 0f
private var scrolled = false
private var anchorId = -1
private var anchorStartX = 0f
@@ -52,7 +58,7 @@ class TouchpadGestures(
releaseClick()
listener.onButton(button, true, x, y)
clicked = button
handler.postDelayed(clickUp, CLICK_MS)
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
}
private fun releaseClick() {
@@ -79,6 +85,20 @@ class TouchpadGestures(
y = py.coerceIn(bounds.top, bounds.bottom)
}
private fun trackMove(px: Float, py: Float) {
val dx = px - lastX
val dy = py - lastY
lastX = px; lastY = py
travelled += abs(dx) + abs(dy)
if (travelled > slopPx) {
handler.removeCallbacks(longPress)
val speed = abs(dx) + abs(dy)
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
place(x + dx * gain, y + dy * gain)
listener.onMove(x, y)
}
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
@@ -86,18 +106,20 @@ class TouchpadGestures(
lastX = event.x; lastY = event.y
downAt = event.eventTime
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
fingers = 1; pinching = false
anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false
if (event.eventTime - lastTapAt < DOUBLE_TAP_MS) {
if (event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
} else {
dragging = false
handler.postDelayed(longPress, HOLD_MS)
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(longPress)
fingers = maxOf(fingers, event.pointerCount)
val i = event.actionIndex
if (moverId == -1 && event.getPointerId(i) != anchorId) {
moverId = event.getPointerId(i)
@@ -111,7 +133,9 @@ class TouchpadGestures(
twoFingers = true
secondDownAt = event.eventTime
secondWasTap = true
scrollAnchorX = (event.getX(0) + event.getX(1)) / 2f
scrollAnchorY = (event.getY(0) + event.getY(1)) / 2f
pinchSpan = span(event)
return true
}
MotionEvent.ACTION_MOVE -> {
@@ -146,29 +170,49 @@ class TouchpadGestures(
} else if (holdDrag) {
return true
}
if (twoFingers && event.pointerCount >= 2) {
val mid = (event.getY(0) + event.getY(1)) / 2f
val dy = mid - scrollAnchorY
val steps = (dy / SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * SCROLL_STEP_PX
if (twoFingers && event.pointerCount >= 2 && desktop) {
if (fingers >= 3) return true
val span = span(event)
if (!scrolled && !pinching && abs(span - pinchSpan) > slopPx * PINCH_SLOPS) {
pinching = true
secondWasTap = false
pinchSpan = span
}
if (pinching) {
val steps = ((span - pinchSpan) / PINCH_STEP_PX).toInt()
if (steps != 0) {
listener.onZoom(-steps)
pinchSpan += steps * PINCH_STEP_PX
}
return true
}
val midX = (event.getX(0) + event.getX(1)) / 2f
val midY = (event.getY(0) + event.getY(1)) / 2f
val dx = scrollAnchorX - midX
val dy = scrollAnchorY - midY
if (scrolled || abs(dx) + abs(dy) > slopPx) {
listener.onScroll(dx, dy)
scrollAnchorX = midX; scrollAnchorY = midY
scrolled = true
secondWasTap = false
}
return true
}
val dx = event.x - lastX
val dy = event.y - lastY
lastX = event.x; lastY = event.y
travelled += abs(dx) + abs(dy)
if (travelled > slopPx) {
handler.removeCallbacks(longPress)
val speed = (abs(dx) + abs(dy))
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
place(x + dx * gain, y + dy * gain)
listener.onMove(x, y)
if (twoFingers && event.pointerCount >= 2) {
val mid = (event.getY(0) + event.getY(1)) / 2f
val dy = mid - scrollAnchorY
val steps = (dy / TouchTiming.SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * TouchTiming.SCROLL_STEP_PX
scrolled = true
secondWasTap = false
}
return true
}
for (h in 0 until event.historySize)
trackMove(event.getHistoricalX(0, h), event.getHistoricalY(0, h))
trackMove(event.x, event.y)
return true
}
MotionEvent.ACTION_POINTER_UP -> {
@@ -194,7 +238,12 @@ class TouchpadGestures(
event.findPointerIndex(anchorId).takeIf { it >= 0 && it != event.actionIndex }?.let {
lastX = event.getX(it); lastY = event.getY(it)
}
if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TAP_MS && !scrolled) {
if (desktop && scrolled && event.pointerCount == 2) listener.onScrollEnd()
if (fingers >= 3) {
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2)
click(PointerGestures.BTN_MIDDLE)
if (event.pointerCount == 2) secondWasTap = false
} else if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TouchTiming.TAP_MS && !scrolled) {
click(PointerGestures.BTN_RIGHT)
secondWasTap = false
}
@@ -206,29 +255,30 @@ class TouchpadGestures(
when {
dragging -> listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
twoFingers -> {
if (secondWasTap && !scrolled && !cancelled && event.eventTime - downAt < TAP_MS * 2) {
if (secondWasTap && !scrolled && !cancelled && event.eventTime - downAt < TouchTiming.TAP_MS * 2) {
click(PointerGestures.BTN_RIGHT)
}
}
!cancelled && travelled <= slopPx && event.eventTime - downAt < TAP_MS -> {
!cancelled && travelled <= slopPx && event.eventTime - downAt < TouchTiming.TAP_MS -> {
click(PointerGestures.BTN_LEFT)
lastTapAt = event.eventTime
}
}
dragging = false; held = false; twoFingers = false
holdDrag = false; scrollLocked = false; anchorId = -1; moverId = -1
pinching = false; fingers = 0
return true
}
}
return false
}
private fun span(event: MotionEvent): Float =
if (event.pointerCount < 2) 0f else hypot(event.getX(0) - event.getX(1), event.getY(0) - event.getY(1))
companion object {
private const val HOLD_MS = 500L
private const val TAP_MS = 300L
private const val CLICK_MS = 50L
private const val DOUBLE_TAP_MS = 300L
private const val SCROLL_STEP_PX = 36f
private const val PINCH_SLOPS = 3f
private const val PINCH_STEP_PX = 60f
private const val HOLD_DRAG_MOVER_SLOPS = 2f
private const val HOLD_DRAG_ANCHOR_SLOPS = 0.5f
}
@@ -36,7 +36,7 @@ public final class TouchscreenGestures {
private final Output output;
private final float doubleTapSlop;
private TouchGestureConfig gestureConfig = new TouchGestureConfig();
private static final int CLICK_DELAYED_TIME = 50;
private static final int CLICK_DELAYED_TIME = 30;
private Runnable delayedPress, pendingHoldClickRelease;
private Runnable pendingTapPress;
private final ArrayDeque<TapClick> pendingTapClicks = new ArrayDeque<>();
@@ -0,0 +1,205 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import kotlin.math.abs
import kotlin.math.hypot
class TwoFingerGestures(private val slopPx: Float, private val listener: Listener) {
interface Listener {
fun cancelTouch()
fun replay(event: MotionEvent)
fun rightClick(x: Float, y: Float)
fun scrollStart(x: Float, y: Float)
fun scroll(dx: Float, dy: Float)
fun scrollEnd()
}
private enum class State { IDLE, PENDING, CANDIDATE, TAPPED, HELD, SCROLLING, PASSING }
private val handler = Handler(Looper.getMainLooper())
private var state = State.IDLE
private var x = 0f
private var y = 0f
private var twoAt = 0L
private var startSpan = 0f
private var lastX = 0f
private var lastY = 0f
private val starts = HashMap<Int, Pair<Float, Float>>()
private val held = ArrayList<MotionEvent>()
private val hold = Runnable {
if (state != State.CANDIDATE) return@Runnable
state = State.HELD
drop()
listener.cancelTouch()
listener.rightClick(x, y)
}
private val release = Runnable {
if (state == State.PENDING) pass(State.IDLE)
}
fun cancel() {
if (state == State.SCROLLING) listener.scrollEnd()
handler.removeCallbacks(hold)
handler.removeCallbacks(release)
drop()
state = State.IDLE
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
cancel()
starts.clear()
x = event.x
y = event.y
note(event, event.actionIndex)
state = State.PENDING
keep(event)
handler.postDelayed(release, LAND_MS)
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
note(event, event.actionIndex)
when (state) {
State.PENDING -> {
handler.removeCallbacks(release)
keep(event)
if (event.pointerCount != 2) {
pass(State.PASSING)
return true
}
state = State.CANDIDATE
twoAt = event.eventTime
startSpan = span(event)
lastX = midX(event)
lastY = midY(event)
handler.postDelayed(hold, HOLD_MS)
return true
}
State.CANDIDATE -> {
keep(event)
pass(State.PASSING)
return true
}
State.SCROLLING, State.HELD, State.TAPPED -> return true
else -> Unit
}
}
MotionEvent.ACTION_MOVE -> when (state) {
State.PENDING -> {
keep(event)
if (moved(event)) pass(State.IDLE)
return true
}
State.CANDIDATE -> {
if (event.pointerCount == 2 && moved(event)) {
handler.removeCallbacks(hold)
if (abs(span(event) - startSpan) > slopPx * 2) {
keep(event)
pass(State.PASSING)
return true
}
state = State.SCROLLING
drop()
listener.cancelTouch()
lastX = midX(event)
lastY = midY(event)
listener.scrollStart(lastX, lastY)
return true
}
keep(event)
return true
}
State.SCROLLING -> {
if (event.pointerCount >= 2) {
val mx = midX(event)
val my = midY(event)
listener.scroll(lastX - mx, lastY - my)
lastX = mx
lastY = my
}
return true
}
State.TAPPED, State.HELD -> return true
else -> Unit
}
MotionEvent.ACTION_POINTER_UP -> when (state) {
State.CANDIDATE -> {
handler.removeCallbacks(hold)
keep(event)
if (event.eventTime - twoAt < TAP_MS) {
state = State.TAPPED
drop()
return true
}
pass(State.PASSING)
return true
}
State.SCROLLING, State.HELD, State.TAPPED -> return true
else -> Unit
}
MotionEvent.ACTION_UP -> {
val was = state
if (was == State.PENDING) {
keep(event)
pass(State.IDLE)
return true
}
cancel()
when (was) {
State.TAPPED -> {
listener.cancelTouch()
listener.rightClick(x, y)
return true
}
State.SCROLLING, State.HELD -> return true
else -> Unit
}
}
MotionEvent.ACTION_CANCEL -> cancel()
}
return false
}
private fun keep(event: MotionEvent) {
held += MotionEvent.obtain(event)
}
private fun drop() {
held.forEach { it.recycle() }
held.clear()
}
private fun pass(next: State) {
handler.removeCallbacks(release)
handler.removeCallbacks(hold)
state = next
val events = held.toList()
held.clear()
events.forEach {
listener.replay(it)
it.recycle()
}
}
private fun note(event: MotionEvent, index: Int) {
starts[event.getPointerId(index)] = event.getX(index) to event.getY(index)
}
private fun moved(event: MotionEvent): Boolean = (0 until event.pointerCount).any { i ->
val start = starts[event.getPointerId(i)] ?: return@any false
hypot(event.getX(i) - start.first, event.getY(i) - start.second) > slopPx
}
private fun span(event: MotionEvent) = hypot(event.getX(1) - event.getX(0), event.getY(1) - event.getY(0))
private fun midX(event: MotionEvent) = (event.getX(0) + event.getX(1)) / 2f
private fun midY(event: MotionEvent) = (event.getY(0) + event.getY(1)) / 2f
companion object {
const val LAND_MS = 250L
const val TAP_MS = 350L
const val HOLD_MS = 500L
}
}
@@ -180,7 +180,8 @@ object BwrapSpawner {
val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
preload(session, rootfs, env).forEach { addBind(it) }
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
if (preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
zypakShims(binds, root, dir).forEach { addBind(it) }
browserSandboxes(env)
return Plan(root, binds, request.optString("cwd", "/").ifEmpty { "/" }, argv, env)
@@ -188,16 +189,20 @@ object BwrapSpawner {
private const val GPU_DIR = "/run/droiddeck-gpu"
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")
private fun runtimeLib(rootfs: String, name: String): File? =
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
val lib = File(rootfs, "usr/lib")
val driver = File(lib, "libvulkan_freedreno.so")
if (!driver.isFile || !File("/dev/kgsl-3d0").exists()) return null
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
if (driver == null || !File("/dev/kgsl-3d0").exists()) return null
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
if (env["BL_DESKTOP"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
val binds = ArrayList<Bind>()
for (name in listOf("libvulkan_freedreno.so", "libdisplay-info.so.3", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")) {
val f = File(lib, name)
if (!f.exists()) { Log.w(TAG, "gpu: the runtime has no $name; apps draw on the CPU"); return null }
val binds = arrayListOf(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_freedreno.so"))
for (name in GPU_LIBS) {
val f = runtimeLib(rootfs, name) ?: continue
binds.add(Bind(f.canonicalPath, "$GPU_DIR/$name"))
}
val icd = File(root.parentFile, "freedreno_icd.json")
@@ -227,6 +232,27 @@ object BwrapSpawner {
return binds
}
private val GLIBC_RELEASE = Regex("release version 2\\.(\\d+)")
private val GLIBC_NEED = Regex("GLIBC_2\\.(\\d+)")
private val glibcMinors = java.util.concurrent.ConcurrentHashMap<String, Int>()
private fun glibcMinor(file: File, pattern: Regex, pick: (Sequence<Int>) -> Int?): Int? {
val key = "${file.path}:${file.length()}:${file.lastModified()}:${pattern.pattern}"
glibcMinors[key]?.let { return it }
val text = runCatching { String(file.readBytes(), Charsets.ISO_8859_1) }.getOrNull() ?: return null
return pick(pattern.findAll(text).map { it.groupValues[1].toInt() })?.also { glibcMinors[key] = it }
}
internal fun preloadFits(rootfs: String, sandboxLibc: String): Boolean {
val libc = File(sandboxLibc)
if (!libc.isFile) return true
val have = glibcMinor(libc, GLIBC_RELEASE) { it.firstOrNull() } ?: return true
val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
?.map { it.trim() }?.filter { it.startsWith("/") } ?: return true
val need = libs.mapNotNull { File(rootfs + it).takeIf { f -> f.isFile }?.let { f -> glibcMinor(f, GLIBC_NEED) { m -> m.maxOrNull() } } }.maxOrNull() ?: return true
return have >= need
}
private const val PRELOAD_DIR = "/run/droiddeck-preload"
private const val NET_LINK = "etc/droiddeck-net"
@@ -321,7 +347,15 @@ object BwrapSpawner {
catch (e: IOException) { }
if (process.isAlive) {
Log.i(TAG, "sandbox $id: its bwrap is gone; stopping it")
process.destroy()
if (pid > 0) {
runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) }
} else {
process.destroy()
}
try {
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) process.destroyForcibly()
} catch (_: InterruptedException) {
}
}
}, "bwrap-$id-watch").apply { isDaemon = true; start() }
val buffer = ByteArray(16384)
@@ -115,19 +115,27 @@ object DesktopCatalog {
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
const val DESKTOP_ID = "desktop-kde"
const val EMULATORS_ID = "emulators"
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
fun desktopEntry(context: Context) = Entry(
DESKTOP_ID, context.getString(R.string.content_linux_desktop), 1, BuildConfig.DESKTOP_KDE_TAG, "tar",
BuildConfig.DESKTOP_KDE_URL, BuildConfig.DESKTOP_KDE_SHA256, BuildConfig.DESKTOP_KDE_SIZE, "",
"", "",
)
fun desktopEntry(context: Context): Entry {
val pack = DesktopPack.info(LinuxRuntime.rootDir(context))
return Entry(
DESKTOP_ID, context.getString(R.string.content_linux_desktop), 1, pack?.tag ?: BuildConfig.DESKTOP_KDE_TAG, "tar",
pack?.url ?: BuildConfig.DESKTOP_KDE_URL, pack?.sha256 ?: BuildConfig.DESKTOP_KDE_SHA256,
pack?.size ?: BuildConfig.DESKTOP_KDE_SIZE, "", "", "",
)
}
fun desktopInstalled(context: Context): Boolean = desktopInstalled(LinuxRuntime.rootDir(context))
fun desktopFromPack(root: File): Boolean = DesktopPack.info(root) != null
fun desktopInstalled(root: File): Boolean =
!File(root, DesktopRemoval.PENDING).exists() &&
File(root, "usr/bin/kwin_wayland").isFile &&
FileUtils.readString(File(root, ".droiddeck-pkg-$DESKTOP_ID"))?.trim() == BuildConfig.DESKTOP_KDE_TAG
FileUtils.readString(File(root, ".droiddeck-pkg-$DESKTOP_ID"))?.trim() ==
(DesktopPack.info(root)?.tag ?: BuildConfig.DESKTOP_KDE_TAG)
fun desktopPresent(context: Context): Boolean {
val root = LinuxRuntime.rootDir(context)
@@ -169,6 +177,7 @@ object DesktopCatalog {
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val root = LinuxRuntime.rootDir(context)
if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing)
if (entry.id == EMULATORS_ID && desktopFromPack(root)) return installEmulators(context, entry, cancelled, listener)
if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name)
val download = downloadFile(context, entry)
val journal = journal(root, entry.id)
@@ -217,11 +226,12 @@ object DesktopCatalog {
check(FileUtils.writeString(journal, entryJson(entry).toString())) { "Could not record the package installation" }
keepDownload = true
marker(context, entry.id).delete()
if (entry.id == DESKTOP_ID && desktopFromPack(root)) DesktopPack.prepareInstall(root)
if (!LinuxRuntimeInstaller.extract(context, download, root, report)) return context.getString(R.string.deskpkg_extract_failed)
}
}
if (entry.id == DESKTOP_ID) {
cleanLegacy(context, report)
if (desktopFromPack(root)) DesktopPack.finishInstall(root) else cleanLegacy(context, report)
val pending = File(root, DesktopRemoval.PENDING)
check(!pending.exists() || pending.delete()) { "Could not finish desktop installation" }
}
@@ -239,6 +249,47 @@ object DesktopCatalog {
}
}
private fun installEmulators(context: Context, entry: Entry, cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val release = RuntimeInstallService.holdForPackage(context, context.getString(R.string.deskpkg_installing, entry.name))
val stop = java.util.concurrent.atomic.AtomicBoolean(false)
val finished = java.util.concurrent.atomic.AtomicBoolean(false)
cancelled?.let { token ->
Thread({
try {
while (!finished.get() && !stop.get()) {
if (token.getAsBoolean()) stop.set(true) else Thread.sleep(200)
}
} catch (_: InterruptedException) {
}
}, "emulators-cancel").apply { isDaemon = true; start() }
}
try {
var failure: String? = null
val status = GuestCommand.run(context, listOf("/bin/bash", EMULATORS_SCRIPT, "install"), logName = "emulators",
cancelled = stop) { line ->
when {
line.startsWith("== STEP ") -> {
val stage = context.getString(R.string.deskpkg_installing, line.removePrefix("== STEP "))
RuntimeInstallService.packageProgress(stage, -1)
listener?.onProgress(stage, -1)
}
line.startsWith("== FAIL ") -> failure = line.removePrefix("== FAIL ")
}
}
if (stop.get()) return context.getString(R.string.user_apps_download_failed)
if (failure != null || status != 0) return context.getString(R.string.deskpkg_install_failed)
check(FileUtils.writeString(marker(context, entry.id), entry.version)) { "Could not finish package installation" }
return null
} catch (e: Exception) {
Log.e(TAG, "install ${entry.id}", e)
return e.message ?: context.getString(R.string.deskpkg_install_failed)
} finally {
finished.set(true)
release()
}
}
private fun unzipAppImage(zip: File, target: File): Boolean {
try {
java.util.zip.ZipInputStream(java.io.BufferedInputStream(java.io.FileInputStream(zip))).use { zin ->
@@ -73,10 +73,42 @@ internal object DesktopFileRemoval {
}
}
private val RECORD = Regex("[A-Za-z0-9@._+:-]+")
fun desktopRecords(root: File): Set<String> {
val list = safeFile(root, "usr/share/droiddeck/pacman/desktop-packages.txt") ?: return emptySet()
if (!Files.isRegularFile(list.toPath(), NOFOLLOW_LINKS)) return emptySet()
return list.readLines().mapNotNull { line ->
line.split(' ').takeIf { it.size == 2 }?.let { "${it[0]}-${it[1]}" }?.takeIf { RECORD.matches(it) && it != "." && it != ".." }
}.toSet()
}
fun removeRecords(root: File, records: Set<String>) {
val lib = File(root, "var/lib/pacman")
if (Files.isSymbolicLink(File(root, "var").toPath()) || Files.isSymbolicLink(lib.toPath())) return
val local = File(lib, "local")
if (!local.isDirectory || Files.isSymbolicLink(local.toPath())) return
for (record in records) {
if (!RECORD.matches(record) || record == "." || record == "..") continue
val dir = File(local, record)
if (Files.isSymbolicLink(dir.toPath()) || !dir.isDirectory) continue
for (file in dir.listFiles().orEmpty()) {
if (Files.isSymbolicLink(file.toPath()) || file.isFile) Files.delete(file.toPath())
}
if (!dir.delete()) throw IOException("Cannot remove $dir")
}
for (name in listOf("sync/droiddeck.db", "droiddeck-desktop")) {
val file = File(lib, name)
if (Files.isSymbolicLink(file.toPath()) || file.isFile) Files.delete(file.toPath())
}
}
fun runtimeFiles(root: File): Set<String> = buildSet {
val database = File(root, "var/lib/pacman/local")
if (!database.isDirectory || Files.isSymbolicLink(database.toPath())) throw IOException("Runtime package database missing")
val desktop = desktopRecords(root)
for (pkg in database.listFiles().orEmpty()) {
if (pkg.name in desktop) continue
val files = File(pkg, "files")
if (!pkg.isDirectory || Files.isSymbolicLink(pkg.toPath()) || !files.isFile || Files.isSymbolicLink(files.toPath())) continue
var inFiles = false
@@ -0,0 +1,178 @@
package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.Hashes
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.util.zip.GZIPInputStream
import org.json.JSONObject
internal object DesktopPack {
const val INFO = "usr/share/droiddeck/desktop-pack.json"
const val META = "usr/share/droiddeck/desktop"
private const val MANIFEST = "$META/files.tsv.gz"
private const val ORIGINALS = "$META/originals"
private const val STATUS = "var/lib/dpkg/status"
private const val STATUS_BEFORE = "var/lib/dpkg/status.droiddeck"
private const val PACK_STATUS = "$META/dpkg-status"
data class Info(val tag: String, val url: String, val sha256: String, val size: Long)
data class Entry(val kind: Char, val type: Char, val size: Long, val value: String, val path: String) {
companion object {
fun parse(line: String): Entry? {
val parts = line.split('\t', limit = 5)
if (parts.size != 5 || parts[0].length != 1 || parts[1].length != 1) return null
return Entry(parts[0][0], parts[1][0], parts[2].toLongOrNull() ?: return null, parts[3], parts[4])
}
}
}
data class Result(val removed: Int, val restored: Int, val kept: Int)
fun info(root: File): Info? = runCatching {
val json = JSONObject(FileUtils.readString(File(root, INFO)) ?: return null)
Info(json.getString("tag"), json.getString("url"), json.getString("sha256"), json.getLong("size"))
}.getOrNull()
fun installed(root: File): Boolean = File(root, MANIFEST).isFile
fun entries(root: File): List<Entry> =
GZIPInputStream(File(root, MANIFEST).inputStream()).bufferedReader().use { reader ->
reader.lineSequence().mapNotNull(Entry::parse).toList()
}
fun installedSize(root: File): Long =
if (installed(root)) entries(root).filter { it.kind == 'N' && it.type == 'F' }.sumOf { it.size } else 0L
fun prepareInstall(root: File) {
val live = File(root, STATUS)
val before = File(root, STATUS_BEFORE)
if (!before.exists() && live.isFile) Files.copy(live.toPath(), before.toPath(), StandardCopyOption.COPY_ATTRIBUTES)
}
fun finishInstall(root: File) {
for (entry in entries(root).filter { it.kind == 'R' }.sortedByDescending { it.path.length }) {
val file = inside(root, entry.path) ?: continue
if (entry.type == 'D') file.delete() else Files.deleteIfExists(file.toPath())
}
val live = File(root, STATUS)
val packStatus = File(root, PACK_STATUS)
if (live.isFile && !packStatus.exists()) Files.copy(live.toPath(), packStatus.toPath())
val before = File(root, STATUS_BEFORE)
val runtime = File(File(root, ORIGINALS), STATUS)
if (before.isFile && runtime.isFile && live.isFile) {
writeStatus(live, mergeStatus(runtime.readText(), packStatus.readText(), before.readText()))
}
Files.deleteIfExists(before.toPath())
}
internal fun mergeStatus(base: String, target: String, mine: String): String {
val from = stanzas(base)
val into = LinkedHashMap(stanzas(target))
val kept = stanzas(mine)
for ((key, stanza) in kept) {
if (from[key] != stanza && into[key] == from[key]) into[key] = stanza
}
for (key in from.keys) {
if (key !in kept && into[key] == from[key]) into.remove(key)
}
return into.values.joinToString("") { it + "\n\n" }
}
private fun stanzas(text: String): Map<String, String> {
val out = LinkedHashMap<String, String>()
for (stanza in text.split(Regex("\n[ \t]*\n")).map { it.trim('\n') }.filter { it.isNotBlank() }) {
val fields = stanza.lines()
fun field(name: String) = fields.firstOrNull { it.startsWith("$name:") }?.substringAfter(':')?.trim().orEmpty()
out["${field("Package")}:${field("Architecture")}"] = stanza
}
return out
}
private fun writeStatus(file: File, text: String) {
val part = LinuxRuntimeInstaller.partFile(file).toPath()
Files.deleteIfExists(part)
Files.copy(file.toPath(), part, StandardCopyOption.COPY_ATTRIBUTES)
Files.write(part, text.toByteArray(), java.nio.file.StandardOpenOption.TRUNCATE_EXISTING)
Files.move(part, file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
}
fun remove(root: File, progress: (Int) -> Unit = {}): Result {
val entries = entries(root)
var removed = 0
var restored = 0
var kept = 0
val originals = File(root, ORIGINALS)
val live = File(root, STATUS)
val userStatus = if (live.isFile) live.readText() else null
for (entry in entries.filter { it.kind == 'C' || it.kind == 'R' }) {
val file = inside(root, entry.path) ?: continue
if (entry.type == 'D') {
file.mkdirs()
continue
}
if (entry.kind == 'C' && !entry.path.startsWith("var/lib/dpkg/") && !matchesOrMissing(file, entry)) {
kept++
continue
}
val source = inside(originals, entry.path) ?: continue
val sourcePath = source.toPath()
if (!Files.exists(sourcePath, LinkOption.NOFOLLOW_LINKS)) continue
file.parentFile?.mkdirs()
val part = LinuxRuntimeInstaller.partFile(file).toPath()
Files.deleteIfExists(part)
if (Files.isSymbolicLink(sourcePath)) Files.createSymbolicLink(part, Files.readSymbolicLink(sourcePath))
else Files.copy(sourcePath, part, StandardCopyOption.COPY_ATTRIBUTES)
if (Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS)) FileUtils.delete(file)
Files.move(part, file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
restored++
}
val added = entries.filter { it.kind == 'N' }
val directories = ArrayList<File>()
added.forEachIndexed { index, entry ->
val file = inside(root, entry.path)
when {
file == null -> kept++
entry.type == 'D' -> directories += file
matches(file, entry) -> { Files.deleteIfExists(file.toPath()); removed++ }
Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS) -> kept++
}
if (index % 2000 == 0) progress(index * 100 / added.size.coerceAtLeast(1))
}
for (dir in directories.sortedByDescending { it.path.length }) {
if (Files.isDirectory(dir.toPath(), LinkOption.NOFOLLOW_LINKS) && dir.list()?.isEmpty() == true) dir.delete()
}
val packStatus = File(root, PACK_STATUS)
if (userStatus != null && packStatus.isFile && live.isFile) {
writeStatus(live, mergeStatus(packStatus.readText(), live.readText(), userStatus))
}
FileUtils.delete(File(root, META))
return Result(removed, restored, kept)
}
private fun matchesOrMissing(file: File, entry: Entry) =
!Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS) || matches(file, entry)
private fun matches(file: File, entry: Entry): Boolean {
val path = file.toPath()
return when (entry.type) {
'L' -> Files.isSymbolicLink(path) && Files.readSymbolicLink(path).toString() == entry.value
'F' -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) && file.length() == entry.size &&
Hashes.sha256(file).equals(entry.value, ignoreCase = true)
else -> false
}
}
internal fun inside(root: File, path: String): File? {
if (path.isEmpty() || path.startsWith("/")) return null
val normal = Paths.get(path).normalize()
if (normal.toString().isEmpty() || normal.startsWith("..")) return null
val parent = normal.parent
val dir = if (parent == null) root else com.droiddeck.launcher.core.ArchivePaths.inside(root, parent.toString()) ?: return null
return File(dir, normal.fileName.toString())
}
}
@@ -18,8 +18,11 @@ internal object DesktopRemoval {
private fun protected(context: Context, root: File) =
DesktopFileRemoval.runtimeFiles(root) + lines(context, "emulators-keep.txt.gzip")
fun installedSize(context: Context): Long =
lines(context, "kde-remove.tsv.gzip").sumOf { line -> line.split('\t').getOrNull(1)?.toLongOrNull() ?: 0L }
fun installedSize(context: Context): Long {
val root = LinuxRuntime.rootDir(context)
if (DesktopPack.info(root) != null) return DesktopPack.installedSize(root)
return lines(context, "kde-remove.tsv.gzip").sumOf { line -> line.split('\t').getOrNull(1)?.toLongOrNull() ?: 0L }
}
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) {
val root = LinuxRuntime.rootDir(context)
@@ -40,8 +43,12 @@ internal object DesktopRemoval {
Log.i("DesktopRemoval", "LXQt: $result")
}
fun remove(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
fun remove(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? {
val root = LinuxRuntime.rootDir(context)
return if (DesktopPack.info(root) != null) removePack(context, root, listener) else removeLegacy(context, root, listener)
}
private fun removeLegacy(context: Context, root: File, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
val pending = File(root, PENDING)
val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
val installing = DesktopCatalog.interrupted(root).firstOrNull { it.id == DesktopCatalog.DESKTOP_ID }
@@ -50,12 +57,14 @@ internal object DesktopRemoval {
check(version in versions && (installing == null || installing.version in versions)) { context.getString(R.string.desktop_removal_unknown) }
val entries = lines(context, "kde-remove.tsv.gzip").map(DesktopFileRemoval.Entry::parse)
val keep = protected(context, root)
val records = DesktopFileRemoval.desktopRecords(root)
cleanLegacy(context, listener)
FileUtils.writeString(pending, version!!)
check(FileUtils.readString(pending)?.trim() == version) { "Could not reserve desktop removal" }
if (marker.exists() && !marker.delete()) error("Could not clear desktop marker")
val removing = context.getString(R.string.desktop_removing)
val result = DesktopFileRemoval.remove(root, entries, keep) { listener.onProgress(removing, it) }
DesktopFileRemoval.removeRecords(root, records)
for ((asset, path) in com.droiddeck.launcher.session.SessionFiles.DESKTOP_FILES) {
val target = DesktopFileRemoval.safeFile(root, path) ?: continue
if (!isRegularFile(target)) continue
@@ -74,5 +83,29 @@ internal object DesktopRemoval {
e.message ?: context.getString(R.string.deskpkg_install_failed)
}
private fun removePack(context: Context, root: File, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
val pending = File(root, PENDING)
val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
FileUtils.writeString(pending, DesktopPack.info(root)!!.tag)
check(pending.isFile) { "Could not reserve desktop removal" }
if (marker.exists() && !marker.delete()) error("Could not clear desktop marker")
val removing = context.getString(R.string.desktop_removing)
for ((_, path) in com.droiddeck.launcher.session.SessionFiles.DESKTOP_FILES) {
DesktopFileRemoval.safeFile(root, path)?.takeIf { isRegularFile(it) }?.delete()
}
for (path in DESKTOP_STATE) DesktopPack.inside(root, path)?.let(FileUtils::delete)
val result = if (DesktopPack.installed(root)) DesktopPack.remove(root) { listener.onProgress(removing, it) } else null
DesktopCatalog.discardDesktopInstall(context)
if (!pending.delete()) error("Could not finish desktop removal")
Log.i("DesktopRemoval", "pack: $result")
listener.onProgress(context.getString(R.string.desktop_removed), 100)
null
} catch (e: Exception) {
Log.e("DesktopRemoval", "remove", e)
e.message ?: context.getString(R.string.deskpkg_install_failed)
}
private val DESKTOP_STATE = listOf("var/lib/PackageKit", "var/cache/swcatalog")
private fun isRegularFile(file: File) = java.nio.file.Files.isRegularFile(file.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)
}
@@ -43,7 +43,7 @@ object GuestCommand {
val fastPathKey = if (fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
cmd += listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
@@ -115,7 +115,7 @@ public final class LinuxRuntime {
public static boolean isInstalled(Context context) {
if (LinuxRuntimeInstaller.isRemoving() || LinuxRuntimeInstaller.hasRemovalPending(context)) return false;
File root = rootDir(context);
return new File(root, "usr/bin/gamescope").isFile()
return (new File(root, "usr/bin/gamescope").isFile() || new File(root, "usr/games/gamescope").isFile())
&& (new File(root, SESSION_SCRIPT.substring(1)).isFile()
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile())
&& (patchedProot(context) || rootfsProotReady(context));
@@ -487,12 +487,72 @@ public final class LinuxRuntime {
+ "\\" + host.version + "\\" + host.machine + "\\localdomain\\-1\\";
}
public static void writeAccounts(Context context) throws IOException {
public static synchronized void writeAccounts(Context context) throws IOException {
File root = rootDir(context);
int uid = Process.myUid();
Files.write(new File(root, "etc/passwd").toPath(),
("root:x:" + uid + ":" + uid + ":root:/root:/bin/bash\n").getBytes(StandardCharsets.UTF_8));
Files.write(new File(root, "etc/group").toPath(),
("root:x:" + uid + ":\n").getBytes(StandardCharsets.UTF_8));
mergeAccounts(new File(root, "etc/passwd"), 2,
"root:x:" + uid + ":" + uid + ":root:/root:/bin/bash", "root:x:0:0:root:/root:/bin/bash", uid);
mergeAccounts(new File(root, "etc/group"), 2,
"root:x:" + uid + ":", "root:x:0:", uid);
File group = new File(root, "etc/group");
String groups = new String(Files.readAllBytes(group.toPath()), StandardCharsets.UTF_8);
writeIfChanged(group, groups, withStorageGroups(groups));
}
private static final String[][] STORAGE_GROUPS = {
{"sdcard_rw", "1015"}, {"media_rw", "1023"}, {"everybody", "9997"}};
static String withStorageGroups(String groups) {
StringBuilder out = new StringBuilder();
List<String> present = new ArrayList<>();
for (String line : groups.split("\n")) {
if (line.trim().isEmpty()) continue;
String[] fields = line.split(":", -1);
if (fields.length >= 4) {
for (String[] storage : STORAGE_GROUPS) {
if (fields[0].equals(storage[0])) present.add(storage[0]);
if (!fields[2].equals(storage[1])) continue;
present.add(storage[0]);
if (!java.util.Arrays.asList(fields[3].split(",")).contains("root")) {
fields[3] = fields[3].isEmpty() ? "root" : fields[3] + ",root";
line = String.join(":", fields);
}
}
}
out.append(line).append('\n');
}
for (String[] storage : STORAGE_GROUPS) {
if (!present.contains(storage[0])) {
out.append(storage[0]).append(":x:").append(storage[1]).append(":root\n");
}
}
return out.toString();
}
static String mergedAccounts(String existing, int idField, String own, String zero, int uid) {
StringBuilder out = new StringBuilder(own).append('\n').append(zero).append('\n');
if (existing == null) return out.toString();
String ownId = Integer.toString(uid);
for (String line : existing.split("\n")) {
if (line.trim().isEmpty()) continue;
String[] fields = line.split(":", -1);
if (fields.length <= idField) continue;
if (fields[0].equals("root") || fields[idField].equals("0") || fields[idField].equals(ownId)) continue;
out.append(line).append('\n');
}
return out.toString();
}
private static void mergeAccounts(File file, int idField, String own, String zero, int uid) throws IOException {
String existing = file.isFile() ? new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8) : null;
writeIfChanged(file, existing, mergedAccounts(existing, idField, own, zero, uid));
}
private static void writeIfChanged(File file, String existing, String merged) throws IOException {
if (merged.equals(existing)) return;
File staged = File.createTempFile(file.getName(), ".staged", file.getParentFile());
Files.write(staged.toPath(), merged.getBytes(StandardCharsets.UTF_8));
Files.move(staged.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.ATOMIC_MOVE);
}
}
@@ -35,7 +35,7 @@ public final class LinuxRuntimeInstaller {
private static final String TAG = "LinuxRuntimeInstaller";
public static final String CATALOG_URL =
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/linuxfs.json";
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/linuxfs-ubuntu.json";
private static final String VERSION_FILE = ".version";
@@ -88,8 +88,20 @@ public final class LinuxRuntimeInstaller {
return v == null ? null : v.trim();
}
private static String catalogUrl() {
if (!com.droiddeck.launcher.BuildConfig.DEBUG) return CATALOG_URL;
try {
Object value = Class.forName("android.os.SystemProperties").getMethod("get", String.class)
.invoke(null, "debug.droiddeck.linuxfs");
if (value instanceof String && ((String) value).startsWith("http")) return (String) value;
} catch (ReflectiveOperationException e) {
Log.w(TAG, "catalog override: " + e);
}
return CATALOG_URL;
}
public static Release fetchRelease() {
String body = Downloader.downloadString(CATALOG_URL);
String body = Downloader.downloadString(catalogUrl());
if (body == null || body.isEmpty()) return null;
try {
JSONObject json = new JSONObject(body);
@@ -292,7 +304,7 @@ public final class LinuxRuntimeInstaller {
recoverInterruptedSwap(root, staging, old);
if (!discard(staging, null) || !staging.mkdirs()) return false;
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1);
if (!extract(context, archive, staging, listener)) {
if (!extract(context, archive, staging, root, listener)) {
RuntimeFileTree.delete(staging, null);
return false;
}
@@ -346,7 +358,11 @@ public final class LinuxRuntimeInstaller {
return false;
}
new File(root, CARRY_MARKER).delete();
try { RuntimeFileTree.dropStaleState(root); }
catch (IOException e) { Log.w(TAG, "could not clear caches left by the previous runtime", e); }
discard(old, null);
try { com.droiddeck.launcher.session.SessionFiles.INSTANCE.stage(context, root, false); }
catch (Exception e) { Log.w(TAG, "could not stage the session files into the new runtime", e); }
return LinuxRuntime.isInstalled(context);
} catch (Exception e) {
Log.e(TAG, "install", e);
@@ -513,6 +529,10 @@ public final class LinuxRuntimeInstaller {
// Packages extract over the live runtime and their archives list a link before the file it
// names, so a kill mid-way must leave neither a truncated file nor a link to a missing one.
public static boolean extract(Context context, File archive, File destination, ProgressListener listener) {
return extract(context, archive, destination, destination, listener);
}
static boolean extract(Context context, File archive, File destination, File linkRoot, ProgressListener listener) {
long entries = 0;
String extracting = context.getString(R.string.rtinst_extracting);
java.util.LinkedHashMap<File, String> links = new java.util.LinkedHashMap<>();
@@ -537,7 +557,7 @@ public final class LinuxRuntimeInstaller {
links.remove(file);
links.put(file, entry.getLinkName());
} else if (entry.isLink()) {
File target = ArchivePaths.inside(destination, entry.getLinkName());
File target = hardLinkTarget(destination, entry.getLinkName());
if (target == null) {
Log.w(TAG, "skipping hard link outside the rootfs: " + entry.getLinkName());
continue;
@@ -548,11 +568,11 @@ public final class LinuxRuntimeInstaller {
try {
Files.createLink(part.toPath(), target.toPath());
} catch (IOException | UnsupportedOperationException e) {
if (target.isFile()) {
if (!l2sLink(target, part, destination, linkRoot) && target.isFile()) {
Files.copy(target.toPath(), part.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
if (part.exists()) place(part, file);
if (Files.exists(part.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) place(part, file);
} else if (entry.isFile()) {
links.remove(file);
File part = partFile(file);
@@ -589,6 +609,67 @@ public final class LinuxRuntimeInstaller {
}
}
static File hardLinkTarget(File destination, String name) throws IOException {
java.nio.file.Path path = java.nio.file.Paths.get(name).normalize();
java.nio.file.Path last = path.getFileName();
if (last == null || last.toString().isEmpty() || last.toString().equals("..")) return null;
java.nio.file.Path parent = path.getParent();
File dir = parent == null ? destination : ArchivePaths.inside(destination, parent.toString());
return dir == null ? null : new File(dir, last.toString());
}
private static final String L2S = ".l2s.";
static boolean l2sLink(File target, File link) {
return l2sLink(target, link, null, null);
}
static boolean l2sLink(File target, File link, File tree, File linkTree) {
java.nio.file.Path here = tree == null ? null : tree.toPath().toAbsolutePath().normalize();
java.nio.file.Path there = linkTree == null ? here : linkTree.toPath().toAbsolutePath().normalize();
java.util.function.UnaryOperator<java.nio.file.Path> shown = path -> {
java.nio.file.Path p = path.toAbsolutePath().normalize();
return here == null || !p.startsWith(here) ? p : there.resolve(here.relativize(p));
};
java.util.function.UnaryOperator<java.nio.file.Path> actual = path -> {
java.nio.file.Path p = path.toAbsolutePath().normalize();
return there == null || !p.startsWith(there) ? p : here.resolve(there.relativize(p));
};
try {
java.nio.file.Path original = target.toPath().toAbsolutePath().normalize();
java.nio.file.Path intermediate;
if (Files.isSymbolicLink(original)) {
intermediate = actual.apply(Files.readSymbolicLink(original));
if (!intermediate.getFileName().toString().startsWith(L2S) || !Files.isSymbolicLink(intermediate)) return false;
java.nio.file.Path fin = actual.apply(Files.readSymbolicLink(intermediate));
String name = fin.getFileName().toString();
int count = Integer.parseInt(name.substring(name.length() - 4)) + 1;
java.nio.file.Path next = fin.resolveSibling(name.substring(0, name.length() - 4) + String.format(java.util.Locale.ROOT, "%04d", count));
Files.move(fin, next, StandardCopyOption.ATOMIC_MOVE);
Files.delete(intermediate);
Files.createSymbolicLink(intermediate, shown.apply(next));
} else {
if (!Files.isRegularFile(original, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return false;
java.nio.file.Path dir = original.getParent();
String base = L2S + original.getFileName();
int suffix = 1;
do {
intermediate = dir.resolve(base + String.format(java.util.Locale.ROOT, "%04d", suffix++));
} while (Files.exists(intermediate, java.nio.file.LinkOption.NOFOLLOW_LINKS) && suffix < 1000);
java.nio.file.Path fin = dir.resolve(intermediate.getFileName() + ".0002");
Files.move(original, fin, StandardCopyOption.ATOMIC_MOVE);
Files.createSymbolicLink(intermediate, shown.apply(fin));
Files.createSymbolicLink(original, shown.apply(intermediate));
}
Files.deleteIfExists(link.toPath());
Files.createSymbolicLink(link.toPath(), shown.apply(intermediate));
return true;
} catch (IOException | RuntimeException e) {
Log.w(TAG, "l2s link " + link + " -> " + target + ": " + e);
return false;
}
}
static File partFile(File file) {
return new File(file.getParentFile(), ".dd-part-" + Integer.toHexString(file.getName().hashCode()));
}
@@ -0,0 +1,201 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.os.ParcelFileDescriptor
import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.File
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.atomic.AtomicInteger
object RootSpawner {
private const val TAG = "RootSpawner"
fun socket(context: Context): String = "${context.packageName}.root"
private val seq = AtomicInteger()
@Volatile private var server: LocalServerSocket? = null
@Synchronized
fun start(context: Context) {
if (server != null) return
val app = context.applicationContext
val name = socket(app)
val socket = try {
LocalServerSocket(name)
} catch (e: IOException) {
Log.e(TAG, "cannot listen on $name", e)
return
}
server = socket
Thread({
while (true) {
val client = try { socket.accept() } catch (e: IOException) { Log.e(TAG, "accept", e); break }
Thread({ serve(app, client) }, "root-${seq.get() + 1}").apply { isDaemon = true; start() }
}
}, "root-server").apply { isDaemon = true; start() }
}
private fun serve(context: Context, client: LocalSocket) {
val id = seq.incrementAndGet()
val received = ArrayList<FileDescriptor>()
client.use {
val out = DataOutputStream(client.outputStream)
try {
if (client.peerCredentials.uid != Process.myUid()) {
Log.w(TAG, "refused root for uid ${client.peerCredentials.uid}")
return
}
val input = DataInputStream(client.inputStream)
val kind = input.readUnsignedByte()
client.ancillaryFileDescriptors?.let { received.addAll(it) }
val body = ByteArray(input.readInt()).also { input.readFully(it) }
client.ancillaryFileDescriptors?.let { received.addAll(it) }
if (kind != 'R'.code) return
run(context, JSONObject(String(body, Charsets.UTF_8)), received, client, input, out, id)
} catch (e: Exception) {
Log.e(TAG, "root $id", e)
runCatching {
frame(out, 'E', (e.message ?: e.toString()).toByteArray())
frame(out, 'X', "1".toByteArray())
}
} finally {
received.forEach { fd -> runCatching { android.system.Os.close(fd) } }
}
}
}
private class Stdio(val redirect: ProcessBuilder.Redirect?, val fd: FileDescriptor?, val dup: ParcelFileDescriptor?)
private fun stdio(fd: FileDescriptor?, write: Boolean): Stdio {
if (fd == null) return Stdio(null, null, null)
val dup = try { ParcelFileDescriptor.dup(fd) } catch (e: IOException) { return Stdio(null, fd, null) }
val path = File("/proc/self/fd/${dup.fd}")
val opens = try {
if (write) FileOutputStream(path, true).close() else FileInputStream(path).close()
true
} catch (e: IOException) { false }
if (!opens) return Stdio(null, fd, dup)
val redirect = if (write) ProcessBuilder.Redirect.appendTo(path) else ProcessBuilder.Redirect.from(path)
return Stdio(redirect, fd, dup)
}
private fun pump(from: InputStream, to: OutputStream, name: String) =
Thread({
val buffer = ByteArray(16384)
try {
while (true) {
val n = from.read(buffer)
if (n < 0) break
to.write(buffer, 0, n)
to.flush()
}
} catch (e: IOException) {
} finally {
runCatching { to.close() }
}
}, name).apply { isDaemon = true; start() }
private fun run(context: Context, request: JSONObject, fds: List<FileDescriptor>, client: LocalSocket,
input: DataInputStream, out: DataOutputStream, id: Int) {
val root = LinuxRuntime.rootDir(context)
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
if (argv.isEmpty()) throw IOException("no command")
val cwd = request.optString("cwd", "/root").ifEmpty { "/root" }
val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true)
cmd.add(1, "--link2symlink")
LinuxRuntime.lastBinds(context).filterNot { it.startsWith("/proc/self/fd/") }.forEach { cmd.add("-b"); cmd.add(it) }
cmd.add("/usr/bin/env")
cmd.add("-i")
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> cmd.add("$k=${e.getString(k)}") } }
cmd.addAll(argv)
val builder = ProcessBuilder(cmd).directory(root)
builder.environment().apply {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
val streams = listOf(stdio(fds.getOrNull(0), false), stdio(fds.getOrNull(1), true), stdio(fds.getOrNull(2), true))
try {
builder.redirectInput(streams[0].redirect ?: ProcessBuilder.Redirect.PIPE)
builder.redirectOutput(streams[1].redirect ?: ProcessBuilder.Redirect.PIPE)
builder.redirectError(streams[2].redirect ?: ProcessBuilder.Redirect.PIPE)
val process = builder.start()
val pid = HostProcess.pidOf(process)
OrphanReaper.keep(pid)
Log.i(TAG, "root $id pid $pid: ${argv.joinToString(" ")}")
synchronized(out) { frame(out, 'P', pid.toString().toByteArray()) }
val pumps = ArrayList<Thread>()
if (streams[0].redirect == null) {
val fd = streams[0].fd
if (fd != null) pumps.add(pump(FileInputStream(fd), process.outputStream, "root-$id-in").also { it.isDaemon = true })
else runCatching { process.outputStream.close() }
}
if (streams[1].redirect == null) pumps.add(pump(process.inputStream,
streams[1].fd?.let { FileOutputStream(it) } ?: OutputStream.nullOutputStream(), "root-$id-out"))
if (streams[2].redirect == null) pumps.add(pump(process.errorStream,
streams[2].fd?.let { FileOutputStream(it) } ?: OutputStream.nullOutputStream(), "root-$id-err"))
Thread({
try {
while (true) {
val kind = input.readUnsignedByte()
val body = ByteArray(input.readInt()).also { input.readFully(it) }
if (kind == 'S'.code) String(body).trim().toIntOrNull()?.let { signal(pid, it) }
}
} catch (e: IOException) {
}
if (process.isAlive) {
Log.i(TAG, "root $id: its caller is gone; stopping it")
signal(pid, android.system.OsConstants.SIGHUP)
android.os.Process.sendSignal(pid, android.system.OsConstants.SIGQUIT)
}
}, "root-$id-watch").apply { isDaemon = true; start() }
val status = process.waitFor()
pumps.filter { it.name.endsWith("-out") || it.name.endsWith("-err") }.forEach { it.join(2000) }
OrphanReaper.release(pid)
Log.i(TAG, "root $id exited $status")
runCatching { synchronized(out) { frame(out, 'X', status.toString().toByteArray()) } }
} finally {
streams.forEach { s -> runCatching { s.dup?.close() } }
}
}
private fun signal(top: Int, signal: Int) {
val parents = HashMap<Int, Int>()
File("/proc").listFiles()?.forEach { dir ->
val pid = dir.name.toIntOrNull() ?: return@forEach
val stat = try { File(dir, "stat").readText() } catch (e: IOException) { return@forEach }
val fields = stat.substringAfterLast(')').trim().split(' ')
fields.getOrNull(1)?.toIntOrNull()?.let { parents[pid] = it }
}
val tree = HashSet<Int>()
var grew = true
while (grew) {
grew = false
for ((pid, parent) in parents) {
if (pid !in tree && (parent == top || parent in tree)) { tree.add(pid); grew = true }
}
}
tree.forEach { runCatching { android.os.Process.sendSignal(it, signal) } }
}
private fun frame(out: DataOutputStream, kind: Char, payload: ByteArray) {
out.writeByte(kind.code)
out.writeInt(payload.size)
out.write(payload)
out.flush()
}
}
@@ -109,10 +109,39 @@ public final class RuntimeFileTree {
static java.util.List<String> existingUserPaths(File from, File to) throws IOException {
java.util.List<String> paths = new java.util.ArrayList<>();
for (String rel : userPaths(from, to)) if (exists(safePath(from, rel).toPath())) paths.add(rel);
for (String rel : userPaths(from, to)) {
if (!exists(safePath(from, rel).toPath())) continue;
if (rel.startsWith("usr/share/applications/") && exists(safePath(to, rel).toPath())) continue;
paths.add(rel);
}
return paths;
}
private static final String[] STALE_HOME_STATE = {
".local/share/droiddeck/pacman", ".cache/droiddeck/pacman-restore.log",
".cache/appstream", ".cache/discover", ".cache/fontconfig", ".cache/kwin", ".cache/ksplash",
".cache/ksvg-elements", ".cache/plasmashell", ".cache/kwinsession.kcache", ".cache/icon-cache.kcache",
};
private static final String[] STALE_HOME_CACHE_PREFIXES = {
"mesa_shader_cache", "ksycoca", "plasma_theme_", "qtshadercache", "event-sound-cache.tdb.",
};
static void dropStaleState(File runtimeRoot) throws IOException {
File home = new File(runtimeRoot, "root");
java.util.List<String> stale = new java.util.ArrayList<>(java.util.Arrays.asList(STALE_HOME_STATE));
for (String n : children(new File(home, ".cache"))) {
for (String prefix : STALE_HOME_CACHE_PREFIXES) {
if (n.startsWith(prefix)) { stale.add(".cache/" + n); break; }
}
}
IOException failed = null;
for (String rel : stale) {
try { delete(safePath(home, rel), null); }
catch (IOException e) { if (failed == null) failed = e; else failed.addSuppressed(e); }
}
if (failed != null) throw failed;
}
private static java.util.List<String> children(File dir) throws IOException {
java.util.List<String> names = new java.util.ArrayList<>();
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir.toPath())) {
@@ -11,14 +11,15 @@ object RuntimeHealth {
fun brokenLibraryLinks(context: Context): List<String> = brokenLibraryLinks(LinuxRuntime.rootDir(context))
/** A complete runtime has no library link in usr/lib whose target is missing. */
fun brokenLibraryLinks(root: File): List<String> {
val lib = File(root, "usr/lib")
val names = lib.list() ?: return emptyList()
return names.sorted().filter { name ->
val path = File(lib, name).toPath()
Files.isSymbolicLink(path) && !resolves(root, path)
fun brokenLibraryLinks(root: File): List<String> =
listOf("usr/lib", "usr/lib/aarch64-linux-gnu").flatMap { dir ->
val lib = File(root, dir)
val names = lib.list() ?: return@flatMap emptyList()
names.sorted().filter { name ->
val path = File(lib, name).toPath()
Files.isSymbolicLink(path) && !resolves(root, path)
}.map { if (dir == "usr/lib") it else "aarch64-linux-gnu/$it" }
}
}
private fun resolves(root: File, link: Path): Boolean = try {
var path = link
@@ -25,6 +25,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
"usr/local/bin/droiddeck-desktop-window-rules" to "usr/local/bin/droiddeck-desktop-window-rules",
"usr/local/bin/droiddeck-ime" to "usr/local/bin/droiddeck-ime",
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
@@ -32,7 +33,7 @@ object SessionFiles {
/** Puts the session's files in place; [startsSession] is true only for the call that starts the Steam session. */
fun stage(context: Context, root: File, startsSession: Boolean = false) {
if (DesktopCatalog.desktopInstalled(root)) try { DesktopCatalog.cleanLegacy(context) }
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
GameEnvironmentStore.publish(context)
WinComponents.publish(context)
@@ -70,6 +71,16 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
"usr/local/bin/droiddeck-snap-run" to "usr/local/bin/droiddeck-snap-run",
"usr/local/bin/droiddeck-snap-confine" to "usr/local/bin/droiddeck-snap-confine",
"usr/local/bin/droiddeck-snapctl" to "usr/local/bin/droiddeck-snapctl",
"usr/local/bin/droiddeck-systemd-run" to "usr/local/bin/systemd-run",
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
"usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim",
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
@@ -235,6 +246,7 @@ object SessionFiles {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n")
@@ -242,6 +254,12 @@ object SessionFiles {
stagedSocket.delete()
Log.e(TAG, "could not write bwrap-socket")
}
val stagedRoot = File(droiddeckEtc, "root-socket.staged")
if (!FileUtils.writeString(stagedRoot, com.droiddeck.launcher.runtime.RootSpawner.socket(context) + "\n")
|| !stagedRoot.renameTo(File(droiddeckEtc, "root-socket"))) {
stagedRoot.delete()
Log.e(TAG, "could not write root-socket")
}
BootMovie.syncFromSteam(context)
val startupMovie = BootMovie.prepare(context)
@@ -586,6 +604,28 @@ object SessionFiles {
* The fonts themselves are bind-mounted by LinuxRuntime.bindSystemFonts() into
* /usr/local/share/fonts/android; here we only need to point fontconfig at them.
*/
private val DESKTOP_STRINGS = listOf(
"desktop_restore_title" to R.string.desktop_restore_title,
"desktop_restore_body" to R.string.desktop_restore_body,
"desktop_restore_done_title" to R.string.desktop_restore_done_title,
"desktop_restore_done_body" to R.string.desktop_restore_done_body,
"desktop_restore_failed_title" to R.string.desktop_restore_failed_title,
"desktop_restore_failed_body" to R.string.desktop_restore_failed_body,
)
private fun writeDesktopStrings(context: Context, dir: File) {
val text = DESKTOP_STRINGS.joinToString("") { (key, id) ->
key + "=" + context.getString(id).replace("\\", "\\\\").replace("%", "%%").replace("\n", "\\n") + "\n"
}
val target = File(dir, "strings")
if (FileUtils.readString(target) == text) return
val staged = File(dir, "strings.staged")
if (!FileUtils.writeString(staged, text) || !staged.renameTo(target)) {
staged.delete()
Log.e(TAG, "could not write desktop strings")
}
}
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
@@ -309,6 +309,18 @@ object SessionPrefs {
prefs(context).edit().putBoolean("lowLatency", on).apply()
}
fun evdevMouse(context: Context): Boolean = prefs(context).getBoolean("evdevMouse", false)
fun setEvdevMouse(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("evdevMouse", on).apply()
}
fun directCursor(context: Context): Boolean = prefs(context).getBoolean("directCursor", false)
fun setDirectCursor(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("directCursor", on).apply()
}
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
fun setBackActionsInverted(context: Context, inverted: Boolean) {
@@ -757,7 +757,7 @@ class SessionService : Service() {
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
guest.add("HOME=/root")
guest.add("USER=root")
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
guest.add("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games")
guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8")
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
@@ -881,7 +881,7 @@ class SessionService : Service() {
}
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
FakeInputWriter.prepareRingSlots(fakeInputDir, 5)
val builtinPad = SessionPrefs.builtinPad(this)
val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad &&
!com.droiddeck.launcher.input.PadBridge.anyControllerConnected()
@@ -174,7 +174,7 @@ private fun DesktopDock(
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val available = s.emulators.filter { !it.installed }
val flatpaks = com.droiddeck.launcher.store.StoreState.installed
val flatpaks = com.droiddeck.launcher.store.StoreState.installed.filter { f -> apps.none { it.key == "flatpak:${f.id}" } }
val keys = installed.map { "emu:${it.id}" } + apps.map { "user:${it.key}" } + flatpaks.map { "flatpak:${it.id}" }
var lastAt by remember { mutableStateOf<Rect?>(null) }
var dockAt by remember { mutableStateOf<Rect?>(null) }
@@ -153,6 +153,9 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_CLICK
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_HOLD
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_NONE
import kotlinx.coroutines.flow.collect
import java.util.Locale
@@ -263,8 +266,15 @@ class DrawerActions(
val onBackActionsInverted: (Boolean) -> Unit,
val lowLatency: Boolean = true,
val onLowLatency: (Boolean) -> Unit = {},
val evdevMouse: Boolean = false,
val onEvdevMouse: (Boolean) -> Unit = {},
val directCursor: Boolean = false,
val onDirectCursor: (Boolean) -> Unit = {},
val onTouch: (String) -> Unit,
val onGestureSettings: () -> Unit = {},
val touchActive: String = "",
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
val onDirectHoldBehavior: (String) -> Unit = {},
val onScreenKeys: (() -> Unit)? = null,
val onScreenLayouts: (() -> Unit)? = null,
val screenKeysShown: Boolean = true,
@@ -565,10 +575,20 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
if (a.touchMode == SessionPrefs.TOUCH_GESTURES) {
ActionRow(stringResource(R.string.gesture_settings), null,
if (a.touchActive == SessionPrefs.TOUCH_DIRECT)
ToggleRow(host, "direct-cursor", stringResource(R.string.drawer_direct_cursor),
null, a.directCursor,
chipModifier = focus.track(page, "direct-cursor"), onChange = a.onDirectCursor)
when (a.touchActive) {
SessionPrefs.TOUCH_GESTURES -> ActionRow(stringResource(R.string.gesture_settings), null,
stringResource(R.string.ctrl_edit), a.onGestureSettings,
modifier = focus.track(page, "gesture-settings"))
SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.gesture_long_press), null,
listOf(MOUSE_BEHAVIOR_NONE to stringResource(R.string.gesture_hold_left),
MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_right_click),
MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_right)),
a.directHoldBehavior, chipModifier = focus.track(page, "long-press"),
onPick = a.onDirectHoldBehavior)
}
if (a.onScreenKeys != null) {
SettingsRow(stringResource(R.string.screen_keys), null, stacked = narrow) {
@@ -628,6 +648,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency),
stringResource(R.string.drawer_low_latency_hint), a.lowLatency,
chipModifier = focus.track(page, "low-latency"), onChange = a.onLowLatency)
ToggleRow(host, "evdev-mouse", stringResource(R.string.drawer_evdev_mouse),
null, a.evdevMouse,
chipModifier = focus.track(page, "evdev-mouse"), onChange = a.onEvdevMouse)
}
SettingsGroup(stringResource(R.string.drawer_keyboard)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
@@ -167,6 +167,10 @@ public final class WaylandCompositor {
public static native void nativeSendKey(int evdev, int state);
public static native boolean nativeFocusTakesTouch();
public static native boolean nativeCursorInputPos(int[] out);
public static native void nativeVsync(long frameTimeNanos);
public static native int nativeCompositorTid();
@@ -323,9 +327,17 @@ public final class WaylandCompositor {
nativeSendSceneInput(6, dx * 256, dy * 256);
}
private static float pendingDeltaX, pendingDeltaY;
public static void sendPointerDelta(float dx, float dy) {
int x = Math.round(dx * 256f), y = Math.round(dy * 256f);
// Round-to-zero per event would drop slow motion entirely; carry the remainder.
pendingDeltaX += dx * 256f;
pendingDeltaY += dy * 256f;
int x = (int) Math.floor(pendingDeltaX);
int y = (int) Math.floor(pendingDeltaY);
if (x == 0 && y == 0) return;
pendingDeltaX -= x;
pendingDeltaY -= y;
nativeSendSceneInput(6, x, y);
}
}