Compare commits

..
94 changed files with 832 additions and 1412 deletions

No files matched your search

+2 -1
View File
@@ -186,7 +186,7 @@ jobs:
uses: actions/cache@v4
with:
path: app/src/main/assets/linuxfs
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/linuxfs/debian-image.env') }}
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/linuxfs/debian-image.env') }}
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
if: steps.preloads.outputs.cache-hit != 'true'
@@ -457,6 +457,7 @@ jobs:
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
run: |
set -o pipefail
python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
python3 tools/release/runtime_inputs.py record
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
python3 tools/release/check_session_assets.py app/build/outputs/apk/release/app-release.apk
+2 -2
View File
@@ -92,8 +92,8 @@ android {
// file out of its own data directory, and this app's entire job is to exec a rootfs:
// proot, gamescope, the Steam client and everything it launches all live under files/.
targetSdkVersion 28
versionCode 13
versionName "0.4.0"
versionCode 12
versionName "0.3.2"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}"
+10 -3
View File
@@ -3600,6 +3600,13 @@ static bool wait_snapshot(std::shared_ptr<FakeController> fake,
}
}
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
// Preserve later preload hooks, including GPU allocation adapters.
static const auto next = reinterpret_cast<ioctl_fn>(dlsym(RTLD_NEXT, "ioctl"));
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
}
EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
va_list va;
void *argp;
@@ -3611,7 +3618,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
// The lock must not be held across the passthrough: binder's transport is a
// blocking ioctl(BINDER_WRITE_READ), so a parked binder pool thread would own
// controller_mutex() for as long as it waits and deadlock every other ioctl.
if (!watched(fd)) return syscall(SYS_ioctl, fd, op, argp);
if (!watched(fd)) return forward_ioctl(fd, op, argp);
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
auto maker = uinput_map().find(fd);
if (maker != uinput_map().end()) return ioctl_uinput(*maker->second, op, argp);
@@ -3629,7 +3636,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
auto controller = controller_map().find(fd);
if (controller == controller_map().end()) {
guard.unlock();
return syscall(SYS_ioctl, fd, op, argp);
return forward_ioctl(fd, op, argp);
}
int type = (op >> 8 & 0xFF);
@@ -3825,7 +3832,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
} else {
Logger::log("Unhandled evdev ioctl, type %d number %d\n", type, number);
guard.unlock();
return syscall(SYS_ioctl, fd, op, argp);
return forward_ioctl(fd, op, argp);
}
}
@@ -255,11 +255,7 @@ static void target_destroy(struct fx_target *t) {
static int target_ensure(struct fx_target *t, int w, int h, const char *what) {
if (t->img && t->w == w && t->h == h) return 0;
target_destroy(t);
/* Unrestricted mutable views keep these render-then-blit targets uncompressed on Turnip.
* UBWC targets corrupt even a constant-colour pass on Adreno 740 (FSR becomes black).
* Only the chain's intermediate images need this; the scene and guest images stay unchanged. */
VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, .imageType = VK_IMAGE_TYPE_2D,
VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
.format = g_fx_fmt, .extent = {(uint32_t)w, (uint32_t)h, 1}, .mipLevels = 1,
.arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
@@ -296,10 +292,6 @@ static void scene_release(void) {
memset(&g_scene, 0, sizeof(g_scene));
}
void vkp_effects_forget_image(VkImage img) {
if (img && g_scene.img == img) scene_release();
}
static int scene_ensure(VkImage img, int w, int h) {
if (g_scene.img == img && g_scene.w == w && g_scene.h == h && g_scene.ds) return 0;
scene_release();
@@ -55,10 +55,6 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
/* Compositor thread: drop every Vulkan object (device teardown / device lost). */
void vkp_effects_destroy(void);
/* Compositor thread: release the cached source view/descriptor before its owner destroys img.
* A later image can reuse the same Vulkan handle and dimensions; that is not the same resource. */
void vkp_effects_forget_image(VkImage img);
/* Compositor thread, before vkp_effects_run(): the format of the scene image it will be handed and the
* format its own targets use. R8G8B8A8 / R8G8B8A8 for every SDR frame (the default); A2B10G10R10 /
* A2B10G10R10 while an HDR picture runs through it (hdr_compose.h). A target-format change rebuilds the
@@ -1164,7 +1164,6 @@ static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkI
}
static void destroy_scene_image(void) {
if (g_scene.img) vkp_effects_forget_image(g_scene.img);
if (g_scene.img) hdrc_forget_image(g_scene.img); /* the HDR pass may have drawn into it */
if (g_scene.img) blendp_forget_image(g_scene.img);
if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL);
@@ -1204,7 +1203,6 @@ static int ensure_scene_image(int w, int h) {
static int ensure_img(struct vkp_img_slot *s, int w, int h, VkFormat fmt, VkImageUsageFlags usage, const char *what) {
if (s->img && s->w == w && s->h == h && s->fmt == fmt) return 0;
if (s->img) hdrc_forget_image(s->img);
if (s->img) vkp_effects_forget_image(s->img);
if (s->img) blendp_forget_image(s->img);
if (s->img) g_vk.DestroyImage(g_dev, s->img, NULL);
if (s->mem) g_vk.FreeMemory(g_dev, s->mem, NULL);
@@ -22,6 +22,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
CrashHandler.install(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.update.AppUpdates.init(this)
GpuClockPin.clearLeftover(this)
@@ -163,7 +163,6 @@ class MainActivity : ComponentActivity() {
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherFullscreen by mutableStateOf(true)
private var animationsEnabled by mutableStateOf(true)
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
/** A page a notification asked for ("stores:downloads", "app:<id>"), until the front end has gone there. */
@@ -535,7 +534,6 @@ class MainActivity : ComponentActivity() {
requestedOrientation = orientation
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
animationsEnabled = SessionPrefs.animationsEnabled(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
storesOpenTab = SessionPrefs.storesOpenTab(this)
storesShowMature = SessionPrefs.storesShowMature(this)
@@ -589,7 +587,6 @@ class MainActivity : ComponentActivity() {
orientation = orientation,
launcherFullscreen = launcherFullscreen,
animationsEnabled = animationsEnabled,
gameStoresEnabled = gameStoresEnabled,
gameStoresSpeedTier = gameStoresSpeedTier,
storesOpenTab = storesOpenTab,
navigate = navRequest,
@@ -730,7 +727,6 @@ class MainActivity : ComponentActivity() {
offline = OfflineMode.enabled(this)
},
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
onLanguage = { tag ->
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
@@ -338,7 +338,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val deviceListener = object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
logInputDevice("connected", deviceId)
padBridge?.syncConnectedControllers()
updateOnScreenControls()
updatePointerCapture()
}
@@ -2408,7 +2407,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
onScreenControls?.reload()
controllerSettings = ControllerPrefs.read(this)
updateOnScreenControls()
@@ -50,7 +50,8 @@ public final class TurnipDriver {
/** 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));
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER));
/** 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. */
@@ -257,14 +257,6 @@ public final class PadBridge {
return false;
}
/** Publishes every currently connected controller so the client can enumerate all players. */
public synchronized void syncConnectedControllers() {
for (int deviceId : InputDevice.getDeviceIds()) {
InputDevice device = InputDevice.getDevice(deviceId);
if (isFromController(device)) publish(slotFor(device));
}
}
/**
* Called (main thread) when a player presses a button, pushes a stick, trigger or d-pad past
* halfway, or uses the on-screen controls - the session hides its mouse cursor then. Resting
@@ -33,7 +33,7 @@ import java.util.concurrent.atomic.AtomicInteger
*/
object BwrapSpawner {
private const val TAG = "BwrapSpawner"
const val SOCKET = "com.droiddeck.launcher.bwrap"
fun socket(context: Context): String = "${context.packageName}.bwrap"
private val seq = AtomicInteger()
@Volatile private var server: LocalServerSocket? = null
@@ -42,10 +42,11 @@ object BwrapSpawner {
fun start(context: Context) {
if (server != null) return
val app = context.applicationContext
val name = socket(app)
val socket = try {
LocalServerSocket(SOCKET)
LocalServerSocket(name)
} catch (e: IOException) {
Log.e(TAG, "cannot listen on $SOCKET", e)
Log.e(TAG, "cannot listen on $name", e)
return
}
server = socket
@@ -51,6 +51,7 @@ object GuestCommand {
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
)
cmd += argv
@@ -406,11 +406,9 @@ object ComponentsManager {
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
}
/** The stored packages, newest version first. */
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
?.filter { it.isFile && it.name.endsWith(".wcp") }
?.filter { it.isFile && it.name.endsWith(".wcp") }?.sortedBy { it.name }
?.mapNotNull { f -> runCatching { packageInfo(context, f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
?.sortedWith(newestFirst { it.version.ifEmpty { it.file } })
?: emptyList()
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
@@ -854,14 +852,10 @@ object ComponentsManager {
val arr = o.optJSONArray("items") ?: JSONArray()
val items = (0 until arr.length()).map { arr.getJSONObject(it) }.map {
CatalogItem(it.optString("file"), it.optString("comp"), it.optString("release"), it.optString("url"), it.optLong("size"), it.optString("digest"))
}.sortedWith(compareBy<CatalogItem> { it.comp }.then(newestFirst { it.file }))
}.sortedWith(compareBy({ it.comp }, { it.release }, { it.file }))
return Catalog(items, o.optLong("fetchedAt"))
}
/** By the version in [of], highest first: the newest builds lead a list, as they are what is picked. */
private fun <T> newestFirst(of: (T) -> String): Comparator<T> =
Comparator { a, b -> ProtonExtras.compareVersions(of(b), of(a)) }
/**
* A package Proton does not ship, required on the GPUs listed here. An empty [models] set
* means every model in [families]. A row the user already chose in Components is left alone;
@@ -24,6 +24,12 @@ object CrashHandler {
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
try {
Log.e(TAG, "uncaught on ${thread.name}", error)
if (QuestExperimental.isSupported()) runCatching {
File(context.filesDir, "quest-last-crash.txt").writeText(
"${java.time.Instant.now()} thread=${thread.name}\n" +
StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
)
}
val dir = SessionPaths.current()
if (dir != null && dir.isDirectory) {
val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
@@ -0,0 +1,60 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Build
import android.util.Log
import com.droiddeck.launcher.BuildConfig
import java.io.File
/** Defaults and launch evidence for this explicitly experimental Quest build. */
object QuestExperimental {
private const val TAG = "QuestExperimental"
const val DRIVER = "turnip25.1.0-quest1"
// Quest 2 has an A6xx GPU and cannot use this bundled A7xx driver.
internal fun supported(model: String, device: String, manufacturer: String): Boolean =
model.equals("Quest 3", ignoreCase = true) || model.equals("Quest 3S", ignoreCase = true) ||
((manufacturer.equals("Oculus", ignoreCase = true) || manufacturer.equals("Meta", ignoreCase = true)) &&
(device == "eureka" || device == "panther"))
fun isSupported(): Boolean = supported(Build.MODEL, Build.DEVICE, Build.MANUFACTURER)
fun initialize(context: Context) {
if (!isSupported()) return
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
if (!prefs.getBoolean("questDefaultsV1", false)) {
// Auto would download an unwrapped display driver and lose the compatibility path.
// Apply once so deliberate changes made during headset testing remain possible.
prefs.edit()
.putString("gpuDriverMode", SessionPrefs.GPU_DRIVERS_MANUAL)
.putString("androidDriver", DRIVER)
.putString("linuxDriver", "")
// The existing HDR option uses SurfaceControl presentation. This is a
// corruption workaround from upstream issue #245, not a claim of HDR accuracy.
.putBoolean("hdr.steam", true)
.putBoolean("questDefaultsV1", true)
.apply()
}
val report = buildString {
appendLine("DroidDeck Quest Experimental ${BuildConfig.VERSION_NAME}")
appendLine("package=${context.packageName}")
appendLine("manufacturer=${Build.MANUFACTURER} model=${Build.MODEL}")
appendLine("device=${Build.DEVICE} board=${Build.BOARD} hardware=${Build.HARDWARE}")
appendLine("android=${Build.VERSION.RELEASE} sdk=${Build.VERSION.SDK_INT}")
appendLine("abis=${Build.SUPPORTED_ABIS.joinToString()}")
for (name in listOf("gpu_model", "gpu_chipid")) {
val value = runCatching { File("/sys/class/kgsl/kgsl-3d0/$name").readText().trim() }
.getOrDefault("unavailable")
appendLine("$name=$value")
}
appendLine("driverMode=${SessionPrefs.gpuDriverMode(context)}")
appendLine("androidDriver=${SessionPrefs.androidDriver(context)}")
appendLine("steamSurfaceControlWorkaround=${SessionPrefs.hdr(context, "steam")}")
appendLine("GPUOBJ fallback installed in Android driver and ARM64 libblsession")
appendLine("Experimental Quest 3/3S compatibility; 2D panel application")
}
Log.i(TAG, report)
runCatching { File(context.filesDir, "quest-startup.txt").writeText(report) }
.onFailure { Log.w(TAG, "Could not write startup report", it) }
}
}
@@ -71,12 +71,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("animations", on).apply()
}
fun gameStoresEnabled(context: Context): Boolean = prefs(context).getBoolean("gameStoresEnabled", true)
fun setGameStoresEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("gameStoresEnabled", on).apply()
}
/** The store download engine's speed tier (stores/download/StoreDownloadTier ids); Fast unless chosen otherwise. */
fun gameStoresSpeedTier(context: Context): String = prefs(context).getString("gameStoresSpeedTier", "fast") ?: "fast"
@@ -343,6 +343,7 @@ class SessionService : Service() {
val size = SessionState.outputSize
val guest = ArrayList<String>()
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
// The desktop's Steam launchers start the client there (droiddeck-steam-launch), through the
// same set-up as a Steam session: it gets what the client and its games are started with.
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
@@ -381,12 +382,7 @@ class SessionService : Service() {
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
SessionState.deckPad = false
deckBinds = emptyList()
if (controllersOn) {
addControllerEnvironment(guest, fakeInputDir, sessionDir)
// Steam enumerates /dev/input while it starts. Make every attached controller's
// discovery node exist after the rings and guest environment are ready.
SessionState.padBridge?.syncConnectedControllers()
}
if (controllersOn) addControllerEnvironment(guest, fakeInputDir, sessionDir)
// The user's own games, for the runtime's shortcuts writer to put in the client's library
// before the client starts (see frontend/AddedGames and droiddeck-steam-shortcuts).
if (steamHere) {
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.stores
import com.droiddeck.launcher.session.SessionPrefs
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.frontend.AddedGames
@@ -77,26 +76,14 @@ object StoreInstalls {
/**
* Removes a store game: its folder with the sidecar, then the shortcut (the listing without
* it makes the writer drop the entry; the live client is asked too). Blocking. [removed] runs
* once the files are gone, before the shortcut list is rebuilt (which reads every added game).
* it makes the writer drop the entry; the live client is asked too). Blocking.
*/
fun uninstall(context: Context, game: InstalledStoreGame, progress: (Float) -> Unit = {}, removed: () -> Unit = {}) {
fun uninstall(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
// The shortcut's id as stored for the folder: scanning every added game for it first held
// the bar at 0% for seconds before a file went.
val appId = SessionPrefs.addedGameStoredAppId(app, game.folder.path)
// File by file, deepest first, saying how far it has got: a big game takes a while to go.
val files = game.folder.walkBottomUp().toList()
val step = (files.size / 100).coerceAtLeast(1)
files.forEachIndexed { i, f ->
f.delete()
if (i % step == 0) progress((i + 1).toFloat() / files.size)
}
val appId = AddedGames.scan(app).firstOrNull { it.folder.absolutePath == game.folder.absolutePath }?.appId
deleteTree(game.folder)
progress(1f)
// The scratch cache an install on a card may have left in the app's cache.
deleteTree(StoreInstallRoot.scratchDir(app, game.sidecar.store, game.sidecar.id))
removed()
register(app)
if (appId != null) SteamLiveShortcuts.remove(app, appId)
StoresState.logLine("uninstalled \"${game.sidecar.title}\"")
@@ -99,8 +99,6 @@ object StoresState {
/** Reads what is on disk for every store: sign-ins, installed games, the engine probe. Off the main thread. */
fun refresh(context: Context) {
val app = context.applicationContext
// The first refresh after the app starts brings back what was in the download queue.
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
Thread({
val found = Store.entries.mapNotNull { store -> StoreAccounts.signedInAs(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
@@ -219,30 +217,15 @@ object StoresState {
fun install(context: Context, item: CatalogItem, root: java.io.File? = null) {
val app = context.applicationContext
val target = root ?: StoreInstallRoot.installRoot(app)
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, target)
backends[item.store]?.install(app, item, target) ?: logLine("${item.store.label}: this build cannot install yet")
}
/** Games being removed, by key ("store:id"), and how far along (0..1): their page shows it. */
val uninstalling = mutableStateMapOf<String, Float>()
/**
* Removes the game's folder and its shortcut, then [onDone] on the main thread. The game reads
* as removed the moment it is gone (its page shows Install, its card its size), not once the
* whole library has been read again.
*/
/** Removes the game's folder and its shortcut, then [onDone] on the main thread. */
fun uninstall(context: Context, game: InstalledStoreGame, onDone: () -> Unit = {}) {
val app = context.applicationContext
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
uninstalling[key] = 0f
Thread({
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
main.post {
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
uninstalling.remove(key)
}
})
StoreInstalls.uninstall(app, game)
main.post(onDone)
}, "stores-uninstall").start()
}
@@ -137,11 +137,6 @@ object DownloadQueue {
private val lock = Any()
private val items = LinkedHashMap<String, Item>()
/** Keys a restart brings back paused: queued as paused, not started. */
private val heldPaused = HashSet<String>()
/** [key]'s next [enqueue] comes in paused (a paused download restored after a restart). */
fun holdPaused(key: String) = synchronized(lock) { heldPaused.add(key) }
private var running = 0
fun parallel(context: Context): Int = SessionPrefs.gameStoresParallel(context)
@@ -176,8 +171,7 @@ object DownloadQueue {
synchronized(lock) {
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
items.remove(entry.key)
val state = if (heldPaused.remove(entry.key)) DownloadState.PAUSED else DownloadState.QUEUED
items[entry.key] = Item(entry.copy(state = state, stage = DownloadStage.MANIFEST, startedAt = System.currentTimeMillis()), factory)
items[entry.key] = Item(entry.copy(state = DownloadState.QUEUED, stage = DownloadStage.MANIFEST, startedAt = System.currentTimeMillis()), factory)
renumber()
}
StoresState.logLine("${entry.store.label}: queued \"${entry.name}\"" + if (entry.bytesTotal > 0) " (${com.droiddeck.launcher.stores.formatBytes(entry.bytesTotal)})" else "")
@@ -312,8 +306,6 @@ object DownloadQueue {
}
}
lastPublishAt = now
// A state change (not progress) is written down, so the queue outlives the app.
if (!progressOnly) SavedQueue.save(items.values.map { it.entry })
val list = items.values.map { it.entry }.sortedByDescending { it.startedAt }
StoresState.post { StoresState.publishDownloads(list) }
}
@@ -1,108 +0,0 @@
package com.droiddeck.launcher.stores.download
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.Executors
/**
* The download queue kept on disk, so what was queued, running or paused comes back after the app
* closes or is killed: the queue itself lives in memory, and a queued game that never started has
* nothing on disk to find. Each install records the game and where it goes ([remember]); every
* change of state writes the active rows in queue order ([save]); the first refresh after the app
* starts asks the stores for them again ([restore]) - running and queued ones carry on, paused ones
* come back paused.
*/
object SavedQueue {
private const val TAG = "StoreDownloads"
private const val FILE = "store-queue.json"
private class Wanted(val item: CatalogItem, val root: File?)
private val wanted = HashMap<String, Wanted>()
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "store-queue-save") }
@Volatile private var app: Context? = null
private var restored = false
private fun key(item: CatalogItem) = "${item.store.id}:${item.id}"
/** An install is asked for: what to ask the store for again after a restart. */
@Synchronized
fun remember(context: Context, item: CatalogItem, root: File?) {
app = context.applicationContext
wanted[key(item)] = Wanted(item, root)
}
/** The active rows, in queue order, as they are now. Any thread; written off it. */
fun save(entries: List<DownloadEntry>) {
val context = app ?: return
val rows = synchronized(this) {
entries.filter { it.isActive }.mapNotNull { e -> wanted[e.key]?.let { e to it } }
}
val out = JSONArray()
for ((e, w) in rows) out.put(JSONObject().apply {
put("paused", e.state == DownloadState.PAUSED)
put("root", w.root?.absolutePath ?: "")
put("item", itemJson(w.item))
})
writer.execute {
runCatching {
val f = File(context.filesDir, FILE)
val tmp = File(context.filesDir, "$FILE.tmp")
tmp.writeText(out.toString())
tmp.renameTo(f)
}.onFailure { Log.w(TAG, "could not save the queue", it) }
}
}
/** Once per process: queues again what was in the queue when the app last closed. */
fun restore(context: Context) {
synchronized(this) { if (restored) return; restored = true }
val app = context.applicationContext
// Read before anything may write it: an install started at once must not save over it.
val rows = runCatching { JSONArray(File(app.filesDir, FILE).readText()) }.getOrNull()
this.app = app
rows ?: return
Thread({
val back = (0 until rows.length()).mapNotNull { i ->
runCatching {
val o = rows.getJSONObject(i)
Triple(itemOf(o.getJSONObject("item")), o.optString("root").takeIf { it.isNotEmpty() }?.let(::File), o.optBoolean("paused"))
}.getOrNull()
}
if (back.isEmpty()) return@Thread
StoresState.post {
for ((item, root, paused) in back) {
if (DownloadQueue.entry(key(item)) != null) continue
if (paused) DownloadQueue.holdPaused(key(item))
StoresState.install(app, item, root)
}
}
}, "store-queue-restore").start()
}
private fun itemJson(i: CatalogItem) = JSONObject().apply {
put("store", i.store.id); put("id", i.id); put("title", i.title)
put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "")
put("tags", i.tags); put("developer", i.developer); put("description", i.description)
put("size", i.sizeBytes); put("owned", i.owned)
put("extra", JSONObject(i.extra))
}
private fun itemOf(o: JSONObject): CatalogItem {
val extra = o.optJSONObject("extra")
return CatalogItem(
store = Store.byId(o.getString("store")) ?: error("unknown store"),
id = o.getString("id"), title = o.getString("title"),
imageUrl = o.optString("image").ifEmpty { null }, tallImageUrl = o.optString("tall").ifEmpty { null },
tags = o.optString("tags"), developer = o.optString("developer"), description = o.optString("description"),
owned = o.optBoolean("owned", true), sizeBytes = o.optLong("size"),
extra = extra?.keys()?.asSequence()?.associateWith { extra.getString(it) } ?: emptyMap(),
)
}
}
@@ -739,15 +739,7 @@ fun ComponentsPage(
Column(Modifier.fillMaxSize()) {
// The in-use bar keeps its place; only its words change.
AnimatedContent(l, transitionSpec = { fadeIn(Motion.tw(240)) togetherWith fadeOut(Motion.tw(160)) }, label = "inUse") { k -> bar(k) }
val detailScroll = androidx.compose.runtime.key(l) { rememberScrollState() }
Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(detailScroll).padding(top = 12.dp, bottom = 16.dp)) {
// Shared performance settings stay visible before the downloadable catalog.
if (l == PROTON_TAB) {
if (!protons.runtimeReady) EmptyLine(stringResource(R.string.content_needs_runtime))
if (protons.sessionRunning) EmptyLine(stringResource(R.string.proton_stop_first))
SettingsGroup(stringResource(R.string.comp_for_every_proton)) { protonOptions() }
Spacer(Modifier.height(12.dp))
}
Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(top = 12.dp, bottom = 16.dp)) {
val slide: @Composable (@Composable (String) -> Unit) -> Unit = { body ->
AnimatedContent(
l,
@@ -785,6 +777,10 @@ fun ComponentsPage(
}
}
if (l == PROTON_TAB) {
Spacer(Modifier.height(10.dp))
if (!protons.runtimeReady) EmptyLine(stringResource(R.string.content_needs_runtime))
if (protons.sessionRunning) EmptyLine(stringResource(R.string.proton_stop_first))
SettingsGroup(stringResource(R.string.comp_for_every_proton)) { protonOptions() }
Spacer(Modifier.height(12.dp))
Note(stringResource(R.string.comp_about_text))
}
@@ -819,37 +815,41 @@ fun ComponentsPage(
if (narrow) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 6.dp)) { DeviceChip(gpu) }
Spacer(Modifier.height(14.dp))
if (games.isNotEmpty()) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp),
) {
Text(stringResource(R.string.comp_profile), fontSize = 14.sp, color = colors.onSurfaceVariant)
Box(Modifier.weight(1f, fill = false)) {
ValueChip(
selectedGame?.name ?: stringResource(R.string.comp_scope_general),
scopeMenu,
modifier = Modifier.widthIn(max = 320.dp).heightIn(min = 44.dp),
) { scopeMenu = !scopeMenu }
AnchoredMenu(
scopeMenu,
onDismiss = { scopeMenu = false },
title = stringResource(R.string.comp_profile_configure),
) { first ->
MenuItem(
stringResource(R.string.comp_scope_general),
checked = selectedGame == null,
detail = stringResource(R.string.comp_scope_general_detail),
focusRequester = first,
) {
selectedGameKey = null
scopeMenu = false
}
games.sortedBy { it.name.lowercase() }.forEach { game ->
MenuItem(game.name, checked = selectedGameKey == game.profileKey) {
selectedGameKey = game.profileKey
SettingsGroup(stringResource(R.string.comp_profile_configure)) {
SettingsRow(
stringResource(R.string.comp_profile),
if (selectedGame == null) {
stringResource(R.string.comp_scope_general_detail)
} else {
stringResource(R.string.comp_profile_game_detail, selectedGame.name)
},
) {
Box {
ValueChip(
selectedGame?.name ?: stringResource(R.string.comp_scope_general),
scopeMenu,
modifier = Modifier.widthIn(max = 320.dp).heightIn(min = 44.dp),
) { scopeMenu = !scopeMenu }
AnchoredMenu(
scopeMenu,
onDismiss = { scopeMenu = false },
title = stringResource(R.string.comp_profile_configure),
) { first ->
MenuItem(
stringResource(R.string.comp_scope_general),
checked = selectedGame == null,
detail = stringResource(R.string.comp_scope_general_detail),
focusRequester = first,
) {
selectedGameKey = null
scopeMenu = false
}
games.sortedBy { it.name.lowercase() }.forEach { game ->
MenuItem(game.name, checked = selectedGameKey == game.profileKey) {
selectedGameKey = game.profileKey
scopeMenu = false
}
}
}
}
}
@@ -901,6 +901,7 @@ fun ComponentsPage(
) {
val tint = rememberUpdatedState(pal.signal)
val local = cardsAt[layer]?.translate(-stackAt)
ChipGlide(LAYERS.indexOf(layer), local, tint, GlideAxis.Vertical, corner = 12.dp)
Stack(
layer, view, gpu, focus = layerFocus, landed = landed, rings = rings,
onPlaced = { l, r -> cardsAt[l] = r },
@@ -911,8 +912,6 @@ fun ComponentsPage(
else runCatching { firstRow.requestFocus() }
},
)
// Over the cards: under them, their rest fill hid it as it crossed them.
ChipGlide(LAYERS.indexOf(layer), local, tint, GlideAxis.Vertical, corner = 12.dp)
}
if (!narrow) {
Spacer(Modifier.width(16.dp))
@@ -1106,17 +1105,14 @@ private fun LayerCard(
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
// The stack's glide draws the picked card's look by touch only; with a pad, its rest look and the bar.
val under = selected && androidx.compose.ui.platform.LocalInputModeManager.current.inputMode != androidx.compose.ui.input.InputMode.Keyboard
Box(Modifier.fillMaxWidth().heightIn(min = 44.dp), contentAlignment = Alignment.Center) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier.fillMaxWidth().height(40.dp)
.landingPop(landed).pulseRing(ring, pal.signal)
.clip(LAYER_SHAPE)
.background(if (under) Color.Transparent else colors.surface)
.shownBar(selected, pal.signal, vertical = true)
.glideBorder(hot, LAYER_SHAPE, pal.signal, if (under) Color.Transparent else pal.line)
.background(if (selected) Color.Transparent else colors.surface)
.glideBorder(hot, LAYER_SHAPE, pal.signal, if (selected) Color.Transparent else pal.line)
.onFocusChanged { if (it.isFocused) onFocus() }
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.background
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
@@ -43,11 +42,6 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.runtime.snapshotFlow
import kotlinx.coroutines.flow.first
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
@@ -90,19 +84,11 @@ fun DriverPage(
// D-pad: up from the first driver lands on refresh; the page opens with the driver in use focused.
val refreshFocus = remember { FocusRequester() }
val selectedFocus = remember { FocusRequester() }
val inputMode = LocalInputModeManager.current
var pageFocused by remember { mutableStateOf(false) }
LaunchedEffect(inputMode.inputMode) {
if (inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
// The chooser holds controller focus until its closing animation finishes.
snapshotFlow { Steps.step }.first { it == null }
focusWithinFrames({ pageFocused }) { selectedFocus }
}
LaunchedEffect(Unit) { runCatching { selectedFocus.requestFocus() } }
val refreshSrc = remember { MutableInteractionSource() }
val refreshHot = refreshSrc.collectIsFocusedAsState().value || refreshSrc.collectIsHoveredAsState().value
SettingsPage(
host, title = title, onBack = onBack, lede = "$hint\n$status",
modifier = Modifier.onFocusChanged { pageFocused = it.hasFocus }.focusGroup(),
action = {
Box(
contentAlignment = Alignment.Center,
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui
import android.view.View
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
@@ -22,7 +23,6 @@ import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
@@ -58,8 +58,6 @@ internal class GlideSource {
var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape)
var color by mutableStateOf(Color.Transparent)
var width by mutableStateOf(2.dp)
/** Focuses the control again: a step-out hands focus back to the control it came out of. */
val requester = androidx.compose.ui.focus.FocusRequester()
}
internal class FocusGlide(val view: View) {
@@ -137,18 +135,15 @@ internal fun Modifier.glideBorder(
onDispose { glide.release(src) }
}
val base = if (restColor.alpha > 0f) border(restWidth, restColor, shape) else this
return base.focusRequester(src.requester).onGloballyPositioned { src.coords = it; glide.moved(src) }
return base.onGloballyPositioned { src.coords = it; glide.moved(src) }
}
/** Leading edge on a focus move: quick and a little loose. */
/** A spring an edge chases its target on: damping ratio and stiffness, as Compose's. */
private class Edge(val damping: Float, val stiffness: Float)
private fun lead() = Edge(0.62f, 700f)
private fun lead(): AnimationSpec<Float> = Motion.sp(0.62f, 700f)
/** Trailing edge: slower, settles without a bounce to speak of. */
private fun trail() = Edge(0.78f, 360f)
private fun trail(): AnimationSpec<Float> = Motion.sp(0.78f, 360f)
/** Following a control that moves under the ring (a scroll): tight, no wobble. */
private fun follow() = Edge(1f, 2400f)
private fun follow(): AnimationSpec<Float> = Motion.sp(1f, 2400f)
/** How long after a focus move the ring keeps its stretchy springs and keeps checking where it is. */
private const val SETTLE_MS = 450L
@@ -157,9 +152,6 @@ private const val STILL_MS = 120L
/** The longest the ring keeps checking after a move, for a control that never stands still. */
private const val TRACK_MAX_MS = 2_000L
/** How strongly the ring tints what it holds. */
private const val RING_FILL = 0.14f
/** Moves closer together than this are a held direction: the ring runs along as one, no stretch. */
private const val REPEAT_MS = 180L
@@ -182,16 +174,8 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
val solid = remember { Animatable(0f) }
val alpha = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
// An edge each, the corner, a droplet carrying all of them, its solid fill, and the chase.
val jobs = remember { arrayOfNulls<Job>(8) }
// The chase: each edge on a spring of its own toward where focus is now. A new target only
// moves where it is heading - restarting an animation on every focus move started it from
// its first frame (which does not move), so a held direction over a busy page (each rail item
// swaps the page) left the ring standing while focus ran on ahead.
val target = remember { FloatArray(4) }
val vel = remember { FloatArray(4) }
val springs = remember { Array(4) { follow() } }
val startAt = remember { LongArray(4) }
// An edge each, the corner, and a droplet carrying all of them.
val jobs = remember { arrayOfNulls<Job>(6) }
val cur = glide.current
var lastColor by remember { mutableStateOf(Color.Transparent) }
if (cur != null) lastColor = cur.color
@@ -202,53 +186,20 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
LaunchedEffect(glide, Motion.scale) {
var shown: GlideSource? = null
var movedAt = 0L
var dirSpecs: List<Edge> = List(4) { follow() }
var dirSpecs: List<AnimationSpec<Float>> = List(4) { follow() }
var delays = LongArray(4)
var lastMove = 0L
fun go(i: Int, v: Float, spec: Edge, wait: Long) {
fun go(i: Int, v: Float, spec: AnimationSpec<Float>, wait: Long) {
// A drop cut short by another move turns back into an outline on the way.
if (jobs[5]?.isActive == true || solid.targetValue > 0f) {
jobs[5]?.cancel()
jobs[6]?.cancel()
jobs[6] = scope.launch { solid.animateTo(0f, Motion.tw(120)) }
}
val chasing = jobs[7]?.isActive == true
// An edge some other animation was moving (the appear, a drop's opening) is taken over
// at the speed it was going.
jobs[i]?.let { if (it.isActive) { it.cancel(); vel[i] = edges[i].velocity } }
if (!chasing) for (j in 0..3) if (jobs[j]?.isActive != true) vel[j] = edges[j].velocity
target[i] = v
springs[i] = spec
startAt[i] = System.nanoTime() + Motion.ms(wait.toInt()) * 1_000_000L
if (chasing) return
jobs[7] = scope.launch {
var last = withFrameNanos { it }
while (true) {
val frame = withFrameNanos { it }
// Real time, however long the frame took, in small steps so a stiff spring holds.
val dt = ((frame - last) / 1e9f).coerceAtMost(0.1f) / Motion.scale.coerceAtLeast(0.01f)
last = frame
val now = System.nanoTime()
var settled = true
for (j in 0..3) {
if (now < startAt[j]) { settled = false; continue }
val k = springs[j].stiffness
val c = 2f * springs[j].damping * kotlin.math.sqrt(k)
var x = edges[j].value
var u = vel[j]
var left = dt
while (left > 0f) {
val h = minOf(left, 0.004f)
u += (-k * (x - target[j]) - c * u) * h
x += u * h
left -= h
}
if (abs(x - target[j]) < 0.3f && abs(u) < 3f) { x = target[j]; u = 0f } else settled = false
vel[j] = u
edges[j].snapTo(x)
}
if (settled) break
}
if (jobs[5]?.isActive == true || solid.targetValue > 0f) scope.launch { solid.animateTo(0f, Motion.tw(120)) }
jobs[5]?.cancel()
// Picks up the speed it is going at: restarting from rest on every step of a held
// direction is what made it stutter.
val speed = edges[i].velocity
jobs[i]?.cancel()
jobs[i] = scope.launch {
if (wait > 0) delay(Motion.ms(wait.toInt()).toLong())
edges[i].animateTo(v, spec, initialVelocity = if (wait > 0) 0f else speed)
}
}
/** Pinch into a solid dot where it is, carry it over, and open it into [b] as it arrives. */
@@ -319,8 +270,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
// Focus passing between two controls can let go of one a moment before the next
// takes it: wait a beat, so that reads as a move and not a fade out and back in.
delay(60)
jobs.forEach { it?.cancel() }
solid.snapTo(0f)
scope.launch { alpha.animateTo(0f, Motion.tw(140)) }
shown = null
return@collectLatest
@@ -347,7 +296,7 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
jobs.forEach { it?.cancel() }
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
dirSpecs = List(4) { Edge(0.6f, 700f) }
dirSpecs = List(4) { Motion.sp(0.6f, 700f) }
delays = LongArray(4)
cornerTo(src, b, snap = true)
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
@@ -366,8 +315,8 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
if (dropped) droplet(src, b)
else {
// A held direction runs along as one piece; a single press stretches.
dirSpecs = if (held) List(4) { Edge(0.9f, 900f) }
else List(4) { i -> when (i) { leadIdx -> lead(); trailIdx -> trail(); else -> Edge(0.7f, 520f) } }
dirSpecs = if (held) List(4) { Motion.sp(0.9f, 900f) }
else List(4) { i -> when (i) { leadIdx -> lead(); trailIdx -> trail(); else -> Motion.sp(0.7f, 520f) } }
delays = LongArray(4) { i -> if (i == trailIdx && !held) 30L else 0L }
cornerTo(src, b, snap = false)
}
@@ -410,18 +359,10 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
cornerRadius = CornerRadius(corner.value), alpha = a * f,
)
if (f < 0.99f) {
// The ring's own infill: the only fill a pad sees, so it is always exactly what
// the ring holds and moves with it (a row's own sliding fill trailed it).
drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * RING_FILL,
)
drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
)
}
if (f < 0.99f) drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
)
},
) {
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
@@ -106,14 +106,14 @@ internal fun SideRail(
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
) {
// Every section on screen at once: items shrink (to 44dp, still a touch target) before the rail scrolls.
val count = 6 + (if (s.gameStoresEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0)
val count = 7 + (if (s.isHomeApp) 1 else 0)
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
// A hop in flight moves the selection ahead of the page it is bringing.
val shown = Hops.railPreview ?: selected
val keys = buildList {
add("steam"); add("games")
if (s.gameStoresEnabled) add("stores")
add("stores")
add("desktop")
add("components")
if (s.isHomeApp) add("android-apps")
@@ -145,7 +145,7 @@ internal fun SideRail(
// The game stores, right under Games: what they install lands there. Its badge counts
// the downloads in flight, so a download started here is never out of sight.
// A section switched on in Setup comes in as the rail's own entrance; off, it folds away.
if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", shown == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, place = place, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", shown == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, place = place, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", shown == "desktop", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", shown == "components", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("components") }) { onSelect("components") }
// Home mode's extra section goes last, so it shifts nothing above it.
@@ -134,7 +134,6 @@ class FrontEndState(
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val launcherFullscreen: Boolean = true,
val animationsEnabled: Boolean = true,
val gameStoresEnabled: Boolean = true,
/** Setup › Stores: the download engine's speed tier (stores/download/StoreDownloadTier ids). */
val gameStoresSpeedTier: String = "fast",
/** Setup › Stores: the tab a signed-in store opens on (SessionPrefs.STORES_OPEN_LIBRARY / STORE). */
@@ -213,7 +212,6 @@ class FrontEndActions(
val onOrientation: (Int) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onGameStoresEnabled: (Boolean) -> Unit = {},
val onGameStoresSpeedTier: (String) -> Unit = {},
val onStoresOpenTab: (String) -> Unit = {},
val onNavigated: () -> Unit = {},
@@ -341,8 +339,6 @@ internal class FrontFocus {
/** Down from this button goes to the first tile of the page's grid, when there is one. */
@Composable
internal fun Modifier.downToFirstTile(): Modifier {
// Sheet rows walk their settings; Desktop's dock stays composed behind the sheet.
if (LocalSheetBeat.current != null) return this
val ff = LocalFrontFocus.current ?: return this
return this.focusProperties { down = if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
}
@@ -503,7 +499,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
val inputModeManager = LocalInputModeManager.current
val window = LocalWindowInfo.current
val androidContext = androidx.compose.ui.platform.LocalContext.current
var anyFocused by remember { mutableStateOf(false) }
Box(
modifier = Modifier.fillMaxSize().background(colors.background)
@@ -535,15 +530,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
if (processSettingsPageVisible) return@LaunchedEffect
// Past the old page's exit (170ms), then the first frame the new page takes focus.
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
if (s.pageKey == "performance") {
val back = "back:${androidContext.getString(R.string.mode_back)}"
focusWithinFrames({ frontFocus.last == back && anyFocused && frontFocus.focusedRail == null }) {
frontFocus.items[back] ?: FocusRequester.Default
}
return@LaunchedEffect
}
if (anyFocused) return@LaunchedEffect
if (anyFocused || inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
}
// A rail item picked with a controller moves on into its page, once the page is in.
@@ -321,6 +321,14 @@ internal fun SetupPanel(
}
}
}
SettingsGroup(stringResource(R.string.setup_account)) {
accountCheck(true)
ToggleRow(
host, "offline", stringResource(R.string.setup_offline),
s.offlineAccount?.let { if (it.isEmpty()) stringResource(R.string.setup_signed_in_unnamed) else stringResource(R.string.setup_signed_in, it) } ?: stringResource(R.string.setup_sign_in_first),
s.offline, enabled = s.offlineAccount != null,
) { a.onOffline() }
}
SettingsGroup(stringResource(R.string.setup_runtime)) { runtimeCheck(false) }
}
1 -> {
@@ -358,7 +366,6 @@ internal fun SetupPanel(
ToggleRow(host, "launcher-animations", stringResource(R.string.setup_animations), null,
s.animationsEnabled, onChange = a.onAnimationsEnabled)
LanguageRow(host, s.language, a.onLanguage)
ToggleRow(host, "show-stores", stringResource(R.string.setup_stores), null, s.gameStoresEnabled, onChange = a.onGameStoresEnabled)
}
}
val device: @Composable () -> Unit = {
@@ -37,14 +37,10 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.ui.platform.testTag
import kotlinx.coroutines.Job
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -130,12 +126,12 @@ internal object SheetTab {
/**
* Where the open sheet's top edge sits in a pane [paneH] tall (px), for a button [buttonH] tall
* riding it: 60dp down a 360dp pane, the same share of any other, and never so high that the
* riding it: 82dp down a 360dp pane, the same share of any other, and never so high that the
* button's top comes closer than [minAbove] to the pane's. [ride] is how far below the edge the
* button's centre sits.
*/
internal fun sheetTop(paneH: Float, buttonH: Float, minAbove: Float, ride: Float): Float =
maxOf(paneH * 60f / 360f, minAbove + buttonH / 2f - ride)
maxOf(paneH * 82f / 360f, minAbove + buttonH / 2f - ride)
/** A finger's hold on the sheet: where it started (0 rest, 1 open), where it is, whether it has it. */
private class SheetDrag {
@@ -232,7 +228,6 @@ internal fun LiftHero(
// Set as a finger's drag lets go: the sheet is already where it is going.
var dragSettled by remember { mutableStateOf(false) }
val scope = androidx.compose.runtime.rememberCoroutineScope()
var dragJob by remember { mutableStateOf<Job?>(null) }
val onOpenNow = rememberUpdatedState(onOpen)
val pull = remember { Animatable(0f) }
val sink = remember { Animatable(0f) }
@@ -248,8 +243,6 @@ internal fun LiftHero(
val playSrc = remember { MutableInteractionSource() }
val playHovered by playSrc.collectIsHoveredAsState()
var playFocused by remember { mutableStateOf(false) }
// Set as a pad leaves the sheet to the left for Play, which folds it once Play has focus.
val leftForPlay = remember { booleanArrayOf(false) }
var heroAt by remember { mutableStateOf(Offset.Zero) }
var rest by remember { mutableStateOf<Rect?>(null) }
fun focusPlay() { if (ff != null && inputMode.inputMode == InputMode.Keyboard) runCatching { ff.primary.requestFocus() } }
@@ -280,7 +273,6 @@ internal fun LiftHero(
onDispose { lifecycle.removeObserver(obs) }
}
LaunchedEffect(open, launching) {
if (!dragSettled) { dragJob?.cancel(); dragJob = null }
if (dragSettled) {
// A finger brought it here and has already animated it: only what opening needs.
dragSettled = false
@@ -352,9 +344,6 @@ internal fun LiftHero(
}
}
BackHandler(enabled = open && !launching) { close() }
// The ring keeps out of the lift and the fold, and comes back on whatever has focus once
// they are done: Play rides the sheet on a layer, and the ring hung where Play had been.
if (ride.isRunning || (shown && !open)) VeilRing()
val openNow = open || shown
LaunchedEffect(openNow) { onOpenChange(openNow) }
@@ -389,8 +378,6 @@ internal fun LiftHero(
}
/** A finger takes the sheet where it is: up from rest, or down from open. */
fun beginDrag() {
dragJob?.cancel(); dragJob = null
dragSettled = false
drag.engaged = true
drag.from = if (open) 1f else 0f
drag.progress = drag.from
@@ -414,8 +401,7 @@ internal fun LiftHero(
else -> drag.progress > 0.3f
}
dragSettled = true
dragJob?.cancel()
dragJob = scope.launch {
scope.launch {
val to = if (opens) 1f else 0f
coroutineScope {
launch { lift.animateTo(to, Motion.sp(if (opens) 0.7f else 1f, 380f)) }
@@ -559,8 +545,8 @@ internal fun LiftHero(
onPrevious = { if (tab > 0) { travel = -1; tab--; runCatching { chipFocus[tab].requestFocus() } } },
onNext = { if (tab < tabs.lastIndex) { travel = 1; tab++; runCatching { chipFocus[tab].requestFocus() } } },
)
// A pad stays in the sheet until it folds; Left from it reaches Play, the handle, and folds it.
.focusProperties { exit = { dir -> if (!openState.value || launchingState.value) FocusRequester.Default else if (dir == FocusDirection.Left && ff != null) { leftForPlay[0] = true; ff.primary } else FocusRequester.Cancel } }
// A pad stays in the sheet until it folds; Left from it reaches Play, the handle.
.focusProperties { exit = { dir -> if (!openState.value || launchingState.value) FocusRequester.Default else if (dir == FocusDirection.Left && ff != null) ff.primary else FocusRequester.Cancel } }
.focusGroup(),
) {
Box(
@@ -568,7 +554,7 @@ internal fun LiftHero(
.offset { IntOffset(chipsX.roundToInt(), chipsY.roundToInt()) }
// Over the rows, whatever they scroll under them.
.zIndex(1f)
.width(with(density) { (sheetW - chipsX - 64.dp.toPx()).coerceAtLeast(0f).toDp() })
.width(with(density) { (sheetW - chipsX - 16.dp.toPx()).coerceAtLeast(0f).toDp() })
.graphicsLayer { val v = pieces[0].value; alpha = v; translationY = (1f - v) * 6.dp.toPx() }
// Up from the chips folds the sheet (a finger drags it down, see the hero's drag).
.onPreviewKeyEvent { e ->
@@ -610,18 +596,6 @@ internal fun LiftHero(
}
}
}
val closeSource = remember { MutableInteractionSource() }
val closeHot = rememberHot(closeSource)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.offset { IntOffset((sheetW - 52.dp.toPx()).roundToInt(), chipsY.roundToInt()) }
.zIndex(1f).size(44.dp).testTag("sheet-close")
.clip(CircleShape).glideBorder(closeHot, CircleShape, pal.signal)
.hoverable(closeSource)
.clickable(interactionSource = closeSource, indication = LocalIndication.current, enabled = open && !launching, role = Role.Button) { close() }
.controllerConfirm(enabled = open && !launching) { close() },
) { Icon(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
}
@@ -634,11 +608,7 @@ internal fun LiftHero(
Modifier
.onGloballyPositioned { rest = it.boundsInRoot() }
.graphicsLayer { translationY = raise * ride.value }
.onFocusChanged {
// Left out of the sheet (from the chips or a row) folds it, as Up from the chips does.
if (it.hasFocus && leftForPlay[0]) { leftForPlay[0] = false; if (openState.value && !launchingState.value) close() }
playFocused = it.hasFocus
}
.onFocusChanged { playFocused = it.hasFocus }
.hoverable(playSrc)
.onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
@@ -673,15 +643,15 @@ internal fun LiftHero(
// A lip a pad can reach stays composed (unseen at rest) so Down always has it to land on.
if (r0 != null && (lipShow.value > 0.01f || pull.value > 0.5f || (!downOpens && !open && !shown))) {
var handleW by remember { mutableStateOf(0f) }
val lipH = 32.dp + pull.value.dp
val lipH = 22.dp + pull.value.dp
val lift = { if (!open) open = true }
Box(
Modifier
.offset { IntOffset((r0.center.x - handleW / 2f).roundToInt(), (r0.bottom + raise * ride.value + (lipShow.value - 1f) * 8.dp.toPx()).roundToInt()) }
.onSizeChanged { handleW = it.width.toFloat() }
.graphicsLayer { alpha = lipShow.value * (1f - lipGone.value) }
// 44dp to touch, with a 32dp visible handle.
.heightIn(min = 44.dp).testTag("sheet-open")
// 44dp to touch; the tab itself is the top 22.
.heightIn(min = 44.dp)
.semantics { contentDescription = settingsLabel }
.then(
if (downOpens) Modifier.focusProperties { canFocus = false }
@@ -728,7 +698,7 @@ private fun Handle(height: Dp) {
.drawBorderSidesAndFoot(pal.line, 12.dp)
.padding(start = 14.dp, end = 10.dp),
) {
Text(stringResource(R.string.drawer_page_settings), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant, maxLines = 1)
Text(stringResource(R.string.drawer_page_settings), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant, maxLines = 1)
Icon(
Icons.Filled.KeyboardArrowUp, null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(16.dp).graphicsLayer { translationY = if (still) 0f else -3.dp.toPx() * lift },
@@ -755,11 +725,9 @@ private fun Modifier.drawBorderSidesAndFoot(color: Color, corner: Dp): Modifier
/**
* The sheet's chips: equal capsules with one selection gliding under them (the stores' chip row),
* LB and RB a chip at a time, a tap or A on a far one a hop as a drop. A pad picks a chip by
* moving onto it, and comes into the row on the picked one. [first] takes focus as the sheet
* opens. Too narrow for equal chips, the row scrolls.
* LB and RB a chip at a time, a tap or A on a far one a hop as a drop. [first] takes focus as the
* sheet opens. Too narrow for equal chips, the row scrolls.
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun SheetChips(labels: List<String>, selected: Int, focus: List<FocusRequester>? = null, onPick: (Int) -> Unit) {
val pal = LocalPalette.current
@@ -775,22 +743,15 @@ internal fun SheetChips(labels: List<String>, selected: Int, focus: List<FocusRe
val scroll = rememberScrollState()
// Room inside the scroll for the focus ring, which the scroll's clip would otherwise cut.
Box(if (equal) Modifier.fillMaxWidth() else Modifier.edgeFade(scroll).horizontalScroll(scroll).padding(3.dp)) {
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp),
// Up from the rows lands on the picked chip, not whichever sits above: landing picks.
modifier = (if (equal) Modifier.fillMaxWidth() else Modifier)
.focusProperties { enter = { chips.getOrNull(selected) ?: FocusRequester.Default } }
.focusGroup(),
) {
ChipGlide(selected, bounds[selected], tint)
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = if (equal) Modifier.fillMaxWidth() else Modifier) {
labels.forEachIndexed { i, label ->
val m = (if (equal) Modifier.weight(1f) else Modifier.widthIn(min = 64.dp))
.onGloballyPositioned { bounds[i] = it.boundsInParent() }
.focusRequester(chips[i])
SheetChip(label, i == selected, m.onFocusChanged { if (it.isFocused && i != selected) onPick(i) }) { onPick(i) }
SheetChip(label, i == selected, m) { onPick(i) }
}
}
// Over the chips: under them, their rest fill hid it as it crossed them.
ChipGlide(selected, bounds[selected], tint)
}
}
}
@@ -802,15 +763,11 @@ private fun SheetChip(label: String, on: Boolean, modifier: Modifier, onClick: (
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(99.dp)
// The row's glide draws the picked chip's look by touch only; with a pad it draws its own rest
// look, and the bar says which is picked.
val under = on && LocalInputModeManager.current.inputMode != InputMode.Keyboard
Box(
contentAlignment = Alignment.Center,
modifier = modifier.heightIn(min = 44.dp).clip(shape)
.background(if (under) Color.Transparent else colors.surfaceVariant.copy(alpha = 0.5f))
.shownBar(on, pal.signal)
.glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line)
.background(if (on) Color.Transparent else colors.surfaceVariant.copy(alpha = 0.5f))
.glideBorder(hot, shape, pal.signal, if (on) Color.Transparent else pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
@@ -159,7 +159,7 @@ class ModeSettingsActions(
* Session (its Files chip is the Desktop page's own).
*/
internal fun modeSheetTabs(steam: Boolean): List<String> =
if (steam) listOf(SheetTab.STEAM, SheetTab.DISPLAY, SheetTab.CONTROLS, SheetTab.AUDIO, SheetTab.SESSION, SheetTab.LIBRARY)
if (steam) listOf(SheetTab.DISPLAY, SheetTab.CONTROLS, SheetTab.AUDIO, SheetTab.SESSION, SheetTab.LIBRARY, SheetTab.STEAM)
else listOf(SheetTab.DISPLAY, SheetTab.CONTROLS, SheetTab.SESSION)
/** A sheet tab's chip label. */
@@ -182,8 +182,6 @@ class SheetExtras(
val frameGen: @Composable () -> Unit = {},
val performance: @Composable () -> Unit = {},
val drivers: @Composable (summary: String?) -> Unit = {},
/** The Steam tab's account rows (offline mode), from the front end's own state. */
val account: @Composable (host: MenuHost) -> Unit = {},
)
/** One tab of a mode's lifted sheet: the rows the settings page had, grouped by what they are for. */
@@ -362,7 +360,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
}
}
if (tab == SheetTab.STEAM && steam) {
extras.account(host)
SettingsGroup(stringResource(R.string.mode_decky)) {
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
s.deckyInstalled != s.deckyLatestRelease.tag
@@ -477,7 +474,7 @@ internal fun ProtonOptions(
onSyncBackend: (String) -> Unit, onFexPreset: (String) -> Unit, onForceSsbs: (Boolean) -> Unit,
) {
val host = rememberMenuHost()
SettingsRow(stringResource(R.string.sync_backend_title), stringResource(R.string.sync_backend_hint), stacked = true) {
SettingsRow(stringResource(R.string.sync_backend_title), stringResource(R.string.sync_backend_hint)) {
SegmentedTabs(
listOf(
SessionPrefs.SYNC_NTSYNC to stringResource(R.string.sync_backend_ntsync),
@@ -30,9 +30,7 @@ import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import kotlinx.coroutines.coroutineScope
@@ -111,14 +109,6 @@ internal fun PageFlood(
/** What the tile shows instead of the control's fill: a game card's art, cropped to the tile as it grows. */
art: Painter? = null,
sinks: Boolean = false,
/**
* Where on the page the control's tile lands (root px), when the page has its own picture of
* the control - a game page's hero art: the tile grows onto it instead of over the whole pane,
* corner to corner ([ontoCorner] there), and the page comes in around it. Back leaves from it.
* Null, or off screen: the pane, as any page.
*/
onto: (() -> Rect?)? = null,
ontoCorner: androidx.compose.ui.unit.Dp = 0.dp,
content: @Composable () -> Unit,
) {
val pal = LocalPalette.current
@@ -128,10 +118,6 @@ internal fun PageFlood(
val shown = remember { Animatable(0f) }
val tile = remember { Animatable(1f) }
var size by remember { mutableStateOf(Size.Zero) }
var at by remember { mutableStateOf(Offset.Zero) }
// Where this flood lands (in its own space), read as it opens and again as it leaves.
var target by remember { mutableStateOf<Rect?>(null) }
val density = androidx.compose.ui.platform.LocalDensity.current
LaunchedEffect(size != Size.Zero, leaving, sinks) {
if (sinks) {
// Whatever the flood in was doing, the page is shown whole and leaves with the pane.
@@ -142,30 +128,6 @@ internal fun PageFlood(
}
if (size == Size.Zero) return@LaunchedEffect
glide?.hidden = true
// The page lays out under the tile at once, so its picture is there within a frame or two.
target = onto?.let { get ->
kotlinx.coroutines.withTimeoutOrNull(300) { snapshotFlow { get() }.first { it != null } }
}?.translate(-at)?.takeIf { it.height > 1f && it.overlaps(Rect(Offset.Zero, size)) }
if (target != null) {
coroutineScope {
if (!leaving) {
// Onto the page's picture, every edge together on one firm spring: no blob, and
// nowhere to go past it.
val runs = edges.map { launch { it.animateTo(1f, Motion.sp(0.85f, 320f)) } }
snapshotFlow { edges.all { it.value >= 0.9f } }.first { it }
launch { shown.animateTo(1f, Motion.tw(240)) }
launch { delay(Motion.ms(140).toLong()); tile.animateTo(0f, Motion.tw(220)) }
runs.forEach { it.join() }
} else {
launch { shown.animateTo(0f, Motion.tw(160)) }
tile.animateTo(1f, Motion.tw(120))
edges.map { launch { it.animateTo(0f, Motion.sp(0.9f, 320f)) } }.forEach { it.join() }
tile.animateTo(0f, Motion.tw(120))
}
}
glide?.hidden = false
return@LaunchedEffect
}
val b = from.bounds
val travel = listOf(b.left, b.top, size.width - b.right, size.height - b.bottom).map { it.coerceAtLeast(0f) }
val far = travel.max().coerceAtLeast(1f)
@@ -198,16 +160,10 @@ internal fun PageFlood(
glide?.hidden = false
}
DisposableEffect(Unit) { onDispose { glide?.hidden = false } }
Box(
Modifier.fillMaxSize().clipToBounds().onSizeChanged { size = Size(it.width.toFloat(), it.height.toFloat()) }
.onGloballyPositioned { at = it.positionInRoot() },
) {
// Landing on the page's picture, the page must not rise: its picture would move off the tile.
val rise = if (onto != null) 0f else 1f
Box(Modifier.fillMaxSize().graphicsLayer { alpha = shown.value; translationY = (1f - shown.value) * 14.dp.toPx() * rise }) { content() }
val onCorner = with(density) { ontoCorner.toPx() }
Box(Modifier.fillMaxSize().clipToBounds().onSizeChanged { size = Size(it.width.toFloat(), it.height.toFloat()) }) {
Box(Modifier.fillMaxSize().graphicsLayer { alpha = shown.value; translationY = (1f - shown.value) * 14.dp.toPx() }) { content() }
Canvas(Modifier.fillMaxSize()) {
if (tile.value > 0.01f) drawTile(from, edges.map { it.value }, pal.surface, pal.line2, tile.value, art, target, onCorner)
if (tile.value > 0.01f) drawTile(from, edges.map { it.value }, pal.surface, pal.line2, tile.value, art)
}
}
}
@@ -216,33 +172,22 @@ internal fun PageFlood(
* The control's tile with its edges [v] of the way to the pane's (left, top, right, bottom):
* sinking with the page behind, blobby in flight, square once it fills the pane.
*/
private fun DrawScope.drawTile(
from: Origin, v: List<Float>, fill: Color, line: Color, alpha: Float, art: Painter? = null,
/** Lands on this instead of the pane (a page's picture of the control), corner [toCorner]. */
to: Rect? = null, toCorner: Float = 0f,
) {
private fun DrawScope.drawTile(from: Origin, v: List<Float>, fill: Color, line: Color, alpha: Float, art: Painter? = null) {
val (l, t, r, b) = v
val mean = v.sumOf { it.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
// The control sinks with the page behind it (scaled to 0.95 about the pane's centre).
val k = 1f - 0.05f * mean
val cx = size.width / 2f
val cy = size.height / 2f
val f = from.bounds
val left: Float; val top: Float; val right: Float; val bottom: Float
if (to != null) {
left = lerp(f.left, to.left, l); top = lerp(f.top, to.top, t)
right = lerp(f.right, to.right, r); bottom = lerp(f.bottom, to.bottom, b)
} else {
// The control sinks with the page behind it (scaled to 0.95 about the pane's centre).
val k = 1f - 0.05f * mean
val cx = size.width / 2f
val cy = size.height / 2f
left = lerp(cx + (f.left - cx) * k, 0f, l)
top = lerp(cy + (f.top - cy) * k, 0f, t)
right = lerp(cx + (f.right - cx) * k, size.width, r)
bottom = lerp(cy + (f.bottom - cy) * k, size.height, b)
}
val left = lerp(cx + (f.left - cx) * k, 0f, l)
val top = lerp(cy + (f.top - cy) * k, 0f, t)
val right = lerp(cx + (f.right - cx) * k, size.width, r)
val bottom = lerp(cy + (f.bottom - cy) * k, size.height, b)
val w = (right - left).coerceAtLeast(0f)
val h = (bottom - top).coerceAtLeast(0f)
// Onto a picture it keeps a card's shape, corner to corner; over the pane it blobs in flight.
val corner = if (to != null) lerp(from.corner, toCorner, mean).coerceAtMost(minOf(w, h) / 2f)
else lerp(from.corner * (1f - mean), minOf(w, h) * 0.42f, sin(PI * mean).toFloat().coerceAtLeast(0f))
val blob = sin(PI * mean).toFloat().coerceAtLeast(0f)
val corner = lerp(from.corner * (1f - mean), minOf(w, h) * 0.42f, blob)
drawRoundRect(fill, Offset(left, top), Size(w, h), CornerRadius(corner), alpha = alpha)
val pic = art?.intrinsicSize?.takeIf { it.isSpecified && it.width > 0f && it.height > 0f }
if (art != null && pic != null && w > 0f && h > 0f) {
@@ -443,7 +443,7 @@ fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable
* under it stay put.
*/
@Composable
fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, control: @Composable () -> Unit) {
fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, control: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val bg by animateColorAsState(if (highlighted) pal.signal.copy(alpha = 0.10f) else Color.Transparent, Motion.tw(200), label = "rowBg")
@@ -452,7 +452,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis)
}
// A narrow page stacks the control under its label, so neither squeezes the other.
if (stacked || LocalNarrowPane.current) Column(
if (LocalNarrowPane.current) Column(
modifier = Modifier.fillMaxWidth().background(bg).padding(start = 14.dp, end = 14.dp, top = 11.dp, bottom = 12.dp),
) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
@@ -13,10 +13,8 @@ import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
@@ -46,10 +44,9 @@ internal enum class GlideAxis { Horizontal, Vertical }
/**
* The selection under a row of chips: [at] (in the row) of chip [index], in [tint]. A move to the
* next chip stretches it - the leading edge on the focus ring's lead spring, the trailing one a
* beat later on its trail spring - and a hop past chips stretches the same way, across them.
* Draw it over the chips: under them, their own rest fill hid it in flight. [axis] runs it down a column instead (the rail, a stack of layers). [corner] is the
* chips' own corner; null draws a capsule. [fill] and [outline] are the resting alphas. Not
* [visible], it fades away, and comes back on whichever chip it is on by then.
* beat later on its trail spring - and a hop past a chip pinches it to a drop, carries it and
* opens it. [axis] runs it down a column instead (the rail, a stack of layers). [corner] is the
* chips' own corner; null draws a capsule. [fill] and [outline] are the resting alphas.
*/
@Composable
internal fun BoxScope.ChipGlide(
@@ -60,25 +57,17 @@ internal fun BoxScope.ChipGlide(
corner: Dp? = null,
fill: Float = 0.16f,
outline: Float = 0.7f,
visible: Boolean = true,
) {
val density = androidx.compose.ui.platform.LocalDensity.current
// The two edges along the axis (left and right, or top and bottom), and the two across it.
val start = remember { Animatable(Float.NaN) }
val end = remember { Animatable(0f) }
val pinch = remember { Animatable(0f) }
// With a pad the focus ring fills what it holds, and is the only fill: a selection of the
// row's own, sliding on its own beat, trailed the ring and sat on items the pad had left.
val pad = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode == androidx.compose.ui.input.InputMode.Keyboard
@Suppress("NAME_SHADOWING") val visible = visible && !pad
val shown = remember { Animatable(if (visible) 1f else 0f) }
val visibleNow = rememberUpdatedState(visible)
LaunchedEffect(visible) { shown.animateTo(if (visible) 1f else 0f, Motion.tw(if (visible) 160 else 120)) }
val crossStart = remember { mutableStateOf(0f) }
val crossEnd = remember { mutableStateOf(0f) }
val was = remember { intArrayOf(-1) }
val vertical = axis == GlideAxis.Vertical
LaunchedEffect(index, at, Motion.scale) {
LaunchedEffect(index, at) {
val b = at ?: return@LaunchedEffect
val s = if (vertical) b.top else b.left
val e = if (vertical) b.bottom else b.right
@@ -87,21 +76,18 @@ internal fun BoxScope.ChipGlide(
val from = was[0]
was[0] = index
if (start.value.isNaN() || from == index || from < 0 || Motion.scale == 0f) {
start.snapTo(s); end.snapTo(e); pinch.snapTo(0f)
if (visibleNow.value) shown.snapTo(1f)
return@LaunchedEffect
}
// Away or on its way back: it goes straight to the chip, unseen.
if (!visibleNow.value || shown.value < 0.5f) {
start.snapTo(s); end.snapTo(e); pinch.snapTo(0f)
return@LaunchedEffect
}
coroutineScope {
run {
// Every move stretches across, however far: a long one used to go as a drop (which
// sat on chips already left) and then as a fade (a flash of no fill at all).
launch { pinch.animateTo(0f, Motion.sp(0.6f, 500f)) }
launch { shown.animateTo(1f, Motion.tw(120)) }
if (abs(index - from) > 1) {
// Too far to stretch: pinch into a drop where it is, carry it over, open it there.
pinch.animateTo(1f, Motion.tw(90))
val l = launch { start.animateTo(s, Motion.sp(0.7f, 380f)) }
val r = launch { end.animateTo(e, Motion.sp(0.7f, 380f)) }
l.join(); r.join()
pinch.animateTo(0f, Motion.sp(0.6f, 500f))
} else {
val forward = index > from
val (lead, trail) = if (forward) end to start else start to end
val leadTo = if (forward) e else s
@@ -120,42 +106,19 @@ internal fun BoxScope.ChipGlide(
val round = minOf(size.width, size.height) / 2f
val r = CornerRadius(corner?.let { lerp(minOf(with(density) { it.toPx() }, round), round, p) } ?: round)
// A drop in flight is solid; on a chip it is the chip's tinted fill and outline.
val a = shown.value
drawRoundRect(tint.value.copy(alpha = lerp(fill, 0.9f, p) * a), at0, size, r)
drawRoundRect(tint.value.copy(alpha = lerp(fill, 0.9f, p)), at0, size, r)
if (outline > 0f) {
// Inside the chip's edge: a stroke on it would lose its outer half to a scrolling row's clip.
val w = with(density) { 1.dp.toPx() }
val inset = w / 2f
drawRoundRect(
tint.value.copy(alpha = outline * (1f - p) * a), at0 + Offset(inset, inset), Size(size.width - w, size.height - w),
tint.value.copy(alpha = outline * (1f - p)), at0 + Offset(inset, inset), Size(size.width - w, size.height - w),
CornerRadius((r.x - inset).coerceAtLeast(0f)), style = Stroke(w),
)
}
}
}
/**
* The chosen one of a row of chips (or a column, [vertical]): a short bar of [color] along its foot
* (or its start edge). Not a fill or an outline, so it never reads as focus; with a pad the ring's
* own infill is the only fill. Goes inside the chip's clip.
*/
@Composable
internal fun Modifier.shownBar(on: Boolean, color: Color, vertical: Boolean = false): Modifier {
val shown = androidx.compose.animation.core.animateFloatAsState(if (on) 1f else 0f, Motion.tw(if (on) 140 else 100), label = "shownBar").value
return drawWithContent {
drawContent()
if (shown <= 0.01f) return@drawWithContent
val t = 3.dp.toPx()
if (vertical) {
val l = size.height * 0.5f
drawRect(color, Offset(0f, (size.height - l) / 2f), Size(t, l), alpha = shown)
} else {
val w = size.width * 0.36f
drawRect(color, Offset((size.width - w) / 2f, size.height - t), Size(w, t), alpha = shown)
}
}
}
/**
* Where a glide's shape is: its edges along the axis at [start] and [end] (either order), across
* it from [crossStart] to [crossEnd], pinched [pinch] of the way (0 to 1) into a drop [drop] each
@@ -92,16 +92,6 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
frameGen = { FrameGenGroup(s, a) },
performance = { PerformanceLink(a, "steam", SheetTab.SESSION) },
drivers = { summary -> DriversLink(a, summary, "steam", back) },
// Offline mode lives with Steam's other settings; Setup only checks the account.
account = { host ->
SettingsGroup(stringResource(R.string.setup_account)) {
ToggleRow(
host, "offline", stringResource(R.string.setup_offline),
s.offlineAccount?.let { if (it.isEmpty()) stringResource(R.string.setup_signed_in_unnamed) else stringResource(R.string.setup_signed_in, it) } ?: stringResource(R.string.setup_sign_in_first),
s.offline, enabled = s.offlineAccount != null,
) { a.onOffline() }
}
},
)
LiftHero(
key = "steam", tabs = tabs,
@@ -7,8 +7,6 @@ import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
@@ -135,7 +133,7 @@ internal enum class StepSide {
}
/** The choices' side of a [StepOut]: each piece fades in on its own beat, and [first] takes focus. */
internal class StepOutScope(private val items: List<Animatable<Float, AnimationVector1D>>, val first: FocusRequester, val open: Boolean, val maxHeight: Dp) {
internal class StepOutScope(private val items: List<Animatable<Float, AnimationVector1D>>, val first: FocusRequester, val open: Boolean) {
/** Piece [i] (0 first) of the box: it fades and rises in after the box has stepped out. */
fun Modifier.stepItem(i: Int): Modifier = graphicsLayer {
val v = items[i.coerceIn(0, items.lastIndex)].value
@@ -181,24 +179,12 @@ internal fun StepOut(
var grown by remember { mutableStateOf(false) }
var measured by remember { mutableStateOf<IntSize?>(null) }
val first = remember { FocusRequester() }
// The control focus was on as it opened: focus goes back to it as it folds, not to wherever
// the screen puts a pad with nothing focused (the rail).
val glide = LocalFocusGlide.current
val opener = remember { arrayOfNulls<GlideSource>(1) }
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
// While the box grows or folds the ring keeps out (it flew across the moving shape) and comes
// back on whatever has focus once it has settled: the first choice, or the control again.
var moving by remember { mutableStateOf(false) }
if (moving) VeilRing()
val pull = with(density) { OutPull.toPx() }
val corner = pillCorner?.let { with(density) { it.toPx() } } ?: minOf(pill.height, pill.width) / 2f
BoxWithConstraints(Modifier.fillMaxSize()) {
val hostWidth = constraints.maxWidth.toFloat()
val hostHeight = constraints.maxHeight.toFloat()
val availableHeight = with(density) {
maxOf(hostHeight - pill.bottom - pull, pill.top - pull).coerceAtLeast(44.dp.toPx()).toDp()
}
// No room under the control (a row near the foot of the screen): it steps out upward
// instead, the same outline mirrored about the control.
val up = measured?.let { pill.bottom + pull + it.height > hostHeight && pill.top - pull - it.height >= 0f } ?: false
@@ -213,7 +199,6 @@ internal fun StepOut(
val boxBottom = pill.bottom + pull + c.height
if (open) {
if (!grown) {
opener[0] = glide?.current
edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f)
pieces.forEach { it.snapTo(0f) }
grown = true
@@ -221,12 +206,8 @@ internal fun StepOut(
coroutineScope {
launch { dim.animateTo(1f, Motion.tw(260)) }
launch { tint.animateTo(1f, Motion.tw(200)) }
// Down and out together, on one spring: down first drew the control as a stick
// that then snapped out sideways.
moving = true
val down = launch { bottom.animateTo(boxBottom, Motion.sp(0.8f, 380f)) }
val across = launch { edge.animateTo(out, Motion.sp(0.8f, 380f)) }
launch { down.join(); across.join(); moving = false }
launch { bottom.animateTo(boxBottom, Motion.sp(0.7f, 380f)) }
launch { delay(Motion.ms(110).toLong()); edge.animateTo(out, Motion.sp(0.55f, 300f)) }
pieces.forEachIndexed { i, a ->
launch { delay(Motion.ms(260 + i * 55).toLong()); a.animateTo(1f, Motion.tw(220)) }
}
@@ -237,20 +218,14 @@ internal fun StepOut(
}
}
} else {
opener[0]?.let { o -> if (inputMode.inputMode == InputMode.Keyboard) runCatching { o.requester.requestFocus() } }
opener[0] = null
coroutineScope {
pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } }
launch { delay(Motion.ms(60).toLong()); dim.animateTo(0f, Motion.tw(300)) }
// In and up together on a timed ease: width first left a tall tail under the
// control, and a damped spring's tail kept a nub of it on screen.
moving = true
launch { delay(Motion.ms(60).toLong()); edge.animateTo(rest, Motion.tw(240)) }
launch { delay(Motion.ms(60).toLong()); bottom.animateTo(pill.bottom, Motion.tw(240)) }
launch { delay(Motion.ms(60).toLong()); edge.animateTo(rest, Motion.sp(1f, 420f)) }
launch { delay(Motion.ms(160).toLong()); bottom.animateTo(pill.bottom, Motion.sp(1f, 380f)) }
launch { delay(Motion.ms(200).toLong()); tint.animateTo(0f, Motion.tw(200)) }
}
grown = false
moving = false
onClosed()
}
}
@@ -276,23 +251,8 @@ internal fun StepOut(
if (side == StepSide.Left) stepPath(path, pill, edge.value, bottom.value, pill.bottom + pull, boxCorner, fillet, corner)
else stepPathRight(path, pill, edge.value, bottom.value, pill.bottom + pull, boxCorner, fillet, corner)
if (up) path.transform(Matrix().apply { this[1, 1] = -1f; this[3, 1] = pill.top + pill.bottom })
// Barely out of the control, the pull and its fillet drew a hook off the control's foot:
// the outline comes in over the first part of the way out (and goes over the last part
// of the way back), by how far along it is. A share of the way, not a distance: a box
// no wider than its control (a confirm under a full-width row) never got 24dp out, and
// was never drawn at all.
val a = measured?.let { c ->
val rest = if (side == StepSide.Left) pill.left else pill.right
val out = if (side == StepSide.Left) (pill.right - c.width).coerceAtLeast(0f) else (pill.left + c.width).coerceAtMost(hostWidth)
val down = pill.bottom + pull + c.height - pill.bottom
val across = kotlin.math.abs(out - rest)
val fd = if (down < 1f) 1f else (bottom.value - pill.bottom) / down
val fa = if (across < 1f) 1f else kotlin.math.abs(edge.value - rest) / across
((minOf(fd, fa) - 0.1f) / 0.3f).coerceIn(0f, 1f)
} ?: 0f
if (a <= 0.01f) return@Canvas
drawPath(path, lerp(hotFill, restFill, tint.value), alpha = a)
drawPath(path, accent.copy(alpha = lerpF(0.9f, 0.55f, tint.value) * a), style = Stroke(rim))
drawPath(path, lerp(hotFill, restFill, tint.value))
drawPath(path, accent.copy(alpha = lerpF(0.9f, 0.55f, tint.value)), style = Stroke(rim))
}
// The control's label rides on top, as the pull's handle.
if (grown) Box(
@@ -305,15 +265,13 @@ internal fun StepOut(
modifier = Modifier
.offset { IntOffset(x.roundToInt(), (if (up) pill.top - pull - (measured?.height ?: 0) else pill.bottom + pull).roundToInt()) }
.widthIn(min = with(density) { pill.width.toDp() }, max = with(density) { maxW.toDp() })
.heightIn(max = availableHeight)
.onSizeChanged { if (measured != it) measured = it }
.controllerBack(onDismiss)
// A pad stays in the box until it is answered or folded, as it did in Stop's dialog.
.focusProperties { exit = { if (openNow.value) FocusRequester.Cancel else FocusRequester.Default } }
.focusProperties { exit = { FocusRequester.Cancel } }
.focusGroup()
.verticalScroll(rememberScrollState())
.padding(start = 14.dp, end = 14.dp, top = 12.dp, bottom = 12.dp),
) { StepOutScope(pieces, first, open, availableHeight).content() }
) { StepOutScope(pieces, first, open).content() }
}
}
@@ -1,7 +0,0 @@
package com.droiddeck.launcher.ui
/** Vertical controller moves keep the same column, including across lazy item boundaries. */
internal fun storeGridNeighbor(index: Int, count: Int, columns: Int, direction: Int): Int? {
if (index !in 0 until count || columns < 1 || direction !in listOf(-1, 1)) return null
return (index + columns * direction).takeIf { it in 0 until count }
}
@@ -392,6 +392,7 @@ private fun FlathubChips(mode: String, modes: List<String>, installed: Int, upda
val bounds = remember { mutableStateMapOf<String, Rect>() }
val tint = rememberUpdatedState(pal.signal)
Box(Modifier.fillMaxWidth()) {
ChipGlide(modes.indexOf(mode), bounds[mode], tint)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
for (m in modes) {
key(m) {
@@ -399,8 +400,6 @@ private fun FlathubChips(mode: String, modes: List<String>, installed: Int, upda
val hot = rememberHot(src)
val shape = RoundedCornerShape(99.dp)
val on = m == mode
// Drawn by the row's glide by touch only; with a pad its own rest look and the bar.
val under = on && androidx.compose.ui.platform.LocalInputModeManager.current.inputMode != androidx.compose.ui.input.InputMode.Keyboard
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
modifier = Modifier.weight(1f).paneItem("flathub:$m")
@@ -409,9 +408,8 @@ private fun FlathubChips(mode: String, modes: List<String>, installed: Int, upda
if (m == MODE_INSTALLED) FlathubMotion.installedChip = it.boundsInRoot()
}
.heightIn(min = 44.dp).clip(shape)
.background(if (under) Color.Transparent else colors.surface)
.shownBar(on, pal.signal)
.glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line)
.background(if (on) Color.Transparent else colors.surface)
.glideBorder(hot, shape, pal.signal, if (on) Color.Transparent else pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab) { onPick(m) }
.controllerConfirm { onPick(m) }
.padding(horizontal = 12.dp, vertical = 8.dp),
@@ -430,8 +428,6 @@ private fun FlathubChips(mode: String, modes: List<String>, installed: Int, upda
}
}
}
// Over the chips: under them, their rest fill hid it as it crossed them.
ChipGlide(modes.indexOf(mode), bounds[mode], tint)
}
}
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.foundation.background
@@ -53,6 +52,8 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
val installed = StoresState.installedGame(store, id)
val download = StoresState.download("${store.id}:$id")?.takeIf { it.isActive }
// Removal asks twice: one stray press of A should not cost a download.
var confirmRemove by remember(key) { mutableStateOf(false) }
LaunchedEffect(confirmRemove) { if (confirmRemove) { kotlinx.coroutines.delay(4000); confirmRemove = false } }
val title = item?.title ?: installed?.sidecar?.title ?: id
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.padding(bottom = 12.dp)) {
@@ -60,16 +61,8 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
SourceChip(store.id)
}
}
// Out of a card, the hero holds still in its place: the card's flood lands on it, and a hero
// still rising in sat below where the flood had measured it (the art showed twice).
val hero: @Composable () -> Unit = {
androidx.compose.runtime.DisposableEffect(Unit) { onDispose { StoresMotion.heroAt = null } }
Box(
Modifier.fillMaxWidth().heightIn(min = if (narrow) 150.dp else 180.dp)
// The card it opened from floods onto this, and draws back into the card from it.
.onGloballyPositioned { StoresMotion.heroAt = it.boundsInRoot() }
.clip(Shape16).background(artBrush(hueOf(title))),
) {
Rise(1) {
Box(Modifier.fillMaxWidth().heightIn(min = if (narrow) 150.dp else 180.dp).clip(Shape16).background(artBrush(hueOf(title)))) {
val art = item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover
if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.5f to colors.background.copy(alpha = 0.55f), 1f to Color.Transparent)))
@@ -90,13 +83,10 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
// Launching, the prefix and the files belong to the Games tab, where every
// installed game has them; here an install only says it is in Steam and
// offers the one thing Games does not: removing it.
// The row keeps its shape: the chip stays, and Uninstall becomes its own
// progress in place while the files go; then the page reads Install again.
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
val gone = StoresState.uninstalling["${store.id}:$id"]
if (gone != null) SecondaryButton(stringResource(R.string.stores_uninstalling), enabled = false, progress = gone) {}
else UninstallButton(title, installed, enabled = download == null) {
StoresState.uninstall(ctx, installed) { StoresState.refresh(ctx); a.onLibraryChanged() }
SecondaryButton(if (confirmRemove) stringResource(R.string.stores_uninstall_confirm) else stringResource(R.string.stores_uninstall), enabled = download == null) {
if (!confirmRemove) confirmRemove = true
else { confirmRemove = false; StoresState.uninstall(ctx, installed) { StoresState.refresh(ctx); a.onLibraryChanged() }; onBack() }
}
}
download != null -> {
@@ -120,7 +110,6 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
}
}
}
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
// Plain text only, and nothing at all when the store sent a template key instead of words.
// A description that is only the title again (some stores fill it so) is no description.
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
@@ -130,40 +119,6 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
}
}
/**
* Uninstall that asks the way Cancel does: a confirm steps out of it, naming the game and what
* goes (its size on disk), with Keep first so a stray A does nothing.
*/
@Composable
private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.InstalledStoreGame, enabled: Boolean, onUninstall: () -> Unit) {
val colors = MaterialTheme.colorScheme
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
val heading = stringResource(R.string.stores_uninstall_title, title)
val size = com.droiddeck.launcher.stores.StoreSizes.onDisk["${game.sidecar.store.id}:${game.sidecar.id}"]
val body = if (size != null && size > 0) stringResource(R.string.stores_uninstall_body_size, formatBytes(size)) else stringResource(R.string.stores_uninstall_body)
val keep = stringResource(R.string.stores_notification_keep)
val remove = stringResource(R.string.stores_uninstall)
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
SecondaryButton(remove, enabled = enabled) {
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot() ?: return@SecondaryButton
// It starts once the confirm has folded back into the button: started at once, the button
// turned into the progress under the fold and it drew back into a control that had gone.
var confirmed = false
StoresMotion.ask(StepAsk(anchor = at, side = StepSide.Right, accent = colors.error, items = 3, pillCorner = 12.dp, maxWidth = 340.dp,
onDismiss = { if (confirmed) onUninstall() }, handle = {
Text(remove, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.error, maxLines = 1)
}) {
StepTitle(heading)
Text(body, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { StoresMotion.fold() }
StepChoice(remove, danger = true, enabled = open) { confirmed = true; StoresMotion.fold() }
}
})
}
}
}
/**
* Install (or Resume install) that says where it sits when pressed: where to install grows out of
* it, and the download it starts leaves it as a dot for the Downloads chip.
@@ -48,7 +48,6 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
@@ -94,10 +93,17 @@ import com.droiddeck.launcher.stores.formatSpeed
// The Downloads chip: one queue for the three stores, its settings and the engine log.
/** The queue. Its settings (speed tier, downloads at a time) live in the chip row's cog only. */
@Composable
internal fun StoresDownloadsPane(s: FrontEndState, a: FrontEndActions) {
DownloadList(s, a)
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 700.dp
val list: @Composable () -> Unit = { DownloadList(s, a) }
val side: @Composable () -> Unit = { DownloadSettings(s, a) }
if (wide) Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) {
Box(Modifier.weight(3f)) { list() }
Box(Modifier.weight(2f)) { side() }
} else Column { list(); side() }
}
}
@Composable
@@ -111,26 +117,10 @@ private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
var clearing by remember { mutableStateOf(false) }
// Under way on top; finished below a line whose X clears them all (rows only - a failed
// download's kept files stay until its game page's Clear).
// Under way first, then paused, then the queue in its order: a queued row sat above the one running.
val (active, finished) = entries.partition { it.isActive }.let { (on, off) ->
on.sortedWith(compareBy<DownloadEntry>({ when (it.state) { DownloadState.RUNNING -> 0; DownloadState.PAUSED -> 1; else -> 2 } }, { it.queuePosition })) to off
}
val (active, finished) = entries.partition { it.isActive }
val finishedShown = if (clearing) emptyList() else finished
// Installs that stopped without the queue knowing (the app closed or was killed): the queue
// lives in memory, so after a restart they were only on their game's page. They resume here too.
val queued = entries.mapTo(HashSet()) { it.key }
// Matched against each store's library: one not read yet (Downloads opened first) is read from
// its cache, quietly, so the rows are there without visiting the store.
val ctx = LocalContext.current
val missing = StoresState.unfinished.map { it.store }.filter { StoresState.library[it] == null }.toSet()
LaunchedEffect(missing) { missing.forEach { StoresState.backend(it)?.syncLibrary(ctx, false) } }
val interrupted = StoresState.unfinished.mapNotNull { u ->
StoresState.library[u.store]?.firstOrNull {
u.id == it.id || (u.id == null && u.folder.name == com.droiddeck.launcher.stores.StoreInstallRoot.folderName(it.title, it.id))
}
}.filter { "${it.store.id}:${it.id}" !in queued }.distinctBy { "${it.store.id}:${it.id}" }
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
AnimatedVisibility(entries.isEmpty() && interrupted.isEmpty(), enter = fadeIn(Motion.tw(300, 300)), exit = fadeOut(Motion.tw(120))) {
AnimatedVisibility(entries.isEmpty(), enter = fadeIn(Motion.tw(300, 300)), exit = fadeOut(Motion.tw(120))) {
Box(Modifier.fillMaxWidth().padding(vertical = 40.dp), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.stores_downloads_empty), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
@@ -151,11 +141,6 @@ private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
else shrinkHorizontally(Motion.tw(260), shrinkTowards = Alignment.End) + shrinkVertically(Motion.tw(300, 120)) + fadeOut(Motion.tw(200, 80))
},
) { row, _ -> DownloadCard(StoresState.download(row.key) ?: row, s, a) }
AnimatedRows(
interrupted, key = { "${it.store.id}:${it.id}" },
enter = { i, _ -> fadeIn(Motion.tw(300, 60 * i.coerceAtMost(5))) + expandVertically(Motion.tw(260)) },
exit = { _, _, _ -> fadeOut(Motion.tw(160)) + shrinkVertically(Motion.tw(220, 60)) },
) { item, _ -> InterruptedRow(item) }
AnimatedVisibility(
finishedShown.isNotEmpty(),
enter = expandVertically(Motion.tw(260)) + fadeIn(Motion.tw(220)),
@@ -193,50 +178,21 @@ private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
}
}
/** An install that stopped before it finished, from an earlier run: Resume picks it up, Clear deletes what it had. */
@Composable
private fun InterruptedRow(item: com.droiddeck.launcher.stores.CatalogItem) {
val ctx = LocalContext.current
ArtStrip(item.imageUrl ?: item.tallImageUrl, item.title) {
Text(item.title, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
SourceChip(item.store.id, small = true)
Text(stringResource(R.string.stores_dl_interrupted), fontSize = 12.sp, color = Color(0xFFFFC24D), maxLines = 1)
Spacer(Modifier.weight(1f))
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { StoresState.requestInstall(ctx, item) }
CancelAction { StoresState.clearUnfinished(ctx, item) }
}
}
/** How long a row that installed holds for its bar to gather into Play before it moves under the line. */
private const val GATHER_HOLD_MS = 900
/**
* A row in the download card's look, shorter: the game's art behind it under the same dark wash,
* the copy in white. Finished and interrupted downloads read as the same thing as one under way.
*/
@Composable
private fun ArtStrip(cover: String?, name: String, content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit) {
val pal = LocalPalette.current
Box(Modifier.fillMaxWidth().heightIn(min = 60.dp).clip(Shape12).background(Color(0xFF101318)).border(1.dp, pal.line, Shape12)) {
if (!cover.isNullOrEmpty()) AsyncImage(model = cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
else Spacer(Modifier.matchParentSize().background(artBrush(hueOf(name))))
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to Color.Black.copy(alpha = 0.92f), 0.5f to Color.Black.copy(alpha = 0.72f), 1f to Color.Black.copy(alpha = 0.2f))))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp), content = content,
)
}
}
/** A finished download: its name and store, and Play when it installed - blooming out of a dot when it just did. */
@Composable
private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions, bloom: Boolean = false) {
val ctx = LocalContext.current
ArtStrip(d.cover, d.name) {
Text(d.name, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
val colors = MaterialTheme.colorScheme
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface).padding(horizontal = 12.dp, vertical = 6.dp),
) {
Text(d.name, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
SourceChip(d.store.id, small = true)
Text(stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), fontSize = 12.sp, color = Color.White.copy(alpha = 0.72f), maxLines = 1)
Spacer(Modifier.weight(1f))
Text(stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.weight(1f))
if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
}
@@ -497,9 +453,21 @@ private fun eta(seconds: Long): String = when {
else -> "~${seconds / 3600} h ${(seconds % 3600) / 60} m"
}
/** The queue's settings beside it: speed tier, downloads at a time, and the engine log. */
@Composable
private fun DownloadSettings(s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
SectionTitle(stringResource(R.string.stores_download_manager), null)
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface).border(1.dp, pal.line, Shape12).padding(horizontal = 14.dp, vertical = 10.dp)) {
DownloadControls(s, a)
}
}
/**
* The queue's two knobs on one line - the speed tier on the left, downloads at a time on the
* right; it sits in the cog's popup. A narrow page puts them on two tight lines.
* right; the same control sits in the cog's popup. A narrow page puts them on two tight lines.
*/
@Composable
internal fun DownloadControls(s: FrontEndState, a: FrontEndActions) {
@@ -532,21 +500,20 @@ internal fun DownloadControls(s: FrontEndState, a: FrontEndActions) {
*/
internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<FrontEndState>, a: FrontEndActions, accent: androidx.compose.ui.graphics.Color): StepAsk =
StepAsk(
anchor = at, side = StepSide.Left, accent = accent, items = 2, maxWidth = 440.dp,
anchor = at, side = StepSide.Left, accent = accent, items = 3, maxWidth = 440.dp,
handle = { androidx.compose.material3.Icon(androidx.compose.material.icons.Icons.Filled.Settings, null, tint = accent, modifier = Modifier.size(20.dp)) },
) {
StepTitle(stringResource(R.string.stores_settings_eyebrow))
Column(
Modifier.stepItem(1).fillMaxWidth().heightIn(max = minOf(340.dp, (maxHeight - 64.dp).coerceAtLeast(44.dp))).verticalScroll(rememberScrollState()),
Modifier.stepItem(1).fillMaxWidth().heightIn(max = 340.dp).verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
val st = s.value
// No OK: B or a tap outside folds it, and a pad starts on the first choice.
SettingsRow(stringResource(R.string.setup_stores_open_on), null, stacked = true) {
Box(Modifier.focusRequester(first).focusGroup()) { SegmentedTabs(
SettingsRow(stringResource(R.string.setup_stores_open_on), null) {
SegmentedTabs(
listOf(SessionPrefs.STORES_OPEN_LIBRARY to stringResource(R.string.stores_tab_library), SessionPrefs.STORES_OPEN_STORE to stringResource(R.string.stores_tab_store)),
st.storesOpenTab,
) { a.onStoresOpenTab(it) } }
) { a.onStoresOpenTab(it) }
}
SettingsRow(stringResource(R.string.stores_show_mature), null) {
ToggleSwitch(st.storesShowMature, label = stringResource(R.string.stores_show_mature)) { a.onStoresShowMature(it) }
@@ -555,4 +522,7 @@ internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<Fron
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { DownloadControls(st, a) }
StoresEngineRow()
}
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth().stepItem(2).padding(top = 8.dp)) {
StepChoice(stringResource(R.string.common_ok), enabled = open, modifier = Modifier.focusRequester(first)) { StoresMotion.fold() }
}
}
@@ -125,12 +125,6 @@ internal object StoresMotion {
/** Where each store's dot sits on its chip, for a sign-in to come home to. */
val dots = HashMap<Store, Rect>()
/** Where the open game page's hero art sits (root px): what a card's flood lands on, and leaves from. */
var heroAt by mutableStateOf<Rect?>(null)
/** The open game page came out of a card: its hero holds still, for the card's flood to land on. */
var heroLands by mutableStateOf(false)
/** The card a game page is about to open from. */
private var card: CardMark? = null
private var cardAt = 0L
@@ -32,10 +32,6 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import android.view.KeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.draw.drawBehind
@@ -311,7 +307,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
val mark = StoresMotion.takeCard(g)
detailFrom = mark?.let { Origin(it.bounds.translate(-viewportAt), it.corner) }
detailArt = mark?.art
StoresMotion.heroLands = mark != null
leaving = false
detail = g
} else if (detail != null) {
@@ -451,9 +446,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
},
)
}
// Onto the page's own hero art, not the whole pane: grown to the pane, the art
// then cut down to the hero's banner (and back out to the pane to close).
PageFlood(from, leaving, art, onto = { StoresMotion.heroAt }, ontoCorner = 16.dp) { body() }
PageFlood(from, leaving, art) { body() }
}
}
}
@@ -588,9 +581,6 @@ private fun StoreChips(
val rootBounds = remember { HashMap<String, Rect>() }
// The fill travels with focus; only the expensive pane change waits for the debounce.
val highlighted = focused ?: selected
// With a pad the row has no fill of its own: the focus ring's infill is the only one.
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode
val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard
val tint = androidx.compose.animation.animateColorAsState(
Store.byId(highlighted)?.let { sourceColours(it.id).dot } ?: pal.signal, Motion.tw(160), label = "chipTint",
)
@@ -599,15 +589,22 @@ private fun StoreChips(
for (store in Store.entries) {
val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true
StoreChip(
label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot,
label = store.shortLabel, on = selected == store.id, key = store.id,
modifier = Modifier.weight(1f).onGloballyPositioned { bounds[store.id] = it.boundsInParent(); rootBounds[store.id] = it.boundsInRoot() },
lead = {
val c = sourceColours(store.id)
// A store's dot pulses when a sign-in lands (and, with the chip's lead, when picked).
// A store's dot pulses once when it is picked signed in, and when a sign-in lands.
var picked by remember { mutableStateOf(0) }
val on = selected == store.id
val wasOn = remember { booleanArrayOf(on) }
LaunchedEffect(on) {
if (on && !wasOn[0] && signedIn) picked++
wasOn[0] = on
}
Box(
Modifier.size(12.dp)
.onGloballyPositioned { StoresMotion.dots[store] = it.boundsInRoot() }
.pulseRing(StoresMotion.pulses[store] ?: 0, c.dot),
.pulseRing(picked + (StoresMotion.pulses[store] ?: 0), c.dot),
) { Box(Modifier.matchParentSize().clip(CircleShape).background(c.dot).alpha(if (signedIn) 1f else 0.35f)) }
},
description = store.label + if (signedIn) "" else " " + stringResource(R.string.stores_chip_signed_out),
@@ -615,7 +612,7 @@ private fun StoreChips(
) { onStore(store, rootBounds[store.id]) }
}
StoreChip(
label = stringResource(R.string.stores_tab_downloads), on = selected == DOWNLOADS, under = fillShown && highlighted == DOWNLOADS, key = DOWNLOADS, mark = pal.signal,
label = stringResource(R.string.stores_tab_downloads), on = selected == DOWNLOADS, key = DOWNLOADS,
modifier = Modifier.weight(1f).onGloballyPositioned {
bounds[DOWNLOADS] = it.boundsInParent()
StoresMotion.downloadsChip = it.boundsInRoot()
@@ -630,13 +627,13 @@ private fun StoreChips(
}
}
// Over the chips: the fill is translucent, and the other chips' rest fill would hide it in flight.
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint)
}
}
@Composable
private fun StoreChip(
label: String, on: Boolean, under: Boolean, key: String, mark: Color, modifier: Modifier, lead: @Composable () -> Unit,
label: String, on: Boolean, key: String, modifier: Modifier, lead: @Composable () -> Unit,
trail: (@Composable () -> Unit)? = null, description: String? = null,
onFocused: (String?) -> Unit = {}, onClick: () -> Unit,
) {
@@ -649,15 +646,7 @@ private fun StoreChip(
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "chipScale")
val shape = RoundedCornerShape(99.dp)
val ink = if (on) colors.onBackground else if (hot) colors.onBackground else colors.onSurfaceVariant
// The chip whose page shows has a bar of its colour along its foot. Picking it pulses its
// lead (a store's dot, Downloads' icon).
var picked by remember { mutableStateOf(0) }
val wasOn = remember { booleanArrayOf(on) }
LaunchedEffect(on) {
if (on && !wasOn[0]) picked++
wasOn[0] = on
}
// The row's glide draws the look of the chip [under] it, so that one draws no rest state of its own.
// The selected look is the row's glide under the chip, so a chip here draws only its rest state.
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
modifier = modifier.paneItem("storechip:$key")
@@ -666,17 +655,14 @@ private fun StoreChip(
else if (!f.isFocused) onFocused(null)
}
.heightIn(min = 44.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape)
.background(if (under) Color.Transparent else colors.surface)
.shownBar(on, mark)
.glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line)
.background(if (on) Color.Transparent else colors.surface)
.glideBorder(hot, shape, pal.signal, if (on) Color.Transparent else pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.then(if (description != null) Modifier.semantics { contentDescription = description } else Modifier)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
androidx.compose.runtime.CompositionLocalProvider(androidx.compose.material3.LocalContentColor provides ink) {
Box(Modifier.pulseRing(picked, mark), contentAlignment = Alignment.Center) { lead() }
}
androidx.compose.runtime.CompositionLocalProvider(androidx.compose.material3.LocalContentColor provides ink) { lead() }
Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis)
trail?.invoke()
}
@@ -732,23 +718,23 @@ private fun SignInCard(store: Store, height: Dp) {
val shape = RoundedCornerShape(20.dp)
val blank = WallCapsule(Brush.linearGradient(listOf(c.fill, colors.background)), edge = c.dot.copy(alpha = 0.22f))
val ground = SolidColor(c.fill)
Box(Modifier.fillMaxWidth().heightIn(min = height.coerceAtLeast(0.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) {
Box(Modifier.fillMaxWidth().height(height.coerceAtLeast(320.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) {
// The storefront arrives a moment after the page: its wall fades in over the blank one.
androidx.compose.animation.Crossfade(art, animationSpec = Motion.tw(600), label = "signInWall", modifier = Modifier.matchParentSize()) { tiles ->
androidx.compose.animation.Crossfade(art, animationSpec = Motion.tw(600), label = "signInWall") { tiles ->
TiltedWall(tiles.size, if (tiles.isEmpty()) 75_000 else 50_000) { i -> if (tiles.isEmpty()) blank else WallCapsule(ground, tiles[i]) }
}
// The wall gives way to the words: dark at the left and the foot, and the store's glow under them.
Box(
Modifier.matchParentSize().background(
Modifier.fillMaxSize().background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.97f), 0.45f to colors.background.copy(alpha = 0.9f),
0.78f to colors.background.copy(alpha = 0.35f), 1f to colors.background.copy(alpha = 0.15f),
),
),
)
Box(Modifier.matchParentSize().background(Brush.verticalGradient(0.5f to Color.Transparent, 1f to colors.background.copy(alpha = 0.92f))))
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.5f to Color.Transparent, 1f to colors.background.copy(alpha = 0.92f))))
Box(
Modifier.matchParentSize().drawBehind {
Modifier.fillMaxSize().drawBehind {
drawRect(Brush.radialGradient(listOf(c.dot.copy(alpha = 0.22f), Color.Transparent), center = Offset(size.width * 0.16f, size.height * 0.9f), radius = size.height * 0.75f))
},
)
@@ -837,50 +823,13 @@ private fun Storefront(
// A lazy item can be recomposed or prefetched out of order; the first grid card is identified
// by its key, rather than whichever happens to compose first.
var firstPlaced = false
var columns by remember { mutableIntStateOf(1) }
val density = androidx.compose.ui.platform.LocalDensity.current
val focus = LocalFrontFocus.current
val scope = rememberCoroutineScope()
val headerItems = 1 + (if (StoresState.status[store] != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0)
val card: @Composable (CatalogItem) -> Unit = { item ->
val first = if (showGrid) item.key == visible.firstOrNull()?.key else !firstPlaced
firstPlaced = true
val navigation = if (!showGrid || focus == null) Modifier else Modifier.onPreviewKeyEvent { event ->
val key = event.nativeKeyEvent
val direction = when (key.keyCode) {
KeyEvent.KEYCODE_DPAD_DOWN -> 1
KeyEvent.KEYCODE_DPAD_UP -> -1
else -> 0
}
val index = visible.indexOfFirst { it.key == item.key }
val next = storeGridNeighbor(index, visible.size, columns, direction)
when {
direction == 0 || index < 0 -> false
next == null -> direction > 0 // The last row stays in its column; Up can reach the header.
else -> {
if (key.action == KeyEvent.ACTION_DOWN) {
val target = "card:${visible[next].key}"
val targetIndex = headerItems + next
// Prefetched cards can accept focus without being on screen.
val visibleTarget = grid.layoutInfo.visibleItemsInfo.any { it.index == targetIndex }
if (!visibleTarget || (focus.attached[target] ?: 0) == 0 ||
runCatching { focus.items.getValue(target).requestFocus() }.isFailure) scope.launch {
grid.scrollToItem(targetIndex)
focusWithinFrames({ focus.last == target }) { focus.items[target] ?: androidx.compose.ui.focus.FocusRequester.Default }
}
}
true
}
}
}
GameCard(item, store, s, a, installedKeys, onOpen, first, navigation)
GameCard(item, store, s, a, installedKeys, onOpen, first)
}
LazyVerticalGrid(
columns = GridCells.Adaptive(CardWidth), state = grid, modifier = Modifier.fillMaxSize().focusGroup().onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
val minimum = with(density) { CardWidth.roundToPx() }
columns = ((it.width + gap) / (minimum + gap)).toInt().coerceAtLeast(1)
},
columns = GridCells.Adaptive(CardWidth), state = grid, modifier = Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
@@ -1117,7 +1066,7 @@ private val CardWidth = 112.dp
* on the store. Tapping the card itself opens the game's page.
*/
@Composable
private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: FrontEndActions, installedKeys: Set<String>, onOpen: (String) -> Unit, first: Boolean = false, navigation: Modifier = Modifier) {
private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: FrontEndActions, installedKeys: Set<String>, onOpen: (String) -> Unit, first: Boolean = false) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -1146,7 +1095,7 @@ private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: Front
if (b.bottom > -ahead && b.top < screen + ahead && b.width > 0f) com.droiddeck.launcher.stores.StoreSizes.request(ctx, item)
}
}
.then(navigation).paneItem("card:${item.key}").then(if (first) Modifier.firstTile() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale }
.paneItem("card:${item.key}").then(if (first) Modifier.firstTile() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale }
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open),
) {
@@ -13,7 +13,7 @@ internal fun StoresEngineRow() {
val version = StoresNative.version
SettingsRow(
stringResource(R.string.setup_stores_engine),
null,
version,
) {
Chip(if (version != null) stringResource(R.string.setup_stores_engine_chip_ready) else stringResource(R.string.setup_stores_engine_chip_missing), ok = version != null)
}
@@ -42,7 +42,7 @@ object Themes {
PAPER, R.string.theme_paper, R.string.theme_paper_detail,
background = Color(0xFF000000), surface = Color(0xFF0F0F10), surfaceVariant = Color(0xFF191A1C), line = Color(0xFF262729), line2 = Color(0xFF343638),
onBackground = Color(0xFFF9F9F9), onSurfaceVariant = Color(0xFF8E9196),
primary = Color(0xFFF9F9F9), primary2 = Color(0xFFD9DADD), onPrimary = Color(0xFF000000), signal = Color(0xFFF9F9F9),
primary = Color(0xFFF9F9F9), primary2 = Color(0xFFD9DADD), onPrimary = Color(0xFF000000), signal = Color(0xFF136CE0),
good = Color(0xFF4CD37F),
),
Palette(
+1 -7
View File
@@ -2087,8 +2087,6 @@
<string name="stores_play">Play</string>
<string name="stores_install">Install</string>
<string name="stores_resume_install">Resume install</string>
<!-- A Downloads row for an install that stopped when the app closed: it can be resumed -->
<string name="stores_dl_interrupted">Interrupted</string>
<string name="stores_install_size">Install · %1$s</string>
<string name="stores_get_free">Get for free</string>
<string name="stores_view_on">View on %1$s</string>
@@ -2124,11 +2122,7 @@
<string name="stores_eyebrow_store">store</string>
<string name="stores_in_steam">✓ In Steam</string>
<string name="stores_uninstall">Uninstall</string>
<string name="stores_uninstalling">Uninstalling…</string>
<!-- The heading of the confirm that steps out of a store game's Uninstall; %1$s is the game -->
<string name="stores_uninstall_title">Uninstall %1$s?</string>
<string name="stores_uninstall_body_size">Frees %1$s and removes it from Steam.</string>
<string name="stores_uninstall_body">Removes its files and its Steam shortcut.</string>
<string name="stores_uninstall_confirm">Press again to uninstall</string>
<string name="stores_launch_not_registered">Steam picks the game up when it next starts; launch it from there, or start Steam now.</string>
<string name="stores_card_proton">Proton</string>
<string name="stores_card_proton_value">Steam\'s choice per game</string>
@@ -0,0 +1,66 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.content.ContextWrapper
import com.droiddeck.launcher.runtime.BwrapSpawner
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBuild
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class QuestExperimentalTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
ShadowBuild.setModel("Phone")
ShadowBuild.setDevice("phone")
}
@Test fun otherDevicesAndQuest2KeepTheirSettings() {
for (model in listOf("Phone", "Quest 2")) {
ShadowBuild.setModel(model)
QuestExperimental.initialize(context)
assertEquals(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.gpuDriverMode(context))
assertEquals("", SessionPrefs.androidDriver(context))
assertFalse(SessionPrefs.hdr(context, "steam"))
}
assertFalse(QuestExperimental.supported("Quest 2", "hollywood", "Oculus"))
}
@Test fun questDefaultsSelectBothCompatibilityPathsAndAreAppliedOnlyOnce() {
ShadowBuild.setModel("Quest 3")
QuestExperimental.initialize(context)
assertEquals(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.gpuDriverMode(context))
assertEquals(QuestExperimental.DRIVER, SessionPrefs.androidDriver(context))
assertEquals("", SessionPrefs.linuxDriver(context))
assertTrue(SessionPrefs.hdr(context, "steam"))
assertTrue(context.filesDir.resolve("quest-startup.txt").readText().contains("model=Quest 3"))
SessionPrefs.setAndroidDriver(context, "chosen-driver")
SessionPrefs.setHdr(context, "steam", false)
QuestExperimental.initialize(context)
assertEquals("chosen-driver", SessionPrefs.androidDriver(context))
assertFalse(SessionPrefs.hdr(context, "steam"))
}
@Test fun quest3sIsRecognizedByModelOrDevice() {
assertTrue(QuestExperimental.supported("Quest 3S", "unknown", "Oculus"))
assertTrue(QuestExperimental.supported("unknown", "panther", "Oculus"))
assertTrue(QuestExperimental.supported("unknown", "eureka", "Meta"))
assertFalse(QuestExperimental.supported("Pixel 7", "panther", "Google"))
}
@Test fun installedPackagesUseSeparateSandboxSockets() {
val quest = object : ContextWrapper(context) {
override fun getPackageName() = "com.droiddeck.quest"
}
assertEquals("com.droiddeck.quest.bwrap", BwrapSpawner.socket(quest))
assertNotEquals(BwrapSpawner.socket(context), BwrapSpawner.socket(quest))
}
}
@@ -4,9 +4,9 @@ import org.junit.Assert.assertEquals
import org.junit.Test
class LiftSheetTest {
@Test fun theSheetTopIs60dpDownA360dpPane() {
assertEquals(60f, sheetTop(360f, 56f, 16f, 3f), 0.01f)
assertEquals(120f, sheetTop(720f, 56f, 16f, 3f), 0.01f)
@Test fun theSheetTopIs82dpDownA360dpPane() {
assertEquals(82f, sheetTop(360f, 56f, 16f, 3f), 0.01f)
assertEquals(164f, sheetTop(720f, 56f, 16f, 3f), 0.01f)
}
@Test fun theButtonKeeps16dpAboveIt() {
@@ -1,29 +0,0 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class StoreGridNavigationTest {
@Test fun downAndUpPreserveEveryColumnAcrossSeveralRows() {
for (columns in 1..6) for (index in 0 until columns * 3) {
val down = storeGridNeighbor(index, columns * 4, columns, 1)!!
assertEquals(index % columns, down % columns)
assertEquals(index, storeGridNeighbor(down, columns * 4, columns, -1))
}
}
@Test fun incompleteLastRowDoesNotWrapBackToTheLeft() {
assertEquals(8, storeGridNeighbor(4, 10, 4, 1))
assertEquals(9, storeGridNeighbor(5, 10, 4, 1))
assertNull(storeGridNeighbor(6, 10, 4, 1))
assertNull(storeGridNeighbor(7, 10, 4, 1))
assertNull(storeGridNeighbor(9, 10, 4, 1))
}
@Test fun firstRowCanLeaveUpwardsAndChangedColumnCountsAreUsed() {
assertNull(storeGridNeighbor(2, 10, 4, -1))
assertEquals(5, storeGridNeighbor(2, 10, 3, 1))
assertEquals(6, storeGridNeighbor(2, 10, 4, 1))
}
}
-53
View File
@@ -1,53 +0,0 @@
# Discord UI and session reports, 2026-10-11
Sources: [bug thread](https://discord.com/channels/1552707793247539220/1558928314956120174), [general](https://discord.com/channels/1552707793247539220/1552707794430459916), and [development](https://discord.com/channels/1552707793247539220/1552751182165049435). Reviewed the post-overhaul discussion on October 11, including screenshot-only messages and linked reports.
Branch: `fix/discord-ui-session-reports`, based on `origin/main` at `0cafa83e`.
Device: AYN Thor, selected by the full advertised ADB serial.
## Changes
| Report | Change |
| --- | --- |
| Settings needs an X and a larger handle | Add a 44dp close target in the sheet's controller focus group; enlarge the visible handle to 32dp and its label to 14sp. |
| Settings has too little height | Raise the sheet from 82/360 to 60/360 of the pane while preserving clearance above the primary action. |
| Reopening during the closing animation breaks settings | Cancel the outstanding drag settlement when a new gesture or open/close transition takes ownership. |
| Store navigation returns to the left column | Route Up/Down by the actual adaptive column count and focus the corresponding card after lazy composition. Incomplete final rows do not wrap. Prefetched offscreen cards are scrolled into view before focus moves. |
| A selection stays as a dot | Unpinch an interrupted long chip jump during the next adjacent move. Cancel an obsolete focus-ring flight and its fill animation on focus loss. |
| Performance opens with focus on Steam | Wait for Back to attach and take focus after the outgoing page leaves. |
| Desktop settings navigation jumps | Do not apply the main page's Down-to-first-app shortcut to settings-sheet buttons. |
| Display-driver navigation loses focus | Wait for the chooser to disappear before focusing the selected driver; initialize controller focus when switching back from touch. |
| Stores can no longer be hidden | Restore a persisted Stores switch under Setup > Launcher; keep it enabled by default. |
| Stores engine is clipped in the settings panel | Bound popup height to the available screen space, expose that limit to its scrollable body, and allow tall popup content to scroll. |
| Wine Sync renders vertically | Stack its label above the full-width sync choices. |
| Profile picker leaves too little room for Proton lists | Replace the large profile group with a compact 44dp picker row. |
| Theme accent is inconsistent | Paper's signal color now follows its white primary color rather than retaining blue. Store brand colors and controller-button tint remain separate settings. |
| Phone sign-in buttons clipped ([development report](https://discord.com/channels/1552707793247539220/1552751182165049435/1558947589997469820)) | Size the sign-in card to the pane and its content instead of enforcing a 320dp minimum. Decorative layers follow the measured card. |
| Force SSBS hard to find behind empty scrolling ([general report](https://discord.com/channels/1552707793247539220/1552707794430459916/1558976573758251029)) | Place shared Proton options before installed/downloadable lists; start each component layer's detail at the top when switching layers. |
## Validation
The release APK was prepared with `tools/build_local.sh`, built with `assembleRelease`, signed with the normal release lineage, and installed with `adb install -r` over Thor's existing app.
16 focused unit tests passed: LiftSheetTest, StoreGridNavigationTest, GlideShapeTest, StoreTabsTest, AppScaleTest, and the Compose ComponentsPageProfileTest. The first unrestricted unit-test run ended because the Gradle test executor exited with code 2 without an individual test failure report; it is not counted as a passing full suite.
Thor checks include the close control, eight close/reopen swipe cycles, 21 rapid long/adjacent Setup tab switches, hiding and restoring Stores, Paper theme colors, controller entry into Performance (Back focused, then Down to the first setting), driver chooser handoff and Up/Down scrolling, and Desktop Files navigation (Open > Choose > Uninstall > Choose > Open). The new close control is reachable and operable with a controller. The newer Stores engine clipping, compact profile picker, and horizontal Wine Sync label were also checked on Thor. The original Graphite theme and existing session preferences were restored after checks.
Device screenshots and UI dumps are saved locally under `captures/discord-reports/` (ignored build evidence). The final signed APK is `app/build/outputs/apk/release/app-release-signed.apk`.
The first pass saw no populated authenticated store grid. During the follow-up, Epic and Amazon loaded their retained accounts and libraries (402 and 150 titles). On Epic, six controller Down moves and six Up moves stayed in the third column, including transitions to offscreen rows, and returned to the original card. This caught and fixed the case where a prefetched offscreen card accepted focus without scrolling. The completed trace is `captures/discord-reports/epic-grid-navigation.json`.
Follow-up validation used both Thor's normal display and a temporary 2400x1080 / 540dpi phone-like layout. GOG's sign-in card and button were fully visible without scrolling. Epic and Amazon remained signed in, so their library layouts were inspected rather than signing the accounts out. Proton options appeared before the catalogs, Force SSBS was reachable by scrolling, and changing layers reset the detail scroll. The physical size/density were restored (1080x1920 / 369dpi). The final build and four focused tests passed; the final signed APK hash is `7dca710d081042ec68aeaf6e8b68371d5fdfa73eca5860ba4ca5f0134c21b9fc`. Wireless ADB file-sync stalled, so the APK was transferred over a temporary direct LAN socket, hash-verified on Thor, and installed with `pm install -r`. The transfer listener closed after delivery.
## Runtime reports still unresolved
**Second Steam launch fails or has sound with a black picture.** The two submitted log bundles reach a first frame and Steam focus, then record a guest exit with status 0. Their crash buffers contain no Android crash. Two consecutive launches of Thor's existing main build reached READY and displayed Steam correctly, using the same retained compositor and app process. Two consecutive Steam launches of the new branch also reached READY with visible Steam UI, and its desktop launch reached READY and stopped cleanly. These observations do not establish the cause of the reporters' failures, and no speculative compositor or Steam-startup change was made.
**Persona 3 Reload drops from 60 to 35 FPS and crashes.** The linked compatibility thread identifies an Odin 3 Max and a UE4 GameThread timeout waiting 120 seconds for RenderThread. Earlier working settings were Performance + TSO and VKD3D shader/feature levels 6_6 / 12_1. The new report has no session log, before/after build identifiers, or controlled comparison. Persona 3 Reload was not found in the inspected Thor library locations. Neither an Odin reproduction nor a Persona performance improvement is claimed. The RDR2 launcher governor matches Rockstar helper executable paths and is not a blanket game-core restriction.
## Related follow-ups outside launcher design
General's fullscreen desktop-app report matches the existing runtime contract: the software desktop hands Steam to a Steam session and wraps games/emulators in gamescope for GPU access. `droiddeck-desktop-gpu` preserves a “Run in a desktop window” action. Changing that GPU/window architecture is separate runtime work; no claim of fixing it here.
Development's request to update driver and Proton defaults without visiting Components is also runtime policy. Driver Auto already calls `ensureAuto` during activity startup. This branch does not replace manual driver selections or install/switch Proton builds as part of a layout fix.
-26
View File
@@ -1,26 +0,0 @@
# Steam black screen with FSR 1
Branch `fix/fsr-steam-black-screen` starts at `origin/main` `e4c375ad` after PR #596 merged.
## Diagnosis
On AYN Thor (Adreno 740, WN-Turnip-1.19-p_Axxx), Steam reached READY and retained focus while the entire screen was black with FSR 1 at 720p / 85% sharpness. Switching the same running session to Linear immediately restored the picture. Production SGSR also went black. At native 1080p, FSR stayed selected but its upscale pass was unnecessary and Steam remained visible.
A temporary SGSR shader drew a constant red strip beside a normal texture sample. The strip and sampled picture were corrupted in a tiled pattern. Allowing unrestricted mutable formats on the post-processing targets made both render correctly. Restoring the original shaders then restored the first production FSR launch. A second launch exposed a separate source-view lifetime bug: the scene owner destroyed its image while the effect chain retained a view and descriptor; a recycled image handle at the same dimensions could hit that stale cache.
## Change
Create the effect chain's intermediate images with `VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT`, without a restricted view-format list. Turnip consequently avoids UBWC compression on these render-then-sample/blit targets. The input scene and guest images retain their existing allocation policy. Release the cached source view and descriptor before an SDR, HDR or frame-generation scene image is destroyed. This makes recycled Vulkan handles create fresh sampling resources. Scaling remains enabled and the FSR EASU/RCAS shaders and sharpness settings are unchanged.
Driver behavior is documented in Mesa's [image allocation implementation](https://chromium.googlesource.com/external/gitlab.freedesktop.org/mesa/mesa/+/3fcec4762f3fec551c00da52f349c83443152159/src/freedreno/vulkan/tu_image.cc), including the mutable-format check and `format_list_ubwc_possible`.
## Validation
- Four native cache regressions passed: recycled handles, unrelated/null images, repeated invalidation, and dimension changes. The fixture executes the actual cache implementation with Vulkan lifetime callbacks.
- Release build and 14 focused Android tests passed: SessionScalingPrefsTest and SessionDisplayTest.
- A separate Vulkan/MoltenVK smoke test ran the actual effect chain: a 16x16 source scaled by FSR to 32x32 retained RGBA 64/128/191/255.
- Signed APK installed over Thor's existing app, with its device-side transfer hash verified.
- Production FSR at 720p / 85% rendered visible Steam, including two consecutive stop/start cycles with the app/compositor retained (sessions 42 and 43). Live SGSR, Linear and return-to-FSR switching also rendered correctly.
- Session preferences match the pre-test snapshot; FSR 1 / 85%, 720p and the existing driver selections are retained.
Local screenshots, state snapshots and renderer logs are under `captures/fsr-black-screen/` (ignored). Temporary probe shaders are excluded from the final source change. The signed APK hash is `2b8b7ea18c49bf53f1f3cb00eea8f73d122258a900c18ffe660c85c5654bedae`. The old cache behavior fails the recycled-handle regression; the corrected implementation passes all four cases.
+37
View File
@@ -0,0 +1,37 @@
# Experimental Quest 3/3S support
Quest 3/3S runs DroidDeck as a 2D panel. This does not add immersive VR or
OpenXR support. Quest 2 is outside the bundled Adreno 7xx driver path.
The first launch on Quest 3/3S selects manual drivers, the bundled
`turnip25.1.0-quest1` Android driver and the default Linux driver. It enables
`hdr.steam` to use the existing SurfaceControl presentation workaround from
[the Quest report](https://github.com/Droid-Deck/DroidDeck/issues/245).
These defaults apply once; subsequent user changes are retained. Colour
accuracy and headset performance still need testing.
Both the Android driver wrapper and the Linux session preload use
`tools/quest/kgsl_compat.c`. Successful legacy allocation/free calls are
unchanged. Only `EACCES`/`EPERM` failures retry through `GPUOBJ_ALLOC`,
`GPUOBJ_INFO` and `GPUOBJ_FREE`. The Android wrapper depends on the original
bundled Turnip binary. Unhandled controller ioctls forward to the next
preload hook rather than skipping it with a raw syscall.
`tools/build_local.sh` and CI build the wrapper from source using the pinned
Android NDK; the normal preload builds include the shared Linux adapter.
Runtime input verification checks the resulting driver archive and invalidates
stale prepared assets after compatibility sources change. To rebuild only the
Android driver archive:
```sh
python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/27.3.13750724"
```
The release variant `quest` produces a separate `com.droiddeck.quest` APK
with its own app data. All installed packages use their own bwrap socket.
The standard APK also applies Quest defaults when running on Quest 3/3S.
On a headset, check the Steam login panel, sign-in, game installation and
then an owned game's rendering/input. Capture the device/OS, session logs,
`files/quest-startup.txt` and any `files/quest-last-crash.txt` failure.
Host allocation and preload-chain tests do not establish headset operation.
-123
View File
@@ -1,123 +0,0 @@
# DroidDeck 0.4.0
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
> **TL;DR for Mr. Sujano specifically**
>
> And speaking about the coolest thing since sliced bread, next up here we're talking about DroidDeck.
>
> For those who are unaware, DroidDeck brings the SteamOS experience to Android on your Snapdragon powered handheld, and DroidDeck just got a brand new update. Now, they just released version 0.4.0, and taking a look at this update, it seems to be a pretty big one.
>
> It says here they've added GOG, Epic Games and Amazon Games integration, with cloud saves for GOG and Epic. On top of that here, they've implemented a fully featured SteamOS-style KDE Plasma desktop with a working "Return to Gaming Mode."
>
> Steam's own Steam Link touch controller, with community layouts that back up to Steam Cloud. Support for connecting up to four controllers for local co-op. Native support for the new Steam Controller. And the built-in controls can now pretend to be a Steam Deck, Steam Controller, Xbox 360, DualShock 4 or DualSense.
>
> If you're on a foldable, Steam and your games now resize when you fold, unfold or rotate, and there's an optional touch gamepad below the game when it's unfolded.
>
> They've also got per-game compatibility profiles, automatic redistributable and Windows component installs, their own custom DroidDeck-Proton, and streamlined non-Steam game imports with automatic artwork. And on the performance side, PRoot is up to 57% faster in some workloads, with lower idle CPU usage, and even more.
>
> You let me know your thoughts.
### Features
- Replaced LXQt with **SteamOS-style KDE Plasma 6.7**, including the familiar desktop layout, Dolphin, Firefox, Konsole, the Steam desktop client and Return to Gaming Mode. (@xXJSONDeruloXx, [#473](https://github.com/Droid-Deck/DroidDeck/pull/473), [#610](https://github.com/Droid-Deck/DroidDeck/pull/610))
<img src="media/0.4.0/desktop-round-trip.gif" width="50%" alt="Switching from Steam to the KDE Plasma desktop, browsing the application launcher, then returning to Gaming Mode; loading shortened and boot animation removed">
- Added **GOG, Epic Games and Amazon Games** integration with account sign-in, game libraries, downloads and launching through Steam. GOG and Epic games also support cloud saves. (@The412Banner, @xXJSONDeruloXx, @Gustash, @maxjivi05, [#476](https://github.com/Droid-Deck/DroidDeck/pull/476), [#500](https://github.com/Droid-Deck/DroidDeck/pull/500), [#578](https://github.com/Droid-Deck/DroidDeck/pull/578), [#400](https://github.com/Droid-Deck/DroidDeck/pull/400))
<img src="media/0.4.0/store-downloads.gif" width="50%" alt="Browsing the Epic Games library, installing 20 Minutes Till Dawn and viewing its download progress">
<img src="media/0.4.0/gog-sign-in.jpg" width="50%" alt="GOG store tab with its Sign in button">
- Added **Steam's native touch controller (beta)**, with per-game Steam Input layouts, community configurations, an on-screen layout editor and Steam Cloud syncing. (@xXJSONDeruloXx, [#431](https://github.com/Droid-Deck/DroidDeck/pull/431))
<img src="media/0.4.0/castle-crashers-touch.gif" width="50%" alt="Launching Castle Crashers with Steam touch controls that switch to its game-specific icons, then browsing and applying a community touch layout; loading and menus sped up">
<img src="media/0.4.0/steam-touch-editor.jpg" width="50%" alt="Castle Crashers touch layout editor">
<details>
<summary>Steam Input layouts and touch settings</summary>
<img src="media/0.4.0/steam-input-touch.jpg" width="50%" alt="Steam Input settings for the Remote Play Touch Controller">
<img src="media/0.4.0/steam-input-cloud-layouts.jpg" width="50%" alt="The saved Castle Crashers touch layout in Steam Input">
<img src="media/0.4.0/steam-input-community.jpg" width="50%" alt="Community touch-controller layouts for Castle Crashers">
<img src="media/0.4.0/steam-touch-menu.jpg" width="50%" alt="Castle Crashers touch controller and mouse settings">
</details>
- Added **multi-controller support for up to 4 players**, allowing connected Android gamepads to work independently for local co-op and split-screen multiplayer through Steam Input. (@xXJSONDeruloXx, @maxjivi05, @Neolyum, [#431](https://github.com/Droid-Deck/DroidDeck/pull/431), [#614](https://github.com/Droid-Deck/DroidDeck/pull/614))
<img src="media/0.4.0/multi-controller.gif" width="50%" alt="Two Bluetooth controllers playing split-screen on the Thor, with both listed under connected devices on the bottom screen">
- Added **Bluetooth LE Steam Controller (2025)** support, including trackpads, back grips and motion controls. (@SG3xHERO, [#404](https://github.com/Droid-Deck/DroidDeck/pull/404))
<img src="media/0.4.0/steam-controller-ble.jpg" width="35%" alt="A 2025 Steam Controller connected to the Thor over Bluetooth, with its Steam Input layout on the top screen">
- The built-in controller can now emulate a **Steam Deck, Steam Controller, Xbox 360, DualShock 4 or DualSense**, with live switching from the session menu without restarting Steam. (@xXJSONDeruloXx, [#545](https://github.com/Droid-Deck/DroidDeck/pull/545), [#558](https://github.com/Droid-Deck/DroidDeck/pull/558), [#559](https://github.com/Droid-Deck/DroidDeck/pull/559))
<img src="media/0.4.0/controller-emulation.jpg" width="50%" alt="Choosing the emulated built-in controller during a Castle Crashers session: Steam Deck, Steam Controller, DualShock 4, DualSense or Xbox 360">
- Added persistent **per-game compatibility profiles** for Proton, FEX, DXVK, VKD3D-Proton, Windows components, environment variables and texture filtering, with inheritance from your default settings. (@jmarti326, [#449](https://github.com/Droid-Deck/DroidDeck/pull/449))
<img src="media/0.4.0/game-profiles.jpg" width="50%" alt="Configure profile menu listing the default profile and per-game profiles">
- Completely revamped **adding and managing non-Steam games**, with automatic game detection, artwork, bulk imports and editing directly from the Games tab. (@The412Banner, [#492](https://github.com/Droid-Deck/DroidDeck/pull/492))
<img src="media/0.4.0/add-game.jpg" width="50%" alt="The Games tab Add a game dialog, choosing internal storage or an SD card to scan">
- Added **Follow screen** resolution for foldables, automatically resizing Steam and games when folding, unfolding or rotating the device. (@SG3xHERO, [#403](https://github.com/Droid-Deck/DroidDeck/pull/403))
<img src="media/0.4.0/follow-screen-landscape.jpg" width="35%" alt="Steam filling the inner screen of an unfolded foldable in landscape">
<img src="media/0.4.0/follow-screen-portrait.jpg" width="20%" alt="Steam resized to the inner screen in portrait">
<img src="media/0.4.0/follow-screen-cover.jpg" width="42%" alt="Steam resized to the folded cover screen">
- Added an optional **touch gamepad below the game on unfolded foldables**, with Steam Deck-style controls, configurable sticks and trackpads. (@SG3xHERO, [#407](https://github.com/Droid-Deck/DroidDeck/pull/407))
<img src="media/0.4.0/foldable-gamepad.jpg" width="25%" alt="Steam on the top half of an unfolded foldable with the touch gamepad below it">
<img src="media/0.4.0/foldable-trackpads.jpg" width="25%" alt="The foldable touch gamepad switched to its two-trackpad layout with back buttons">
<img src="media/0.4.0/foldable-landscape.jpg" width="50%" alt="The foldable touch gamepad in landscape, laid out along the bottom edge under Steam">
- Added **DroidDeck-Proton** as an installable Proton source alongside GE-Proton and CachyOS Proton, with update notifications for all three. (@The412Banner, [#588](https://github.com/Droid-Deck/DroidDeck/pull/588))
- Added support for installing **Flatpak apps directly from .flatpak bundles**, including apps no longer available through Flathub. (@xXJSONDeruloXx, [#446](https://github.com/Droid-Deck/DroidDeck/pull/446))
- Added a manual **landscape orientation** setting, including reverse landscape. (@Kobtul, [#441](https://github.com/Droid-Deck/DroidDeck/pull/441))
- Added an optional controller setting to open the Steam menu with the physical **Select** button. (@0x1428571429, [#384](https://github.com/Droid-Deck/DroidDeck/pull/384))
### Improvements
- Major **launcher UI redesign** across Steam settings, Components, Setup, Stores, Flathub and Desktop, with smoother transitions, animated navigation, redesigned settings panels and improved controller focus. (@xXJSONDeruloXx, [#482](https://github.com/Droid-Deck/DroidDeck/pull/482), [#548](https://github.com/Droid-Deck/DroidDeck/pull/548), [#605](https://github.com/Droid-Deck/DroidDeck/pull/605))
<img src="media/0.4.0/steam-settings.gif" width="50%" alt="Opening the slide-up Steam settings panel and switching to Display settings">
- **Store downloads now survive app restarts**, preserving queued and paused downloads and allowing interrupted installs to resume from the Downloads page. (@xXJSONDeruloXx, [#608](https://github.com/Droid-Deck/DroidDeck/pull/608))
- Store game removal now shows **confirmation and uninstall progress** before returning the game to its installable state. (@xXJSONDeruloXx, [#609](https://github.com/Droid-Deck/DroidDeck/pull/609))
- Expanded **PRoot fast paths**, with performance improvements of up to 57% in measured workloads, alongside further reductions in filesystem and process overhead. (@maxjivi05, @xXJSONDeruloXx, [#466](https://github.com/Droid-Deck/DroidDeck/pull/466), [#494](https://github.com/Droid-Deck/DroidDeck/pull/494))
- Significantly reduced launcher idle CPU usage, controller input overhead and session log processing time, with additional game startup and performance optimizations. (@maxjivi05, [#529](https://github.com/Droid-Deck/DroidDeck/pull/529))
- **Windows components are now selected automatically** using each game's Steam, GOG, Epic or Amazon dependency information, while preserving manual overrides. (@The412Banner, [#554](https://github.com/Droid-Deck/DroidDeck/pull/554))
- Expanded Windows component installation to support **VC++ redistributables, .NET Framework and more installer formats**, without needing to run the original Windows setup programs. (@The412Banner, [#480](https://github.com/Droid-Deck/DroidDeck/pull/480), [#495](https://github.com/Droid-Deck/DroidDeck/pull/495))
- KDE Desktop can now launch **Windows executables, Linux programs, AppImages and scripts** directly from the file manager or terminal. (@maxjivi05, [#549](https://github.com/Droid-Deck/DroidDeck/pull/549))
- Added safer **Desktop uninstall and legacy LXQt cleanup**, preserving user data while reclaiming storage from older desktop installations. (@xXJSONDeruloXx, [#493](https://github.com/Droid-Deck/DroidDeck/pull/493))
- Improved **Proton and component management**, with newest versions shown first, update detection, clearer installed-version information and streamlined settings. (@The412Banner, @xXJSONDeruloXx, [#588](https://github.com/Droid-Deck/DroidDeck/pull/588), [#606](https://github.com/Droid-Deck/DroidDeck/pull/606))
- Improved **DirectAudio compatibility**, including CachyOS Proton support and direct audio output from the Steam client. (@The412Banner, [#439](https://github.com/Droid-Deck/DroidDeck/pull/439))
- Reduced unnecessary motion sensor polling, reading the device's gyro and accelerometer only when Steam requests them. (@muazkadan, [#534](https://github.com/Droid-Deck/DroidDeck/pull/534))
- Added alignment guides and snapping when dragging buttons in the **on-screen controller editor**. (@willie-yao, [#490](https://github.com/Droid-Deck/DroidDeck/pull/490))
- Improved security by **encrypting store credentials with Android Keystore** and keeping logs in private app storage until explicitly shared as a sanitized ZIP. (@The412Banner, [#484](https://github.com/Droid-Deck/DroidDeck/pull/484), [#486](https://github.com/Droid-Deck/DroidDeck/pull/486))
- Steam now consistently uses **Steam Deck mode and the Steam Deck beta branch**, removing the legacy client and mode switches. (@xXJSONDeruloXx, [#546](https://github.com/Droid-Deck/DroidDeck/pull/546))
### Fixed
- Fixed **Red Dead Redemption 2** failing to launch, and reduced resource usage from the Rockstar launcher while playing. (@maxjivi05, [#585](https://github.com/Droid-Deck/DroidDeck/pull/585))
- Fixed Steam's screensaver appearing over running games after prolonged controller inactivity. (@maxjivi05, [#585](https://github.com/Droid-Deck/DroidDeck/pull/585))
- Fixed **black Steam output with FSR 1** image scaling enabled. (@xXJSONDeruloXx, [#597](https://github.com/Droid-Deck/DroidDeck/pull/597))
- Fixed **touch and mouse input landing away from the displayed position** when the session resolution and device screen have different aspect ratios. (@maxjivi05, [#389](https://github.com/Droid-Deck/DroidDeck/pull/389))
- Fixed the **Odin 3 unexpectedly rebooting** when its Wi-Fi firmware enters low-latency mode. (@kmnkv1, [#512](https://github.com/Droid-Deck/DroidDeck/pull/512))
- Fixed **Linux runtime removal getting stuck** on files that Android's SELinux policy would not allow the app to delete. (@xXJSONDeruloXx, [#463](https://github.com/Droid-Deck/DroidDeck/pull/463))
- Fixed **Android 12 and older devices crashing during audio initialization**, and restored Firefox compatibility on affected Android 16 devices. (@kolmant, @The412Banner, [#531](https://github.com/Droid-Deck/DroidDeck/pull/531), [#460](https://github.com/Droid-Deck/DroidDeck/pull/460))
- Fixed **Bluetooth keyboards with combined keyboard, mouse and controller interfaces** losing ordinary keyboard input. (@kaosjammo, [#435](https://github.com/Droid-Deck/DroidDeck/pull/435))
- Fixed repeated force-feedback packets unnecessarily restarting the device vibrator. (@kmnkv1, [#514](https://github.com/Droid-Deck/DroidDeck/pull/514))
- Fixed **CPU temperature showing 0°C** in the Steam performance overlay on affected devices. (@muazkadan, [#516](https://github.com/Droid-Deck/DroidDeck/pull/516))
- Fixed older **NativeAOT games failing to start** because of an incompatible .NET garbage collector setting. (@Arthur031221, [#385](https://github.com/Droid-Deck/DroidDeck/pull/385))
- Fixed fullscreen layout issues around display cutouts, clipped settings, and several controller navigation and focus problems. (@kaosjammo, @xXJSONDeruloXx, [#432](https://github.com/Droid-Deck/DroidDeck/pull/432), [#596](https://github.com/Droid-Deck/DroidDeck/pull/596), [#600](https://github.com/Droid-Deck/DroidDeck/pull/600))
- Fixed the touchpad cursor remaining visible after switching from Touchpad to Direct touch mode. (@KingHacker9000, [#424](https://github.com/Droid-Deck/DroidDeck/pull/424))
### New contributors
- @SG3xHERO made their first contribution in [#403](https://github.com/Droid-Deck/DroidDeck/pull/403).
- @Arthur031221 made their first contribution in [#385](https://github.com/Droid-Deck/DroidDeck/pull/385).
- @KingHacker9000 made their first contribution in [#424](https://github.com/Droid-Deck/DroidDeck/pull/424).
- @kaosjammo made their first contribution in [#432](https://github.com/Droid-Deck/DroidDeck/pull/432).
- @Kobtul made their first contribution in [#441](https://github.com/Droid-Deck/DroidDeck/pull/441).
- @willie-yao made their first contribution in [#490](https://github.com/Droid-Deck/DroidDeck/pull/490).
- @muazkadan made their first contribution in [#516](https://github.com/Droid-Deck/DroidDeck/pull/516).
- @kolmant made their first contribution in [#531](https://github.com/Droid-Deck/DroidDeck/pull/531).
- @Gustash made their first contribution in [#578](https://github.com/Droid-Deck/DroidDeck/pull/578).
- @Neolyum made their first contribution in [#614](https://github.com/Droid-Deck/DroidDeck/pull/614).
[Full changelog](https://github.com/Droid-Deck/DroidDeck/compare/0.3.2...0.4.0)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 290 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 463 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 201 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 MiB

-13
View File
@@ -1,13 +0,0 @@
# Steam desktop client in KDE
The [Discord report](https://discord.com/channels/1552707793247539220/1552707794430459916/1558974992753098874) describes Steam replacing KDE with a gamescope session. The launcher unconditionally wrote `steam-launch`, which tells the Android app to end KDE and start Steam under gamescope. Other desktop applications have a separate GPU wrapper; this change addresses Steam's desktop client.
Desktop Steam now runs the existing session supervisor with `BL_INSIDE=1` on KDE's inherited Xwayland display and authentication. CEF uses software rendering because KDE's QPainter compositor accepts shared-memory buffers. Big Picture continues to request the explicit gaming session. A lock keeps repeated menu clicks from starting another supervisor while Steam is starting or updating; subsequent clicks wait for Steam's live IPC pipe and then forward the Steam URL to the existing client. This also prevents a second click during cold startup from launching a client without software CEF. KDE retains its own agent and clipboard helpers when Steam starts and exits.
Validation on AYN Thor uses the full wireless ADB serial `adb-d234a848-fv2FDl (2)._adb-tls-connect._tcp`. Live script testing displayed the authenticated library, restored the main window from maximized to windowed, opened Settings as a separate window, and forwarded a second launch to Downloads. KDE's panel remained visible, no gamescope process started, and no session handoff file was written. Quitting Steam returned to the running Plasma desktop with its agent still available. An explicit Big Picture launch then switched to a Steam session and reached READY with Steam focused.
Rapid repeated desktop-icon taps were also tested: one client started with software CEF and the library remained on KDE.
Host regression tests cover desktop display preservation, game URLs, duplicate launches before and after IPC is ready, explicit Big Picture handoff, non-desktop callers, invalid targets, and software CEF limited to the KDE desktop client. Gameplay through Steam's library on KDE has not been validated; the desktop's existing GPU presentation limitations remain.
The final release-signed APK was built with `tools/build_local.sh`, verified to contain the exact tested Steam scripts, and installed with `adb install -r`. APK SHA-256: `d104b1e6e20fb10e85fcdd95eaf2a8ca69061547164640b8590e41e4495663e4`. On that installation, two rapid desktop-icon taps started one software-rendered Steam client; the library displayed on KDE and restored to a desktop window. Final session: `2026-10-12-09-desktop`, READY, mode `lxqt`, with no gamescope process or handoff request. The Thor was left running this desktop Steam client.
+1
View File
@@ -316,6 +316,7 @@ else
fi
cd "${repo_root}"
python3 tools/quest/build-driver.py "${NDK}"
python3 tools/release/runtime_inputs.py record
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
+5 -4
View File
@@ -34,9 +34,9 @@ export MOZ_SHM_NO_SEALS=1
# and the KGSL stand-in is not one. Its windows get shm buffers only, so GL programs on it draw with
# Mesa's software rasterizer, Plasma's own Qt Quick draws with Qt's software renderer (plasmashell
# crashes on llvmpipe here), and a Vulkan program cannot draw at all: games and emulators from the
# menu run through droiddeck-gpu (their own gamescope on the app's compositor), and Steam's desktop
# client uses software CEF on KDE. The session's own GL choice (zink on Turnip)
# is put back by droiddeck-gpu.
# menu run through droiddeck-gpu (their own gamescope on the app's compositor), and Steam goes back
# to the app as a Steam session - SteamOS's "Return to Gaming Mode". The session's own GL choice
# (zink on Turnip, for the Steam client) is put back by droiddeck-gpu.
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
# mpv refuses that software GL and then fails its X11 fallback (an assertion): allowed it, it plays.
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
@@ -61,7 +61,8 @@ chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null
# Fontconfig defaults and Android language fallbacks are set up by droiddeck-session before this
# script or any desktop program starts.
# Steam opens on KDE; Steam Big Picture explicitly hands off to the gaming session.
# The menu's "Steam" / "Steam Big Picture" entries and one entry per installed game: all of them
# hand off to the app (droiddeck-steam-launch), since the client cannot draw on this desktop.
export BL_DESKTOP=1
ln -sf /usr/local/bin/droiddeck-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
ln -sf /usr/local/bin/droiddeck-steam-shim /usr/local/bin/steam 2>/dev/null
@@ -20,7 +20,7 @@ import socket
import struct
import sys
SOCKET = "\0com.droiddeck.launcher.bwrap"
SOCKET = "\0" + os.environ.get("DROIDDECK_BWRAP_SOCKET", "com.droiddeck.launcher.bwrap")
VERSION = "bubblewrap 0.11.0 (droiddeck)"
# Options and how many arguments each takes; bwrap(1).
@@ -355,12 +355,11 @@ reap_orphans() {
# Gamescope's Wayland backend does not forward the outer clipboard into Xwayland.
# This helper owns only Android text selections and exits with this guest session.
if [ "${BL_DESKTOP:-}" != 1 ] && [ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
if [ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" &
fi
# KDE already has a session agent; starting another would race its request files.
[ "${BL_DESKTOP:-}" = 1 ] || start_agent
start_agent
case $mode in
desktop)
@@ -858,16 +857,9 @@ BUSCONF
droiddeck-steam-compat "$steam_root" 2>&1 &
# The client exits 42 when it has updated itself and wants a fresh start (steam.sh does this).
# BL_STEAM_UI=desktop = the client's desktop UI (a window, the library as a list), which the
# desktop's launchers ask for. KDE owns its windows when BL_DESKTOP=1.
# desktop's launchers ask for; gamescope shows one window at a time and the game takes over.
_bl_ui=(-gamepadui)
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle=vulkan)
if [ "${BL_DESKTOP:-}" = 1 ] && [ "${BL_STEAM_UI:-}" = desktop ]; then
# KDE uses QPainter/shm on Android. CEF's Vulkan buffers cannot be
# presented there; its software path keeps the library and dialogs on KDE.
_bl_cef=(-cef-disable-gpu)
_bl_ui=(-nobigpicture)
fi
# Deck mode, always outside the desktop UI: -steamdeck is the flag that puts
# the Quick Access Menu and the Deck settings pages on screen; the QAM's performance overlay
# controls stay greyed out without -steamos3, as SteamOS and Armada launch it. -steamos3 makes
@@ -937,7 +929,7 @@ BUSCONF
done
) &
fi
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*"
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*"
# An update that cannot install asks for a restart (rc=42) every time; the count is capped so a
# session can never again loop in silence, which reads as a menu opening and closing by itself.
steam_updates=0
@@ -1028,7 +1020,8 @@ BUSCONF
desktop_ui_pid=$!
fi
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-ozone-platform=x11 "${_bl_cef[@]}" "$@"
-no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 \
-cef-use-gl=angle -cef-use-angle=vulkan "$@"
rc=$?
if [ -n "$desktop_ui_pid" ]; then
kill "$desktop_ui_pid" 2>/dev/null || true
@@ -4,8 +4,10 @@
# droiddeck-steam-launch desktop [appid|steam-url] Steam's desktop UI, optionally a game
# droiddeck-steam-launch bigpicture [appid|steam-url] Big Picture
#
# The desktop client stays on KDE's Xwayland. Big Picture is the explicit handoff
# to the app's gaming session.
# The desktop (KDE Plasma) composites in software and has no dma-buf, so the client's own Vulkan
# window - and any game it starts - would die at its first frame there. The request goes to the app
# instead, which ends the desktop and starts a Steam session under gamescope in its place, as
# SteamOS's desktop hands Steam back to Gaming Mode.
set -u
ui=${1:-desktop}
target=${2:-}
@@ -18,31 +20,6 @@ case $target in
*) url=steam://rungameid/$target ;;
esac
if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
steam_root=${XDG_DATA_HOME:-${HOME:-/root}/.local/share}/Steam
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
# A second menu click forwards its URL to Steam's existing instance. Keep only
# one session supervisor, including while the client restarts for an update.
mkdir -p "${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck"
exec 9>"${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck/steam-desktop.lock"
if ! flock -n 9; then
# The supervisor may still be preparing Proton or updating Steam. Invoking
# the binary before its IPC pipe exists would start a competing client.
for ((attempt = 0; attempt < 180; attempt++)); do
pid=$(cat "$HOME/.steam/steam.pid" 2>/dev/null || true)
if [ -p "$HOME/.steam/steam.pipe" ] && [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
exec "$steam_root/steamrtarm64/steam" -nobigpicture -no-cef-sandbox \
-cef-ozone-platform=x11 -cef-disable-gpu "${url:-steam://open/library}"
fi
sleep 0.5
done
echo "droiddeck-steam-launch: the desktop client did not become ready" >&2
exit 69
fi
export BL_INSIDE=1 BL_STEAM_UI=desktop
exec /usr/local/bin/droiddeck-session steam "${url:-steam://open/library}"
fi
# Ask the app for a Steam session.
dir=${BL_LAUNCH_DIR:-}
if [ -z "$dir" ] || [ ! -d "$dir" ]; then
@@ -1,8 +1,9 @@
#!/bin/bash
# `steam` on the desktop. The client writes a menu entry per installed game that runs
# `steam steam://rungameid/<id>`, and its own launchers say `steam`. On the desktop that goes
# through droiddeck-steam-launch, which keeps the desktop client on KDE and
# hands URLs to a client already running there. Anywhere else it is the client itself.
# through droiddeck-steam-launch - which runs the client on the desktop itself when it draws with
# the GPU, hands the URL to a client already running there, and asks the app for a Steam session
# on a software desktop. Anywhere else it is the client itself.
set -u
if [ "${BL_DESKTOP:-}" = 1 ]; then
url=
+2 -1
View File
@@ -421,6 +421,7 @@ static int is_link_query(unsigned long request) {
}
void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc); /* kgslid.c */
#include "../../quest/kgsl_compat.h"
int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
@@ -440,7 +441,7 @@ int ioctl(int fd, unsigned long request, ...) {
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = real(fd, request, arg);
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
bl_kgsl_chip_id_fixup(request, arg, rc);
if (arg == NULL || !is_link_query(request)) return rc;
int saved = errno;
+3
View File
@@ -0,0 +1,3 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Shared with the Android driver wrapper so the two translation paths cannot drift. */
#include "../../quest/kgsl_compat.c"
+26
View File
@@ -0,0 +1,26 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Loaded as the AdrenoTools driver; DT_NEEDED points to the original Turnip.
* Vulkan/HAL symbols are resolved from that dependency. Its ioctl calls resolve here.
*/
#define _GNU_SOURCE
#include "kgsl_compat.h"
#include <dlfcn.h>
#include <pthread.h>
#include <stdarg.h>
#include <sys/syscall.h>
#include <unistd.h>
static int (*next_ioctl)(int, int, ...);
static pthread_once_t once = PTHREAD_ONCE_INIT;
static void resolve_ioctl(void) { next_ioctl = dlsym(RTLD_NEXT, "ioctl"); }
static int forward(int fd, unsigned long request, void *arg) {
pthread_once(&once, resolve_ioctl);
return next_ioctl ? next_ioctl(fd, (int)request, arg) : (int)syscall(SYS_ioctl, fd, request, arg);
}
__attribute__((visibility("default"))) int ioctl(int fd, int request, ...) {
va_list ap;
va_start(ap, request);
void *arg = va_arg(ap, void *);
va_end(ap);
return quest_kgsl_ioctl(forward, fd, (unsigned int)request, arg);
}
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Build the Quest allocation adapter around the unchanged bundled Android Turnip."""
import io
import json
from pathlib import Path
import subprocess
import sys
import tarfile
import tempfile
ROOT = Path(__file__).resolve().parents[2]
OUTPUT = ROOT / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst'
def build(ndk, output=OUTPUT):
hosts = list((Path(ndk) / 'toolchains/llvm/prebuilt').glob('*'))
if len(hosts) != 1:
raise ValueError('Expected one NDK host toolchain')
llvm = hosts[0] / 'bin'
original = ROOT / 'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst'
data = subprocess.run(['zstd', '-dc', str(original)], capture_output=True, check=True).stdout
with tempfile.TemporaryDirectory(prefix='quest-driver-') as folder:
work = Path(folder)
with tarfile.open(fileobj=io.BytesIO(data)) as archive:
# Only read the known driver entry; no archive paths are extracted.
driver = archive.extractfile('vulkan.ad07xx.so').read()
(work / 'vulkan.ad07xx.so').write_bytes(driver)
wrapper = work / 'libquest_turnip.so'
subprocess.run([
str(llvm / 'aarch64-linux-android26-clang'), '-shared', '-fPIC', '-O2',
'-Wall', '-Wextra', '-Werror', '-fvisibility=hidden',
'-Wl,-z,max-page-size=16384', '-Wl,-soname,libquest_turnip.so',
'-Wl,--no-as-needed', str(work / 'vulkan.ad07xx.so'), '-Wl,--as-needed',
str(ROOT / 'tools/quest/android_wrapper.c'), str(ROOT / 'tools/quest/kgsl_compat.c'),
'-ldl', '-llog', '-o', str(wrapper),
], check=True)
subprocess.run([str(llvm / 'llvm-strip'), '--strip-unneeded', str(wrapper)], check=True)
metadata = json.dumps({
'libraryName': 'libquest_turnip.so',
'name': 'Turnip Adreno 7xx - Quest GPUOBJ experimental',
'description': 'Bundled A7xx driver with the experimental Quest 3/3S allocation adapter.',
'driverVersion': 'Bundled Mesa + Quest GPUOBJ v1',
}, indent=2).encode() + b'\n'
stream = io.BytesIO()
with tarfile.open(fileobj=stream, mode='w', format=tarfile.USTAR_FORMAT) as archive:
for name, content in [('meta.json', metadata), ('libquest_turnip.so', wrapper.read_bytes()),
('vulkan.ad07xx.so', driver)]:
entry = tarfile.TarInfo(name)
entry.size = len(content)
entry.mode = 0o644
archive.addfile(entry, io.BytesIO(content))
compressed = subprocess.run(['zstd', '-q', '-19', '-c'], input=stream.getvalue(),
capture_output=True, check=True).stdout
output.parent.mkdir(parents=True, exist_ok=True)
output.write_bytes(compressed)
print(output)
if __name__ == '__main__':
build(sys.argv[1])
+78
View File
@@ -0,0 +1,78 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Quest experimental build, 2026-10-11.
* Horizon permits GPUOBJ allocation, but rejects the legacy GPUMEM alloc/free calls.
* Retry only those two calls after EACCES/EPERM. No change to device permissions.
*/
#include "kgsl_compat.h"
#include <errno.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#ifdef __ANDROID__
#include <android/log.h>
#endif
#if __SIZEOF_POINTER__ == 8
_Static_assert(sizeof(struct kgsl_gpumem_alloc_id) == 48, "KGSL alloc ABI");
_Static_assert(sizeof(struct kgsl_gpuobj_alloc) == 48, "GPUOBJ alloc ABI");
_Static_assert(sizeof(struct kgsl_gpuobj_free) == 32, "GPUOBJ free ABI");
_Static_assert(sizeof(struct kgsl_gpuobj_info) == 48, "GPUOBJ info ABI");
#endif
static void report(const char *operation, int error) {
static unsigned successes, failures;
unsigned *counter = error ? &failures : &successes;
/* Log the first success and at most eight failures per process. */
if (__atomic_fetch_add(counter, 1, __ATOMIC_RELAXED) >= (error ? 8u : 1u)) return;
int saved = errno;
#ifdef __ANDROID__
__android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "QuestKGSL",
"%s: GPUOBJ compatibility path, errno=%d", operation, error);
#else
fprintf(stderr, "[QuestKGSL] %s: GPUOBJ compatibility path, errno=%d\n", operation, error);
#endif
errno = saved;
}
int quest_kgsl_ioctl(quest_ioctl_fn real, int fd, unsigned long request, void *arg) {
int rc = real(fd, request, arg);
if (rc != -1 || (errno != EACCES && errno != EPERM) || arg == NULL) return rc;
if (request == IOCTL_KGSL_GPUMEM_ALLOC_ID) {
struct kgsl_gpumem_alloc_id *old = arg;
struct kgsl_gpuobj_alloc alloc = {.size = old->size, .flags = old->flags};
rc = real(fd, IOCTL_KGSL_GPUOBJ_ALLOC, &alloc);
if (rc != 0) { report("alloc failed", errno); return rc; }
struct kgsl_gpuobj_info info = {.id = alloc.id};
rc = real(fd, IOCTL_KGSL_GPUOBJ_INFO, &info);
int error = errno;
if (rc == 0 && (info.size > SIZE_MAX || alloc.mmapsize > SIZE_MAX ||
info.gpuaddr > ULONG_MAX || info.flags > UINT_MAX)) {
rc = -1;
error = EOVERFLOW;
}
if (rc != 0) {
/* The caller never receives this allocation, so clean it up on an INFO failure. */
struct kgsl_gpuobj_free release = {.id = alloc.id};
if (real(fd, IOCTL_KGSL_GPUOBJ_FREE, &release) != 0)
report("cleanup failed", errno);
errno = error;
report("info failed", error);
return rc;
}
old->id = alloc.id;
old->flags = (unsigned int)info.flags;
old->size = info.size;
old->mmapsize = alloc.mmapsize;
old->gpuaddr = info.gpuaddr;
report("allocation succeeded", 0);
return 0;
}
if (request == IOCTL_KGSL_GPUMEM_FREE_ID) {
const struct kgsl_gpumem_free_id *old = arg;
struct kgsl_gpuobj_free release = {.id = old->id};
rc = real(fd, IOCTL_KGSL_GPUOBJ_FREE, &release);
if (rc != 0) report("free failed", errno);
}
return rc;
}
+15
View File
@@ -0,0 +1,15 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
#ifndef DROIDDECK_QUEST_KGSL_COMPAT_H
#define DROIDDECK_QUEST_KGSL_COMPAT_H
/* Use the vendored Qualcomm UAPI, including its architecture-dependent ioctl sizes. */
#ifndef __user
#define __user
#endif
#include "../../app/src/main/cpp/adrenotools/src/hook/kgsl.h"
typedef int (*quest_ioctl_fn)(int, unsigned long, void *);
__attribute__((visibility("hidden")))
int quest_kgsl_ioctl(quest_ioctl_fn real, int fd, unsigned long request, void *arg);
#endif
+77
View File
@@ -0,0 +1,77 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
#include "kgsl_compat.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
static unsigned long calls[8];
static int count, old_error, alloc_error, info_error, free_error;
static unsigned long address;
static int mock(int fd, unsigned long request, void *arg) {
assert(fd == 42 && count < 8);
calls[count++] = request;
if (request == IOCTL_KGSL_GPUMEM_ALLOC_ID || request == IOCTL_KGSL_GPUMEM_FREE_ID) {
if (old_error) { errno = old_error; return -1; }
return 0;
}
if (request == IOCTL_KGSL_GPUOBJ_ALLOC) {
if (alloc_error) { errno = alloc_error; return -1; }
struct kgsl_gpuobj_alloc *p = arg;
assert(p->size == 123 && p->flags == 0x10000 && !p->metadata && !p->metadata_len);
p->id = 77; p->size = 4096; p->mmapsize = 8192;
return 0;
}
if (request == IOCTL_KGSL_GPUOBJ_INFO) {
struct kgsl_gpuobj_info *p = arg;
assert(p->id == 77);
if (info_error) { errno = info_error; return -1; }
p->gpuaddr = address; p->flags = 0x20000; p->size = 4096;
return 0;
}
if (request == IOCTL_KGSL_GPUOBJ_FREE) {
struct kgsl_gpuobj_free *p = arg;
assert(p->id == 77 && !p->flags && !p->priv && !p->type && !p->len);
if (free_error) { errno = free_error; return -1; }
return 0;
}
errno = EACCES;
return -1;
}
static struct kgsl_gpumem_alloc_id reset(void) {
count = old_error = alloc_error = info_error = free_error = 0;
address = 0x100000;
return (struct kgsl_gpumem_alloc_id){.size = 123, .flags = 0x10000};
}
int main(void) {
struct kgsl_gpumem_alloc_id p = reset();
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == 0 && count == 1);
p = reset(); old_error = EACCES;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == 0);
assert(count == 3 && p.id == 77 && p.size == 4096 && p.mmapsize == 8192);
assert(p.flags == 0x20000 && p.gpuaddr == address);
p = reset(); old_error = EPERM; address = 0;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == 0 && p.gpuaddr == 0);
p = reset(); old_error = ENOMEM;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == -1 && errno == ENOMEM && count == 1);
p = reset(); old_error = EACCES; alloc_error = ENOMEM;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == -1 && errno == ENOMEM && count == 2);
assert(p.id == 0 && p.size == 123);
p = reset(); old_error = EACCES; info_error = EIO;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == -1 && errno == EIO);
assert(count == 4 && calls[3] == IOCTL_KGSL_GPUOBJ_FREE && p.id == 0);
p = reset(); old_error = EACCES; info_error = EIO; free_error = ENOSPC;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == -1 && errno == EIO && count == 4);
p = reset(); old_error = EACCES;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, NULL) == -1 && count == 1);
p = reset(); old_error = EACCES;
assert(quest_kgsl_ioctl(mock, 42, 0x1234, &p) == -1 && errno == EACCES && count == 1);
struct kgsl_gpumem_free_id release = {.id = 77};
reset(); old_error = EACCES;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_FREE_ID, &release) == 0 && count == 2);
reset(); old_error = EPERM; free_error = EIO;
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_FREE_ID, &release) == -1 && errno == EIO && count == 2);
reset();
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_FREE_ID, &release) == 0 && count == 1);
puts("PASS: 12 GPUOBJ translation, passthrough, failure and cleanup scenarios");
}
+7 -2
View File
@@ -16,7 +16,9 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/build_local.sh',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal']
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
def digest(path):
@@ -48,11 +50,14 @@ def outputs(root):
for library in ['libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so']:
result['lib/arm64-v8a/' + library] = 'app/src/main/jniLibs/arm64-v8a/' + library
result['assets/pulseaudio.tzst'] = 'app/build/prepared-assets/pulseaudio.tzst'
result['assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst'] = \
'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst'
return result
def required():
paths = ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libblsession.so',
paths = ['assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst']
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libblsession.so',
'libblfastpath.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime']]
for arch in ['x86_64', 'i386']:
+1
View File
@@ -7,3 +7,4 @@ standard com.droiddeck.launcher -
pubg com.tencent.ig -pubg
antutu com.antutu.benchmark.full -antutu
ludashi com.ludashi.benchmark -ludashi
quest com.droiddeck.quest -quest
@@ -1,85 +0,0 @@
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Exercise the real cache with Vulkan lifetime callbacks, without an Android surface or GPU. */
#define VK_PRESENT_H
const char *vkp_gpu_name(void) { return "cache test"; }
void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; }
#include "vk_loader.h"
struct vk_api g_vk;
#include "effects_chain.c"
static unsigned views, sets, freed_views, freed_sets;
static VkImageView bound_view;
static VkResult VKAPI_CALL create_view(VkDevice dev, const VkImageViewCreateInfo *info,
const VkAllocationCallbacks *alloc, VkImageView *out) {
(void)dev; (void)alloc;
assert(info->image != VK_NULL_HANDLE);
*out = (VkImageView)(uintptr_t)(100 + ++views);
return VK_SUCCESS;
}
static VkResult VKAPI_CALL allocate_set(VkDevice dev, const VkDescriptorSetAllocateInfo *info,
VkDescriptorSet *out) {
(void)dev;
assert(info->descriptorPool != VK_NULL_HANDLE && info->descriptorSetCount == 1);
*out = (VkDescriptorSet)(uintptr_t)(200 + ++sets);
return VK_SUCCESS;
}
static void VKAPI_CALL update_set(VkDevice dev, uint32_t count, const VkWriteDescriptorSet *writes,
uint32_t copies, const VkCopyDescriptorSet *copy) {
(void)dev; (void)copies; (void)copy;
assert(count == 1);
bound_view = writes->pImageInfo->imageView;
}
static VkResult VKAPI_CALL free_set(VkDevice dev, VkDescriptorPool pool, uint32_t count,
const VkDescriptorSet *set) {
(void)dev; (void)pool;
assert(pool != VK_NULL_HANDLE && count == 1 && *set != VK_NULL_HANDLE);
freed_sets++;
return VK_SUCCESS;
}
static void VKAPI_CALL destroy_view(VkDevice dev, VkImageView view, const VkAllocationCallbacks *alloc) {
(void)dev; (void)alloc;
assert(view != VK_NULL_HANDLE);
freed_views++;
}
int main(int argc, char **argv) {
assert(argc == 2);
g_dev = (VkDevice)(uintptr_t)1;
g_dpool = (VkDescriptorPool)(uintptr_t)2;
g_dsl = (VkDescriptorSetLayout)(uintptr_t)3;
g_sampler = (VkSampler)(uintptr_t)4;
g_vk.CreateImageView = create_view;
g_vk.AllocateDescriptorSets = allocate_set;
g_vk.UpdateDescriptorSets = update_set;
g_vk.FreeDescriptorSets = free_set;
g_vk.DestroyImageView = destroy_view;
VkImage source = (VkImage)(uintptr_t)10;
assert(scene_ensure(source, 1280, 720) == 0);
VkImageView original = bound_view;
if (!strcmp(argv[1], "recycled")) {
/* The owner destroys the image, then Vulkan reuses its handle at the same size. */
vkp_effects_forget_image(source);
assert(freed_sets == 1 && freed_views == 1);
assert(scene_ensure(source, 1280, 720) == 0);
assert(bound_view != original && views == 2 && sets == 2);
} else if (!strcmp(argv[1], "unrelated")) {
vkp_effects_forget_image((VkImage)(uintptr_t)11);
vkp_effects_forget_image(VK_NULL_HANDLE);
assert(scene_ensure(source, 1280, 720) == 0);
assert(bound_view == original && views == 1 && !freed_views && !freed_sets);
} else if (!strcmp(argv[1], "repeated")) {
vkp_effects_forget_image(source);
vkp_effects_forget_image(source);
assert(freed_sets == 1 && freed_views == 1);
} else {
assert(!strcmp(argv[1], "resize"));
assert(scene_ensure(source, 1920, 1080) == 0);
assert(bound_view != original && views == 2 && freed_views == 1 && freed_sets == 1);
}
puts("PASS");
return 0;
}
-63
View File
@@ -1,63 +0,0 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
REPO = Path(__file__).resolve().parents[2]
class EffectsSourceCacheTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if compiler is None:
raise unittest.SkipTest('A host C compiler is required for the Vulkan cache test')
candidates = [Path('/usr/include/vulkan'), Path('/opt/homebrew/include/vulkan')]
for name in ('ANDROID_NDK_HOME', 'ANDROID_NDK_ROOT', 'NDK_HOME'):
if os.environ.get(name):
candidates.extend(Path(os.environ[name]).glob('toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan'))
for sdk in {Path(os.environ.get('ANDROID_HOME', '/nonexistent')),
Path(os.environ.get('ANDROID_SDK_ROOT', '/nonexistent')),
Path.home() / 'Library/Android/sdk', Path.home() / 'Android/Sdk'}:
candidates.extend(sdk.glob('ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan'))
headers = next((p for p in candidates if (p / 'vulkan.h').is_file()), None)
if headers is None:
raise unittest.SkipTest('Vulkan headers from the Android NDK or system SDK are required')
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-effects-cache-')
cls.addClassCleanup(cls.temp.cleanup)
folder = Path(cls.temp.name)
# Copy only Vulkan headers so Android's libc headers cannot shadow the host's libc.
shutil.copytree(headers, folder / 'include/vulkan', ignore=shutil.ignore_patterns('*.hpp'))
if (headers.parent / 'vk_video').is_dir():
shutil.copytree(headers.parent / 'vk_video', folder / 'include/vk_video')
cls.binary = folder / 'cache-test'
build = subprocess.run([compiler, '-std=c11', '-pthread', '-I' + str(folder / 'include'),
'-I' + str(REPO / 'app/src/main/cpp/waylandcomp/src'),
'-I' + str(REPO / 'app/src/main/cpp/shaders'),
str(REPO / 'tools/tests/effects_source_cache_harness.c'),
'-o', str(cls.binary)], capture_output=True, text=True)
if build.returncode:
raise RuntimeError(build.stderr)
def check_cache(self, case):
result = subprocess.run([str(self.binary), case], check=True, capture_output=True, text=True)
self.assertEqual('PASS', result.stdout.strip())
def test_recycled_image_handle_gets_a_new_view_and_descriptor(self):
self.check_cache('recycled')
def test_unrelated_and_null_images_preserve_the_current_view(self):
self.check_cache('unrelated')
def test_repeated_owner_invalidation_does_not_double_free(self):
self.check_cache('repeated')
def test_resize_replaces_the_cached_view_and_descriptor(self):
self.check_cache('resize')
if __name__ == '__main__':
unittest.main()
+84
View File
@@ -0,0 +1,84 @@
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
PROGRAM = r"""
#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#ifdef BACKEND
int ioctl(int fd, unsigned long request, ...) {
va_list ap;
va_start(ap, request);
int *value = va_arg(ap, int *);
va_end(ap);
assert(fd == -1 && request == 0x12345678 && value);
*value = 0x51;
errno = EACCES;
return -1;
}
#else
int main(int argc, char **argv) {
if (argc > 1) {
int value = 0;
assert(ioctl(-1, 0x12345678, &value) == -1);
assert(value == 0x51 && errno == EACCES);
} else {
int fds[2];
assert(pipe(fds) == 0);
struct termios term;
assert(ioctl(fds[0], TCGETS, &term) == -1 && errno == ENOTTY);
close(fds[0]);
close(fds[1]);
}
return 0;
}
#endif
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("gcc") and shutil.which("g++"),
"needs Linux, gcc and g++")
class FakeinputIoctlTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.addClassCleanup(cls.tmp.cleanup)
cls.path = Path(cls.tmp.name)
source = cls.path / "program.c"
source.write_text(PROGRAM)
subprocess.run(["gcc", "-o", str(cls.path / "program"), str(source)], check=True)
subprocess.run(["gcc", "-shared", "-fPIC", "-DBACKEND", "-o",
str(cls.path / "backend.so"), str(source)], check=True)
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread",
"-std=c++17", "-static-libstdc++", "-static-libgcc",
"-Wl,--exclude-libs,ALL", "-o", str(cls.path / "libfakeinput.so"),
str(SOURCE), "-ldl"], check=True)
def run_program(self, backend=False):
preload = str(self.path / "libfakeinput.so")
args = [str(self.path / "program")]
if backend:
preload += ":" + str(self.path / "backend.so")
args.append("backend")
subprocess.run(args, env=dict(os.environ, LD_PRELOAD=preload), check=True, timeout=10)
def test_later_interposer_receives_arguments_and_returns_errno(self):
self.run_program(backend=True)
def test_libc_passthrough_retains_kernel_error(self):
self.run_program()
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -0,0 +1,23 @@
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
QUEST = Path(__file__).resolve().parents[1] / 'quest'
@unittest.skipUnless(sys.platform == 'linux' and shutil.which('gcc'), 'needs Linux and gcc')
class QuestKgslTest(unittest.TestCase):
def test_allocation_passthrough_translation_and_cleanup(self):
with tempfile.TemporaryDirectory() as folder:
binary = str(Path(folder) / 'test-kgsl')
subprocess.run(['gcc', '-Wall', '-Wextra', '-Werror', '-O2', '-o', binary,
str(QUEST / 'test_kgsl_compat.c'), str(QUEST / 'kgsl_compat.c')], check=True)
result = subprocess.run([binary], capture_output=True, text=True, check=True, timeout=10)
self.assertIn('PASS: 12 GPUOBJ', result.stdout)
if __name__ == '__main__':
unittest.main()
+14
View File
@@ -55,6 +55,20 @@ class RuntimeInputsTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_changed_quest_source_rejects_old_outputs(self):
source = self.root / 'tools/quest/kgsl_compat.c'
source.parent.mkdir(parents=True)
source.write_text('old compatibility code')
runtime.record(self.root)
source.write_text('new compatibility code')
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_missing_quest_driver_cannot_be_attested(self):
(self.root / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst').unlink()
with self.assertRaisesRegex(ValueError, 'quest1.tzst'):
runtime.record(self.root)
def test_modified_prebuilt_binary_is_rejected(self):
runtime.record(self.root)
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
-117
View File
@@ -1,117 +0,0 @@
"""Desktop Steam stays on KDE; explicit Big Picture still switches sessions."""
import fcntl
import os
from pathlib import Path
import subprocess
import tempfile
import time
import unittest
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
class DesktopSteamLaunchTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.session = self.root / 'session'
self.session.mkdir()
self.env = dict(os.environ, HOME=str(self.root), XDG_DATA_HOME=str(self.root / 'data'),
XDG_CACHE_HOME=str(self.root / 'cache'), BL_DESKTOP='1',
BL_LAUNCH_DIR=str(self.session))
supervisor = self.root / 'supervisor'
supervisor.write_text('#!/bin/bash\nprintf "%s\\n" "$BL_INSIDE" "$BL_STEAM_UI" "$DISPLAY" "$@"\n')
supervisor.chmod(0o755)
self.launcher = self.root / 'launch'
self.launcher.write_text((BIN / 'droiddeck-steam-launch').read_text().replace(
'/usr/local/bin/droiddeck-session', str(supervisor)))
def launch(self, *args):
return subprocess.run(['bash', str(self.launcher), *args], env=self.env,
text=True, capture_output=True)
def test_desktop_keeps_display_and_does_not_request_session_switch(self):
self.env['DISPLAY'] = ':7'
result = self.launch('desktop')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines(), ['1', 'desktop', ':7', 'steam', 'steam://open/library'])
self.assertFalse((self.session / 'steam-launch').exists())
def test_desktop_game_url_goes_to_client(self):
result = self.launch('desktop', '501590')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines()[-1], 'steam://rungameid/501590')
self.assertFalse((self.session / 'steam-launch').exists())
def test_second_click_forwards_without_another_supervisor(self):
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
lock.parent.mkdir(parents=True)
steam = self.root / 'data/Steam/steamrtarm64/steam'
steam.parent.mkdir(parents=True)
steam.write_text('#!/bin/bash\nprintf "%s\\n" "$@"\n')
steam.chmod(0o755)
(self.root / '.steam').mkdir()
os.mkfifo(self.root / '.steam/steam.pipe')
(self.root / '.steam/steam.pid').write_text(str(os.getpid()))
with lock.open('w') as handle:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
result = self.launch('desktop', 'steam://open/settings')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines(), ['-nobigpicture', '-no-cef-sandbox', '-cef-ozone-platform=x11',
'-cef-disable-gpu', 'steam://open/settings'])
self.assertFalse((self.session / 'steam-launch').exists())
def test_second_click_waits_for_steam_ipc_during_startup(self):
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
lock.parent.mkdir(parents=True)
steam = self.root / 'data/Steam/steamrtarm64/steam'
steam.parent.mkdir(parents=True)
marker = self.root / 'forwarded'
steam.write_text(f'#!/bin/bash\ntouch "{marker}"\n')
steam.chmod(0o755)
with lock.open('w') as handle:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
process = subprocess.Popen(['bash', str(self.launcher), 'desktop'], env=self.env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
time.sleep(0.7)
self.assertIsNone(process.poll())
self.assertFalse(marker.exists())
(self.root / '.steam').mkdir()
(self.root / '.steam/steam.pid').write_text(str(os.getpid()))
os.mkfifo(self.root / '.steam/steam.pipe')
_, stderr = process.communicate(timeout=3)
self.assertEqual(process.returncode, 0, stderr)
self.assertTrue(marker.exists())
finally:
if process.poll() is None:
process.kill()
process.communicate()
def test_big_picture_requests_explicit_handoff(self):
result = self.launch('bigpicture')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.session / 'steam-launch').read_text(), 'ui=bigpicture\nurl=\n')
def test_outside_desktop_preserves_session_request(self):
self.env.pop('BL_DESKTOP')
result = self.launch('desktop', 'steam://open/settings')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.session / 'steam-launch').read_text(),
'ui=desktop\nurl=steam://open/settings\n')
def test_invalid_target_cannot_trigger_a_handoff(self):
self.assertEqual(self.launch('desktop', 'bad').returncode, 64)
self.assertFalse((self.session / 'steam-launch').exists())
def test_cef_software_is_scoped_to_the_kde_client(self):
source = (BIN / 'droiddeck-session').read_text()
setup = source[source.index(' _bl_ui=(-gamepadui)'):source.index(' # Deck mode, always')]
for desktop, ui, software in [('1', 'desktop', True), ('1', 'bigpicture', False), ('', 'desktop', False)]:
with self.subTest(desktop=desktop, ui=ui):
env = dict(self.env, BL_DESKTOP=desktop, BL_STEAM_UI=ui)
result = subprocess.check_output(['bash', '-c', setup + '\nprintf "%s\\n" "${_bl_cef[@]}"'],
env=env, text=True)
self.assertEqual('-cef-disable-gpu' in result, software)
self.assertEqual('-cef-use-angle=vulkan' in result, not software)