diff --git a/app/src/main/java/com/steamdeck/launcher/MainActivity.kt b/app/src/main/java/com/steamdeck/launcher/MainActivity.kt index c0a8a24480..2e3b8cfaac 100644 --- a/app/src/main/java/com/steamdeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/steamdeck/launcher/MainActivity.kt @@ -22,6 +22,7 @@ import com.steamdeck.launcher.gpu.FrameGen import com.steamdeck.launcher.gpu.LinuxVulkanDriver import com.steamdeck.launcher.gpu.LinuxVulkanDriverManager import com.steamdeck.launcher.gpu.TurnipDriver +import com.steamdeck.launcher.gpu.TurnipReleases import com.steamdeck.launcher.gpu.LsfgNative import com.steamdeck.launcher.runtime.LinuxRuntime import com.steamdeck.launcher.runtime.DesktopCatalog @@ -105,6 +106,13 @@ class MainActivity : ComponentActivity() { private var clientDirectAudio by mutableStateOf(false) private var mic by mutableStateOf(false) private var linuxRows by mutableStateOf>(emptyList()) + /** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */ + private var linuxDownloads by mutableStateOf>(emptyList()) + private var androidDownloads by mutableStateOf>(emptyList()) + private var releaseStatus by mutableStateOf("Check for the latest Turnip") + private var releaseChecking = false + /** Asset name -> download percent, while it downloads. */ + private val releaseProgress = HashMap() private var linuxSteam by mutableStateOf("") private var linuxDesktop by mutableStateOf("") private var androidRows by mutableStateOf>(emptyList()) @@ -517,6 +525,7 @@ class MainActivity : ComponentActivity() { addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null, addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(), addedGamesArt = addedGamesArt, + linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, releaseStatus = releaseStatus, ), ModeSettingsActions( onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap }, @@ -525,10 +534,12 @@ class MainActivity : ComponentActivity() { onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() }, onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) }, - onRemoveLinux = { id -> LinuxVulkanDriverManager(this).removeDriver(id); refreshDrivers() }, + onRemoveLinux = { id -> deleteDriver(id, linux = true) }, + onRefreshReleases = { checkLatestTurnip() }, + onDownloadDriver = { name -> downloadReleaseDriver(name) }, onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() }, onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) }, - onRemoveAndroid = { id -> TurnipDriver(this).remove(id); refreshDrivers() }, + onRemoveAndroid = { id -> deleteDriver(id, linux = false) }, onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t }, onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy }, onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o }, @@ -676,6 +687,7 @@ class MainActivity : ComponentActivity() { for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), "imported" + td.driverVersion(id).let { if (it.isEmpty()) "" else " · $it" }, true)) } androidSelected = SessionPrefs.androidDriver(this) + refreshReleaseRows() } /** @@ -705,6 +717,112 @@ class MainActivity : ComponentActivity() { }, "import-driver").start() } + /** + * Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a + * session never starts on a driver that is gone; a release download is forgotten, so the menu + * offers it again. + */ + private fun deleteDriver(id: String, linux: Boolean) { + if (linux) { + LinuxVulkanDriverManager(this).removeDriver(id) + for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) { + if (SessionPrefs.linuxDriver(this, mode) == id) SessionPrefs.setLinuxDriver(this, mode, "") + } + } else { + TurnipDriver(this).remove(id) + if (SessionPrefs.androidDriver(this) == id) SessionPrefs.setAndroidDriver(this, TurnipDriver.AUTO) + } + TurnipReleases.forget(this, id) + android.widget.Toast.makeText(this, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show() + refreshDrivers() + } + + /** The download entries and the refresh line, from the release the last check found. */ + private fun refreshReleaseRows() { + val release = TurnipReleases.cached(this) + val lm = LinuxVulkanDriverManager(this) + val td = TurnipDriver(this) + fun rows(linux: Boolean) = release?.assets.orEmpty() + .filter { it.linux == linux } + .filter { a -> TurnipReleases.installedId(this, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null } + .map { a -> + val mb = "%.1f MB".format(a.size / 1_048_576.0) + com.steamdeck.launcher.ui.DownloadRow( + a.name, "Download Turnip ${release!!.tag}", + releaseProgress[a.name]?.let { "${a.gpus} · downloading $it%" } ?: "${a.gpus} · $mb", + ) + } + linuxDownloads = rows(linux = true) + androidDownloads = rows(linux = false) + if (!releaseChecking) releaseStatus = when (release) { + null -> "Check for the latest Turnip" + else -> "Latest: ${release.tag} · checked ${ago(release.checkedAt)} · tap to refresh" + } + } + + private fun ago(t: Long): String { + val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0) + return when { + m < 1 -> "just now" + m < 60 -> "$m min ago" + m < 48 * 60 -> "${m / 60} h ago" + else -> "${m / (24 * 60)} days ago" + } + } + + /** Only when the user taps refresh: nothing goes online on its own. */ + private fun checkLatestTurnip() { + if (releaseChecking) return + releaseChecking = true + releaseStatus = "Checking Banners-Turnip…" + Thread({ + val problem = try { TurnipReleases.refresh(this); null } catch (e: Exception) { + Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed" + } + ui.post { + releaseChecking = false + refreshReleaseRows() + if (problem != null) releaseStatus = "Couldn't check: $problem · tap to retry" + } + }, "turnip-release-check").start() + } + + /** Download one release driver and import it through the same importer a picked zip uses. */ + private fun downloadReleaseDriver(assetName: String) { + val asset = TurnipReleases.cached(this)?.assets?.firstOrNull { it.name == assetName } ?: return + if (releaseProgress.containsKey(assetName)) return + releaseProgress[assetName] = 0 + refreshReleaseRows() + Thread({ + var file: java.io.File? = null + val problem = try { + file = TurnipReleases.download(this, asset) { pct -> + ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() } + } + val uri = Uri.fromFile(file) + val id = if (asset.linux) LinuxVulkanDriverManager(this).installDriver(uri, asset.name) + else TurnipDriver(this).installFromZip(uri, asset.name) + TurnipReleases.recordDownload(this, asset, id) + null + } catch (e: IllegalArgumentException) { + e.message + } catch (e: Exception) { + Log.w(TAG, "release driver download", e) + "Download failed: ${e.message}" + } finally { + file?.let { com.steamdeck.launcher.core.FileUtils.delete(it) } + } + ui.post { + releaseProgress.remove(assetName) + android.widget.Toast.makeText( + this, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu", + android.widget.Toast.LENGTH_LONG, + ).show() + refreshDrivers() + } + }, "download-turnip").start() + } + private fun displayNameOf(uri: Uri): String? = if (uri.scheme == "file") uri.lastPathSegment else try { contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null) ?.use { c -> if (c.moveToFirst()) c.getString(0) else null } diff --git a/app/src/main/java/com/steamdeck/launcher/gpu/TurnipReleases.kt b/app/src/main/java/com/steamdeck/launcher/gpu/TurnipReleases.kt new file mode 100644 index 0000000000..90eb2bc893 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/gpu/TurnipReleases.kt @@ -0,0 +1,153 @@ +package com.steamdeck.launcher.gpu + +import android.content.Context +import com.steamdeck.launcher.core.FileUtils +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL + +/** + * The latest Banners-Turnip release, offered in both driver menus as downloads. Checked only when + * the user taps refresh - the result is remembered, so the menu shows the last release found + * without going online. A download goes through the same importer as a zip picked by hand, so it + * gets the same checks and lands as an ordinary imported driver. + * + * Asset names are `Turnip-[-variant][-Linux|-Wayland].zip`: the plain ones are AdrenoTools + * drivers for the display driver menu, `-Linux` ones are glibc drivers for the runtime driver menu, + * and `-Wayland` ones are for a path this app does not have, so they are never offered. + */ +object TurnipReleases { + private const val API = "https://api.github.com/repos/The412Banner/Banners-Turnip/releases/latest" + private const val PREFS = "turnip_releases" + private const val KEY_RELEASE = "latest" + private const val KEY_DOWNLOADS = "downloads" + + class Asset(val name: String, val url: String, val size: Long, val linux: Boolean, val gpus: String) + class Release(val tag: String, val assets: List, val checkedAt: Long) + + /** The release found by the last check, or null when the user has never checked. */ + fun cached(context: Context): Release? { + val raw = prefs(context).getString(KEY_RELEASE, null) ?: return null + return runCatching { parse(JSONObject(raw)) }.getOrNull() + } + + /** Ask GitHub for the latest release now and remember it. Throws on network or API errors. */ + fun refresh(context: Context): Release { + val c = URL(API).openConnection() as HttpURLConnection + c.connectTimeout = 15_000 + c.readTimeout = 20_000 + c.setRequestProperty("Accept", "application/vnd.github+json") + c.setRequestProperty("User-Agent", "SteamDeck-app") + try { + val code = c.responseCode + if (code == 403 || code == 429) throw IOException("GitHub's rate limit was hit - try again later") + if (code != 200) throw IOException("GitHub answered HTTP $code") + val body = c.inputStream.bufferedReader().use { it.readText() } + val json = JSONObject(body) + val tag = json.getString("tag_name") + val assets = JSONArray() + val list = json.optJSONArray("assets") ?: JSONArray() + for (i in 0 until list.length()) { + val a = list.getJSONObject(i) + assets.put(JSONObject().put("name", a.getString("name")) + .put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))) + } + val stored = JSONObject().put("tag", tag).put("assets", assets).put("checkedAt", System.currentTimeMillis()) + prefs(context).edit().putString(KEY_RELEASE, stored.toString()).apply() + return parse(stored) + } finally { + c.disconnect() + } + } + + private fun parse(json: JSONObject): Release { + val tag = json.getString("tag") + val out = ArrayList() + val list = json.getJSONArray("assets") + for (i in 0 until list.length()) { + val a = list.getJSONObject(i) + classify(a.getString("name"), tag)?.let { (linux, gpus) -> + out.add(Asset(a.getString("name"), a.getString("url"), a.optLong("size"), linux, gpus)) + } + } + return Release(tag, out, json.optLong("checkedAt")) + } + + /** (is it a Linux driver, which GPUs it is for), or null for anything this app cannot use. */ + internal fun classify(name: String, tag: String): Pair? { + val prefix = "Turnip-$tag" + if (!name.startsWith(prefix) || !name.endsWith(".zip")) return null + var variant = name.removePrefix(prefix).removeSuffix(".zip") + if (variant.endsWith("-Wayland")) return null + val linux = variant.endsWith("-Linux") + variant = variant.removeSuffix("-Linux") + val gpus = when { + variant.isEmpty() -> "Adreno 6xx/7xx" + variant == "-A8xx" -> "Adreno 8xx" + variant.startsWith("-710-720") -> "Adreno 710/720" + if (variant.contains("Test")) " (test)" else "" + else -> variant.trimStart('-') + } + return linux to gpus + } + + /** The id an asset was installed as, when it was downloaded before and is still installed. */ + fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? = + downloads(context).optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) } + + fun recordDownload(context: Context, asset: Asset, id: String) { + prefs(context).edit().putString(KEY_DOWNLOADS, downloads(context).put(asset.name, id).toString()).apply() + } + + /** Forget a deleted driver, so its release offers the download again. */ + fun forget(context: Context, id: String) { + val d = downloads(context) + val keys = d.keys().asSequence().filter { d.optString(it) == id }.toList() + if (keys.isEmpty()) return + keys.forEach { d.remove(it) } + prefs(context).edit().putString(KEY_DOWNLOADS, d.toString()).apply() + } + + /** Download an asset into the cache; the caller imports it and deletes the file. */ + fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File { + val target = File(context.cacheDir, asset.name) + val c = URL(asset.url).openConnection() as HttpURLConnection + c.connectTimeout = 15_000 + c.readTimeout = 60_000 + c.setRequestProperty("User-Agent", "SteamDeck-app") + c.instanceFollowRedirects = true + try { + if (c.responseCode != 200) throw IOException("download answered HTTP ${c.responseCode}") + val total = c.contentLengthLong.takeIf { it > 0 } ?: asset.size + c.inputStream.use { input -> + FileOutputStream(target).use { out -> + val buf = ByteArray(1 shl 16) + var done = 0L + var last = -1 + while (true) { + val r = input.read(buf) + if (r <= 0) break + out.write(buf, 0, r) + done += r + val pct = if (total > 0) (done * 100 / total).toInt() else 0 + if (pct != last) { last = pct; progress(pct) } + } + } + } + return target + } catch (e: Exception) { + FileUtils.delete(target) + throw e + } finally { + c.disconnect() + } + } + + private fun downloads(context: Context): JSONObject = + runCatching { JSONObject(prefs(context).getString(KEY_DOWNLOADS, "{}")!!) }.getOrDefault(JSONObject()) + + private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) +} diff --git a/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt index 2a3e60ab2e..3b7a03350a 100644 --- a/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt @@ -3,6 +3,10 @@ package com.steamdeck.launcher.ui import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material.icons.outlined.Download +import androidx.compose.material.icons.outlined.Refresh import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -19,6 +23,9 @@ import com.steamdeck.launcher.session.SessionService class DriverRow(val id: String, val name: String, val detail: String, val removable: Boolean) +/** A driver from the latest Banners-Turnip release that is not installed yet; [key] is its asset name. */ +class DownloadRow(val key: String, val label: String, val detail: String) + class ModeSettings( val mode: String, val resolutionCap: Int, @@ -49,6 +56,10 @@ class ModeSettings( val addedGamesDirs: List? = null, val addedGames: List = emptyList(), val addedGamesArt: Boolean = true, + /** Latest Banners-Turnip release: what each driver menu offers to download, and the refresh line. */ + val linuxDownloads: List = emptyList(), + val androidDownloads: List = emptyList(), + val releaseStatus: String = "Check for the latest Turnip", ) /** One added game as the settings page shows it: its folder, the chosen .exe, the other .exe files it could be. */ @@ -63,6 +74,9 @@ class ModeSettingsActions( val onSelectLinux: (String) -> Unit, val onImportLinux: () -> Unit, val onRemoveLinux: (String) -> Unit, + val onRefreshReleases: () -> Unit = {}, + /** Asset name of the release driver to download. */ + val onDownloadDriver: (String) -> Unit = {}, val onSelectAndroid: (String) -> Unit, val onImportAndroid: () -> Unit, val onRemoveAndroid: (String) -> Unit, @@ -131,12 +145,16 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { (if (steam) "Used by Steam and games." else "Used by desktop apps.") + " Applies next session.", s.linuxRows, s.linuxSelected, importLabel = "Import Turnip zip…", onSelect = a.onSelectLinux, onRemove = a.onRemoveLinux, onImport = a.onImportLinux, + downloads = s.linuxDownloads, releaseStatus = s.releaseStatus, + onRefresh = a.onRefreshReleases, onDownload = a.onDownloadDriver, ) DriverRowMenu( host, "panel", "Display driver", "Used by the compositor in both modes. Restart the app to apply.", s.androidRows, s.androidSelected, importLabel = "Import an AdrenoTools zip…", onSelect = a.onSelectAndroid, onRemove = a.onRemoveAndroid, onImport = a.onImportAndroid, + downloads = s.androidDownloads, releaseStatus = s.releaseStatus, + onRefresh = a.onRefreshReleases, onDownload = a.onDownloadDriver, ) } SettingsGroup(if (steam) "Touch & controls" else "Touch") { @@ -263,9 +281,12 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { private fun DriverRowMenu( host: MenuHost, key: String, label: String, hint: String, rows: List, selected: String, importLabel: String, onSelect: (String) -> Unit, onRemove: (String) -> Unit, onImport: () -> Unit, + downloads: List = emptyList(), releaseStatus: String? = null, + onRefresh: () -> Unit = {}, onDownload: (String) -> Unit = {}, ) { val open = host.open == key val colors = MaterialTheme.colorScheme + var confirmDelete by remember { mutableStateOf(null) } SettingsRow(label, hint, highlighted = open) { androidx.compose.foundation.layout.Box { ValueChip(rows.firstOrNull { it.id == selected }?.name ?: rows.firstOrNull()?.name ?: "-", open) { host.open = if (open) null else key } @@ -273,16 +294,36 @@ private fun DriverRowMenu( for (row in rows) MenuItem( row.name, checked = row.id == selected, detail = row.detail.ifEmpty { null }, trailing = if (row.removable) ({ - Text( - "✕", fontSize = 12.sp, color = colors.onSurfaceVariant, - modifier = Modifier.size(24.dp).padding(4.dp).clickable { onRemove(row.id); host.open = null }, + androidx.compose.material3.Icon( + Icons.Outlined.Delete, contentDescription = "Delete ${row.name}", + tint = colors.onSurfaceVariant, + modifier = Modifier.size(32.dp).clickable { confirmDelete = row }.padding(6.dp), ) }) else null, ) { onSelect(row.id); host.open = null } + // The latest Banners-Turnip release: what is not installed yet, then the refresh line. + // Tapping either keeps the menu open, so the progress and the result show in place. + for (d in downloads) MenuItem( + d.label, checked = false, detail = d.detail, + leading = { androidx.compose.material3.Icon(Icons.Outlined.Download, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(18.dp)) }, + ) { onDownload(d.key) } + if (releaseStatus != null) MenuItem( + releaseStatus, checked = false, + leading = { androidx.compose.material3.Icon(Icons.Outlined.Refresh, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(18.dp)) }, + ) { onRefresh() } MenuItem(importLabel, checked = false) { host.open = null; onImport() } } } } + confirmDelete?.let { row -> + androidx.compose.material3.AlertDialog( + onDismissRequest = { confirmDelete = null }, + title = { Text("Delete ${row.name}?") }, + text = { Text("Its files are removed from the app. If it is the driver in use, the default takes its place.", fontSize = 13.sp) }, + confirmButton = { androidx.compose.material3.TextButton(onClick = { confirmDelete = null; onRemove(row.id) }) { Text("Delete") } }, + dismissButton = { androidx.compose.material3.TextButton(onClick = { confirmDelete = null }) { Text("Cancel") } }, + ) + } } /** The Resolution menu's "Custom…" entry. */