Rename the app SteamDeck → DroidDeck

App name, app ID and code package: DroidDeck, com.droiddeck.launcher
(sources moved to com/droiddeck/launcher, the 68 JNI functions renamed
with them). The new app ID installs beside SteamDeck rather than over it.

Everywhere the name was the app's own: the sidebar title, the session
report, share zips, the shell title, wake-lock and log tags, User-Agents,
the Compose theme, the Download folder and switch files (droiddeck-env,
-osc, -driver, -tu-debug, -no-pad, -pad-log, -no-hud, -wlr-renderer; the
old names are not read), and inside the runtime (droiddeck-desktop,
Firefox's droiddeck.js, the shortcuts tag, the rumble socket, debug and
cache paths). Build scripts, CI artifact (droiddeck-apk), CMake project,
README and the progress log follow.

Kept on purpose: Valve's Steam Deck (the -steamdeck flag,
steamdeck_publicbeta/stable, 'Steam Deck mode', the steamos.cloud
package URLs) and names inside the hosted desktop package (steamdeck.png,
steamdeck-steam, steamdeck-bigpicture). 'Desktop installed' now tests for
labwc instead of the launcher the app stages itself. A committed
__pycache__ .pyc is removed.
This commit is contained in:
The412Banner committed 2026-09-23 18:28:04 -04:00
1 parent bd51571530
commit ae6dcc9798
118 files changed
+498 -487

No files matched your search

@@ -0,0 +1,128 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.wayland.WaylandCompositor
/**
* The frame-generation setting and how it reaches the compositor.
*
* Both engines generate on gamescope's final output inside our compositor, so they work for any
* game with nothing changed in the runtime. Win-FG is our own and needs nothing; LSFG needs the
* shader chain from the user's copy of Lossless Scaling (see [LsfgNative]). Every compositor
* setter is a value store on the native side, so this can be applied before the compositor is
* up and changed live from the main screen while a session runs.
*/
object FrameGen {
const val ENGINE_OFF = "off"
const val ENGINE_WINFG = "winfg"
const val ENGINE_LSFG = "lsfg"
/** Win-FG's Performance preset, pinned: changing it live rebuilds the whole chain. */
private const val WINFG_PERF_PRESET = 2
/** Bidirectional flow with the occlusion gate - the chain's own default. */
private const val WINFG_MODEL = 4
/** Optical-flow resolution as a fraction of the output; Bannerlator's per-engine defaults. */
private const val FLOW_SCALE_WINFG = 0.60f
private const val FLOW_SCALE_LSFG = 0.80f
private const val PREFS = "frame_gen"
fun engine(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("engine", ENGINE_OFF) ?: ENGINE_OFF
fun multiplier(context: Context): Int =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getInt("multiplier", 2).coerceIn(2, 4)
fun set(context: Context, engine: String, multiplier: Int) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString("engine", engine).putInt("multiplier", multiplier).apply()
}
/** "Off", "Win-FG 2×", "LSFG 3×" - for the main screen. */
fun label(context: Context): String = when (engine(context)) {
ENGINE_WINFG -> "Win-FG ${multiplier(context)}×"
ENGINE_LSFG -> "LSFG ${multiplier(context)}×"
else -> "Off"
}
/**
* Pushes the saved setting into the compositor. Returns a message for the user when the
* engine cannot run (LSFG without Lossless Scaling), or null.
*/
fun apply(context: Context, refreshHz: Float): String? {
val engine = engine(context)
val multiplier = multiplier(context)
var problem: String? = null
when (engine) {
ENGINE_LSFG -> {
val status = LsfgNative.ensureCache(context)
if (status != LsfgNative.STATUS_OK) {
problem = if (status == LsfgNative.STATUS_NOT_INSTALLED)
"LSFG needs Lossless Scaling installed from the Steam client"
else "LSFG: " + LsfgNative.statusName(status)
Log.w(TAG, problem)
WaylandCompositor.nativeSetFrameGenArmed(false, 0)
return problem
}
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG)
WaylandCompositor.nativeSetLsfgCachePath(LsfgNative.cacheFile(context).absolutePath)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, multiplier)
}
ENGINE_WINFG -> {
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_WINFG)
WaylandCompositor.nativeSetWinFgTuning(WINFG_MODEL, WINFG_PERF_PRESET)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_WINFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, multiplier)
}
else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0)
}
Log.i(TAG, "frame generation: $engine x$multiplier at ${refreshHz}Hz")
return problem
}
/**
* Off, or an engine at 2x/3x/4x; saved on pick, then [onChanged]. The LSFG rows are greyed
* and unpickable until Lossless Scaling is installed in the Steam client - the engine cannot
* run without its DLL, so offering it would only produce a setting that silently does nothing.
*/
fun showPicker(activity: android.app.Activity, onChanged: () -> Unit) {
val lsfgReady = LsfgNative.isInstalled(activity)
val lsfgNote = if (lsfgReady) "" else " - install Lossless Scaling in Steam"
val choices = listOf("Off",
"Win-FG 2×", "Win-FG 3×", "Win-FG 4×",
"LSFG 2×$lsfgNote", "LSFG 3×$lsfgNote", "LSFG 4×$lsfgNote")
val current = when (engine(activity)) {
ENGINE_WINFG -> multiplier(activity) - 1
ENGINE_LSFG -> if (lsfgReady) multiplier(activity) + 2 else 0
else -> 0
}
val adapter = object : android.widget.ArrayAdapter<String>(
activity, android.R.layout.simple_list_item_single_choice, choices) {
override fun isEnabled(position: Int) = lsfgReady || position < 4
override fun areAllItemsEnabled() = lsfgReady
override fun getView(position: Int, convertView: android.view.View?, parent: android.view.ViewGroup): android.view.View {
val view = super.getView(position, convertView, parent)
view.isEnabled = isEnabled(position)
view.alpha = if (isEnabled(position)) 1f else 0.38f
return view
}
}
android.app.AlertDialog.Builder(activity)
.setTitle(com.droiddeck.launcher.R.string.frame_gen_title)
.setSingleChoiceItems(adapter, current) { dialog, which ->
when (which) {
0 -> set(activity, ENGINE_OFF, 2)
in 1..3 -> set(activity, ENGINE_WINFG, which + 1)
else -> set(activity, ENGINE_LSFG, which - 2)
}
dialog.dismiss()
onChanged()
}
.setNeutralButton(android.R.string.ok, null)
.show()
}
private const val TAG = "FrameGen"
}
@@ -0,0 +1,76 @@
package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* The Vulkan driver a session draws with inside the runtime: in Steam mode the native client's
* own UI (OpenGL through the runtime's Zink), every game it launches (D3D through Proton's
* DXVK/VKD3D) and gamescope's compositing; in desktop mode every program on the desktop. One
* choice per mode covers all of it.
*
* <p>Distinct from the Android driver the app's compositor loads to put the finished frame on the
* screen ({@link TurnipDriver}), which every session ends in - and NOT interchangeable with it:
* these are glibc processes, that one is bionic.
*
* <p>"" (the default) means the driver the runtime was built with, at
* {@code usr/lib/libvulkan_freedreno.so} inside it - nothing is set and nothing is touched.
* Otherwise the value is an imported driver's id ({@link LinuxVulkanDriverManager}), and the
* session is handed that driver's ICD manifest in {@code BL_VK_DRIVER}: the session script points
* the Vulkan loader at it with {@code VK_DRIVER_FILES} after checking both the manifest and the
* library are readable from inside, so the runtime itself is never modified and the choice is
* reversible. Ported from Bannerlator's {@code LinuxVulkanDriver} (GPL-3.0); the choice lives in
* {@code SessionPrefs} per mode here rather than on a shortcut.
*/
public final class LinuxVulkanDriver {
private static final String TAG = "LinuxVulkanDriver";
/** Env var the session reads; its value is an absolute ICD manifest path. */
public static final String ENV = "BL_VK_DRIVER";
public static final String HELP_TEXT =
"The driver the Steam client, the games it launches and the desktop's programs render on, "
+ "inside the Linux runtime. Imported \"-Linux\" Turnip zips only: these are Linux processes "
+ "and cannot load an Android or Wayland driver. Frames still reach the screen through the "
+ "display driver below. Takes effect at the next session start.";
private LinuxVulkanDriver() {}
/** Stored values in editor order: the runtime's own driver, then each imported one. */
public static List<String> optionValues(Context context) {
ArrayList<String> values = new ArrayList<>();
values.add("");
values.addAll(new LinuxVulkanDriverManager(context).enumerateInstalledDrivers());
return values;
}
/**
* Label for a stored value. An id that is no longer installed says so - the launch path falls
* back to the runtime's own driver for it.
*/
public static String optionLabel(Context context, String value) {
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
String ver = m.getDriverVersion(value);
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
}
/**
* The ICD manifest path to hand the session, or null to leave the runtime's own driver alone.
* An id whose import is gone resolves to null rather than failing the launch.
*/
public static String resolveIcdPath(Context context, String value) {
if (value == null || value.isEmpty()) return null;
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
String icd = m.getIcdPath(value);
if (icd == null) {
Log.w(TAG, "imported Linux driver \"" + value + "\" is gone; using the runtime's own driver");
return null;
}
Log.i(TAG, "Linux session draws with imported driver " + value + " (" + icd + ")");
return icd;
}
}
@@ -0,0 +1,288 @@
package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.droiddeck.launcher.core.FileUtils;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Imported LINUX Vulkan drivers: glibc Turnip ICDs ({@code Turnip-<tag>[-variant]-Linux.zip} from
* Banners-Turnip) for the runtime - the gamescope session that runs Valve's native ARM64 Steam
* client, and the labwc desktop beside it. This is the driver that DRAWS there: the client's own UI
* (OpenGL through the runtime's Zink), every game the client launches (D3D through Proton's
* DXVK/VKD3D) and everything on the desktop. Putting the frame on the screen stays the Android
* driver's job, in the app's compositor ({@link TurnipDriver}).
*
* <p>Not interchangeable with that one: the client and its games are glibc processes and cannot
* load a bionic object at all, and this one cannot be loaded by the app. The check that separates
* them is the libc the driver links against - {@code libc.so.6} here, {@code libc.so} there.
*
* <p>Layout (under the app's files dir, which the session sees by its full host path):
* <pre>
* files/linux_vulkan_drivers/&lt;id&gt;/
* libvulkan_freedreno.so the driver
* icd.json generated Vulkan ICD manifest; library_path = the .so's ABSOLUTE path
* meta.json name / driverVersion / minGlibc, our own schema
* </pre>
* The session gets {@code icd.json}'s path in {@code BL_VK_DRIVER} and exports it as
* {@code VK_DRIVER_FILES}, so nothing inside the runtime is modified and the choice is reversible.
*
* <p>Ported from Bannerlator's {@code LinuxVulkanDriverManager} (GPL-3.0), unchanged in behaviour.
*/
public class LinuxVulkanDriverManager {
private static final String TAG = "LinuxVulkanDriver";
public static final String DIR_NAME = "linux_vulkan_drivers";
public static final String LIB_NAME = "libvulkan_freedreno.so";
public static final String ICD_NAME = "icd.json";
public static final String META_NAME = "meta.json";
private final Context context;
private final File rootDir;
public LinuxVulkanDriverManager(Context context) {
this.context = context;
this.rootDir = new File(context.getFilesDir(), DIR_NAME);
if (!rootDir.exists()) rootDir.mkdirs();
}
public File getDriverDir(String id) {
return new File(rootDir, id);
}
/** Installed = has the .so AND the generated manifest (a half-extracted dir is never offered). */
public boolean isInstalled(String id) {
if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return false;
File dir = getDriverDir(id);
return new File(dir, LIB_NAME).isFile() && new File(dir, ICD_NAME).isFile();
}
/** Absolute path of the driver's ICD manifest, or null when the id isn't installed. */
public String getIcdPath(String id) {
return isInstalled(id) ? new File(getDriverDir(id), ICD_NAME).getAbsolutePath() : null;
}
public List<String> enumerateInstalledDrivers() {
ArrayList<String> ids = new ArrayList<>();
File[] dirs = rootDir.listFiles();
if (dirs == null) return ids;
for (File d : dirs) if (d.isDirectory() && isInstalled(d.getName())) ids.add(d.getName());
Collections.sort(ids);
return ids;
}
private JSONObject readMeta(String id) {
try {
File meta = new File(getDriverDir(id), META_NAME);
if (!meta.isFile()) return null;
return new JSONObject(FileUtils.readString(meta));
} catch (Exception e) {
return null;
}
}
public String getDriverName(String id) {
JSONObject m = readMeta(id);
String name = m != null ? m.optString("name", "") : "";
return name.isEmpty() ? id : name;
}
public String getDriverVersion(String id) {
JSONObject m = readMeta(id);
return m != null ? m.optString("driverVersion", "") : "";
}
/** The glibc the driver asks for, as its zip recorded it ("" when the zip did not say). */
public String getMinGlibc(String id) {
JSONObject m = readMeta(id);
return m != null ? m.optString("minGlibc", "") : "";
}
public void removeDriver(String id) {
if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return;
Log.d(TAG, "removing imported Linux Vulkan driver " + id);
FileUtils.delete(getDriverDir(id));
// A mode still set to this id falls back to the runtime's own driver at launch (logged there).
}
/**
* Import a {@code -Linux.zip}. Returns the new driver id.
* @throws IllegalArgumentException with a user-facing reason when the zip is not an importable
* Linux driver; {@link IOException} on read/extract failures.
*/
public String installDriver(Uri zipUri, String displayName) throws IOException {
File tmpDir = new File(rootDir, ".tmp-" + System.currentTimeMillis());
FileUtils.delete(tmpDir);
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
boolean keep = false;
try {
String soName = null;
JSONObject zipMeta = null;
try (InputStream is = context.getContentResolver().openInputStream(zipUri);
ZipInputStream zis = new ZipInputStream(is)) {
if (is == null) throw new IOException("cannot open " + zipUri);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) continue;
// Flatten: only the base name matters, and it also defeats zip-slip paths.
String base = new File(entry.getName()).getName();
if (base.isEmpty()) continue;
if (base.startsWith("libvulkan_freedreno") && base.endsWith(".so")) {
if (soName != null) Log.w(TAG, "zip has several libvulkan_freedreno*.so; using the first (" + soName + ")");
else {
Files.copy(zis, new File(tmpDir, LIB_NAME).toPath(), StandardCopyOption.REPLACE_EXISTING);
soName = base;
}
} else if (base.equals(META_NAME)) {
try {
zipMeta = new JSONObject(new String(readAll(zis), StandardCharsets.UTF_8));
} catch (Exception e) {
Log.w(TAG, "meta.json unreadable, ignoring: " + e.getMessage());
}
}
// The zip's own freedreno_icd.aarch64.json is dropped on purpose: its
// library_path is relative to itself, and we write an absolute one below.
}
}
if (soName == null) {
throw new IllegalArgumentException("No libvulkan_freedreno*.so in this zip. An Android "
+ "(AdrenoTools) or -Wayland Turnip zip is not a Linux runtime driver.");
}
File so = new File(tmpDir, LIB_NAME);
if (!isAarch64Elf(so)) {
throw new IllegalArgumentException(soName + " is not a 64-bit AArch64 ELF shared library.");
}
// The one check that actually separates this from the bionic builds. Both sonames
// are in the driver's .dynstr, so a byte scan is enough and needs no ELF parsing:
// glibc's is versioned ("libc.so.6"), bionic's is not ("libc.so").
if (!containsAscii(so, "libc.so.6")) {
throw new IllegalArgumentException(soName + " is not a glibc driver - it links Android's libc. "
+ "The Linux runtime needs a \"-Linux\" zip; a plain or \"-Wayland\" Turnip cannot be "
+ "loaded by the Steam client at all.");
}
String kind = zipMeta != null ? zipMeta.optString("kind", "") : "";
if (!kind.isEmpty() && !"linux-vulkan-icd".equals(kind)) {
Log.w(TAG, "meta.json says kind=" + kind + ", importing anyway (the binary is glibc)");
}
String name = zipMeta != null ? zipMeta.optString("name", "") : "";
String version = zipMeta != null ? zipMeta.optString("driverVersion", "") : "";
String minGlibc = zipMeta != null ? zipMeta.optString("minGlibc", "") : "";
if (name.isEmpty()) {
name = displayName != null ? displayName : "linux-driver";
if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4);
}
String id = uniqueId(sanitizeId(name));
File dir = getDriverDir(id);
// ICD manifest: absolute library_path, so the loader never depends on cwd and the guest
// reads it at the same path the app wrote (the files dir is bound into the session).
JSONObject icd = new JSONObject();
icd.put("file_format_version", "1.0.0");
JSONObject icdBody = new JSONObject();
icdBody.put("library_path", new File(dir, LIB_NAME).getAbsolutePath());
icdBody.put("api_version", "1.1.274");
icd.put("ICD", icdBody);
if (!FileUtils.writeString(new File(tmpDir, ICD_NAME), icd.toString(2))) throw new IOException("cannot write icd.json");
JSONObject meta = new JSONObject();
meta.put("schemaVersion", 1);
meta.put("kind", "linux-vulkan-icd");
meta.put("name", name);
meta.put("driverVersion", version);
meta.put("libc", "glibc");
meta.put("minGlibc", minGlibc);
meta.put("sourceLibraryName", soName);
meta.put("importedAt", System.currentTimeMillis());
if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json");
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
keep = true;
Log.i(TAG, "imported Linux Vulkan driver " + id + " (" + soName + ", minGlibc=" + minGlibc + ") -> " + dir);
return id;
} catch (org.json.JSONException e) {
throw new IOException("manifest write failed: " + e.getMessage());
} finally {
if (!keep) FileUtils.delete(tmpDir);
}
}
private String uniqueId(String base) {
String id = base;
int n = 2;
while (getDriverDir(id).exists()) id = base + "-" + (n++);
return id;
}
static String sanitizeId(String name) {
String s = name.trim().replaceAll("[^A-Za-z0-9._-]+", "_").replaceAll("^[._]+", "");
if (s.length() > 64) s = s.substring(0, 64);
return s.isEmpty() ? "linux-driver" : s;
}
/** ELF magic, EI_CLASS = 64-bit, EI_DATA = little-endian, e_machine = 0xB7 (AArch64). */
static boolean isAarch64Elf(File f) {
try (FileInputStream in = new FileInputStream(f)) {
byte[] h = new byte[20];
int n = 0;
while (n < h.length) {
int r = in.read(h, n, h.length - n);
if (r < 0) break;
n += r;
}
if (n < 20) return false;
if (h[0] != 0x7f || h[1] != 'E' || h[2] != 'L' || h[3] != 'F') return false;
if (h[4] != 2 || h[5] != 1) return false;
int machine = (h[18] & 0xff) | ((h[19] & 0xff) << 8);
return machine == 0xB7;
} catch (IOException e) {
return false;
}
}
private static byte[] readAll(InputStream in) throws IOException {
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[8192];
int r;
while ((r = in.read(buf)) > 0) bos.write(buf, 0, r);
return bos.toByteArray();
}
static boolean containsAscii(File f, String needle) {
byte[] nb = needle.getBytes(StandardCharsets.US_ASCII);
try (InputStream in = new FileInputStream(f)) {
byte[] buf = new byte[1 << 16];
int carry = 0;
int r;
while ((r = in.read(buf, carry, buf.length - carry)) > 0) {
int len = carry + r;
for (int i = 0; i + nb.length <= len; i++) {
int j = 0;
while (j < nb.length && buf[i + j] == nb[j]) j++;
if (j == nb.length) return true;
}
// Keep the last needle-1 bytes so a match across a buffer boundary is still found.
carry = Math.min(nb.length - 1, len);
System.arraycopy(buf, len - carry, buf, 0, carry);
}
} catch (IOException e) {
return false;
}
return false;
}
}
@@ -0,0 +1,99 @@
package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.runtime.LinuxRuntime;
import java.io.File;
/**
* LSFG frame generation's shader chain: extracted from the user's own copy of Lossless Scaling
* and cached on device.
*
* <p>The 25 compute shaders are not redistributable. They live as resources inside the user's
* paid {@code Lossless.dll} (Steam app 993090), which in this app the user installs from the
* Steam client itself - so the DLL sits in the runtime's own Steam library. It is mapped
* read-only and parsed as data, never loaded or executed. Extraction is slow enough to be worth
* doing once (the DXBC chain is translated to SPIR-V), so the result is cached, keyed on the
* DLL's size and hash. Call {@link #ensureCache} off the main thread.
*
* <p>Ported from Bannerlator's LsfgNative; the native side is the same lsfg_jni.cpp compiled into
* the compositor library.
*/
public final class LsfgNative {
private static final String TAG = "LsfgNative";
static { System.loadLibrary("bannerwayland"); }
private LsfgNative() {}
// Mirrors lsfg::DllStatus.
public static final int STATUS_OK = 0;
public static final int STATUS_NOT_INSTALLED = 1;
public static final int STATUS_UNREADABLE_FILE = 2;
public static final int STATUS_NOT_PORTABLE_EXECUTABLE = 3;
public static final int STATUS_MISSING_SHADERS = 4;
public static final int STATUS_TRANSLATION_FAILED = 5;
public static final int STATUS_CACHE_UNUSABLE = 6;
private static native int nativeValidateDll(String dllPath);
private static native int nativeDllVariant(String dllPath, boolean preferFp16);
private static native int nativeBuildCache(String dllPath, String cachePath, boolean preferFp16);
private static native boolean nativeCacheMatchesSource(String cachePath, String dllPath);
private static native int nativeCacheVariant(String cachePath);
private static native String nativeStatusName(int status);
private static native String nativeVariantName(int variant);
/** Where Lossless Scaling lands when installed from the client inside the runtime. */
public static File losslessDll(Context context) {
return new File(LinuxRuntime.rootDir(context),
"root/.local/share/Steam/steamapps/common/Lossless Scaling/Lossless.dll");
}
/** Where the translated SPIR-V chain is cached. */
public static File cacheFile(Context context) {
return new File(context.getFilesDir(), "lsfg-native/shaders.cache");
}
public static boolean isInstalled(Context context) {
return losslessDll(context).isFile();
}
/**
* Makes sure a usable cache exists for the installed DLL, building it if the DLL is new or
* changed. Returns a {@code STATUS_*} code; {@link #STATUS_OK} means the engine can start.
*/
public static int ensureCache(Context context) {
File dll = losslessDll(context);
if (!dll.isFile()) return STATUS_NOT_INSTALLED;
File cache = cacheFile(context);
try {
if (cache.isFile() && nativeCacheMatchesSource(cache.getPath(), dll.getPath())) {
return STATUS_OK;
}
int status = nativeValidateDll(dll.getPath());
if (status != STATUS_OK) {
Log.w(TAG, "Lossless.dll rejected: " + statusName(status));
return status;
}
//noinspection ResultOfMethodCallIgnored
cache.getParentFile().mkdirs();
status = nativeBuildCache(dll.getPath(), cache.getPath(), true);
Log.i(TAG, "cache build: " + statusName(status)
+ (status == STATUS_OK ? " (" + nativeVariantName(nativeCacheVariant(cache.getPath())) + ")" : ""));
return status;
} catch (Throwable t) {
Log.e(TAG, "ensureCache", t);
return STATUS_CACHE_UNUSABLE;
}
}
public static String statusName(int status) {
try {
return nativeStatusName(status);
} catch (Throwable t) {
return "status " + status;
}
}
}
@@ -0,0 +1,350 @@
package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.TarZst;
import com.droiddeck.launcher.session.SessionPrefs;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* The Vulkan driver the in-app compositor runs on. It has to be Turnip: the system Adreno driver
* does not implement VK_EXT_image_drm_format_modifier, so importing the dma-bufs gamescope hands
* over fails and the session renders nothing. Two builds ship in the apk, one per Adreno
* generation, and the GPU decides which is unpacked - unless the user has imported an AdrenoTools
* zip of their own and chosen it, which then wins.
*
* <p>The guest's own Turnip is a different copy entirely - a glibc build inside the rootfs, or an
* imported one ({@link LinuxVulkanDriverManager}). This one is the bionic build the app process
* loads through adrenotools, and it is what every session ends in: whatever draws inside the
* runtime, this is the driver that puts the frame on the panel.
*
* <p>Every driver, bundled or imported, lives under {@code files/graphics_driver/<id>/} with a
* {@code meta.json} whose {@code libraryName} names the .so beside it - the AdrenoTools layout.
* The import path is ported from Bannerlator's {@code AdrenotoolsManager} (GPL-3.0), including
* the refusal of zips that belong in the Linux runtime list: a "-Linux" (glibc) Turnip names no
* library on purpose, and installed here it would put the compositor on the system Vulkan - a
* black screen wearing a driver's name.
*/
public final class TurnipDriver {
private static final String TAG = "TurnipDriver";
/** Adreno 7xx (8 Gen 2/3, e.g. the Pocket FIT's A750). */
private static final String DRIVER_A7XX = "turnip25.1.0";
/** Adreno 8xx (8 Elite, e.g. a Fold 8's A830). */
private static final String DRIVER_A8XX = "turnip-sdk36";
/** The two the apk carries; never removable, unpacked on demand. */
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(DRIVER_A7XX, DRIVER_A8XX));
/** Overrides the pick, for a device we cannot reach: a7xx, a8xx or system. */
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
/** Bundled drivers the user deleted: hidden from the list, their unpacked copy removed. */
private static final String PREFS = "graphics_driver";
private static final String KEY_HIDDEN = "hiddenBundled";
/** Stored choice meaning "pick by GPU" - the default, and what a removed import falls back to. */
public static final String AUTO = "";
public static final String HELP_TEXT =
"The driver the app's compositor puts frames on the screen with - the last step of every "
+ "session, Steam or desktop. AdrenoTools zips only (vulkan.adXXXX.so): a \"-Linux\" Turnip "
+ "belongs in the Linux runtime list above and is refused here. The compositor loads its "
+ "driver once per app process, so a change takes effect after the app is fully closed and "
+ "started again.";
private final Context context;
private final File contentDir;
public TurnipDriver(Context context) {
this.context = context;
this.contentDir = new File(context.getFilesDir(), "graphics_driver");
}
/** Absolute directory holding the driver, with a trailing slash - adrenotools wants both. */
public String driverPath(String driverId) {
return new File(contentDir, driverId).getAbsolutePath() + "/";
}
public String libraryName(String driverId) {
JSONObject meta = readMeta(driverId);
return meta != null ? meta.optString("libraryName", null) : null;
}
/** meta.json's "name", or the id when it has none. */
public String displayName(String driverId) {
JSONObject meta = readMeta(driverId);
String name = meta != null ? meta.optString("name", "") : "";
return name.isEmpty() ? driverId : name;
}
public String driverVersion(String driverId) {
JSONObject meta = readMeta(driverId);
return meta != null ? meta.optString("driverVersion", "") : "";
}
private JSONObject readMeta(String driverId) {
if (driverId == null || driverId.isEmpty() || driverId.contains("/") || driverId.contains("..")) return null;
File meta = new File(new File(contentDir, driverId), "meta.json");
String content = FileUtils.readString(meta);
if (content == null) return null;
try {
return new JSONObject(content);
} catch (Exception e) {
Log.w(TAG, "meta.json for " + driverId, e);
return null;
}
}
/** An imported driver is installed when its meta.json names a library that is there. */
public boolean isInstalled(String driverId) {
String library = libraryName(driverId);
return library != null && !library.isEmpty() && new File(new File(contentDir, driverId), library).isFile();
}
/**
* The bundled drivers the list shows: {@link #BUNDLED} minus the ones the user deleted. A deleted
* one still lives in the apk and Auto still unpacks it on a GPU that needs it, so deleting can
* never leave a device without a driver; it only leaves the list.
*/
public List<String> visibleBundled() {
java.util.Set<String> hidden = hiddenBundled();
ArrayList<String> out = new ArrayList<>();
for (String id : BUNDLED) if (!hidden.contains(id)) out.add(id);
return out;
}
public java.util.Set<String> hiddenBundled() {
return new java.util.HashSet<>(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getStringSet(KEY_HIDDEN, java.util.Collections.<String>emptySet()));
}
/** "Delete" for a bundled driver: remove its unpacked copy and hide it from the list. */
public void hideBundled(String driverId) {
if (!BUNDLED.contains(driverId)) return;
FileUtils.delete(new File(contentDir, driverId));
java.util.Set<String> hidden = hiddenBundled();
hidden.add(driverId);
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY_HIDDEN, hidden).apply();
Log.i(TAG, "bundled driver " + driverId + " hidden by the user");
}
public void restoreBundled() {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().remove(KEY_HIDDEN).apply();
}
/** Imported drivers only - the bundled two are listed by {@link #BUNDLED}. */
public List<String> enumerateImported() {
ArrayList<String> ids = new ArrayList<>();
File[] dirs = contentDir.listFiles();
if (dirs == null) return ids;
for (File d : dirs) {
String id = d.getName();
if (d.isDirectory() && !BUNDLED.contains(id) && !id.startsWith(".") && isInstalled(id)) ids.add(id);
}
Collections.sort(ids);
return ids;
}
/** The bundled build the GPU would pick on its own, for the "Auto" row's label. */
public String autoId() {
String id = chooseByDevice();
return id == null ? "system" : id;
}
public void remove(String driverId) {
if (driverId == null || driverId.isEmpty() || BUNDLED.contains(driverId)
|| driverId.contains("/") || driverId.contains("..")) return;
Log.d(TAG, "removing imported driver " + driverId);
FileUtils.delete(new File(contentDir, driverId));
if (driverId.equals(SessionPrefs.androidDriver(context))) SessionPrefs.setAndroidDriver(context, AUTO);
}
/**
* Import an AdrenoTools zip. Returns the new driver id.
* @throws IllegalArgumentException with a user-facing reason when the zip is not an AdrenoTools
* driver - including when it is a Linux runtime driver, which says which list it belongs in;
* {@link IOException} on read/extract failures.
*/
public String installFromZip(Uri zipUri, String displayName) throws IOException {
if (!contentDir.exists()) contentDir.mkdirs();
File tmpDir = new File(contentDir, ".tmp-" + System.currentTimeMillis());
FileUtils.delete(tmpDir);
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
boolean keep = false;
try {
try (InputStream is = context.getContentResolver().openInputStream(zipUri);
ZipInputStream zis = new ZipInputStream(is)) {
if (is == null) throw new IOException("cannot open " + zipUri);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) continue;
// Flatten: adrenotools reads the .so beside meta.json, and a base name also
// defeats zip-slip paths.
String base = new File(entry.getName()).getName();
if (base.isEmpty()) continue;
Files.copy(zis, new File(tmpDir, base).toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
String rejected = rejectionReason(tmpDir);
if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected);
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
String name = meta != null ? meta.optString("name", "") : "";
if (name.isEmpty()) {
name = displayName != null ? displayName : "adrenotools-driver";
if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4);
}
String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name));
File dir = new File(contentDir, id);
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
keep = true;
Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir);
return id;
} finally {
if (!keep) FileUtils.delete(tmpDir);
}
}
private static JSONObject readMetaFile(File metaFile) {
try {
return new JSONObject(FileUtils.readString(metaFile));
} catch (Exception e) {
return null;
}
}
/**
* Why a just-extracted zip is not something adrenotools can be pointed at, or null when it is.
* The kinds refused by name are the other driver lists' zips, which carry a meta.json too.
*/
private static String rejectionReason(File dir) {
File metaFile = new File(dir, "meta.json");
if (!metaFile.isFile()) return "no meta.json";
String libraryName, kind;
try {
JSONObject meta = new JSONObject(FileUtils.readString(metaFile));
libraryName = meta.optString("libraryName", "");
kind = meta.optString("kind", "");
} catch (Exception e) {
return "meta.json is unreadable (" + e.getMessage() + ")";
}
if ("linux-vulkan-icd".equals(kind))
return "this is a Linux runtime driver (import it under \"Linux runtime driver\")";
if ("wayland-game-driver".equals(kind))
return "this is a Wayland game driver, which this app has no use for";
if (libraryName.isEmpty())
return "meta.json names no libraryName, so nothing could be handed to AdrenoTools";
File library = new File(dir, libraryName);
if (!library.isFile())
return "meta.json names " + libraryName + ", which is not in the zip";
if (!LinuxVulkanDriverManager.isAarch64Elf(library))
return libraryName + " is not a 64-bit AArch64 ELF shared library";
// A glibc build that happens to carry a libraryName would load nothing in this process.
if (LinuxVulkanDriverManager.containsAscii(library, "libc.so.6"))
return libraryName + " links glibc - a \"-Linux\" Turnip, which belongs under \"Linux runtime driver\"";
return null;
}
private String uniqueId(String base) {
String id = base;
int n = 2;
while (new File(contentDir, id).exists()) id = base + "-" + (n++);
return id;
}
/**
* Unpacks the driver this device needs and returns its id, or null to fall back to the system
* Vulkan loader (which means a black session on Adreno, but is better than refusing to start
* on a GPU neither build covers).
*/
public String install() {
String id = choose();
if (id == null) return null;
File dir = new File(contentDir, id);
if (!new File(dir, "meta.json").isFile()) {
FileUtils.delete(dir);
if (!TarZst.extractAsset(context, "graphics_driver/adrenotools-" + id + ".tzst", dir)) {
Log.e(TAG, "could not unpack " + id);
FileUtils.delete(dir);
return null;
}
}
String library = libraryName(id);
if (library == null || !new File(dir, library).isFile()) {
Log.e(TAG, id + " unpacked without " + library);
return null;
}
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
return id;
}
/**
* The user's choice first - an imported driver, or one of the bundled two pinned by hand -
* then the Downloads override, then the GPU. A chosen import that has since been removed logs
* and falls through, so a stale preference never blocks a session.
*/
private String choose() {
String chosen = SessionPrefs.androidDriver(context);
if (chosen != null && !chosen.isEmpty()) {
if (BUNDLED.contains(chosen)) {
Log.i(TAG, "driver pinned by the user: " + chosen);
return chosen;
}
if (isInstalled(chosen)) {
Log.i(TAG, "imported driver chosen by the user: " + chosen);
return chosen;
}
Log.w(TAG, "chosen driver \"" + chosen + "\" is gone; picking by GPU");
}
return chooseByDevice();
}
private String chooseByDevice() {
File override = new File(Environment.getExternalStorageDirectory(), OVERRIDE_FILE);
String forced = override.isFile() ? FileUtils.readString(override) : null;
if (forced != null) {
forced = forced.trim().toLowerCase(java.util.Locale.US);
Log.i(TAG, "driver forced by " + override + ": " + forced);
if (forced.startsWith("system")) return null;
if (forced.startsWith("a8")) return DRIVER_A8XX;
if (forced.startsWith("a7")) return DRIVER_A7XX;
}
String model = gpuModel();
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
if (model != null) {
// "Adreno750", "adreno_830" - the generation is the first digit of the three.
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(\\d)\\d\\d").matcher(model);
if (m.find()) {
char generation = m.group(1).charAt(0);
if (generation >= '8') return DRIVER_A8XX;
if (generation == '7') return DRIVER_A7XX;
}
}
// Nothing to go on: Android 16 shipped with the 8 Elite, so treat a new device as 8xx.
return android.os.Build.VERSION.SDK_INT >= 36 ? DRIVER_A8XX : DRIVER_A7XX;
}
/** KGSL names the GPU here, and this file is world-readable where /dev/kgsl-3d0 is not. */
private static String gpuModel() {
for (String path : new String[]{
"/sys/class/kgsl/kgsl-3d0/gpu_model",
"/sys/class/kgsl/kgsl-3d0/gpu_chipid"}) {
String value = FileUtils.readString(new File(path));
if (value != null && !value.trim().isEmpty()) return value.trim();
}
return null;
}
}
@@ -0,0 +1,207 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import com.droiddeck.launcher.core.FileUtils
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
/**
* Driver downloads from the Turnip release repos, offered in both driver menus. Checked only when
* the user taps refresh - the result is remembered, so the menu shows the last check without going
* online. A download goes through the same importer as a zip picked by hand, so it gets the same
* checks and lands as an ordinary imported driver.
*
* Each repo's recent releases are read newest first and every driver variant is offered from the
* newest release that carries it: a repo that stops publishing one variant (Banners-Turnip's A8xx
* Linux build after v26.3.0-20260923) still offers its last one, and a repo with two release lines
* (WinNative's Android `v1.x` and Linux `linux-v0.x`) offers the newest of each.
*/
object TurnipReleases {
private const val PREFS = "turnip_releases"
private const val KEY_RELEASE = "latest"
private const val KEY_DOWNLOADS = "downloads"
/** [label] names the variant for the menu: the GPUs it is for, and a build flavour. */
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String)
/** [latest] = each source's newest release tag, for the refresh line. */
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Pair<Boolean, String>?)
private val SOURCES = listOf(
// Turnip-<tag>[-variant][-Linux|-Wayland].zip; -Wayland is for a path this app does not have.
Source("Banners-Turnip", "The412Banner/Banners-Turnip") { name, tag ->
val prefix = "Turnip-$tag"
if (!name.startsWith(prefix) || !name.endsWith(".zip")) return@Source null
var variant = name.removePrefix(prefix).removeSuffix(".zip")
if (variant.endsWith("-Wayland")) return@Source null
val linux = variant.endsWith("-Linux")
variant = variant.removeSuffix("-Linux")
linux to when {
variant.isEmpty() -> "Adreno 6xx/7xx"
variant == "-A8xx" -> "Adreno 8xx"
variant.startsWith("-710-720") -> "Adreno 710/720" + if (variant.contains("Test")) " (test)" else ""
else -> variant.trimStart('-')
}
},
// WN-Turnip-<ver>-<b|p>_Axxx.zip (Android) and WN-Linux-Turnip-<ver>-<b|p>_Axxx.zip (Linux):
// b = Balanced, p = Performance, Axxx = every Adreno.
Source("WinNative", "WinNative-Emu/Drivers") { name, _ ->
val m = Regex("""^WN-(Linux-)?Turnip-[^-]+-([a-z]+)_(\w+)\.zip$""").find(name) ?: return@Source null
val flavour = when (m.groupValues[2]) { "b" -> "Balanced"; "p" -> "Performance"; else -> m.groupValues[2] }
val gpus = if (m.groupValues[3] == "Axxx") "all Adreno" else m.groupValues[3]
(m.groupValues[1].isNotEmpty()) to "$gpus · $flavour"
},
)
/** The result of the last check, or null when the user has never checked. */
fun cached(context: Context): Check? {
val raw = prefs(context).getString(KEY_RELEASE, null) ?: return null
return runCatching { parse(JSONObject(raw)) }.getOrNull()
}
/**
* Read every source now and remember the result. A source that fails is named in [Check.failed]
* and the others still count; throws only when every source failed.
*/
fun refresh(context: Context): Check {
val assets = JSONArray()
val latest = JSONArray()
val failed = ArrayList<String>()
var lastError: Exception? = null
for (src in SOURCES) {
try {
val releases = JSONArray(get("https://api.github.com/repos/${src.repo}/releases?per_page=15"))
val seen = HashSet<String>()
var newest: String? = null
for (i in 0 until releases.length()) {
val r = releases.getJSONObject(i)
if (r.optBoolean("draft")) continue
val tag = r.getString("tag_name")
if (newest == null) newest = tag
val list = r.optJSONArray("assets") ?: continue
for (j in 0 until list.length()) {
val a = list.getJSONObject(j)
val name = a.getString("name")
val (linux, label) = src.classify(name, tag) ?: continue
// Newest first: the first release carrying a variant is the one offered.
if (!seen.add("$linux|$label")) continue
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
.put("linux", linux).put("label", label))
}
}
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
} catch (e: Exception) {
failed.add(src.label)
lastError = e
}
}
if (failed.size == SOURCES.size) throw lastError ?: IOException("no source answered")
val stored = JSONObject().put("assets", assets).put("latest", latest)
.put("failed", JSONArray(failed)).put("checkedAt", System.currentTimeMillis())
prefs(context).edit().putString(KEY_RELEASE, stored.toString()).apply()
return parse(stored)
}
private fun get(url: String): String {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
c.readTimeout = 20_000
c.setRequestProperty("Accept", "application/vnd.github+json")
c.setRequestProperty("User-Agent", "DroidDeck-app")
try {
val code = c.responseCode
if (code == 403 || code == 429) throw IOException("GitHub's rate limit was hit - try again later")
if (code != 200) throw IOException("GitHub answered HTTP $code")
return c.inputStream.bufferedReader().use { it.readText() }
} finally {
c.disconnect()
}
}
private fun parse(json: JSONObject): Check {
val out = ArrayList<Asset>()
val list = json.getJSONArray("assets")
for (i in 0 until list.length()) {
val a = list.getJSONObject(i)
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
a.optLong("size"), a.getBoolean("linux"), a.getString("label")))
}
val latest = ArrayList<Pair<String, String>>()
val l = json.optJSONArray("latest") ?: JSONArray()
for (i in 0 until l.length()) l.getJSONObject(i).let { latest.add(it.getString("source") to it.getString("tag")) }
val failed = ArrayList<String>()
val f = json.optJSONArray("failed") ?: JSONArray()
for (i in 0 until f.length()) failed.add(f.getString(i))
return Check(out, latest, failed, json.optLong("checkedAt"))
}
/** The id an asset was installed as, when it was downloaded before and is still installed. */
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
downloads(context).optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
/** True when [id] came from a release download rather than a zip picked by hand. */
fun isDownloaded(context: Context, id: String): Boolean {
val d = downloads(context)
return d.keys().asSequence().any { d.optString(it) == id }
}
fun recordDownload(context: Context, asset: Asset, id: String) {
prefs(context).edit().putString(KEY_DOWNLOADS, downloads(context).put(asset.name, id).toString()).apply()
}
/** Forget a deleted driver, so its release offers the download again. */
fun forget(context: Context, id: String) {
val d = downloads(context)
val keys = d.keys().asSequence().filter { d.optString(it) == id }.toList()
if (keys.isEmpty()) return
keys.forEach { d.remove(it) }
prefs(context).edit().putString(KEY_DOWNLOADS, d.toString()).apply()
}
/** Download an asset into the cache; the caller imports it and deletes the file. */
fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File {
val target = File(context.cacheDir, asset.name)
val c = URL(asset.url).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
c.readTimeout = 60_000
c.setRequestProperty("User-Agent", "DroidDeck-app")
c.instanceFollowRedirects = true
try {
if (c.responseCode != 200) throw IOException("download answered HTTP ${c.responseCode}")
val total = c.contentLengthLong.takeIf { it > 0 } ?: asset.size
c.inputStream.use { input ->
FileOutputStream(target).use { out ->
val buf = ByteArray(1 shl 16)
var done = 0L
var last = -1
while (true) {
val r = input.read(buf)
if (r <= 0) break
out.write(buf, 0, r)
done += r
val pct = if (total > 0) (done * 100 / total).toInt() else 0
if (pct != last) { last = pct; progress(pct) }
}
}
}
return target
} catch (e: Exception) {
FileUtils.delete(target)
throw e
} finally {
c.disconnect()
}
}
private fun downloads(context: Context): JSONObject =
runCatching { JSONObject(prefs(context).getString(KEY_DOWNLOADS, "{}")!!) }.getOrDefault(JSONObject())
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}