Keep the session alive in the background, rename the package, sign with the testkey, and draw the app a logo

The session now belongs to a foreground service rather than the activity.
Android demotes a process as soon as its last visible activity goes and the
low-memory killer reaps the guest, so leaving Big Picture to answer a message
came back to a dead Steam; the service holds the process at perceptible
priority, a partial wake lock keeps the CPU from dropping the guest's threads,
and a high-performance WiFi lock keeps a backgrounded download from being
throttled to nothing. The notification is silent (IMPORTANCE_LOW), carries a
Stop action, and returns to the session when tapped. Back now puts the app away
and leaves Steam running; a swipe out of recents ends the session.

The compositor moved with it: it is process-wide, started once, and merely
swaps the Surface it presents into as the activity comes and goes.

Package is com.steamdeck.launcher, signed with the AOSP testkey (v1+v2+v3) so
every build installs over the last one, and CI asserts all three schemes.

The launcher icon is our own controller on a purple glow — the spirit of the
Steam tile the client entry uses, none of its geometry.
This commit is contained in:
The412Banner committed 2026-09-19 14:17:25 -04:00
1 parent 4031f512fc
commit 344e70afc6
49 files changed
+977 -615

No files matched your search

@@ -1,4 +1,4 @@
package com.the412banner.steamdeck
package com.steamdeck.launcher
import android.Manifest
import android.app.Activity
@@ -13,9 +13,9 @@ import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import com.the412banner.steamdeck.core.FileUtils
import com.the412banner.steamdeck.runtime.LinuxRuntime
import com.the412banner.steamdeck.runtime.LinuxRuntimeInstaller
import com.steamdeck.launcher.core.FileUtils
import com.steamdeck.launcher.runtime.LinuxRuntime
import com.steamdeck.launcher.runtime.LinuxRuntimeInstaller
/**
* The whole app outside a session: is the runtime installed, is there a newer one, and one button
@@ -0,0 +1,279 @@
package com.steamdeck.launcher
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.TextView
import com.steamdeck.launcher.core.FileUtils
import com.steamdeck.launcher.gpu.TurnipDriver
import com.steamdeck.launcher.input.EvdevKeys
import com.steamdeck.launcher.input.PadBridge
import com.steamdeck.launcher.runtime.LinuxRuntime
import com.steamdeck.launcher.session.SessionService
import com.steamdeck.launcher.session.SessionState
import com.steamdeck.launcher.wayland.CompositorHost
import com.steamdeck.launcher.wayland.WaylandCompositor
import java.io.File
/**
* The session's screen: our Wayland compositor presenting onto this activity's Surface, and the
* input that reaches it. The session itself — gamescope, the Steam client, audio — belongs to
* [SessionService] and keeps running when this activity does not exist, which is what lets the
* user leave Big Picture for another app and come back to it still signed in and still
* downloading.
*
* So there are only three jobs here: hold a Surface under the compositor, forward input, and show
* the session's milestones until its first frame arrives.
*/
class SessionActivity : Activity(), SurfaceHolder.Callback {
private lateinit var surfaceView: SurfaceView
private lateinit var statusView: TextView
private var padBridge: PadBridge? = null
private var watching = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
goFullscreen()
if (!LinuxRuntime.isInstalled(this)) {
Log.e(TAG, "the Linux runtime is not installed")
finish()
return
}
val root = FrameLayout(this)
surfaceView = SurfaceView(this)
surfaceView.holder.addCallback(this)
root.addView(surfaceView)
// Until the client's first frame arrives there is nothing on screen for a minute or more
// on a first run, so the session's own milestones are shown instead of a black panel.
statusView = TextView(this).apply {
setPadding(48, 48, 48, 48)
setTextColor(0xFFDDDDDD.toInt())
textSize = 14f
text = getString(R.string.session_starting)
// A session already running is past its milestones; do not cover its picture.
visibility = if (SessionState.running) View.GONE else View.VISIBLE
}
root.addView(statusView)
setContentView(root)
padBridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
WaylandCompositor.setFirstFrameListener { runOnUiThread { statusView.visibility = View.GONE } }
SessionState.endListener = { status -> onSessionEnded(status) }
watchSessionLog()
}
// ── Compositor ──────────────────────────────────────────────────────────────────────────
override fun surfaceCreated(holder: SurfaceHolder) {
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
// The compositor hands this keymap to wl_keyboard clients, which is how the guest reads
// the evdev codes we inject.
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
// Turnip, not the system Adreno driver: importing the dma-bufs gamescope commits needs
// VK_EXT_image_drm_format_modifier, which the system driver does not implement.
val turnip = TurnipDriver(this)
val driverId = if (CompositorHost.isStarted) null else turnip.install()
val size = outputSize()
SessionState.outputSize = size
SessionState.refreshHz = refreshHz()
val first = CompositorHost.startOrAttach(
holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(),
)
// The service owns everything below the compositor, and starting it is idempotent: coming
// back to a running session just re-attaches the Surface above.
if (first) SessionService.start(this)
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
override fun surfaceDestroyed(holder: SurfaceHolder) {
CompositorHost.detach()
}
/**
* The size the session renders at. gamescope is told this and scales its output onto whatever
* the panel is, so a 1440p phone can run the client at 1080p without the client knowing.
*/
private fun outputSize(): Pair<Int, Int> {
// The panel, not the window: resources.displayMetrics is what is left after the system
// bars and the cutout are taken out, which sized the first session 1920x968 on a 1080p
// device and had gamescope patch its EDID to match.
val bounds = if (Build.VERSION.SDK_INT >= 30) {
windowManager.maximumWindowMetrics.bounds
} else {
val metrics = android.util.DisplayMetrics()
@Suppress("DEPRECATION")
windowManager.defaultDisplay.getRealMetrics(metrics)
android.graphics.Rect(0, 0, metrics.widthPixels, metrics.heightPixels)
}
var width = maxOf(bounds.width(), bounds.height())
var height = minOf(bounds.width(), bounds.height())
// The client's CEF is the heaviest thing in the session; above 1080p it costs frames for
// nothing anyone can see on a phone panel.
if (height > 1080) {
width = width * 1080 / height
height = 1080
}
// Odd sizes upset the scaler; both dimensions even is what every mode here would be.
return Pair(width and 1.inv(), height and 1.inv())
}
private fun refreshHz(): Float {
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
val hz = display?.refreshRate ?: 60f
return if (hz > 1f) hz else 60f
}
// ── Session state ───────────────────────────────────────────────────────────────────────
/** Mirrors the session script's "== STEP" milestones onto the screen while it starts. */
private fun watchSessionLog() {
val handler = Handler(Looper.getMainLooper())
Thread({
var shown = ""
while (watching) {
try {
Thread.sleep(500)
val log = SessionState.logFile ?: continue
val text = FileUtils.readString(log) ?: continue
val step = text.lineSequence().lastOrNull { it.startsWith("== STEP") } ?: continue
val message = step.substringAfter("== STEP ").substringAfter(' ')
if (message != shown) {
shown = message
handler.post { if (statusView.visibility == View.VISIBLE) statusView.text = message }
}
} catch (e: InterruptedException) {
return@Thread
} catch (ignored: Exception) {
}
}
}, "session-log").start()
}
private fun onSessionEnded(status: Int) {
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
if (status != 0) {
statusView.visibility = View.VISIBLE
statusView.text = getString(R.string.session_ended, status,
SessionState.logFile?.path ?: "-")
// A moment on screen, so a failure is readable rather than a flash of black.
Handler(Looper.getMainLooper()).postDelayed({ finish() }, 4000)
} else {
finish()
}
}
}
// ── Input ───────────────────────────────────────────────────────────────────────────────
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (padBridge?.onKeyEvent(event) == true) return true
// A hardware keyboard, forwarded to the compositor's wl_keyboard. This is how an account
// name and password get typed on the client's first run; the client's own on-screen
// keyboard covers a device without one, driven by touch or the pad.
if (CompositorHost.isStarted && event.device != null && !PadBridge.isFromController(event.device)) {
val down = event.action == KeyEvent.ACTION_DOWN
if (down || event.action == KeyEvent.ACTION_UP) {
// An unmapped key may still be a real one on a foreign layout: its scan code is
// the evdev code the kernel gave Android in the first place.
var evdev = EvdevKeys.fromKeyCode(event.keyCode)
if (evdev < 0 && event.scanCode > 0) evdev = event.scanCode
if (evdev > 0) {
WaylandCompositor.nativeSendKey(evdev, if (down) 1 else 0)
return true
}
}
}
return super.dispatchKeyEvent(event)
}
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (padBridge?.onMotionEvent(event) == true) return true
return super.dispatchGenericMotionEvent(event)
}
/**
* Touch as a mouse: where you touch is where the pointer goes, and a tap is a left click.
* The compositor's pointer space is a fixed 1920x1080 whatever the output size, so the view's
* coordinates are scaled into it.
*/
override fun onTouchEvent(event: MotionEvent): Boolean {
val width = surfaceView.width.takeIf { it > 0 } ?: return false
val height = surfaceView.height.takeIf { it > 0 } ?: return false
val action = when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> 0
MotionEvent.ACTION_MOVE -> 1
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> 2
else -> return false
}
val x = (event.x / width * 1920f).toInt().coerceIn(0, 1919)
val y = (event.y / height * 1080f).toInt().coerceIn(0, 1079)
WaylandCompositor.nativeSendPointer(action, x, y)
return true
}
// ── Lifecycle ───────────────────────────────────────────────────────────────────────────
/**
* Back leaves the session running and puts the app behind whatever the user wants next; the
* notification brings it back. Ending a session is done deliberately — from the
* notification's Stop action, or by swiping the app out of recents.
*/
@Suppress("DEPRECATION")
override fun onBackPressed() {
moveTaskToBack(true)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) goFullscreen()
}
private fun goFullscreen() {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
if (Build.VERSION.SDK_INT >= 28) {
window.attributes = window.attributes.apply {
layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
}
}
override fun onDestroy() {
// Deliberately does NOT end the session: this activity can be destroyed while the user is
// in another app, and the whole point of the service is that Steam survives that.
watching = false
padBridge?.stop()
SessionState.endListener = null
WaylandCompositor.setFirstFrameListener(null)
super.onDestroy()
}
companion object {
private const val TAG = "SessionActivity"
}
}
@@ -1,13 +1,13 @@
package com.the412banner.steamdeck.audio;
package com.steamdeck.launcher.audio;
import android.content.Context;
import android.os.Process;
import android.util.Log;
import com.the412banner.steamdeck.core.FileUtils;
import com.the412banner.steamdeck.core.EnvironmentComponent;
import com.the412banner.steamdeck.core.ProcessHelper;
import com.the412banner.steamdeck.core.TarZst;
import com.steamdeck.launcher.core.FileUtils;
import com.steamdeck.launcher.core.EnvironmentComponent;
import com.steamdeck.launcher.core.ProcessHelper;
import com.steamdeck.launcher.core.TarZst;
import java.io.File;
import java.io.InputStream;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.core;
package com.steamdeck.launcher.core;
/** One-argument callback, kept so the ported runtime classes read as they did in Bannerlator. */
public interface Callback<T> {
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.core;
package com.steamdeck.launcher.core;
import android.util.Log;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.core;
package com.steamdeck.launcher.core;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.core;
package com.steamdeck.launcher.core;
import android.content.Context;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.core;
package com.steamdeck.launcher.core;
import android.content.Context;
import android.system.ErrnoException;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.core;
package com.steamdeck.launcher.core;
import android.util.Log;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.core;
package com.steamdeck.launcher.core;
import android.content.Context;
import android.util.Log;
@@ -16,7 +16,7 @@ import java.io.OutputStream;
/**
* The small zstd tarballs that ship inside the apk (the Turnip driver, the PulseAudio modules).
* The runtime rootfs is not one of these — it needs hard links and symlinks preserved, which
* {@link com.the412banner.steamdeck.runtime.LinuxRuntimeInstaller} handles itself.
* {@link com.steamdeck.launcher.runtime.LinuxRuntimeInstaller} handles itself.
*/
public final class TarZst {
private static final String TAG = "TarZst";
@@ -1,11 +1,11 @@
package com.the412banner.steamdeck.gpu;
package com.steamdeck.launcher.gpu;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.the412banner.steamdeck.core.FileUtils;
import com.the412banner.steamdeck.core.TarZst;
import com.steamdeck.launcher.core.FileUtils;
import com.steamdeck.launcher.core.TarZst;
import org.json.JSONObject;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.input;
package com.steamdeck.launcher.input;
import android.view.KeyEvent;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.input;
package com.steamdeck.launcher.input;
import android.util.Log;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.input;
package com.steamdeck.launcher.input;
public class GamepadState {
/** Bit index of the Steam/Guide button; 0-9 are the face/shoulder/stick buttons. */
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.input;
package com.steamdeck.launcher.input;
import android.util.Log;
import android.view.InputDevice;
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.runtime
package com.steamdeck.launcher.runtime
import android.content.Context
import android.net.ConnectivityManager
@@ -7,7 +7,7 @@ import android.net.Network
import android.os.Build
import android.provider.Settings
import android.util.Log
import com.the412banner.steamdeck.core.EnvironmentComponent
import com.steamdeck.launcher.core.EnvironmentComponent
import java.io.File
import java.io.IOException
import java.net.Inet4Address
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.runtime;
package com.steamdeck.launcher.runtime;
import android.content.Context;
import android.os.Process;
@@ -1,11 +1,11 @@
package com.the412banner.steamdeck.runtime;
package com.steamdeck.launcher.runtime;
import android.content.Context;
import android.util.Log;
import com.the412banner.steamdeck.core.Downloader;
import com.the412banner.steamdeck.core.FileUtils;
import com.steamdeck.launcher.core.Downloader;
import com.steamdeck.launcher.core.FileUtils;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
@@ -0,0 +1,89 @@
package com.steamdeck.launcher.session
import android.content.Context
import android.os.Environment
import android.util.Log
import com.steamdeck.launcher.core.FileUtils
import com.steamdeck.launcher.runtime.LinuxRuntime
import java.io.File
/** Everything the session needs written into the runtime before it starts. */
object SessionFiles {
private const val TAG = "SessionFiles"
private const val NO_PAD_SWITCH = "Download/steamdeck-no-pad"
/**
* The libraries and scripts the session runs, refreshed from the apk at every launch.
*
* The runtime image carries its own copies, but a runtime installed months ago carries the
* copies of that day and a device has no way to replace them from outside the app. Staging
* them here is how a fix inside the session shim, the controller reader or one of the scripts
* reaches an already-installed runtime without a ~790 MB re-download. Each lands through a
* rename, so a session that still has one mapped keeps the file it opened.
*/
fun stage(context: Context, root: File) {
val files = arrayOf(
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
"usr/local/bin/bannerlator-steam-library" to "usr/local/bin/bannerlator-steam-library",
"usr/local/bin/bannerlator-seed-redists" to "usr/local/bin/bannerlator-seed-redists",
)
for ((asset, relative) in files) {
val target = File(root, relative)
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
context.assets.open("linuxfs/$asset").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage $relative", e)
} finally {
if (!installed) staged.delete()
}
if (!installed) Log.e(TAG, "$relative NOT staged")
}
// What every process in the session preloads. LD_PRELOAD in the environment would not
// survive: the Steam client rebuilds it for each process it starts and appends its own
// overlay entry without a separator, which silently drops whatever was there.
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
val etc = File(root, "etc").apply { mkdirs() }
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
staged.delete()
Log.e(TAG, "could not write ld.so.preload")
}
}
/**
* Where the session writes its log. Downloads is the point — a failed run is handed over as a
* folder rather than dug out of app-private storage — but the session script redirects its own
* output there with `exec`, and a redirection a non-interactive shell cannot open ends that
* shell. So a public directory is used only once it is proven writable; otherwise the app's
* own files directory, which is bound into the session anyway, stands in.
*/
fun logDirectory(context: Context): File {
val public = LinuxRuntime.debugLogDir()
if (public.isDirectory || public.mkdirs()) {
val probe = File(public, ".writable")
try {
if (probe.createNewFile() || probe.isFile) {
probe.delete()
return public
}
} catch (ignored: Exception) {
}
}
Log.w(TAG, "$public is not writable (storage permission?); logging to files/logs")
return File(context.filesDir, "logs").apply { mkdirs() }
}
}
@@ -0,0 +1,316 @@
package com.steamdeck.launcher.session
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Environment
import android.os.IBinder
import android.os.PowerManager
import android.util.Log
import com.steamdeck.launcher.R
import com.steamdeck.launcher.SessionActivity
import com.steamdeck.launcher.audio.PulseAudioComponent
import com.steamdeck.launcher.core.EnvVars
import com.steamdeck.launcher.core.EnvironmentComponent
import com.steamdeck.launcher.core.FileUtils
import com.steamdeck.launcher.core.ProcessHelper
import com.steamdeck.launcher.input.FakeInputWriter
import com.steamdeck.launcher.runtime.LinuxNetworkLinkComponent
import com.steamdeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Owns the running session: the proot tree, the audio daemon, the network link and the locks that
* keep all three alive while the app is not on screen.
*
* The session deliberately does **not** belong to the activity. Android demotes a process the
* moment it loses its last visible activity, and the low-memory killer then reaps the guest — so
* leaving Big Picture to answer a message would come back to a dead Steam. A foreground service
* holds the process at perceptible priority, a partial wake lock keeps the CPU from dropping the
* guest's threads, and a high-performance WiFi lock keeps the radio out of power-save so a
* backgrounded download does not throttle to nothing. All three are Bannerlator's recipe, where
* each was added to fix a failure seen on a device.
*
* The activity comes and goes on top of this; see [com.steamdeck.launcher.wayland.CompositorHost].
*/
class SessionService : Service() {
private val components = ArrayList<EnvironmentComponent>()
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
private var sessionPid = -1
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) {
Log.i(TAG, "stop requested from the notification")
stopSession(0)
return START_NOT_STICKY
}
startForeground(NOTIFICATION_ID, buildNotification())
if (SessionState.running) return START_NOT_STICKY
SessionState.running = true
acquireLocks()
Thread({ runSession() }, "session-start").start()
// The activity or the notification stops us; the system must not resurrect a session whose
// guest processes are long gone.
return START_NOT_STICKY
}
// ── The session ─────────────────────────────────────────────────────────────────────────
private fun runSession() {
try {
LinuxRuntime.writeAccounts(this)
} catch (e: Exception) {
Log.e(TAG, "could not write the guest's passwd/group", e)
stopSession(-1)
return
}
val root = LinuxRuntime.rootDir(this)
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
SessionFiles.stage(this, root)
val logDir = SessionFiles.logDirectory(this)
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val sessionLog = File(logDir, "session-$stamp.log")
SessionState.logFile = sessionLog
val size = SessionState.outputSize
val guest = ArrayList<String>()
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("HOME=/root")
guest.add("USER=root")
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8")
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
// Steam's CEF needs GL and the rootfs ships no native GL driver: route it through Zink.
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
val pulse = PulseAudioComponent(this)
pulse.setContext(this)
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
components.add(pulse)
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
guest.add("BL_FPS=0")
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + File(logDir, "session-$stamp").path)
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
if (controllersOn) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
// SDL and Steam key their mapping database on bus+vendor+product: only a known
// identity gets the standard layout without the user configuring the pad by hand.
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
guest.add("FAKE_EVDEV_VIBRATION=1")
guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_JOYSTICK_HIDAPI=0")
if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) {
guest.add("FAKE_EVDEV_LOG=1")
}
SessionState.fakeInputDir = fakeInputDir
}
guest.add(LinuxRuntime.SESSION_SCRIPT)
guest.add(LinuxRuntime.MODE_STEAM)
// Android has no /dev/shm; the cache stands in for it and, unlike the real thing, keeps
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
FileUtils.clear(File(cacheDir, "shm"))
val binds = ArrayList<String>()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
)
val hostEnv = EnvVars()
hostEnv.put("PROOT_LOADER", LinuxRuntime.prootLoader(this).path)
hostEnv.put("PROOT_TMP_DIR", cacheDir.path)
// proot links against a libtalloc beside it, and Android's linker does not search an
// executable's own directory: unnamed, the process dies before it starts and says so only
// in `logcat -b crash`.
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv.put("LD_LIBRARY_PATH", prootLibs)
val networkLink = LinuxNetworkLinkComponent(this, root)
networkLink.setContext(this)
networkLink.publish()
components.add(networkLink)
components.forEach { it.start() }
val line = command.joinToString(" ") { it.replace(" ", "\\ ") }
sessionPid = ProcessHelper.exec(line, hostEnv.toStringArray(), root, { status ->
Log.i(TAG, "session ended: $status")
stopSession(status ?: -1)
}, null)
Log.i(TAG, "session pid $sessionPid, log ${sessionLog.path}")
}
private fun stopSession(status: Int) {
if (!SessionState.running) return
SessionState.running = false
// proot runs with --kill-on-exit, so killing it takes the whole guest tree with it.
if (sessionPid != -1) {
android.os.Process.killProcess(sessionPid)
sessionPid = -1
}
components.reversed().forEach {
try {
it.stop()
} catch (e: Exception) {
Log.w(TAG, "stopping ${it.javaClass.simpleName}", e)
}
}
components.clear()
FakeInputWriter.releaseAllRingSlots()
releaseLocks()
SessionState.notifyEnded(status)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
/**
* Swiped out of recents. The activity is destroyed without any of our teardown running, so the
* guest would survive as an orphan holding the rootfs and the GPU. Treat the swipe as "quit".
*/
override fun onTaskRemoved(rootIntent: Intent?) {
Log.i(TAG, "task removed — ending the session")
stopSession(0)
super.onTaskRemoved(rootIntent)
}
override fun onDestroy() {
stopSession(0)
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
// ── Keeping the process alive ───────────────────────────────────────────────────────────
private fun acquireLocks() {
try {
val power = getSystemService(Context.POWER_SERVICE) as? PowerManager
wakeLock = power?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SteamDeck:session")?.apply {
setReferenceCounted(false)
// Capped, so a crash on some path cannot pin the CPU awake for good. A session
// longer than this re-acquires from the notification tap; nothing else needs it.
acquire(12L * 60L * 60L * 1000L)
}
Log.i(TAG, "wake lock held=${wakeLock?.isHeld}")
} catch (t: Throwable) {
Log.w(TAG, "no wake lock (${t.message}) — the session may be killed in the background")
}
try {
val wifi = applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
@Suppress("DEPRECATION") // deprecated from API 29, still honoured; targetSdk is 28
wifiLock = wifi?.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "SteamDeck:session-wifi")
?.apply {
setReferenceCounted(false)
acquire()
}
Log.i(TAG, "wifi lock held=${wifiLock?.isHeld}")
} catch (t: Throwable) {
// A partial wake lock keeps the process alive but does not stop WiFi power-save from
// throttling a backgrounded download to nothing, which is what this lock is for.
Log.w(TAG, "no wifi lock (${t.message}) — a backgrounded download may stall")
}
}
private fun releaseLocks() {
try {
wakeLock?.takeIf { it.isHeld }?.release()
} catch (t: Throwable) {
Log.w(TAG, "releasing the wake lock", t)
}
wakeLock = null
try {
wifiLock?.takeIf { it.isHeld }?.release()
} catch (t: Throwable) {
Log.w(TAG, "releasing the wifi lock", t)
}
wifiLock = null
}
// ── Notification ────────────────────────────────────────────────────────────────────────
private fun buildNotification(): Notification {
val manager = getSystemService(NotificationManager::class.java)
// IMPORTANCE_LOW: it must never make a sound or push a heads-up over a game.
val channel = NotificationChannel(CHANNEL_ID, getString(R.string.session_channel),
NotificationManager.IMPORTANCE_LOW).apply {
description = getString(R.string.session_channel_description)
setShowBadge(false)
setSound(null, null)
enableVibration(false)
}
manager?.createNotificationChannel(channel)
val open = PendingIntent.getActivity(
this, 0,
Intent(this, SessionActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE,
)
val stop = PendingIntent.getService(
this, 1, Intent(this, SessionService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE,
)
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.session_notification))
.setContentIntent(open)
.addAction(Notification.Action.Builder(null, getString(R.string.stop_session), stop).build())
.setOngoing(true)
.setShowWhen(false)
.apply { if (Build.VERSION.SDK_INT >= 31) setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) }
.build()
}
companion object {
private const val TAG = "SessionService"
private const val CHANNEL_ID = "session"
private const val NOTIFICATION_ID = 1001
const val ACTION_STOP = "com.steamdeck.launcher.STOP_SESSION"
private const val NO_PAD_SWITCH = "Download/steamdeck-no-pad"
private const val PAD_LOG_SWITCH = "Download/steamdeck-pad-log"
fun start(context: Context) {
val intent = Intent(context, SessionService::class.java)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent)
else context.startService(intent)
}
fun stop(context: Context) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
}
}
}
@@ -0,0 +1,36 @@
package com.steamdeck.launcher.session
import java.io.File
/**
* The little that the activity and the service have to agree on. Process-wide rather than passed
* through intents, because both halves live in one process and the point of the split is that
* either can outlive the other.
*/
object SessionState {
@Volatile
var running = false
/** The size gamescope was told to render at; set by the activity before the service starts. */
@Volatile
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
@Volatile
var refreshHz: Float = 60f
/** Where this session is writing its log, for the "it ended" message. */
@Volatile
var logFile: File? = null
/** The fake evdev directory, once the service has prepared the rings. */
@Volatile
var fakeInputDir: File? = null
/** Told when the session ends, so a visible activity can close itself. */
@Volatile
var endListener: ((Int) -> Unit)? = null
fun notifyEnded(status: Int) {
endListener?.invoke(status)
}
}
@@ -0,0 +1,74 @@
package com.steamdeck.launcher.wayland
import android.view.Choreographer
import android.view.Surface
/**
* The compositor is a process-wide thing, not an activity's: it is started once, keeps running
* while the session does, and merely swaps the Surface it presents into as the activity comes and
* goes. An activity that started it again on re-creation would be starting a second compositor on
* a socket the first one owns.
*/
object CompositorHost {
@Volatile
private var started = false
private var vsyncRunning = false
private val vsync = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
WaylandCompositor.nativeVsync(frameTimeNanos)
if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this)
}
}
/** True when this call was the one that started the compositor. */
@Synchronized
fun startOrAttach(
surface: Surface,
xdgRuntimeDir: String,
driverPath: String?,
libraryName: String?,
nativeLibDir: String,
outputWidth: Int,
outputHeight: Int,
refreshHz: Float,
): Boolean {
if (started) {
WaylandCompositor.nativeSetSurface(surface)
resumeVsync()
return false
}
WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight)
WaylandCompositor.nativeSetOutputRefreshRate(refreshHz)
WaylandCompositor.nativeStartWithSurface(
surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir,
)
started = true
resumeVsync()
return true
}
/**
* The activity is going away. The compositor keeps running with nothing to present into —
* the guest carries on, and its next frames land on the Surface the next activity brings.
*/
@Synchronized
fun detach() {
if (!started) return
pauseVsync()
WaylandCompositor.nativeSetSurface(null)
}
/** Frames are only worth drawing while a Surface is attached. */
private fun resumeVsync() {
if (vsyncRunning) return
vsyncRunning = true
Choreographer.getInstance().postFrameCallback(vsync)
}
private fun pauseVsync() {
vsyncRunning = false
}
val isStarted: Boolean get() = started
}
@@ -1,4 +1,4 @@
package com.the412banner.steamdeck.wayland;
package com.steamdeck.launcher.wayland;
import android.view.Surface;
@@ -1,500 +0,0 @@
package com.the412banner.steamdeck
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Choreographer
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.FrameLayout
import com.the412banner.steamdeck.audio.PulseAudioComponent
import com.the412banner.steamdeck.core.EnvVars
import com.the412banner.steamdeck.core.EnvironmentComponent
import com.the412banner.steamdeck.core.FileUtils
import com.the412banner.steamdeck.core.ProcessHelper
import com.the412banner.steamdeck.gpu.TurnipDriver
import com.the412banner.steamdeck.input.EvdevKeys
import com.the412banner.steamdeck.input.FakeInputWriter
import com.the412banner.steamdeck.input.PadBridge
import com.the412banner.steamdeck.runtime.LinuxNetworkLinkComponent
import com.the412banner.steamdeck.runtime.LinuxRuntime
import com.the412banner.steamdeck.wayland.WaylandCompositor
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* The session: our Wayland compositor on this activity's Surface, and gamescope plus Valve's
* native arm64 Steam client running under proot inside the Linux runtime, presenting into it.
*
* Nothing here is Wine. proot and the session script are the whole of the guest side, and the
* activity's own job is three things: keep a Surface under the compositor, feed it input, and
* hold the session's host-side components (audio, the network link, the proot process) for as
* long as the client is up.
*
* Ported from Bannerlator's XServerDisplayActivity.setupLinuxSession, which in turn follows
* WinNative's gamescope runtime (GPL-3.0).
*/
class SessionActivity : Activity(), SurfaceHolder.Callback {
private lateinit var surfaceView: SurfaceView
private lateinit var statusView: TextView
private val components = ArrayList<EnvironmentComponent>()
private var padBridge: PadBridge? = null
private var compositorStarted = false
private var sessionStarted = false
private var finishing = false
private var sessionPid = -1
private var vsyncRunning = false
private lateinit var sessionLog: File
private val vsyncCallback = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
WaylandCompositor.nativeVsync(frameTimeNanos)
if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
goFullscreen()
if (!LinuxRuntime.isInstalled(this)) {
Log.e(TAG, "the Linux runtime is not installed")
finish()
return
}
val root = FrameLayout(this)
surfaceView = SurfaceView(this)
surfaceView.holder.addCallback(this)
root.addView(surfaceView)
// Until the client's first frame arrives there is nothing on screen for a minute or more
// on a first run, so the session's own milestones are shown instead of a black panel.
statusView = TextView(this).apply {
setPadding(48, 48, 48, 48)
setTextColor(0xFFDDDDDD.toInt())
textSize = 14f
text = getString(R.string.session_starting)
}
root.addView(statusView)
setContentView(root)
WaylandCompositor.setFirstFrameListener {
runOnUiThread { statusView.visibility = View.GONE }
}
}
// ── Compositor ──────────────────────────────────────────────────────────────────────────
override fun surfaceCreated(holder: SurfaceHolder) {
if (compositorStarted) {
WaylandCompositor.nativeSetSurface(holder.surface)
return
}
compositorStarted = true
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
// The compositor hands this keymap to wl_keyboard clients, which is how the guest reads
// the evdev codes we inject.
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
// Turnip, not the system Adreno driver: importing the dma-bufs gamescope commits needs
// VK_EXT_image_drm_format_modifier, which the system driver does not implement.
val turnip = TurnipDriver(this)
val driverId = turnip.install()
val driverPath = driverId?.let { turnip.driverPath(it) }
val libraryName = driverId?.let { turnip.libraryName(it) }
val size = outputSize()
WaylandCompositor.nativeSetOutputSize(size.first, size.second)
WaylandCompositor.nativeSetOutputRefreshRate(refreshHz())
WaylandCompositor.nativeStartWithSurface(
holder.surface, runtimeDir.path, driverPath, libraryName,
applicationInfo.nativeLibraryDir,
)
vsyncRunning = true
Choreographer.getInstance().postFrameCallback(vsyncCallback)
Thread({ startSession(runtimeDir, size) }, "session-start").start()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
override fun surfaceDestroyed(holder: SurfaceHolder) {
WaylandCompositor.nativeSetSurface(null)
}
/**
* The size the session renders at. gamescope is told this and scales its output onto whatever
* the panel is, so a 1440p phone can run the client at 1080p without the client knowing.
*/
private fun outputSize(): Pair<Int, Int> {
// The panel, not the window: resources.displayMetrics is what is left after the system
// bars and the cutout are taken out, which sized the first session 1920x968 on a 1080p
// device and had gamescope patch its EDID to match.
val bounds = if (Build.VERSION.SDK_INT >= 30) {
windowManager.maximumWindowMetrics.bounds
} else {
val metrics = android.util.DisplayMetrics()
@Suppress("DEPRECATION")
windowManager.defaultDisplay.getRealMetrics(metrics)
android.graphics.Rect(0, 0, metrics.widthPixels, metrics.heightPixels)
}
var width = maxOf(bounds.width(), bounds.height())
var height = minOf(bounds.width(), bounds.height())
// The client's CEF is the heaviest thing in the session; above 1080p it costs frames for
// nothing anyone can see on a phone panel.
if (height > 1080) {
width = width * 1080 / height
height = 1080
}
// Odd sizes upset the scaler; both dimensions even is what every mode here would be.
return Pair(width and 1.inv(), height and 1.inv())
}
private fun refreshHz(): Float {
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
val hz = display?.refreshRate ?: 60f
return if (hz > 1f) hz else 60f
}
// ── Session ─────────────────────────────────────────────────────────────────────────────
private fun startSession(runtimeDir: File, size: Pair<Int, Int>) {
try {
LinuxRuntime.writeAccounts(this)
} catch (e: Exception) {
Log.e(TAG, "could not write the guest's passwd/group", e)
endSession(-1)
return
}
val root = LinuxRuntime.rootDir(this)
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
stageSessionFiles(root)
val logDir = logDirectory()
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
sessionLog = File(logDir, "session-$stamp.log")
val guest = ArrayList<String>()
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("HOME=/root")
guest.add("USER=root")
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8")
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
// Steam's CEF needs GL and the rootfs ships no native GL driver: route it through Zink.
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
val pulse = PulseAudioComponent(this)
pulse.setContext(this)
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
components.add(pulse)
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
guest.add("BL_FPS=0")
// What gamescope advertises as the refresh rate, and what a game reads as the display's.
// Left unset it says 60, and a 120 Hz panel then offers only 60 Hz in game settings.
guest.add("BL_REFRESH=" + Math.round(refreshHz()))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + File(logDir, "session-$stamp").path)
// Controllers. WinHandler is a Wine thing and there is none here, so the pad is published
// into the rings by PadBridge instead; the reader is the same interposer either way.
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
if (controllersOn) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
// SDL and Steam key their mapping database on bus+vendor+product: only a known
// identity gets the standard layout without the user configuring the pad by hand.
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
guest.add("FAKE_EVDEV_VIBRATION=1")
guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
// No udev runs in the runtime: SDL and hidapi scan /dev/input themselves, and the
// netlink monitor they open anyway is answered by the session shim's stand-in.
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_JOYSTICK_HIDAPI=0")
if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) {
guest.add("FAKE_EVDEV_LOG=1")
}
padBridge = PadBridge(fakeInputDir).also { it.start() }
}
guest.add(LinuxRuntime.SESSION_SCRIPT)
guest.add(LinuxRuntime.MODE_STEAM)
// Android has no /dev/shm; the cache stands in for it and, unlike the real thing, keeps
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
FileUtils.clear(File(cacheDir, "shm"))
val binds = ArrayList<String>()
// Apps may not list /dev/input, so the fake nodes are bound in as the whole directory.
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
)
val hostEnv = EnvVars()
hostEnv.put("PROOT_LOADER", LinuxRuntime.prootLoader(this).path)
hostEnv.put("PROOT_TMP_DIR", cacheDir.path)
// proot links against a libtalloc beside it, and Android's linker does not search an
// executable's own directory: unnamed, the process dies before it starts and says so only
// in `logcat -b crash`.
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv.put("LD_LIBRARY_PATH", prootLibs)
val networkLink = LinuxNetworkLinkComponent(this, LinuxRuntime.rootDir(this))
networkLink.setContext(this)
networkLink.publish()
components.add(networkLink)
components.forEach { it.start() }
watchSessionLog()
val line = command.joinToString(" ") { it.replace(" ", "\\ ") }
sessionPid = ProcessHelper.exec(line, hostEnv.toStringArray(), root, { status ->
Log.i(TAG, "session ended: $status")
endSession(status)
}, null)
sessionStarted = true
Log.i(TAG, "session pid $sessionPid, log ${sessionLog.path}")
}
/**
* Where the session writes its log. Downloads is the point — a failed run is handed over as a
* folder rather than dug out of app-private storage — but the session script redirects its own
* output there with `exec`, and a redirection a non-interactive shell cannot open ends that
* shell. So a public directory is used only once it is proven writable; otherwise the app's
* own files directory, which is bound into the session anyway, stands in.
*/
private fun logDirectory(): File {
val public = LinuxRuntime.debugLogDir()
if (public.isDirectory || public.mkdirs()) {
val probe = File(public, ".writable")
try {
if (probe.createNewFile() || probe.isFile) {
probe.delete()
return public
}
} catch (ignored: Exception) {
}
}
Log.w(TAG, "$public is not writable (storage permission?); logging to files/logs")
return File(filesDir, "logs").apply { mkdirs() }
}
/**
* The libraries and scripts the session runs, refreshed from the apk at every launch.
*
* The runtime image carries its own copies, but a runtime installed months ago carries the
* copies of that day and a device has no way to replace them from outside the app. Staging
* them here is how a fix inside the session shim, the controller reader or one of the scripts
* reaches an already-installed runtime without a ~790 MB re-download. Each lands through a
* rename, so a session that still has one mapped keeps the file it opened.
*/
private fun stageSessionFiles(root: File) {
val files = arrayOf(
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
"usr/local/bin/bannerlator-steam-library" to "usr/local/bin/bannerlator-steam-library",
"usr/local/bin/bannerlator-seed-redists" to "usr/local/bin/bannerlator-seed-redists",
)
for ((asset, relative) in files) {
val target = File(root, relative)
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
assets.open("linuxfs/$asset").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage $relative", e)
} finally {
if (!installed) staged.delete()
}
if (!installed) Log.e(TAG, "$relative NOT staged")
}
// What every process in the session preloads. LD_PRELOAD in the environment would not
// survive: the Steam client rebuilds it for each process it starts and appends its own
// overlay entry without a separator, which silently drops whatever was there.
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
val etc = File(root, "etc").apply { mkdirs() }
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString()) || !staged.renameTo(File(etc, "ld.so.preload"))) {
staged.delete()
Log.e(TAG, "could not write ld.so.preload")
}
}
/** Mirrors the session script's "== STEP" milestones onto the screen while it starts. */
private fun watchSessionLog() {
val handler = Handler(Looper.getMainLooper())
Thread({
var shown = ""
while (!finishing) {
try {
Thread.sleep(500)
val text = FileUtils.readString(sessionLog) ?: continue
val step = text.lineSequence().lastOrNull { it.startsWith("== STEP") } ?: continue
val message = step.substringAfter("== STEP ").substringAfter(' ')
if (message != shown) {
shown = message
handler.post { if (statusView.visibility == View.VISIBLE) statusView.text = message }
}
} catch (e: InterruptedException) {
return@Thread
} catch (ignored: Exception) {
}
}
}, "session-log").start()
}
private fun endSession(status: Int) {
if (finishing) return
finishing = true
runOnUiThread {
if (status != 0) {
statusView.visibility = View.VISIBLE
statusView.text = getString(R.string.session_ended, status, sessionLogName())
}
// A moment on screen, so a failure is readable rather than a flash of black.
Handler(Looper.getMainLooper()).postDelayed({ finish() }, if (status == 0) 0 else 4000)
}
}
private fun sessionLogName(): String =
if (::sessionLog.isInitialized) sessionLog.path else "-"
// ── Input ───────────────────────────────────────────────────────────────────────────────
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (padBridge?.onKeyEvent(event) == true) return true
// A hardware keyboard, forwarded to the compositor's wl_keyboard. This is how an account
// name and password get typed on the client's first run; the client's own on-screen
// keyboard covers a device without one, driven by touch or the pad.
if (compositorStarted && event.device != null && !PadBridge.isFromController(event.device)) {
val down = event.action == KeyEvent.ACTION_DOWN
if (down || event.action == KeyEvent.ACTION_UP) {
// An unmapped key may still be a real one on a foreign layout: its scan code is
// the evdev code the kernel gave Android in the first place.
var evdev = EvdevKeys.fromKeyCode(event.keyCode)
if (evdev < 0 && event.scanCode > 0) evdev = event.scanCode
if (evdev > 0) {
WaylandCompositor.nativeSendKey(evdev, if (down) 1 else 0)
return true
}
}
}
return super.dispatchKeyEvent(event)
}
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (padBridge?.onMotionEvent(event) == true) return true
return super.dispatchGenericMotionEvent(event)
}
/**
* Touch as a mouse: where you touch is where the pointer goes, and a tap is a left click.
* The compositor's pointer space is a fixed 1920x1080 whatever the output size, so the view's
* coordinates are scaled into it.
*/
override fun onTouchEvent(event: MotionEvent): Boolean {
val width = surfaceView.width.takeIf { it > 0 } ?: return false
val height = surfaceView.height.takeIf { it > 0 } ?: return false
val action = when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> 0
MotionEvent.ACTION_MOVE -> 1
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> 2
else -> return false
}
val x = (event.x / width * 1920f).toInt().coerceIn(0, 1919)
val y = (event.y / height * 1080f).toInt().coerceIn(0, 1079)
WaylandCompositor.nativeSendPointer(action, x, y)
return true
}
// ── Lifecycle ───────────────────────────────────────────────────────────────────────────
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) goFullscreen()
}
private fun goFullscreen() {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
if (Build.VERSION.SDK_INT >= 28) {
window.attributes = window.attributes.apply {
layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
}
}
override fun onDestroy() {
finishing = true
vsyncRunning = false
padBridge?.stop()
// proot runs with --kill-on-exit, so killing it takes the whole guest tree with it.
if (sessionPid != -1) {
android.os.Process.killProcess(sessionPid)
sessionPid = -1
}
components.reversed().forEach {
try {
it.stop()
} catch (e: Exception) {
Log.w(TAG, "stopping ${it.javaClass.simpleName}", e)
}
}
components.clear()
FakeInputWriter.releaseAllRingSlots()
WaylandCompositor.setFirstFrameListener(null)
super.onDestroy()
}
companion object {
private const val TAG = "SessionActivity"
/** Turns the whole controller feature off, for a true baseline on a device we cannot reach. */
private const val NO_PAD_SWITCH = "Download/steamdeck-no-pad"
/** Traces every interposer call into the session log. */
private const val PAD_LOG_SWITCH = "Download/steamdeck-pad-log"
}
}