The last of the Winlator lineage rewritten out; rumble on the phone

The five files the audit measured as Winlator's are replaced: a one-method callback interface by
java.util.function.Consumer, the component base by SessionPart (attach an application context,
start, stop), the environment list by HostEnvironment, the process starter by HostProcess, and
the pad's state holder by PadState with named sticks, triggers, directions and buttons. The
frame-generation tree is framegen/ (its contents were never Winlator's: lsfg-vk's port and
Bannerlator's Win-FG), the log tags are the app's, and the fake pad's rumble socket is now one
the app actually serves: RumbleComponent turns a game's force-feedback effects into the phone's
vibrator, which used to go nowhere. The two design notes describing Bannerlator's X11 path are
gone, and the README and credits say what is whose.
This commit is contained in:
The412Banner committed 2026-09-23 09:12:14 -04:00
1 parent 35dbef0536
commit a604dce6cb
84 files changed
+493 -1771

No files matched your search

@@ -178,9 +178,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// Xbox button, or a pad the client hides the controls for, has no other
// way to open the client's menu in a game.
drawerOpen = false
padBridge?.applyTouch { st -> st.setPressed(com.steamdeck.launcher.input.GamepadState.IDX_BUTTON_MODE.toInt(), true) }
padBridge?.applyTouch { st -> st.press(com.steamdeck.launcher.input.PadState.GUIDE, true) }
Handler(Looper.getMainLooper()).postDelayed({
padBridge?.applyTouch { st -> st.setPressed(com.steamdeck.launcher.input.GamepadState.IDX_BUTTON_MODE.toInt(), false) }
padBridge?.applyTouch { st -> st.press(com.steamdeck.launcher.input.PadState.GUIDE, false) }
}, 90)
}) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({
@@ -3,8 +3,8 @@ package com.steamdeck.launcher.audio;
import android.os.Process;
import android.util.Log;
import com.steamdeck.launcher.core.EnvironmentComponent;
import com.steamdeck.launcher.core.ProcessHelper;
import com.steamdeck.launcher.core.SessionPart;
import com.steamdeck.launcher.core.HostProcess;
import java.io.File;
import java.util.ArrayList;
@@ -28,7 +28,7 @@ import java.util.ArrayList;
* picks an audio driver, and reports itself unavailable if not. Ported from Bannerlator (GPL-3.0);
* the helper binary is the one built by The412Banner/directaudio's relay workflow.
*/
public class DirectAudioRelayComponent extends EnvironmentComponent {
public class DirectAudioRelayComponent extends SessionPart {
private static final String TAG = "DirectAudioRelay";
/** The helper, named as a library so Android will run it. */
public static final String BINARY = "libdirectaudiorelay.so";
@@ -53,7 +53,7 @@ public class DirectAudioRelayComponent extends EnvironmentComponent {
@Override
public void start() {
stop();
File binary = new File(context.getApplicationInfo().nativeLibraryDir, BINARY);
File binary = new File(app().getApplicationInfo().nativeLibraryDir, BINARY);
if (!binary.isFile()) {
Log.w(TAG, "helper missing at " + binary + "; DirectAudio will report itself unavailable");
return;
@@ -97,7 +97,7 @@ public class DirectAudioRelayComponent extends EnvironmentComponent {
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
}
ArrayList<String> env = new ArrayList<>();
env.add("HOME=" + context.getFilesDir());
env.add("HOME=" + app().getFilesDir());
java.io.PrintWriter out = null;
if (logFile != null) {
try {
@@ -110,8 +110,8 @@ public class DirectAudioRelayComponent extends EnvironmentComponent {
}
}
final java.io.PrintWriter log = out;
pid = ProcessHelper.exec(command.toString(), env.toArray(new String[0]),
context.getFilesDir(), null,
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
if (log != null) synchronized (log) { log.println(line); log.flush(); }
@@ -5,8 +5,8 @@ import android.os.Process;
import android.util.Log;
import com.steamdeck.launcher.core.FileUtils;
import com.steamdeck.launcher.core.EnvironmentComponent;
import com.steamdeck.launcher.core.ProcessHelper;
import com.steamdeck.launcher.core.SessionPart;
import com.steamdeck.launcher.core.HostProcess;
import com.steamdeck.launcher.core.TarZst;
import java.io.File;
@@ -26,7 +26,7 @@ import java.util.ArrayList;
* recreate - those need the pasink native client, and a session here is a foreground activity
* that does not background the way a game container does.
*/
public class PulseAudioComponent extends EnvironmentComponent {
public class PulseAudioComponent extends SessionPart {
private static final String TAG = "PulseAudio";
/** Where the guest reaches the daemon; the session exports PULSE_SERVER=unix:<this>. */
public static final String SOCKET_NAME = "PS0";
@@ -136,7 +136,7 @@ public class PulseAudioComponent extends EnvironmentComponent {
// startup: all of it used to reach logcat and nothing else, so a user's folder said nothing
// at all about sound. Four separate faults hid behind "no input device" in one night.
final java.io.PrintWriter out = openLog();
pid = ProcessHelper.exec(command, env.toArray(new String[0]), workingDir, null,
pid = HostProcess.start(command, env.toArray(new String[0]), workingDir, null,
line -> {
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
@@ -1,6 +0,0 @@
package com.steamdeck.launcher.core;
/** One-argument callback, kept so the ported runtime classes read as they did in Bannerlator. */
public interface Callback<T> {
void call(T value);
}
@@ -50,7 +50,7 @@ public final class Downloader {
* 790 MB download survive a dropped connection instead of starting over.
*/
public static boolean downloadFile(String url, File destination, boolean resume,
Callback<Float> progress) {
java.util.function.Consumer<Float> progress) {
HttpURLConnection connection = null;
long have = resume && destination.isFile() ? destination.length() : 0;
try {
@@ -87,11 +87,11 @@ public final class Downloader {
// enough to move a progress bar smoothly.
if (progress != null && written - lastReport > (1 << 20)) {
lastReport = written;
progress.call(total > 0 ? written / (float) total : -1f);
progress.accept(total > 0 ? written / (float) total : -1f);
}
}
}
if (progress != null) progress.call(1f);
if (progress != null) progress.accept(1f);
return total <= 0 || written >= total;
} catch (Exception e) {
Log.w(TAG, "download " + url, e);
@@ -1,31 +0,0 @@
package com.steamdeck.launcher.core;
import java.util.LinkedHashMap;
import java.util.Map;
/** An ordered NAME=VALUE set, in the shape {@code ProcessBuilder} and proot want it. */
public class EnvVars {
private final Map<String, String> vars = new LinkedHashMap<>();
public EnvVars put(String name, String value) {
vars.put(name, value);
return this;
}
public void putAll(EnvVars other) {
if (other != null) vars.putAll(other.vars);
}
public String get(String name) { return vars.get(name); }
public boolean has(String name) { return vars.containsKey(name); }
public boolean isEmpty() { return vars.isEmpty(); }
public String[] toStringArray() {
String[] out = new String[vars.size()];
int i = 0;
for (Map.Entry<String, String> e : vars.entrySet()) out[i++] = e.getKey() + "=" + e.getValue();
return out;
}
}
@@ -1,17 +0,0 @@
package com.steamdeck.launcher.core;
import android.content.Context;
/**
* One piece of a running session - the audio daemon, the network-link file, the session process
* itself. The session starts them in order and stops them in reverse.
*/
public abstract class EnvironmentComponent {
protected Context context;
public void setContext(Context context) { this.context = context; }
public abstract void start();
public abstract void stop();
}
@@ -0,0 +1,13 @@
package com.steamdeck.launcher.core
/** The variables a host process is started with, in the order they were set. */
class HostEnvironment {
private val entries = LinkedHashMap<String, String>()
operator fun set(name: String, value: String) {
entries[name] = value
}
/** `NAME=VALUE` lines, the shape ProcessBuilder and proot take. */
fun asArray(): Array<String> = entries.map { (name, value) -> "$name=$value" }.toTypedArray()
}
@@ -0,0 +1,94 @@
package com.steamdeck.launcher.core
import android.util.Log
import java.io.File
import java.util.function.Consumer
/**
* Starts a process on the Android side - proot, the audio daemon, logcat - and hands back its pid.
*
* The pid matters: stopping a session means killing that exact process (proot runs with
* --kill-on-exit, so the guest tree goes with it), and java.lang.Process does not expose it before
* API 33, so it is read from the implementation's private field. Output can be drained line by
* line to a callback; without one it goes to /dev/null, never to a pipe nobody reads, which would
* block the child the moment the pipe filled.
*/
object HostProcess {
private const val TAG = "HostProcess"
/**
* @param command the program and its arguments as one line; a backslash escapes a space, since
* paths under /data are full of them.
* @param env `NAME=VALUE` lines added to the app's own environment (proot needs nothing from
* the inherited set, and the guest starts with `env -i` anyway), or null.
* @param onExit told the exit status from a waiting thread, or null.
* @param onLine told each line of stdout and stderr, or null to discard both.
* @return the pid, or -1 when the process could not be started.
*/
@JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int {
val argv = split(command)
if (argv.isEmpty()) return -1
return try {
val builder = ProcessBuilder(argv)
if (dir != null) builder.directory(dir)
env?.forEach { line ->
val eq = line.indexOf('=')
if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1)
}
builder.redirectErrorStream(true)
if (onLine == null) builder.redirectOutput(File("/dev/null"))
val process = builder.start()
val pid = pidOf(process)
Log.i(TAG, "started pid $pid: $command")
if (onLine != null) {
Thread({
try {
process.inputStream.bufferedReader().useLines { lines -> lines.forEach { onLine.accept(it) } }
} catch (e: Exception) {
// The process ended or the pipe closed; nothing more to read.
}
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
}
if (onExit != null) {
Thread({
var status = -1
try { status = process.waitFor() } catch (e: InterruptedException) { /* reported as -1 */ }
onExit.accept(status)
}, "proc-wait-$pid").apply { priority = Thread.NORM_PRIORITY - 1; start() }
}
pid
} catch (e: Exception) {
Log.e(TAG, "could not start: $command", e)
-1
}
}
private fun pidOf(process: Process): Int = try {
val field = process.javaClass.getDeclaredField("pid")
field.isAccessible = true
val pid = field.getInt(process)
field.isAccessible = false
pid
} catch (e: Exception) {
-1
}
/** Splits a command line on spaces; a backslash keeps the space that follows it. */
@JvmStatic
fun split(command: String): List<String> {
val parts = ArrayList<String>()
val current = StringBuilder()
var escaped = false
for (c in command) {
when {
escaped -> { current.append(c); escaped = false }
c == '\\' -> escaped = true
c == ' ' -> if (current.isNotEmpty()) { parts.add(current.toString()); current.setLength(0) }
else -> current.append(c)
}
}
if (current.isNotEmpty()) parts.add(current.toString())
return parts
}
}
@@ -1,116 +0,0 @@
package com.steamdeck.launcher.core;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* Starts the session's host processes - proot and the audio daemon - and reports the exit status.
* The pid is read out of the hidden field on {@code java.lang.Process} because stopping a session
* means killing that exact process: proot runs with {@code --kill-on-exit}, so the whole guest
* tree goes with it.
*/
public final class ProcessHelper {
private static final String TAG = "ProcessHelper";
private ProcessHelper() {}
public static int exec(String command, String[] envp, File workingDir) {
return exec(command, envp, workingDir, null, null);
}
/**
* @param lineCallback receives stdout and stderr line by line, or null to discard both. The
* Linux session sends everything to its own log file, so nothing is passed
* here for it; the audio daemon is the one that benefits.
*/
public static int exec(String command, String[] envp, File workingDir,
Callback<Integer> terminationCallback, Callback<String> lineCallback) {
int pid = -1;
try {
ProcessBuilder builder = new ProcessBuilder(splitCommand(command));
if (workingDir != null) builder.directory(workingDir);
if (envp != null) {
// Added to the app's own environment rather than replacing it, which is what
// Bannerlator does on the path this was taken from. proot needs nothing from the
// inherited set, but the guest command starts with `env -i` anyway, so clearing
// here buys nothing and only differs from the configuration proven on a device.
for (String entry : envp) {
int eq = entry.indexOf('=');
if (eq > 0) builder.environment().put(entry.substring(0, eq), entry.substring(eq + 1));
}
}
builder.redirectErrorStream(true);
if (lineCallback == null) builder.redirectOutput(new File("/dev/null"));
Process process = builder.start();
Field pidField = process.getClass().getDeclaredField("pid");
pidField.setAccessible(true);
pid = pidField.getInt(process);
pidField.setAccessible(false);
Log.i(TAG, "started pid " + pid + ": " + command);
if (lineCallback != null) drain(process.getInputStream(), lineCallback);
if (terminationCallback != null) {
Thread waiter = new Thread(() -> {
int status = -1;
try {
status = process.waitFor();
} catch (InterruptedException ignored) {
} finally {
terminationCallback.call(status);
}
}, "proc-wait-" + pid);
waiter.setPriority(Thread.NORM_PRIORITY - 1);
waiter.start();
}
} catch (Exception e) {
Log.e(TAG, "exec " + command, e);
}
return pid;
}
private static void drain(InputStream stream, Callback<String> lineCallback) {
Thread thread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
lineCallback.call(line);
}
} catch (Exception ignored) {
}
}, "proc-out");
thread.setPriority(Thread.NORM_PRIORITY - 1);
thread.start();
}
/** Splits on spaces, honouring backslash-escaped spaces - paths under /data are full of them. */
public static String[] splitCommand(String command) {
List<String> parts = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean escaped = false;
for (int i = 0; i < command.length(); i++) {
char c = command.charAt(i);
if (escaped) {
current.append(c);
escaped = false;
} else if (c == '\\') {
escaped = true;
} else if (c == ' ') {
if (current.length() > 0) {
parts.add(current.toString());
current.setLength(0);
}
} else {
current.append(c);
}
}
if (current.length() > 0) parts.add(current.toString());
return parts.toArray(new String[0]);
}
}
@@ -43,7 +43,7 @@ object SessionLogCapture {
this.target = target
// -T 1 starts at the newest line rather than replaying the whole buffer; -v threadtime
// keeps the timestamps and thread ids that make two logs line up.
pid = ProcessHelper.exec(
pid = HostProcess.start(
"/system/bin/logcat -v threadtime -T 1 --pid=" + Process.myPid(),
null, target.parentFile, null,
) { line ->
@@ -103,7 +103,7 @@ object SessionLogCapture {
// callback on another thread, so a poll for "is it empty yet" declared an empty buffer
// every time and still cost the wait. exec() returns a pid, never an exit status - the
// first version printed that pid as "rc", which was nonsense in the file.
val pid = ProcessHelper.exec(
val pid = HostProcess.start(
"/system/bin/logcat -b crash -d -v threadtime -t 400", null, target.parentFile,
{ done.countDown() },
) { line -> synchronized(lines) { lines.append(line).append('\n') } }
@@ -0,0 +1,26 @@
package com.steamdeck.launcher.core;
import android.content.Context;
/**
* One thing a running session depends on beside the guest process itself: the audio daemon, the
* rumble listener, the battery the client reads, the network-link file. The session starts its
* parts in order before the guest and stops them in reverse after it. A part is handed the
* application context, never an activity's, so nothing here can keep a screen alive.
*/
public abstract class SessionPart {
private Context app;
public final void attach(Context context) {
this.app = context.getApplicationContext();
}
/** The application context, valid after {@link #attach}. */
protected final Context app() {
return app;
}
public abstract void start();
public abstract void stop();
}
@@ -137,21 +137,21 @@ import java.util.Locale
/**
* What to do when a pasted item already exists at the destination.
*
* OVERWRITE and MERGE resolve to the same call - `copyWithProgress` recurses into an existing
* directory and truncates existing files - but they mean different things to the user, so both are
* OVERWRITE and MERGE resolve to the same call — `copyWithProgress` recurses into an existing
* directory and truncates existing files — but they mean different things to the user, so both are
* offered and the wording is chosen per item type (files overwrite, folders merge).
*/
enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP }
/**
* Ordering for the file list. Folders always lead regardless of direction - a descending sort that
* Ordering for the file list. Folders always lead regardless of direction — a descending sort that
* buries every folder under the files is never what someone means by "Z to A".
*/
/**
* Shortens a path from the LEFT, keeping whole segments.
*
* Compose's TextOverflow can only ellipsise the tail, which for a path throws away the part that
* matters - `/storage/emulated/0/Winlator/Game…` tells you nothing about where you are.
* matters — `/storage/emulated/0/Games/…` tells you nothing about where you are.
*/
private fun elidePathStart(path: String, max: Int): String {
if (path.length <= max) return path
@@ -196,7 +196,7 @@ private fun isWithin(child: File, ancestor: File): Boolean {
// ── DOS file attributes (Read-only / Hidden) ──
// The in-container file manager (wfm.exe) exposes these in its Properties dialog; this mirrors the
// same two toggles for files browsed from the app side. No root - we only touch permission bits the
// same two toggles for files browsed from the app side. No root — we only touch permission bits the
// app owns (container files) and the Wine DOS-attribute xattr.
// FILE_ATTRIBUTE_HIDDEN, as Wine encodes it in the user.DOSATTRIB extended attribute.
@@ -204,7 +204,7 @@ private const val FILE_ATTRIBUTE_HIDDEN = 0x2
private const val DOSATTRIB_XATTR = "user.DOSATTRIB"
// Snapshot of a file's two toggleable attributes. hiddenSupported is false when the underlying
// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) - the Hidden toggle is then
// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) — the Hidden toggle is then
// disabled while Read-only keeps working.
private data class FileAttrState(
val readOnly: Boolean,
@@ -226,7 +226,7 @@ private fun parseDosAttrib(raw: ByteArray): Int {
// comes back hiddenSupported=false (Hidden toggle disabled), Read-only always resolves.
private fun readFileAttrs(file: File): FileAttrState {
val path = file.absolutePath
// Read-only reflects the OWNER write bit - that's what Wine maps to FILE_ATTRIBUTE_READONLY.
// Read-only reflects the OWNER write bit — that's what Wine maps to FILE_ATTRIBUTE_READONLY.
val readOnly = runCatching {
(android.system.Os.stat(path).st_mode and android.system.OsConstants.S_IWUSR) == 0
}.getOrDefault(!file.canWrite())
@@ -309,7 +309,7 @@ fun describeLocation(file: File): FavLocation {
}
// Semantic identity colours for the favourite-card drive badge. Intentionally NOT theme
// accent colours - they identify the storage source at a glance. Returns (background, foreground).
// accent colours — they identify the storage source at a glance. Returns (background, foreground).
private fun badgeColors(loc: FavLocation): Pair<Color, Color> {
val white = Color(0xFFFFFFFF)
return when {
@@ -350,13 +350,13 @@ fun FileManagerScreen(
val rootDir = remember {
// Both modes: honour an explicit caller-supplied start dir (e.g. Log Manager's game-log
// folder), else open at the INTERNAL STORAGE ROOT. Selection screens (drive-folder pick,
// local component pick, imports) previously defaulted to Download which - combined with the
// currentRoot floor below - trapped users in Download with no way up (reported bug).
// local component pick, imports) previously defaulted to Download which — combined with the
// currentRoot floor below — trapped users in Download with no way up (reported bug).
initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
}
var currentDir by remember { mutableStateOf(rootDir) }
// The up/back FLOOR - back + the up-arrow are disabled while currentDir == currentRoot. It MUST be
// The up/back FLOOR — back + the up-arrow are disabled while currentDir == currentRoot. It MUST be
// the VOLUME ROOT of the start dir (internal /storage/emulated/0, or an SD card /storage/XXXX-XXXX),
// NOT the start dir itself: otherwise opening at any subfolder disables up/back and traps the user
// there. (Mirrors the volume-root logic in favLocationOf above.)
@@ -377,7 +377,7 @@ fun FileManagerScreen(
var selectedEntry by remember { mutableStateOf<File?>(null) }
var showMenuFor by remember { mutableStateOf<File?>(null) }
// Clipboard holds a LIST so one paste can carry a whole selection. Cut/copy semantics are a
// flag on the batch rather than per item - mixing the two in one clipboard has no sane meaning.
// flag on the batch rather than per item — mixing the two in one clipboard has no sane meaning.
var clipboardFiles by remember { mutableStateOf<List<File>>(emptyList()) }
var isCutOperation by remember { mutableStateOf(false) }
// Multi-select. Keyed by absolute path rather than File so a directory reload (which builds
@@ -398,10 +398,10 @@ fun FileManagerScreen(
var sortDesc by remember { mutableStateOf(browsePrefs.getBoolean("fmSortDesc", false)) }
var showHidden by remember { mutableStateOf(browsePrefs.getBoolean("fmShowHidden", true)) }
var showSortMenu by remember { mutableStateOf(false) }
// View mode: list of cards (default) or a thumbnail grid. Density applies to the list only -
// View mode: list of cards (default) or a thumbnail grid. Density applies to the list only —
// a grid tile has no second line to compact.
// The grid/list toggle is the SOURCE OF TRUTH in BOTH orientations (it drives the view and its
// choice persists across rotation). Grid is the default - most useful in landscape, and in
// choice persists across rotation). Grid is the default — most useful in landscape, and in
// portrait GridCells.Adaptive naturally renders fewer columns (~2). Do NOT force portrait to list:
// that broke the toggle on-device (tapping it did nothing in portrait).
var gridView by remember { mutableStateOf(browsePrefs.getBoolean("fmGridView", true)) }
@@ -502,7 +502,7 @@ fun FileManagerScreen(
suspend fun askConflict(file: File): ConflictChoice? {
pendingConflict = file
conflictChoice = null
// Poll rather than plumb a CompletableDeferred through Compose state - the dialog answers
// Poll rather than plumb a CompletableDeferred through Compose state — the dialog answers
// by setting conflictChoice, and this coroutine is already off the critical path.
while (pendingConflict != null && conflictChoice == null) kotlinx.coroutines.delay(50)
return conflictChoice
@@ -556,7 +556,7 @@ fun FileManagerScreen(
operationLabel = buildString {
append(if (cut) "Moving" else "Copying")
if (sources.size > 1) append(" ${done + 1}/${sources.size}")
append(" - ").append(src.name)
append(" — ").append(src.name)
}
var lastPct = -1
val onProgress = FileOps.ProgressCallback { copied, total ->
@@ -745,7 +745,7 @@ fun FileManagerScreen(
isOperationRunning = true
var failed = 0
victims.forEachIndexed { i, f ->
operationLabel = "Deleting ${i + 1}/${victims.size} - ${f.name}"
operationLabel = "Deleting ${i + 1}/${victims.size} — ${f.name}"
if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++
}
isOperationRunning = false
@@ -761,7 +761,7 @@ fun FileManagerScreen(
)
}
// Paste conflict - one per colliding item, with "apply to all" for a long batch.
// Paste conflict — one per colliding item, with "apply to all" for a long batch.
pendingConflict?.let { conflict ->
val isDir = conflict.isDirectory
OutlinedAlertDialog(
@@ -856,7 +856,7 @@ fun FileManagerScreen(
val driveChipAlpha = if (showFavorites) 0.45f else 1f
Box {
// The drive/location selector opens the drive dropdown, so give it the same outlined
// look as the "New Folder" button + the rail location items - it reads as a button, not
// look as the "New Folder" button + the rail location items — it reads as a button, not
// plain text. Border uses the theme accent token; behaviour unchanged.
val driveChipShape = RoundedCornerShape(8.dp)
Text(
@@ -909,7 +909,7 @@ fun FileManagerScreen(
if (showFavorites) {
Text(
text = "Favorites",
text = "★ Favorites",
color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
@@ -918,12 +918,12 @@ fun FileManagerScreen(
modifier = Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
// PORTRAIT: hide the current-folder name - it's redundant with the path bar directly
// PORTRAIT: hide the current-folder name — it's redundant with the path bar directly
// below (which shows the full path). The spacer keeps the action icons right-aligned.
Spacer(Modifier.weight(1f))
} else {
// LANDSCAPE: the CURRENT FOLDER, not the full path. A path ellipsised on the right
// hides its tail - the only part that says where you are ("…/Winlator/Game…"). The
// hides its tail — the only part that says where you are ("…/Games/…"). The
// full path moves to the line below, where it has room.
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
@@ -1029,7 +1029,7 @@ fun FileManagerScreen(
)
}
// Free space on the volume being browsed - worth knowing before starting a 60 GB copy.
// Free space on the volume being browsed — worth knowing before starting a 60 GB copy.
val freeSpace = remember(currentDir.absolutePath, entries) {
runCatching { currentDir.usableSpace }.getOrDefault(0L)
}
@@ -1225,7 +1225,7 @@ fun FileManagerScreen(
val locationSections = buildList {
add(RailSection("STORAGE", storageItems))
if (quickItems.isNotEmpty()) add(RailSection("QUICK", quickItems))
if (favItems.isNotEmpty()) add(RailSection("FAVORITES", favItems))
if (favItems.isNotEmpty()) add(RailSection("★ FAVORITES", favItems))
}
Row(modifier = Modifier.weight(1f).fillMaxWidth()) {
@@ -1431,7 +1431,7 @@ fun FileManagerScreen(
// The context-menu item list shared by the list rows (FileItemRow) and the grid tiles
// (FileGridTile), so both open the identical menu. Gating (isDir/canRun/isInno/looksLikeArchive) is
// recomputed from [file] here - one source of truth for what each item shows. Every item dismisses
// recomputed from [file] here — one source of truth for what each item shows. Every item dismisses
// the menu first, then runs its action.
@Composable
private fun FileContextMenuItems(
@@ -1462,7 +1462,7 @@ private fun FileContextMenuItems(
onClick = { onDismissMenu(); onProperties() },
)
MenuItemDivider()
// Favorites are directories - only folders get the pin toggle.
// Favorites are directories — only folders get the pin toggle.
if (isDir) {
DropdownMenuItem(
text = { Text(if (isFavorite) "Remove from Favorites" else "Add to Favorites") },
@@ -1708,7 +1708,7 @@ private fun FavoritesList(
contentAlignment = Alignment.Center,
) {
Text(
text = "No favorites yet - pin a folder with its ⋮ menu to jump back here fast.",
text = "No favorites yet — pin a folder with its ⋮ menu to jump back here fast.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 13.sp,
modifier = Modifier.padding(horizontal = 32.dp),
@@ -1729,7 +1729,7 @@ private fun FavoritesList(
}
}
// A single favourite - matches the FileItemRow card style (surfaceContainer + outline +
// A single favourite — matches the FileItemRow card style (surfaceContainer + outline +
// RoundedCornerShape(10.dp)). Shows the folder name, a coloured drive badge + origin text,
// and the full display path; tapping jumps into it, the filled star unpins.
@Composable
@@ -1818,7 +1818,7 @@ private fun FavoriteCard(
/**
* One entry in the File Manager's grid view: a big thumbnail with the name under it.
*
* Deliberately drops size and date - at this width they truncate to noise. The grid is for
* Deliberately drops size and date — at this width they truncate to noise. The grid is for
* recognising things by sight (screenshots, covers, game folders); the list stays the view for
* reading details.
*/
@@ -1852,7 +1852,7 @@ private fun FileGridTile(
if (bmp != null) exeIcon = bmp.asImageBitmap()
}
}
// The tile has no ⋮ button - long-press opens this menu, anchored to the Box around the Card.
// The tile has no ⋮ button — long-press opens this menu, anchored to the Box around the Card.
Box {
Card(
modifier = Modifier
@@ -1942,7 +1942,7 @@ private fun FileGridTile(
/**
* Properties sheet for a single file or folder: basic info plus the two Windows/Wine file attributes
* the in-container file manager (wfm.exe) also exposes - Read-only and Hidden. Each toggle applies
* the in-container file manager (wfm.exe) also exposes — Read-only and Hidden. Each toggle applies
* immediately (off the main thread) and refreshes the listing via [onChanged].
*
* State is keyed on the file so it always reflects the entry it was opened for. On a filesystem that
@@ -1980,7 +1980,7 @@ private fun FilePropertiesDialog(
overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(6.dp))
PropertyLine("Location", file.parent ?: "-")
PropertyLine("Location", file.parent ?: "—")
PropertyLine(
"Type",
if (file.isDirectory) "Folder"
@@ -2033,7 +2033,7 @@ private fun FilePropertiesDialog(
attrs = attrs?.copy(hidden = want)
onChanged()
} else {
// The write failed after all - disable the toggle rather than lie.
// The write failed after all — disable the toggle rather than lie.
attrs = attrs?.copy(hiddenSupported = false)
Toast.makeText(context, "Couldn't change Hidden on this storage", Toast.LENGTH_SHORT).show()
}
@@ -64,8 +64,8 @@ public class FakeInputWriter {
BTN_SELECT, BTN_START, BTN_THUMBL, BTN_THUMBR,
BTN_MODE
};
/** Bit 10 of the snapshot word. The first ten are GamepadState's own bit order; the Steam
* button is not, because GamepadState keeps 10 and 11 for the triggers. */
/** Bit 10 of the snapshot word. The first ten are PadState's own bit order; the Steam
* button is not, because PadState keeps 10 and 11 for the triggers. */
private static final int SNAPSHOT_IDX_MODE = 10;
private static final int EVENT_SIZE = 24;
@@ -595,7 +595,7 @@ public class FakeInputWriter {
writeEvent(EV_KEY, BUTTON_MAP[idx], pressed ? 1 : 0);
}
public synchronized void writeGamepadState(GamepadState state) {
public synchronized void writePad(PadState state) {
if (!isOpen && !open())
return;
@@ -613,19 +613,19 @@ public class FakeInputWriter {
// Buttons
for (int i = 0; i < 10; i++) {
writeButton(i, state.isPressed((byte) i));
writeButton(i, state.isDown(i));
}
// The Steam button. In a Linux session this is what opens the client's own in-game menu,
// and the client looks for it where an Xbox pad keeps it: evdev BTN_MODE, which SDL then
// reports as button 8 - exactly the "guide:b8" in the mapping Steam writes for this pad.
writeButton(SNAPSHOT_IDX_MODE,
state.isPressed(GamepadState.IDX_BUTTON_MODE));
state.isDown(PadState.GUIDE));
// Sticks
int lx = (int) (state.thumbLX * 32767);
int ly = (int) (state.thumbLY * 32767);
int rx = (int) (state.thumbRX * 32767);
int ry = (int) (state.thumbRY * 32767);
int lx = (int) (state.leftX * 32767);
int ly = (int) (state.leftY * 32767);
int rx = (int) (state.rightX * 32767);
int ry = (int) (state.rightY * 32767);
// The fake evdev ring is event-queue semantics, so unchanged axes normally
// stay silent; forceResend overrides that to emit a complete keyframe.
@@ -647,8 +647,8 @@ public class FakeInputWriter {
}
// L2 and R2 (Triggers)
int tl = (int) (state.triggerL * 255);
int tr = (int) (state.triggerR * 255);
int tl = (int) (state.leftTrigger * 255);
int tr = (int) (state.rightTrigger * 255);
if (forceResend || tl != prevTriggerL) {
prevTriggerL = tl;
writeEvent(EV_ABS, ABS_BRAKE, tl);
@@ -659,8 +659,8 @@ public class FakeInputWriter {
}
// D-pad
int hatX = state.dpad[3] ? -1 : (state.dpad[1] ? 1 : 0);
int hatY = state.dpad[0] ? -1 : (state.dpad[2] ? 1 : 0);
int hatX = state.hatX();
int hatY = state.hatY();
if (forceResend || hatX != prevHatX) {
prevHatX = hatX;
writeEvent(EV_ABS, ABS_HAT0X, hatX);
@@ -1,58 +0,0 @@
package com.steamdeck.launcher.input;
public class GamepadState {
/** Bit index of the Steam/Guide button; 0-9 are the face/shoulder/stick buttons. */
public static final byte IDX_BUTTON_MODE = 12;
public float thumbLX = 0;
public float thumbLY = 0;
public float thumbRX = 0;
public float thumbRY = 0;
public float triggerL = 0;
public float triggerR = 0;
public final boolean[] dpad = new boolean[4];
public short buttons = 0;
public void setPressed(int buttonIdx, boolean pressed) {
int flag = 1<<buttonIdx;
if (pressed) {
buttons |= flag;
}
else buttons &= ~flag;
}
public boolean isPressed(int buttonIdx) {
return (buttons & (1<<buttonIdx)) != 0;
}
public byte getDPadX() {
return (byte)(dpad[1] ? 1 : (dpad[3] ? -1 : 0));
}
public byte getDPadY() {
return (byte)(dpad[0] ? -1 : (dpad[2] ? 1 : 0));
}
public void copy(GamepadState other) {
thumbLX = other.thumbLX;
thumbLY = other.thumbLY;
thumbRX = other.thumbRX;
thumbRY = other.thumbRY;
triggerL = other.triggerL;
triggerR = other.triggerR;
buttons = other.buttons;
System.arraycopy(other.dpad, 0, dpad, 0, dpad.length);
}
public void reset() {
thumbLX = 0;
thumbLY = 0;
thumbRX = 0;
thumbRY = 0;
triggerL = 0;
triggerR = 0;
buttons = 0;
java.util.Arrays.fill(dpad, false);
}
}
@@ -30,9 +30,9 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
private class Control(
val id: String,
val label: String,
/** Bit index in GamepadState, or -1. */
/** A PadState button number, or -1. */
val button: Int,
/** Index into GamepadState.dpad, or -1. */
/** A d-pad direction (0 up, 1 right, 2 down, 3 left), or -1. */
val dpad: Int,
/** 0 = left stick, 1 = right stick, -1 = a button. */
val stick: Int,
@@ -83,7 +83,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
Control("select", "⧉", 6, -1, -1, dp(20f)),
Control("start", "☰", 7, -1, -1, dp(20f)),
// The client's own in-game menu; the interposer publishes it as BTN_MODE.
Control("guide", "◉", GamepadState.IDX_BUTTON_MODE.toInt(), -1, -1, dp(22f)),
Control("guide", "◉", PadState.GUIDE, -1, -1, dp(22f)),
Control("qam", "⋯", -1, -1, -1, dp(22f)),
)
@@ -318,10 +318,13 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
val held = control.pressedBy != -1
when {
control.stick >= 0 && !control.dirty -> {}
control.stick == 0 -> { state.thumbLX = control.kx / control.radius; state.thumbLY = control.ky / control.radius; control.dirty = false }
control.stick == 1 -> { state.thumbRX = control.kx / control.radius; state.thumbRY = control.ky / control.radius; control.dirty = false }
control.dpad >= 0 -> state.dpad[control.dpad] = held
control.button >= 0 -> state.setPressed(control.button, held)
control.stick == 0 -> { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius; control.dirty = false }
control.stick == 1 -> { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius; control.dirty = false }
control.dpad == 0 -> state.up = held
control.dpad == 1 -> state.right = held
control.dpad == 2 -> state.down = held
control.dpad == 3 -> state.left = held
control.button >= 0 -> state.press(control.button, held)
}
}
}
@@ -15,7 +15,7 @@ import java.io.File;
* <p>Android hands a gamepad to the foreground activity as key and motion events; the Steam client
* inside the runtime never sees that. What it does scan is {@code /dev/input}, which the session's
* interposer (libfakeinput.so) serves out of the shared-memory rings written here. So the path is:
* Android event → {@link GamepadState} → {@link FakeInputWriter} ring → interposer → evdev node →
* Android event → {@link PadState} → {@link FakeInputWriter} ring → interposer → evdev node →
* SDL → Big Picture.
*
* <p>The identity the interposer reports is an Xbox 360 pad, which is what makes SDL apply a known
@@ -31,8 +31,8 @@ public final class PadBridge {
private static final long QAM_GUIDE_TAIL_MS = 40;
private final FakeInputWriter writer;
private final GamepadState state = new GamepadState();
private final GamepadState effectiveState = new GamepadState();
private final PadState state = new PadState();
private final PadState effectiveState = new PadState();
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private boolean open;
private boolean systemGuidePressed;
@@ -61,8 +61,8 @@ public final class PadBridge {
qamSyntheticAPressed = false;
qamChordGeneration++;
if (open) {
state.reset();
writer.writeGamepadState(state);
state.clear();
writer.writePad(state);
writer.close();
open = false;
}
@@ -92,28 +92,28 @@ public final class PadBridge {
if (!isFromController(event.getDevice())) return false;
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BUTTON_A: state.setPressed(0, pressed); break;
case KeyEvent.KEYCODE_BUTTON_B: state.setPressed(1, pressed); break;
case KeyEvent.KEYCODE_BUTTON_X: state.setPressed(2, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Y: state.setPressed(3, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L1: state.setPressed(4, pressed); break;
case KeyEvent.KEYCODE_BUTTON_R1: state.setPressed(5, pressed); break;
case KeyEvent.KEYCODE_BUTTON_A: state.press(0, pressed); break;
case KeyEvent.KEYCODE_BUTTON_B: state.press(1, pressed); break;
case KeyEvent.KEYCODE_BUTTON_X: state.press(2, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Y: state.press(3, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L1: state.press(4, pressed); break;
case KeyEvent.KEYCODE_BUTTON_R1: state.press(5, pressed); break;
case KeyEvent.KEYCODE_BUTTON_SELECT:
case KeyEvent.KEYCODE_BACK: state.setPressed(6, pressed); break;
case KeyEvent.KEYCODE_BACK: state.press(6, pressed); break;
case KeyEvent.KEYCODE_BUTTON_START:
case KeyEvent.KEYCODE_MENU: state.setPressed(7, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: state.setPressed(8, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: state.setPressed(9, pressed); break;
case KeyEvent.KEYCODE_MENU: state.press(7, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: state.press(8, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: state.press(9, pressed); break;
// The client's own in-game menu is opened by this one; the interposer publishes it as
// BTN_MODE, which SDL reports as the "guide" button.
case KeyEvent.KEYCODE_BUTTON_MODE:
case KeyEvent.KEYCODE_HOME: state.setPressed(GamepadState.IDX_BUTTON_MODE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L2: state.triggerL = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_BUTTON_R2: state.triggerR = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_DPAD_UP: state.dpad[0] = pressed; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: state.dpad[1] = pressed; break;
case KeyEvent.KEYCODE_DPAD_DOWN: state.dpad[2] = pressed; break;
case KeyEvent.KEYCODE_DPAD_LEFT: state.dpad[3] = pressed; break;
case KeyEvent.KEYCODE_HOME: state.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L2: state.leftTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_BUTTON_R2: state.rightTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_DPAD_UP: state.up = pressed; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: state.right = pressed; break;
case KeyEvent.KEYCODE_DPAD_DOWN: state.down = pressed; break;
case KeyEvent.KEYCODE_DPAD_LEFT: state.left = pressed; break;
default: return false;
}
publish();
@@ -124,19 +124,19 @@ public final class PadBridge {
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isFromController(event.getDevice())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
state.thumbLX = axis(event, MotionEvent.AXIS_X);
state.leftX = axis(event, MotionEvent.AXIS_X);
// Android's Y axis grows downwards and evdev's ABS_Y does too, so no flip here: what the
// pad reports as "down" is what the client is told.
state.thumbLY = axis(event, MotionEvent.AXIS_Y);
state.thumbRX = axis(event, MotionEvent.AXIS_Z);
state.thumbRY = axis(event, MotionEvent.AXIS_RZ);
state.leftY = axis(event, MotionEvent.AXIS_Y);
state.rightX = axis(event, MotionEvent.AXIS_Z);
state.rightY = axis(event, MotionEvent.AXIS_RZ);
float lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
float rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
// Some pads only report the triggers on BRAKE/GAS.
if (lt == 0f) lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
if (rt == 0f) rt = event.getAxisValue(MotionEvent.AXIS_GAS);
state.triggerL = lt;
state.triggerR = rt;
state.leftTrigger = lt;
state.rightTrigger = rt;
float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
state.dpad[0] = hatY < -0.5f;
@@ -151,7 +151,7 @@ public final class PadBridge {
* The on-screen controls' way in: they mutate the same state a physical pad writes, so the
* client only ever sees one device and a user can use both at once without them fighting.
*/
public synchronized void applyTouch(java.util.function.Consumer<GamepadState> mutation) {
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
mutation.accept(state);
publish();
}
@@ -203,13 +203,13 @@ public final class PadBridge {
if (!open && !start()) return;
if (systemGuidePressed || qamChordActive) {
effectiveState.copy(state);
effectiveState.setPressed(GamepadState.IDX_BUTTON_MODE, true);
effectiveState.setPressed(PadState.IDX_BUTTON_MODE, true);
if (qamSyntheticAPressed) {
effectiveState.setPressed(0, state.isPressed(0) || qamSyntheticAPressed);
}
writer.writeGamepadState(effectiveState);
writer.writePadState(effectiveState);
} else {
writer.writeGamepadState(state);
writer.writePad(state);
}
}
@@ -0,0 +1,61 @@
package com.steamdeck.launcher.input
/**
* What one Xbox-shaped pad is doing right now: two sticks and two triggers as -1..1 / 0..1, the
* four d-pad directions, and a bitmask of the buttons numbered the way the fake evdev node
* reports them. Written by whatever drives the pad (a physical controller, the on-screen one, or
* both at once) and read by [FakeInputWriter] into the guest's input ring.
*/
class PadState {
@JvmField var leftX = 0f
@JvmField var leftY = 0f
@JvmField var rightX = 0f
@JvmField var rightY = 0f
@JvmField var leftTrigger = 0f
@JvmField var rightTrigger = 0f
@JvmField var up = false
@JvmField var right = false
@JvmField var down = false
@JvmField var left = false
private var buttons = 0
fun press(button: Int, down: Boolean) {
buttons = if (down) buttons or (1 shl button) else buttons and (1 shl button).inv()
}
fun isDown(button: Int): Boolean = buttons and (1 shl button) != 0
/** The d-pad as a hat: -1 left, 1 right; -1 up, 1 down. Opposites cancel to 0. */
fun hatX(): Int = if (right && !left) 1 else if (left && !right) -1 else 0
fun hatY(): Int = if (down && !up) 1 else if (up && !down) -1 else 0
fun copyFrom(other: PadState) {
leftX = other.leftX; leftY = other.leftY; rightX = other.rightX; rightY = other.rightY
leftTrigger = other.leftTrigger; rightTrigger = other.rightTrigger
up = other.up; right = other.right; down = other.down; left = other.left
buttons = other.buttons
}
/** Everything released and centred. */
fun clear() {
leftX = 0f; leftY = 0f; rightX = 0f; rightY = 0f
leftTrigger = 0f; rightTrigger = 0f
up = false; right = false; down = false; left = false
buttons = 0
}
companion object {
const val A = 0
const val B = 1
const val X = 2
const val Y = 3
const val LB = 4
const val RB = 5
const val SELECT = 6
const val START = 7
const val L3 = 8
const val R3 = 9
/** The Steam/Guide button, which the fake evdev node reports as BTN_MODE. */
const val GUIDE = 12
}
}
@@ -7,7 +7,7 @@ import android.net.Network
import android.os.Build
import android.provider.Settings
import android.util.Log
import com.steamdeck.launcher.core.EnvironmentComponent
import com.steamdeck.launcher.core.SessionPart
import java.io.File
import java.io.IOException
import java.net.Inet4Address
@@ -28,7 +28,7 @@ import java.net.Inet6Address
class LinuxNetworkLinkComponent(
context: Context,
private val rootDir: File,
) : EnvironmentComponent() {
) : SessionPart() {
private val appContext = context.applicationContext
private val connectivity =
appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@@ -4,7 +4,7 @@ import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.util.Log
import com.steamdeck.launcher.core.EnvironmentComponent
import com.steamdeck.launcher.core.SessionPart
import java.io.File
import kotlin.math.abs
@@ -22,7 +22,7 @@ import kotlin.math.abs
* from |current| × voltage; time to empty from charge ÷ |average current| while discharging. Where
* a device reports no current, the client still gets status and percentage.
*/
class BatteryComponent(val dir: File) : EnvironmentComponent() {
class BatteryComponent(val dir: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
@@ -45,7 +45,7 @@ class BatteryComponent(val dir: File) : EnvironmentComponent() {
}
private fun write() {
val ctx = context ?: return
val ctx = app() ?: return
try {
val bm = ctx.getSystemService(BatteryManager::class.java)
val sticky: Intent? = ctx.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
@@ -0,0 +1,75 @@
package com.steamdeck.launcher.session
import android.net.LocalServerSocket
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.util.Log
import com.steamdeck.launcher.core.SessionPart
import java.io.DataInputStream
import kotlin.math.max
/**
* Rumble for the on-screen pad, on the phone itself.
*
* When a game plays a force-feedback effect on the fake pad, the fake evdev layer inside the guest
* connects to the abstract socket [NAME] and sends one packet: strong, weak, duration in ms and
* the pad slot, four little-endian 16-bit values. This listens for those and drives the device's
* vibrator with the stronger motor's strength for the effect's duration. Best effort both ways:
* a missing listener costs the guest nothing, and a bad packet is dropped.
*/
class RumbleComponent : SessionPart() {
@Volatile private var server: LocalServerSocket? = null
override fun start() {
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
server = s
Thread({
while (server === s) {
val client = try { s.accept() } catch (e: Exception) { break }
try {
val bytes = ByteArray(8)
DataInputStream(client.inputStream).readFully(bytes)
val strong = u16(bytes, 0); val weak = u16(bytes, 2); val ms = u16(bytes, 4)
buzz(max(strong, weak), ms)
} catch (e: Exception) {
// A partial packet or a closed peer: nothing to play.
} finally {
try { client.close() } catch (e: Exception) { /* already gone */ }
}
}
}, "rumble").apply { isDaemon = true; start() }
Log.i(TAG, "rumble: listening on @$NAME")
}
override fun stop() {
val s = server ?: return
server = null
try { s.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ }
}
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
private fun buzz(strength: Int, ms: Int) {
val ctx = app() ?: return
val vibrator: Vibrator = if (Build.VERSION.SDK_INT >= 31) ctx.getSystemService(VibratorManager::class.java)?.defaultVibrator ?: return
else @Suppress("DEPRECATION") (ctx.getSystemService(Vibrator::class.java) ?: return)
if (!vibrator.hasVibrator()) return
if (strength == 0 || ms == 0) { vibrator.cancel(); return }
val amplitude = (strength * 255L / 65535L).toInt().coerceIn(1, 255)
val duration = ms.toLong().coerceIn(1L, 5000L)
try {
if (vibrator.hasAmplitudeControl()) vibrator.vibrate(VibrationEffect.createOneShot(duration, amplitude))
else vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE))
} catch (e: Exception) {
Log.w(TAG, "rumble: $e")
}
}
companion object {
private const val TAG = "SessionService"
/** Must match the fake evdev layer (fakeinput_steam.cpp). */
const val NAME = "steamdeck-rumble"
}
}
@@ -23,12 +23,12 @@ import com.steamdeck.launcher.audio.DirectAudioRelayComponent
import com.steamdeck.launcher.audio.PulseAudioComponent
import com.steamdeck.launcher.core.CpuCores
import com.steamdeck.launcher.core.DeviceReport
import com.steamdeck.launcher.core.EnvVars
import com.steamdeck.launcher.core.HostEnvironment
import com.steamdeck.launcher.core.SessionLogCapture
import com.steamdeck.launcher.core.NetworkReport
import com.steamdeck.launcher.core.EnvironmentComponent
import com.steamdeck.launcher.core.SessionPart
import com.steamdeck.launcher.core.FileUtils
import com.steamdeck.launcher.core.ProcessHelper
import com.steamdeck.launcher.core.HostProcess
import com.steamdeck.launcher.input.FakeInputWriter
import com.steamdeck.launcher.runtime.LinuxNetworkLinkComponent
import com.steamdeck.launcher.runtime.LinuxRuntime
@@ -52,7 +52,7 @@ import java.util.Locale
* The activity comes and goes on top of this; see [com.steamdeck.launcher.wayland.CompositorHost].
*/
class SessionService : Service() {
private val components = ArrayList<EnvironmentComponent>()
private val components = ArrayList<SessionPart>()
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
private var sessionPid = -1
@@ -250,14 +250,14 @@ class SessionService : Service() {
val audioLog = File(sessionDir, "audio.log")
val pulse = PulseAudioComponent(this, micFifo?.absolutePath)
pulse.setLogFile(audioLog)
pulse.setContext(this)
pulse.attach(this)
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
components.add(pulse)
if (wantsDirectAudio || wantsMic) {
// After the daemon in the list, so it can wait for the pipe the daemon makes.
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
relay.setLogFile(audioLog)
relay.setContext(this)
relay.attach(this)
components.add(relay)
}
if (wantsDirectAudio) {
@@ -355,9 +355,12 @@ class SessionService : Service() {
// called "battery" and its files differ, so the client sees no battery at all. A directory
// of our own, written from Android's battery API every few seconds, is bound over it.
val battery = BatteryComponent(File(filesDir, "session/sys/power_supply"))
battery.setContext(this)
battery.attach(this)
components.add(battery)
binds.add(battery.dir.path + ":/sys/class/power_supply")
// Rumble for the on-screen pad: the fake evdev layer sends force-feedback effects to this
// listener, which drives the phone's vibrator (see RumbleComponent).
if (controllersOn) components.add(RumbleComponent().also { it.attach(this) })
// Where the device's files appear inside the session. Internal storage is bound at its own
// path already, and every program's file dialog opens at home and lists "Computer" from
// /proc/mounts, where a proot bind never shows - so a user saw only the runtime's own
@@ -396,26 +399,26 @@ class SessionService : Service() {
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)
val hostEnv = HostEnvironment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
hostEnv["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`.
// proot reads this itself, so it belongs in proot's own environment rather than the guest's.
if (SessionPrefs.prootNoSeccomp(this)) {
hostEnv.put("PROOT_NO_SECCOMP", "1")
hostEnv["PROOT_NO_SECCOMP"] = "1"
Log.i(TAG, "proot: seccomp acceleration off by request")
}
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv.put("LD_LIBRARY_PATH", prootLibs)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
// Whether the client signs in to Valve or starts offline: read once, while it starts, and
// rewritten by the client when it exits, so it is set again here at every session start.
if (SessionState.mode == MODE_STEAM) OfflineMode.apply(this, root)
val networkLink = LinuxNetworkLinkComponent(this, root)
networkLink.setContext(this)
networkLink.attach(this)
networkLink.publish()
components.add(networkLink)
components.forEach { it.start() }
@@ -426,10 +429,10 @@ class SessionService : Service() {
// by the teardown a second after the new one has started, and its exit used to arrive
// here as "session ended: 137" and end the NEW session. An exit belongs to the session
// that started it.
sessionPid = ProcessHelper.exec(line, hostEnv.toStringArray(), root, { status ->
sessionPid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@exec
return@start
}
Log.i(TAG, "session ended: $status")
stopSession(status ?: -1)
@@ -41,6 +41,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.steamdeck.launcher.R
/** Everything the main screen shows; the activity owns the values and the work behind them. */
class MainUiState(
val installed: String?,
val ready: Boolean,
@@ -52,13 +53,29 @@ class MainUiState(
val failed: Boolean,
val frameGenLabel: String,
val desktopInstalled: Boolean,
/** The account the client would sign in as offline, or null if it has never signed in. */
val offlineAccount: String?,
val offline: Boolean,
/** The folder every session shows at /root/ROMs, or null if none is chosen. */
val romsDir: String?,
val logsEnabled: Boolean,
/** Installed emulators that can run under gamescope: label to path inside the runtime. */
val emulators: List<Pair<String, String>> = emptyList(),
)
/**
* The whole app outside a session, in one column that is sized to the window it has.
*
* Panels and densities vary too much for fixed dp: a 7" 1080p handheld in landscape has barely
* 400dp of height, a foldable's inner screen has 900. So the column is designed at one size and
* scaled by the height available — everything on it, text included, shrinks together until it
* fits — with scrolling left as the last resort, and a width cap so the buttons never span a
* wide panel. The system bars are kept clear of.
*
* Play and Desktop span the column; everything else is a tile in two columns, a title with the
* setting's current value under it, so the menu is read at a glance and fits without scrolling
* on a handheld.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun MainScreen(
@@ -87,6 +104,7 @@ fun MainScreen(
.systemBarsPadding(),
contentAlignment = Alignment.Center,
) {
// The column as designed needs about this much height; below it, scale everything.
val designHeight = 480.dp
val k = (maxHeight / designHeight).coerceIn(0.55f, 1f)
val colors = MaterialTheme.colorScheme
@@ -106,6 +124,10 @@ fun MainScreen(
)
Spacer(Modifier.height(6.dp * k))
Text("SteamDeck", fontSize = 22.sp * k, color = colors.onBackground)
Text(
"Valve's native ARM64 Steam client, under gamescope",
fontSize = 12.sp * k, color = colors.onSurfaceVariant, textAlign = TextAlign.Center,
)
Spacer(Modifier.height(14.dp * k))
val status = when {
@@ -116,14 +138,14 @@ fun MainScreen(
Text(status, fontSize = 15.sp * k, color = colors.onBackground)
val detail = when {
state.busy -> if (state.percent >= 0) "${state.stage} ${state.percent}%" else state.stage
state.failed -> "Install failed. Nothing changed."
state.failed -> "Install failed — nothing was changed"
!state.ready -> state.available?.let { "$it · ${state.availableSize} download, one time" }
?: "Could not reach the runtime catalog"
state.available != null && state.available != state.installed ->
"Runtime ${state.installed ?: "?"} installed · ${state.available} available"
else -> null
else -> "Runtime ${state.installed ?: "?"} installed"
}
if (detail != null) Text(
Text(
detail, fontSize = 12.sp * k, color = colors.onSurfaceVariant, textAlign = TextAlign.Center,
modifier = Modifier.padding(top = 3.dp * k),
)
@@ -138,6 +160,7 @@ fun MainScreen(
Spacer(Modifier.height(14.dp * k))
val buttonHeight = 40.dp * k
// Each launch button has its own cog: what only matters for that mode lives there.
Row(horizontalArrangement = Arrangement.spacedBy(6.dp * k), modifier = Modifier.fillMaxWidth()) {
Button(
onClick = onPlay, enabled = state.ready && !state.busy,
@@ -149,9 +172,11 @@ fun MainScreen(
OutlinedButton(
onClick = onDesktop, enabled = state.ready && !state.busy && state.desktopInstalled,
modifier = Modifier.weight(1f).height(buttonHeight),
) { Text("Desktop", fontSize = 13.sp * k, maxLines = 1, overflow = TextOverflow.Ellipsis) }
) { Text(if (state.desktopInstalled) "Desktop" else "Desktop — install it under Desktop & apps", fontSize = 13.sp * k, maxLines = 1, overflow = TextOverflow.Ellipsis) }
CogButton(k, onDesktopSettings)
}
// The ROMs folder, then every installed emulator as a session of its own under
// gamescope (where the GPU is); the ? says why they are here and not on the desktop.
FlowRow(
horizontalArrangement = Arrangement.spacedBy(4.dp * k),
verticalArrangement = Arrangement.spacedBy(4.dp * k),
@@ -172,7 +197,7 @@ fun MainScreen(
onClick = { onLaunchEmulator(path) }, enabled = state.ready && !state.busy,
contentPadding = PaddingValues(horizontal = 10.dp * k, vertical = 0.dp),
modifier = Modifier.height(30.dp * k),
) { Text(label, fontSize = 11.sp * k, maxLines = 1) }
) { Text("▶ $label", fontSize = 11.sp * k, maxLines = 1) }
}
OutlinedButton(
onClick = onEmulatorHelp,
@@ -180,13 +205,15 @@ fun MainScreen(
modifier = Modifier.width(30.dp * k).height(30.dp * k),
) { Text("?", fontSize = 12.sp * k) }
}
// Offline is read while the client starts, so it is decided here rather than in the
// session's drawer, and it needs credentials from an earlier sign-in to be possible.
OutlinedButton(
onClick = onOffline, enabled = state.offlineAccount != null,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight),
) {
Text(
when {
state.offlineAccount == null -> "Start offline"
state.offlineAccount == null -> "Start offline — sign in once first"
state.offline -> "Start offline: on · ${state.offlineAccount}"
else -> "Start offline: off"
},
@@ -233,6 +260,7 @@ fun MainScreen(
}
}
/** The cog beside a launch button. */
@Composable
private fun CogButton(k: Float, onClick: () -> Unit) {
OutlinedButton(
@@ -242,6 +270,7 @@ private fun CogButton(k: Float, onClick: () -> Unit) {
) { Icon(Icons.Filled.Settings, contentDescription = "Settings", modifier = Modifier.size(18.dp * k)) }
}
/** One tile of the two-column menu: what it is, and under it what it is set to. */
@Composable
private fun MenuTile(
title: String,
@@ -268,12 +297,40 @@ private fun MenuTile(
}
}
/** The ? beside the emulator row: what the ▶ buttons are, how to use them, and why. */
@Composable
fun EmulatorHelpDialog(onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Emulators") },
text = { Text("Place games in the ROMs folder. In RPCS3, install firmware from File > Install Firmware.") },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Text("What the ▶ buttons are", style = MaterialTheme.typography.titleSmall)
Text(
"One per emulator installed under Desktop & apps. Each starts that emulator fullscreen, as a " +
"session of its own under gamescope — the same way the Steam client runs — with the Steam " +
"cog's display, driver and HDR settings.",
style = MaterialTheme.typography.bodySmall,
)
Spacer(Modifier.height(8.dp))
Text("How to use them", style = MaterialTheme.typography.titleSmall)
Text(
"Put your games in the folder the ROMs chip beside these buttons points at. In the emulator, open root › ROMs " +
"(/root/ROMs); the whole phone is at root › Storage. Firmware and BIOS files go in the " +
"same way (RPCS3: File › Install Firmware). Back opens the drawer; Stop session ends it.",
style = MaterialTheme.typography.bodySmall,
)
Spacer(Modifier.height(8.dp))
Text("Why not from the desktop", style = MaterialTheme.typography.titleSmall)
Text(
"The desktop draws in software (labwc on pixman) and cannot hand a program the GPU: a Vulkan " +
"emulator started there dies at its first frame (\"Surface lost\"). gamescope can, so an " +
"emulator that renders with Vulkan or OpenGL belongs here. The desktop stays for files, " +
"Firefox and anything that draws in software.",
style = MaterialTheme.typography.bodySmall,
)
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } },
)
}
@@ -296,11 +353,10 @@ fun CreditsDialog(onDismiss: () -> Unit) {
title = { Text("Credits") },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Text("The412Banner - the app, the Wayland compositor, the runtime and the Steam session.", style = MaterialTheme.typography.bodyMedium)
Text("The412Banner — the app, the Wayland compositor, the runtime and the Steam session.", style = MaterialTheme.typography.bodyMedium)
Spacer(Modifier.height(10.dp))
Text("maxjivi05 (Max) - the gamescope runtime this is built on: the proot session, the session shim, the fake-evdev interposer and the controller work, from WinNative.", style = MaterialTheme.typography.bodyMedium)
Text("maxjivi05 (Max) — the gamescope runtime this is built on: the proot session, the session shim, the fake-evdev interposer and the controller work, from WinNative.", style = MaterialTheme.typography.bodyMedium)
Spacer(Modifier.height(10.dp))
Text("Winlator (brunodev85) - the audio stack, the gamepad model and the shape of a session's host-side components; WinNative and Bannerlator are both Winlator lineage.", style = MaterialTheme.typography.bodyMedium)
Spacer(Modifier.height(10.dp))
Text(
"GPL-3.0. Valve, Steam, Steam Deck and Proton are trademarks of Valve Corporation; this project is not affiliated with Valve. gamescope, Mesa, Turnip, Xwayland, PulseAudio, proot and Arch Linux ARM are their authors' own.",