Fix runtime removal and first-run Steam setup (#185)

* Fix runtime removal races and show removal progress

* Bootstrap Steam from the selected client channel

* Show runtime progress below its Setup row

* Always stage current session helpers and verify APK assets

* Initialize Steam UI scale once using the handheld default
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-03 22:03:26 -04:00
1 parent f5e204eb1d
commit db2e1d7da2
27 files changed
+978 -90

No files matched your search

@@ -88,6 +88,7 @@ public final class LinuxRuntime {
/** The rootfs is present with gamescope and the session script the launcher hands control to. */
public static boolean isInstalled(Context context) {
if (LinuxRuntimeInstaller.isRemoving() || LinuxRuntimeInstaller.hasRemovalPending(context)) return false;
File root = rootDir(context);
return new File(root, "usr/bin/gamescope").isFile()
&& new File(root, SESSION_SCRIPT.substring(1)).isFile()
@@ -64,7 +64,7 @@ public final class LinuxRuntimeInstaller {
}
/**
* One install per process. The launcher and the session screen can both start one, and a
* One runtime operation per process. The launcher and session can both install, and a
* launcher rebuilt mid-install (a pad plugged in, dark mode switched) forgets it had: a second
* install would share the first one's archive and staging directory and wreck both.
*/
@@ -74,11 +74,13 @@ public final class LinuxRuntimeInstaller {
volatile String stage = "Starting\u2026";
volatile int percent = -1;
volatile boolean ok;
final boolean removal;
Job(boolean removal) { this.removal = removal; }
}
private static final Object JOB_LOCK = new Object();
private static Job running;
private static boolean removing;
private static volatile String removalError;
private LinuxRuntimeInstaller() {}
@@ -127,9 +129,9 @@ public final class LinuxRuntimeInstaller {
Job job;
boolean owner;
synchronized (JOB_LOCK) {
if (removing) return false;
if (running != null && running.removal) return false;
owner = running == null;
if (owner) running = new Job();
if (owner) { running = new Job(false); removalError = null; }
job = running;
if (listener != null) job.listeners.add(listener);
}
@@ -152,13 +154,31 @@ public final class LinuxRuntimeInstaller {
/** True while an install is running in this process, whoever started it. */
public static boolean isInstalling() {
synchronized (JOB_LOCK) {
return running != null;
return running != null && !running.removal;
}
}
public static boolean isBusy() {
synchronized (JOB_LOCK) { return running != null; }
}
public static boolean isRemoving() {
synchronized (JOB_LOCK) { return running != null && running.removal; }
}
public static String removalError() { return removalError; }
public static boolean hasRemovalPending(Context context) {
return removalDirectory(LinuxRuntime.rootDir(context)).exists();
}
private static File removalDirectory(File root) {
return new File(root.getParentFile(), root.getName() + ".removing");
}
/**
* Follows the install already running, for a screen that was rebuilt mid-install. Blocks until
* it ends and returns its result, or returns null at once when nothing is installing.
* Follows the runtime operation already running, including removal, after a screen rebuild.
* Blocks until it ends and returns its result, or null when there is no current operation.
*/
public static Boolean attach(ProgressListener listener) {
Job job;
@@ -186,6 +206,11 @@ public final class LinuxRuntimeInstaller {
private static boolean installOnce(Context context, Release release, ProgressListener listener) {
File archive = new File(context.getCacheDir(), "linuxfs.tar.zst");
try {
// A failed/interrupted explicit removal must finish before a fresh installation.
// Its quarantined home is not user data to carry into an update.
File pendingRemoval = removalDirectory(LinuxRuntime.rootDir(context));
if (pendingRemoval.exists() && listener != null) listener.onProgress("Removing runtime leftovers", -1);
RuntimeFileTree.delete(pendingRemoval, null);
if (listener != null) listener.onProgress("Downloading", 0);
// Downloader reports a 0..1 fraction, or -1 while the total size is unknown.
boolean ok = Downloader.downloadFile(release.url, archive, true, (fraction) -> {
@@ -212,18 +237,18 @@ public final class LinuxRuntimeInstaller {
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
recoverInterruptedSwap(root, staging, old);
FileUtils.delete(staging);
RuntimeFileTree.delete(staging, null);
if (!staging.mkdirs()) return false;
if (listener != null) listener.onProgress("Extracting", -1);
if (!extract(archive, staging, listener)) {
FileUtils.delete(staging);
RuntimeFileTree.delete(staging, null);
return false;
}
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
FileUtils.delete(old);
RuntimeFileTree.delete(old, null);
if (root.isDirectory() && !root.renameTo(old)) {
FileUtils.delete(staging);
RuntimeFileTree.delete(staging, null);
return false;
}
@@ -232,16 +257,15 @@ public final class LinuxRuntimeInstaller {
// own empty /root is dropped first so the rename has somewhere to land. If this fails
// the update is abandoned and the previous runtime is put back untouched - shipping a
// working system with the user's games gone is the worse outcome.
File keptFrom = new File(old, USER_DATA);
if (keptFrom.isDirectory()) {
File keptTo = new File(staging, USER_DATA);
FileUtils.delete(keptTo);
if (!keptFrom.renameTo(keptTo)) {
Log.w(TAG, "could not carry " + USER_DATA + " across the update; rolling back");
FileUtils.delete(staging);
old.renameTo(root);
return false;
}
try {
RuntimeFileTree.carryHome(old, staging);
} catch (IOException e) {
Log.w(TAG, "could not carry root across the update; rolling back", e);
// Restore the live name even if cleaning the failed staging tree is denied.
old.renameTo(root);
try { RuntimeFileTree.delete(staging, null); }
catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); }
return false;
}
if (!staging.renameTo(root)) {
@@ -250,7 +274,7 @@ public final class LinuxRuntimeInstaller {
if (old.isDirectory()) old.renameTo(root);
return false;
}
FileUtils.delete(old);
RuntimeFileTree.delete(old, null);
return LinuxRuntime.isInstalled(context);
} catch (Exception e) {
Log.e(TAG, "install", e);
@@ -260,13 +284,13 @@ public final class LinuxRuntimeInstaller {
}
}
private static void recoverInterruptedSwap(File root, File staging, File old) {
static void recoverInterruptedSwap(File root, File staging, File old) throws IOException {
File target = root.isDirectory() ? root : old;
File stagedHome = new File(staging, USER_DATA);
File home = new File(target, USER_DATA);
if (target.isDirectory() && stagedHome.isDirectory() && (!home.exists() || isEmptyDir(home))) {
FileUtils.delete(home);
if (stagedHome.renameTo(home)) Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update");
RuntimeFileTree.carryHome(staging, target);
Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update");
}
if (!root.isDirectory() && old.isDirectory() && old.renameTo(root)) {
Log.w(TAG, "restored the previous runtime after an interrupted update");
@@ -278,20 +302,76 @@ public final class LinuxRuntimeInstaller {
return dir.isDirectory() && names != null && names.length == 0;
}
/** Removes the runtime; returns false without touching it while an install is running. */
public static boolean uninstall(Context context) {
/** Reserve removal before returning to the UI, so Play cannot race the worker. */
public static Removal beginUninstall(Context context) {
if (com.droiddeck.launcher.session.SessionState.INSTANCE.getRunning()) return null;
com.droiddeck.launcher.session.SessionPhase phase = com.droiddeck.launcher.session.SessionState.INSTANCE.getPhase();
if (phase != com.droiddeck.launcher.session.SessionPhase.IDLE && phase != com.droiddeck.launcher.session.SessionPhase.FAILED) return null;
return beginUninstall(LinuxRuntime.rootDir(context));
}
static Removal beginUninstall(File root) {
synchronized (JOB_LOCK) {
if (running != null || removing) return false;
removing = true;
if (running != null) return null;
removalError = null;
running = new Job(true);
running.stage = "Removing Linux runtime";
return new Removal(root, running);
}
try {
FileUtils.delete(LinuxRuntime.rootDir(context));
return true;
} finally {
synchronized (JOB_LOCK) {
removing = false;
}
public static final class Removal {
private final File root;
private final Job job;
private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean();
private Removal(File root, Job job) { this.root = root; this.job = job; }
public boolean run(ProgressListener listener) {
if (!started.compareAndSet(false, true)) return join(job, listener);
if (listener != null) job.listeners.add(listener);
try {
report("Removing Linux runtime", -1);
final long[] removed = {0};
final long[] lastShown = {0};
java.util.function.LongConsumer progress = ignored -> {
removed[0]++;
long now = System.nanoTime();
if (removed[0] == 1 || now - lastShown[0] >= 200_000_000L) {
lastShown[0] = now;
report("Removing Linux runtime · " + removed[0] + " entries", -1);
}
};
File pending = removalDirectory(root);
// Invalidate the installation before traversing it. A process killed halfway
// through leaves a named removal to resume, never a launchable partial runtime.
if (root.exists()) {
RuntimeFileTree.delete(pending, progress);
if (!root.renameTo(pending)) throw new IOException("Cannot prepare the runtime for removal");
} else if (!pending.isDirectory() && !pending.mkdirs()) {
throw new IOException("Cannot prepare the runtime for removal");
}
// Keep the quarantine until all leftovers are gone, so a failure stays retryable.
RuntimeFileTree.delete(new File(root.getParentFile(), root.getName() + ".new"), progress);
RuntimeFileTree.delete(new File(root.getParentFile(), root.getName() + ".old"), progress);
RuntimeFileTree.delete(pending, progress);
job.ok = true;
report("Linux runtime removed", 100);
return true;
} catch (IOException e) {
removalError = "Could not finish removing the Linux runtime. Retry removal in Setup.";
Log.w(TAG, "runtime removal incomplete", e);
report(removalError, -1);
return false;
} finally {
synchronized (JOB_LOCK) { running = null; }
job.done.countDown();
}
}
private void report(String stage, int percent) {
job.stage = stage;
job.percent = percent;
for (ProgressListener listener : job.listeners) listener.onProgress(stage, percent);
}
}
/**
@@ -0,0 +1,51 @@
package com.droiddeck.launcher.runtime;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.function.LongConsumer;
/** Checked removal of an app-owned runtime tree, including read-only directories. */
final class RuntimeFileTree {
private RuntimeFileTree() {}
static void delete(File root, LongConsumer progress) throws IOException {
delete(root.toPath(), progress, new long[]{0});
}
private static void delete(Path path, LongConsumer progress, long[] removed) throws IOException {
BasicFileAttributes attrs;
try { attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); }
catch (NoSuchFileException e) { return; }
if (attrs.isDirectory()) {
// Change directory permissions before opening it, so mode 000 also works. Links
// are inspected with lstat and unlinked directly; never chmod or visit their target.
makeWritable(path.toFile());
try (DirectoryStream<Path> children = Files.newDirectoryStream(path)) {
for (Path child : children) delete(child, progress, removed);
}
}
Files.delete(path);
if (progress != null) progress.accept(++removed[0]);
}
private static void makeWritable(File dir) throws IOException {
if (!dir.setReadable(true, true) || !dir.setWritable(true, true) || !dir.setExecutable(true, true))
throw new IOException("Cannot make directory removable: " + dir);
}
static void carryHome(File old, File staging) throws IOException {
File home = new File(old, "root");
if (!home.isDirectory()) return;
makeWritable(old);
makeWritable(staging);
File target = new File(staging, "root");
delete(target, null);
if (!home.renameTo(target)) throw new IOException("Cannot carry root across the update");
}
}
@@ -25,22 +25,25 @@ class RuntimeInstallService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val removal = intent?.action == ACTION_REMOVE
val release = intent?.let(::releaseFrom)
startForeground(NOTIFICATION_ID, notification("Starting…", -1))
if (release == null) {
startForeground(NOTIFICATION_ID, notification(if (removal) "Removing Linux runtime" else "Starting…", -1))
if (release == null && !removal) {
stopSelf(startId)
return START_NOT_STICKY
}
Thread({
val manager = getSystemService(NotificationManager::class.java)
var shown = Int.MIN_VALUE
LinuxRuntimeInstaller.install(applicationContext, release) { stage, percent ->
// Every percent at most once: a notification per read would flood the system.
if (percent != shown) {
shown = percent
var shown = ""
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
// Install percentages and throttled removal counts, including stage transitions.
if ("$stage:$percent" != shown) {
shown = "$stage:$percent"
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
}
}
if (removal) LinuxRuntimeInstaller.attach(progress)
else LinuxRuntimeInstaller.install(applicationContext, release!!, progress)
@Suppress("DEPRECATION")
stopForeground(true)
stopSelf(startId)
@@ -50,9 +53,9 @@ class RuntimeInstallService : Service() {
private fun notification(stage: String, percent: Int): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Runtime install",
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Linux runtime",
NotificationManager.IMPORTANCE_LOW).apply {
description = "Shows while the Linux runtime downloads and installs"
description = "Shows while the Linux runtime is installed or removed"
setShowBadge(false)
setSound(null, null)
enableVibration(false)
@@ -62,7 +65,7 @@ class RuntimeInstallService : Service() {
PendingIntent.FLAG_IMMUTABLE)
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle("Installing the Linux runtime")
.setContentTitle(if (LinuxRuntimeInstaller.isRemoving()) "Removing the Linux runtime" else "Installing the Linux runtime")
.setContentText(stage)
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
.setContentIntent(open)
@@ -75,6 +78,7 @@ class RuntimeInstallService : Service() {
companion object {
private const val CHANNEL_ID = "runtime-install"
private const val NOTIFICATION_ID = 2
private const val ACTION_REMOVE = "com.droiddeck.launcher.REMOVE_RUNTIME"
private const val EXTRA_VERSION = "version"
private const val EXTRA_URL = "url"
private const val EXTRA_SHA256 = "sha256"
@@ -90,6 +94,11 @@ class RuntimeInstallService : Service() {
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
}
fun keepRemovalAlive(context: Context) {
val intent = Intent(context, RuntimeInstallService::class.java).setAction(ACTION_REMOVE)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
}
private fun releaseFrom(intent: Intent): LinuxRuntimeInstaller.Release? {
val version = intent.getStringExtra(EXTRA_VERSION) ?: return null
val url = intent.getStringExtra(EXTRA_URL) ?: return null