diff --git a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt index df3f07836..ff5ce18fe 100644 --- a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt +++ b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt @@ -11,6 +11,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.mutableIntStateOf +import com.droiddeck.launcher.gpu.DriverBundle import com.droiddeck.launcher.gpu.DriverPairs import com.droiddeck.launcher.gpu.GpuInfo import com.droiddeck.launcher.gpu.LinuxVulkanDriver @@ -27,7 +28,8 @@ import com.droiddeck.launcher.wayland.CompositorHost /** * The GPU drivers: what this GPU is, the matched driver pairs the release repos offer for it, and * - in Auto, the default - keeping the recommended pair installed and set. Under Advanced, the - * Linux (runtime) and Android (display) lists as before, each picked on its own. The launcher + * Linux (runtime) and Android (display) lists as before, each picked on its own - except a + * bundle's two halves (DriverBundle), which are always picked, and deleted, together. The launcher * screen keeps one and hands it to the Components page's GPU drivers tab. */ internal class DriverMenus(private val activity: Activity, private val ui: Handler) { @@ -50,6 +52,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl var pairPercent by mutableIntStateOf(-1) /** What Auto last did or found, for the line under the pair in use. */ var autoStatus by mutableStateOf("") + /** The bundle both drivers are set to, as "DD-Turnip 0.1.0", or null when they are not one. */ + var activeBundle by mutableStateOf(null) private var autoCheckedThisProcess = false fun state() = GpuDriversState( @@ -59,6 +63,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl autoStatus = autoStatus, releaseStatus = releaseStatus, checking = releaseChecking, linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected, linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled, + activeBundle = activeBundle, ) var androidRows by mutableStateOf>(emptyList()) var androidSelected by mutableStateOf("") @@ -66,9 +71,13 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl fun refreshDrivers() { val lm = LinuxVulkanDriverManager(activity) fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED + val bundles = DriverBundle.all(activity) + fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let { + DriverRow(id, it.label, "Android + Linux: sets the ${if (linux) "display" else "runtime"} driver with it", true, DriverRow.BUNDLE) + } linuxRows = LinuxVulkanDriver.optionValues(activity).map { id -> if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false) - else DriverRow( + else bundleRow(id, linux = true) ?: DriverRow( id, lm.getDriverName(id), listOfNotNull( lm.getDriverVersion(id).takeIf { it.isNotEmpty() }, @@ -88,17 +97,18 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl false, )) for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED)) - for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id))) + for (id in td.enumerateImported()) add(bundleRow(id, linux = false) ?: DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id))) } canRestoreBundled = td.hiddenBundled().isNotEmpty() androidSelected = SessionPrefs.androidDriver(activity) + activeBundle = DriverBundle.active(activity)?.label refreshReleaseRows() refreshPairs() } /** One line for the settings row that opens this: "Auto · WinNative · Balanced". */ fun summary(): String { - val active = pairRows.firstOrNull { it.active }?.name + val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle return (if (mode == SessionPrefs.GPU_DRIVERS_AUTO) "Auto" else "Manual") + (active?.let { " · $it" } ?: "") } @@ -106,11 +116,13 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl fun refreshPairs() { val lm = LinuxVulkanDriverManager(activity) val td = TurnipDriver(activity) - val recommended = DriverPairs.recommendedKey(gpu) - pairRows = DriverPairs.from(TurnipReleases.cached(activity)).map { p -> - val displayId = p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) } - val linuxId = p.linux?.let { TurnipReleases.installedId(activity, it, lm::isInstalled) } - val mb = listOfNotNull(p.display, p.linux).sumOf { it.size } / 1_048_576.0 + val pairs = DriverPairs.from(TurnipReleases.cached(activity)) + val recommended = DriverPairs.recommendedKey(gpu, pairs) + pairRows = pairs.map { p -> + val bundle = p.bundle?.let { installedBundle(it) } + val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) } + val linuxId = if (p.bundle != null) bundle?.linuxId else p.linux?.let { TurnipReleases.installedId(activity, it, lm::isInstalled) } + val mb = p.assets.sumOf { it.size } / 1_048_576.0 PairRow( key = p.key, name = p.name, version = p.version, detail = if (!p.complete) "Only one half is published right now" else "%.0f MB for both".format(mb), @@ -140,8 +152,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl if (mode != SessionPrefs.GPU_DRIVERS_AUTO || pairBusy != null || releaseChecking) return if (!force && autoCheckedThisProcess) return autoCheckedThisProcess = true - val key = DriverPairs.recommendedKey(gpu) - if (key == null) { + if (DriverPairs.recommendedKey(gpu, emptyList()) == null) { autoStatus = "No drivers to set: ${gpu.supportText.lowercase()}" return } @@ -156,7 +167,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl releaseChecking = false refreshReleaseRows() refreshPairs() - val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key } + val pairs = DriverPairs.from(TurnipReleases.cached(activity)) + val key = DriverPairs.recommendedKey(gpu, pairs) + val pair = pairs.firstOrNull { it.key == key } val row = pairRows.firstOrNull { it.key == key } when { row?.active == true -> autoStatus = "Up to date" + (problem?.let { " (couldn't check: $it)" } ?: "") @@ -181,8 +194,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl * ones the new pair replaces are removed. */ private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean) { - val display = pair.display ?: return - val linux = pair.linux ?: return + if (!pair.complete) return pairBusy = pair.key pairPercent = 0 if (auto) autoStatus = "Downloading ${pair.name} ${pair.version}…" @@ -191,11 +203,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl val td = TurnipDriver(activity) var downloaded = false val result = runCatching { - val halves = listOf(display, linux) - halves.mapIndexed { i, asset -> - TurnipReleases.installedId(activity, asset) { id -> if (asset.linux) lm.isInstalled(id) else td.isInstalled(id) } - ?: installAsset(asset) { pct -> ui.post { pairPercent = (i * 100 + pct) / halves.size } }.also { downloaded = true } + val zips = pair.assets + val ids = zips.mapIndexed { i, asset -> + installedIdOf(asset) + ?: installAsset(asset) { pct -> ui.post { pairPercent = (i * 100 + pct) / zips.size } }.also { downloaded = true } } + if (pair.bundle != null) DriverBundle.get(activity, ids[0])!!.let { listOf(it.androidId, it.linuxId) } else ids } ui.post { pairBusy = null @@ -208,7 +221,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl if (auto) { val previous = SessionPrefs.gpuAutoInstalled(activity) for (id in previous - setOf(displayId, linuxId)) { - if (lm.isInstalled(id)) lm.removeDriver(id) else td.remove(id) + val bundle = DriverBundle.containing(activity, id, lm.isInstalled(id)) + when { + bundle != null -> { DriverBundle.remove(activity, bundle); TurnipReleases.forget(activity, bundle.id) } + lm.isInstalled(id) -> lm.removeDriver(id) + else -> td.remove(id) + } TurnipReleases.forget(activity, id) } SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId)) @@ -227,14 +245,31 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl }, "gpu-driver-pair").start() } - /** One release asset, downloaded, checked and installed through the importer; returns its id. */ + /** The bundle a release bundle was downloaded as, while both its halves are installed. */ + private fun installedBundle(asset: TurnipReleases.Asset): DriverBundle.Bundle? = + TurnipReleases.installedId(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) } + + /** The id a release asset was installed as (a bundle's id for a bundle), or null when it is not installed. */ + private fun installedIdOf(asset: TurnipReleases.Asset): String? = when { + asset.bundle -> installedBundle(asset)?.id + asset.linux -> TurnipReleases.installedId(activity, asset, LinuxVulkanDriverManager(activity)::isInstalled) + else -> TurnipReleases.installedId(activity, asset, TurnipDriver(activity)::isInstalled) + } + + /** + * One release asset, downloaded, checked and installed through the importer; returns its id, + * a bundle's id for a bundle. + */ private fun installAsset(asset: TurnipReleases.Asset, progress: (Int) -> Unit): String { var file: File? = null try { file = TurnipReleases.download(activity, asset, progress) val uri = Uri.fromFile(file) - val id = if (asset.linux) LinuxVulkanDriverManager(activity).installDriver(uri, asset.name) - else TurnipDriver(activity).installFromZip(uri, asset.name) + val id = when { + asset.bundle -> DriverBundle.install(activity, uri).id + asset.linux -> LinuxVulkanDriverManager(activity).installDriver(uri, asset.name) + else -> TurnipDriver(activity).installFromZip(uri, asset.name) + } TurnipReleases.recordDownload(activity, asset, id) return id } finally { @@ -244,14 +279,29 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl /** * Import off the main thread - a driver zip is a few MB and the glibc check reads the whole - * library - then say what happened. A refusal's message is the user-facing reason. + * library - then say what happened. A refusal's message is the user-facing reason. A bundle, + * from any import, installs both halves and is set as both drivers at once. [linux] null (the + * tab's own Import .zip) takes a single driver to whichever list its libc belongs in. */ - fun importDriver(uri: Uri, linux: Boolean) { + fun importDriver(uri: Uri, linux: Boolean?) { val name = activity.displayNameOf(uri) Thread({ + var bundle: DriverBundle.Bundle? = null val problem = try { - if (linux) LinuxVulkanDriverManager(activity).installDriver(uri, name) - else TurnipDriver(activity).installFromZip(uri, name) + when { + DriverBundle.isBundle(activity, uri) -> bundle = DriverBundle.install(activity, uri) + linux == true -> LinuxVulkanDriverManager(activity).installDriver(uri, name) + linux == false -> TurnipDriver(activity).installFromZip(uri, name) + else -> try { + TurnipDriver(activity).installFromZip(uri, name) + } catch (display: IllegalArgumentException) { + try { + LinuxVulkanDriverManager(activity).installDriver(uri, name) + } catch (runtime: IllegalArgumentException) { + throw IllegalArgumentException("Not a driver zip: neither an AdrenoTools driver, a -Linux Turnip nor an Android + Linux bundle") + } + } + } null } catch (e: IllegalArgumentException) { e.message @@ -260,21 +310,54 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl "Import failed: ${e.message}" } ui.post { + val done = bundle?.let { useBundle(it) } ?: "Imported ${name ?: "driver"}" android.widget.Toast.makeText( - activity, problem ?: "Imported ${name ?: "driver"}", - if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT, + activity, problem ?: done, + if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT, ).show() refreshDrivers() } }, "import-driver").start() } + /** + * Pick one driver from a list, which is Manual (Auto would put its pair back). A bundle's half + * sets the bundle's other half in the other list as well. + */ + fun selectDriver(id: String, linux: Boolean) { + val bundle = DriverBundle.containing(activity, id, linux) + when { + bundle != null -> useBundle(bundle) + linux -> SessionPrefs.setLinuxDriver(activity, id) + else -> SessionPrefs.setAndroidDriver(activity, id) + } + setMode(false) + refreshDrivers() + } + + /** Set both halves of [bundle] as the drivers in use; returns what to tell the user. */ + private fun useBundle(bundle: DriverBundle.Bundle): String { + val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId + DriverBundle.select(activity, bundle) + if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false) + return "Using ${bundle.label} as both the runtime and display driver." + + if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else "" + } + /** * 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. */ fun deleteDriver(id: String, linux: Boolean) { + val bundle = DriverBundle.containing(activity, id, linux) + if (bundle != null) { + DriverBundle.remove(activity, bundle) + TurnipReleases.forget(activity, bundle.id) + android.widget.Toast.makeText(activity, "Deleted ${bundle.label} (both drivers)", android.widget.Toast.LENGTH_SHORT).show() + refreshDrivers() + return + } if (linux) { LinuxVulkanDriverManager(activity).removeDriver(id) if (SessionPrefs.linuxDriver(activity) == id) SessionPrefs.setLinuxDriver(activity, "") @@ -291,11 +374,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl /** The download entries and the refresh line, from what the last check found. */ fun refreshReleaseRows() { val check = TurnipReleases.cached(activity) - val lm = LinuxVulkanDriverManager(activity) - val td = TurnipDriver(activity) fun rows(linux: Boolean) = check?.assets.orEmpty() - .filter { it.linux == linux } - .filter { a -> TurnipReleases.installedId(activity, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null } + .filter { it.bundle || it.linux == linux } + .filter { a -> installedIdOf(a) == null } .map { a -> val mb = "%.1f MB".format(a.size / 1_048_576.0) com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name]) @@ -324,7 +405,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl fun checkLatestTurnip() { if (releaseChecking) return releaseChecking = true - releaseStatus = "Checking Banners-Turnip and WinNative…" + releaseStatus = "Checking Banners-Turnip, WinNative and DroidDeck…" Thread({ val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) { Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed" @@ -345,28 +426,20 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl releaseProgress[assetName] = 0 refreshReleaseRows() Thread({ - var file: java.io.File? = null val problem = try { - file = TurnipReleases.download(activity, asset) { pct -> - ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() } - } - val uri = Uri.fromFile(file) - val id = if (asset.linux) LinuxVulkanDriverManager(activity).installDriver(uri, asset.name) - else TurnipDriver(activity).installFromZip(uri, asset.name) - TurnipReleases.recordDownload(activity, asset, id) + installAsset(asset) { pct -> ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() } } null } catch (e: IllegalArgumentException) { e.message } catch (e: Exception) { Log.w(TAG, "release driver download", e) "Download failed: ${e.message}" - } finally { - file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) } } ui.post { releaseProgress.remove(assetName) + val pick = if (asset.bundle) "pick it in either list to set both drivers" else "pick it in the menu" android.widget.Toast.makeText( - activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu", + activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - $pick", android.widget.Toast.LENGTH_LONG, ).show() refreshDrivers() diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 1413323f0..4ef672e72 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -157,6 +157,9 @@ class MainActivity : ComponentActivity() { private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = false) } } + private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> + if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) } + } private val pickSaveZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then) @@ -826,13 +829,14 @@ class MainActivity : ComponentActivity() { onPair = { key -> drivers.selectPair(key) }, onRefresh = { if (drivers.mode == SessionPrefs.GPU_DRIVERS_AUTO) drivers.ensureAuto(force = true) else drivers.checkLatestTurnip() }, // Picking one driver on its own is Manual: Auto would put its pair back. - onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, id); drivers.setMode(false); drivers.refreshDrivers() }, - onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); drivers.setMode(false); drivers.refreshDrivers() }, + onSelectLinux = { id -> drivers.selectDriver(id, linux = true) }, + onSelectAndroid = { id -> drivers.selectDriver(id, linux = false) }, onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) }, onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) }, onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) }, - onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) }, - onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) }, + onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip or Android + Linux bundle)")) }, + onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip or Android + Linux bundle)")) }, + onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a driver zip or an Android + Linux bundle")) }, onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() }, ), ) diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index 06449dab5..96e495b53 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -116,7 +116,8 @@ object DeviceReport { val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect() k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "") k("Driver mode", SessionPrefs.gpuDriverMode(context) + - (com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu)?.let { " (recommended pair: $it)" } ?: "")) + (com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from( + com.droiddeck.launcher.gpu.TurnipReleases.cached(context)))?.let { " (recommended pair: $it)" } ?: "")) val turnip = TurnipDriver(context) val androidChoice = SessionPrefs.androidDriver(context) k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/DriverBundle.kt b/app/src/main/java/com/droiddeck/launcher/gpu/DriverBundle.kt new file mode 100644 index 000000000..169682101 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/gpu/DriverBundle.kt @@ -0,0 +1,196 @@ +package com.droiddeck.launcher.gpu + +import android.content.Context +import android.net.Uri +import android.util.Log +import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.session.SessionPrefs +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.util.zip.ZipInputStream + +/** + * An all-in-one driver package: one zip carrying both halves of a matched pair, the display + * (Android, bionic) driver in one directory and the runtime (Linux, glibc) driver in another, + * indexed by a root `manifest.json` - DroidDeck's own DD-Turnip releases (Droid-Deck/Drivers): + * + * ``` + * manifest.json {"package", "version", "drivers": {"android": {"path"}, "linux": {"path"}}} + * android/ meta.json (AdrenoTools) + libvulkan_freedreno.so + * linux/ meta.json + libvulkan_freedreno.so + * ``` + * + * Installing one puts each half through its own importer, with that importer's checks, and + * remembers the two as one bundle: picking either half sets both, and deleting either deletes both, + * so a bundle is always used whole. Zips of the older kind, one driver each, never reach this. + */ +object DriverBundle { + private const val TAG = "DriverBundle" + private const val PREFS = "driver_bundles" + private const val MANIFEST = "manifest.json" + /** Refuses a zip that unpacks to more than this: both halves together are about 30 MB. */ + private const val MAX_BYTES = 512L shl 20 + + class Manifest(val name: String, val version: String, val tag: String, val androidPath: String, val linuxPath: String) + + /** An installed bundle: [androidId] in TurnipDriver's list, [linuxId] in LinuxVulkanDriverManager's. */ + class Bundle(val id: String, val name: String, val version: String, val androidId: String, val linuxId: String) { + /** "DD-Turnip 0.1.0". */ + val label: String get() = if (version.isEmpty()) name else "$name $version" + } + + /** The manifest of a bundle, or null when [json] is not one (both halves, in two directories). */ + fun parseManifest(json: JSONObject): Manifest? { + val drivers = json.optJSONObject("drivers") ?: return null + val android = cleanPath(drivers.optJSONObject("android")?.optString("path").orEmpty()) ?: return null + val linux = cleanPath(drivers.optJSONObject("linux")?.optString("path").orEmpty()) ?: return null + if (android == linux) return null + return Manifest( + json.optString("package").ifEmpty { "Driver bundle" }, json.optString("version"), + json.optString("tag"), android, linux, + ) + } + + private fun cleanPath(path: String): String? { + val p = path.trim().trim('/') + return p.takeIf { it.isNotEmpty() && it.split('/').none { part -> part.isEmpty() || part == "." || part == ".." } } + } + + /** True when the zip at [uri] is a bundle rather than a single driver. */ + fun isBundle(context: Context, uri: Uri): Boolean = try { + context.contentResolver.openInputStream(uri)?.use { input -> + ZipInputStream(input).use { zip -> + generateSequence { zip.nextEntry }.firstOrNull { !it.isDirectory && it.name == MANIFEST } + ?.let { parseManifest(JSONObject(zip.readBytes().toString(Charsets.UTF_8))) } != null + } + } ?: false + } catch (e: Exception) { + Log.w(TAG, "reading $uri as a bundle", e) + false + } + + /** + * Install both halves of the bundle at [uri]. Both or neither: a half that is refused removes + * the one already in. Throws [IllegalArgumentException] with a user-facing reason when the zip + * is not a usable bundle, [IOException] on read failures. + */ + fun install(context: Context, uri: Uri): Bundle { + val work = File(context.cacheDir, "bundle-${System.nanoTime()}") + val td = TurnipDriver(context) + val lm = LinuxVulkanDriverManager(context) + var androidId: String? = null + try { + unzip(context, uri, work) + val manifest = File(work, MANIFEST).takeIf { it.isFile } + ?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() } + ?: throw IllegalArgumentException("Not a driver bundle: no manifest.json naming an android and a linux driver") + val androidDir = File(work, manifest.androidPath) + val linuxDir = File(work, manifest.linuxPath) + + val androidStage = td.newStagingDir() + androidId = try { + androidDir.listFiles()?.filter { it.isFile }?.forEach { it.copyTo(File(androidStage, it.name)) } + td.adopt(androidStage, manifest.name) + } catch (e: Exception) { + FileUtils.delete(androidStage) + throw e + } + + val linuxStage = lm.newStagingDir() + val linuxId = try { + val library = linuxDir.listFiles()?.firstOrNull { it.isFile && it.name.startsWith("libvulkan_freedreno") && it.name.endsWith(".so") } + library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.LIB_NAME)) + val meta = File(linuxDir, LinuxVulkanDriverManager.META_NAME).takeIf { it.isFile } + ?.let { runCatching { JSONObject(FileUtils.readString(it)) }.getOrNull() } + lm.adopt(linuxStage, library?.name, meta, manifest.name) + } catch (e: Exception) { + FileUtils.delete(linuxStage) + throw e + } + + val base = LinuxVulkanDriverManager.sanitizeId(manifest.tag.ifEmpty { "${manifest.name}-${manifest.version}" }) + val saved = registry(context) + var id = base + var n = 2 + while (saved.contains(id)) id = "$base-${n++}" + val bundle = Bundle(id, manifest.name, manifest.version, androidId, linuxId) + saved.edit().putString(id, JSONObject().put("name", bundle.name).put("version", bundle.version) + .put("android", androidId).put("linux", linuxId).toString()).apply() + Log.i(TAG, "installed bundle $id: display $androidId, runtime $linuxId") + return bundle + } catch (e: Exception) { + androidId?.let { td.remove(it) } + throw e + } finally { + FileUtils.delete(work) + } + } + + private fun unzip(context: Context, uri: Uri, dest: File) { + val root = dest.canonicalFile + var total = 0L + context.contentResolver.openInputStream(uri)?.use { input -> + ZipInputStream(input).use { zip -> + for (entry in generateSequence { zip.nextEntry }) { + if (entry.isDirectory) continue + val out = File(root, entry.name).canonicalFile + if (!out.path.startsWith(root.path + File.separator)) throw IllegalArgumentException("Not a driver bundle: ${entry.name} points outside it") + out.parentFile?.mkdirs() + out.outputStream().use { sink -> + val buf = ByteArray(1 shl 16) + while (true) { + val r = zip.read(buf) + if (r <= 0) break + total += r + if (total > MAX_BYTES) throw IllegalArgumentException("Not a driver bundle: it unpacks to more than ${MAX_BYTES shr 20} MB") + sink.write(buf, 0, r) + } + } + } + } + } ?: throw IOException("cannot open $uri") + } + + /** Every installed bundle whose two halves are both still there. */ + fun all(context: Context): List { + val td = TurnipDriver(context) + val lm = LinuxVulkanDriverManager(context) + return registry(context).all.mapNotNull { (id, raw) -> + runCatching { + val j = JSONObject(raw as String) + Bundle(id, j.getString("name"), j.optString("version"), j.getString("android"), j.getString("linux")) + }.getOrNull() + }.filter { td.isInstalled(it.androidId) && lm.isInstalled(it.linuxId) }.sortedBy { it.id } + } + + fun get(context: Context, id: String): Bundle? = all(context).firstOrNull { it.id == id } + + /** The bundle [driverId] is a half of, in the runtime list when [linux], else the display list. */ + fun containing(context: Context, driverId: String, linux: Boolean): Bundle? = + all(context).firstOrNull { (if (linux) it.linuxId else it.androidId) == driverId } + + /** The bundle both drivers are set to right now, if they are one. */ + fun active(context: Context): Bundle? { + val android = SessionPrefs.androidDriver(context) + val linux = SessionPrefs.linuxDriver(context) + return all(context).firstOrNull { it.androidId == android && it.linuxId == linux } + } + + /** Set both halves as the drivers in use. */ + fun select(context: Context, bundle: Bundle) { + SessionPrefs.setAndroidDriver(context, bundle.androidId) + SessionPrefs.setLinuxDriver(context, bundle.linuxId) + } + + /** Delete both halves; a driver still set to either goes back to its default. */ + fun remove(context: Context, bundle: Bundle) { + TurnipDriver(context).remove(bundle.androidId) + LinuxVulkanDriverManager(context).removeDriver(bundle.linuxId) + if (SessionPrefs.linuxDriver(context) == bundle.linuxId) SessionPrefs.setLinuxDriver(context, "") + registry(context).edit().remove(bundle.id).apply() + Log.i(TAG, "removed bundle ${bundle.id}") + } + + private fun registry(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) +} diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt b/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt index bf2bf7ba2..f3b28fe38 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt @@ -13,6 +13,8 @@ import com.droiddeck.launcher.gpu.GpuInfo.Family * newest release that carries both halves. * - WinNative ships its display (`v1.x`) and Linux (`linux-v0.x`) builds as two release lines with * their own numbers: the pair is the newest of each, of one flavour (Balanced or Performance). + * - DroidDeck's DD-Turnip ships both halves in one zip per release (DriverBundle): the pair is the + * newest bundle, and it can never be mixed. */ object DriverPairs { const val BANNER = "banner" @@ -21,6 +23,9 @@ object DriverPairs { const val BANNER_ONEUI = "banner-8g2-oneui" const val WN_BALANCED = "wn-b" const val WN_PERFORMANCE = "wn-p" + const val DD_TURNIP = "dd-turnip" + /** Each DD-Turnip release is its own pair: "dd-turnip:DD-Turnip-v0.1.0". */ + fun ddTurnip(tag: String) = "$DD_TURNIP:$tag" class DriverPair( val key: String, @@ -30,18 +35,27 @@ object DriverPairs { val families: Set, val display: TurnipReleases.Asset?, val linux: TurnipReleases.Asset?, + /** Both halves in one zip, instead of [display] and [linux]. */ + val bundle: TurnipReleases.Asset? = null, ) { - val complete: Boolean get() = display != null && linux != null + val complete: Boolean get() = bundle != null || (display != null && linux != null) + /** The zips to download for the pair: the bundle, or the two halves. */ + val assets: List get() = listOfNotNull(bundle ?: display, if (bundle == null) linux else null) /** "r4 · 1.19 + 0.1.2": the build of each half. */ val version: String - get() = listOfNotNull(display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-") } + get() = listOfNotNull(bundle?.tag, display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-").removePrefix("DD-Turnip-") } fun suits(gpu: GpuInfo) = gpu.family in families || (gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families)) } private val ALL_ADRENO = setOf(Family.A6XX, Family.A7XX, Family.A7XX_LOW, Family.A8XX, Family.ADRENO_UNKNOWN) - private fun describe(key: String): Pair> = when (key) { + private fun describe(key: String): Pair> = when { + key.startsWith(DD_TURNIP) -> "DroidDeck · DD-Turnip" to ALL_ADRENO + else -> describeFixed(key) + } + + private fun describeFixed(key: String): Pair> = when (key) { BANNER -> "Banners-Turnip · Adreno 6xx/7xx" to setOf(Family.A6XX, Family.A7XX) BANNER_A8XX -> "Banners-Turnip · Adreno 8xx" to setOf(Family.A8XX) BANNER_710 -> "Banners-Turnip · Adreno 710/720/722 (test)" to setOf(Family.A7XX_LOW) @@ -54,12 +68,13 @@ object DriverPairs { /** Every pair the last release check found, in the order the list shows them. */ fun from(check: TurnipReleases.Check?): List { val assets = check?.assets.orEmpty().filter { it.pair.isNotEmpty() } - val order = listOf(BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE) + val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE) return assets.map { it.pair }.distinct() - .sortedBy { order.indexOf(it).let { i -> if (i < 0) order.size else i } } + .sortedBy { key -> order.indexOf(key.substringBefore(':')).let { i -> if (i < 0) order.size else i } } .map { key -> val (name, families) = describe(key) val halves = assets.filter { it.pair == key } + halves.firstOrNull { it.bundle }?.let { return@map DriverPair(key, name, families, null, null, it) } // The list keeps the newest release of each half; for Banners-Turnip the two halves // must come from the same release, so a set missing one half in its newest release // is offered incomplete rather than mixed with an older one. @@ -71,17 +86,27 @@ object DriverPairs { } /** - * The pair Auto sets for [gpu]: WinNative Balanced on the 8xx (Banners' A8xx builds still break - * on some first boots), the OneUI build for an 8 Gen 2 under One UI, the patched test builds for + * The pair Auto sets for [gpu], among the [pairs] the last release check found: the newest + * official DD-Turnip release on the Adreno 840 (840 and 840v2), WinNative Balanced on the other + * 8xx (Banners' A8xx builds still break on some first boots) and on an 840 while no DD-Turnip + * release is listed, the OneUI build for an 8 Gen 2 under One UI, the patched test builds for * the 710/720/722, and upstream Banners-Turnip for the rest. Null when nothing fits (not Adreno). */ - fun recommendedKey(gpu: GpuInfo): String? = when (gpu.family) { + fun recommendedKey(gpu: GpuInfo, pairs: List): String? = when (gpu.family) { Family.NOT_ADRENO -> null - Family.A8XX -> WN_BALANCED + Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED Family.A7XX_LOW -> BANNER_710 Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER Family.A6XX -> BANNER // KGSL gave no model: Android 16 arrived with the 8xx, so a device that new is taken as one. Family.ADRENO_UNKNOWN -> if (android.os.Build.VERSION.SDK_INT >= 36) WN_BALANCED else BANNER } + + /** The complete DD-Turnip pair with the highest version, or null when none is listed. */ + fun newestDdTurnip(pairs: List): String? = pairs + .filter { it.key.startsWith("$DD_TURNIP:") && it.complete } + .maxByOrNull { p -> + Regex("""(\d+)\.(\d+)\.(\d+)$""").find(p.key)?.destructured + ?.let { (major, minor, patch) -> major.toLong() * 1_000_000_000_000 + minor.toLong() * 1_000_000 + patch.toLong() } ?: -1L + }?.key } diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java index 077e230cd..c0cb48f08 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java @@ -126,9 +126,7 @@ public class LinuxVulkanDriverManager { * Linux driver; {@link IOException} on read/extract failures. */ public String installDriver(Uri zipUri, String displayName) throws IOException { - File tmpDir = new File(rootDir, ".tmp-" + System.currentTimeMillis()); - FileUtils.delete(tmpDir); - if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir); + File tmpDir = newStagingDir(); boolean keep = false; try { String soName = null; @@ -156,9 +154,32 @@ public class LinuxVulkanDriverManager { } } // The zip's own freedreno_icd.aarch64.json is dropped on purpose: its - // library_path is relative to itself, and we write an absolute one below. + // library_path is relative to itself, and adopt() writes an absolute one. } } + String id = adopt(tmpDir, soName, zipMeta, displayName); + keep = true; + return id; + } finally { + if (!keep) FileUtils.delete(tmpDir); + } + } + + /** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */ + File newStagingDir() throws IOException { + File tmpDir = new File(rootDir, ".tmp-" + System.nanoTime()); + FileUtils.delete(tmpDir); + if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir); + return tmpDir; + } + + /** + * Check a staged driver ({@link #LIB_NAME} in {@code tmpDir}, copied from {@code soName} in + * the zip), write its manifest and meta.json, and move it in. Returns the id; the caller + * deletes {@code tmpDir} when this throws. + */ + String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException { + try { if (soName == null) { throw new IllegalArgumentException("No libvulkan_freedreno*.so in this zip. An Android " + "(AdrenoTools) or -Wayland Turnip zip is not a Linux runtime driver."); @@ -212,13 +233,10 @@ public class LinuxVulkanDriverManager { if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json"); if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir); - keep = true; Log.i(TAG, "imported Linux Vulkan driver " + id + " (" + soName + ", minGlibc=" + minGlibc + ") -> " + dir); return id; } catch (org.json.JSONException e) { throw new IOException("manifest write failed: " + e.getMessage()); - } finally { - if (!keep) FileUtils.delete(tmpDir); } } diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java index 8d8863961..52d8129ff 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java @@ -179,10 +179,7 @@ public final class TurnipDriver { * {@link IOException} on read/extract failures. */ public String installFromZip(Uri zipUri, String displayName) throws IOException { - if (!contentDir.exists()) contentDir.mkdirs(); - File tmpDir = new File(contentDir, ".tmp-" + System.currentTimeMillis()); - FileUtils.delete(tmpDir); - if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir); + File tmpDir = newStagingDir(); boolean keep = false; try { try (InputStream is = context.getContentResolver().openInputStream(zipUri); @@ -198,26 +195,44 @@ public final class TurnipDriver { Files.copy(zis, new File(tmpDir, base).toPath(), StandardCopyOption.REPLACE_EXISTING); } } - String rejected = rejectionReason(tmpDir); - if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected); - - JSONObject meta = readMetaFile(new File(tmpDir, "meta.json")); - String name = meta != null ? meta.optString("name", "") : ""; - if (name.isEmpty()) { - name = displayName != null ? displayName : "adrenotools-driver"; - if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4); - } - String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name)); - File dir = new File(contentDir, id); - if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir); + String id = adopt(tmpDir, displayName); keep = true; - Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir); return id; } finally { if (!keep) FileUtils.delete(tmpDir); } } + /** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */ + File newStagingDir() throws IOException { + if (!contentDir.exists()) contentDir.mkdirs(); + File tmpDir = new File(contentDir, ".tmp-" + System.nanoTime()); + FileUtils.delete(tmpDir); + if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir); + return tmpDir; + } + + /** + * Check a staged driver (meta.json and its library, flat) and move it in as a new driver. + * Returns the id; the caller deletes {@code tmpDir} when this throws. + */ + String adopt(File tmpDir, String displayName) throws IOException { + String rejected = rejectionReason(tmpDir); + if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected); + + JSONObject meta = readMetaFile(new File(tmpDir, "meta.json")); + String name = meta != null ? meta.optString("name", "") : ""; + if (name.isEmpty()) { + name = displayName != null ? displayName : "adrenotools-driver"; + if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4); + } + String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name)); + File dir = new File(contentDir, id); + if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir); + Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir); + return id; + } + private static JSONObject readMetaFile(File metaFile) { try { return new JSONObject(FileUtils.readString(metaFile)); diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipReleases.kt b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipReleases.kt index 2344f4190..9a6235f1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipReleases.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipReleases.kt @@ -33,13 +33,14 @@ object TurnipReleases { * [pair] names the matched set an asset belongs to (DriverPairs): a display build and a Linux * build of the same pair are made to run together. "" for a list cached before pairs were kept. */ + /** [bundle]: one zip holding both halves of the pair (DriverBundle); [linux] is false for it. */ class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String, - val sha256: String = "", val pair: String = "") + val sha256: String = "", val pair: String = "", val bundle: Boolean = false) /** [latest] = each source's newest release tag, for the refresh line. */ class Check(val assets: List, val latest: List>, val failed: List, val checkedAt: Long) /** What an asset is: a Linux build or not, the menu label, and the pair it belongs to. */ - private class Kind(val linux: Boolean, val label: String, val pair: String) + private class Kind(val linux: Boolean, val label: String, val pair: String, val bundle: Boolean = false) private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Kind?) @@ -69,6 +70,12 @@ object TurnipReleases { val gpus = if (m.groupValues[3] == "Axxx") "all Adreno" else m.groupValues[3] Kind(m.groupValues[1].isNotEmpty(), "$gpus · $flavour", "wn-" + m.groupValues[2]) }, + // DD-Turnip-v.zip: DroidDeck's own all-in-one build, both halves in one zip, published + // to Drivers-CI (releases only). Every release is offered, not just the newest, each its own pair. + Source("DroidDeck", "Droid-Deck/Drivers-CI") { name, tag -> + if (!Regex("""^DD-Turnip-v\d+\.\d+\.\d+\.zip$""").matches(name)) return@Source null + Kind(false, "Android + Linux · all Adreno", DriverPairs.ddTurnip(tag), bundle = true) + }, ) /** The result of the last check, or null when the user has never checked. */ @@ -101,15 +108,18 @@ object TurnipReleases { val a = list.getJSONObject(j) val name = a.getString("name") val kind = src.classify(name, tag) ?: continue + // A bundle is only offered from an official release, never a pre-release. + if (kind.bundle && r.optBoolean("prerelease")) continue val linux = kind.linux val label = kind.label // Only assets GitHub has a sha256 for are offered: the download is checked against it. val sha = Hashes.githubSha256(a.optString("digest")) ?: continue // Newest first: the first release carrying a variant is the one offered. - if (!seen.add("$linux|$label")) continue + if (!seen.add(if (kind.bundle) kind.pair else "$linux|$label")) continue assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name) .put("url", a.getString("browser_download_url")).put("size", a.optLong("size")) - .put("linux", linux).put("label", label).put("sha256", sha).put("pair", kind.pair)) + .put("linux", linux).put("label", label).put("sha256", sha).put("pair", kind.pair) + .put("bundle", kind.bundle)) } } if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest)) @@ -147,7 +157,8 @@ object TurnipReleases { for (i in 0 until list.length()) { val a = list.getJSONObject(i) out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"), - a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", ""), a.optString("pair", ""))) + a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", ""), a.optString("pair", ""), + a.optBoolean("bundle", false))) } val latest = ArrayList>() val l = json.optJSONArray("latest") ?: JSONArray() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index 1705cd398..0e5e40320 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -217,6 +217,9 @@ fun ComponentsPage( when { gpuTab -> Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { GpuDriversPanel(gpu, gpuActions) { driverPage = it } + Row(modifier = Modifier.padding(top = 14.dp)) { + SmallButton("Import .zip", onClick = gpuActions.onImportZip) + } } snapshot == null -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp)) { CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt index df76a1e81..d7c90ca5f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt @@ -141,6 +141,7 @@ fun DriverPage( text = { Text( if (row.tag == DriverRow.BUNDLED) "It is built into the app, so this removes its unpacked files and hides it. \"Restore built-in drivers\" brings it back, and Auto still uses it on a GPU that needs it." + else if (row.tag == DriverRow.BUNDLE) "It is one half of an Android + Linux bundle, so its runtime and display drivers are both removed. A driver in use goes back to the default." else "Its files are removed from the app." + if (row.id == selected) " It is the driver in use, so the default takes its place." else "", fontSize = 13.sp, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt index eea931034..bedab4c2b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt @@ -21,6 +21,9 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.AutoAwesome import androidx.compose.material.icons.outlined.Memory import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme @@ -79,6 +82,8 @@ class GpuDriversState( val linuxDownloads: List = emptyList(), val androidDownloads: List = emptyList(), val canRestoreBundled: Boolean = false, + /** The Android + Linux bundle both drivers are set to ("DD-Turnip 0.1.0"), or null. */ + val activeBundle: String? = null, ) { /** The pair both drivers are set to, if they make one. */ val activePair: PairRow? get() = pairs.firstOrNull { it.active } @@ -95,6 +100,8 @@ class GpuDriversActions( val onDownloadDriver: (String) -> Unit = {}, val onImportLinux: () -> Unit = {}, val onImportAndroid: () -> Unit = {}, + /** The tab's own import: a bundle, or a single driver of either kind. */ + val onImportZip: () -> Unit = {}, val onRestoreBundled: () -> Unit = {}, ) @@ -130,16 +137,48 @@ internal fun GpuDriversPanel(s: GpuDriversState, a: GpuDriversActions, onAdvance } } SettingsGroup("Advanced") { - SettingsRow("Runtime driver", "Games and the desktop draw with it. Pick it on its own, or import a -Linux Turnip zip.") { - SecondaryButton(s.linuxRows.firstOrNull { it.id == s.linuxSelected }?.name ?: "Runtime default", compact = true) { onAdvanced("rt") } + val together = s.activeBundle?.let { "Set together with the %s driver: $it carries both." } + SettingsRow("Runtime driver", together?.format("display") ?: "Games and the desktop draw with it.") { + DriverDropdown(s.linuxRows, s.linuxSelected, "Runtime default", a.onSelectLinux) { onAdvanced("rt") } } - SettingsRow("Display driver", "Puts frames on the screen. Changes apply after DroidDeck restarts.") { - SecondaryButton(s.androidRows.firstOrNull { it.id == s.androidSelected }?.name ?: "Auto - picked by GPU", compact = true) { onAdvanced("panel") } + SettingsRow("Display driver", together?.format("runtime") ?: "Puts frames on the screen. Changes apply after DroidDeck restarts.") { + DriverDropdown(s.androidRows, s.androidSelected, "Auto - picked by GPU", a.onSelectAndroid) { onAdvanced("panel") } } } } } +/** + * One driver list as a drop-down: the installed drivers to pick from, and the full page for + * downloading and deleting them. An Android + Linux bundle's row is tagged, and picking it sets both. + */ +@Composable +private fun DriverDropdown(rows: List, selected: String, fallback: String, onSelect: (String) -> Unit, onManage: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var open by remember { mutableStateOf(false) } + Box { + SecondaryButton((rows.firstOrNull { it.id == selected }?.name ?: fallback) + " ▾", compact = true) { open = true } + DropdownMenu(open, onDismissRequest = { open = false }, modifier = Modifier.heightIn(max = 360.dp)) { + for (row in rows) DropdownMenuItem( + leadingIcon = { Radio(row.id == selected) }, + text = { + Column { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(row.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (row.id == selected) pal.signal else colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (row.tag == DriverRow.BUNDLE) Text(row.tag, fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = colors.onSurfaceVariant) + } + if (row.detail.isNotEmpty()) Text(row.detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + }, + onClick = { open = false; if (row.id != selected) onSelect(row.id) }, + ) + HorizontalDivider(color = pal.line) + DropdownMenuItem(text = { Text("Download, import or delete…", fontSize = 14.sp, color = pal.signal) }, onClick = { open = false; onManage() }) + } + } +} + @Composable private fun DeviceCard(s: GpuDriversState) { val colors = MaterialTheme.colorScheme @@ -180,11 +219,11 @@ private fun AutoCard(s: GpuDriversState) { ) { Text("IN USE", fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = colors.onSurfaceVariant) Text( - active?.let { "${it.name} ${it.version}" } ?: "The drivers built into DroidDeck", + active?.let { "${it.name} ${it.version}" } ?: s.activeBundle ?: "The drivers built into DroidDeck", fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, ) Text( - if (active != null) "Runtime and display drivers set together as a matched pair." + if (active != null || s.activeBundle != null) "Runtime and display drivers set together as a matched pair." else recommended?.let { "Recommended for this GPU: ${it.name}." } ?: "Tap refresh to look for drivers for this GPU.", fontSize = 13.sp, color = colors.onSurfaceVariant, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 3fe24f0cb..6f228a0ca 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -33,6 +33,8 @@ class DriverRow(val id: String, val name: String, val detail: String, val remova const val BUNDLED = "BUNDLED" const val DOWNLOADED = "DOWNLOADED" const val IMPORTED = "IMPORTED" + /** One half of an Android + Linux bundle: picked and deleted together with the other. */ + const val BUNDLE = "ANDROID + LINUX" } } diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/DriverBundleTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/DriverBundleTest.kt new file mode 100644 index 000000000..434e87d09 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/gpu/DriverBundleTest.kt @@ -0,0 +1,133 @@ +package com.droiddeck.launcher.gpu + +import android.content.Context +import android.net.Uri +import com.droiddeck.launcher.session.SessionPrefs +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +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 java.io.File +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class DriverBundleTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + File(context.filesDir, "graphics_driver").deleteRecursively() + File(context.filesDir, LinuxVulkanDriverManager.DIR_NAME).deleteRecursively() + context.getSharedPreferences("driver_bundles", Context.MODE_PRIVATE).edit().clear().commit() + SessionPrefs.setAndroidDriver(context, "") + SessionPrefs.setLinuxDriver(context, "") + } + + /** Enough of an AArch64 ELF for the importers: the header they read, then the libc they look for. */ + private fun library(libc: String) = ByteArray(64).also { + byteArrayOf(0x7f, 'E'.code.toByte(), 'L'.code.toByte(), 'F'.code.toByte(), 2, 1).copyInto(it) + it[18] = 0xB7.toByte() + } + libc.toByteArray() + ByteArray(1) + + private val manifest = JSONObject() + .put("package", "DD-Turnip").put("version", "0.1.0").put("tag", "DD-Turnip-v0.1.0") + .put("drivers", JSONObject() + .put("android", JSONObject().put("path", "android")) + .put("linux", JSONObject().put("path", "linux"))) + + private fun zip(entries: Map): Uri { + val file = File.createTempFile("bundle", ".zip", context.cacheDir) + ZipOutputStream(file.outputStream()).use { z -> + for ((name, data) in entries) { z.putNextEntry(ZipEntry(name)); z.write(data); z.closeEntry() } + } + return Uri.fromFile(file) + } + + private fun bundle(linuxLibc: String = "libc.so.6", extra: Map = emptyMap()) = zip(mapOf( + "android/meta.json" to JSONObject().put("name", "DD-Turnip v0.1.0").put("libraryName", "libvulkan_freedreno.so").toString().toByteArray(), + "android/libvulkan_freedreno.so" to library("libc.so"), + "linux/meta.json" to JSONObject().put("name", "DD-Turnip v0.1.0").put("driverVersion", "DD-Turnip-v0.1.0").toString().toByteArray(), + "linux/libvulkan_freedreno.so" to library(linuxLibc), + "manifest.json" to manifest.toString().toByteArray(), + ) + extra) + + @Test fun manifestNeedsBothHalvesInSeparateSafeDirectories() { + val m = DriverBundle.parseManifest(manifest)!! + assertEquals("android", m.androidPath) + assertEquals("linux", m.linuxPath) + assertNull(DriverBundle.parseManifest(JSONObject().put("drivers", JSONObject().put("android", JSONObject().put("path", "a"))))) + val same = JSONObject(manifest.toString()).apply { getJSONObject("drivers").getJSONObject("linux").put("path", "android/") } + assertNull(DriverBundle.parseManifest(same)) + val escape = JSONObject(manifest.toString()).apply { getJSONObject("drivers").getJSONObject("linux").put("path", "../x") } + assertNull(DriverBundle.parseManifest(escape)) + } + + @Test fun singleDriverZipsAreNotBundles() { + val legacy = zip(mapOf("meta.json" to "{}".toByteArray(), "libvulkan_freedreno.so" to library("libc.so"))) + assertFalse(DriverBundle.isBundle(context, legacy)) + assertTrue(DriverBundle.isBundle(context, bundle())) + } + + @Test fun installsBothHalvesAndPicksAndDeletesThemTogether() { + val b = DriverBundle.install(context, bundle()) + assertEquals("DD-Turnip-v0.1.0", b.id) + assertEquals("DD-Turnip 0.1.0", b.label) + assertTrue(TurnipDriver(context).isInstalled(b.androidId)) + assertTrue(LinuxVulkanDriverManager(context).isInstalled(b.linuxId)) + assertEquals(b.id, DriverBundle.containing(context, b.linuxId, linux = true)?.id) + assertEquals(b.id, DriverBundle.containing(context, b.androidId, linux = false)?.id) + + assertNull(DriverBundle.active(context)) + DriverBundle.select(context, b) + assertEquals(b.androidId, SessionPrefs.androidDriver(context)) + assertEquals(b.linuxId, SessionPrefs.linuxDriver(context)) + assertNotNull(DriverBundle.active(context)) + + DriverBundle.remove(context, b) + assertFalse(TurnipDriver(context).isInstalled(b.androidId)) + assertFalse(LinuxVulkanDriverManager(context).isInstalled(b.linuxId)) + assertEquals("", SessionPrefs.androidDriver(context)) + assertEquals("", SessionPrefs.linuxDriver(context)) + assertTrue(DriverBundle.all(context).isEmpty()) + } + + @Test fun aRefusedHalfLeavesNothingInstalled() { + try { + DriverBundle.install(context, bundle(linuxLibc = "libc.so")) + fail("a bionic library in linux/ must be refused") + } catch (e: IllegalArgumentException) { + assertTrue(e.message!!.contains("glibc")) + } + assertTrue(TurnipDriver(context).enumerateImported().isEmpty()) + assertTrue(LinuxVulkanDriverManager(context).enumerateInstalledDrivers().isEmpty()) + } + + @Test fun entriesOutsideTheBundleAreRefused() { + try { + DriverBundle.install(context, bundle(extra = mapOf("../escape.so" to ByteArray(4)))) + fail("a zip-slip entry must be refused") + } catch (e: IllegalArgumentException) { + assertTrue(e.message!!.contains("outside")) + } + assertFalse(File(context.cacheDir.parentFile, "escape.so").exists()) + } + + @Test fun twoInstallsOfOneReleaseGetTheirOwnIds() { + val first = DriverBundle.install(context, bundle()) + val second = DriverBundle.install(context, bundle()) + assertEquals("DD-Turnip-v0.1.0-2", second.id) + assertEquals(2, DriverBundle.all(context).size) + assertFalse(first.androidId == second.androidId) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt index 16fbf4612..47431f253 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt @@ -36,13 +36,14 @@ class DriverPairsTest { @Test fun autoPicksWinNativeBalancedOn8xxAndBannersElsewhere() { - assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830))) - assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825))) - assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740))) - assertEquals(DriverPairs.BANNER_ONEUI, DriverPairs.recommendedKey(gpu(740, oneUi = true))) - assertEquals(DriverPairs.BANNER_710, DriverPairs.recommendedKey(gpu(720))) - assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650))) - assertNull(DriverPairs.recommendedKey(gpu(0, adreno = false))) + assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), emptyList())) + assertEquals("840 with no DD-Turnip release listed", DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(840), emptyList())) + assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), emptyList())) + assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), emptyList())) + assertEquals(DriverPairs.BANNER_ONEUI, DriverPairs.recommendedKey(gpu(740, oneUi = true), emptyList())) + assertEquals(DriverPairs.BANNER_710, DriverPairs.recommendedKey(gpu(720), emptyList())) + assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650), emptyList())) + assertNull(DriverPairs.recommendedKey(gpu(0, adreno = false), emptyList())) } @Test @@ -68,4 +69,41 @@ class DriverPairsTest { assertTrue(wn.suits(gpu(830))) assertFalse(pairs.getValue(DriverPairs.BANNER).suits(gpu(830))) } + + @Test + fun everyBundleReleaseIsACompletePairOnItsOwnNewestFirst() { + fun bundle(tag: String) = TurnipReleases.Asset("DroidDeck", tag, "$tag.zip", "https://example/$tag", 6_000_000, + false, "Android + Linux", "0".repeat(64), DriverPairs.ddTurnip(tag), bundle = true) + val newer = bundle("DD-Turnip-v0.2.0") + val older = bundle("DD-Turnip-v0.1.0") + val pairs = DriverPairs.from(TurnipReleases.Check( + listOf(asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER), newer, older, + asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER)), + emptyList(), emptyList(), 0L, + )) + assertEquals(listOf(DriverPairs.ddTurnip("DD-Turnip-v0.2.0"), DriverPairs.ddTurnip("DD-Turnip-v0.1.0"), DriverPairs.BANNER), pairs.map { it.key }) + val dd = pairs.first() + assertTrue(dd.complete) + assertEquals(listOf(newer), dd.assets) + assertEquals("v0.2.0", dd.version) + assertEquals("DroidDeck · DD-Turnip", dd.name) + assertTrue(dd.suits(gpu(840))) + assertTrue(dd.suits(gpu(740))) + } + + @Test + fun adreno840GetsTheNewestOfficialDdTurnip() { + fun bundle(tag: String) = TurnipReleases.Asset("DroidDeck", tag, "$tag.zip", "https://example/$tag", 6_000_000, + false, "Android + Linux", "0".repeat(64), DriverPairs.ddTurnip(tag), bundle = true) + val pairs = DriverPairs.from(TurnipReleases.Check( + listOf(bundle("DD-Turnip-v0.9.0"), bundle("DD-Turnip-v1.0.0"), bundle("DD-Turnip-v0.10.1"), + asset("WN-Turnip-1.19-b_Axxx.zip", "v1.19", false, DriverPairs.WN_BALANCED), + asset("WN-Linux-Turnip-0.1.2-b_Axxx.zip", "linux-v0.1.2", true, DriverPairs.WN_BALANCED)), + emptyList(), emptyList(), 0L, + )) + assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(840), pairs)) + assertEquals("other 8xx keep WinNative", DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), pairs)) + assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), pairs)) + assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), pairs)) + } }