Compare commits

..
146 changed files with 3618 additions and 13145 deletions

No files matched your search

+1 -1
View File
@@ -343,7 +343,7 @@ jobs:
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1 echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
fi fi
SESSION=$(syms "$D/libblsession.so") SESSION=$(syms "$D/libblsession.so")
for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap drmPrimeFDToHandle drmCloseBufferHandle drmIoctl; do for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap; do
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; } grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
done done
test -f "$D/usr/local/bin/droiddeck-session" test -f "$D/usr/local/bin/droiddeck-session"
+2 -4
View File
@@ -79,8 +79,8 @@ android {
// file out of its own data directory, and this app's entire job is to exec a rootfs: // 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/. // proot, gamescope, the Steam client and everything it launches all live under files/.
targetSdkVersion 28 targetSdkVersion 28
versionCode 11 versionCode 10
versionName "0.3.1" versionName "0.3.0"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\"" buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\"" buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}" buildConfigField "int", "PR_NUMBER", "${prNumber}"
@@ -165,8 +165,6 @@ android {
testOptions { testOptions {
// Plain JVM tests: a stray android.util.Log call returns a default instead of throwing. // Plain JVM tests: a stray android.util.Log call returns a default instead of throwing.
unitTests.returnDefaultValues = true unitTests.returnDefaultValues = true
// Robolectric tests start activities whose text is now all string resources.
unitTests.includeAndroidResources = true
} }
compileOptions { compileOptions {
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- Debug builds only. Android grants DUMP to adb shell; release APKs have no bridge. -->
<activity
android:name=".agent.AgentStartActivity"
android:exported="true"
android:excludeFromRecents="true"
android:noHistory="true"
android:permission="android.permission.DUMP"
android:theme="@style/SessionTheme" />
<provider
android:name=".agent.AgentBridgeProvider"
android:authorities="${applicationId}.agent"
android:exported="true"
android:permission="android.permission.DUMP"
android:grantUriPermissions="false" />
</application>
</manifest>
-14
View File
@@ -123,14 +123,6 @@
android:screenOrientation="sensorLandscape" android:screenOrientation="sensorLandscape"
android:theme="@style/AppTheme" /> android:theme="@style/AppTheme" />
<activity
android:name=".agent.AgentStartActivity"
android:exported="true"
android:excludeFromRecents="true"
android:noHistory="true"
android:permission="android.permission.DUMP"
android:theme="@style/SessionTheme" />
<activity <activity
android:name=".SessionActivity" android:name=".SessionActivity"
android:exported="false" android:exported="false"
@@ -181,11 +173,5 @@
<action android:name="android.content.action.DOCUMENTS_PROVIDER" /> <action android:name="android.content.action.DOCUMENTS_PROVIDER" />
</intent-filter> </intent-filter>
</provider> </provider>
<provider
android:name=".agent.AgentBridgeProvider"
android:authorities="${applicationId}.agent"
android:exported="true"
android:permission="android.permission.DUMP"
android:grantUriPermissions="false" />
</application> </application>
</manifest> </manifest>
@@ -11,14 +11,6 @@ import com.droiddeck.launcher.session.GpuClockPin
* sandboxes are started through (BwrapSpawner). * sandboxes are started through (BwrapSpawner).
*/ */
class App : Application() { class App : Application() {
override fun attachBaseContext(base: android.content.Context) =
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(base))
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
com.droiddeck.launcher.core.AppLanguage.systemChanged(newConfig)
}
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
CrashHandler.install(this) CrashHandler.install(this)
@@ -14,6 +14,7 @@ import com.droiddeck.launcher.session.ProtonDefault
*/ */
internal class ComponentsMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) { internal class ComponentsMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null) var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null)
var defaultProtonId by mutableStateOf<String?>(null)
var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList()) var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
var compCatalogAt by mutableStateOf(0L) var compCatalogAt by mutableStateOf(0L)
var compProton by mutableStateOf<String?>(null) var compProton by mutableStateOf<String?>(null)
@@ -21,7 +22,6 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
var compChecking by mutableStateOf(false) var compChecking by mutableStateOf(false)
var compBusy by mutableStateOf<String?>(null) var compBusy by mutableStateOf<String?>(null)
var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap()) var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
private var shownDefault: String? = null
/** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */ /** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */
fun refreshComponents(snapshotFirst: Boolean = false) { fun refreshComponents(snapshotFirst: Boolean = false) {
@@ -33,11 +33,9 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
val chosen = snap?.let { s -> runCatching { ProtonDefault.selectedId(activity, s.protons.map { it.proton }) }.getOrNull() } val chosen = snap?.let { s -> runCatching { ProtonDefault.selectedId(activity, s.protons.map { it.proton }) }.getOrNull() }
ui.post { ui.post {
compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList()) compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList())
defaultProtonId = chosen
if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt } if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
if (chosen != null && chosen != shownDefault) { if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) {
shownDefault = chosen
compProton = chosen
} else if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) {
compProton = chosen ?: snap?.protons?.firstOrNull()?.proton?.id compProton = chosen ?: snap?.protons?.firstOrNull()?.proton?.id
} }
} }
@@ -46,7 +44,6 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
fun chooseProton(id: String) { fun chooseProton(id: String) {
val proton = compSnapshot?.protons?.firstOrNull { it.proton.id == id }?.proton ?: return val proton = compSnapshot?.protons?.firstOrNull { it.proton.id == id }?.proton ?: return
compProton = id
Thread({ Thread({
val message = runCatching { val message = runCatching {
when (ProtonDefault.request(activity, proton)) { when (ProtonDefault.request(activity, proton)) {
@@ -55,7 +52,10 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
ProtonDefault.Outcome.NOT_RUNNABLE -> activity.getString(R.string.comp_default_not_runnable, proton.name) ProtonDefault.Outcome.NOT_RUNNABLE -> activity.getString(R.string.comp_default_not_runnable, proton.name)
} }
}.getOrElse { e -> activity.getString(R.string.comp_default_failed, e.message ?: e.javaClass.simpleName) } }.getOrElse { e -> activity.getString(R.string.comp_default_failed, e.message ?: e.javaClass.simpleName) }
ui.post { android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show() } ui.post {
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
refreshComponents()
}
}, "components-default").start() }, "components-default").start()
} }
@@ -63,7 +63,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
if (compBusy != null) return if (compBusy != null) return
compBusy = label compBusy = label
Thread({ Thread({
val message = runCatching(work).getOrElse { e -> activity.getString(R.string.main_action_failed, label, e.message ?: e.javaClass.simpleName) } val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
ui.post { ui.post {
compBusy = null compBusy = null
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
val cat = runCatching { ComponentsManager.catalog(activity, true) }.getOrNull() val cat = runCatching { ComponentsManager.catalog(activity, true) }.getOrNull()
ui.post { ui.post {
compChecking = false compChecking = false
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(activity, activity.getString(R.string.comp_nightlies_unreachable), android.widget.Toast.LENGTH_LONG).show() if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(activity, "The Nightlies could not be reached", android.widget.Toast.LENGTH_LONG).show()
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt } else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
} }
}, "components-catalog").start() }, "components-catalog").start()
@@ -91,8 +91,8 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
Thread({ Thread({
val message = runCatching { val message = runCatching {
val pkg = ComponentsManager.download(activity, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } } val pkg = ComponentsManager.download(activity, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
activity.getString(R.string.comp_stored, pkg.version) "Stored ${pkg.version}"
}.getOrElse { e -> activity.getString(R.string.comp_download_failed, e.message ?: e.javaClass.simpleName) } }.getOrElse { e -> "Download failed: ${e.message ?: e.javaClass.simpleName}" }
ui.post { ui.post {
compDownloads = compDownloads - item.file compDownloads = compDownloads - item.file
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT).show()
@@ -19,8 +19,6 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
var deckyChecking by mutableStateOf(false) var deckyChecking by mutableStateOf(false)
var deckyStage by mutableStateOf<String?>(null) var deckyStage by mutableStateOf<String?>(null)
var deckyPercent by mutableIntStateOf(-1) var deckyPercent by mutableIntStateOf(-1)
/** True while the stage is the plugin's binary download (DeckyManager.downloadingBinary). */
var deckyDownloadingBinary by mutableStateOf(false)
var deckySupervisor by mutableStateOf(false) var deckySupervisor by mutableStateOf(false)
var deckyReleaseRequest = 0 var deckyReleaseRequest = 0
@@ -43,11 +41,11 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
fun installDecky(release: DeckyManager.Release) { fun installDecky(release: DeckyManager.Release) {
if (deckyStage != null || SessionState.running) return if (deckyStage != null || SessionState.running) return
deckyStage = activity.getString(R.string.store_starting); deckyPercent = -1 deckyStage = "Starting…"; deckyPercent = -1
Thread({ Thread({
val problem = runCatching { val problem = runCatching {
DeckyManager.install(activity, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } } DeckyManager.install(activity, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
}.getOrElse { error -> activity.getString(R.string.decky_install_failed, error.message ?: error.javaClass.simpleName) } }.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
ui.post { ui.post {
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(activity) deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(activity)
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show() if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
@@ -57,17 +55,16 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
fun importPluginZip(archive: File) { fun importPluginZip(archive: File) {
if (deckyStage != null || SessionState.running || deckyInstalled == null) return if (deckyStage != null || SessionState.running || deckyInstalled == null) return
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1 deckyStage = "Starting plugin import…"; deckyPercent = -1
Thread({ Thread({
val problem = runCatching { val problem = runCatching {
DeckyManager.installPluginZip(activity, archive) { label, value -> DeckyManager.installPluginZip(activity, archive) { label, value ->
val binary = DeckyManager.downloadingBinary ui.post { deckyStage = label; deckyPercent = value }
ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary }
} }
}.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) } }.getOrElse { error -> "Plugin import failed: ${error.message ?: error.javaClass.simpleName}" }
ui.post { ui.post {
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false deckyStage = null; deckyPercent = -1
val message = problem ?: activity.getString(R.string.decky_plugin_installed) val message = problem ?: "Plugin installed. Restart Steam to load it."
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
} }
}, "import-decky-plugin").start() }, "import-decky-plugin").start()
@@ -37,8 +37,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */ /** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList()) var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList()) var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
// Empty until the first refresh: the activity has no context yet while its fields are made. var releaseStatus by mutableStateOf("Not checked yet - tap refresh to look for new drivers")
var releaseStatus by mutableStateOf("")
var releaseChecking by mutableStateOf(false) var releaseChecking by mutableStateOf(false)
var canRestoreBundled by mutableStateOf(false) var canRestoreBundled by mutableStateOf(false)
/** Asset name -> download percent, while it downloads. */ /** Asset name -> download percent, while it downloads. */
@@ -58,10 +57,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private var autoCheckedThisProcess = false private var autoCheckedThisProcess = false
fun state() = GpuDriversState( fun state() = GpuDriversState(
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity), gpuName = gpu.name, gpuFamily = gpu.family.label, soc = gpu.soc, supportText = gpu.supportText,
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED, supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent, auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
autoStatus = autoStatus, releaseStatus = releaseStatus.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking, autoStatus = autoStatus, releaseStatus = releaseStatus, checking = releaseChecking,
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected, linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled, linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
activeBundle = activeBundle, activeBundle = activeBundle,
@@ -74,10 +73,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
val bundles = DriverBundle.all(activity) val bundles = DriverBundle.all(activity)
fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let { fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let {
DriverRow(id, it.label, activity.getString(if (linux) R.string.drivers_bundle_sets_display else R.string.drivers_bundle_sets_runtime), true, DriverRow.BUNDLE) 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 -> linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false) if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
else bundleRow(id, linux = true) ?: DriverRow( else bundleRow(id, linux = true) ?: DriverRow(
id, lm.getDriverName(id), id, lm.getDriverName(id),
listOfNotNull( listOfNotNull(
@@ -93,8 +92,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val auto = td.autoId() val auto = td.autoId()
androidRows = buildList { androidRows = buildList {
add(DriverRow( add(DriverRow(
TurnipDriver.AUTO, activity.getString(R.string.gpu_auto_by_gpu), TurnipDriver.AUTO, "Auto - picked by GPU",
if (auto == "system") activity.getString(R.string.drivers_system_vulkan) else activity.getString(R.string.drivers_bundled, td.displayName(auto)), if (auto == "system") "system Vulkan: no bundled build for this GPU" else "${td.displayName(auto)} (bundled)",
false, false,
)) ))
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED)) for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
@@ -110,8 +109,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */ /** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
fun summary(): String { fun summary(): String {
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
val label = activity.getString(if (mode == SessionPrefs.GPU_DRIVERS_AUTO) R.string.common_auto else R.string.drivers_manual) return (if (mode == SessionPrefs.GPU_DRIVERS_AUTO) "Auto" else "Manual") + (active?.let { " · $it" } ?: "")
return active?.let { activity.getString(R.string.drivers_summary, label, it) } ?: label
} }
/** The pairs the last check found, with what is installed and in use; this GPU's first. */ /** The pairs the last check found, with what is installed and in use; this GPU's first. */
@@ -127,7 +125,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val mb = p.assets.sumOf { it.size } / 1_048_576.0 val mb = p.assets.sumOf { it.size } / 1_048_576.0
PairRow( PairRow(
key = p.key, name = p.name, version = p.version, key = p.key, name = p.name, version = p.version,
detail = if (!p.complete) activity.getString(R.string.drivers_half_published) else activity.getString(R.string.drivers_pair_size, mb), detail = if (!p.complete) "Only one half is published right now" else "%.0f MB for both".format(mb),
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete, recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
installed = displayId != null && linuxId != null, installed = displayId != null && linuxId != null,
active = displayId != null && linuxId != null && active = displayId != null && linuxId != null &&
@@ -155,11 +153,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
if (!force && autoCheckedThisProcess) return if (!force && autoCheckedThisProcess) return
autoCheckedThisProcess = true autoCheckedThisProcess = true
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) { if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity).lowercase()) autoStatus = "No drivers to set: ${gpu.supportText.lowercase()}"
return return
} }
releaseChecking = true releaseChecking = true
autoStatus = activity.getString(R.string.drivers_checking_latest) autoStatus = "Checking for the latest drivers…"
Thread({ Thread({
val cached = TurnipReleases.cached(activity) val cached = TurnipReleases.cached(activity)
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L || val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L ||
@@ -174,10 +172,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val pair = pairs.firstOrNull { it.key == key } val pair = pairs.firstOrNull { it.key == key }
val row = pairRows.firstOrNull { it.key == key } val row = pairRows.firstOrNull { it.key == key }
when { when {
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) } row?.active == true -> autoStatus = "Up to date" + (problem?.let { " (couldn't check: $it)" } ?: "")
?: activity.getString(R.string.upd_current_status)
pair == null || !pair.complete -> pair == null || !pair.complete ->
autoStatus = problem?.let { activity.getString(R.string.upd_couldnt_check, it) } ?: activity.getString(R.string.drivers_recommended_unpublished) autoStatus = problem?.let { "Couldn't check: $it" } ?: "The recommended drivers aren't published right now"
else -> installPair(pair, auto = true) else -> installPair(pair, auto = true)
} }
} }
@@ -200,7 +197,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
if (!pair.complete) return if (!pair.complete) return
pairBusy = pair.key pairBusy = pair.key
pairPercent = 0 pairPercent = 0
if (auto) autoStatus = activity.getString(R.string.drivers_downloading_pair, pair.name, pair.version) if (auto) autoStatus = "Downloading ${pair.name} ${pair.version}…"
Thread({ Thread({
val lm = LinuxVulkanDriverManager(activity) val lm = LinuxVulkanDriverManager(activity)
val td = TurnipDriver(activity) val td = TurnipDriver(activity)
@@ -220,7 +217,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val displayChanged = SessionPrefs.androidDriver(activity) != displayId val displayChanged = SessionPrefs.androidDriver(activity) != displayId
SessionPrefs.setAndroidDriver(activity, displayId) SessionPrefs.setAndroidDriver(activity, displayId)
SessionPrefs.setLinuxDriver(activity, linuxId) SessionPrefs.setLinuxDriver(activity, linuxId)
val restart = displayChanged && CompositorHost.isStarted val restart = if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
if (auto) { if (auto) {
val previous = SessionPrefs.gpuAutoInstalled(activity) val previous = SessionPrefs.gpuAutoInstalled(activity)
for (id in previous - setOf(displayId, linuxId)) { for (id in previous - setOf(displayId, linuxId)) {
@@ -233,18 +230,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
TurnipReleases.forget(activity, id) TurnipReleases.forget(activity, id)
} }
SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId)) SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId))
autoStatus = activity.getString( autoStatus = (if (downloaded) "Updated to" else "Switched to") + " ${pair.name} ${pair.version}.$restart"
if (downloaded) { if (restart) R.string.drivers_updated_to_restart else R.string.drivers_updated_to }
else { if (restart) R.string.drivers_switched_to_restart else R.string.drivers_switched_to },
pair.name, pair.version,
)
} else { } else {
android.widget.Toast.makeText(activity, activity.getString(if (restart) R.string.drivers_using_restart else R.string.drivers_using, pair.name, pair.version), android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(activity, "Using ${pair.name} ${pair.version}.$restart", android.widget.Toast.LENGTH_LONG).show()
} }
}.onFailure { e -> }.onFailure { e ->
Log.w(TAG, "driver pair ${pair.key}", e) Log.w(TAG, "driver pair ${pair.key}", e)
val why = if (e is IllegalArgumentException) e.message else activity.getString(R.string.comp_download_failed, e.message) val why = if (e is IllegalArgumentException) e.message else "Download failed: ${e.message}"
if (auto) autoStatus = why ?: activity.getString(R.string.user_apps_download_failed) if (auto) autoStatus = why ?: "Download failed"
else android.widget.Toast.makeText(activity, why, android.widget.Toast.LENGTH_LONG).show() else android.widget.Toast.makeText(activity, why, android.widget.Toast.LENGTH_LONG).show()
} }
refreshDrivers() refreshDrivers()
@@ -305,7 +298,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
try { try {
LinuxVulkanDriverManager(activity).installDriver(uri, name) LinuxVulkanDriverManager(activity).installDriver(uri, name)
} catch (runtime: IllegalArgumentException) { } catch (runtime: IllegalArgumentException) {
throw IllegalArgumentException(activity.getString(R.string.drivers_not_a_driver)) throw IllegalArgumentException("Not a driver zip: neither an AdrenoTools driver, a -Linux Turnip nor an Android + Linux bundle")
} }
} }
} }
@@ -314,11 +307,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
e.message e.message
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "driver import", e) Log.w(TAG, "driver import", e)
activity.getString(R.string.drivers_import_failed, e.message) "Import failed: ${e.message}"
} }
ui.post { ui.post {
val done = bundle?.let { useBundle(it) } val done = bundle?.let { useBundle(it) } ?: "Imported ${name ?: "driver"}"
?: name?.let { activity.getString(R.string.comp_imported, it) } ?: activity.getString(R.string.drivers_imported_unnamed)
android.widget.Toast.makeText( android.widget.Toast.makeText(
activity, problem ?: done, activity, problem ?: done,
if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT, if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
@@ -348,10 +340,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId
DriverBundle.select(activity, bundle) DriverBundle.select(activity, bundle)
if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false) if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false)
return activity.getString( return "Using ${bundle.label} as both the runtime and display driver." +
if (displayChanged && CompositorHost.isStarted) R.string.drivers_using_bundle_restart else R.string.drivers_using_bundle, if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
bundle.label,
)
} }
/** /**
@@ -364,7 +354,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
if (bundle != null) { if (bundle != null) {
DriverBundle.remove(activity, bundle) DriverBundle.remove(activity, bundle)
TurnipReleases.forget(activity, bundle.id) TurnipReleases.forget(activity, bundle.id)
android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_deleted_bundle, bundle.label), android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(activity, "Deleted ${bundle.label} (both drivers)", android.widget.Toast.LENGTH_SHORT).show()
refreshDrivers() refreshDrivers()
return return
} }
@@ -377,7 +367,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
if (SessionPrefs.androidDriver(activity) == id) SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO) if (SessionPrefs.androidDriver(activity) == id) SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
} }
TurnipReleases.forget(activity, id) TurnipReleases.forget(activity, id)
android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_deleted, id), android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(activity, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show()
refreshDrivers() refreshDrivers()
} }
@@ -388,28 +378,26 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
.filter { it.bundle || it.linux == linux } .filter { it.bundle || it.linux == linux }
.filter { a -> installedIdOf(a) == null } .filter { a -> installedIdOf(a) == null }
.map { a -> .map { a ->
val mb = activity.getString(R.string.common_size_mb, a.size / 1_048_576.0) 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]) com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
} }
linuxDownloads = rows(linux = true) linuxDownloads = rows(linux = true)
androidDownloads = rows(linux = false) androidDownloads = rows(linux = false)
if (!releaseChecking) releaseStatus = when (check) { if (!releaseChecking) releaseStatus = when (check) {
null -> activity.getString(R.string.drivers_not_checked) null -> "Not checked yet - tap refresh to look for new drivers"
else -> { else -> "Latest: " + check.latest.joinToString(" · ") { "${it.first} ${it.second}" } +
val latest = check.latest.joinToString(" · ") { "${it.first} ${it.second}" } (if (check.failed.isEmpty()) "" else " · ${check.failed.joinToString()} unreachable") +
if (check.failed.isEmpty()) activity.getString(R.string.drivers_release_status, latest, ago(check.checkedAt)) " · checked ${ago(check.checkedAt)}"
else activity.getString(R.string.drivers_release_status_failed, latest, check.failed.joinToString(), ago(check.checkedAt))
}
} }
} }
private fun ago(t: Long): String { private fun ago(t: Long): String {
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0) val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
return when { return when {
m < 1 -> activity.getString(R.string.upd_just_now) m < 1 -> "just now"
m < 60 -> activity.resources.getQuantityString(R.plurals.drivers_ago_minutes, m.toInt(), m) m < 60 -> "$m min ago"
m < 48 * 60 -> activity.resources.getQuantityString(R.plurals.drivers_ago_hours, (m / 60).toInt(), m / 60) m < 48 * 60 -> "${m / 60} h ago"
else -> activity.resources.getQuantityString(R.plurals.drivers_ago_days, (m / (24 * 60)).toInt(), m / (24 * 60)) else -> "${m / (24 * 60)} days ago"
} }
} }
@@ -417,16 +405,16 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
fun checkLatestTurnip() { fun checkLatestTurnip() {
if (releaseChecking) return if (releaseChecking) return
releaseChecking = true releaseChecking = true
releaseStatus = activity.getString(R.string.drivers_checking_sources) releaseStatus = "Checking Banners-Turnip, WinNative and DroidDeck…"
Thread({ Thread({
val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) { val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) {
Log.w(TAG, "latest Turnip check", e); e.message ?: activity.getString(R.string.drivers_check_failed) Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
} }
ui.post { ui.post {
releaseChecking = false releaseChecking = false
refreshReleaseRows() refreshReleaseRows()
refreshPairs() refreshPairs()
if (problem != null) releaseStatus = activity.getString(R.string.upd_couldnt_check, problem) if (problem != null) releaseStatus = "Couldn't check: $problem"
} }
}, "turnip-release-check").start() }, "turnip-release-check").start()
} }
@@ -445,16 +433,13 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
e.message e.message
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "release driver download", e) Log.w(TAG, "release driver download", e)
activity.getString(R.string.comp_download_failed, e.message) "Download failed: ${e.message}"
} }
ui.post { ui.post {
releaseProgress.remove(assetName) releaseProgress.remove(assetName)
val installed = activity.getString( val pick = if (asset.bundle) "pick it in either list to set both drivers" else "pick it in the menu"
if (asset.bundle) R.string.drivers_installed_pick_either else R.string.drivers_installed_pick,
asset.name.removeSuffix(".zip"),
)
android.widget.Toast.makeText( android.widget.Toast.makeText(
activity, problem ?: installed, activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - $pick",
android.widget.Toast.LENGTH_LONG, android.widget.Toast.LENGTH_LONG,
).show() ).show()
refreshDrivers() refreshDrivers()
@@ -7,11 +7,6 @@ import com.droiddeck.launcher.session.SessionService
/** Receives the system Home launch and routes it without consuming KEYCODE_HOME. */ /** Receives the system Home launch and routes it without consuming KEYCODE_HOME. */
class HomeActivity : Activity() { class HomeActivity : Activity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
routeHome() routeHome()
@@ -42,7 +42,6 @@ import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.GameSaves import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionLogShare import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.ui.ProtonPage import com.droiddeck.launcher.ui.ProtonPage
import com.droiddeck.launcher.core.CpuCores import com.droiddeck.launcher.core.CpuCores
import com.droiddeck.launcher.core.PhantomProcessLimit import com.droiddeck.launcher.core.PhantomProcessLimit
@@ -52,7 +51,6 @@ import com.droiddeck.launcher.core.WifiDiscovery
import com.droiddeck.launcher.core.WirelessAdbPairingService import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.ui.CoreRow import com.droiddeck.launcher.ui.CoreRow
import com.droiddeck.launcher.ui.PerformancePage import com.droiddeck.launcher.ui.PerformancePage
import com.droiddeck.launcher.ui.ModeSettingsPage
import com.droiddeck.launcher.ui.ModeSettings import com.droiddeck.launcher.ui.ModeSettings
import com.droiddeck.launcher.ui.ModeSettingsActions import com.droiddeck.launcher.ui.ModeSettingsActions
import com.droiddeck.launcher.ui.ConfirmDialog import com.droiddeck.launcher.ui.ConfirmDialog
@@ -61,6 +59,12 @@ import com.droiddeck.launcher.ui.ControllerMappingPage
import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.ControllerEditorActivity import com.droiddeck.launcher.input.ControllerEditorActivity
import com.droiddeck.launcher.ui.FrontEndScreen import com.droiddeck.launcher.ui.FrontEndScreen
import com.droiddeck.launcher.ui.SettingsCategory
import com.droiddeck.launcher.ui.SettingsDestination
import com.droiddeck.launcher.ui.SettingsHistory
import com.droiddeck.launcher.ui.SettingsCategoryPage
import com.droiddeck.launcher.ui.ModeSettingsContent
import com.droiddeck.launcher.ui.MenuHost
import com.droiddeck.launcher.ui.FrontEndState import com.droiddeck.launcher.ui.FrontEndState
import com.droiddeck.launcher.ui.FrontEndActions import com.droiddeck.launcher.ui.FrontEndActions
import com.droiddeck.launcher.frontend.CoverArt import com.droiddeck.launcher.frontend.CoverArt
@@ -81,11 +85,6 @@ import com.droiddeck.launcher.input.SecondScreenDisplays
* the store, downloads, settings - is the client's own job once [SessionActivity] has it on screen. * the store, downloads, settings - is the client's own job once [SessionActivity] has it on screen.
*/ */
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
private val ui = Handler(Looper.getMainLooper()) private val ui = Handler(Looper.getMainLooper())
private val drivers = DriverMenus(this, ui) private val drivers = DriverMenus(this, ui)
private val components = ComponentsMenu(this, ui) private val components = ComponentsMenu(this, ui)
@@ -109,21 +108,20 @@ class MainActivity : ComponentActivity() {
private var stage by mutableStateOf("") private var stage by mutableStateOf("")
private var percent by mutableIntStateOf(-1) private var percent by mutableIntStateOf(-1)
private var failed by mutableStateOf(false) private var failed by mutableStateOf(false)
private var frameGenLabel by mutableStateOf("") private var frameGenLabel by mutableStateOf("Off")
private var lossless by mutableStateOf(Lossless.State.NONE) private var lossless by mutableStateOf(Lossless.State.NONE)
private var showRemove by mutableStateOf(false) private var showRemove by mutableStateOf(false)
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null) private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
private var glThread by mutableStateOf(true) private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true) private var noGlError by mutableStateOf(true)
private var steamDeckMode by mutableStateOf(false) private var steamDeckMode by mutableStateOf(false)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true) private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK) private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var showProtons by mutableStateOf(false) private val showProtons get() = settingsHistory.current is SettingsDestination.Protons
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager). // Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
private var showComponents by mutableStateOf(false) private val showComponents get() = settingsHistory.current is SettingsDestination.Components
private var focusComponentsContent by mutableStateOf(true) private var focusComponentsContent by mutableStateOf(true)
private var showMapping by mutableStateOf(false) private val showMapping get() = settingsHistory.current is SettingsDestination.Mapping
private var saveBusy: String? = null private var saveBusy: String? = null
/** What to do with the zip or folder the file picker hands back after a game page's Manage saves. */ /** What to do with the zip or folder the file picker hands back after a game page's Manage saves. */
private var onSavePicked: ((File) -> Unit)? = null private var onSavePicked: ((File) -> Unit)? = null
@@ -137,7 +135,7 @@ class MainActivity : ComponentActivity() {
private var desktopInstalled by mutableStateOf(false) private var desktopInstalled by mutableStateOf(false)
private var offlineAccount by mutableStateOf<String?>(null) private var offlineAccount by mutableStateOf<String?>(null)
private var offline by mutableStateOf(false) private var offline by mutableStateOf(false)
private var showPerformance by mutableStateOf(false) private val showPerformance get() = settingsHistory.current is SettingsDestination.Performance
private var clientOverride by mutableStateOf(false) private var clientOverride by mutableStateOf(false)
private var clientCores by mutableStateOf<Set<Int>>(emptySet()) private var clientCores by mutableStateOf<Set<Int>>(emptySet())
private var gameCores by mutableStateOf<Set<Int>>(emptySet()) private var gameCores by mutableStateOf<Set<Int>>(emptySet())
@@ -157,7 +155,7 @@ class MainActivity : ComponentActivity() {
private var showPhantomGate by mutableStateOf(false) private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false) private var directAudio by mutableStateOf(false)
private var clientDirectAudio by mutableStateOf(false) private var clientDirectAudio by mutableStateOf(false)
private var forceFullscreen by mutableStateOf(false) private var forceFullscreen by mutableStateOf(true)
private var stretch16x9 by mutableStateOf(false) private var stretch16x9 by mutableStateOf(false)
private var launcherFullscreen by mutableStateOf(true) private var launcherFullscreen by mutableStateOf(true)
private var animationsEnabled by mutableStateOf(true) private var animationsEnabled by mutableStateOf(true)
@@ -256,32 +254,29 @@ class MainActivity : ComponentActivity() {
/** Import a save zip into [game]: pick it in the app's file picker, then back up and unzip off the main thread. */ /** Import a save zip into [game]: pick it in the app's file picker, then back up and unzip off the main thread. */
private fun importSaves(name: String, game: () -> GameSaves.Game) { private fun importSaves(name: String, game: () -> GameSaves.Game) {
if (SessionState.running) { if (SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_saves_close_session, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(this, "Close the Steam session first, so the game can't save over the import", android.widget.Toast.LENGTH_LONG).show()
return return
} }
onSavePicked = { zip -> onSavePicked = { zip ->
saveAction(getString(R.string.main_saves_importing, name)) { saveAction("Importing into $name") {
val (written, backup) = GameSaves.import(this, game(), zip) val (written, backup) = GameSaves.import(game(), zip)
val kind = GameSaves.layoutOf(zip)?.label(this) ?: getString(R.string.saves_zip) val kind = GameSaves.layoutOf(zip)?.label ?: "zip"
resources.getQuantityString( "Imported $written files from the $kind into $name" + (backup?.let { ". Old saves backed up to Download/DroidDeck/Saves/backups" } ?: "")
if (backup != null) R.plurals.main_saves_imported_backup else R.plurals.main_saves_imported,
written, written, kind, name,
)
} }
} }
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_saves_pick_zip, name), GameSaves.savesDir().parentFile?.parentFile?.path)) pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), "Choose a save zip for $name", GameSaves.savesDir().parentFile?.parentFile?.path))
} }
/** Export [game]'s saves in [layout] to a folder picked in the app's file picker. */ /** Export [game]'s saves in [layout] to a folder picked in the app's file picker. */
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) { private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
onSavePicked = { dir -> onSavePicked = { dir ->
saveAction(getString(R.string.main_saves_exporting, name)) { saveAction("Exporting $name") {
val (zip, count) = GameSaves.export(this, game(), layout, dir) val (zip, count) = GameSaves.export(game(), layout, dir)
resources.getQuantityString(R.plurals.main_saves_exported, count, count, layout.label(this), zip.path.removePrefix("/storage/emulated/0/")) "Exported $count files as a ${layout.label}: ${zip.path.removePrefix("/storage/emulated/0/")}"
} }
} }
GameSaves.savesDir().mkdirs() GameSaves.savesDir().mkdirs()
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_saves_pick_folder, name, layout.label(this)), GameSaves.savesDir().path)) pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, "Choose where to save $name (${layout.label})", GameSaves.savesDir().path))
} }
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
@@ -313,13 +308,16 @@ class MainActivity : ComponentActivity() {
} }
} }
// The mode whose settings dialog is open, with what it shows; refreshed by openModeSettings(). // The mode whose settings dialog is open, with what it shows; refreshed by openModeSettings().
private var settingsMode by mutableStateOf<String?>(null) private var settingsHistory by mutableStateOf(SettingsHistory())
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION) private val settingsMode get() = (settingsHistory.current as? SettingsDestination.Category)?.mode
private var requestedRailTab by mutableStateOf<String?>(null)
private var resolutionCap by mutableStateOf(1080)
private var customResolution by mutableStateOf<Pair<Int, Int>?>(null)
private var fexPreset by mutableStateOf("") private var fexPreset by mutableStateOf("")
private var steamChannel by mutableStateOf("steamdeck_publicbeta") private var steamChannel by mutableStateOf("steamdeck_publicbeta")
private var runSteamAtStartup by mutableStateOf(false) private var runSteamAtStartup by mutableStateOf(false)
private var theme by mutableStateOf("graphite") private var theme by mutableStateOf("graphite")
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
private var hdrOn by mutableStateOf(false) private var hdrOn by mutableStateOf(false)
private var fpsLimit by mutableStateOf(0) private var fpsLimit by mutableStateOf(0)
private var upscaler by mutableStateOf(0) private var upscaler by mutableStateOf(0)
@@ -332,7 +330,7 @@ class MainActivity : ComponentActivity() {
private var renderer by mutableStateOf("vulkan") private var renderer by mutableStateOf("vulkan")
private var gameStorage by mutableStateOf("") private var gameStorage by mutableStateOf("")
private var storageDiagnostics by mutableStateOf(false) private var storageDiagnostics by mutableStateOf(false)
private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList()) private var storageOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) } if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
} }
@@ -363,15 +361,15 @@ class MainActivity : ComponentActivity() {
if (intent?.component?.className == SessionActivity::class.java.name) { if (intent?.component?.className == SessionActivity::class.java.name) {
when { when {
busy || LinuxRuntimeInstaller.isBusy() -> { busy || LinuxRuntimeInstaller.isBusy() -> {
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(this, "Wait for the runtime operation to finish", android.widget.Toast.LENGTH_SHORT).show()
return return
} }
protons.protonBusyId != null || ProtonExtras.installInProgress -> { protons.protonBusyId != null || ProtonExtras.installInProgress -> {
android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(this, "Wait for the compatibility tool install to finish", android.widget.Toast.LENGTH_SHORT).show()
return return
} }
pkgStage != null -> { pkgStage != null -> {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(this, "Wait for the desktop app install to finish", android.widget.Toast.LENGTH_SHORT).show()
return return
} }
} }
@@ -407,7 +405,7 @@ class MainActivity : ComponentActivity() {
private fun pickGameExport(game: Library.SteamGame?) { private fun pickGameExport(game: Library.SteamGame?) {
onSavePicked = { folder -> onSavePicked = { folder ->
saveAction(getString(R.string.game_frontend_files)) { saveAction(getString(R.string.game_frontend_files)) {
if (game != null) com.droiddeck.launcher.frontend.GameFiles.export(this, folder, game) if (game != null) com.droiddeck.launcher.frontend.GameFiles.export(folder, game)
else com.droiddeck.launcher.frontend.GameFileSync.enable(this, folder) else com.droiddeck.launcher.frontend.GameFileSync.enable(this, folder)
ui.post { gameSyncFolder = com.droiddeck.launcher.frontend.GameFileSync.folder(this) } ui.post { gameSyncFolder = com.droiddeck.launcher.frontend.GameFileSync.folder(this) }
getString(R.string.game_file_exported, folder.path) getString(R.string.game_file_exported, folder.path)
@@ -442,7 +440,7 @@ class MainActivity : ComponentActivity() {
private fun launchGame(game: Library.SteamGame): Boolean { private fun launchGame(game: Library.SteamGame): Boolean {
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) { if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(this, "Wait for the install to finish before launching a game", android.widget.Toast.LENGTH_SHORT).show()
return false return false
} }
if (SessionState.running) { if (SessionState.running) {
@@ -489,8 +487,6 @@ class MainActivity : ComponentActivity() {
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus() refreshPhantomStatus()
theme = SessionPrefs.theme(this) theme = SessionPrefs.theme(this)
frameGenLabel = getString(R.string.frame_gen_off)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it. // Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this) steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
backActionsInverted = SessionPrefs.backActionsInverted(this) backActionsInverted = SessionPrefs.backActionsInverted(this)
@@ -500,11 +496,11 @@ class MainActivity : ComponentActivity() {
applyLauncherFullscreen() applyLauncherFullscreen()
updates.start() updates.start()
setContent { setContent {
DroidDeckTheme(theme, appScale = appScale) { DroidDeckTheme(theme) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
val sm = settingsMode val sm = settingsMode
val page: (@Composable () -> Unit)? = when { val page: (@Composable () -> Unit)? = when {
sm != null -> { { ModeSettingsHost(sm) } } sm != null -> null
showPerformance -> { { PerformanceHost() } } showPerformance -> { { PerformanceHost() } }
showProtons -> { { ProtonHost() } } showProtons -> { { ProtonHost() } }
showComponents -> { { ComponentsHost() } } showComponents -> { { ComponentsHost() } }
@@ -525,10 +521,14 @@ class MainActivity : ComponentActivity() {
steamGames = steamGames, emulators = emulatorList, running = runningLabel, steamGames = steamGames, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this), frameGen = FrameGen.mode(this),
lossless = lossless, lossless = lossless,
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null, pageKey = settingsHistory.current?.key,
settingsCategory = (settingsHistory.current as? SettingsDestination.Category)?.category,
settingsMode = sm ?: SessionService.MODE_STEAM,
settingsTarget = (settingsHistory.current as? SettingsDestination.Category)?.target
?: (settingsHistory.current as? SettingsDestination.Performance)?.target
?: (settingsHistory.current as? SettingsDestination.Components)?.target,
requestedRailTab = requestedRailTab,
theme = theme, theme = theme,
language = com.droiddeck.launcher.core.AppLanguage.chosen(this),
appScale = appScale,
isHomeApp = homeAppSelected, isHomeApp = homeAppSelected,
homeScreenEnabled = homeScreenEnabled, homeScreenEnabled = homeScreenEnabled,
defaultHomeLabel = defaultHomeLabel, defaultHomeLabel = defaultHomeLabel,
@@ -622,7 +622,7 @@ class MainActivity : ComponentActivity() {
// A game page's Manage saves: the game's Proton and saves are read when the work runs, off the main thread. // A game page's Manage saves: the game's Proton and saves are read when the work runs, off the main thread.
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } }, onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } }, onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true }, onPerformance = { refreshCores(); settingsHistory = settingsHistory.open(SettingsDestination.Performance()) },
onRoms = { showRoms = true }, onRoms = { showRoms = true },
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) }, onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
onBrowseFiles = { dir -> onBrowseFiles = { dir ->
@@ -637,7 +637,7 @@ class MainActivity : ComponentActivity() {
Thread({ Thread({
val zip = runCatching { SessionLogShare.zipLatest(this) }.getOrNull() val zip = runCatching { SessionLogShare.zipLatest(this) }.getOrNull()
ui.post { ui.post {
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show() if (zip == null) android.widget.Toast.makeText(this, "No session logs yet: run a session first.", android.widget.Toast.LENGTH_LONG).show()
else startActivity(SessionLogShare.shareIntent(this, zip)) else startActivity(SessionLogShare.shareIntent(this, zip))
} }
}, "share-logs").start() }, "share-logs").start()
@@ -647,7 +647,7 @@ class MainActivity : ComponentActivity() {
val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0) val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0)
ui.post { ui.post {
android.widget.Toast.makeText(this, android.widget.Toast.makeText(this,
if (cleared == 0) getString(R.string.main_no_logs_to_clear) else resources.getQuantityString(R.plurals.main_logs_cleared, cleared, cleared), if (cleared == 0) "No session logs to clear." else "Cleared $cleared session log folder${if (cleared == 1) "" else "s"}.",
android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.LENGTH_SHORT).show()
} }
}, "clear-logs").start() }, "clear-logs").start()
@@ -656,19 +656,19 @@ class MainActivity : ComponentActivity() {
OfflineMode.setEnabled(this, !OfflineMode.enabled(this)) OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
offline = OfflineMode.enabled(this) offline = OfflineMode.enabled(this)
}, },
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false }, onPageBack = { settingsBack() },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id }, onCloseSettings = { settingsHistory = SettingsHistory() },
onLanguage = { tag -> onSettingsCategory = { category, target -> openSettingsCategory(category, target) },
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) { onSettingsMode = { mode ->
com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag) val destination = settingsHistory.current as? SettingsDestination.Category
// Redrawn in the new language; Setup's page and tab are saved state. if (destination != null) {
recreate() refreshModeSettings(mode)
settingsHistory = settingsHistory.replace(destination.copy(mode = mode, target = null))
} }
}, },
onAppScale = { percent -> onOpenUpdates = { settingsHistory = SettingsHistory(); requestedRailTab = "updates" },
com.droiddeck.launcher.core.AppUiPrefs.setScale(this, percent) onRailTabHandled = { requestedRailTab = null },
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this) onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
},
onLauncherFullscreen = { on -> onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on) SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on launcherFullscreen = on
@@ -697,7 +697,7 @@ class MainActivity : ComponentActivity() {
val result = runCatching { val result = runCatching {
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) } kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
} }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_pair_failed) } val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging pairing failed" }
ui.post { complete(error) } ui.post { complete(error) }
}, "wireless-adb-pair").start() }, "wireless-adb-pair").start()
}, },
@@ -710,7 +710,7 @@ class MainActivity : ComponentActivity() {
onWirelessAdbApply = { host, port, enabled, complete -> onWirelessAdbApply = { host, port, enabled, complete ->
Thread({ Thread({
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) } val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_command_failed) } val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging command failed" }
ui.post { ui.post {
if (error == null) refreshPhantomStatus() if (error == null) refreshPhantomStatus()
complete(error) complete(error)
@@ -720,7 +720,7 @@ class MainActivity : ComponentActivity() {
onSetPhantomProcessLimit = { enabled, complete -> onSetPhantomProcessLimit = { enabled, complete ->
Thread({ Thread({
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) } val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_unavailable) } val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging is unavailable" }
ui.post { ui.post {
if (error == null) refreshPhantomStatus() if (error == null) refreshPhantomStatus()
complete(error) complete(error)
@@ -729,9 +729,9 @@ class MainActivity : ComponentActivity() {
}, },
onCopyPhantomCommand = { enabled -> onCopyPhantomCommand = { enabled ->
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip( (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
ClipData.newPlainText(getString(R.string.main_adb_clip_label), PhantomProcessLimit.adbCommand(enabled)), ClipData.newPlainText("DroidDeck child-process setting", PhantomProcessLimit.adbCommand(enabled)),
) )
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(this, "ADB command copied", android.widget.Toast.LENGTH_SHORT).show()
}, },
onDismissPhantomGate = { showPhantomGate = false }, onDismissPhantomGate = { showPhantomGate = false },
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) }, onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
@@ -754,35 +754,42 @@ class MainActivity : ComponentActivity() {
onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() }, onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() },
onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) }, onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() }, onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = true }, onMapping = { settingsHistory = settingsHistory.open(SettingsDestination.Mapping) },
onResetAll = { ControllerPrefs.resetAll(this); refreshController() }, onResetAll = { ControllerPrefs.resetAll(this); refreshController() },
), ),
), ),
page = page, page = page,
settingsContent = { s, a, openDeveloperOptions, requestWirelessAdb ->
s.settingsCategory?.let { category ->
SettingsCategoryPage(s, a, category, s.settingsMode, s.settingsTarget, openDeveloperOptions, requestWirelessAdb) { host ->
ModeSettingsHost(s.settingsMode, category, host)
}
}
},
) )
} }
if (showRoms) RomsDialog( if (showRoms) RomsDialog(
path = romsDir, path = romsDir,
onChoose = { onChoose = {
showRoms = false showRoms = false
pickRomsDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_roms), romsDir)) pickRomsDir.launch(InAppFilePicker.buildDirIntent(this, "Choose the ROMs folder", romsDir))
}, },
onClear = { SessionPrefs.setRomsDir(this, ""); romsDir = null; showRoms = false }, onClear = { SessionPrefs.setRomsDir(this, ""); romsDir = null; showRoms = false },
onDismiss = { showRoms = false }, onDismiss = { showRoms = false },
) )
showNonAdreno?.let { release -> showNonAdreno?.let { release ->
ConfirmDialog( ConfirmDialog(
title = androidx.compose.ui.res.stringResource(R.string.main_non_adreno_title), title = "Not an Adreno GPU",
text = androidx.compose.ui.res.stringResource(R.string.main_non_adreno_text, com.droiddeck.launcher.core.DeviceSupport.gpuName(this@MainActivity), release.size / 1e6), text = "Turnip supports Adreno GPUs. On ${com.droiddeck.launcher.core.DeviceSupport.gpuName()}, Steam may show a black screen. Download: ${"%.0f".format(release.size / 1e6)} MB.",
confirm = androidx.compose.ui.res.stringResource(R.string.main_install_anyway), confirm = "Install anyway",
onConfirm = { showNonAdreno = null; install(release) }, onConfirm = { showNonAdreno = null; install(release) },
onDismiss = { showNonAdreno = null }, onDismiss = { showNonAdreno = null },
) )
} }
if (showRemove) ConfirmDialog( if (showRemove) ConfirmDialog(
title = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_title), title = "Remove Linux runtime",
text = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_text), text = "This deletes the runtime, the Steam client inside it, and every game installed there.",
confirm = androidx.compose.ui.res.stringResource(R.string.store_remove), confirm = "Remove",
onConfirm = { showRemove = false; removeRuntime() }, onConfirm = { showRemove = false; removeRuntime() },
onDismiss = { showRemove = false }, onDismiss = { showRemove = false },
) )
@@ -892,7 +899,7 @@ class MainActivity : ComponentActivity() {
if (!SessionState.running) Thread({ if (!SessionState.running) Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList()) val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
if (applied.isNotEmpty()) ui.post { if (applied.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
} }
ui.post { if (showComponents) components.refreshComponents() } ui.post { if (showComponents) components.refreshComponents() }
}, "components-queue").start() }, "components-queue").start()
@@ -951,13 +958,9 @@ class MainActivity : ComponentActivity() {
try { try {
HomeApp.launch(this, app, displayId) HomeApp.launch(this, app, displayId)
} catch (_: Exception) { } catch (_: Exception) {
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
val message = when { else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label) android.widget.Toast.makeText(this, "Could not open ${app.label} on $target", android.widget.Toast.LENGTH_SHORT).show()
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
}
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
} }
} }
@@ -988,7 +991,7 @@ class MainActivity : ComponentActivity() {
if (busy || LinuxRuntimeInstaller.isBusy() || saveBusy != null) return if (busy || LinuxRuntimeInstaller.isBusy() || saveBusy != null) return
saveBusy = label saveBusy = label
Thread({ Thread({
val message = runCatching(work).getOrElse { e -> getString(R.string.main_action_failed, label, e.message ?: e.javaClass.simpleName) } val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
ui.post { ui.post {
saveBusy = null saveBusy = null
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
@@ -997,11 +1000,7 @@ class MainActivity : ComponentActivity() {
} }
private fun openProtons() { private fun openProtons() {
settingsMode = null settingsHistory = settingsHistory.open(SettingsDestination.Protons)
showPerformance = false
showComponents = false
showMapping = false
showProtons = true
protons.refreshProtons() protons.refreshProtons()
} }
@@ -1016,28 +1015,24 @@ class MainActivity : ComponentActivity() {
mapping = settings.mapping, mapping = settings.mapping,
onPick = { id, target -> ControllerPrefs.setTarget(this, id, target); refreshController() }, onPick = { id, target -> ControllerPrefs.setTarget(this, id, target); refreshController() },
onReset = { ControllerPrefs.resetMapping(this); refreshController() }, onReset = { ControllerPrefs.resetMapping(this); refreshController() },
onBack = { showMapping = false }, onBack = { settingsBack() },
) )
} }
private fun openComponents(focusContent: Boolean = true, tab: String? = null) { private fun openComponents(focusContent: Boolean = true, tab: String? = null, target: String? = null) {
focusComponentsContent = focusContent focusComponentsContent = focusContent
if (tab != null) components.compComp = tab if (tab != null) components.compComp = tab
settingsMode = null settingsHistory = settingsHistory.open(SettingsDestination.Components(tab ?: components.compComp, target))
showPerformance = false
showProtons = false
showMapping = false
showComponents = true
components.refreshComponents(snapshotFirst = true) components.refreshComponents(snapshotFirst = true)
drivers.refreshDrivers() drivers.refreshDrivers()
} }
private fun importComponent(uri: Uri) { private fun importComponent(uri: Uri) {
val name = displayNameOf(uri) ?: "imported.wcp" val name = displayNameOf(uri) ?: "imported.wcp"
components.componentAction(getString(R.string.comp_busy_importing)) { components.componentAction("Importing") {
val tmp = File(cacheDir, "component-import.wcp") val tmp = File(cacheDir, "component-import.wcp")
contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error(getString(R.string.comp_cannot_read)) contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("cannot read the file")
try { getString(R.string.comp_imported, ComponentsManager.importPackage(this, tmp, name).version) } finally { tmp.delete() } try { "Imported ${ComponentsManager.importPackage(this, tmp, name).version}" } finally { tmp.delete() }
} }
} }
@@ -1053,17 +1048,24 @@ class MainActivity : ComponentActivity() {
busy = if (busy) stage else components.compBusy, busy = if (busy) stage else components.compBusy,
downloads = components.compDownloads, downloads = components.compDownloads,
requestInitialFocus = focusComponentsContent, requestInitialFocus = focusComponentsContent,
onProton = { components.chooseProton(it) }, onProton = { components.compProton = it },
onComp = { components.compComp = it }, defaultProtonId = components.defaultProtonId,
onSwap = { file -> components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_swapping)) { ComponentsManager.swap(this, pid, file) } } }, onDefaultProton = { components.chooseProton(it) },
onRestore = { version -> components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_restoring)) { ComponentsManager.restore(this, pid, components.compComp, version) } } }, onComp = { tab ->
onCancelQueued = { components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_cancelling)) { ComponentsManager.cancelQueued(this, pid, components.compComp); getString(R.string.comp_swap_cancelled) } } }, components.compComp = tab
onDeletePackage = { file -> components.componentAction(getString(R.string.comp_busy_deleting)) { ComponentsManager.deletePackage(this, file) } }, if (settingsHistory.current is SettingsDestination.Components) {
onDeleteOriginal = { version -> components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_deleting)) { ComponentsManager.deleteOriginal(this, pid, components.compComp, version) } } }, settingsHistory = settingsHistory.replace(SettingsDestination.Components(tab))
}
},
onSwap = { file -> components.compProton?.let { pid -> components.componentAction("Swapping") { ComponentsManager.swap(this, pid, file) } } },
onRestore = { version -> components.compProton?.let { pid -> components.componentAction("Restoring") { ComponentsManager.restore(this, pid, components.compComp, version) } } },
onCancelQueued = { components.compProton?.let { pid -> components.componentAction("Cancelling") { ComponentsManager.cancelQueued(this, pid, components.compComp); "The waiting swap was cancelled." } } },
onDeletePackage = { file -> components.componentAction("Deleting") { ComponentsManager.deletePackage(this, file) } },
onDeleteOriginal = { version -> components.compProton?.let { pid -> components.componentAction("Deleting") { ComponentsManager.deleteOriginal(this, pid, components.compComp, version) } } },
onDownload = { components.downloadComponent(it) }, onDownload = { components.downloadComponent(it) },
onRefresh = { components.refreshComponentCatalog() }, onRefresh = { components.refreshComponentCatalog() },
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) }, onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
onBack = { showComponents = false }, onBack = { settingsBack() },
gpu = drivers.state(), gpu = drivers.state(),
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions( gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
onAuto = { on -> drivers.setMode(on) }, onAuto = { on -> drivers.setMode(on) },
@@ -1075,9 +1077,9 @@ class MainActivity : ComponentActivity() {
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) }, onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) }, onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) }, onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.drivers_pick_linux))) }, 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, getString(R.string.drivers_pick_android))) }, 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, getString(R.string.drivers_pick_any))) }, onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a driver zip or an Android + Linux bundle")) },
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() }, onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
), ),
) )
@@ -1095,7 +1097,7 @@ class MainActivity : ComponentActivity() {
onInstall = { id -> protons.installProton(id) }, onInstall = { id -> protons.installProton(id) },
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() }, onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
onRemove = { id -> protons.removeProton(id) }, onRemove = { id -> protons.removeProton(id) },
onBack = { showProtons = false }, onBack = { settingsBack() },
) )
} }
@@ -1113,14 +1115,14 @@ class MainActivity : ComponentActivity() {
private fun installPackage(id: String) { private fun installPackage(id: String) {
val entry = catalog?.firstOrNull { it.id == id } ?: return val entry = catalog?.firstOrNull { it.id == id } ?: return
if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return
pkgId = id; pkgStage = getString(R.string.store_starting); pkgPercent = -1 pkgId = id; pkgStage = "Starting…"; pkgPercent = -1
Thread({ Thread({
val problem = DesktopCatalog.install(this, entry) { stage, percent -> val problem = DesktopCatalog.install(this, entry) { stage, percent ->
ui.post { pkgStage = stage; pkgPercent = percent } ui.post { pkgStage = stage; pkgPercent = percent }
} }
ui.post { ui.post {
pkgStage = null; pkgId = null pkgStage = null; pkgId = null
if (problem != null) android.widget.Toast.makeText(this, getString(R.string.main_pkg_problem, entry.name, problem), android.widget.Toast.LENGTH_LONG).show() if (problem != null) android.widget.Toast.makeText(this, "${entry.name}: $problem", android.widget.Toast.LENGTH_LONG).show()
refreshPackages() refreshPackages()
refresh() refresh()
} }
@@ -1130,7 +1132,7 @@ class MainActivity : ComponentActivity() {
private fun removePackage(id: String) { private fun removePackage(id: String) {
val entry = catalog?.firstOrNull { it.id == id } ?: return val entry = catalog?.firstOrNull { it.id == id } ?: return
if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return
pkgId = id; pkgStage = getString(if (entry.kind == "appimage") R.string.main_removing_named else R.string.main_forgetting_named, entry.name); pkgPercent = -1 pkgId = id; pkgStage = if (entry.kind == "appimage") "Removing ${entry.name}…" else "Forgetting ${entry.name}…"; pkgPercent = -1
Thread({ Thread({
DesktopCatalog.remove(this, entry) DesktopCatalog.remove(this, entry)
ui.post { ui.post {
@@ -1142,11 +1144,10 @@ class MainActivity : ComponentActivity() {
} }
@Composable @Composable
private fun ModeSettingsHost(mode: String) { private fun ModeSettingsHost(mode: String, category: SettingsCategory, host: MenuHost) {
ModeSettingsPage( ModeSettingsContent(
ModeSettings( ModeSettings(
mode = mode, resolution = resolution, mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit,
upscaler = upscaler, upscaleSharpness = upscaleSharpness, upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(), gpuDrivers = drivers.summary(),
@@ -1169,7 +1170,6 @@ class MainActivity : ComponentActivity() {
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null, syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null, steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode, steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp, mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null, steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup, runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
@@ -1184,7 +1184,6 @@ class MainActivity : ComponentActivity() {
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null, deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null, deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent, deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
deckyDownloadingBinary = decky.deckyDownloadingBinary,
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running, deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
), ),
ModeSettingsActions( ModeSettingsActions(
@@ -1203,7 +1202,9 @@ class MainActivity : ComponentActivity() {
} }
}, },
onWifiDiscoverySettings = { openWifiDiscoverySettings() }, onWifiDiscoverySettings = { openWifiDiscoverySettings() },
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value }, onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps }, onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
@@ -1233,7 +1234,7 @@ class MainActivity : ComponentActivity() {
onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r }, onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
onGameStorage = { path, label -> setGameStorage(path, label) }, onGameStorage = { path, label -> setGameStorage(path, label) },
onPickGameStorageFolder = { onPickGameStorageFolder = {
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_game_storage), gameStorage.ifEmpty { null })) pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, "Choose the game storage folder", gameStorage.ifEmpty { null }))
}, },
onStorageDiagnostics = { on -> onStorageDiagnostics = { on ->
SessionPrefs.setStorageDiagnosticsEnabled(this, on) SessionPrefs.setStorageDiagnosticsEnabled(this, on)
@@ -1247,7 +1248,6 @@ class MainActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this) syncFallback = SessionPrefs.syncFallback(this)
}, },
onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id }, onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) },
onSteamDeckMode = { on -> onSteamDeckMode = { on ->
SessionPrefs.setSteamDeckMode(this, on) SessionPrefs.setSteamDeckMode(this, on)
steamDeckMode = on steamDeckMode = on
@@ -1259,13 +1259,13 @@ class MainActivity : ComponentActivity() {
SessionPrefs.setRunSteamAtStartup(this, on) SessionPrefs.setRunSteamAtStartup(this, on)
runSteamAtStartup = on runSteamAtStartup = on
}, },
onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_added_games), addedGamesDirs.lastOrNull())) }, onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, "Choose a folder of your own games", addedGamesDirs.lastOrNull())) },
onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() }, onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() }, onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() },
onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() }, onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() },
onPickAddedGameExe = { folder -> onPickAddedGameExe = { folder ->
pendingAddedGame = folder pendingAddedGame = folder
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), getString(R.string.main_pick_game_exe), folder)) pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder))
}, },
onDeckyInstall = { release -> decky.installDecky(release) }, onDeckyInstall = { release -> decky.installDecky(release) },
onDeckyCheck = { decky.refreshDecky() }, onDeckyCheck = { decky.refreshDecky() },
@@ -1276,10 +1276,15 @@ class MainActivity : ComponentActivity() {
decky.deckySupervisor = false decky.deckySupervisor = false
}, },
onPickDeckyPluginZip = { onPickDeckyPluginZip = {
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip))) pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Decky plugin ZIP"))
}, },
onDismiss = { settingsMode = null }, onDismiss = { settingsBack() },
), ),
category = category,
host = host,
)
if (category == SettingsCategory.DISPLAY) com.droiddeck.launcher.ui.GraphicsSettingsContent(
host, upscaler, { value -> SessionPrefs.setUpscaler(this, value); upscaler = value },
) )
} }
@@ -1308,7 +1313,7 @@ class MainActivity : ComponentActivity() {
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on }, onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on }, onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on }, onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) }, onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name); guestHostname = SessionPrefs.guestHostname(this) },
onClientCore = { core, on -> onClientCore = { core, on ->
clientCores = if (on) clientCores + core else clientCores - core clientCores = if (on) clientCores + core else clientCores - core
SessionPrefs.setClientCpus(this, CpuCores.format(clientCores)) SessionPrefs.setClientCpus(this, CpuCores.format(clientCores))
@@ -1317,7 +1322,7 @@ class MainActivity : ComponentActivity() {
gameCores = if (on) gameCores + core else gameCores - core gameCores = if (on) gameCores + core else gameCores - core
SessionPrefs.setGameCpus(this, CpuCores.format(gameCores)) SessionPrefs.setGameCpus(this, CpuCores.format(gameCores))
}, },
onDismiss = { showPerformance = false }, onDismiss = { settingsBack() },
) )
} }
@@ -1354,23 +1359,57 @@ class MainActivity : ComponentActivity() {
private var pipAutoEnter by mutableStateOf(false) private var pipAutoEnter by mutableStateOf(false)
private fun openModeSettings(mode: String) { private fun openModeSettings(mode: String) {
refreshModeSettings(mode)
settingsHistory = settingsHistory.open(SettingsDestination.Category(SettingsCategory.SESSIONS, mode))
}
private fun openSettingsCategory(category: SettingsCategory, target: String?) {
val entry = com.droiddeck.launcher.ui.SettingsCatalog.entries.firstOrNull { it.target == target }
val mode = entry?.mode ?: SessionService.MODE_STEAM
refreshModeSettings(mode)
val categoryTarget = com.droiddeck.launcher.ui.settingsCategoryTarget(target)
settingsHistory = settingsHistory.open(SettingsDestination.Category(category, mode, categoryTarget))
when {
target == "components" -> openComponents(true, "fex")
target == "default-proton" || target == "editing-proton" -> openComponents(true, "fex", target)
target == "gpu-drivers" -> openComponents(true, com.droiddeck.launcher.ui.GPU_TAB)
target == "protons" -> openProtons()
target == "controller-mapping" -> settingsHistory = settingsHistory.open(SettingsDestination.Mapping)
target == "performance" || target?.startsWith("performance:") == true -> {
refreshCores()
settingsHistory = settingsHistory.open(SettingsDestination.Performance(target?.substringAfter("performance:", "")?.ifEmpty { null }))
}
}
}
private fun settingsBack() {
settingsHistory = settingsHistory.back()
when (val destination = settingsHistory.current) {
is SettingsDestination.Category -> refreshModeSettings(destination.mode)
is SettingsDestination.Components -> {
destination.tab?.let { components.compComp = it }
components.refreshComponents(snapshotFirst = true)
drivers.refreshDrivers()
}
else -> Unit
}
}
private fun refreshModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this) pipAutoEnter = SessionPrefs.pipAutoEnter(this)
showPerformance = false resolutionCap = SessionPrefs.resolutionCap(this, mode)
showProtons = false customResolution = SessionPrefs.customResolution(this, mode)
showComponents = false
showMapping = false
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
fexPreset = SessionPrefs.fexPreset(this) fexPreset = SessionPrefs.fexPreset(this)
fastSync = SessionPrefs.fastSync(this) fastSync = SessionPrefs.fastSync(this)
fsyncFirst = SessionPrefs.fsyncFirst(this) fsyncFirst = SessionPrefs.fsyncFirst(this)
syncFallback = SessionPrefs.syncFallback(this) syncFallback = SessionPrefs.syncFallback(this)
steamChannel = SessionPrefs.steamChannel(this) steamChannel = SessionPrefs.steamChannel(this)
steamDeckMode = SessionPrefs.steamDeckMode(this) steamDeckMode = SessionPrefs.steamDeckMode(this)
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this) mangoapp = SessionPrefs.mangoapp(this)
steamController = SessionPrefs.steamController(this) steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this) runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
addedGamesDirs = SessionPrefs.addedGamesDirs(this) addedGamesDirs = SessionPrefs.addedGamesDirs(this)
shapeMode = SessionPrefs.shapeMode(this)
hdrOn = SessionPrefs.hdr(this, mode) hdrOn = SessionPrefs.hdr(this, mode)
fpsLimit = SessionPrefs.fpsLimit(this, mode) fpsLimit = SessionPrefs.fpsLimit(this, mode)
upscaler = SessionPrefs.upscaler(this) upscaler = SessionPrefs.upscaler(this)
@@ -1389,13 +1428,12 @@ class MainActivity : ComponentActivity() {
renderer = SessionPrefs.desktopRenderer(this) renderer = SessionPrefs.desktopRenderer(this)
gameStorage = SessionPrefs.gameStorage(this) gameStorage = SessionPrefs.gameStorage(this)
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this) storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
settingsMode = mode
// The page opens at once, on what was last read; the slow part (driver files, a walk of the // The page opens at once, on what was last read; the slow part (driver files, a walk of the
// added-games folders, the storage volumes) lands while it animates in. // added-games folders, the storage volumes) lands while it animates in.
Thread({ Thread({
drivers.refreshDrivers() drivers.refreshDrivers()
val games = scanAddedGames() val games = scanAddedGames()
val storage = GameStorage.options(this) val storage = GameStorage.options(this).map { it.label to it.path }
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this) val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
ui.post { ui.post {
@@ -1414,9 +1452,9 @@ class MainActivity : ComponentActivity() {
/** A second Steam library, proven writable first; "" = internal only. */ /** A second Steam library, proven writable first; "" = internal only. */
private fun setGameStorage(path: String, label: String) { private fun setGameStorage(path: String, label: String) {
if (path.isNotEmpty() && path != SessionPrefs.GAME_STORAGE_OFF) { if (path.isNotEmpty() && path != SessionPrefs.GAME_STORAGE_OFF) {
val problem = GameStorage.prepare(this, path) val problem = GameStorage.prepare(path)
if (problem != null) { if (problem != null) {
android.widget.Toast.makeText(this, getString(R.string.main_storage_not_usable, problem), android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(this, "Not usable: $problem", android.widget.Toast.LENGTH_LONG).show()
return return
} }
} }
@@ -1458,9 +1496,9 @@ class MainActivity : ComponentActivity() {
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() } romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this) logsEnabled = SessionPrefs.logsEnabled(this)
runningLabel = if (SessionState.running) when (SessionState.mode) { runningLabel = if (SessionState.running) when (SessionState.mode) {
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop) SessionService.MODE_DESKTOP -> "Desktop"
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program) SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
?: SessionState.program?.substringAfterLast('/')?.substringBefore('.') ?: getString(R.string.main_running_program) ?: SessionState.program?.substringAfterLast('/')?.substringBefore('.') ?: "Program"
else -> "Steam" else -> "Steam"
} else null } else null
// The libraries, off the main thread: manifests and a folder scan. // The libraries, off the main thread: manifests and a folder scan.
@@ -1527,10 +1565,7 @@ class MainActivity : ComponentActivity() {
private fun refreshPhantomStatus() { private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(this) phantomProcessStatus = PhantomProcessLimit.read(this)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
getString( "${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.adbCommand()}"
R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus),
PhantomProcessLimit.instructions(this, phantomProcessStatus), PhantomProcessLimit.adbCommand(),
)
} else null } else null
} }
@@ -1546,10 +1581,10 @@ class MainActivity : ComponentActivity() {
} catch (error: Exception) { } catch (error: Exception) {
if (displayId != null) { if (displayId != null) {
runCatching { startActivity(intent) } runCatching { startActivity(intent) }
android.widget.Toast.makeText(this, R.string.main_settings_main_screen, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(this, "Could not open Settings on the bottom screen; opened it on the main screen.", android.widget.Toast.LENGTH_LONG).show()
} else { } else {
startActivity(Intent(android.provider.Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) startActivity(Intent(android.provider.Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
android.widget.Toast.makeText(this, R.string.main_open_dev_options, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(this, "Open Developer options in Settings", android.widget.Toast.LENGTH_LONG).show()
} }
} }
} }
@@ -1582,7 +1617,7 @@ class MainActivity : ComponentActivity() {
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) { private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
busy = true busy = true
failed = false failed = false
stage = getString(if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting) stage = if (LinuxRuntimeInstaller.isRemoving()) "Removing Linux runtime" else "Starting…"
percent = -1 percent = -1
Thread({ Thread({
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p -> val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
@@ -24,7 +24,7 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
if (protonBusyId != null || SessionState.running) return if (protonBusyId != null || SessionState.running) return
ProtonExtras.unqueue(activity, tool) ProtonExtras.unqueue(activity, tool)
protonBusyId = id protonBusyId = id
protonStage = activity.getString(R.string.store_starting) protonStage = "Starting…"
protonPercent = -1 protonPercent = -1
Thread({ Thread({
val problem = ProtonExtras.install(activity, tool) { label, value -> val problem = ProtonExtras.install(activity, tool) { label, value ->
@@ -44,7 +44,7 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return if (protonBusyId != null || SessionState.running) return
protonBusyId = id protonBusyId = id
protonStage = activity.getString(R.string.main_removing_named, tool.name) protonStage = "Removing ${tool.name}…"
protonPercent = -1 protonPercent = -1
Thread({ Thread({
ProtonExtras.remove(activity, tool) ProtonExtras.remove(activity, tool)
@@ -59,7 +59,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.LoadingState import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.PerfHud import com.droiddeck.launcher.session.PerfHud
import com.droiddeck.launcher.session.PerfMode import com.droiddeck.launcher.session.PerfMode
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.session.GameEnvironmentStore import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionEvents import com.droiddeck.launcher.session.SessionEvents
@@ -83,9 +82,7 @@ import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File import java.io.File
import com.droiddeck.launcher.session.ComponentsManager import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.SessionDrawerPage import com.droiddeck.launcher.ui.DRAWER_PAGES
import com.droiddeck.launcher.ui.sessionDrawerPages
import com.droiddeck.launcher.ui.step
import kotlin.math.abs import kotlin.math.abs
/** /**
@@ -100,11 +97,6 @@ import kotlin.math.abs
* the HUD line, the loading overlay, the drawer and its dialogs. * the HUD line, the loading overlay, the drawer and its dialogs.
*/ */
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
private var pipUi by mutableStateOf(false) private var pipUi by mutableStateOf(false)
private var pipAutoEnter by mutableStateOf(false) private var pipAutoEnter by mutableStateOf(false)
@@ -166,21 +158,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val cursorBuf = IntArray(WaylandCompositor.CURSOR_BUF_INTS) private val cursorBuf = IntArray(WaylandCompositor.CURSOR_BUF_INTS)
private var cursorSerial = 0 private var cursorSerial = 0
private var clientHidesCursor = false private var clientHidesCursor = false
/**
* A program holds a pointer lock (zwp_locked_pointer_v1: a mouse-look game, through gamescope).
* While it does, a physical mouse is captured and its raw deltas go to the program as relative
* motion. Without capture the deltas are worked out from Android's pointer position, which stops
* at the screen edge, and so did the camera (#153).
*/
private var pointerLocked = false
private val pointerLockListener = WaylandCompositor.PointerLockListener { locked, _, _ ->
uiHandler.post {
if (pointerLocked == locked) return@post
pointerLocked = locked
Log.i(TAG, "pointer lock " + if (locked) "taken by a program" else "released")
updatePointerCapture()
}
}
private var cursorImage by mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null) private var cursorImage by mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null)
private var cursorHotX by mutableStateOf(0) private var cursorHotX by mutableStateOf(0)
private var cursorHotY by mutableStateOf(0) private var cursorHotY by mutableStateOf(0)
@@ -228,7 +205,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var closeAtOnce = false private var closeAtOnce = false
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */ /** The drawer's Components tab: the Protons as last read (ComponentsManager). */
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null) private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER) private var drawerPage by mutableIntStateOf(0)
private var drawerControllerActive by mutableStateOf(false) private var drawerControllerActive by mutableStateOf(false)
private var backActionsInverted by mutableStateOf(false) private var backActionsInverted by mutableStateOf(false)
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */ /** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
@@ -248,7 +225,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var fexPreset by mutableStateOf("") private var fexPreset by mutableStateOf("")
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var onScreenButtonsVisible by mutableStateOf(false) private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode) private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode)
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList()) private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay) private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay)
@@ -290,12 +267,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onInputDeviceAdded(deviceId: Int) { override fun onInputDeviceAdded(deviceId: Int) {
logInputDevice("connected", deviceId) logInputDevice("connected", deviceId)
updateOnScreenControls() updateOnScreenControls()
updatePointerCapture()
} }
override fun onInputDeviceRemoved(deviceId: Int) { override fun onInputDeviceRemoved(deviceId: Int) {
Log.i(TAG, "input device $deviceId disconnected") Log.i(TAG, "input device $deviceId disconnected")
updateOnScreenControls() updateOnScreenControls()
updatePointerCapture()
} }
override fun onInputDeviceChanged(deviceId: Int) = updateOnScreenControls() override fun onInputDeviceChanged(deviceId: Int) = updateOnScreenControls()
} }
@@ -306,7 +281,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving()) { if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving()) {
runtimeRemovalBlocked = true runtimeRemovalBlocked = true
android.widget.Toast.makeText(this, R.string.session_wait_removal, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(this, "Wait for runtime removal to finish", android.widget.Toast.LENGTH_SHORT).show()
finish() finish()
return return
} }
@@ -346,16 +321,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// below) and the session starts when it is in. // below) and the session starts when it is in.
if (!LinuxRuntime.isInstalled(this)) Log.i(TAG, "the Linux runtime is not installed; the loading screen installs it") if (!LinuxRuntime.isInstalled(this)) Log.i(TAG, "the Linux runtime is not installed; the loading screen installs it")
// Captured mouse events go down the focus chain, and focus sits somewhere in the overlay: val root = FrameLayout(this)
// the root sees every one of them whichever view that is.
val root = object : FrameLayout(this) {
override fun dispatchCapturedPointerEvent(event: MotionEvent): Boolean =
onCapturedPointer(event) || super.dispatchCapturedPointerEvent(event)
override fun dispatchPointerCaptureChanged(hasCapture: Boolean) {
super.dispatchPointerCaptureChanged(hasCapture)
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
}
}
surfaceView = SurfaceView(this) surfaceView = SurfaceView(this)
surfaceView.holder.addCallback(this) surfaceView.holder.addCallback(this)
root.addView(surfaceView) root.addView(surfaceView)
@@ -418,7 +384,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
updateOnScreenControls() updateOnScreenControls()
WaylandCompositor.setFirstFrameListener(firstFrameListener) WaylandCompositor.setFirstFrameListener(firstFrameListener)
WaylandCompositor.setPointerLockListener(pointerLockListener)
SessionEvents.markReadyIfPossible() SessionEvents.markReadyIfPossible()
SessionState.endListener = endListener SessionState.endListener = endListener
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord. // A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
@@ -449,8 +414,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// this full-screen host and remain as a white veil after the drawer closes. // this full-screen host and remain as a white veil after the drawer closes.
defaultFocusHighlightEnabled = false defaultFocusHighlightEnabled = false
setContent { setContent {
// The drawer, the PC keyboard and picture in picture take the mouse back.
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, pipUi) { updatePointerCapture() }
DroidDeckTheme { DroidDeckTheme {
if (pipUi) { if (pipUi) {
if (SessionState.suspended) androidx.compose.foundation.layout.Box( if (SessionState.suspended) androidx.compose.foundation.layout.Box(
@@ -467,7 +430,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (hud.text.isNotEmpty()) HudText(hud.text) if (hud.text.isNotEmpty()) HudText(hud.text)
if (loading.visible) LoadingOverlay( if (loading.visible) LoadingOverlay(
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended, loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
topic = loading.topic, readable = loading.readable,
title = loadingTitle(), steam = loadingMode() == SessionService.MODE_STEAM, title = loadingTitle(), steam = loadingMode() == SessionService.MODE_STEAM,
// As the drawer's Stop does: the service stops, and a start still installing is cancelled. // As the drawer's Stop does: the service stops, and a start still installing is cancelled.
onCancel = { SessionService.stop(this@SessionActivity); finish() }, onCancel = { SessionService.stop(this@SessionActivity); finish() },
@@ -503,7 +465,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions( SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM, steam = SessionState.mode == SessionService.MODE_STEAM,
title = if (SessionState.mode == SessionService.MODE_RUN) title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null, com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null,
isHomeApp = isHomeApp, isHomeApp = isHomeApp,
androidApps = androidApps, androidApps = androidApps,
hudOn = hudOn, hudOn = hudOn,
@@ -512,9 +474,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias, effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
frameGen = frameGen, frameGen = frameGen,
lossless = lossless, lossless = lossless,
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy, touchMode = touchMode, oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct), touchAuto = if (usingTouchpad()) "touchpad" else "direct",
fexPreset = fexPreset, shapeMode = shapeMode, fexPreset = fexPreset,
secondScreenMode = secondScreenMode, secondScreenMode = secondScreenMode,
secondScreenDisplays = secondScreenDisplays, secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay, selectedSecondScreenDisplay = selectedSecondScreenDisplay,
@@ -566,6 +528,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionService.suspendPolicyChanged(this@SessionActivity) SessionService.suspendPolicyChanged(this@SessionActivity)
}, },
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = ::selectSecondScreenMode, onSecondScreenMode = ::selectSecondScreenMode,
onSecondScreenDisplay = ::selectSecondScreenDisplay, onSecondScreenDisplay = ::selectSecondScreenDisplay,
@@ -574,13 +537,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
try { try {
HomeApp.launch(this@SessionActivity, app, displayId) HomeApp.launch(this@SessionActivity, app, displayId)
} catch (_: Exception) { } catch (_: Exception) {
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
val message = when { else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label) Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
}
Toast.makeText(this@SessionActivity, message, Toast.LENGTH_SHORT).show()
} }
}, },
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this@SessionActivity), pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this@SessionActivity),
@@ -698,7 +657,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val snap = runCatching { ComponentsManager.snapshot(this) }.getOrNull() val snap = runCatching { ComponentsManager.snapshot(this) }.getOrNull()
uiHandler.post { uiHandler.post {
drawerComponents = snap drawerComponents = snap
if (applied.isNotEmpty()) android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show() if (applied.isNotEmpty()) android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
} }
}, "drawer-components").start() }, "drawer-components").start()
} }
@@ -713,10 +672,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val current = active ?: "orig:$build" val current = active ?: "orig:$build"
if (queued != null && value == current) { if (queued != null && value == current) {
// Picking what is already in place again cancels the swap waiting for the game. // Picking what is already in place again cancels the swap waiting for the game.
ComponentsManager.cancelQueued(this, protonId, comp); getString(R.string.comp_swap_cancelled) ComponentsManager.cancelQueued(this, protonId, comp); "The waiting swap was cancelled."
} else if (value.startsWith("orig:")) ComponentsManager.restore(this, protonId, comp, value.removePrefix("orig:")) } else if (value.startsWith("orig:")) ComponentsManager.restore(this, protonId, comp, value.removePrefix("orig:"))
else ComponentsManager.swap(this, protonId, value) else ComponentsManager.swap(this, protonId, value)
}.getOrElse { e -> getString(R.string.session_swap_failed, e.message ?: e.javaClass.simpleName) } }.getOrElse { e -> "Swap failed: ${e.message ?: e.javaClass.simpleName}" }
uiHandler.post { uiHandler.post {
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
refreshDrawerComponents() refreshDrawerComponents()
@@ -730,22 +689,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
else intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM else intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
private fun pausedTitle(): String = when (SessionState.mode) { private fun pausedTitle(): String = when (SessionState.mode) {
SessionService.MODE_DESKTOP -> getString(R.string.session_desktop_paused) SessionService.MODE_DESKTOP -> "The desktop is paused"
SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) SessionService.MODE_RUN -> (com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "The program") + " is paused"
?.let { getString(R.string.session_named_paused, it) } ?: getString(R.string.session_program_paused) else -> "Steam is paused"
else -> getString(R.string.load_steam_paused)
} }
private fun loadingTitle(): String = when (loadingMode()) { private fun loadingTitle(): String = when (loadingMode()) {
SessionService.MODE_DESKTOP -> SessionService.MODE_DESKTOP ->
if (!SessionState.running && intent.getStringExtra(SessionService.EXTRA_STEAM_UI) != null) getString(R.string.session_starting_steam_desktop) if (!SessionState.running && intent.getStringExtra(SessionService.EXTRA_STEAM_UI) != null) "Starting Steam on the desktop"
else getString(R.string.session_starting_desktop) else "Starting the desktop"
SessionService.MODE_RUN -> { SessionService.MODE_RUN -> {
val program = if (SessionState.running) SessionState.program else intent.getStringExtra(SessionService.EXTRA_PROGRAM) val program = if (SessionState.running) SessionState.program else intent.getStringExtra(SessionService.EXTRA_PROGRAM)
com.droiddeck.launcher.frontend.Library.nameForProgram(program)?.let { getString(R.string.session_starting_named, it) } "Starting " + (com.droiddeck.launcher.frontend.Library.nameForProgram(program) ?: "the program")
?: getString(R.string.session_starting_program)
} }
else -> getString(R.string.load_starting_steam) else -> "Starting Steam"
} }
private fun shareCurrentSessionLogs() { private fun shareCurrentSessionLogs() {
@@ -753,7 +710,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// ended screen's Share logs is for that one. // ended screen's Share logs is for that one.
val folder = SessionPaths.current() ?: SessionPaths.lastEnded() val folder = SessionPaths.current() ?: SessionPaths.lastEnded()
if (folder == null || !folder.isDirectory) { if (folder == null || !folder.isDirectory) {
Toast.makeText(this, R.string.session_no_logs, Toast.LENGTH_LONG).show() Toast.makeText(this, "No logs for this session.", Toast.LENGTH_LONG).show()
return return
} }
Thread({ Thread({
@@ -762,12 +719,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
.getOrNull() .getOrNull()
uiHandler.post { uiHandler.post {
if (zip == null) { if (zip == null) {
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show() Toast.makeText(this, "Could not create the session log archive.", Toast.LENGTH_LONG).show()
} else { } else {
runCatching { startActivity(SessionLogShare.shareIntent(this, zip)) } runCatching { startActivity(SessionLogShare.shareIntent(this, zip)) }
.onFailure { .onFailure {
Log.w(TAG, "could not share current session logs", it) Log.w(TAG, "could not share current session logs", it)
Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show() Toast.makeText(this, "Could not share the session logs.", Toast.LENGTH_LONG).show()
} }
} }
} }
@@ -799,6 +756,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
fexPreset = SessionPrefs.fexPreset(this) fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
oscMode = SessionPrefs.oscMode(this) oscMode = SessionPrefs.oscMode(this)
shapeMode = SessionPrefs.shapeMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this) backActionsInverted = SessionPrefs.backActionsInverted(this)
} }
@@ -826,8 +784,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
"${SessionState.installing}.installing", "${SessionState.installing}.installing",
mapOf("component" to SessionState.installing), mapOf("component" to SessionState.installing),
) )
val first = if (runtime) RUNTIME_LINES else if (desktop) DESKTOP_LINES else PROTON_LINES loading.step = if (runtime) "downloading the Linux runtime" else if (desktop) "downloading the desktop"
loading.say(getString(first.downloading), first.topic, readable = true) else "downloading Proton Experimental (ARM64)"
loading.percent = -1 loading.percent = -1
Thread({ Thread({
var failedComponent: String? = null var failedComponent: String? = null
@@ -868,7 +826,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return@post return@post
} }
loading.percent = -1 loading.percent = -1
loading.say(getString(R.string.session_starting_session), LoadingState.Topic.SESSION, readable = false) loading.step = "Starting the session…"
// The surface may have come and gone while the download ran; start on the live one. // The surface may have come and gone while the download ran; start on the live one.
if (surfaceView.holder.surface?.isValid == true) surfaceCreated(surfaceView.holder) if (surfaceView.holder.surface?.isValid == true) surfaceCreated(surfaceView.holder)
} }
@@ -884,32 +842,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}, "session-failure-artifacts").start() }, "session-failure-artifacts").start()
} }
/**
* The loading screen's lines for one package: downloading it (with and without its size), checking it,
* unpacking it; the checklist [topic] they belong to, and whether the checking line is shown as it is.
*/
private class PackageLines(
val downloading: Int, val downloadingMb: Int, val checking: Int, val unpacking: Int,
val topic: LoadingState.Topic, val checkingReadable: Boolean,
)
/** Reports one package's download on the loading screen: "<what> · 332 of 791 MB", checking, unpacking. */ /** Reports one package's download on the loading screen: "<what> · 332 of 791 MB", checking, unpacking. */
private fun progressFor(what: PackageLines, mb: Long) = object : com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { private fun progressFor(what: String, mb: Long) = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { stage, p ->
override fun onProgress(stage: String, percent: Int) = uiHandler.post {
onProgress(com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.Step.OTHER, stage, percent) loading.percent = p
loading.step = when {
override fun onProgress(step: com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.Step, stage: String, percent: Int) { stage.startsWith("Downloading") -> if (p >= 0 && mb > 0) "downloading $what · ${p * mb / 100} of $mb MB" else "downloading $what"
uiHandler.post { stage.startsWith("Verifying") -> "checking $what"
loading.percent = percent else -> "unpacking $what"
when (step) {
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.Step.DOWNLOADING -> loading.say(
if (percent >= 0 && mb > 0) getString(what.downloadingMb, percent * mb / 100, mb) else getString(what.downloading),
what.topic, readable = true,
)
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.Step.VERIFYING ->
loading.say(getString(what.checking), what.topic, what.checkingReadable)
else -> loading.say(getString(what.unpacking), what.topic, readable = true)
}
} }
} }
} }
@@ -917,29 +857,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
/** Null when the runtime is in, else the loading screen's closing line. */ /** Null when the runtime is in, else the loading screen's closing line. */
private fun installRuntime(): String? { private fun installRuntime(): String? {
val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease() val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease()
?: return getString(R.string.session_runtime_catalog_unreachable) ?: return "Could not reach the runtime catalog. Check the connection and press Play again."
val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release, val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release,
progressFor(RUNTIME_LINES, release.size / 1_000_000)) progressFor("the Linux runtime", release.size / 1_000_000))
return if (ok) null else getString(R.string.session_runtime_install_failed) return if (ok) null else "The Linux runtime did not install. Check the runtime in Setup and press Play again."
} }
/** Null when the desktop package is in, else the loading screen's closing line. */ /** Null when the desktop package is in, else the loading screen's closing line. */
private fun installDesktop(): String? { private fun installDesktop(): String? {
uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) } uiHandler.post { loading.percent = -1; loading.step = "downloading the desktop" }
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.fetch()?.firstOrNull { it.id == "desktop" } val entry = com.droiddeck.launcher.runtime.DesktopCatalog.fetch()?.firstOrNull { it.id == "desktop" }
?: return getString(R.string.session_desktop_catalog_unreachable) ?: return "Could not reach the desktop catalog. Check the connection and press Desktop again."
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry, val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
progressFor(DESKTOP_LINES, entry.size / 1_000_000)) progressFor("the desktop", entry.size / 1_000_000))
return problem?.let { getString(R.string.session_desktop_install_failed, it) } return problem?.let { "The desktop did not install ($it). Check the connection and press Desktop again." }
} }
/** Null when the ARM64 Proton is in, else why not; the session goes on either way. */ /** Null when the ARM64 Proton is in, else why not; the session goes on either way. */
private fun installProton(): String? { private fun installProton(): String? {
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) } uiHandler.post { loading.percent = -1; loading.step = "downloading Proton Experimental (ARM64)" }
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID } val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
?: return "catalog unreachable" ?: return "catalog unreachable"
return catalog.install(this, entry, progressFor(PROTON_LINES, entry.size / 1_000_000)) return catalog.install(this, entry, progressFor("Proton Experimental (ARM64)", entry.size / 1_000_000))
} }
override fun surfaceCreated(holder: SurfaceHolder) { override fun surfaceCreated(holder: SurfaceHolder) {
@@ -1072,15 +1012,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
private fun outputSize(): Pair<Int, Int> { private fun outputSize(): Pair<Int, Int> {
val bounds = panelBounds()
val panelW = maxOf(bounds.width(), bounds.height()).toFloat()
val panelH = minOf(bounds.width(), bounds.height()).toFloat()
// Never narrower than 16:9. A foldable's inner panel is nearly square, and a game handed a
// square display draws for the frame it was made for and cuts the sides off itself.
// Wider than 16:9 is fine - games and the client cope with a phone's 20:9 - so the
// panel's aspect is kept above that, unless the user pinned 16:9 for a foldable, and the
// compositor letterboxes onto a squarer panel.
// "Match screen" drops that floor, for a 4:3 or 3:2 handheld whose games should
// fill it.
val aspect = when (SessionPrefs.shapeMode(this)) {
SessionPrefs.SHAPE_WIDE -> 16f / 9f
SessionPrefs.SHAPE_EXACT -> panelW / panelH
else -> maxOf(panelW / panelH, 16f / 9f)
}
// 720 tall at most by default, client and desktop alike: the client's CEF is the heaviest
// thing in the session, and pixels above that cost frames for nothing anyone can see on a
// handheld panel. The mode's settings (the cog beside Play / Desktop) can change
// the cap or lift it to the panel.
val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this) // A custom resolution is taken as given; the compositor fits it to the panel.
SessionPrefs.customResolution(this, mode)?.let { return it }
// An emulator whose frames cost next to nothing (Library.drawsAtPanel) gets the panel,
// unless the user chose a resolution for the mode.
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
// Lightweight emulators keep their panel-sized default until a resolution is chosen. val cap = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
val choice = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN && Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode)) 0
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode)) else SessionPrefs.resolutionCap(this, mode)
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt()
else SessionPrefs.resolutionChoice(this, mode, panel) val width = (height * aspect).toInt()
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice) // Odd sizes upset the scaler; both dimensions even is what every mode here would be.
return Pair(width and 1.inv(), height and 1.inv())
} }
/** /**
@@ -1199,15 +1162,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return return
} }
// It stays until the user leaves: a failure read against a timer is a failure not read. // It stays until the user leaves: a failure read against a timer is a failure not read.
val stopped = when (SessionState.mode) { val what = when (SessionState.mode) {
SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "The program"
?.let { getString(R.string.session_ended_named, it) } ?: getString(R.string.session_ended_program) SessionService.MODE_DESKTOP -> "The desktop"
SessionService.MODE_DESKTOP -> getString(R.string.session_ended_desktop) else -> "Steam"
else -> getString(R.string.session_ended_named, "Steam")
} }
loading.showEnded( loading.showEnded(
hint?.text ?: stopped, hint?.text ?: "$what stopped unexpectedly. Share the logs with a bug report, or try again.",
getString(R.string.session_ended_detail, status, SessionState.logFile?.path ?: getString(R.string.session_ended_no_log)), "Exit status $status · ${SessionState.logFile?.path ?: "no log"}",
) )
focusEndedScreen() focusEndedScreen()
} }
@@ -1257,8 +1219,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program) val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true) EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
} else if (enosys >= 8) { } else if (enosys >= 8) {
EndHint(resources.getQuantityString(R.plurals.session_hint_enosys, enosys, enosys, EndHint("The log shows $enosys \"Function not implemented\" errors: proot's seccomp acceleration is failing a helper on this device. " +
getString(R.string.perf_title), getString(R.string.perf_seccomp), getString(R.string.perf_xalia))) "Try Performance \u2192 \"Run proot without seccomp\" (or \"Skip Steam's xalia helper\") and start again.")
} else null } else null
} catch (e: Exception) { } catch (e: Exception) {
null null
@@ -1299,8 +1261,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (drawerOpen) { if (drawerOpen) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
drawerPage = sessionDrawerPages(SessionState.mode == SessionService.MODE_STEAM && secondScreenDisplays.isNotEmpty()) drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else DRAWER_PAGES - 1) % DRAWER_PAGES
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection() releaseDrawerDirection()
} }
return true return true
@@ -1387,10 +1348,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchGenericMotionEvent(event) return super.dispatchGenericMotionEvent(event)
} }
/** With no view focused, captured mouse events skip the root and arrive here as trackball events. */
override fun dispatchTrackballEvent(event: MotionEvent): Boolean =
onCapturedPointer(event) || super.dispatchTrackballEvent(event)
override fun dispatchTouchEvent(event: MotionEvent): Boolean { override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (pipUi) return true if (pipUi) return true
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
@@ -1741,55 +1698,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true return true
} }
/** A physical mouse, not a touchscreen, stylus or the system's own virtual devices. */
private fun mouseAttached(): Boolean = InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
d != null && !d.isVirtual && d.supportsSource(InputDevice.SOURCE_MOUSE)
}
/** Capture the mouse exactly while a program holds a lock and the session has the mouse. */
private fun updatePointerCapture() {
if (!::surfaceView.isInitialized) return
val view = window.decorView
val want = pointerLocked && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !pipUi && mouseAttached()
if (want == view.hasPointerCapture()) return
if (want) view.requestPointerCapture() else view.releasePointerCapture()
}
/**
* A captured mouse: raw motion as relative pointer deltas, buttons and the wheel as on the
* uncaptured path. Anything else (a captured touchpad's absolute fingers) is left alone.
*/
private fun onCapturedPointer(event: MotionEvent): Boolean {
if (!pointerLocked || !event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)) return false
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> {
var dx = event.x
var dy = event.y
for (i in 0 until event.historySize) {
dx += event.getHistoricalX(i)
dy += event.getHistoricalY(i)
}
WaylandCompositor.sendPointerDelta(dx, dy)
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
val button = when (event.actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
else -> PointerGestures.BTN_LEFT
}
WaylandCompositor.nativeSendSceneInput(3, button, if (event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) 1 else 0)
}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) WaylandCompositor.nativeSendSceneInput(4, -Math.round(v), 0)
}
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP -> {} // the BUTTON_* events carry these
else -> return false
}
return true
}
/** The mode decides which controls appear; `droiddeck-osc` in Downloads still overrides. */ /** The mode decides which controls appear; `droiddeck-osc` in Downloads still overrides. */
/** Which controller the session has, so a pad report says what was plugged in and when. */ /** Which controller the session has, so a pad report says what was plugged in and when. */
private fun logInputDevice(what: String, deviceId: Int) { private fun logInputDevice(what: String, deviceId: Int) {
@@ -1806,7 +1714,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
?: SessionPrefs.oscMode(this) ?: SessionPrefs.oscMode(this)
val controls = onScreenControls ?: return val controls = onScreenControls ?: return
if (pipUi) { if (pipUi) {
onScreenButtonsVisible = false
controls.releaseAll() controls.releaseAll()
controls.visibility = View.GONE controls.visibility = View.GONE
return return
@@ -1822,7 +1729,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// started from the rail, or Steam, gets it; the drawer turns it on anywhere. // started from the rail, or Steam, gets it; the drawer turns it on anywhere.
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
} }
onScreenButtonsVisible = show
if (show == (controls.visibility == View.VISIBLE)) return if (show == (controls.visibility == View.VISIBLE)) return
if (!show) controls.releaseAll() if (!show) controls.releaseAll()
controls.visibility = if (show) View.VISIBLE else View.GONE controls.visibility = if (show) View.VISIBLE else View.GONE
@@ -1961,7 +1867,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
controllerSettings = ControllerPrefs.read(this) controllerSettings = ControllerPrefs.read(this)
updateOnScreenControls() updateOnScreenControls()
resumed = true resumed = true
updatePointerCapture()
if (!pipUi) sessionClipboard.start() if (!pipUi) sessionClipboard.start()
updatePadMotion() updatePadMotion()
readPrefs() readPrefs()
@@ -1981,7 +1886,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// A button held when the app goes away would stay held in the ring for the whole session. // A button held when the app goes away would stay held in the ring for the whole session.
onScreenControls?.releaseAll() onScreenControls?.releaseAll()
resumed = false resumed = false
updatePointerCapture()
updatePadMotion() updatePadMotion()
keyboard?.takeIf { it.shown }?.hide() keyboard?.takeIf { it.shown }?.hide()
super.onPause() super.onPause()
@@ -2002,8 +1906,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
goFullscreen() goFullscreen()
refreshClipboard() refreshClipboard()
} }
// Android drops a capture with the focus; a lock still held takes it again on return.
updatePointerCapture()
} }
/** The keyboard/trackpad presentation can own focus instead of the main display. */ /** The keyboard/trackpad presentation can own focus instead of the main display. */
@@ -2031,7 +1933,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) } private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) }
private val firstFrameListener = Runnable { private val firstFrameListener = Runnable {
SessionEvents.firstFrame() SessionEvents.firstFrame()
if (SessionState.mode == SessionService.MODE_STEAM) SteamRepair.clientShown(this)
runOnUiThread { runOnUiThread {
loading.visible = false loading.visible = false
hud.start() hud.start()
@@ -2054,7 +1955,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null
if (SessionState.endListener === endListener) SessionState.endListener = null if (SessionState.endListener === endListener) SessionState.endListener = null
WaylandCompositor.clearFirstFrameListener(firstFrameListener) WaylandCompositor.clearFirstFrameListener(firstFrameListener)
WaylandCompositor.clearPointerLockListener(pointerLockListener)
super.onDestroy() super.onDestroy()
} }
@@ -2119,20 +2019,5 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
/** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */ /** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */
private const val SCALE_FIT = 1 private const val SCALE_FIT = 1
private const val ALIGN_CENTER = 0 private const val ALIGN_CENTER = 0
private val RUNTIME_LINES = PackageLines(
R.string.session_runtime_downloading, R.string.session_runtime_downloading_mb,
R.string.session_runtime_checking, R.string.session_runtime_unpacking,
LoadingState.Topic.RUNTIME, checkingReadable = true,
)
private val DESKTOP_LINES = PackageLines(
R.string.session_desktop_downloading, R.string.session_desktop_downloading_mb,
R.string.session_desktop_checking, R.string.session_desktop_unpacking,
LoadingState.Topic.DESKTOP, checkingReadable = false,
)
private val PROTON_LINES = PackageLines(
R.string.session_proton_downloading, R.string.session_proton_downloading_mb,
R.string.session_proton_checking, R.string.session_proton_unpacking,
LoadingState.Topic.STEAM, checkingReadable = false,
)
} }
} }
@@ -46,7 +46,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
onAllowInstalls = { onAllowInstalls = {
askPermission = false askPermission = false
runCatching { activity.startActivity(SelfInstaller.permissionIntent(activity)) } runCatching { activity.startActivity(SelfInstaller.permissionIntent(activity)) }
.onFailure { error = activity.getString(R.string.upd_unknown_apps_failed); pending = null } .onFailure { error = "Couldn't open Android's \"Install unknown apps\" setting"; pending = null }
}, },
onDismissPermission = { askPermission = false; pending = null }, onDismissPermission = { askPermission = false; pending = null },
) )
@@ -77,7 +77,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
catalog = it catalog = it
follow = AppUpdates.follow(activity, it) follow = AppUpdates.follow(activity, it)
error = null error = null
}.onFailure { if (force) error = activity.getString(R.string.upd_couldnt_check, it.message ?: it.javaClass.simpleName) } }.onFailure { if (force) error = "Couldn't check: ${it.message ?: it.javaClass.simpleName}" }
} }
}, "app-updates").start() }, "app-updates").start()
} }
@@ -90,20 +90,20 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
private fun install(r: AppUpdates.Release) { private fun install(r: AppUpdates.Release) {
if (stage != null) return if (stage != null) return
val apk = r.apk ?: run { error = activity.getString(R.string.upd_no_download); return } val apk = r.apk ?: run { error = "This build has no download for this copy of DroidDeck"; return }
AppUpdates.installBlock(r)?.let { error = it.message(activity); return } AppUpdates.installBlock(r)?.let { error = it; return }
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return } if (SessionState.running) { error = "Stop the running session first, then update"; return }
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return } if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
error = null error = null
stage = activity.getString(R.string.upd_stage_downloading) stage = "Downloading"
percent = 0 percent = 0
Thread({ Thread({
val result = runCatching { val result = runCatching {
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } } val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 } ui.post { stage = "Installing"; percent = -1 }
SelfInstaller.install(activity, file) SelfInstaller.install(activity, file)
} }
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } } result.onFailure { e -> ui.post { stage = null; error = e.message ?: "The update failed" } }
}, "app-update-install").start() }, "app-update-install").start()
} }
@@ -114,14 +114,14 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
PackageInstaller.STATUS_PENDING_USER_ACTION -> { PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java) val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT) else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return } if (confirm == null) { stage = null; error = "Android didn't offer to install the update"; return }
stage = activity.getString(R.string.upd_stage_confirm) stage = "Waiting for you to confirm"
activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
} }
PackageInstaller.STATUS_SUCCESS -> stage = null PackageInstaller.STATUS_SUCCESS -> stage = null
else -> { else -> {
stage = null stage = null
error = SelfInstaller.describeFailure(activity, status, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)) error = SelfInstaller.describeFailure(status, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE))
} }
} }
} }
@@ -1,127 +0,0 @@
package com.droiddeck.launcher.core
import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.os.LocaleList
import java.util.Locale
/**
* The language the app shows itself in.
*
* Nothing chosen (the default) means the system's: Android's own language, or the per-app language
* Android 13+ lets a user set for DroidDeck in its settings, exactly as Android resolves it. Picking
* one in Setup overrides that until the user picks "System default" again. Each activity and service
* applies the choice to its own context ([wrap], [applyTo]), so it works on every Android version
* the app runs on rather than only where the platform's per-app language API exists.
*
* Steam follows the same choice: [SteamLanguage] turns [effective] into the client's language.
*/
object AppLanguage {
/** The stored value meaning "follow the system". */
const val SYSTEM = ""
/** The languages the app ships, as BCP 47 tags, in the order the picker lists them. */
val supported: List<String> = listOf("en", "es", "ja", "ko", "zh-CN", "zh-TW", "zh-HK")
private const val PREFS = "language"
private const val KEY = "app_language"
/** The locale Android gave the process before any choice here was applied. */
@Volatile private var systemLocale: Locale? = null
/** The stored choice: one of [supported], or [SYSTEM]. */
fun chosen(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, SYSTEM)
?.takeIf { it in supported } ?: SYSTEM
fun setChosen(context: Context, tag: String) {
val value = if (tag in supported) tag else SYSTEM
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, value).commit()
val locale = value.takeIf { it.isNotEmpty() }?.let(Locale::forLanguageTag) ?: system(context)
Locale.setDefault(locale)
// Code that reads strings through the application context sees the new language too.
val app = context.applicationContext
@Suppress("DEPRECATION")
app.resources.updateConfiguration(
Configuration(app.resources.configuration).apply { setLocales(LocaleList(locale)) },
app.resources.displayMetrics,
)
}
/** The locale Android chose for the app, ignoring the choice made here. */
fun system(context: Context): Locale =
systemLocale ?: context.resources.configuration.locales[0] ?: Locale.getDefault()
/** The locale the app is shown in: the chosen language, or else the system's. */
fun effective(context: Context): Locale =
chosen(context).takeIf { it.isNotEmpty() }?.let(Locale::forLanguageTag) ?: system(context)
/** Remembers the system's locale; call with the untouched base context, before [wrap]. */
fun noteSystem(base: Context) {
if (systemLocale == null) systemLocale = base.resources.configuration.locales[0]
}
/**
* [base], showing the chosen language: for an Application's or a Service's attachBaseContext.
* Only the locale is overridden, so screen size, density and night mode keep following the
* device as they change.
*/
fun wrap(base: Context): Context {
noteSystem(base)
val tag = chosen(base).ifEmpty { return base }
val locale = Locale.forLanguageTag(tag)
Locale.setDefault(locale)
return base.createConfigurationContext(override(locale))
}
/**
* Applies the chosen language to an activity; call from its attachBaseContext, after super.
* applyOverrideConfiguration keeps the locale through rotation and window resizes, which an
* activity here handles itself rather than being recreated.
*/
fun applyTo(activity: Activity, base: Context) {
noteSystem(base)
val tag = chosen(base).ifEmpty { return }
val locale = Locale.forLanguageTag(tag)
Locale.setDefault(locale)
activity.applyOverrideConfiguration(override(locale))
}
/** Follows a change of the system's language while the process lives (Application.onConfigurationChanged). */
fun systemChanged(config: Configuration) {
config.locales[0]?.let { systemLocale = it }
}
// A new Configuration's fontScale is 1, which as an override would undo the user's font size;
// 0 leaves it undefined, so only the locale is changed.
private fun override(locale: Locale) = Configuration().apply { fontScale = 0f; setLocales(LocaleList(locale)) }
/** Which of the app's languages [locale] reads as, or null when the app does not ship it. */
fun supportedTag(locale: Locale): String? = when (locale.language) {
"en", "es", "ja", "ko" -> locale.language
"zh" -> when {
locale.script == "Hans" -> "zh-CN"
locale.country == "HK" || locale.country == "MO" -> "zh-HK"
locale.script == "Hant" || locale.country == "TW" -> "zh-TW"
else -> "zh-CN"
}
else -> null
}
/** [locale]'s language named in itself, without its region unless the app tells them apart. */
fun displayName(locale: Locale): String =
supportedTag(locale)?.let(::nativeName) ?: locale.getDisplayLanguage(locale).replaceFirstChar { it.titlecase(locale) }
/** A language's name in that language, for the picker: what a reader of it looks for. */
fun nativeName(tag: String): String = when (tag) {
"en" -> "English"
"es" -> "Español"
"ja" -> "日本語"
"ko" -> "한국어"
"zh-CN" -> "简体中文"
"zh-TW" -> "繁體中文(台灣)"
"zh-HK" -> "繁體中文(香港)"
else -> Locale.forLanguageTag(tag).let { it.getDisplayName(it) }
}
}
@@ -1,19 +0,0 @@
package com.droiddeck.launcher.core
import android.content.Context
object AppUiPrefs {
const val DEFAULT_SCALE = 100
val scales = listOf(75, 85, 100, 115, 125, 150)
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
fun scale(context: Context): Int = normalizeScale(
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getInt("scale", DEFAULT_SCALE),
)
fun setScale(context: Context, percent: Int) {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit()
.putInt("scale", normalizeScale(percent)).apply()
}
}
@@ -108,9 +108,9 @@ object DeviceReport {
h("Display") h("Display")
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" }) k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
k("Session refresh", String.format(Locale.US, "%.2f Hz", SessionState.refreshHz)) k("Session refresh", String.format(Locale.US, "%.2f Hz", SessionState.refreshHz))
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context) k("Shape setting", SessionPrefs.shapeMode(context))
k("Resolution (Steam)", SessionPrefs.resolutionChoice(context, SessionService.MODE_STEAM, panelSize)) k("Custom resolution (Steam)", SessionPrefs.customResolution(context, SessionService.MODE_STEAM)?.let { "${it.first}x${it.second}" } ?: "off")
k("Resolution (Desktop)", SessionPrefs.resolutionChoice(context, SessionService.MODE_DESKTOP, panelSize)) k("Custom resolution (Desktop)", SessionPrefs.customResolution(context, SessionService.MODE_DESKTOP)?.let { "${it.first}x${it.second}" } ?: "off")
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
h("Drivers") h("Drivers")
@@ -1,8 +1,6 @@
package com.droiddeck.launcher.core package com.droiddeck.launcher.core
import android.content.Context
import android.os.Build import android.os.Build
import com.droiddeck.launcher.R
import java.io.File import java.io.File
/** /**
@@ -19,8 +17,8 @@ object DeviceSupport {
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
/** The chip as the device names it, for the card that explains the refusal. */ /** The chip as the device names it, for the card that explains the refusal. */
fun gpuName(context: Context): String { fun gpuName(): String {
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
return soc?.let { "$it (${Build.HARDWARE})" } ?: Build.HARDWARE.ifBlank { context.getString(R.string.gpu_this_gpu) } return soc?.let { "$it (${Build.HARDWARE})" } ?: Build.HARDWARE.ifBlank { "this GPU" }
} }
} }
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.core
import android.content.Context import android.content.Context
import android.os.Build import android.os.Build
import android.provider.Settings import android.provider.Settings
import com.droiddeck.launcher.R
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */ /** Android's phantom process monitor can kill the many child processes used by a Steam session. */
enum class PhantomProcessStatus { enum class PhantomProcessStatus {
@@ -99,30 +98,29 @@ object PhantomProcessLimit {
fun blocksSteam(status: PhantomProcessStatus): Boolean = fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) { fun title(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> R.string.phantom_title_on PhantomProcessStatus.ENABLED -> "Child-process limit is on"
PhantomProcessStatus.UNSET -> R.string.phantom_title_unset PhantomProcessStatus.UNSET -> "Child-process limit is unset"
PhantomProcessStatus.UNREADABLE -> R.string.phantom_title_unreadable PhantomProcessStatus.UNREADABLE -> "Child-process limit could not be checked"
PhantomProcessStatus.DISABLED -> R.string.phantom_title_off PhantomProcessStatus.DISABLED -> "Child-process limit is off"
PhantomProcessStatus.NOT_APPLICABLE -> R.string.phantom_title_not_required PhantomProcessStatus.NOT_APPLICABLE -> "Child-process limit not required"
})
fun instructions(context: Context, status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE ->
context.getString(R.string.phantom_instructions_fix, fixSentence(context))
PhantomProcessStatus.DISABLED -> context.getString(R.string.phantom_instructions_off)
PhantomProcessStatus.NOT_APPLICABLE -> context.getString(R.string.phantom_instructions_not_applicable)
} }
fun gateInstructions(context: Context, status: PhantomProcessStatus): String = when (status) { fun instructions(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence(context) PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence() + " If that is not possible, connect this device to a computer with ADB and run the command below. Return here and check again."
else -> instructions(context, status) PhantomProcessStatus.DISABLED -> "Steam sessions can start."
PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit."
} }
fun fixSentence(context: Context, sdk: Int = Build.VERSION.SDK_INT): String = fun gateInstructions(status: PhantomProcessStatus): String = when (status) {
context.getString(if (hasDeveloperToggle(sdk)) R.string.phantom_fix_toggle else R.string.phantom_fix_no_toggle) PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence()
else -> instructions(status)
}
fun fixSentence(sdk: Int = Build.VERSION.SDK_INT): String =
if (hasDeveloperToggle(sdk)) "Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards."
else "This Android version has no switch for it. Use Wireless debugging to change it from this device."
/** English: for the device report. */
fun reportValue(status: PhantomProcessStatus): String = when (status) { fun reportValue(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)" PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)" PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.core
import android.content.Context import android.content.Context
import android.net.nsd.NsdManager import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo import android.net.nsd.NsdServiceInfo
import com.droiddeck.launcher.R
import com.flyfishxu.kadb.Kadb import com.flyfishxu.kadb.Kadb
import com.flyfishxu.kadb.cert.KadbCert import com.flyfishxu.kadb.cert.KadbCert
import java.io.File import java.io.File
@@ -38,21 +37,21 @@ object WirelessAdbFix {
val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650)) val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650))
KadbCert.set(identity.first, identity.second) KadbCert.set(identity.first, identity.second)
writeAtomically(context, cert, identity.first) writeAtomically(cert, identity.first)
writeAtomically(context, key, identity.second) writeAtomically(key, identity.second)
} }
private fun writeAtomically(context: Context, destination: File, contents: ByteArray) { private fun writeAtomically(destination: File, contents: ByteArray) {
val temporary = File(destination.parentFile, "${destination.name}.tmp") val temporary = File(destination.parentFile, "${destination.name}.tmp")
temporary.writeBytes(contents) temporary.writeBytes(contents)
check(temporary.renameTo(destination)) { context.getString(R.string.adbfix_save_failed) } check(temporary.renameTo(destination)) { "Could not save Wireless debugging identity" }
} }
suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) { suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) {
loadOrCreateIdentity(context.applicationContext) loadOrCreateIdentity(context.applicationContext)
Kadb.pair(host, port, pairingCode, "DroidDeck") Kadb.pair(host, port, pairingCode, "DroidDeck")
writeAtomically(context, File(context.noBackupFilesDir, HOST_FILE), host.toByteArray()) writeAtomically(File(context.noBackupFilesDir, HOST_FILE), host.toByteArray())
writeAtomically(context, File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0)) writeAtomically(File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
} }
private fun savedConnection(context: Context): SavedConnection? { private fun savedConnection(context: Context): SavedConnection? {
@@ -74,7 +73,6 @@ object WirelessAdbFix {
private fun saveConnection(context: Context, host: String, port: Int) { private fun saveConnection(context: Context, host: String, port: Int) {
writeAtomically( writeAtomically(
context,
File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE), File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE),
"$host\n$port".toByteArray(), "$host\n$port".toByteArray(),
) )
@@ -173,11 +171,11 @@ object WirelessAdbFix {
Kadb.create(host, port).use { adb -> Kadb.create(host, port).use { adb ->
PhantomProcessLimit.shellCommands(enabled).forEach { command -> PhantomProcessLimit.shellCommands(enabled).forEach { command ->
val change = adb.shell(command) val change = adb.shell(command)
check(change.exitCode == 0) { change.allOutput.ifBlank { context.getString(R.string.adbfix_command_failed, change.exitCode) } } check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
} }
val result = adb.shell(PhantomProcessLimit.verifyCommand()) val result = adb.shell(PhantomProcessLimit.verifyCommand())
check(result.exitCode == 0 && PhantomProcessLimit.verified(result.output, enabled)) { check(result.exitCode == 0 && PhantomProcessLimit.verified(result.output, enabled)) {
context.getString(R.string.adbfix_not_confirmed, result.allOutput.trim()) "Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}"
} }
} }
if (PhantomProcessLimit.usesDeviceConfig()) PhantomProcessLimit.rememberAndroid12(context, !enabled) if (PhantomProcessLimit.usesDeviceConfig()) PhantomProcessLimit.rememberAndroid12(context, !enabled)
@@ -188,7 +186,7 @@ object WirelessAdbFix {
fun setUsingSavedPairing(context: Context, enabled: Boolean) { fun setUsingSavedPairing(context: Context, enabled: Boolean) {
val appContext = context.applicationContext val appContext = context.applicationContext
val saved = savedConnection(appContext) val saved = savedConnection(appContext)
?: error(appContext.getString(R.string.adbfix_no_pairing)) ?: error("No Wireless debugging pairing is saved")
val cachedPort = saved.port val cachedPort = saved.port
if (cachedPort != null) { if (cachedPort != null) {
val cachedResult = runCatching { val cachedResult = runCatching {
@@ -203,7 +201,7 @@ object WirelessAdbFix {
} }
} else { } else {
val discoveredPort = findConnectPort(appContext, saved.host) val discoveredPort = findConnectPort(appContext, saved.host)
?: error(appContext.getString(R.string.adbfix_enter_address)) ?: error("Enter the current Wireless debugging IP address & Port")
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled) setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
} }
} }
@@ -20,9 +20,6 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
class WirelessAdbPairingService : Service() { class WirelessAdbPairingService : Service() {
override fun attachBaseContext(newBase: android.content.Context) =
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(newBase))
sealed interface Stage { sealed interface Stage {
data object Idle : Stage data object Idle : Stage
data object Waiting : Stage data object Waiting : Stage
@@ -38,7 +35,7 @@ class WirelessAdbPairingService : Service() {
private var pairingHost: String? = null private var pairingHost: String? = null
private var pairingPort: Int? = null private var pairingPort: Int? = null
@Volatile private var working = false @Volatile private var working = false
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) } private val timeout = Runnable { finish(Stage.Failed("Timed out waiting for the pairing pop-up. Try again from DroidDeck.")) }
override fun onBind(intent: Intent?): IBinder? = null override fun onBind(intent: Intent?): IBinder? = null
@@ -78,13 +75,13 @@ class WirelessAdbPairingService : Service() {
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
override fun onDiscoveryStopped(serviceType: String) = Unit override fun onDiscoveryStopped(serviceType: String) = Unit
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
main.post { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed_code, errorCode))) } main.post { finish(Stage.Failed("Could not look for the pairing pop-up ($errorCode). Check that Wi-Fi is on.")) }
} }
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
} }
runCatching { manager.discoverServices("$PAIRING_TYPE.", NsdManager.PROTOCOL_DNS_SD, listener) } runCatching { manager.discoverServices("$PAIRING_TYPE.", NsdManager.PROTOCOL_DNS_SD, listener) }
.onSuccess { nsd = manager; discovery = listener } .onSuccess { nsd = manager; discovery = listener }
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) } .onFailure { finish(Stage.Failed("Could not look for the pairing pop-up: ${it.localizedMessage}")) }
} }
private fun resolveListener() = object : NsdManager.ResolveListener { private fun resolveListener() = object : NsdManager.ResolveListener {
@@ -110,34 +107,34 @@ class WirelessAdbPairingService : Service() {
return return
} }
if (code.length != 6) { if (code.length != 6) {
show(Stage.CodeNeeded(getString(R.string.adbpair_six_digits))) show(Stage.CodeNeeded("Enter all 6 digits of the code"))
return return
} }
working = true working = true
show(Stage.Working(getString(R.string.adbpair_pairing))) show(Stage.Working("Pairing…"))
Thread({ Thread({
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } } val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
if (paired.isFailure) { if (paired.isFailure) {
main.post { main.post {
working = false working = false
pairingPort = null pairingPort = null
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected))) show(Stage.CodeNeeded("That code didn't work. Open the pairing pop-up again and enter its new code."))
} }
return@Thread return@Thread
} }
main.post { main.post {
stopDiscovery() stopDiscovery()
show(Stage.Working(getString(R.string.adbpair_connecting))) show(Stage.Working("Paired. Connecting…"))
} }
val result = runCatching { val result = runCatching {
val connectPort = WirelessAdbFix.localConnectPort(this) val connectPort = WirelessAdbFix.localConnectPort(this)
?: error(getString(R.string.adbpair_port_not_found)) ?: error("Paired, but the Wireless debugging port was not found. Keep Wireless debugging on and try again.")
main.post { show(Stage.Working(getString(R.string.adbpair_applying))) } main.post { show(Stage.Working("Applying the setting…")) }
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false) WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
} }
main.post { main.post {
working = false working = false
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done) finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: "Wireless debugging command failed") } ?: Stage.Done)
} }
}, "wireless-adb-pairing").start() }, "wireless-adb-pairing").start()
} }
@@ -177,9 +174,9 @@ class WirelessAdbPairingService : Service() {
private fun notification(stage: Stage): Notification { private fun notification(stage: Stage): Notification {
val manager = getSystemService(NotificationManager::class.java) val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.adbpair_channel_name), manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Wireless debugging setup",
NotificationManager.IMPORTANCE_HIGH).apply { NotificationManager.IMPORTANCE_HIGH).apply {
description = getString(R.string.adbpair_channel_description) description = "Asks for the Wireless debugging pairing code while Settings is open"
setShowBadge(false) setShowBadge(false)
setSound(null, null) setSound(null, null)
enableVibration(false) enableVibration(false)
@@ -196,40 +193,41 @@ class WirelessAdbPairingService : Service() {
.setCategory(Notification.CATEGORY_STATUS) .setCategory(Notification.CATEGORY_STATUS)
when (stage) { when (stage) {
Stage.Waiting, Stage.Idle -> builder Stage.Waiting, Stage.Idle -> builder
.setContentTitle(getString(R.string.adbpair_title_pair)) .setContentTitle("Pair Wireless debugging")
.setContentText(getString(R.string.adbpair_waiting_text)) .setContentText("Turn on Wireless debugging, then tap “Pair device with pairing code”.")
.setStyle(Notification.BigTextStyle().bigText(getString(R.string.adbpair_waiting_long))) .setStyle(Notification.BigTextStyle().bigText(
"Turn on Wireless debugging, then tap “Pair device with pairing code”. Stay in Settings: the code goes in this notification."))
.setOngoing(true) .setOngoing(true)
.setOnlyAlertOnce(true) .setOnlyAlertOnce(true)
.addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build()) .addAction(Notification.Action.Builder(null, "Cancel", cancel).build())
is Stage.CodeNeeded -> { is Stage.CodeNeeded -> {
val reply = PendingIntent.getService(this, 2, val reply = PendingIntent.getService(this, 2,
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CODE), Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CODE),
if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
else PendingIntent.FLAG_UPDATE_CURRENT) else PendingIntent.FLAG_UPDATE_CURRENT)
val input = RemoteInput.Builder(KEY_CODE).setLabel(getString(R.string.adbpair_code_label)).build() val input = RemoteInput.Builder(KEY_CODE).setLabel("6-digit pairing code").build()
val text = stage.error ?: getString(R.string.adbpair_code_hint) val text = stage.error ?: "Tap Enter code and type the 6 digits shown in Settings."
builder builder
.setContentTitle(getString(if (stage.error == null) R.string.adbpair_title_code else R.string.adbpair_title_retry)) .setContentTitle(if (stage.error == null) "Enter the Wi-Fi pairing code" else "Try the code again")
.setContentText(text) .setContentText(text)
.setStyle(Notification.BigTextStyle().bigText(text)) .setStyle(Notification.BigTextStyle().bigText(text))
.setOngoing(true) .setOngoing(true)
.addAction(Notification.Action.Builder(null, getString(R.string.adbpair_enter_code), reply).addRemoteInput(input).build()) .addAction(Notification.Action.Builder(null, "Enter code", reply).addRemoteInput(input).build())
.addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build()) .addAction(Notification.Action.Builder(null, "Cancel", cancel).build())
} }
is Stage.Working -> builder is Stage.Working -> builder
.setContentTitle(getString(R.string.adbpair_title_working)) .setContentTitle("Setting up Steam")
.setContentText(stage.step) .setContentText(stage.step)
.setProgress(0, 0, true) .setProgress(0, 0, true)
.setOngoing(true) .setOngoing(true)
.setOnlyAlertOnce(true) .setOnlyAlertOnce(true)
Stage.Done -> builder Stage.Done -> builder
.setContentTitle(getString(R.string.adbpair_title_done)) .setContentTitle("Steam is ready")
.setContentText(getString(R.string.adbpair_done_text)) .setContentText("Tap to go back to DroidDeck. You can turn Wireless debugging off now.")
.setStyle(Notification.BigTextStyle().bigText(getString(R.string.adbpair_done_text))) .setStyle(Notification.BigTextStyle().bigText("Tap to go back to DroidDeck. You can turn Wireless debugging off now."))
.setAutoCancel(true) .setAutoCancel(true)
is Stage.Failed -> builder is Stage.Failed -> builder
.setContentTitle(getString(R.string.adbpair_title_failed)) .setContentTitle("Wireless debugging setup stopped")
.setContentText(stage.error) .setContentText(stage.error)
.setStyle(Notification.BigTextStyle().bigText(stage.error)) .setStyle(Notification.BigTextStyle().bigText(stage.error))
.setAutoCancel(true) .setAutoCancel(true)
@@ -56,8 +56,6 @@ data class RailItem(
val selected: Boolean, val selected: Boolean,
/** >0 shows a small accent count badge on the item's icon (expanded and collapsed). */ /** >0 shows a small accent count badge on the item's icon (expanded and collapsed). */
val badge: Int = 0, val badge: Int = 0,
/** The under-icon label when the rail is collapsed, for names too long to fit; null derives one. */
val shortLabel: String? = null,
// onClick stays LAST so existing call sites can pass it as a trailing lambda; badge is an // onClick stays LAST so existing call sites can pass it as a trailing lambda; badge is an
// optional named param before it (default 0). // optional named param before it (default 0).
val onClick: () -> Unit, val onClick: () -> Unit,
@@ -75,6 +73,7 @@ private fun collapsedLabel(label: String): String {
when (label) { when (label) {
"ENVIROMENT" -> return "ENVIRON" // the app's existing (mis)spelling, kept uppercase "ENVIROMENT" -> return "ENVIRON" // the app's existing (mis)spelling, kept uppercase
"WIN COMPONENTS" -> return "WIN COMP" "WIN COMPONENTS" -> return "WIN COMP"
"Downloads" -> return "Downlds"
} }
if (label.contains(' ')) return label // multi-word → wraps to 2 lines if (label.contains(' ')) return label // multi-word → wraps to 2 lines
return if (label.length > 9) label.take(8) + "…" else label return if (label.length > 9) label.take(8) + "…" else label
@@ -318,7 +317,7 @@ fun CollapsibleRail(
RailItemIcon(item, iconTint) RailItemIcon(item, iconTint)
Spacer(Modifier.height(2.dp)) Spacer(Modifier.height(2.dp))
Text( Text(
item.shortLabel ?: collapsedLabel(item.label), collapsedLabel(item.label),
color = labelColor, color = labelColor,
fontSize = 7.5.sp, fontSize = 7.5.sp,
lineHeight = 8.5.sp, lineHeight = 8.5.sp,
@@ -15,11 +15,6 @@ import java.io.File
/** The File Manager as a screen of its own, from the Files tile on the main screen. */ /** The File Manager as a screen of its own, from the Files tile on the main screen. */
class FileManagerActivity : ComponentActivity() { class FileManagerActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
@@ -27,7 +22,7 @@ class FileManagerActivity : ComponentActivity() {
} }
val initialDir = intent.getStringExtra(EXTRA_START_DIR)?.let(::File) val initialDir = intent.getStringExtra(EXTRA_START_DIR)?.let(::File)
setContent { setContent {
DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) { DroidDeckTheme {
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) { Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
FileManagerScreen(initialDir = initialDir) FileManagerScreen(initialDir = initialDir)
} }
@@ -61,7 +61,6 @@ import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import coil.compose.AsyncImage import coil.compose.AsyncImage
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
@@ -108,7 +107,7 @@ private fun FileContextMenuItems(
) { ) {
val isDir = file.isDirectory val isDir = file.isDirectory
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.fm_select)) }, text = { Text("Select") },
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) }, leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onSelect() }, onClick = { onDismissMenu(); onSelect() },
) )
@@ -116,7 +115,7 @@ private fun FileContextMenuItems(
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config // Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu. // files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.fm_properties)) }, text = { Text("Properties") },
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) }, leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onProperties() }, onClick = { onDismissMenu(); onProperties() },
) )
@@ -124,7 +123,7 @@ private fun FileContextMenuItems(
// Favorites are directories - only folders get the pin toggle. // Favorites are directories - only folders get the pin toggle.
if (isDir) { if (isDir) {
DropdownMenuItem( DropdownMenuItem(
text = { Text(if (isFavorite) stringResource(R.string.fm_favorite_remove) else stringResource(R.string.fm_favorite_add)) }, text = { Text(if (isFavorite) "Remove from Favorites" else "Add to Favorites") },
leadingIcon = { leadingIcon = {
Icon( Icon(
if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder, if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder,
@@ -137,25 +136,25 @@ private fun FileContextMenuItems(
MenuItemDivider() MenuItemDivider()
} }
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.fm_rename)) }, text = { Text("Rename") },
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) }, leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onRename() }, onClick = { onDismissMenu(); onRename() },
) )
MenuItemDivider() MenuItemDivider()
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.fm_copy)) }, text = { Text("Copy") },
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) }, leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onCopy() }, onClick = { onDismissMenu(); onCopy() },
) )
MenuItemDivider() MenuItemDivider()
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.fm_cut)) }, text = { Text("Cut") },
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) }, leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onCut() }, onClick = { onDismissMenu(); onCut() },
) )
MenuItemDivider() MenuItemDivider()
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.common_delete)) }, text = { Text("Delete") },
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) }, leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onDelete() }, onClick = { onDismissMenu(); onDelete() },
) )
@@ -185,7 +184,6 @@ internal fun FileItemRow(
onProperties: () -> Unit = {}, onProperties: () -> Unit = {},
) { ) {
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) } val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
val context = LocalContext.current
val isDir = file.isDirectory val isDir = file.isDirectory
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") } val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
// Image files show a real thumbnail instead of the generic file icon (handy when picking a // Image files show a real thumbnail instead of the generic file icon (handy when picking a
@@ -278,7 +276,7 @@ internal fun FileItemRow(
) )
Text( Text(
text = buildString { text = buildString {
if (!isDir) append(FileOps.formatBytes(context, file.length())).append(" \u2022 ") if (!isDir) append(FileOps.formatBytes(file.length())).append(" \u2022 ")
append(dateFormat.format(Date(file.lastModified()))) append(dateFormat.format(Date(file.lastModified())))
}, },
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
@@ -287,7 +285,7 @@ internal fun FileItemRow(
} }
if (showActions) Box { if (showActions) Box {
IconButton(onClick = onMenu) { IconButton(onClick = onMenu) {
Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp)) Icon(Icons.Filled.MoreVert, "Actions", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
} }
DropdownMenu( DropdownMenu(
expanded = menuExpanded, expanded = menuExpanded,
@@ -340,7 +338,7 @@ internal fun FavoritesList(
.padding(horizontal = 16.dp, vertical = 8.dp), .padding(horizontal = 16.dp, vertical = 8.dp),
) { ) {
Text( Text(
text = stringResource(R.string.fm_favorites), text = "Favorites",
color = MaterialTheme.colorScheme.onBackground, color = MaterialTheme.colorScheme.onBackground,
fontSize = 15.sp, fontSize = 15.sp,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
@@ -353,7 +351,7 @@ internal fun FavoritesList(
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp)) Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(6.dp)) Spacer(Modifier.width(6.dp))
Text( Text(
text = stringResource(R.string.fm_pin_current), text = "Pin current folder",
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp, fontSize = 13.sp,
) )
@@ -368,7 +366,7 @@ internal fun FavoritesList(
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
Text( Text(
text = stringResource(R.string.fm_no_favorites), text = "No favorites yet - pin a folder with its ⋮ menu to jump back here fast.",
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 13.sp, fontSize = 13.sp,
modifier = Modifier.padding(horizontal = 32.dp), modifier = Modifier.padding(horizontal = 32.dp),
@@ -433,7 +431,7 @@ private fun FavoriteCard(
// Origin line: coloured drive badge + source description. // Origin line: coloured drive badge + source description.
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Text( Text(
text = stringResource(loc.driveLabel), text = loc.driveLabel,
color = badgeFg, color = badgeFg,
fontSize = 11.sp, fontSize = 11.sp,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
@@ -445,9 +443,9 @@ private fun FavoriteCard(
Spacer(Modifier.width(6.dp)) Spacer(Modifier.width(6.dp))
Text( Text(
text = when (loc.storage) { text = when (loc.storage) {
FavStorage.INTERNAL -> stringResource(R.string.games_internal) FavStorage.INTERNAL -> "Internal storage"
FavStorage.SD -> stringResource(R.string.fm_drive_sd) FavStorage.SD -> "SD card"
FavStorage.OTHER -> stringResource(R.string.fm_drive_storage) FavStorage.OTHER -> "Storage"
}, },
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp, fontSize = 12.sp,
@@ -466,7 +464,7 @@ private fun FavoriteCard(
IconButton(onClick = onUnpin) { IconButton(onClick = onUnpin) {
Icon( Icon(
Icons.Filled.Star, Icons.Filled.Star,
contentDescription = stringResource(R.string.fm_unpin_favorite), contentDescription = "Remove from favorites",
tint = MaterialTheme.colorScheme.primary, tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(22.dp), modifier = Modifier.size(22.dp),
) )
@@ -8,8 +8,6 @@ import androidx.compose.material.icons.filled.Image
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import java.io.File import java.io.File
// The File Manager's non-UI helpers: sorting, paths, conflict choices and favourite locations. // The File Manager's non-UI helpers: sorting, paths, conflict choices and favourite locations.
@@ -79,7 +77,7 @@ enum class FavStorage { INTERNAL, SD, OTHER }
data class FavLocation( data class FavLocation(
val storage: FavStorage, val storage: FavStorage,
@StringRes val driveLabel: Int, // Internal, SD card, or Storage val driveLabel: String, // "Internal", "SD card", or "Storage"
val displayPath: String // the unix absolute path val displayPath: String // the unix absolute path
) )
@@ -89,15 +87,15 @@ fun describeLocation(file: File): FavLocation {
val internal = "/storage/emulated/0" val internal = "/storage/emulated/0"
if (abs == internal || abs.startsWith("$internal/")) { if (abs == internal || abs.startsWith("$internal/")) {
return FavLocation(FavStorage.INTERNAL, R.string.fm_drive_internal, abs) return FavLocation(FavStorage.INTERNAL, "Internal", abs)
} }
if (abs.startsWith("/storage/")) { if (abs.startsWith("/storage/")) {
val name = abs.removePrefix("/storage/").substringBefore('/') val name = abs.removePrefix("/storage/").substringBefore('/')
if (name.isNotEmpty() && name != "emulated" && name != "self") { if (name.isNotEmpty() && name != "emulated" && name != "self") {
return FavLocation(FavStorage.SD, R.string.fm_drive_sd, abs) return FavLocation(FavStorage.SD, "SD card", abs)
} }
} }
return FavLocation(FavStorage.OTHER, R.string.fm_drive_storage, abs) return FavLocation(FavStorage.OTHER, "Storage", abs)
} }
@@ -76,9 +76,6 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleEventObserver
@@ -264,11 +261,11 @@ fun FileManagerScreen(
fun performDelete(file: File) { fun performDelete(file: File) {
scope.launch { scope.launch {
isOperationRunning = true isOperationRunning = true
operationLabel = context.getString(R.string.fm_op_deleting) operationLabel = "Deleting..."
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) } val ok = withContext(Dispatchers.IO) { FileOps.delete(file) }
isOperationRunning = false isOperationRunning = false
loadDirectory(currentDir, resetScroll = false) loadDirectory(currentDir, resetScroll = false)
if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show() if (!ok) Toast.makeText(context, "Delete failed", Toast.LENGTH_SHORT).show()
} }
} }
@@ -291,7 +288,7 @@ fun FileManagerScreen(
operationJob = scope.launch { operationJob = scope.launch {
operationProgress = 0f operationProgress = 0f
operationDeterminate = true operationDeterminate = true
operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying) operationLabel = if (cut) "Moving..." else "Copying..."
isOperationRunning = true isOperationRunning = true
var applyToAll: ConflictChoice? = null var applyToAll: ConflictChoice? = null
@@ -327,10 +324,10 @@ fun FileManagerScreen(
} }
// Progress is per item; with a batch the label carries the overall position. // Progress is per item; with a batch the label carries the overall position.
operationLabel = if (sources.size > 1) { operationLabel = buildString {
context.getString(if (cut) R.string.fm_op_moving_batch else R.string.fm_op_copying_batch, done + 1, sources.size, src.name) append(if (cut) "Moving" else "Copying")
} else { if (sources.size > 1) append(" ${done + 1}/${sources.size}")
context.getString(if (cut) R.string.fm_op_moving_item else R.string.fm_op_copying_item, src.name) append(" - ").append(src.name)
} }
var lastPct = -1 var lastPct = -1
val onProgress = FileOps.ProgressCallback { copied, total -> val onProgress = FileOps.ProgressCallback { copied, total ->
@@ -358,9 +355,9 @@ fun FileManagerScreen(
loadDirectory(currentDir, resetScroll = false) loadDirectory(currentDir, resetScroll = false)
val message = when { val message = when {
failed > 0 -> context.getString(R.string.fm_paste_failed, done, failed) failed > 0 -> "$done done, $failed failed"
skipped > 0 -> context.getString(R.string.fm_paste_skipped, done, skipped) skipped > 0 -> "$done done, $skipped skipped"
sources.size > 1 -> context.resources.getQuantityString(if (cut) R.plurals.fm_paste_moved else R.plurals.fm_paste_copied, done, done) sources.size > 1 -> "$done items ${if (cut) "moved" else "copied"}"
else -> null else -> null
} }
if (message != null) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() if (message != null) Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
@@ -370,32 +367,32 @@ fun FileManagerScreen(
fun performRename(file: File, newName: String) { fun performRename(file: File, newName: String) {
val target = File(file.parentFile, newName) val target = File(file.parentFile, newName)
if (target.exists()) { if (target.exists()) {
Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show() Toast.makeText(context, "\"$newName\" already exists", Toast.LENGTH_SHORT).show()
return return
} }
scope.launch { scope.launch {
isOperationRunning = true isOperationRunning = true
operationLabel = context.getString(R.string.fm_op_renaming) operationLabel = "Renaming..."
val ok = withContext(Dispatchers.IO) { file.renameTo(target) } val ok = withContext(Dispatchers.IO) { file.renameTo(target) }
isOperationRunning = false isOperationRunning = false
loadDirectory(currentDir, resetScroll = false) loadDirectory(currentDir, resetScroll = false)
if (!ok) Toast.makeText(context, R.string.fm_rename_failed, Toast.LENGTH_SHORT).show() if (!ok) Toast.makeText(context, "Rename failed", Toast.LENGTH_SHORT).show()
} }
} }
fun createFolder(parent: File, name: String) { fun createFolder(parent: File, name: String) {
val target = File(parent, name) val target = File(parent, name)
if (target.exists()) { if (target.exists()) {
Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show() Toast.makeText(context, "\"$name\" already exists", Toast.LENGTH_SHORT).show()
return return
} }
scope.launch { scope.launch {
isOperationRunning = true isOperationRunning = true
operationLabel = context.getString(R.string.fm_op_creating_folder) operationLabel = "Creating folder..."
val ok = withContext(Dispatchers.IO) { target.mkdirs() } val ok = withContext(Dispatchers.IO) { target.mkdirs() }
isOperationRunning = false isOperationRunning = false
loadDirectory(currentDir, resetScroll = false) loadDirectory(currentDir, resetScroll = false)
if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show() if (!ok) Toast.makeText(context, "Could not create folder", Toast.LENGTH_SHORT).show()
} }
} }
@@ -419,12 +416,12 @@ fun FileManagerScreen(
var folderName by remember { mutableStateOf("") } var folderName by remember { mutableStateOf("") }
OutlinedAlertDialog( OutlinedAlertDialog(
onDismissRequest = { showNewFolderDialog = false }, onDismissRequest = { showNewFolderDialog = false },
title = { Text(stringResource(R.string.fm_new_folder)) }, title = { Text("New Folder") },
text = { text = {
OutlinedTextField( OutlinedTextField(
value = folderName, value = folderName,
onValueChange = { folderName = it }, onValueChange = { folderName = it },
label = { Text(stringResource(R.string.fm_folder_name)) }, label = { Text("Folder name") },
singleLine = true, singleLine = true,
) )
}, },
@@ -432,9 +429,9 @@ fun FileManagerScreen(
TextButton(onClick = { TextButton(onClick = {
showNewFolderDialog = false showNewFolderDialog = false
if (folderName.isNotBlank()) createFolder(currentDir, folderName) if (folderName.isNotBlank()) createFolder(currentDir, folderName)
}) { Text(stringResource(R.string.fm_create)) } }) { Text("Create") }
}, },
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } }, dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text("Cancel") } },
) )
} }
@@ -442,12 +439,12 @@ fun FileManagerScreen(
var newName by remember(renameTarget) { mutableStateOf(renameTarget?.name ?: "") } var newName by remember(renameTarget) { mutableStateOf(renameTarget?.name ?: "") }
OutlinedAlertDialog( OutlinedAlertDialog(
onDismissRequest = { renameTarget = null }, onDismissRequest = { renameTarget = null },
title = { Text(stringResource(R.string.fm_rename)) }, title = { Text("Rename") },
text = { text = {
OutlinedTextField( OutlinedTextField(
value = newName, value = newName,
onValueChange = { newName = it }, onValueChange = { newName = it },
label = { Text(stringResource(R.string.fm_new_name)) }, label = { Text("New name") },
singleLine = true, singleLine = true,
) )
}, },
@@ -456,9 +453,9 @@ fun FileManagerScreen(
val file = renameTarget val file = renameTarget
renameTarget = null renameTarget = null
if (file != null && newName.isNotBlank()) performRename(file, newName) if (file != null && newName.isNotBlank()) performRename(file, newName)
}) { Text(stringResource(R.string.fm_rename)) } }) { Text("Rename") }
}, },
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } }, dismissButton = { TextButton(onClick = { renameTarget = null }) { Text("Cancel") } },
) )
} }
@@ -476,15 +473,15 @@ fun FileManagerScreen(
val file = selectedEntry ?: return val file = selectedEntry ?: return
OutlinedAlertDialog( OutlinedAlertDialog(
onDismissRequest = { selectedEntry = null }, onDismissRequest = { selectedEntry = null },
title = { Text(stringResource(R.string.fm_delete_title)) }, title = { Text("Delete?") },
text = { Text(stringResource(R.string.fm_delete_text, file.name)) }, text = { Text("Delete \"${file.name}\" permanently?") },
confirmButton = { confirmButton = {
TextButton(onClick = { TextButton(onClick = {
selectedEntry = null selectedEntry = null
performDelete(file) performDelete(file)
}) { Text(stringResource(R.string.common_delete)) } }) { Text("Delete") }
}, },
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } }, dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text("Cancel") } },
) )
} }
@@ -492,10 +489,10 @@ fun FileManagerScreen(
val victims = pendingBulkDelete val victims = pendingBulkDelete
OutlinedAlertDialog( OutlinedAlertDialog(
onDismissRequest = { pendingBulkDelete = emptyList() }, onDismissRequest = { pendingBulkDelete = emptyList() },
title = { Text(pluralStringResource(R.plurals.fm_delete_items_title, victims.size, victims.size)) }, title = { Text("Delete ${victims.size} item${if (victims.size == 1) "" else "s"}?") },
text = { text = {
Column { Column {
Text(stringResource(R.string.fm_cannot_undo)) Text("This can't be undone.")
Spacer(Modifier.height(6.dp)) Spacer(Modifier.height(6.dp))
// Name a few so an accidental Select-All is obvious before it's too late. // Name a few so an accidental Select-All is obvious before it's too late.
victims.take(5).forEach { victims.take(5).forEach {
@@ -503,7 +500,7 @@ fun FileManagerScreen(
} }
if (victims.size > 5) { if (victims.size > 5) {
Text( Text(
pluralStringResource(R.plurals.fm_and_more, victims.size - 5, victims.size - 5), "…and ${victims.size - 5} more",
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp, fontSize = 12.sp,
) )
@@ -519,19 +516,19 @@ fun FileManagerScreen(
isOperationRunning = true isOperationRunning = true
var failed = 0 var failed = 0
victims.forEachIndexed { i, f -> victims.forEachIndexed { i, f ->
operationLabel = context.getString(R.string.fm_op_deleting_batch, i + 1, victims.size, f.name) operationLabel = "Deleting ${i + 1}/${victims.size} - ${f.name}"
if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++ if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++
} }
isOperationRunning = false isOperationRunning = false
operationJob = null operationJob = null
loadDirectory(currentDir, resetScroll = false) loadDirectory(currentDir, resetScroll = false)
if (failed > 0) { if (failed > 0) {
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show() Toast.makeText(context, "$failed couldn't be deleted", Toast.LENGTH_SHORT).show()
} }
} }
}) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) } }) { Text("Delete", color = MaterialTheme.colorScheme.error) }
}, },
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } }, dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text("Cancel") } },
) )
} }
@@ -540,12 +537,12 @@ fun FileManagerScreen(
val isDir = conflict.isDirectory val isDir = conflict.isDirectory
OutlinedAlertDialog( OutlinedAlertDialog(
onDismissRequest = { pendingConflict = null }, onDismissRequest = { pendingConflict = null },
title = { Text(stringResource(R.string.fm_already_exists, conflict.name)) }, title = { Text("\"${conflict.name}\" already exists") },
text = { text = {
Column { Column {
Text( Text(
if (isDir) stringResource(R.string.fm_conflict_merge_hint) if (isDir) "Merge adds and replaces files inside the existing folder."
else stringResource(R.string.fm_conflict_overwrite_hint), else "Overwrite replaces the existing file.",
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp, fontSize = 12.sp,
) )
@@ -556,15 +553,15 @@ fun FileManagerScreen(
checked = conflictApplyToAll, checked = conflictApplyToAll,
onCheckedChange = { conflictApplyToAll = it }, onCheckedChange = { conflictApplyToAll = it },
) )
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp) Text("Apply to all conflicts", fontSize = 12.sp)
} }
} }
Spacer(Modifier.height(4.dp)) Spacer(Modifier.height(4.dp))
listOf( listOf(
(if (isDir) ConflictChoice.MERGE else ConflictChoice.OVERWRITE) to (if (isDir) ConflictChoice.MERGE else ConflictChoice.OVERWRITE) to
(if (isDir) stringResource(R.string.fm_conflict_merge) else stringResource(R.string.fm_conflict_overwrite)), (if (isDir) "Merge" else "Overwrite"),
ConflictChoice.KEEP_BOTH to stringResource(R.string.fm_conflict_keep_both), ConflictChoice.KEEP_BOTH to "Keep both",
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip), ConflictChoice.SKIP to "Skip",
).forEach { (choice, label) -> ).forEach { (choice, label) ->
TextButton( TextButton(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -576,7 +573,7 @@ fun FileManagerScreen(
confirmButton = {}, confirmButton = {},
dismissButton = { dismissButton = {
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) { TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
Text(stringResource(R.string.common_cancel)) Text("Cancel")
} }
}, },
) )
@@ -606,7 +603,7 @@ fun FileManagerScreen(
) { ) {
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp)) Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp)) Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.fm_select_this_folder)) Text("Select this folder")
} }
} }
// ── Path bar ── // ── Path bar ──
@@ -622,10 +619,10 @@ fun FileManagerScreen(
// Don't climb above the current drive's root. // Don't climb above the current drive's root.
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent) if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
}, enabled = currentDir != currentRoot) { }, enabled = currentDir != currentRoot) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary) Icon(Icons.Filled.ArrowBack, "Back", tint = MaterialTheme.colorScheme.primary)
} }
val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel) val currentDriveLabel = describeLocation(currentDir).driveLabel
// Dim the drive chip while the Favorites list is open (it's not the active context). // Dim the drive chip while the Favorites list is open (it's not the active context).
val driveChipAlpha = if (showFavorites) 0.45f else 1f val driveChipAlpha = if (showFavorites) 0.45f else 1f
Box { Box {
@@ -669,7 +666,7 @@ fun FileManagerScreen(
} else { } else {
Toast.makeText( Toast.makeText(
context, context,
context.getString(R.string.fm_drive_not_readable, drive.label), "${drive.label} is mounted but not readable right now",
Toast.LENGTH_SHORT, Toast.LENGTH_SHORT,
).show() ).show()
} }
@@ -683,7 +680,7 @@ fun FileManagerScreen(
if (showFavorites) { if (showFavorites) {
Text( Text(
text = stringResource(R.string.fm_favorites), text = "Favorites",
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp, fontSize = 13.sp,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
@@ -721,7 +718,7 @@ fun FileManagerScreen(
) { ) {
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp)) Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(5.dp)) Spacer(Modifier.width(5.dp))
Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp) Text("New Folder", color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
} }
} }
IconButton(onClick = { IconButton(onClick = {
@@ -730,19 +727,19 @@ fun FileManagerScreen(
}) { }) {
Icon( Icon(
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView, if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view), if (gridView) "List view" else "Grid view",
tint = MaterialTheme.colorScheme.onSurfaceVariant, tint = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) { IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant) Icon(Icons.Filled.Search, "Search", tint = MaterialTheme.colorScheme.onSurfaceVariant)
} }
Box { Box {
IconButton(onClick = { showSortMenu = true }) { IconButton(onClick = { showSortMenu = true }) {
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant) Icon(Icons.Filled.Sort, "Sort", tint = MaterialTheme.colorScheme.onSurfaceVariant)
} }
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) { DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size)) listOf("name" to "Name", "date" to "Date modified", "size" to "Size")
.forEach { (key, label) -> .forEach { (key, label) ->
DropdownMenuItem( DropdownMenuItem(
text = { text = {
@@ -761,7 +758,7 @@ fun FileManagerScreen(
} }
HorizontalDivider(color = MaterialTheme.colorScheme.outline) HorizontalDivider(color = MaterialTheme.colorScheme.outline)
DropdownMenuItem( DropdownMenuItem(
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) }, text = { Text(if (compactRows) "Comfortable rows" else "Compact rows") },
onClick = { onClick = {
compactRows = !compactRows compactRows = !compactRows
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply() browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
@@ -769,7 +766,7 @@ fun FileManagerScreen(
}, },
) )
DropdownMenuItem( DropdownMenuItem(
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) }, text = { Text(if (showHidden) "Hide hidden files" else "Show hidden files") },
onClick = { onClick = {
showHidden = !showHidden showHidden = !showHidden
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply() browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
@@ -784,9 +781,9 @@ fun FileManagerScreen(
// Star toggle: open/close the dedicated Favorites list. // Star toggle: open/close the dedicated Favorites list.
IconButton(onClick = { showFavorites = !showFavorites }) { IconButton(onClick = { showFavorites = !showFavorites }) {
if (showFavorites) { if (showFavorites) {
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary) Icon(Icons.Filled.Star, "Hide favorites", tint = MaterialTheme.colorScheme.primary)
} else { } else {
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant) Icon(Icons.Filled.StarBorder, "Show favorites", tint = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
} }
@@ -797,7 +794,7 @@ fun FileManagerScreen(
value = searchQuery, value = searchQuery,
onValueChange = { searchQuery = it }, onValueChange = { searchQuery = it },
singleLine = true, singleLine = true,
placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) }, placeholder = { Text("Filter this folder", fontSize = 13.sp) },
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
) )
} }
@@ -824,7 +821,7 @@ fun FileManagerScreen(
) )
if (freeSpace > 0) { if (freeSpace > 0) {
Text( Text(
stringResource(R.string.fm_free_space, FileOps.formatBytes(context, freeSpace)), "${FileOps.formatBytes(freeSpace)} free",
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp, fontSize = 12.sp,
maxLines = 1, maxLines = 1,
@@ -845,7 +842,7 @@ fun FileManagerScreen(
.padding(horizontal = 12.dp, vertical = 6.dp), .padding(horizontal = 12.dp, vertical = 6.dp),
) { ) {
Text( Text(
stringResource(R.string.fm_selected_count, selectedPaths.size), "${selectedPaths.size} selected",
color = MaterialTheme.colorScheme.onBackground, color = MaterialTheme.colorScheme.onBackground,
fontSize = 13.sp, fontSize = 13.sp,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
@@ -858,7 +855,7 @@ fun FileManagerScreen(
else entries.map { it.absolutePath }.toSet() else entries.map { it.absolutePath }.toSet()
}, },
contentPadding = selBarPadding, contentPadding = selBarPadding,
) { Text(if (selectedPaths.size == entries.size) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) } ) { Text(if (selectedPaths.size == entries.size) "None" else "All", fontSize = 12.sp) }
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
OutlinedButton( OutlinedButton(
enabled = selectedPaths.isNotEmpty(), enabled = selectedPaths.isNotEmpty(),
@@ -869,7 +866,7 @@ fun FileManagerScreen(
selectedPaths = emptySet() selectedPaths = emptySet()
}, },
contentPadding = selBarPadding, contentPadding = selBarPadding,
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) } ) { Text("Copy", fontSize = 12.sp) }
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
OutlinedButton( OutlinedButton(
enabled = selectedPaths.isNotEmpty(), enabled = selectedPaths.isNotEmpty(),
@@ -880,19 +877,19 @@ fun FileManagerScreen(
selectedPaths = emptySet() selectedPaths = emptySet()
}, },
contentPadding = selBarPadding, contentPadding = selBarPadding,
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) } ) { Text("Cut", fontSize = 12.sp) }
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
OutlinedButton( OutlinedButton(
enabled = selectedPaths.isNotEmpty(), enabled = selectedPaths.isNotEmpty(),
onClick = { pendingBulkDelete = entries.filter { it.absolutePath in selectedPaths } }, onClick = { pendingBulkDelete = entries.filter { it.absolutePath in selectedPaths } },
contentPadding = selBarPadding, contentPadding = selBarPadding,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error), border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) } ) { Text("Delete", color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
OutlinedButton( OutlinedButton(
onClick = { selectionMode = false; selectedPaths = emptySet() }, onClick = { selectionMode = false; selectedPaths = emptySet() },
contentPadding = selBarPadding, contentPadding = selBarPadding,
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) } ) { Text("Done", fontSize = 12.sp) }
} }
} }
@@ -906,16 +903,16 @@ fun FileManagerScreen(
.clickable { performPaste() } .clickable { performPaste() }
.padding(horizontal = 16.dp, vertical = 8.dp), .padding(horizontal = 16.dp, vertical = 8.dp),
) { ) {
Icon(Icons.Filled.ContentPaste, stringResource(R.string.fm_paste), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp)) Icon(Icons.Filled.ContentPaste, "Paste", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp)) Spacer(Modifier.width(8.dp))
val what = if (clipboardFiles.size == 1) clipboardFiles.first().name val what = if (clipboardFiles.size == 1) clipboardFiles.first().name
else pluralStringResource(R.plurals.fm_items, clipboardFiles.size, clipboardFiles.size) else "${clipboardFiles.size} items"
Text( Text(
if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what), "Paste $what${if (isCutOperation) " (move)" else ""} here",
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f), color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
) )
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) { TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp) Text("Cancel", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
} }
} }
} }
@@ -947,7 +944,7 @@ fun FileManagerScreen(
isOperationRunning = false isOperationRunning = false
operationDeterminate = false operationDeterminate = false
loadDirectory(currentDir, resetScroll = false) loadDirectory(currentDir, resetScroll = false)
}) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) } }) { Text("Cancel", fontSize = 12.sp) }
} }
} }
Spacer(Modifier.height(4.dp)) Spacer(Modifier.height(4.dp))
@@ -973,12 +970,12 @@ fun FileManagerScreen(
// shown in pick mode (the themed picker keeps its slim layout). Built each recompose (cheap) // shown in pick mode (the themed picker keeps its slim layout). Built each recompose (cheap)
// so it tracks the current drive/favourites without stale click lambdas. // so it tracks the current drive/favourites without stale click lambdas.
val fmRailState = rememberRailState("filemanager") val fmRailState = rememberRailState("filemanager")
fun locItem(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, dir: File, shortLabel: String? = null) = fun locItem(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, dir: File) =
RailItem(label, icon, !showFavorites && currentRoot.absolutePath == dir.absolutePath, shortLabel = shortLabel) { RailItem(label, icon, !showFavorites && currentRoot.absolutePath == dir.absolutePath) {
showFavorites = false; openDrive(dir) showFavorites = false; openDrive(dir)
} }
val storageItems = buildList { val storageItems = buildList {
add(locItem(stringResource(R.string.fm_drive_internal), Icons.Filled.Smartphone, File("/storage/emulated/0"))) add(locItem("Internal", Icons.Filled.Smartphone, File("/storage/emulated/0")))
drives.filter { it.removable }.forEach { d -> drives.filter { it.removable }.forEach { d ->
add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) { add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) {
showFavorites = false; if (d.readable) openDrive(d.dir) showFavorites = false; if (d.readable) openDrive(d.dir)
@@ -986,25 +983,25 @@ fun FileManagerScreen(
} }
} }
val quickItems = buildList { val quickItems = buildList {
File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_downloads), Icons.Filled.Download, it, stringResource(R.string.fm_rail_downloads_short))) } File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem("Downloads", Icons.Filled.Download, it)) }
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs. // The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory } SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) } ?.let { add(locItem("ROMs", Icons.Filled.SportsEsports, it)) }
File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) } File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem("Session logs", Icons.Filled.Description, it)) }
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) } File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem("Pictures", Icons.Filled.Image, it)) }
} }
val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } } val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } }
.map { d -> RailItem(d.name, Icons.Filled.Star, false) { showFavorites = false; openDrive(d) } } .map { d -> RailItem(d.name, Icons.Filled.Star, false) { showFavorites = false; openDrive(d) } }
val locationSections = buildList { val locationSections = buildList {
add(RailSection(stringResource(R.string.fm_rail_storage), storageItems)) add(RailSection("STORAGE", storageItems))
if (quickItems.isNotEmpty()) add(RailSection(stringResource(R.string.fm_rail_quick), quickItems)) if (quickItems.isNotEmpty()) add(RailSection("QUICK", quickItems))
if (favItems.isNotEmpty()) add(RailSection(stringResource(R.string.fm_rail_favorites), favItems)) if (favItems.isNotEmpty()) add(RailSection("FAVORITES", favItems))
} }
Row(modifier = Modifier.weight(1f).fillMaxWidth()) { Row(modifier = Modifier.weight(1f).fillMaxWidth()) {
// The slim picker keeps its layout: no rail. // The slim picker keeps its layout: no rail.
if (!pickMode) { if (!pickMode) {
CollapsibleRail(state = fmRailState, title = stringResource(R.string.fm_rail_title), sections = locationSections, outlinedItems = true) CollapsibleRail(state = fmRailState, title = "Files", sections = locationSections, outlinedItems = true)
} }
Box(modifier = Modifier.weight(1f).fillMaxSize()) { Box(modifier = Modifier.weight(1f).fillMaxSize()) {
// ── Favorites list OR file list ── // ── Favorites list OR file list ──
@@ -1015,7 +1012,7 @@ fun FileManagerScreen(
onPinCurrent = { onPinCurrent = {
FavoritesStore.add(context, currentDir.absolutePath) FavoritesStore.add(context, currentDir.absolutePath)
favTick++ favTick++
Toast.makeText(context, context.getString(R.string.fm_favorite_added, currentDir.name), Toast.LENGTH_SHORT).show() Toast.makeText(context, "Added \"${currentDir.name}\" to Favorites", Toast.LENGTH_SHORT).show()
}, },
onJump = { dir -> onJump = { dir ->
showFavorites = false showFavorites = false
@@ -1024,7 +1021,7 @@ fun FileManagerScreen(
onUnpin = { dir -> onUnpin = { dir ->
FavoritesStore.remove(context, dir.absolutePath) FavoritesStore.remove(context, dir.absolutePath)
favTick++ favTick++
Toast.makeText(context, context.getString(R.string.fm_favorite_removed, dir.name), Toast.LENGTH_SHORT).show() Toast.makeText(context, "Removed \"${dir.name}\" from Favorites", Toast.LENGTH_SHORT).show()
}, },
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
) )
@@ -1098,8 +1095,8 @@ fun FileManagerScreen(
showMenuFor = null showMenuFor = null
Toast.makeText( Toast.makeText(
context, context,
if (nowFav) context.getString(R.string.fm_favorite_added, file.name) if (nowFav) "Added \"${file.name}\" to Favorites"
else context.getString(R.string.fm_favorite_removed, file.name), else "Removed \"${file.name}\" from Favorites",
Toast.LENGTH_SHORT, Toast.LENGTH_SHORT,
).show() ).show()
}, },
@@ -1115,7 +1112,7 @@ fun FileManagerScreen(
modifier = Modifier.fillParentMaxSize(), modifier = Modifier.fillParentMaxSize(),
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
Text(stringResource(R.string.fm_empty_directory), color = MaterialTheme.colorScheme.onSurfaceVariant) Text("Empty directory", color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
} else { } else {
@@ -1176,8 +1173,8 @@ fun FileManagerScreen(
showMenuFor = null showMenuFor = null
Toast.makeText( Toast.makeText(
context, context,
if (nowFav) context.getString(R.string.fm_favorite_added, file.name) if (nowFav) "Added \"${file.name}\" to Favorites"
else context.getString(R.string.fm_favorite_removed, file.name), else "Removed \"${file.name}\" from Favorites",
Toast.LENGTH_SHORT, Toast.LENGTH_SHORT,
).show() ).show()
}, },
@@ -1,8 +1,6 @@
package com.droiddeck.launcher.files package com.droiddeck.launcher.files
import android.content.Context
import android.util.Log import android.util.Log
import com.droiddeck.launcher.R
import java.io.File import java.io.File
import java.io.FileInputStream import java.io.FileInputStream
import java.io.FileOutputStream import java.io.FileOutputStream
@@ -21,9 +19,9 @@ object FileOps {
/** Byte-accurate copy progress (copied/total bytes), reported as the copy proceeds. */ /** Byte-accurate copy progress (copied/total bytes), reported as the copy proceeds. */
fun interface ProgressCallback { fun onProgress(copiedBytes: Long, totalBytes: Long) } fun interface ProgressCallback { fun onProgress(copiedBytes: Long, totalBytes: Long) }
fun formatBytes(context: Context, bytes: Long): String { fun formatBytes(bytes: Long): String {
if (bytes <= 0) return context.getString(R.string.fm_size_zero) if (bytes <= 0) return "0 bytes"
val units = arrayOf(context.getString(R.string.fm_unit_bytes), "KB", "MB", "GB", "TB") val units = arrayOf("bytes", "KB", "MB", "GB", "TB")
val group = (Math.log10(bytes.toDouble()) / Math.log10(1024.0)).toInt().coerceIn(0, units.lastIndex) val group = (Math.log10(bytes.toDouble()) / Math.log10(1024.0)).toInt().coerceIn(0, units.lastIndex)
return String.format(Locale.ENGLISH, "%.2f", bytes / Math.pow(1024.0, group.toDouble())) + " " + units[group] return String.format(Locale.ENGLISH, "%.2f", bytes / Math.pow(1024.0, group.toDouble())) + " " + units[group]
} }
@@ -12,7 +12,6 @@ import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import com.droiddeck.launcher.R
import com.droiddeck.launcher.ui.DroidDeckTheme import com.droiddeck.launcher.ui.DroidDeckTheme
import java.io.File import java.io.File
@@ -27,11 +26,6 @@ import java.io.File
* - [EXTRA_PICKER_TITLE] the header * - [EXTRA_PICKER_TITLE] the header
*/ */
class FilePickerActivity : ComponentActivity() { class FilePickerActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@@ -49,14 +43,14 @@ class FilePickerActivity : ComponentActivity() {
?.let { File(it) }?.takeIf { it.isDirectory } ?.let { File(it) }?.takeIf { it.isDirectory }
setContent { setContent {
DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) { DroidDeckTheme {
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) { Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
FileManagerScreen( FileManagerScreen(
pickMode = true, pickMode = true,
pickDirMode = pickDir, pickDirMode = pickDir,
pickExtensions = extensions, pickExtensions = extensions,
initialDir = initialDir, initialDir = initialDir,
pickerTitle = title ?: getString(if (pickDir) R.string.fm_choose_folder else R.string.fm_choose_file), pickerTitle = title ?: if (pickDir) "Choose a folder" else "Choose a file",
onPick = { file -> onPick = { file ->
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath)) setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
finish() finish()
@@ -25,8 +25,6 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -68,7 +66,7 @@ internal fun FilePropertiesDialog(
OutlinedAlertDialog( OutlinedAlertDialog(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.fm_properties)) }, title = { Text("Properties") },
text = { text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) { Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
// ── Basic info ── // ── Basic info ──
@@ -81,14 +79,14 @@ internal fun FilePropertiesDialog(
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
Spacer(Modifier.height(6.dp)) Spacer(Modifier.height(6.dp))
PropertyLine(stringResource(R.string.fm_prop_location), file.parent ?: "-") PropertyLine("Location", file.parent ?: "-")
PropertyLine( PropertyLine(
stringResource(R.string.fm_prop_type), "Type",
if (file.isDirectory) stringResource(R.string.fm_type_folder) if (file.isDirectory) "Folder"
else file.extension.uppercase().let { if (it.isBlank()) stringResource(R.string.fm_type_file) else stringResource(R.string.fm_type_ext_file, it) }, else file.extension.uppercase().let { if (it.isBlank()) "File" else "$it file" },
) )
if (!file.isDirectory) PropertyLine(stringResource(R.string.fm_prop_size), FileOps.formatBytes(context, file.length())) if (!file.isDirectory) PropertyLine("Size", FileOps.formatBytes(file.length()))
PropertyLine(stringResource(R.string.fm_prop_modified), dateFormat.format(Date(file.lastModified()))) PropertyLine("Modified", dateFormat.format(Date(file.lastModified())))
Spacer(Modifier.height(10.dp)) Spacer(Modifier.height(10.dp))
HorizontalDivider(color = MaterialTheme.colorScheme.outline) HorizontalDivider(color = MaterialTheme.colorScheme.outline)
@@ -97,8 +95,8 @@ internal fun FilePropertiesDialog(
val state = attrs val state = attrs
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY). // ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
AttributeToggleRow( AttributeToggleRow(
label = stringResource(R.string.fm_read_only), label = "Read-only",
description = stringResource(R.string.fm_read_only_hint), description = "Stops games (and Wine) from overwriting or deleting this file.",
checked = state?.readOnly == true, checked = state?.readOnly == true,
enabled = state != null && !busy, enabled = state != null && !busy,
onToggle = { want -> onToggle = { want ->
@@ -110,7 +108,7 @@ internal fun FilePropertiesDialog(
attrs = attrs?.copy(readOnly = want) attrs = attrs?.copy(readOnly = want)
onChanged() onChanged()
} else { } else {
Toast.makeText(context, R.string.fm_read_only_failed, Toast.LENGTH_SHORT).show() Toast.makeText(context, "Couldn't change Read-only", Toast.LENGTH_SHORT).show()
} }
} }
}, },
@@ -119,10 +117,10 @@ internal fun FilePropertiesDialog(
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr. // ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
val hiddenSupported = state?.hiddenSupported == true val hiddenSupported = state?.hiddenSupported == true
AttributeToggleRow( AttributeToggleRow(
label = stringResource(R.string.fm_hidden), label = "Hidden",
description = if (state != null && !hiddenSupported) description = if (state != null && !hiddenSupported)
stringResource(R.string.fm_hidden_unsupported) "This storage can't store the hidden flag."
else stringResource(R.string.fm_hidden_hint), else "Marks the file hidden in Windows (Wine's hidden attribute).",
checked = state?.hidden == true, checked = state?.hidden == true,
enabled = state != null && hiddenSupported && !busy, enabled = state != null && hiddenSupported && !busy,
onToggle = { want -> onToggle = { want ->
@@ -136,14 +134,14 @@ internal fun FilePropertiesDialog(
} else { } else {
// The write failed after all - disable the toggle rather than lie. // The write failed after all - disable the toggle rather than lie.
attrs = attrs?.copy(hiddenSupported = false) attrs = attrs?.copy(hiddenSupported = false)
Toast.makeText(context, R.string.fm_hidden_failed, Toast.LENGTH_SHORT).show() Toast.makeText(context, "Couldn't change Hidden on this storage", Toast.LENGTH_SHORT).show()
} }
} }
}, },
) )
} }
}, },
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.fm_done)) } }, confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } },
) )
} }
@@ -5,7 +5,6 @@ import android.os.Build
import android.os.Environment import android.os.Environment
import android.os.storage.StorageManager import android.os.storage.StorageManager
import android.os.storage.StorageVolume import android.os.storage.StorageVolume
import com.droiddeck.launcher.R
import java.io.File import java.io.File
/** /**
@@ -64,7 +63,7 @@ object StorageRoots {
// Internal storage is never removable and never absent; seed it first so it heads the menu. // Internal storage is never removable and never absent; seed it first so it heads the menu.
volumeOf(PRIMARY_KEY).apply { volumeOf(PRIMARY_KEY).apply {
label = context.getString(R.string.fm_drive_internal) label = "Internal"
removable = false removable = false
candidates += File(INTERNAL_PATH) candidates += File(INTERNAL_PATH)
} }
@@ -110,13 +109,13 @@ object StorageRoots {
entry.seeds += dir entry.seeds += dir
} }
val roots = volumes.values.map { it.toRoot(context) } val roots = volumes.values.map { it.toRoot() }
val internal = roots.filter { !it.removable } val internal = roots.filter { !it.removable }
val removable = roots.filter { it.removable }.sortedBy { it.label } val removable = roots.filter { it.removable }.sortedBy { it.label }
return disambiguate(internal + removable) return disambiguate(internal + removable)
} }
private fun Volume.toRoot(context: Context): StorageRoot { private fun Volume.toRoot(): StorageRoot {
// Prefer a path we can actually list; a readable child beats an unreadable root. // Prefer a path we can actually list; a readable child beats an unreadable root.
val dir = candidates.firstOrNull(::canBrowse) val dir = candidates.firstOrNull(::canBrowse)
?: candidates.firstNotNullOfOrNull { root -> seeds.firstNotNullOfOrNull { deepestReadable(root, it) } } ?: candidates.firstNotNullOfOrNull { root -> seeds.firstNotNullOfOrNull { deepestReadable(root, it) } }
@@ -126,14 +125,14 @@ object StorageRoots {
?: File("/storage/$key") ?: File("/storage/$key")
return StorageRoot( return StorageRoot(
label = label ?: defaultLabel(context), label = label ?: defaultLabel(),
dir = dir, dir = dir,
removable = removable, removable = removable,
readable = canBrowse(dir), readable = canBrowse(dir),
) )
} }
private fun Volume.defaultLabel(context: Context): String = if (removable) context.getString(R.string.fm_drive_sd) else key private fun Volume.defaultLabel(): String = if (removable) "SD card" else key
/** Appends the volume id to any label used by more than one volume, so entries stay tellable apart. */ /** Appends the volume id to any label used by more than one volume, so entries stay tellable apart. */
private fun disambiguate(roots: List<StorageRoot>): List<StorageRoot> { private fun disambiguate(roots: List<StorageRoot>): List<StorageRoot> {
@@ -184,12 +183,12 @@ object StorageRoots {
* name like "android", which tells the user nothing about which card they are looking at. * name like "android", which tells the user nothing about which card they are looking at.
*/ */
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String { private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
if (volume.isPrimary) return context.getString(R.string.fm_drive_internal) if (volume.isPrimary) return "Internal"
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd) if (volume.isRemovable) return "SD card"
val description = volume.getDescription(context)?.trim() val description = volume.getDescription(context)?.trim()
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) } return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
?: uuid ?: uuid
?: context.getString(R.string.fm_drive_storage) ?: "Storage"
} }
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX) private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.frontend
import android.content.Context import android.content.Context
import android.util.Log import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
@@ -38,18 +37,18 @@ object GameFileSync {
} }
@Synchronized private fun sync(context: Context, folder: File) { @Synchronized private fun sync(context: Context, folder: File) {
check(LinuxRuntime.isInstalled(context)) { context.getString(R.string.game_sync_err_runtime) } check(LinuxRuntime.isInstalled(context)) { "Install the runtime first" }
// A disconnected library must not be interpreted as a mass uninstall. // A disconnected library must not be interpreted as a mass uninstall.
check(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps").isDirectory) { context.getString(R.string.game_sync_err_steam_library) } check(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps").isDirectory) { "Steam library is unavailable" }
val storage = GameStorage.effective(context) val storage = GameStorage.effective(context)
val storageSetting = SessionPrefs.gameStorage(context) val storageSetting = SessionPrefs.gameStorage(context)
val previousStorage = prefs(context).getString("storagePath", null) val previousStorage = prefs(context).getString("storagePath", null)
if (storageSetting.isEmpty() && prefs(context).getString("storageSetting", null) == storageSetting && previousStorage != null) { if (storageSetting.isEmpty() && prefs(context).getString("storageSetting", null) == storageSetting && previousStorage != null) {
check(File(previousStorage).isDirectory) { context.getString(R.string.game_sync_err_previous_sd) } check(File(previousStorage).isDirectory) { "Previous SD library is unavailable" }
} }
storage?.let { check(File(it.path).listFiles() != null) { context.getString(R.string.game_sync_err_game_storage) } } storage?.let { check(File(it.path).listFiles() != null) { "Game storage is unavailable" } }
SessionPrefs.addedGamesDirs(context).forEach { check(File(it).listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } } SessionPrefs.addedGamesDirs(context).forEach { check(File(it).listFiles() != null) { "Added games folder is unavailable" } }
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true)) GameFiles.sync(folder, Library.launchableGames(context, strictRead = true))
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply() prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
} }
} }
@@ -6,7 +6,6 @@ import android.util.AtomicFile
import androidx.core.util.readText import androidx.core.util.readText
import androidx.core.util.writeBytes import androidx.core.util.writeBytes
import androidx.core.util.writeText import androidx.core.util.writeText
import com.droiddeck.launcher.R
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
import java.io.InputStream import java.io.InputStream
@@ -60,18 +59,18 @@ object GameFiles {
private fun contents(id: String) = GameLaunchLink.uri(id) + "\n" private fun contents(id: String) = GameLaunchLink.uri(id) + "\n"
@Synchronized fun export(context: Context, folder: File, game: Library.SteamGame): File { @Synchronized fun export(folder: File, game: Library.SteamGame): File {
require(folder.isDirectory) { context.getString(R.string.gfiles_folder_unavailable) } require(folder.isDirectory) { "Folder is unavailable" }
val target = child(context, folder, filename(game)) val target = child(folder, filename(game))
val text = contents(game.gameIdString) val text = contents(game.gameIdString)
require(!target.exists() || matches(target, text)) { context.getString(R.string.gfiles_name_taken, target.name) } require(!target.exists() || matches(target, text)) { "A different file already uses ${target.name}" }
if (!target.exists()) write(target, text) if (!target.exists()) write(target, text)
exportArt(context, folder, game) exportArt(folder, game)
return target return target
} }
/** Cocoon matches icons in its data folder's images directory. Never replace custom art. */ /** Cocoon matches icons in its data folder's images directory. Never replace custom art. */
private fun exportArt(context: Context, folder: File, game: Library.SteamGame) { private fun exportArt(folder: File, game: Library.SteamGame) {
val art = listOfNotNull(game.icon, game.art).firstOrNull { val art = listOfNotNull(game.icon, game.art).firstOrNull {
it.isFile && it.extension.lowercase() in listOf("jpg", "jpeg", "png", "webp") it.isFile && it.extension.lowercase() in listOf("jpg", "jpeg", "png", "webp")
} ?: return } ?: return
@@ -80,27 +79,27 @@ object GameFiles {
.replace(Regex("[^a-zA-Z0-9\\s]"), "").trim() .replace(Regex("[^a-zA-Z0-9\\s]"), "").trim()
.replace(Regex("\\s+"), "-").lowercase(java.util.Locale.ROOT).take(50).trimEnd('-') .replace(Regex("\\s+"), "-").lowercase(java.util.Locale.ROOT).take(50).trimEnd('-')
if (title.isEmpty()) return if (title.isEmpty()) return
val images = child(context, folder, "images") val images = child(folder, "images")
check(images.isDirectory || images.mkdir()) { context.getString(R.string.gfiles_art_unavailable) } check(images.isDirectory || images.mkdir()) { "Artwork folder is unavailable" }
val target = child(context, images, "$title-icon.${art.extension.lowercase()}") val target = child(images, "$title-icon.${art.extension.lowercase()}")
if (!target.exists()) AtomicFile(target).writeBytes(art.readBytes()) if (!target.exists()) AtomicFile(target).writeBytes(art.readBytes())
} }
/** Only remove files in our inventory whose content is still exactly what we wrote. */ /** Only remove files in our inventory whose content is still exactly what we wrote. */
@Synchronized fun sync(context: Context, folder: File, games: List<Library.SteamGame>) { @Synchronized fun sync(folder: File, games: List<Library.SteamGame>) {
require(folder.isDirectory) { context.getString(R.string.gfiles_folder_unavailable) } require(folder.isDirectory) { "Folder is unavailable" }
val inventory = child(context, folder, INVENTORY) val inventory = child(folder, INVENTORY)
val previous = if (inventory.exists()) { val previous = if (inventory.exists()) {
val record = JSONObject(AtomicFile(inventory).readText()) val record = JSONObject(AtomicFile(inventory).readText())
require(record.optString("format") == FORMAT) { context.getString(R.string.gfiles_unrelated_inventory) } require(record.optString("format") == FORMAT) { "Folder has an unrelated sync inventory" }
record.getJSONObject("games") record.getJSONObject("games")
} else JSONObject() } else JSONObject()
val next = JSONObject() val next = JSONObject()
val exports = games.distinctBy { it.gameId }.map { game -> val exports = games.distinctBy { it.gameId }.map { game ->
val target = child(context, folder, filename(game)) val target = child(folder, filename(game))
// Keep an edited export without letting it block the rest of the library sync. // Keep an edited export without letting it block the rest of the library sync.
val file = if (previous.optString(target.name) == game.gameIdString && target.exists() && val file = if (previous.optString(target.name) == game.gameIdString && target.exists() &&
!matches(target, contents(game.gameIdString))) target else export(context, folder, game) !matches(target, contents(game.gameIdString))) target else export(folder, game)
next.put(file.name, game.gameIdString) next.put(file.name, game.gameIdString)
file file
} }
@@ -108,22 +107,22 @@ object GameFiles {
for (name in previous.keys()) { for (name in previous.keys()) {
val id = previous.getString(name) val id = previous.getString(name)
if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) { if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) {
val file = child(context, folder, name) val file = child(folder, name)
if (matches(file, contents(id))) { if (matches(file, contents(id))) {
// Android shared storage is often case insensitive. A case-only rename may // Android shared storage is often case insensitive. A case-only rename may
// still resolve to the live export, which must not be pruned as an old file. // still resolve to the live export, which must not be pruned as an old file.
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) } val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
if (!retained) check(file.delete()) { context.getString(R.string.gfiles_remove_failed, name) } if (!retained) check(file.delete()) { "Could not remove $name" }
} }
} }
} }
if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString()) if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString())
} }
private fun child(context: Context, folder: File, name: String): File { private fun child(folder: File, name: String): File {
require(name.isNotEmpty() && '/' !in name && '\\' !in name && name != "." && name != "..") require(name.isNotEmpty() && '/' !in name && '\\' !in name && name != "." && name != "..")
val file = File(folder, name) val file = File(folder, name)
require(file.canonicalFile.parentFile == folder.canonicalFile) { context.getString(R.string.gfiles_outside_folder) } require(file.canonicalFile.parentFile == folder.canonicalFile) { "File leaves the export folder" }
return file return file
} }
@@ -33,8 +33,6 @@ object Library {
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null) class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) { class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
/** The shown name of [system] when it is words rather than a platform name, else 0. */
val systemRes: Int get() = if (id == "retroarch") R.string.content_system_many else 0
/** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */ /** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */
val iconRes: Int get() = when (id) { val iconRes: Int get() = when (id) {
"rpcs3" -> R.drawable.emu_rpcs3; "armsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin "rpcs3" -> R.drawable.emu_rpcs3; "armsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
@@ -111,7 +109,7 @@ object Library {
for ((library, label) in libraries) { for ((library, label) in libraries) {
val steamapps = File(library, "steamapps") val steamapps = File(library, "steamapps")
val manifests = steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") } val manifests = steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }
if (strictRead && steamapps.isDirectory) check(manifests != null) { context.getString(R.string.game_sync_err_manifests) } if (strictRead && steamapps.isDirectory) check(manifests != null) { "Steam manifests are unavailable" }
manifests?.sortedBy { it.name }?.forEach { manifest -> manifests?.sortedBy { it.name }?.forEach { manifest ->
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.gpu
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import android.util.Log import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject import org.json.JSONObject
@@ -85,7 +84,7 @@ object DriverBundle {
unzip(context, uri, work) unzip(context, uri, work)
val manifest = File(work, MANIFEST).takeIf { it.isFile } val manifest = File(work, MANIFEST).takeIf { it.isFile }
?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() } ?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() }
?: throw IllegalArgumentException(context.getString(R.string.bundle_no_manifest)) ?: throw IllegalArgumentException("Not a driver bundle: no manifest.json naming an android and a linux driver")
val androidDir = File(work, manifest.androidPath) val androidDir = File(work, manifest.androidPath)
val linuxDir = File(work, manifest.linuxPath) val linuxDir = File(work, manifest.linuxPath)
@@ -136,7 +135,7 @@ object DriverBundle {
for (entry in generateSequence { zip.nextEntry }) { for (entry in generateSequence { zip.nextEntry }) {
if (entry.isDirectory) continue if (entry.isDirectory) continue
val out = File(root, entry.name).canonicalFile val out = File(root, entry.name).canonicalFile
if (!out.path.startsWith(root.path + File.separator)) throw IllegalArgumentException(context.getString(R.string.bundle_entry_outside, entry.name)) if (!out.path.startsWith(root.path + File.separator)) throw IllegalArgumentException("Not a driver bundle: ${entry.name} points outside it")
out.parentFile?.mkdirs() out.parentFile?.mkdirs()
out.outputStream().use { sink -> out.outputStream().use { sink ->
val buf = ByteArray(1 shl 16) val buf = ByteArray(1 shl 16)
@@ -144,7 +143,7 @@ object DriverBundle {
val r = zip.read(buf) val r = zip.read(buf)
if (r <= 0) break if (r <= 0) break
total += r total += r
if (total > MAX_BYTES) throw IllegalArgumentException(context.getString(R.string.bundle_too_large, MAX_BYTES shr 20)) 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) sink.write(buf, 0, r)
} }
} }
@@ -1,8 +1,6 @@
package com.droiddeck.launcher.gpu package com.droiddeck.launcher.gpu
import android.content.Context
import android.os.Build import android.os.Build
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.core.FileUtils
import java.io.File import java.io.File
@@ -31,10 +29,7 @@ data class GpuInfo(
A6XX("Adreno 6xx"), A6XX("Adreno 6xx"),
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */ /** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
ADRENO_UNKNOWN("Adreno"), ADRENO_UNKNOWN("Adreno"),
NOT_ADRENO("Not an Adreno GPU"); NOT_ADRENO("Not an Adreno GPU"),
/** [label] in the app's language: the Adreno families are names, the rest is words. */
fun label(context: Context): String = if (this == NOT_ADRENO) context.getString(R.string.gpuinfo_not_adreno) else label
} }
enum class Support { TESTED, UNTESTED, UNSUPPORTED } enum class Support { TESTED, UNTESTED, UNSUPPORTED }
@@ -47,7 +42,7 @@ data class GpuInfo(
else -> Support.UNTESTED else -> Support.UNTESTED
} }
/** One line for the device card and the system check, in English for the device report. */ /** One line for the device card and the system check. */
val supportText: String val supportText: String
get() = when (support) { get() = when (support) {
Support.TESTED -> "Supported" Support.TESTED -> "Supported"
@@ -56,20 +51,7 @@ data class GpuInfo(
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU" Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
} }
/** [supportText] in the app's language. */
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
Support.UNTESTED -> if (family == Family.A7XX_LOW) R.string.gpuinfo_experimental else R.string.gpuinfo_below_tested
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
})
/** [name] for the screen: the stand-in for a GPU the device does not name is in the app's language. */
fun displayName(context: Context): String = if (name == UNNAMED) context.getString(R.string.gpu_this_gpu) else name
companion object { companion object {
/** [name] when the device names no GPU; English, as the device report shows it. */
private const val UNNAMED = "this GPU"
fun detect(): GpuInfo { fun detect(): GpuInfo {
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid") val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
@@ -79,7 +61,7 @@ data class GpuInfo(
val family = familyOf(adreno, model) val family = familyOf(adreno, model)
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo( return GpuInfo(
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno", name = if (!adreno) Build.HARDWARE.ifBlank { "this GPU" } else if (model > 0) "Adreno $model" else "Adreno",
model = model, family = family, soc = soc, model = model, family = family, soc = soc,
oneUi8Gen2 = samsung && model == 740, oneUi8Gen2 = samsung && model == 740,
) )
@@ -4,7 +4,6 @@ import android.content.Context;
import android.net.Uri; import android.net.Uri;
import android.util.Log; import android.util.Log;
import com.droiddeck.launcher.R;
import com.droiddeck.launcher.core.FileUtils; import com.droiddeck.launcher.core.FileUtils;
import org.json.JSONObject; import org.json.JSONObject;
@@ -182,17 +181,20 @@ public class LinuxVulkanDriverManager {
String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException { String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException {
try { try {
if (soName == null) { if (soName == null) {
throw new IllegalArgumentException(context.getString(R.string.lvd_no_library)); throw new IllegalArgumentException("No libvulkan_freedreno*.so in this zip. An Android "
+ "(AdrenoTools) or -Wayland Turnip zip is not a Linux runtime driver.");
} }
File so = new File(tmpDir, LIB_NAME); File so = new File(tmpDir, LIB_NAME);
if (!isAarch64Elf(so)) { if (!isAarch64Elf(so)) {
throw new IllegalArgumentException(context.getString(R.string.lvd_not_aarch64, soName)); throw new IllegalArgumentException(soName + " is not a 64-bit AArch64 ELF shared library.");
} }
// The one check that actually separates this from the bionic builds. Both sonames // The one check that actually separates this from the bionic builds. Both sonames
// are in the driver's .dynstr, so a byte scan is enough and needs no ELF parsing: // are in the driver's .dynstr, so a byte scan is enough and needs no ELF parsing:
// glibc's is versioned ("libc.so.6"), bionic's is not ("libc.so"). // glibc's is versioned ("libc.so.6"), bionic's is not ("libc.so").
if (!containsAscii(so, "libc.so.6")) { if (!containsAscii(so, "libc.so.6")) {
throw new IllegalArgumentException(context.getString(R.string.lvd_not_glibc, soName)); throw new IllegalArgumentException(soName + " is not a glibc driver - it links Android's libc. "
+ "The Linux runtime needs a \"-Linux\" zip; a plain or \"-Wayland\" Turnip cannot be "
+ "loaded by the Steam client at all.");
} }
String kind = zipMeta != null ? zipMeta.optString("kind", "") : ""; String kind = zipMeta != null ? zipMeta.optString("kind", "") : "";
if (!kind.isEmpty() && !"linux-vulkan-icd".equals(kind)) { if (!kind.isEmpty() && !"linux-vulkan-icd".equals(kind)) {
@@ -1,7 +1,5 @@
package com.droiddeck.launcher.gpu package com.droiddeck.launcher.gpu
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.wayland.WaylandCompositor import com.droiddeck.launcher.wayland.WaylandCompositor
import org.json.JSONObject import org.json.JSONObject
import kotlin.math.abs import kotlin.math.abs
@@ -84,15 +82,11 @@ data class ScreenEffects(
* SessionPrefs.upscalerChoices mode the Look switches to. * SessionPrefs.upscalerChoices mode the Look switches to.
*/ */
data class Look( data class Look(
/** The Look's id: what the row picks by and the compositor logs. */
val name: String, val name: String,
val effects: ScreenEffects, val effects: ScreenEffects,
val scalingMode: Int? = null, val scalingMode: Int? = null,
/** One line under the row while this Look is picked. */ /** One line under the row while this Look is picked. */
val desc: String, val desc: String,
/** [name] and [desc] in the app's language, for the menu. */
@StringRes val label: Int,
@StringRes val descRes: Int,
) )
object ScreenEffectLooks { object ScreenEffectLooks {
@@ -102,29 +96,29 @@ object ScreenEffectLooks {
/** Index 0 is the neutral state a fresh session matches, so the row always names something. */ /** Index 0 is the neutral state a fresh session matches, so the row always names something. */
val LOOKS: List<Look> = listOf( val LOOKS: List<Look> = listOf(
Look("Off", ScreenEffects.OFF, desc = "Nothing applied.", label = R.string.frame_gen_off, descRes = R.string.look_off_desc), Look("Off", ScreenEffects.OFF, desc = "Nothing applied."),
Look("Game Clarity", ScreenEffects(brightness = 2, contrast = 12, saturation = 108, cas = true, casLevel = 55), Look("Game Clarity", ScreenEffects(brightness = 2, contrast = 12, saturation = 108, cas = true, casLevel = 55),
desc = "Sharpening with a touch of contrast - the everyday one.", label = R.string.look_game_clarity, descRes = R.string.look_game_clarity_desc), desc = "Sharpening with a touch of contrast - the everyday one."),
Look("Vivid", ScreenEffects(brightness = 3, contrast = 10, gamma = 0.98f, saturation = 145, cas = true, casLevel = 30, deband = true), Look("Vivid", ScreenEffects(brightness = 3, contrast = 10, gamma = 0.98f, saturation = 145, cas = true, casLevel = 30, deband = true),
desc = "Colour pushed hard. Deband on so skies don't stripe.", label = R.string.look_vivid, descRes = R.string.look_vivid_desc), desc = "Colour pushed hard. Deband on so skies don't stripe."),
Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, fxaa = true, deband = true), Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, fxaa = true, deband = true),
desc = "Deeper contrast, cooler colour, edges smoothed.", label = R.string.look_cinematic, descRes = R.string.look_cinematic_desc), desc = "Deeper contrast, cooler colour, edges smoothed."),
Look("Competitive", ScreenEffects(brightness = 16, contrast = 18, gamma = 0.92f, saturation = 82, cas = true, casLevel = 75), Look("Competitive", ScreenEffects(brightness = 16, contrast = 18, gamma = 0.92f, saturation = 82, cas = true, casLevel = 75),
desc = "Shadows lifted and heavy sharpening - spot people first.", label = R.string.look_competitive, descRes = R.string.look_competitive_desc), desc = "Shadows lifted and heavy sharpening - spot people first."),
Look("Adaptive Sharpen", ScreenEffects(cas = true, casLevel = 85), Look("Adaptive Sharpen", ScreenEffects(cas = true, casLevel = 85),
desc = "Sharpening only, colour untouched.", label = R.string.look_adaptive_sharpen, descRes = R.string.look_adaptive_sharpen_desc), desc = "Sharpening only, colour untouched."),
Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, fxaa = true, deband = true), Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, fxaa = true, deband = true),
desc = "Film-like curve, slightly muted.", label = R.string.look_filmic, descRes = R.string.look_filmic_desc), desc = "Film-like curve, slightly muted."),
Look("Arcade", ScreenEffects(brightness = 6, contrast = 20, gamma = 0.95f, saturation = 170, cas = true, casLevel = 45, deband = true), Look("Arcade", ScreenEffects(brightness = 6, contrast = 20, gamma = 0.95f, saturation = 170, cas = true, casLevel = 45, deband = true),
desc = "Loud and punchy.", label = R.string.look_arcade, descRes = R.string.look_arcade_desc), desc = "Loud and punchy."),
Look("Retro CRT", ScreenEffects(brightness = 6, contrast = 14, gamma = 1.05f, saturation = 115, crt = true, ntsc = true), Look("Retro CRT", ScreenEffects(brightness = 6, contrast = 14, gamma = 1.05f, saturation = 115, crt = true, ntsc = true),
desc = "The CRT tube and analogue signal passes together.", label = R.string.look_retro_crt, descRes = R.string.look_retro_crt_desc), desc = "The CRT tube and analogue signal passes together."),
Look("Upscale Sharp", ScreenEffects(contrast = 6, saturation = 104, cas = true, casLevel = 70), scalingMode = SCALING_FSR, Look("Upscale Sharp", ScreenEffects(contrast = 6, saturation = 104, cas = true, casLevel = 70), scalingMode = SCALING_FSR,
desc = "For running below panel resolution.", label = R.string.look_upscale_sharp, descRes = R.string.look_upscale_sharp_desc), desc = "For running below panel resolution."),
Look("Pixel Clean", ScreenEffects(contrast = 8, deband = true), scalingMode = SCALING_NEAREST, Look("Pixel Clean", ScreenEffects(contrast = 8, deband = true), scalingMode = SCALING_NEAREST,
desc = "Crisp pixels for 2D and old titles.", label = R.string.look_pixel_clean, descRes = R.string.look_pixel_clean_desc), desc = "Crisp pixels for 2D and old titles."),
Look("Anime Edge", ScreenEffects(brightness = 2, contrast = 10, saturation = 125, cas = true, casLevel = 50, toon = true, deband = true), Look("Anime Edge", ScreenEffects(brightness = 2, contrast = 10, saturation = 125, cas = true, casLevel = 50, toon = true, deband = true),
desc = "Toon outlines plus sharpening.", label = R.string.look_anime_edge, descRes = R.string.look_anime_edge_desc), desc = "Toon outlines plus sharpening."),
) )
/** /**
@@ -5,7 +5,6 @@ import android.net.Uri;
import android.os.Environment; import android.os.Environment;
import android.util.Log; import android.util.Log;
import com.droiddeck.launcher.R;
import com.droiddeck.launcher.core.FileUtils; import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.TarZst; import com.droiddeck.launcher.core.TarZst;
import com.droiddeck.launcher.session.SessionPrefs; import com.droiddeck.launcher.session.SessionPrefs;
@@ -219,7 +218,7 @@ public final class TurnipDriver {
*/ */
String adopt(File tmpDir, String displayName) throws IOException { String adopt(File tmpDir, String displayName) throws IOException {
String rejected = rejectionReason(tmpDir); String rejected = rejectionReason(tmpDir);
if (rejected != null) throw new IllegalArgumentException(context.getString(R.string.turnip_not_adrenotools, rejected)); if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected);
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json")); JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
String name = meta != null ? meta.optString("name", "") : ""; String name = meta != null ? meta.optString("name", "") : "";
@@ -246,31 +245,31 @@ public final class TurnipDriver {
* Why a just-extracted zip is not something adrenotools can be pointed at, or null when it is. * Why a just-extracted zip is not something adrenotools can be pointed at, or null when it is.
* The kinds refused by name are the other driver lists' zips, which carry a meta.json too. * The kinds refused by name are the other driver lists' zips, which carry a meta.json too.
*/ */
private String rejectionReason(File dir) { private static String rejectionReason(File dir) {
File metaFile = new File(dir, "meta.json"); File metaFile = new File(dir, "meta.json");
if (!metaFile.isFile()) return context.getString(R.string.turnip_reject_no_meta); if (!metaFile.isFile()) return "no meta.json";
String libraryName, kind; String libraryName, kind;
try { try {
JSONObject meta = new JSONObject(FileUtils.readString(metaFile)); JSONObject meta = new JSONObject(FileUtils.readString(metaFile));
libraryName = meta.optString("libraryName", ""); libraryName = meta.optString("libraryName", "");
kind = meta.optString("kind", ""); kind = meta.optString("kind", "");
} catch (Exception e) { } catch (Exception e) {
return context.getString(R.string.turnip_reject_meta_unreadable, e.getMessage()); return "meta.json is unreadable (" + e.getMessage() + ")";
} }
if ("linux-vulkan-icd".equals(kind)) if ("linux-vulkan-icd".equals(kind))
return context.getString(R.string.turnip_reject_linux_driver); return "this is a Linux runtime driver (import it under \"Linux runtime driver\")";
if ("wayland-game-driver".equals(kind)) if ("wayland-game-driver".equals(kind))
return context.getString(R.string.turnip_reject_wayland); return "this is a Wayland game driver, which this app has no use for";
if (libraryName.isEmpty()) if (libraryName.isEmpty())
return context.getString(R.string.turnip_reject_no_library_name); return "meta.json names no libraryName, so nothing could be handed to AdrenoTools";
File library = new File(dir, libraryName); File library = new File(dir, libraryName);
if (!library.isFile()) if (!library.isFile())
return context.getString(R.string.turnip_reject_library_missing, libraryName); return "meta.json names " + libraryName + ", which is not in the zip";
if (!LinuxVulkanDriverManager.isAarch64Elf(library)) if (!LinuxVulkanDriverManager.isAarch64Elf(library))
return context.getString(R.string.turnip_reject_not_aarch64, libraryName); return libraryName + " is not a 64-bit AArch64 ELF shared library";
// A glibc build that happens to carry a libraryName would load nothing in this process. // A glibc build that happens to carry a libraryName would load nothing in this process.
if (LinuxVulkanDriverManager.containsAscii(library, "libc.so.6")) if (LinuxVulkanDriverManager.containsAscii(library, "libc.so.6"))
return context.getString(R.string.turnip_reject_glibc, libraryName); return libraryName + " links glibc - a \"-Linux\" Turnip, which belongs under \"Linux runtime driver\"";
return null; return null;
} }
@@ -1,7 +1,6 @@
package com.droiddeck.launcher.gpu package com.droiddeck.launcher.gpu
import com.droiddeck.launcher.core.Hashes import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.R
import android.content.Context import android.content.Context
import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.core.FileUtils
import org.json.JSONArray import org.json.JSONArray
@@ -96,7 +95,7 @@ object TurnipReleases {
var lastError: Exception? = null var lastError: Exception? = null
for (src in SOURCES) { for (src in SOURCES) {
try { try {
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=15")) val releases = JSONArray(get("https://api.github.com/repos/${src.repo}/releases?per_page=15"))
val seen = HashSet<String>() val seen = HashSet<String>()
var newest: String? = null var newest: String? = null
for (i in 0 until releases.length()) { for (i in 0 until releases.length()) {
@@ -136,7 +135,7 @@ object TurnipReleases {
return parse(stored) return parse(stored)
} }
private fun get(context: Context, url: String): String { private fun get(url: String): String {
val c = URL(url).openConnection() as HttpURLConnection val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 15_000 c.connectTimeout = 15_000
c.readTimeout = 20_000 c.readTimeout = 20_000
@@ -144,8 +143,8 @@ object TurnipReleases {
c.setRequestProperty("User-Agent", "DroidDeck-app") c.setRequestProperty("User-Agent", "DroidDeck-app")
try { try {
val code = c.responseCode val code = c.responseCode
if (code == 403 || code == 429) throw IOException(context.getString(R.string.turnip_rate_limited)) if (code == 403 || code == 429) throw IOException("GitHub's rate limit was hit - try again later")
if (code != 200) throw IOException(context.getString(R.string.turnip_github_http, code)) if (code != 200) throw IOException("GitHub answered HTTP $code")
return c.inputStream.bufferedReader().use { it.readText() } return c.inputStream.bufferedReader().use { it.readText() }
} finally { } finally {
c.disconnect() c.disconnect()
@@ -195,7 +194,7 @@ object TurnipReleases {
/** Download an asset into the cache; the caller imports it and deletes the file. */ /** Download an asset into the cache; the caller imports it and deletes the file. */
fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File { fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File {
if (asset.sha256.isEmpty()) throw IOException(context.getString(R.string.turnip_list_predates_checksums)) if (asset.sha256.isEmpty()) throw IOException("This driver list predates checksums - refresh it and try again")
val target = File(context.cacheDir, asset.name) val target = File(context.cacheDir, asset.name)
val c = URL(asset.url).openConnection() as HttpURLConnection val c = URL(asset.url).openConnection() as HttpURLConnection
c.connectTimeout = 15_000 c.connectTimeout = 15_000
@@ -203,7 +202,7 @@ object TurnipReleases {
c.setRequestProperty("User-Agent", "DroidDeck-app") c.setRequestProperty("User-Agent", "DroidDeck-app")
c.instanceFollowRedirects = true c.instanceFollowRedirects = true
try { try {
if (c.responseCode != 200) throw IOException(context.getString(R.string.turnip_download_http, c.responseCode)) if (c.responseCode != 200) throw IOException("download answered HTTP ${c.responseCode}")
val total = c.contentLengthLong.takeIf { it > 0 } ?: asset.size val total = c.contentLengthLong.takeIf { it > 0 } ?: asset.size
c.inputStream.use { input -> c.inputStream.use { input ->
FileOutputStream(target).use { out -> FileOutputStream(target).use { out ->
@@ -221,7 +220,7 @@ object TurnipReleases {
} }
} }
if (!asset.sha256.equals(Hashes.sha256(target), ignoreCase = true)) { if (!asset.sha256.equals(Hashes.sha256(target), ignoreCase = true)) {
throw IOException(context.getString(R.string.turnip_checksum_mismatch)) throw IOException("Checksum mismatch - the download was discarded")
} }
return target return target
} catch (e: Exception) { } catch (e: Exception) {
@@ -24,18 +24,11 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.ui.DroidDeckTheme import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.onSignal import com.droiddeck.launcher.ui.onSignal
import com.droiddeck.launcher.ui.LocalPalette import com.droiddeck.launcher.ui.LocalPalette
class ControllerEditorActivity : ComponentActivity() { class ControllerEditorActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
private lateinit var controls: OnScreenControls private lateinit var controls: OnScreenControls
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
@@ -55,10 +48,10 @@ class ControllerEditorActivity : ComponentActivity() {
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), RoundedCornerShape(50)) .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), RoundedCornerShape(50))
.padding(start = 14.dp, end = 5.dp, top = 5.dp, bottom = 5.dp), .padding(start = 14.dp, end = 5.dp, top = 5.dp, bottom = 5.dp),
) { ) {
Text(stringResource(R.string.ctrl_editor_drag), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(end = 4.dp)) Text("Drag to move", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(end = 4.dp))
EditorButton(stringResource(R.string.ctrl_reset), false) { controls.resetLayout() } EditorButton("Reset", false) { controls.resetLayout() }
EditorButton(stringResource(R.string.common_cancel), false) { finish() } EditorButton("Cancel", false) { finish() }
EditorButton(stringResource(R.string.ctrl_editor_save), true) { EditorButton("Save", true) {
controls.saveLayout() controls.saveLayout()
finish() finish()
} }
@@ -1,21 +1,20 @@
package com.droiddeck.launcher.input package com.droiddeck.launcher.input
import android.content.Context import android.content.Context
import com.droiddeck.launcher.R
object ControllerPrefs { object ControllerPrefs {
const val STEAM_BLUE = 0xFF1A9FFF.toInt() const val STEAM_BLUE = 0xFF1A9FFF.toInt()
const val OFF = "off" const val OFF = "off"
val tints = listOf( val tints = listOf(
STEAM_BLUE to R.string.ctrl_tint_steam_blue, STEAM_BLUE to "Steam blue",
0xFF66C0F4.toInt() to R.string.ctrl_tint_sky, 0xFF66C0F4.toInt() to "Sky",
0xFFE8EEF4.toInt() to R.string.ctrl_tint_white, 0xFFE8EEF4.toInt() to "White",
0xFFC77DFF.toInt() to R.string.ctrl_tint_violet, 0xFFC77DFF.toInt() to "Violet",
0xFF3DDC84.toInt() to R.string.ctrl_tint_green, 0xFF3DDC84.toInt() to "Green",
0xFFFFA726.toInt() to R.string.ctrl_tint_amber, 0xFFFFA726.toInt() to "Amber",
0xFFFF5252.toInt() to R.string.ctrl_tint_red, 0xFFFF5252.toInt() to "Red",
0xFFFF6FB5.toInt() to R.string.ctrl_tint_pink, 0xFFFF6FB5.toInt() to "Pink",
) )
val opacities = listOf(40, 60, 80, 100) val opacities = listOf(40, 60, 80, 100)
@@ -23,17 +22,17 @@ object ControllerPrefs {
val sizes = listOf(80, 90, 100, 110, 125) val sizes = listOf(80, 90, 100, 110, 125)
val mappable = listOf( val mappable = listOf(
"a" to R.string.ctrl_button_a, "b" to R.string.ctrl_button_b, "x" to R.string.ctrl_button_x, "y" to R.string.ctrl_button_y, "a" to "A button", "b" to "B button", "x" to "X button", "y" to "Y button",
"lb" to R.string.ctrl_button_lb, "rb" to R.string.ctrl_button_rb, "lt" to R.string.ctrl_button_lt, "rt" to R.string.ctrl_button_rt, "lb" to "Left bumper", "rb" to "Right bumper", "lt" to "Left trigger", "rt" to "Right trigger",
"select" to R.string.ctrl_button_view, "start" to R.string.ctrl_button_menu, "select" to "View button", "start" to "Menu button",
) )
val targets = listOf( val targets = listOf(
"a" to R.string.ctrl_target_a, "b" to R.string.ctrl_target_b, "x" to R.string.ctrl_target_x, "y" to R.string.ctrl_target_y, "a" to "A", "b" to "B", "x" to "X", "y" to "Y",
"lb" to R.string.ctrl_target_lb, "rb" to R.string.ctrl_target_rb, "lt" to R.string.ctrl_target_lt, "rt" to R.string.ctrl_target_rt, "lb" to "LB", "rb" to "RB", "lt" to "LT", "rt" to "RT",
"l3" to R.string.ctrl_target_l3, "r3" to R.string.ctrl_target_r3, "select" to R.string.ctrl_target_view, "start" to R.string.ctrl_target_menu, "guide" to R.string.ctrl_target_steam, "l3" to "L3", "r3" to "R3", "select" to "View", "start" to "Menu", "guide" to "Steam",
"up" to R.string.ctrl_target_up, "down" to R.string.ctrl_target_down, "left" to R.string.ctrl_target_left, "right" to R.string.ctrl_target_right, "up" to "D-pad up", "down" to "D-pad down", "left" to "D-pad left", "right" to "D-pad right",
OFF to R.string.ctrl_target_hidden, OFF to "Hidden",
) )
class Settings( class Settings(
@@ -1,39 +0,0 @@
package com.droiddeck.launcher.input;
import java.io.File;
/**
* Where the fake input rings live and how the guest is told about them. Kept apart from
* {@link FakeInputWriter}, which loads native code, so it can be tested on the JVM.
*/
final class FakeInputRingPaths {
static final String RING_DIR_NAME = "fakeinput-rings";
private FakeInputRingPaths() {}
/** The rings sit beside the fake evdev nodes: session/dev/input -> session/dev/fakeinput-rings. */
static File ringDir(File fakeInputDir) {
if (fakeInputDir == null) {
return null;
}
File inputDir = fakeInputDir.getAbsoluteFile();
File parent = inputDir.getParentFile();
return new File(parent != null ? parent : inputDir, RING_DIR_NAME);
}
static File ringFile(File fakeInputDir, int slot) {
File ringDir = ringDir(fakeInputDir);
return ringDir != null ? new File(ringDir, "ring" + slot) : null;
}
/**
* The ring's path as the guest opens it. The session tree is bound into the guest at its own
* host path, spelled the way {@code Context.getFilesDir()} spells it (LinuxRuntime.binds), so
* the export has to use that same spelling. A canonical path is not that: where
* /data/user/0 is a link, or a separate mount, onto /data/data (ColorOS 16, #166) it resolves
* to a prefix nothing is bound at, and every pad, physical and on-screen, goes dead.
*/
static String exportPath(File ringFile) {
return ringFile.getAbsolutePath();
}
}
@@ -94,6 +94,7 @@ public class FakeInputWriter {
private static final int RING_SNAPSHOT_SEQ_OFFSET = 32; private static final int RING_SNAPSHOT_SEQ_OFFSET = 32;
private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40; private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40;
private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8] private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8]
private static final String RING_DIR_NAME = "fakeinput-rings";
// After the events - MUST match the block in fakeinput_steam.cpp (DeckImu): what a Deck has and // After the events - MUST match the block in fakeinput_steam.cpp (DeckImu): what a Deck has and
// an Xbox pad does not - motion, back grips, trackpads - in the Steam Deck controller's axes and // an Xbox pad does not - motion, back grips, trackpads - in the Steam Deck controller's axes and
// units, under a seqlock like the snapshot's. Only libfakeinput's Deck controller reads it. // units, under a seqlock like the snapshot's. Only libfakeinput's Deck controller reads it.
@@ -197,8 +198,26 @@ public class FakeInputWriter {
return builder.toString(); return builder.toString();
} }
private static File getRingDir(File fakeInputDir) {
if (fakeInputDir == null) {
return null;
}
File inputDir = fakeInputDir.getAbsoluteFile();
File parent = inputDir.getParentFile();
return new File(parent != null ? parent : inputDir, RING_DIR_NAME);
}
private static File getRingFile(File fakeInputDir, int slot) { private static File getRingFile(File fakeInputDir, int slot) {
return FakeInputRingPaths.ringFile(fakeInputDir, slot); File ringDir = getRingDir(fakeInputDir);
return ringDir != null ? new File(ringDir, "ring" + slot) : null;
}
private static String getCanonicalOrAbsolutePath(File file) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
return file.getAbsolutePath();
}
} }
private static void initializeRingHeader(ByteBuffer data) { private static void initializeRingHeader(ByteBuffer data) {
@@ -306,7 +325,7 @@ public class FakeInputWriter {
ringSlot.ringFile = ringFile.getAbsoluteFile(); ringSlot.ringFile = ringFile.getAbsoluteFile();
ringSlot.ringRaf = raf; ringSlot.ringRaf = raf;
ringSlot.ringChannel = channel; ringSlot.ringChannel = channel;
ringSlot.exportPath = FakeInputRingPaths.exportPath(ringFile); ringSlot.exportPath = getCanonicalOrAbsolutePath(ringFile);
Log.i(TAG, "Created fake input file ring for slot " + slot + ": " + ringSlot.exportPath); Log.i(TAG, "Created fake input file ring for slot " + slot + ": " + ringSlot.exportPath);
return ringSlot; return ringSlot;
} catch (IOException e) { } catch (IOException e) {
@@ -76,17 +76,6 @@ public final class PadBridge {
private final java.util.Set<Integer> seenDevices = new java.util.HashSet<>(); private final java.util.Set<Integer> seenDevices = new java.util.HashSet<>();
private int lastDeviceId = Integer.MIN_VALUE; private int lastDeviceId = Integer.MIN_VALUE;
/** No physical controller is driving the pad: nothing yet, or the on-screen controls were last. */
public static final int NO_CONTROLLER = -1;
/**
* The Android input device id of the physical controller that last drove the pad, or
* {@link #NO_CONTROLLER}. Every pad feeds the one exported slot, so this is how a game's rumble
* on that slot finds the motors in the player's hands (RumbleComponent).
*/
private static volatile int activeControllerId = NO_CONTROLLER;
public static int activeControllerId() { return activeControllerId; }
public PadBridge(File fakeInputDir) { public PadBridge(File fakeInputDir) {
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT); writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
} }
@@ -101,7 +90,6 @@ public final class PadBridge {
} }
public synchronized void stop() { public synchronized void stop() {
activeControllerId = NO_CONTROLLER;
systemGuidePressed = false; systemGuidePressed = false;
systemQamPressed = false; systemQamPressed = false;
qamChordActive = false; qamChordActive = false;
@@ -230,7 +218,6 @@ public final class PadBridge {
*/ */
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) { public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
mutation.accept(state); mutation.accept(state);
activeControllerId = NO_CONTROLLER;
notePlayerInput(); notePlayerInput();
statOnScreen++; statOnScreen++;
scheduleStats(); scheduleStats();
@@ -312,7 +299,6 @@ public final class PadBridge {
/** Per event, so the common case - the same pad as last time - is a single compare. */ /** Per event, so the common case - the same pad as last time - is a single compare. */
private void noteDevice(InputDevice device) { private void noteDevice(InputDevice device) {
activeControllerId = device.getId();
if (device.getId() == lastDeviceId) return; if (device.getId() == lastDeviceId) return;
lastDeviceId = device.getId(); lastDeviceId = device.getId();
statDevice = device.getName(); statDevice = device.getName();
@@ -2,16 +2,14 @@ package com.droiddeck.launcher.input
import android.hardware.display.DisplayManager import android.hardware.display.DisplayManager
import android.view.Display import android.view.Display
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
/** The control surface shown on a secondary Android display during a Linux session. */ /** The control surface shown on a secondary Android display during a Linux session. */
enum class SecondScreenMode(val id: String, @StringRes val label: Int) { enum class SecondScreenMode(val id: String, val label: String) {
NONE("none", R.string.second_mode_none), NONE("none", "None"),
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad), KEYBOARD_TRACKPAD("keyboard-trackpad", "Keyboard + trackpad"),
TERMINAL("terminal", R.string.second_mode_terminal), TERMINAL("terminal", "Terminal"),
/** The Steam Deck controller's back grips and trackpads; offered while the pad is one. */ /** The Steam Deck controller's back grips and trackpads; offered while the pad is one. */
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls), DECK_CONTROLS("deck-controls", "Deck grips + trackpads"),
} }
data class SecondScreenDisplay(val id: Int, val label: String) data class SecondScreenDisplay(val id: Int, val label: String)
@@ -5,8 +5,6 @@ import android.graphics.BitmapFactory
import android.os.StatFs import android.os.StatFs
import android.system.Os import android.system.Os
import android.util.Log import android.util.Log
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.core.FileUtils
import java.io.File import java.io.File
import java.io.RandomAccessFile import java.io.RandomAccessFile
@@ -29,11 +27,6 @@ object AppImageManager {
val guestDir: String get() = "$GUEST_DIR/$id" val guestDir: String get() = "$GUEST_DIR/$id"
} }
/** Why a file cannot be imported: [text] with its [args]. */
internal class Problem(@StringRes val text: Int, vararg val args: Any) {
fun describe(context: Context): String = context.getString(text, *args)
}
private fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1)) private fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1))
fun list(context: Context): List<Item> = fun list(context: Context): List<Item> =
@@ -51,22 +44,22 @@ object AppImageManager {
* What is wrong with [file] as an AppImage for this device, or null when it can be imported. * What is wrong with [file] as an AppImage for this device, or null when it can be imported.
* An AppImage is an ELF program (its runtime) with "AI" and the format version at byte 8. * An AppImage is an ELF program (its runtime) with "AI" and the format version at byte 8.
*/ */
internal fun problem(file: File): Problem? { internal fun problem(file: File): String? {
if (!file.isFile) return Problem(R.string.user_apps_file_gone) if (!file.isFile) return "The file is gone"
val head = ByteArray(20) val head = ByteArray(20)
try { try {
RandomAccessFile(file, "r").use { if (it.read(head) < head.size) return Problem(R.string.appimg_too_small) } RandomAccessFile(file, "r").use { if (it.read(head) < head.size) return "The file is too small to be an AppImage" }
} catch (e: Exception) { } catch (e: Exception) {
return Problem(R.string.appimg_unreadable, e.message.toString()) return "The file cannot be read: ${e.message}"
} }
if (head[0] != 0x7f.toByte() || head[1] != 'E'.code.toByte() || head[2] != 'L'.code.toByte() || head[3] != 'F'.code.toByte()) { if (head[0] != 0x7f.toByte() || head[1] != 'E'.code.toByte() || head[2] != 'L'.code.toByte() || head[3] != 'F'.code.toByte()) {
return Problem(R.string.appimg_not_linux) return "This is not an AppImage (it is not a Linux program)"
} }
val machine = (head[18].toInt() and 0xff) or ((head[19].toInt() and 0xff) shl 8) val machine = (head[18].toInt() and 0xff) or ((head[19].toInt() and 0xff) shl 8)
return when { return when {
machine != LinuxFex.ELF_AARCH64 && !LinuxFex.isX86(machine) -> Problem(R.string.appimg_wrong_arch) machine != LinuxFex.ELF_AARCH64 && !LinuxFex.isX86(machine) -> "This AppImage is built for neither ARM64 (aarch64) nor x86 PCs"
head[8] != 'A'.code.toByte() || head[9] != 'I'.code.toByte() -> Problem(R.string.appimg_not_appimage) head[8] != 'A'.code.toByte() || head[9] != 'I'.code.toByte() -> "This is a Linux program but not an AppImage"
head[10].toInt() != 2 -> Problem(R.string.appimg_wrong_type, head[10].toInt()) head[10].toInt() != 2 -> "Only type 2 AppImages can be imported (this one is type ${head[10].toInt()})"
else -> null else -> null
} }
} }
@@ -90,12 +83,12 @@ object AppImageManager {
fun import( fun import(
context: Context, file: File, name: String?, icon: File?, meta: Map<String, String> = emptyMap(), onProgress: (String) -> Unit, context: Context, file: File, name: String?, icon: File?, meta: Map<String, String> = emptyMap(), onProgress: (String) -> Unit,
): String? { ): String? {
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required) if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
problem(file)?.let { return it.describe(context) } problem(file)?.let { return it }
val base = root(context).apply { mkdirs() } val base = root(context).apply { mkdirs() }
// Room for the image while it is extracted, and the extracted tree (about the same again). // Room for the image while it is extracted, and the extracted tree (about the same again).
if (StatFs(base.path).availableBytes < file.length() * 3) { if (StatFs(base.path).availableBytes < file.length() * 3) {
return context.getString(R.string.appimg_no_space_import, FileUtils.sizeToString(file.length() * 3)) return "Not enough free space: importing needs about ${FileUtils.sizeToString(file.length() * 3)}"
} }
val dir = File(base, idFor(name ?: file.name, base.list()?.toSet() ?: emptySet())) val dir = File(base, idFor(name ?: file.name, base.list()?.toSet() ?: emptySet()))
try { try {
@@ -110,17 +103,17 @@ object AppImageManager {
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "import ${file.name}", e) Log.e(TAG, "import ${file.name}", e)
FileUtils.delete(dir) FileUtils.delete(dir)
return e.message ?: context.getString(R.string.appimg_import_failed) return e.message ?: "Import failed"
} }
} }
/** Swaps the program of imported [id] for [file], keeping its name and icon; the old one stays if this fails. */ /** Swaps the program of imported [id] for [file], keeping its name and icon; the old one stays if this fails. */
fun replace(context: Context, id: String, file: File, meta: Map<String, String>, onProgress: (String) -> Unit): String? { fun replace(context: Context, id: String, file: File, meta: Map<String, String>, onProgress: (String) -> Unit): String? {
problem(file)?.let { return it.describe(context) } problem(file)?.let { return it }
val dir = dir(context, id) val dir = dir(context, id)
if (!File(dir, "app").isDirectory) return context.getString(R.string.appimg_gone) if (!File(dir, "app").isDirectory) return "That AppImage is gone"
if (StatFs(dir.path).availableBytes < file.length() * 3) { if (StatFs(dir.path).availableBytes < file.length() * 3) {
return context.getString(R.string.appimg_no_space_update, FileUtils.sizeToString(file.length() * 3)) return "Not enough free space: updating needs about ${FileUtils.sizeToString(file.length() * 3)}"
} }
return try { return try {
extract(context, dir, file, onProgress) ?: run { extract(context, dir, file, onProgress) ?: run {
@@ -130,7 +123,7 @@ object AppImageManager {
} }
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "replace $id", e) Log.e(TAG, "replace $id", e)
e.message ?: context.getString(R.string.appimg_update_failed) e.message ?: "Update failed"
} }
} }
@@ -142,10 +135,10 @@ object AppImageManager {
dir.mkdirs() dir.mkdirs()
// Copied in, not run where it lies: shared storage is mounted noexec, and proot's loader // Copied in, not run where it lies: shared storage is mounted noexec, and proot's loader
// maps a program executable. // maps a program executable.
onProgress(context.getString(R.string.user_apps_copying, file.name)) onProgress("Copying ${file.name}")
file.inputStream().use { input -> image.outputStream().use { FileUtils.copy(input, it) } } file.inputStream().use { input -> image.outputStream().use { FileUtils.copy(input, it) } }
image.setExecutable(true, false) image.setExecutable(true, false)
onProgress(context.getString(R.string.appimg_extracting, file.name)) onProgress("Extracting ${file.name}")
val unpack = if (LinuxFex.isX86(LinuxFex.elfMachine(image))) "${LinuxFex.TOOL} extract ./image.AppImage" val unpack = if (LinuxFex.isX86(LinuxFex.elfMachine(image))) "${LinuxFex.TOOL} extract ./image.AppImage"
else "./image.AppImage --appimage-extract || { rm -rf squashfs-root AppDir; ${LinuxFex.TOOL} extract ./image.AppImage; }" else "./image.AppImage --appimage-extract || { rm -rf squashfs-root AppDir; ${LinuxFex.TOOL} extract ./image.AppImage; }"
val out = StringBuilder() val out = StringBuilder()
@@ -159,8 +152,7 @@ object AppImageManager {
), logName = "appimage-import", linkDir = links) { line -> if (out.length < 2000) out.appendLine(line) } ), logName = "appimage-import", linkDir = links) { line -> if (out.length < 2000) out.appendLine(line) }
if (status != 0 || !File(dir, "app").isDirectory) { if (status != 0 || !File(dir, "app").isDirectory) {
listOf("squashfs-root", "AppDir").forEach { FileUtils.delete(File(dir, it)) } listOf("squashfs-root", "AppDir").forEach { FileUtils.delete(File(dir, it)) }
return out.lines().lastOrNull { it.isNotBlank() }?.let { context.getString(R.string.appimg_extract_failed_detail, it) } return "The AppImage could not be extracted" + (out.lines().lastOrNull { it.isNotBlank() }?.let { ": $it" } ?: "")
?: context.getString(R.string.appimg_extract_failed)
} }
copyLinkedFiles(File(dir, "app"), links) copyLinkedFiles(File(dir, "app"), links)
return null return null
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.Hashes import com.droiddeck.launcher.core.Hashes
import android.content.Context import android.content.Context
import android.util.Log import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.Downloader import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.core.ArchivePaths import com.droiddeck.launcher.core.ArchivePaths
@@ -25,17 +24,13 @@ object DeckyManager {
private const val VERSION = "root/homebrew/services/.droiddeck-decky-version" private const val VERSION = "root/homebrew/services/.droiddeck-decky-version"
private const val CEF_REMOTE_DEBUG_MARKER = "root/.local/share/Steam/.cef-enable-remote-debugging" private const val CEF_REMOTE_DEBUG_MARKER = "root/.local/share/Steam/.cef-enable-remote-debugging"
/** True while a plugin's remote binary downloads: what the UI branches on, not the stage's words. */
@Volatile var downloadingBinary = false
private set
data class Release(val tag: String, val prerelease: Boolean, val asset: String, val url: String, val digest: String?, val shaUrl: String?, val size: Long, val machine: Int) data class Release(val tag: String, val prerelease: Boolean, val asset: String, val url: String, val digest: String?, val shaUrl: String?, val size: Long, val machine: Int)
data class ReleaseChannels(val stable: List<Release>, val prerelease: List<Release>) data class ReleaseChannels(val stable: List<Release>, val prerelease: List<Release>)
fun installed(context: Context): String? { fun installed(context: Context): String? {
val loader = loader(context) val loader = loader(context)
if (!loader.isFile || !loader.canExecute()) return null if (!loader.isFile || !loader.canExecute()) return null
return File(LinuxRuntime.rootDir(context), VERSION).takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: context.getString(R.string.setup_installed) return File(LinuxRuntime.rootDir(context), VERSION).takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: "Installed"
} }
fun loader(context: Context) = File(LinuxRuntime.rootDir(context), PATH) fun loader(context: Context) = File(LinuxRuntime.rootDir(context), PATH)
@@ -107,40 +102,39 @@ object DeckyManager {
/** Downloads to a sibling temp file and atomically renames only after size, digest and ELF checks. */ /** Downloads to a sibling temp file and atomically renames only after size, digest and ELF checks. */
fun install(context: Context, release: Release, progress: (String, Int) -> Unit): String? { fun install(context: Context, release: Release, progress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_loader) if (SessionState.running) return "Stop the active session before installing Decky Loader"
val target = loader(context) val target = loader(context)
target.parentFile?.mkdirs() target.parentFile?.mkdirs()
val temp = File(target.parentFile, "PluginLoader.download") val temp = File(target.parentFile, "PluginLoader.download")
val downloading = context.getString(R.string.user_apps_downloading, release.tag) val ok = Downloader.downloadFile(release.url, temp, false) { f -> progress("Downloading ${release.tag}", if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }
val ok = Downloader.downloadFile(release.url, temp, false) { f -> progress(downloading, if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) } if (!ok) { temp.delete(); return "Decky Loader download failed" }
if (!ok) { temp.delete(); return context.getString(R.string.deckymgr_download_failed) } if (temp.length() != release.size) { temp.delete(); return "Decky Loader size did not match the release metadata" }
if (temp.length() != release.size) { temp.delete(); return context.getString(R.string.deckymgr_size_mismatch) }
val expected = release.digest?.substringAfter(':') ?: release.shaUrl?.let { checksumUrl -> val expected = release.digest?.substringAfter(':') ?: release.shaUrl?.let { checksumUrl ->
val checksumBody = Downloader.downloadString(checksumUrl) ?: run { temp.delete(); return context.getString(R.string.deckymgr_checksum_download_failed) } val checksumBody = Downloader.downloadString(checksumUrl) ?: run { temp.delete(); return "Could not download the release checksum" }
Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value
} ?: run { temp.delete(); return context.getString(R.string.deckymgr_checksum_missing) } } ?: run { temp.delete(); return "Release checksum is missing" }
if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return context.getString(R.string.deckymgr_checksum_invalid) } if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return "Release checksum is invalid" }
if (!expected.equals(Hashes.sha256(temp), true)) { temp.delete(); return context.getString(R.string.deckymgr_checksum_mismatch) } if (!expected.equals(Hashes.sha256(temp), true)) { temp.delete(); return "Decky Loader checksum mismatch" }
if (!validElf(temp, release.machine)) { temp.delete(); return context.getString(R.string.deckymgr_not_elf) } if (!validElf(temp, release.machine)) { temp.delete(); return "Release asset is not a compatible 64-bit Linux executable" }
if (SessionState.running) { temp.delete(); return context.getString(R.string.deckymgr_session_started_loader) } if (SessionState.running) { temp.delete(); return "A session started during the download; stop it before installing Decky Loader" }
if (!temp.setExecutable(true, false)) { temp.delete(); return context.getString(R.string.deckymgr_loader_not_executable) } if (!temp.setExecutable(true, false)) { temp.delete(); return "Could not mark PluginLoader executable" }
// Decky needs Steam's local CEF debugger only when its session supervisor is enabled. // Decky needs Steam's local CEF debugger only when its session supervisor is enabled.
val cefMarker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER) val cefMarker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
val cefReady = !supervisorEnabled(context) || cefMarker.isFile || runCatching { val cefReady = !supervisorEnabled(context) || cefMarker.isFile || runCatching {
cefMarker.parentFile?.mkdirs() cefMarker.parentFile?.mkdirs()
cefMarker.createNewFile() || cefMarker.isFile cefMarker.createNewFile() || cefMarker.isFile
}.getOrDefault(false) }.getOrDefault(false)
if (!cefReady) { temp.delete(); return context.getString(R.string.deckymgr_cef_failed) } if (!cefReady) { temp.delete(); return "Could not enable Steam CEF remote debugging" }
val staged = File(target.parentFile, "PluginLoader.new") val staged = File(target.parentFile, "PluginLoader.new")
staged.delete() staged.delete()
if (!temp.renameTo(staged)) { temp.delete(); return context.getString(R.string.deckymgr_stage_failed) } if (!temp.renameTo(staged)) { temp.delete(); return "Could not stage PluginLoader" }
val old = File(target.parentFile, "PluginLoader.old") val old = File(target.parentFile, "PluginLoader.old")
old.delete() old.delete()
if (target.exists() && !target.renameTo(old)) { staged.delete(); return context.getString(R.string.deckymgr_loader_preserve_failed) } if (target.exists() && !target.renameTo(old)) { staged.delete(); return "Could not preserve the existing PluginLoader" }
if (!staged.renameTo(target)) { if (!staged.renameTo(target)) {
if (old.exists()) old.renameTo(target) if (old.exists()) old.renameTo(target)
staged.delete() staged.delete()
return context.getString(R.string.deckymgr_loader_activate_failed) return "Could not activate the new PluginLoader"
} }
old.delete() old.delete()
File(target.parentFile, ".droiddeck-decky-version").writeText(release.tag + "\n") File(target.parentFile, ".droiddeck-decky-version").writeText(release.tag + "\n")
@@ -151,44 +145,43 @@ object DeckyManager {
/** Imports a Decky distribution ZIP into homebrew/plugins for the next Steam session. */ /** Imports a Decky distribution ZIP into homebrew/plugins for the next Steam session. */
fun installPluginZip(context: Context, archive: File, progress: (String, Int) -> Unit): String? { fun installPluginZip(context: Context, archive: File, progress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin) if (SessionState.running) return "Stop the active session before installing a plugin"
if (installed(context) == null) return context.getString(R.string.deckymgr_loader_required) if (installed(context) == null) return "Install Decky Loader before importing a plugin"
if (!archive.isFile || !archive.canRead()) return context.getString(R.string.deckymgr_zip_unreadable) if (!archive.isFile || !archive.canRead()) return "Could not read the selected ZIP file"
val plugins = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins") val plugins = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins")
if (!plugins.exists() && !plugins.mkdirs()) return context.getString(R.string.deckymgr_plugins_dir_failed) if (!plugins.exists() && !plugins.mkdirs()) return "Could not create the Decky plugins directory"
val staging = File(plugins, ".droiddeck-import-${UUID.randomUUID()}") val staging = File(plugins, ".droiddeck-import-${UUID.randomUUID()}")
val backupSuffix = ".droiddeck-backup-${UUID.randomUUID()}" val backupSuffix = ".droiddeck-backup-${UUID.randomUUID()}"
try { try {
staging.mkdirs() staging.mkdirs()
progress(context.getString(R.string.deckymgr_extracting_zip), -1) progress("Extracting plugin ZIP", -1)
extractPluginZip(context, archive, staging) extractPluginZip(archive, staging)
val roots = staging.listFiles()?.filter { it.isDirectory } ?: emptyList() val roots = staging.listFiles()?.filter { it.isDirectory } ?: emptyList()
if (roots.size != 1 || staging.listFiles()?.size != 1) return context.getString(R.string.deckymgr_zip_one_folder) if (roots.size != 1 || staging.listFiles()?.size != 1) return "Plugin ZIP must contain one top-level plugin folder"
val plugin = roots.single() val plugin = roots.single()
if (!File(plugin, "plugin.json").isFile || !File(plugin, "package.json").isFile || !File(plugin, "dist/index.js").isFile) { if (!File(plugin, "plugin.json").isFile || !File(plugin, "package.json").isFile || !File(plugin, "dist/index.js").isFile) {
return context.getString(R.string.deckymgr_zip_missing_files) return "Plugin ZIP is missing plugin.json, package.json, or dist/index.js"
} }
val name = JSONObject(File(plugin, "plugin.json").readText()).getString("name") val name = JSONObject(File(plugin, "plugin.json").readText()).getString("name")
require(name.isNotBlank()) { context.getString(R.string.deckymgr_plugin_name_missing) } require(name.isNotBlank()) { "Plugin name is missing" }
val metadata = JSONObject(File(plugin, "package.json").readText()) val metadata = JSONObject(File(plugin, "package.json").readText())
downloadRemoteBinaries(context, metadata, plugin, progress) downloadRemoteBinaries(metadata, plugin, progress)
if (SessionState.running) return context.getString(R.string.deckymgr_session_started_plugin) if (SessionState.running) return "A session started during installation; stop it before installing a plugin"
DeckyPluginInstall.activate(plugin, plugins, name, DeckyPluginInstall.activate(plugin, plugins, name,
File(plugins.parentFile, "settings/loader.json"), backupSuffix) File(plugins.parentFile, "settings/loader.json"), backupSuffix)
progress(context.getString(R.string.deckymgr_plugin_installed), 100) progress("Plugin installed · restart Steam to load it", 100)
return null return null
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "plugin ZIP import", e) Log.w(TAG, "plugin ZIP import", e)
if (e is DeckyPluginInstall.Failure) return context.getString(e.text) return e.message?.takeIf { it.isNotBlank() } ?: "Plugin ZIP installation failed"
return e.message?.takeIf { it.isNotBlank() } ?: context.getString(R.string.deckymgr_plugin_install_failed)
} finally { } finally {
staging.deleteRecursively() staging.deleteRecursively()
} }
} }
private fun extractPluginZip(context: Context, archive: File, destination: File) { private fun extractPluginZip(archive: File, destination: File) {
var totalBytes = 0L var totalBytes = 0L
var entries = 0 var entries = 0
val seen = HashSet<String>() val seen = HashSet<String>()
@@ -196,30 +189,30 @@ object DeckyManager {
while (true) { while (true) {
val entry = zip.nextEntry ?: break val entry = zip.nextEntry ?: break
entries++ entries++
require(entries <= 10_000) { context.getString(R.string.deckymgr_zip_too_many) } require(entries <= 10_000) { "Plugin ZIP contains too many entries" }
val relative = entry.name.replace('\\', '/') val relative = entry.name.replace('\\', '/')
require(relative.isNotBlank() && !relative.startsWith('/')) { context.getString(R.string.deckymgr_zip_invalid_path) } require(relative.isNotBlank() && !relative.startsWith('/')) { "Plugin ZIP contains an invalid path" }
require(seen.add(relative)) { context.getString(R.string.deckymgr_zip_duplicate_paths) } require(seen.add(relative)) { "Plugin ZIP contains duplicate paths" }
val output = ArchivePaths.inside(destination, relative) val output = ArchivePaths.inside(destination, relative)
?: throw IllegalArgumentException(context.getString(R.string.deckymgr_zip_unsafe_path)) ?: throw IllegalArgumentException("Plugin ZIP contains an unsafe path")
if (entry.isDirectory) { if (entry.isDirectory) {
require(output.mkdirs() || output.isDirectory) { context.getString(R.string.deckymgr_folder_failed) } require(output.mkdirs() || output.isDirectory) { "Could not create plugin folder" }
} else { } else {
require(output.parentFile?.let { it.mkdirs() || it.isDirectory } == true) { context.getString(R.string.deckymgr_folder_failed) } require(output.parentFile?.let { it.mkdirs() || it.isDirectory } == true) { "Could not create plugin folder" }
FileOutputStream(output).use { out -> FileOutputStream(output).use { out ->
val buffer = ByteArray(64 * 1024) val buffer = ByteArray(64 * 1024)
while (true) { while (true) {
val read = zip.read(buffer) val read = zip.read(buffer)
if (read < 0) break if (read < 0) break
totalBytes += read totalBytes += read
require(totalBytes <= MAX_PLUGIN_ZIP_BYTES) { context.getString(R.string.deckymgr_zip_too_large) } require(totalBytes <= MAX_PLUGIN_ZIP_BYTES) { "Plugin ZIP expands beyond the 1 GiB limit" }
out.write(buffer, 0, read) out.write(buffer, 0, read)
} }
} }
// Decky distributions place plugin executables under bin/. Java's ZIP reader // Decky distributions place plugin executables under bin/. Java's ZIP reader
// does not expose Unix mode bits, so restore execution on those payload files. // does not expose Unix mode bits, so restore execution on those payload files.
if (relative.split('/').dropLast(1).any { it == "bin" } && !output.setExecutable(true, false)) { if (relative.split('/').dropLast(1).any { it == "bin" } && !output.setExecutable(true, false)) {
throw IllegalStateException(context.getString(R.string.deckymgr_bundled_not_executable)) throw IllegalStateException("Could not mark bundled plugin binary executable")
} }
} }
zip.closeEntry() zip.closeEntry()
@@ -227,49 +220,42 @@ object DeckyManager {
} }
} }
private fun downloadRemoteBinaries(context: Context, metadata: JSONObject, plugin: File, progress: (String, Int) -> Unit) { private fun downloadRemoteBinaries(metadata: JSONObject, plugin: File, progress: (String, Int) -> Unit) {
val binaries = metadata.optJSONArray("remote_binary") ?: return val binaries = metadata.optJSONArray("remote_binary") ?: return
val bin = File(plugin, "bin") val bin = File(plugin, "bin")
for (i in 0 until binaries.length()) { for (i in 0 until binaries.length()) {
val binary = binaries.optJSONObject(i) ?: throw IllegalArgumentException(context.getString(R.string.deckymgr_remote_entry_invalid)) val binary = binaries.optJSONObject(i) ?: throw IllegalArgumentException("Invalid remote_binary entry")
val name = binary.optString("name") val name = binary.optString("name")
val url = binary.optString("url") val url = binary.optString("url")
val hash = binary.optString("sha256hash") val hash = binary.optString("sha256hash")
require(name.isNotBlank() && name != "." && name != ".." && !name.contains('/') && !name.contains('\\')) { context.getString(R.string.deckymgr_remote_name_invalid) } require(name.isNotBlank() && name != "." && name != ".." && !name.contains('/') && !name.contains('\\')) { "Invalid remote binary name" }
require(url.startsWith("https://")) { context.getString(R.string.deckymgr_remote_url_https) } require(url.startsWith("https://")) { "Remote binary URL must use HTTPS" }
require(hash.matches(Regex("(?i)[0-9a-f]{64}"))) { context.getString(R.string.deckymgr_remote_hash_invalid, name) } require(hash.matches(Regex("(?i)[0-9a-f]{64}"))) { "Remote binary $name has an invalid SHA-256 hash" }
require(bin.mkdirs() || bin.isDirectory) { context.getString(R.string.deckymgr_bin_dir_failed) } require(bin.mkdirs() || bin.isDirectory) { "Could not create plugin bin directory" }
val temp = File(bin, ".$name.download") val temp = File(bin, ".$name.download")
val downloading = context.getString(R.string.deckymgr_downloading_binary, name) progress("Downloading plugin binary · $name", -1)
downloadingBinary = true if (!Downloader.downloadFile(url, temp, false) { fraction ->
progress(downloading, -1) progress("Downloading plugin binary · $name", if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
val downloaded = try { }) {
Downloader.downloadFile(url, temp, false) { fraction ->
progress(downloading, if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
}
} finally {
downloadingBinary = false
}
if (!downloaded) {
temp.delete() temp.delete()
throw IllegalStateException(context.getString(R.string.deckymgr_binary_download_failed, name)) throw IllegalStateException("Could not download plugin binary $name")
} }
if (!hash.equals(Hashes.sha256(temp), ignoreCase = true)) { if (!hash.equals(Hashes.sha256(temp), ignoreCase = true)) {
temp.delete() temp.delete()
throw IllegalStateException(context.getString(R.string.deckymgr_binary_checksum_mismatch, name)) throw IllegalStateException("Plugin binary checksum mismatch · $name")
} }
if (!temp.setExecutable(true, false)) { if (!temp.setExecutable(true, false)) {
temp.delete() temp.delete()
throw IllegalStateException(context.getString(R.string.deckymgr_binary_not_executable, name)) throw IllegalStateException("Could not mark plugin binary executable · $name")
} }
val target = File(bin, name) val target = File(bin, name)
if (target.exists() && !target.delete()) { if (target.exists() && !target.delete()) {
temp.delete() temp.delete()
throw IllegalStateException(context.getString(R.string.deckymgr_binary_replace_failed, name)) throw IllegalStateException("Could not replace plugin binary · $name")
} }
if (!temp.renameTo(target)) { if (!temp.renameTo(target)) {
temp.delete() temp.delete()
throw IllegalStateException(context.getString(R.string.deckymgr_binary_install_failed, name)) throw IllegalStateException("Could not install plugin binary · $name")
} }
} }
} }
@@ -1,16 +1,11 @@
package com.droiddeck.launcher.runtime package com.droiddeck.launcher.runtime
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import java.io.File import java.io.File
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
/** Offline equivalent of Decky's identity-based replacement and loader settings update. */ /** Offline equivalent of Decky's identity-based replacement and loader settings update. */
internal object DeckyPluginInstall { internal object DeckyPluginInstall {
/** A failure the user is told about: [text] is its string resource. */
class Failure(@StringRes val text: Int) : IllegalStateException()
fun activate(staged: File, plugins: File, name: String, settingsFile: File, backupSuffix: String) { fun activate(staged: File, plugins: File, name: String, settingsFile: File, backupSuffix: String) {
val settings = if (settingsFile.exists()) JSONObject(settingsFile.readText()) else JSONObject() val settings = if (settingsFile.exists()) JSONObject(settingsFile.readText()) else JSONObject()
val existing = plugins.listFiles().orEmpty().filter { folder -> val existing = plugins.listFiles().orEmpty().filter { folder ->
@@ -19,7 +14,7 @@ internal object DeckyPluginInstall {
}.getOrDefault(false) }.getOrDefault(false)
} }
val target = File(plugins, staged.name) val target = File(plugins, staged.name)
if (target.exists() && target !in existing) throw Failure(R.string.deckymgr_folder_taken) require(!target.exists() || target in existing) { "Plugin folder belongs to another plugin" }
val order = settings.optJSONArray("pluginOrder") ?: JSONArray(plugins.listFiles().orEmpty() val order = settings.optJSONArray("pluginOrder") ?: JSONArray(plugins.listFiles().orEmpty()
.filter { it.isDirectory && !it.name.startsWith(".droiddeck-") } .filter { it.isDirectory && !it.name.startsWith(".droiddeck-") }
.mapNotNull { runCatching { JSONObject(File(it, "plugin.json").readText()).getString("name") }.getOrNull() } .mapNotNull { runCatching { JSONObject(File(it, "plugin.json").readText()).getString("name") }.getOrNull() }
@@ -39,15 +34,15 @@ internal object DeckyPluginInstall {
pending.writeText(settings.toString(4)) pending.writeText(settings.toString(4))
for (old in existing) { for (old in existing) {
val backup = File(plugins, ".droiddeck-backup-${old.name}$backupSuffix") val backup = File(plugins, ".droiddeck-backup-${old.name}$backupSuffix")
if (!old.renameTo(backup)) throw Failure(R.string.deckymgr_preserve_failed) check(old.renameTo(backup)) { "Could not preserve the existing plugin" }
backups.add(old to backup) backups.add(old to backup)
} }
if (!staged.renameTo(target)) throw Failure(R.string.deckymgr_activate_failed) check(staged.renameTo(target)) { "Could not activate the imported plugin" }
activated = true activated = true
if (!pending.renameTo(settingsFile)) throw Failure(R.string.deckymgr_settings_failed) check(pending.renameTo(settingsFile)) { "Could not update Decky plugin settings" }
} catch (error: Exception) { } catch (error: Exception) {
if (activated) target.deleteRecursively() if (activated) target.deleteRecursively()
for ((old, backup) in backups.asReversed()) if (!backup.renameTo(old)) throw Failure(R.string.deckymgr_restore_failed) for ((old, backup) in backups.asReversed()) check(backup.renameTo(old)) { "Could not restore the existing plugin" }
throw error throw error
} finally { } finally {
pending.delete() pending.delete()
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.Hashes import com.droiddeck.launcher.core.Hashes
import android.content.Context import android.content.Context
import android.util.Log import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.Downloader import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.core.FileUtils
import org.json.JSONObject import org.json.JSONObject
@@ -82,21 +81,20 @@ object DesktopCatalog {
/** Downloads, verifies and installs one package. Returns null on success, else a message. */ /** Downloads, verifies and installs one package. Returns null on success, else a message. */
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? { fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val root = LinuxRuntime.rootDir(context) val root = LinuxRuntime.rootDir(context)
if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing) if (!root.isDirectory) return "The Linux runtime is not installed"
// Every catalog row carries a sha256; one without is refused rather than trusted. // Every catalog row carries a sha256; one without is refused rather than trusted.
if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name) if (entry.sha256.isEmpty()) return "The catalog has no checksum for ${entry.name}"
val download = File(context.cacheDir, "pkg-${entry.id}.download") val download = File(context.cacheDir, "pkg-${entry.id}.download")
try { try {
val downloading = context.getString(R.string.user_apps_downloading, entry.name) listener?.onProgress("Downloading ${entry.name}", 0)
listener?.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, 0)
val ok = Downloader.downloadFile(entry.url, download, true) { f -> val ok = Downloader.downloadFile(entry.url, download, true) { f ->
listener?.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, if (f < 0) -1 else Math.round(f * 100f)) listener?.onProgress("Downloading ${entry.name}", if (f < 0) -1 else Math.round(f * 100f))
} }
if (!ok) return context.getString(R.string.user_apps_download_failed) if (!ok) return "Download failed"
listener?.onProgress(LinuxRuntimeInstaller.Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1) listener?.onProgress("Verifying", -1)
val actual = Hashes.sha256(download) val actual = Hashes.sha256(download)
if (!entry.sha256.equals(actual, ignoreCase = true)) return context.getString(R.string.deskpkg_checksum_mismatch) if (!entry.sha256.equals(actual, ignoreCase = true)) return "Checksum mismatch - nothing was changed"
listener?.onProgress(context.getString(R.string.deskpkg_installing, entry.name), -1) listener?.onProgress("Installing ${entry.name}", -1)
when (entry.kind) { when (entry.kind) {
"appimage" -> { "appimage" -> {
val dir = File(root, "opt/appimages").apply { mkdirs() } val dir = File(root, "opt/appimages").apply { mkdirs() }
@@ -104,20 +102,20 @@ object DesktopCatalog {
// Some projects zip the AppImage (melonDS); the one file inside is what we want. // Some projects zip the AppImage (melonDS); the one file inside is what we want.
val placed = if (entry.url.endsWith(".zip", ignoreCase = true)) unzipAppImage(download, target) val placed = if (entry.url.endsWith(".zip", ignoreCase = true)) unzipAppImage(download, target)
else download.renameTo(target) else download.renameTo(target)
if (!placed) return context.getString(R.string.deskpkg_place_failed) if (!placed) return "Could not place the AppImage"
target.setExecutable(true, false) target.setExecutable(true, false)
FileUtils.writeString(File(root, "usr/share/applications/droiddeck-${entry.id}.desktop"), FileUtils.writeString(File(root, "usr/share/applications/droiddeck-${entry.id}.desktop"),
"[Desktop Entry]\nType=Application\nName=${entry.name}\n" + "[Desktop Entry]\nType=Application\nName=${entry.name}\n" +
"Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/${entry.id}.AppImage\n" + "Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/${entry.id}.AppImage\n" +
"Icon=${entry.icon}\nTerminal=false\nCategories=${entry.category};\n") "Icon=${entry.icon}\nTerminal=false\nCategories=${entry.category};\n")
} }
else -> if (!LinuxRuntimeInstaller.extract(context, download, root, listener)) return context.getString(R.string.deskpkg_extract_failed) else -> if (!LinuxRuntimeInstaller.extract(download, root, listener)) return "Extraction failed"
} }
FileUtils.writeString(marker(context, entry.id), entry.version) FileUtils.writeString(marker(context, entry.id), entry.version)
return null return null
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "install ${entry.id}", e) Log.e(TAG, "install ${entry.id}", e)
return e.message ?: context.getString(R.string.deskpkg_install_failed) return e.message ?: "Install failed"
} finally { } finally {
download.delete() download.delete()
} }
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.runtime
import android.content.Context import android.content.Context
import android.util.Log import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.core.FileUtils
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
@@ -103,7 +102,7 @@ object FlatpakManager {
/** Puts Flatpak into the runtime and adds Flathub. Null on success, else what went wrong. */ /** Puts Flatpak into the runtime and adds Flathub. Null on success, else what went wrong. */
fun setup(context: Context, onProgress: (String, Int) -> Unit): String? { fun setup(context: Context, onProgress: (String, Int) -> Unit): String? {
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required) if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
return exclusive("setup") { return exclusive("setup") {
var failure: String? = null var failure: String? = null
val status = runGuest(context, listOf("/bin/bash", SETUP), fakeRoot = true) { line -> val status = runGuest(context, listOf("/bin/bash", SETUP), fakeRoot = true) { line ->
@@ -115,11 +114,11 @@ object FlatpakManager {
} }
when { when {
failure != null -> failure failure != null -> failure
status != 0 -> context.getString(R.string.flatpakmgr_setup_failed, status) status != 0 -> "Flatpak setup failed (exit $status)"
!ready(context) -> context.getString(R.string.flatpakmgr_setup_unfinished) !ready(context) -> "Flatpak setup did not finish"
else -> null else -> null
} }
} ?: context.getString(R.string.flatpakmgr_busy) } ?: "Another store task is running"
} }
/** /**
@@ -127,61 +126,51 @@ object FlatpakManager {
* an overall percentage across the steps Flatpak plans (a runtime, its extensions, the app). * an overall percentage across the steps Flatpak plans (a runtime, its extensions, the app).
*/ */
private fun transaction(context: Context, verb: String, id: String?, onProgress: (String, Int) -> Unit): String? { private fun transaction(context: Context, verb: String, id: String?, onProgress: (String, Int) -> Unit): String? {
if (!ready(context)) return context.getString(R.string.flatpakmgr_not_ready) if (!ready(context)) return "Set up Flatpak first"
return exclusive("$verb:${id ?: "all"}") { return exclusive("$verb:${id ?: "all"}") {
var error: String? = null var error: String? = null
// Progress lines carry no ref; they belong to the step the last "op" line started. // Progress lines carry no ref; they belong to the step the last "op" line started.
var step = context.getString(R.string.flatpakmgr_starting) var step = "Starting"
val argv = listOfNotNull("/usr/bin/python3", HELPER, verb, id) val argv = listOfNotNull("/usr/bin/python3", HELPER, verb, id)
val status = runGuest(context, argv, fakeRoot = false) { line -> val status = runGuest(context, argv, fakeRoot = false) { line ->
val o = runCatching { JSONObject(line) }.getOrNull() val o = runCatching { JSONObject(line) }.getOrNull()
if (o == null) { Log.i(TAG, "$verb: $line"); return@runGuest } if (o == null) { Log.i(TAG, "$verb: $line"); return@runGuest }
when (o.optString("e")) { when (o.optString("e")) {
"op" -> { step = stage(context, o); onProgress(step, overall(o, 0)) } "op" -> { step = stage(o); onProgress(step, overall(o, 0)) }
"progress" -> onProgress(step, overall(o, o.optInt("percent"))) "progress" -> onProgress(step, overall(o, o.optInt("percent")))
"error" -> { error = o.optString("message"); Log.w(TAG, "$verb $id: $error") } "error" -> { error = o.optString("message"); Log.w(TAG, "$verb $id: $error") }
"warning" -> Log.w(TAG, "$verb $id: ${o.optString("message")}") "warning" -> Log.w(TAG, "$verb $id: ${o.optString("message")}")
} }
} }
error ?: if (status != 0) context.getString(R.string.flatpakmgr_exit_status, status) else null error ?: if (status != 0) "Flatpak exited with status $status" else null
} ?: context.getString(R.string.flatpakmgr_busy) } ?: "Another store task is running"
} }
private fun stage(context: Context, o: JSONObject): String { private fun stage(o: JSONObject): String {
val ref = o.optString("ref") val ref = o.optString("ref")
if (ref.isEmpty()) return o.optString("status").ifEmpty { context.getString(R.string.setup_check_busy) } val name = refLabel(ref)
val name = refLabel(ref) { id, args -> context.getString(id, *args) } val step = if (o.optInt("n") > 1) " (${o.optInt("i")}/${o.optInt("n")})" else ""
val n = o.optInt("n") return when (o.optString("kind")) {
val kind = o.optString("kind") "uninstall" -> "Removing $name$step"
return if (n > 1) context.getString(when (kind) { "update" -> "Updating $name$step"
"uninstall" -> R.string.flatpakmgr_removing_step else -> "Installing $name$step"
"update" -> R.string.flatpakmgr_updating_step }.let { if (ref.isEmpty()) o.optString("status").ifEmpty { "Working" } else it }
else -> R.string.flatpakmgr_installing_step
}, name, o.optInt("i"), n)
else context.getString(when (kind) {
"uninstall" -> R.string.flatpakmgr_removing
"update" -> R.string.flatpakmgr_updating
else -> R.string.flatpakmgr_installing
}, name)
} }
/** /** A ref in words: "app/org.supertuxproject.SuperTux/aarch64/stable" is "SuperTux". */
* A ref in words: "app/org.supertuxproject.SuperTux/aarch64/stable" is "SuperTux". [text] internal fun refLabel(ref: String): String {
* resolves a string resource with its arguments.
*/
internal fun refLabel(ref: String, text: (Int, Array<out Any>) -> String): String {
val parts = ref.split('/') val parts = ref.split('/')
val id = parts.getOrNull(1) ?: return ref val id = parts.getOrNull(1) ?: return ref
if (parts.firstOrNull() == "app") return id.substringAfterLast('.') if (parts.firstOrNull() == "app") return id.substringAfterLast('.')
val branch = parts.getOrNull(3) val branch = parts.getOrNull(3)?.let { " $it" } ?: ""
return when { return when {
id.endsWith(".Locale") -> text(R.string.flatpakmgr_ref_translations, emptyArray()) id.endsWith(".Locale") -> "translations"
".GL." in id || ".GL32." in id -> text(R.string.flatpakmgr_ref_graphics_drivers, emptyArray()) ".GL." in id || ".GL32." in id -> "graphics drivers"
"codecs" in id.lowercase() || id.endsWith(".ffmpeg-full") -> text(R.string.flatpakmgr_ref_media_codecs, emptyArray()) "codecs" in id.lowercase() || id.endsWith(".ffmpeg-full") -> "media codecs"
id.endsWith(".Platform") -> when (val vendor = id.removeSuffix(".Platform").substringAfterLast('.')) { id.endsWith(".Platform") -> when (val vendor = id.removeSuffix(".Platform").substringAfterLast('.')) {
"gnome", "kde" -> vendor.uppercase() "gnome", "kde" -> vendor.uppercase()
else -> vendor.replaceFirstChar { it.uppercase() } else -> vendor.replaceFirstChar { it.uppercase() }
}.let { if (branch != null) text(R.string.flatpakmgr_ref_runtime_branch, arrayOf(it, branch)) else text(R.string.flatpakmgr_ref_runtime, arrayOf(it)) } } + " runtime$branch"
else -> id.substringAfterLast('.') else -> id.substringAfterLast('.')
} }
} }
@@ -1,74 +0,0 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.core.AppLanguage
import java.io.File
import java.util.Locale
/**
* Fonts for every script the app's languages (and Steam's) are written in.
*
* The runtime ships DejaVu and Adwaita only, which have no Chinese, Japanese, Korean or Thai, so
* Steam drew those as boxes (#118, #206). Android already carries Noto for all of them in
* /system/fonts; the guest gets that folder read-only at [GUEST_DIR], where fontconfig finds it
* with the rest of /usr/share/fonts. Nothing is downloaded and the runtime is not changed.
*
* One CJK font holds Chinese, Japanese and Korean under one set of characters, and a character
* they share is drawn the way the chosen region writes it. [preferenceConf] puts that region's
* variant first, after DejaVu, which stays the font for Latin text.
*/
object GuestFonts {
const val HOST_DIR = "/system/fonts"
const val GUEST_DIR = "/usr/share/fonts/android"
/** Rewritten at every session start, so it follows the language picked in Setup. */
const val CONF = "etc/fonts/conf.d/65-droiddeck-language.conf"
/** The bind spec for Android's fonts, or null on a device without the folder. */
@JvmStatic
fun bindSpec(): String? = File(HOST_DIR).takeIf { it.isDirectory }?.let { "${it.path}:$GUEST_DIR" }
/** Writes the guest's font preference for the app's current language; best effort. */
@JvmStatic
fun prepare(context: Context, root: File) {
val conf = File(root, CONF)
val text = preferenceConf(AppLanguage.effective(context))
try {
if (conf.isFile && conf.readText() == text) return
conf.parentFile?.mkdirs()
conf.writeText(text)
} catch (e: Exception) {
// fontconfig still finds every font; shared characters just take its own default shape.
}
}
/** The CJK variant whose shapes match how [locale]'s readers write shared characters. */
fun cjkRegion(locale: Locale): String {
val script = locale.script
return when (locale.language) {
"ja" -> "JP"
"ko" -> "KR"
"zh" -> when {
script == "Hans" -> "SC"
locale.country == "HK" || locale.country == "MO" -> "HK"
script == "Hant" || locale.country == "TW" -> "TC"
else -> "SC"
}
else -> "SC"
}
}
fun preferenceConf(locale: Locale): String {
val region = cjkRegion(locale)
fun alias(generic: String, latin: String, cjk: String) =
" <alias binding=\"same\">\n <family>$generic</family>\n <prefer>\n" +
" <family>$latin</family>\n <family>$cjk $region</family>\n" +
" </prefer>\n </alias>\n"
return "<?xml version=\"1.0\"?>\n<!DOCTYPE fontconfig SYSTEM \"urn:fontconfig:fonts.dtd\">\n" +
"<!-- Written by DroidDeck at session start for its language (${locale.toLanguageTag()}). -->\n" +
"<fontconfig>\n" +
alias("sans-serif", "DejaVu Sans", "Noto Sans CJK") +
alias("serif", "DejaVu Serif", "Noto Serif CJK") +
alias("monospace", "DejaVu Sans Mono", "Noto Sans Mono CJK") +
"</fontconfig>\n"
}
}
@@ -270,13 +270,6 @@ public final class LinuxRuntime {
if (extraBinds != null) { if (extraBinds != null) {
for (String spec : extraBinds) bind(cmd, spec); for (String spec : extraBinds) bind(cmd, spec);
} }
// Android's fonts, for the scripts the runtime's own fonts lack (GuestFonts). Last, so a
// fast path that keeps only its first binds drops these before a game library.
String fonts = GuestFonts.bindSpec();
if (fonts != null) {
bind(cmd, fonts);
GuestFonts.prepare(context, root);
}
List<String> specs = new ArrayList<>(); List<String> specs = new ArrayList<>();
for (int i = 0; i + 1 < cmd.size(); i += 2) specs.add(cmd.get(i + 1)); for (int i = 0; i + 1 < cmd.size(); i += 2) specs.add(cmd.get(i + 1));
return specs; return specs;
@@ -4,7 +4,6 @@ import android.content.Context;
import android.util.Log; import android.util.Log;
import com.droiddeck.launcher.R;
import com.droiddeck.launcher.core.ArchivePaths; import com.droiddeck.launcher.core.ArchivePaths;
import com.droiddeck.launcher.core.Downloader; import com.droiddeck.launcher.core.Downloader;
import com.droiddeck.launcher.core.Hashes; import com.droiddeck.launcher.core.Hashes;
@@ -45,17 +44,9 @@ public final class LinuxRuntimeInstaller {
private static final String VERSION_FILE = ".version"; private static final String VERSION_FILE = ".version";
/** What a stage is doing, for code that branches on it rather than on its (translated) words. */
public enum Step { DOWNLOADING, VERIFYING, OTHER }
public interface ProgressListener { public interface ProgressListener {
/** {@code percent} is -1 while the size is unknown. */ /** {@code percent} is -1 while the size is unknown. */
void onProgress(String stage, int percent); void onProgress(String stage, int percent);
/** The same with its {@link Step}; a listener that branches on the step overrides this one. */
default void onProgress(Step step, String stage, int percent) {
onProgress(stage, percent);
}
} }
public static final class Release { public static final class Release {
@@ -80,12 +71,11 @@ public final class LinuxRuntimeInstaller {
private static final class Job { private static final class Job {
final CopyOnWriteArrayList<ProgressListener> listeners = new CopyOnWriteArrayList<>(); final CopyOnWriteArrayList<ProgressListener> listeners = new CopyOnWriteArrayList<>();
final CountDownLatch done = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1);
volatile String stage; volatile String stage = "Starting\u2026";
volatile Step step = Step.OTHER;
volatile int percent = -1; volatile int percent = -1;
volatile boolean ok; volatile boolean ok;
final boolean removal; final boolean removal;
Job(boolean removal, String stage) { this.removal = removal; this.stage = stage; } Job(boolean removal) { this.removal = removal; }
} }
private static final Object JOB_LOCK = new Object(); private static final Object JOB_LOCK = new Object();
@@ -141,23 +131,16 @@ public final class LinuxRuntimeInstaller {
synchronized (JOB_LOCK) { synchronized (JOB_LOCK) {
if (running != null && running.removal) return false; if (running != null && running.removal) return false;
owner = running == null; owner = running == null;
if (owner) { running = new Job(false, context.getString(R.string.user_apps_starting)); removalError = null; } if (owner) { running = new Job(false); removalError = null; }
job = running; job = running;
if (listener != null) job.listeners.add(listener); if (listener != null) job.listeners.add(listener);
} }
if (!owner) return join(job, listener); if (!owner) return join(job, listener);
try { try {
job.ok = installOnce(context.getApplicationContext(), release, new ProgressListener() { job.ok = installOnce(context.getApplicationContext(), release, (stage, percent) -> {
@Override public void onProgress(String stage, int percent) { job.stage = stage;
onProgress(Step.OTHER, stage, percent); job.percent = percent;
} for (ProgressListener l : job.listeners) l.onProgress(stage, percent);
@Override public void onProgress(Step step, String stage, int percent) {
job.step = step;
job.stage = stage;
job.percent = percent;
for (ProgressListener l : job.listeners) l.onProgress(step, stage, percent);
}
}); });
return job.ok; return job.ok;
} finally { } finally {
@@ -209,7 +192,7 @@ public final class LinuxRuntimeInstaller {
private static boolean join(Job job, ProgressListener listener) { private static boolean join(Job job, ProgressListener listener) {
try { try {
if (listener != null) listener.onProgress(job.step, job.stage, job.percent); if (listener != null) listener.onProgress(job.stage, job.percent);
job.done.await(); job.done.await();
return job.ok; return job.ok;
} catch (InterruptedException e) { } catch (InterruptedException e) {
@@ -226,14 +209,13 @@ public final class LinuxRuntimeInstaller {
// A failed/interrupted explicit removal must finish before a fresh installation. // A failed/interrupted explicit removal must finish before a fresh installation.
// Its quarantined home is not user data to carry into an update. // Its quarantined home is not user data to carry into an update.
File pendingRemoval = removalDirectory(LinuxRuntime.rootDir(context)); File pendingRemoval = removalDirectory(LinuxRuntime.rootDir(context));
if (pendingRemoval.exists() && listener != null) listener.onProgress(context.getString(R.string.rtinst_removing_leftovers), -1); if (pendingRemoval.exists() && listener != null) listener.onProgress("Removing runtime leftovers", -1);
RuntimeFileTree.delete(pendingRemoval, null); RuntimeFileTree.delete(pendingRemoval, null);
String downloading = context.getString(R.string.rtinst_downloading); if (listener != null) listener.onProgress("Downloading", 0);
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
// Downloader reports a 0..1 fraction, or -1 while the total size is unknown. // Downloader reports a 0..1 fraction, or -1 while the total size is unknown.
boolean ok = Downloader.downloadFile(release.url, archive, true, (fraction) -> { boolean ok = Downloader.downloadFile(release.url, archive, true, (fraction) -> {
if (listener != null) { if (listener != null) {
listener.onProgress(Step.DOWNLOADING, downloading, listener.onProgress("Downloading",
fraction < 0 ? -1 : Math.round(fraction * 100f)); fraction < 0 ? -1 : Math.round(fraction * 100f));
} }
}); });
@@ -242,7 +224,7 @@ public final class LinuxRuntimeInstaller {
return false; return false;
} }
if (listener != null) listener.onProgress(Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1); if (listener != null) listener.onProgress("Verifying", -1);
String actual = Hashes.sha256(archive); String actual = Hashes.sha256(archive);
if (!release.sha256.equalsIgnoreCase(actual)) { if (!release.sha256.equalsIgnoreCase(actual)) {
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual); Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
@@ -257,8 +239,8 @@ public final class LinuxRuntimeInstaller {
recoverInterruptedSwap(root, staging, old); recoverInterruptedSwap(root, staging, old);
RuntimeFileTree.delete(staging, null); RuntimeFileTree.delete(staging, null);
if (!staging.mkdirs()) return false; if (!staging.mkdirs()) return false;
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1); if (listener != null) listener.onProgress("Extracting", -1);
if (!extract(context, archive, staging, listener)) { if (!extract(archive, staging, listener)) {
RuntimeFileTree.delete(staging, null); RuntimeFileTree.delete(staging, null);
return false; return false;
} }
@@ -325,35 +307,30 @@ public final class LinuxRuntimeInstaller {
if (com.droiddeck.launcher.session.SessionState.INSTANCE.getRunning()) return null; if (com.droiddeck.launcher.session.SessionState.INSTANCE.getRunning()) return null;
com.droiddeck.launcher.session.SessionPhase phase = com.droiddeck.launcher.session.SessionState.INSTANCE.getPhase(); com.droiddeck.launcher.session.SessionPhase phase = com.droiddeck.launcher.session.SessionState.INSTANCE.getPhase();
if (phase != com.droiddeck.launcher.session.SessionPhase.IDLE && phase != com.droiddeck.launcher.session.SessionPhase.FAILED) return null; if (phase != com.droiddeck.launcher.session.SessionPhase.IDLE && phase != com.droiddeck.launcher.session.SessionPhase.FAILED) return null;
return beginUninstall(context.getApplicationContext(), LinuxRuntime.rootDir(context)); return beginUninstall(LinuxRuntime.rootDir(context));
} }
/** {@code app} words the progress; unit tests pass null and get none. */ static Removal beginUninstall(File root) {
static Removal beginUninstall(Context app, File root) {
synchronized (JOB_LOCK) { synchronized (JOB_LOCK) {
if (running != null) return null; if (running != null) return null;
removalError = null; removalError = null;
running = new Job(true, text(app, R.string.rtinst_removing)); running = new Job(true);
return new Removal(app, root, running); running.stage = "Removing Linux runtime";
return new Removal(root, running);
} }
} }
private static String text(Context app, int id) {
return app == null ? "" : app.getString(id);
}
public static final class Removal { public static final class Removal {
private final Context app;
private final File root; private final File root;
private final Job job; private final Job job;
private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean(); private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean();
private Removal(Context app, File root, Job job) { this.app = app; this.root = root; this.job = job; } private Removal(File root, Job job) { this.root = root; this.job = job; }
public boolean run(ProgressListener listener) { public boolean run(ProgressListener listener) {
if (!started.compareAndSet(false, true)) return join(job, listener); if (!started.compareAndSet(false, true)) return join(job, listener);
if (listener != null) job.listeners.add(listener); if (listener != null) job.listeners.add(listener);
try { try {
report(text(app, R.string.rtinst_removing), -1); report("Removing Linux runtime", -1);
final long[] removed = {0}; final long[] removed = {0};
final long[] lastShown = {0}; final long[] lastShown = {0};
java.util.function.LongConsumer progress = ignored -> { java.util.function.LongConsumer progress = ignored -> {
@@ -361,8 +338,7 @@ public final class LinuxRuntimeInstaller {
long now = System.nanoTime(); long now = System.nanoTime();
if (removed[0] == 1 || now - lastShown[0] >= 200_000_000L) { if (removed[0] == 1 || now - lastShown[0] >= 200_000_000L) {
lastShown[0] = now; lastShown[0] = now;
report(app == null ? "" : app.getResources().getQuantityString( report("Removing Linux runtime · " + removed[0] + " entries", -1);
R.plurals.rtinst_removing_entries, (int) Math.min(removed[0], Integer.MAX_VALUE), removed[0]), -1);
} }
}; };
File pending = removalDirectory(root); File pending = removalDirectory(root);
@@ -379,10 +355,10 @@ public final class LinuxRuntimeInstaller {
RuntimeFileTree.delete(new File(root.getParentFile(), root.getName() + ".old"), progress); RuntimeFileTree.delete(new File(root.getParentFile(), root.getName() + ".old"), progress);
RuntimeFileTree.delete(pending, progress); RuntimeFileTree.delete(pending, progress);
job.ok = true; job.ok = true;
report(text(app, R.string.rtinst_removed), 100); report("Linux runtime removed", 100);
return true; return true;
} catch (IOException e) { } catch (IOException e) {
removalError = text(app, R.string.rtinst_removal_failed); removalError = "Could not finish removing the Linux runtime. Retry removal in Setup.";
Log.w(TAG, "runtime removal incomplete", e); Log.w(TAG, "runtime removal incomplete", e);
report(removalError, -1); report(removalError, -1);
return false; return false;
@@ -404,9 +380,8 @@ public final class LinuxRuntimeInstaller {
* empty file instead of its link target is a rootfs that boots to nothing. Symlinks, hard * empty file instead of its link target is a rootfs that boots to nothing. Symlinks, hard
* links and the executable bit are all carried over here. * links and the executable bit are all carried over here.
*/ */
public static boolean extract(Context context, File archive, File destination, ProgressListener listener) { public static boolean extract(File archive, File destination, ProgressListener listener) {
long entries = 0; long entries = 0;
String extracting = context.getString(R.string.rtinst_extracting);
try (InputStream in = new ZstdCompressorInputStream( try (InputStream in = new ZstdCompressorInputStream(
new BufferedInputStream(new FileInputStream(archive), 1 << 16)); new BufferedInputStream(new FileInputStream(archive), 1 << 16));
TarArchiveInputStream tar = new TarArchiveInputStream(in)) { TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
@@ -457,7 +432,7 @@ public final class LinuxRuntimeInstaller {
continue; // device nodes and fifos: the runtime binds the real ones continue; // device nodes and fifos: the runtime binds the real ones
} }
if (++entries % 2000 == 0 && listener != null) { if (++entries % 2000 == 0 && listener != null) {
listener.onProgress(extracting, -1); listener.onProgress("Extracting", -1);
} }
} }
return true; return true;
@@ -22,15 +22,12 @@ import com.droiddeck.launcher.R
* two gets there first. * two gets there first.
*/ */
class RuntimeInstallService : Service() { class RuntimeInstallService : Service() {
override fun attachBaseContext(newBase: android.content.Context) =
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(newBase))
override fun onBind(intent: Intent?): IBinder? = null override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val removal = intent?.action == ACTION_REMOVE val removal = intent?.action == ACTION_REMOVE
val release = intent?.let(::releaseFrom) val release = intent?.let(::releaseFrom)
startForeground(NOTIFICATION_ID, notification(getString(if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1)) startForeground(NOTIFICATION_ID, notification(if (removal) "Removing Linux runtime" else "Starting…", -1))
if (release == null && !removal) { if (release == null && !removal) {
stopSelf(startId) stopSelf(startId)
return START_NOT_STICKY return START_NOT_STICKY
@@ -56,9 +53,9 @@ class RuntimeInstallService : Service() {
private fun notification(stage: String, percent: Int): Notification { private fun notification(stage: String, percent: Int): Notification {
val manager = getSystemService(NotificationManager::class.java) val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime), manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Linux runtime",
NotificationManager.IMPORTANCE_LOW).apply { NotificationManager.IMPORTANCE_LOW).apply {
description = getString(R.string.rtinst_channel_description) description = "Shows while the Linux runtime is installed or removed"
setShowBadge(false) setShowBadge(false)
setSound(null, null) setSound(null, null)
enableVibration(false) enableVibration(false)
@@ -68,7 +65,7 @@ class RuntimeInstallService : Service() {
PendingIntent.FLAG_IMMUTABLE) PendingIntent.FLAG_IMMUTABLE)
return Notification.Builder(this, CHANNEL_ID) return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session) .setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(getString(if (LinuxRuntimeInstaller.isRemoving()) R.string.rtinst_title_removing else R.string.rtinst_title_installing)) .setContentTitle(if (LinuxRuntimeInstaller.isRemoving()) "Removing the Linux runtime" else "Installing the Linux runtime")
.setContentText(stage) .setContentText(stage)
.setProgress(100, percent.coerceIn(0, 100), percent < 0) .setProgress(100, percent.coerceIn(0, 100), percent < 0)
.setContentIntent(open) .setContentIntent(open)
@@ -14,7 +14,7 @@ import kotlin.math.abs
* The client reads `/sys/class/power_supply/BAT<n>/...` - a laptop's or a Deck's naming and files * The client reads `/sys/class/power_supply/BAT<n>/...` - a laptop's or a Deck's naming and files
* (`energy_now`, `power_now`, `time_to_empty_now`, a `uevent` of `POWER_SUPPLY_*` lines). Android * (`energy_now`, `power_now`, `time_to_empty_now`, a `uevent` of `POWER_SUPPLY_*` lines). Android
* names its supply `battery` and lays it out differently, and on many phones an app may not read * names its supply `battery` and lays it out differently, and on many phones an app may not read
* it at all, so the client showed no battery. This writes one `BAT1` (the Deck's name) * it at all, so the client showed no battery. This writes a `BAT0` (and a `BAT1`, the Deck's name)
* from Android's own battery API - the same on every device - into a directory the session binds * from Android's own battery API - the same on every device - into a directory the session binds
* over `/sys/class/power_supply`, refreshed every few seconds while the session runs. * over `/sys/class/power_supply`, refreshed every few seconds while the session runs.
* *
@@ -31,8 +31,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
private var thread: Thread? = null private var thread: Thread? = null
override fun start() { override fun start() {
// Older builds exported the same aggregate battery twice; MangoHud counts both supplies.
File(dir, "BAT0").deleteRecursively()
running = true running = true
write() write()
thread = Thread({ thread = Thread({
@@ -41,7 +39,7 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
if (running) write() if (running) write()
} }
}, "battery-sysfs").apply { isDaemon = true; start() } }, "battery-sysfs").apply { isDaemon = true; start() }
Log.i(TAG, "battery: BAT1 written to ${dir.path} every ${PERIOD_MS / 1000} s") Log.i(TAG, "battery: BAT0/BAT1 written to ${dir.path} every ${PERIOD_MS / 1000} s")
} }
override fun stop() { override fun stop() {
@@ -89,7 +87,7 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
pct <= 15 -> "Low" pct <= 15 -> "Low"
else -> "Normal" else -> "Normal"
} }
for (name in listOf("BAT1")) { for (name in listOf("BAT0", "BAT1")) {
val bat = File(dir, name).apply { mkdirs() } val bat = File(dir, name).apply { mkdirs() }
val attrs = linkedMapOf( val attrs = linkedMapOf(
"type" to "Battery", "type" to "Battery",
@@ -1,7 +1,6 @@
package com.droiddeck.launcher.session package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.Hashes import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.R
import android.content.Context import android.content.Context
import android.util.Log import android.util.Log
import com.droiddeck.launcher.core.Downloader import com.droiddeck.launcher.core.Downloader
@@ -248,13 +247,12 @@ object ComponentsManager {
Regex("\\(([^)]+)\\)").find(text)?.groupValues?.get(1) ?: text.split(Regex("\\s+")).last() Regex("\\(([^)]+)\\)").find(text)?.groupValues?.get(1) ?: text.split(Regex("\\s+")).last()
}.getOrDefault("") }.getOrDefault("")
/** The FEX build's version name; [unnamed] when its DLL carries none, "" when there is no FEX. */ private fun fexVersion(dir: File): String {
private fun fexVersion(dir: File, unnamed: String = "FEX (build without a version name)"): String {
val dll = File(dir, FEX_FILES[0]) val dll = File(dir, FEX_FILES[0])
if (!dll.isFile) return "" if (!dll.isFile) return ""
val text = runCatching { String(dll.readBytes(), Charsets.ISO_8859_1) }.getOrDefault("") val text = runCatching { String(dll.readBytes(), Charsets.ISO_8859_1) }.getOrDefault("")
return Regex("FEX-\\d{4}(?:\\.\\d+)?(?:-\\d+-g[0-9a-f]{6,})?").findAll(text).map { it.value }.maxByOrNull { it.length } return Regex("FEX-\\d{4}(?:\\.\\d+)?(?:-\\d+-g[0-9a-f]{6,})?").findAll(text).map { it.value }.maxByOrNull { it.length }
?: unnamed ?: "FEX (build without a version name)"
} }
private fun compFiles(dir: File, comp: String): List<String> { private fun compFiles(dir: File, comp: String): List<String> {
@@ -275,24 +273,23 @@ object ComponentsManager {
private inline fun <T> readWcp(f: File, block: (TarArchiveInputStream) -> T): T = private inline fun <T> readWcp(f: File, block: (TarArchiveInputStream) -> T): T =
TarArchiveInputStream(ZstdInputStream(BufferedInputStream(FileInputStream(f), 1 shl 16))).use(block) TarArchiveInputStream(ZstdInputStream(BufferedInputStream(FileInputStream(f), 1 shl 16))).use(block)
private fun readProfile(context: Context, f: File): JSONObject = readWcp(f) { tar -> private fun readProfile(f: File): JSONObject = readWcp(f) { tar ->
while (true) { while (true) {
val e = tar.nextTarEntry ?: break val e = tar.nextTarEntry ?: break
if (!e.isDirectory && normalize(e.name) == "profile.json") return@readWcp JSONObject(tar.readBytes().decodeToString()) if (!e.isDirectory && normalize(e.name) == "profile.json") return@readWcp JSONObject(tar.readBytes().decodeToString())
} }
throw IllegalArgumentException(context.getString(R.string.cmgr_no_profile, f.name)) throw IllegalArgumentException("no profile.json in ${f.name}")
} }
private fun packageInfo(context: Context, f: File): Package { private fun packageInfo(f: File): Package {
val prof = readProfile(context, f) val prof = readProfile(f)
val comp = TYPES[prof.optString("type")] val comp = TYPES[prof.optString("type")] ?: throw IllegalArgumentException("${f.name} is not a Linux component package (type ${prof.optString("type")})")
?: throw IllegalArgumentException(context.getString(R.string.cmgr_not_component_package, f.name, prof.optString("type")))
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length()) return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
} }
fun packages(context: Context): List<Package> = packagesDir(context).listFiles() fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
?.filter { it.isFile && it.name.endsWith(".wcp") }?.sortedBy { it.name } ?.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() } ?.mapNotNull { f -> runCatching { packageInfo(f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
?: emptyList() ?: emptyList()
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */ /** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
@@ -365,7 +362,7 @@ object ComponentsManager {
return versions.flatMap { v -> return versions.flatMap { v ->
COMPONENTS.mapNotNull { comp -> COMPONENTS.mapNotNull { comp ->
val f = File(v, "$comp.wcp") val f = File(v, "$comp.wcp")
if (!f.isFile) null else Original(comp, v.name, runCatching { readProfile(context, f).optString("description") }.getOrDefault(""), f.length()) if (!f.isFile) null else Original(comp, v.name, runCatching { readProfile(f).optString("description") }.getOrDefault(""), f.length())
} }
} }
} }
@@ -417,24 +414,24 @@ object ComponentsManager {
val syncPacks = EsyncPacks.status(root(context)) val syncPacks = EsyncPacks.status(root(context))
val views = protons(context).map { p -> val views = protons(context).map { p ->
val comps = COMPONENTS.associateWith { comp -> val comps = COMPONENTS.associateWith { comp ->
val detected = if (comp == "fex") fexVersion(p.dir, context.getString(R.string.cmgr_fex_unnamed)) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version")) val detected = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
val detail = if (comp == "fex") context.getString(if (File(p.dir, FEX_FILES[2]).isFile) R.string.cmgr_fex_linux_helpers else R.string.cmgr_fex_dlls_only) else "" val detail = if (comp == "fex") (if (File(p.dir, FEX_FILES[2]).isFile) "with Linux helpers" else "DLLs only") else ""
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp) val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
val inUseLabel = when { val inUseLabel = when {
active == null -> context.getString(R.string.comp_tag_original) active == null -> "Original"
active.optString("protonVersion") != p.version -> context.getString(R.string.cmgr_original_proton_updated) active.optString("protonVersion") != p.version -> "Original (Proton updated since the last swap)"
else -> { else -> {
val want = active.optJSONObject("files") ?: JSONObject() val want = active.optJSONObject("files") ?: JSONObject()
val fp = fingerprint(p.dir, comp) val fp = fingerprint(p.dir, comp)
if (want.keys().asSequence().all { fp[it] == want.optString(it) }) originalLabel(context, active) ?: active.optString("label", active.optString("file")) if (want.keys().asSequence().all { fp[it] == want.optString(it) }) active.optString("label", active.optString("file"))
else context.getString(R.string.cmgr_changed_outside) else "Changed outside Components"
} }
} }
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp) val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
Component( Component(
detected.ifEmpty { context.getString(R.string.cmgr_not_present) }, detail, inUseLabel, detected.ifEmpty { "not present" }, detail, inUseLabel,
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version }, active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
q?.let { originalLabel(context, it) ?: it.optString("label") }, q?.optString("label"),
) )
} }
ProtonView(p, comps, originals(context, p.id), gameRunning(context, p), reapplied[p.dir.name] ?: 0, syncPacks.tool(p.guestPath)) ProtonView(p, comps, originals(context, p.id), gameRunning(context, p), reapplied[p.dir.name] ?: 0, syncPacks.tool(p.guestPath))
@@ -442,16 +439,6 @@ object ComponentsManager {
Snapshot(views, packages(context)) Snapshot(views, packages(context))
} }
/**
* The label of a chosen or queued original, in the app's language: the stored "label" was written
* in English when it was chosen. Null for a package, whose label is its version.
*/
private fun originalLabel(context: Context, entry: JSONObject): String? = when {
entry.optString("kind") == "original" -> context.getString(R.string.cmgr_original_version, entry.optString("protonVersion"))
entry.optString("file").startsWith("original ") -> context.getString(R.string.cmgr_original_from, entry.optString("file").removePrefix("original "))
else -> null
}
// ------------------------------------------------------------------ launch-time enforcement // ------------------------------------------------------------------ launch-time enforcement
/** /**
@@ -520,17 +507,17 @@ object ComponentsManager {
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) { fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
val p = proton(context, protonId) val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file)) val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp) val info = packageInfo(wcp)
val state = loadState(context) val state = loadState(context)
if (inUse(context, p)) { if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)) state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
saveState(context, state) saveState(context, state)
return context.getString(R.string.cmgr_swap_queued, LABEL[info.comp], info.version, p.name) return "${LABEL[info.comp]} ${info.version} goes into ${p.name} when the game running on it closes."
} }
applyPackage(context, p, info, wcp, state) applyPackage(context, p, info, wcp, state)
state.sub("queued").optJSONObject(p.id)?.remove(info.comp) state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
saveState(context, state) saveState(context, state)
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name) "${LABEL[info.comp]} ${info.version} is now in ${p.name}. It applies the next time a game starts."
} }
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) { private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
@@ -546,17 +533,17 @@ object ComponentsManager {
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) { fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
val p = proton(context, protonId) val p = proton(context, protonId)
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp") val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(wcp.isFile) { context.getString(R.string.cmgr_original_missing) } check(wcp.isFile) { "That original bundle is not stored" }
val state = loadState(context) val state = loadState(context)
if (inUse(context, p)) { if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(comp, JSONObject().put("kind", "original").put("protonVersion", protonVersion).put("label", "Original $protonVersion")) state.sub("queued").sub(p.id).put(comp, JSONObject().put("kind", "original").put("protonVersion", protonVersion).put("label", "Original $protonVersion"))
saveState(context, state) saveState(context, state)
return context.getString(R.string.cmgr_restore_queued, LABEL[comp], p.name) return "${LABEL[comp]} of ${p.name} goes back to its original when the game running on it closes."
} }
applyOriginal(context, p, comp, protonVersion, wcp, state) applyOriginal(context, p, comp, protonVersion, wcp, state)
state.sub("queued").optJSONObject(p.id)?.remove(comp) state.sub("queued").optJSONObject(p.id)?.remove(comp)
saveState(context, state) saveState(context, state)
context.getString(R.string.cmgr_restore_done, LABEL[comp], p.name, protonVersion) "${LABEL[comp]} of ${p.name} restored from its $protonVersion original."
} }
private fun applyOriginal(context: Context, p: Proton, comp: String, protonVersion: String, wcp: File, state: JSONObject) { private fun applyOriginal(context: Context, p: Proton, comp: String, protonVersion: String, wcp: File, state: JSONObject) {
@@ -588,7 +575,7 @@ object ComponentsManager {
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state) applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
} else { } else {
val wcp = File(packagesDir(context), q.optString("file")) val wcp = File(packagesDir(context), q.optString("file"))
applyPackage(context, p, packageInfo(context, wcp), wcp, state) applyPackage(context, p, packageInfo(wcp), wcp, state)
} }
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}" done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) } }.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
@@ -612,27 +599,27 @@ object ComponentsManager {
val active = state.sub("active") val active = state.sub("active")
for (pid in active.keys()) { for (pid in active.keys()) {
val comps = active.optJSONObject(pid) ?: continue val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) } for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { "$name is in use in $pid. Swap that Proton to something else first." }
} }
val f = File(packagesDir(context), name) val f = File(packagesDir(context), name)
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) } check(f.isFile) { "$name is not stored" }
f.delete() f.delete()
context.getString(R.string.cmgr_deleted, name) "Deleted $name."
} }
fun deleteOriginal(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) { fun deleteOriginal(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
val p = proton(context, protonId) val p = proton(context, protonId)
check(safeName(p.version) != protonVersion) { context.getString(R.string.cmgr_original_kept) } check(safeName(p.version) != protonVersion) { "The installed build's original is kept: it is the way back." }
val f = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp") val f = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(f.isFile) { context.getString(R.string.cmgr_not_stored) } check(f.isFile) { "Not stored" }
f.delete() f.delete()
f.parentFile?.takeIf { it.listFiles().isNullOrEmpty() }?.delete() f.parentFile?.takeIf { it.listFiles().isNullOrEmpty() }?.delete()
context.getString(R.string.cmgr_deleted_original, protonVersion, LABEL[comp]) "Deleted the $protonVersion original of ${LABEL[comp]}."
} }
/** Imports a -linux .wcp from anywhere the app can read (the file picker hands over a copy). */ /** Imports a -linux .wcp from anywhere the app can read (the file picker hands over a copy). */
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) { fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
val info = packageInfo(context, source) val info = packageInfo(source)
val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" }) val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" })
source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest) source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest)
info.copy(file = dest.name) info.copy(file = dest.name)
@@ -675,14 +662,14 @@ object ComponentsManager {
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */ /** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package { fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { context.getString(R.string.cmgr_nightlies_only) } require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { "Downloads come only from the Nightlies releases" }
require(Hashes.isGithubSha256(item.digest)) { context.getString(R.string.cmgr_list_predates_checksums) } require(Hashes.isGithubSha256(item.digest)) { "This package list predates checksums - refresh it and try again" }
val dest = File(packagesDir(context), safeName(item.file)) val dest = File(packagesDir(context), safeName(item.file))
val part = File(dest.parentFile, dest.name + ".part") val part = File(dest.parentFile, dest.name + ".part")
part.delete() part.delete()
check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { context.getString(R.string.user_apps_download_failed) } check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { "Download failed" }
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error(context.getString(R.string.cmgr_checksum_mismatch)) } if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error("Checksum mismatch") }
val info = runCatching { packageInfo(context, part) }.getOrElse { part.delete(); throw it } val info = runCatching { packageInfo(part) }.getOrElse { part.delete(); throw it }
synchronized(lock) { part.renameTo(dest) } synchronized(lock) { part.renameTo(dest) }
return info.copy(file = dest.name) return info.copy(file = dest.name)
} }
@@ -49,6 +49,7 @@ object EsyncPacks {
private const val TOOLS = "tools.tsv" private const val TOOLS = "tools.tsv"
private const val FLOOR = "floor" private const val FLOOR = "floor"
private const val PACK_FAILURES = "packFailures" private const val PACK_FAILURES = "packFailures"
private const val PROGRESS_LABEL = "Fetching droiddeck-esync pack"
private const val INDEX_LIMIT = 4L shl 20 private const val INDEX_LIMIT = 4L shl 20
private const val SIG_LIMIT = 4096L private const val SIG_LIMIT = 4096L
private const val ASSET_LIMIT = 256L shl 20 private const val ASSET_LIMIT = 256L shl 20
@@ -617,15 +618,14 @@ object EsyncPacks {
return false return false
} }
try { try {
val label = context.getString(com.droiddeck.launcher.R.string.esync_fetching) onProgress?.invoke(PROGRESS_LABEL, -1)
onProgress?.invoke(label, -1)
var reported = -1 var reported = -1
val fetched = FileOutputStream(part).use { output -> val fetched = FileOutputStream(part).use { output ->
fetch(entry.asset.url, entry.asset.size, output) { done -> fetch(entry.asset.url, entry.asset.size, output) { done ->
val percent = (done * 100 / entry.asset.size).toInt().coerceIn(0, 100) val percent = (done * 100 / entry.asset.size).toInt().coerceIn(0, 100)
if (percent != reported) { if (percent != reported) {
reported = percent reported = percent
onProgress?.invoke(label, percent) onProgress?.invoke(PROGRESS_LABEL, percent)
} }
} }
} }
@@ -1,8 +1,6 @@
package com.droiddeck.launcher.session package com.droiddeck.launcher.session
import android.content.Context
import android.os.Environment import android.os.Environment
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.frontend.Library
import java.io.BufferedInputStream import java.io.BufferedInputStream
import java.io.BufferedOutputStream import java.io.BufferedOutputStream
@@ -27,12 +25,9 @@ import java.util.zip.ZipOutputStream
* Ported from Bannerlator's GameSaveBackup and SaveLocator. * Ported from Bannerlator's GameSaveBackup and SaveLocator.
*/ */
object GameSaves { object GameSaves {
enum class Layout(val app: String, val rootPrefix: String, val user: String) { enum class Layout(val label: String, val rootPrefix: String, val user: String) {
GAMEHUB("GameHub", "/drive_c/", "steamuser"), GAMEHUB("GameHub zip", "/drive_c/", "steamuser"),
WINLATOR("Winlator", "drive_c/", "xuser"); WINLATOR("Winlator zip", "drive_c/", "xuser"),
/** "GameHub zip", in the app's language. */
fun label(context: Context): String = context.getString(R.string.saves_layout_zip, app)
} }
/** A game, its prefix, and the save folders found in it. */ /** A game, its prefix, and the save folders found in it. */
@@ -132,12 +127,12 @@ object GameSaves {
* Zips the game's saves into [dir] as "<Game>_<date>.zip" in [layout]. The found save folders when * Zips the game's saves into [dir] as "<Game>_<date>.zip" in [layout]. The found save folders when
* there are any, else the whole steamuser profile minus Temp and crash dumps. Returns the zip. * there are any, else the whole steamuser profile minus Temp and crash dumps. Returns the zip.
*/ */
fun export(context: Context, game: Game, layout: Layout, dir: File): Pair<File, Int> { fun export(game: Game, layout: Layout, dir: File): Pair<File, Int> {
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name)) val prefix = game.prefix ?: error("${game.game.name} has not been launched yet")
dir.mkdirs() dir.mkdirs()
val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip") val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip")
val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out) val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out)
if (count == 0) { out.delete(); error(context.getString(R.string.saves_none_found, game.game.name)) } if (count == 0) { out.delete(); error("No save files found for ${game.game.name}") }
return out to count return out to count
} }
@@ -167,11 +162,11 @@ object GameSaves {
* profile holds now into Download/DroidDeck/Saves/backups. Entries outside drive_c, launcher * profile holds now into Download/DroidDeck/Saves/backups. Entries outside drive_c, launcher
* shortcuts and anything escaping drive_c are skipped. Returns (files written, backup or null). * shortcuts and anything escaping drive_c are skipped. Returns (files written, backup or null).
*/ */
fun import(context: Context, game: Game, zip: File): Pair<Int, File?> { fun import(game: Game, zip: File): Pair<Int, File?> {
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name)) val prefix = game.prefix ?: error("${game.game.name} has not been launched yet")
val driveC = File(prefix, "drive_c") val driveC = File(prefix, "drive_c")
if (!driveC.isDirectory) error(context.getString(R.string.saves_not_launched, game.game.name)) if (!driveC.isDirectory) error("${game.game.name} has not been launched yet")
if (!looksLikeSaveZip(zip)) error(context.getString(R.string.saves_not_save_zip, zip.name)) if (!looksLikeSaveZip(zip)) error("${zip.name} has no drive_c folder, so it isn't a GameHub or Winlator save zip")
backupsDir().mkdirs() backupsDir().mkdirs()
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip") val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip")
@@ -4,7 +4,6 @@ import android.content.Context
import android.os.Environment import android.os.Environment
import android.os.StatFs import android.os.StatFs
import android.os.storage.StorageManager import android.os.storage.StorageManager
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.core.FileUtils
import java.io.File import java.io.File
@@ -18,8 +17,7 @@ import java.io.File
* slowly (intro movies, big asset loads); internal stays the default and the dialog says so. * slowly (intro movies, big asset loads); internal stays the default and the dialog says so.
*/ */
object GameStorage { object GameStorage {
/** A library root: [label] as the menu lists it (a volume with its free space), [name] alone. */ class Option(val label: String, val path: String)
class Option(val label: String, val path: String, val name: String = label)
/** Every removable volume, as its app folder, with the free space it has. */ /** Every removable volume, as its app folder, with the free space it has. */
fun options(context: Context): List<Option> { fun options(context: Context): List<Option> {
@@ -28,8 +26,8 @@ object GameStorage {
val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false } val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false }
if (!removable) return@mapNotNull null if (!removable) return@mapNotNull null
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null } val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: context.getString(R.string.gstore_sd_card) val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: "SD card"
Option(context.getString(R.string.gstore_volume_free, name, free(dir)), File(dir, "steam").absolutePath, name) Option("$name · ${free(dir)} free", File(dir, "steam").absolutePath)
} }
} }
@@ -43,15 +41,15 @@ object GameStorage {
* Makes [path] a library root the session can bind - the folder and its steamapps/ - and proves * Makes [path] a library root the session can bind - the folder and its steamapps/ - and proves
* it writable. Returns why it cannot be used, or null when it can. * it writable. Returns why it cannot be used, or null when it can.
*/ */
fun prepare(context: Context, path: String): String? { fun prepare(path: String): String? {
val root = File(path) val root = File(path)
val steamapps = File(root, "steamapps") val steamapps = File(root, "steamapps")
if (!steamapps.isDirectory && !steamapps.mkdirs()) return context.getString(R.string.gstore_cannot_create, path) if (!steamapps.isDirectory && !steamapps.mkdirs()) return "cannot create folders in $path"
val probe = File(steamapps, ".writable") val probe = File(steamapps, ".writable")
return try { return try {
if (!probe.createNewFile() && !probe.isFile) context.getString(R.string.gstore_cannot_write, path) else { probe.delete(); null } if (!probe.createNewFile() && !probe.isFile) "cannot write in $path" else { probe.delete(); null }
} catch (e: Exception) { } catch (e: Exception) {
context.getString(R.string.gstore_cannot_write_detail, path, e.message) "cannot write in $path (${e.message})"
} }
} }
@@ -60,13 +58,13 @@ object GameStorage {
val pref = SessionPrefs.gameStorage(context) val pref = SessionPrefs.gameStorage(context)
return when { return when {
pref == SessionPrefs.GAME_STORAGE_OFF -> null pref == SessionPrefs.GAME_STORAGE_OFF -> null
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) } pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.label.substringBefore(" ·"), it.path) }
else -> Option(SessionPrefs.gameStorageLabel(context), pref) else -> Option(SessionPrefs.gameStorageLabel(context), pref)
} }
} }
/** The label the client shows for a chosen folder: its last name, or the volume's. */ /** The label the client shows for a chosen folder: its last name, or the volume's. */
fun labelFor(context: Context, path: String): String = fun labelFor(context: Context, path: String): String =
options(context).firstOrNull { it.path == path }?.name options(context).firstOrNull { it.path == path }?.label?.substringBefore(" ·")
?: File(path).name.ifEmpty { context.getString(R.string.gstore_folder) } ?: File(path).name.ifEmpty { "Folder" }
} }
@@ -17,16 +17,9 @@ import java.nio.charset.StandardCharsets
* progress, and lifting that out is the difference between "starting the Steam client" for three * progress, and lifting that out is the difference between "starting the Steam client" for three
* minutes and a percentage that moves. * minutes and a percentage that moves.
*/ */
class LoadingState(context: Context, private val steam: Boolean = true) { class LoadingState(context: Context, steam: Boolean = true) {
var visible by mutableStateOf(true) var visible by mutableStateOf(true)
var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting)) var step by mutableStateOf("Starting the session…")
private set
/** What [step] is about, so the screen picks its checklist stage without reading the (translated) words. */
var topic by mutableStateOf(Topic.SESSION)
private set
/** [step] is a download or install line worth showing as it is, not one of the script's own notes. */
var readable by mutableStateOf(false)
private set
var percent by mutableIntStateOf(-1) var percent by mutableIntStateOf(-1)
var elapsed by mutableStateOf("") var elapsed by mutableStateOf("")
var hint by mutableStateOf("") var hint by mutableStateOf("")
@@ -38,23 +31,15 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
private val hints = context.resources.getStringArray( private val hints = context.resources.getStringArray(
if (steam) com.droiddeck.launcher.R.array.loading_hints else com.droiddeck.launcher.R.array.loading_hints_desktop, if (steam) com.droiddeck.launcher.R.array.loading_hints else com.droiddeck.launcher.R.array.loading_hints_desktop,
) )
private val res = context.resources
private val startedAt = SystemClock.elapsedRealtime() private val startedAt = SystemClock.elapsedRealtime()
/** Once a second: the clock and the hint. */ /** Once a second: the clock and the hint. */
fun tick() { fun tick() {
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000 val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, seconds / 60, seconds % 60) elapsed = String.format(java.util.Locale.US, "%d:%02d elapsed · still working", seconds / 60, seconds % 60)
hint = hints[((seconds / 8) % hints.size).toInt()] hint = hints[((seconds / 8) % hints.size).toInt()]
} }
/** A line the app itself writes (an install's progress, the session starting). */
fun say(line: String, topic: Topic, readable: Boolean) {
step = line
this.topic = topic
this.readable = readable
}
fun showEnded(message: String, detail: String? = null) { fun showEnded(message: String, detail: String? = null) {
visible = true visible = true
ended = true ended = true
@@ -65,16 +50,12 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
/** Re-reads the end of the log and updates the line and the bar. */ /** Re-reads the end of the log and updates the line and the bar. */
fun update(context: Context, log: File?) { fun update(context: Context, log: File?) {
val state = read(context, log) ?: return val state = read(context, log) ?: return
step = state.line step = state.first
topic = state.topic percent = state.second
readable = state.readable
percent = state.percent
} }
private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean)
/** Only the tail is read: the client alone writes megabytes an hour. */ /** Only the tail is read: the client alone writes megabytes an hour. */
private fun read(context: Context, log: File?): Line? { private fun read(context: Context, log: File?): Pair<String, Int>? {
if (log == null || !log.isFile) return null if (log == null || !log.isFile) return null
val text = try { val text = try {
RandomAccessFile(log, "r").use { file -> RandomAccessFile(log, "r").use { file ->
@@ -119,45 +100,16 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
} }
} }
return when { return when {
downloadAt > stepAt && downloadPercent >= 0 -> Line( downloadAt > stepAt && downloadPercent >= 0 ->
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent, Pair("Downloading the Steam client update · $downloadPercent%", downloadPercent)
Topic.STEAM, readable = true, clientDownloadAt == stepAt && clientDownload != null ->
) Pair("Downloading the Steam client · $clientDownload", clientPercent)
clientDownloadAt == stepAt && clientDownload != null -> Line( stepText != null -> Pair(stepText, -1)
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
Topic.STEAM, readable = true,
)
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
else -> null else -> null
} }
} }
/** The checklist stages a loading line can move the screen to. */
enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
companion object { companion object {
/**
* A session script "== STEP" line's topic in a Steam ([steam]) or desktop session; those
* lines are English whatever the app's language.
*/
internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
val t = scriptStep.lowercase()
return when {
"linux runtime" in t -> Topic.RUNTIME
"starting the session" in t -> Topic.SESSION
!steam && "desktop" in t -> Topic.DESKTOP
steam && "starting the steam client" in t -> Topic.STEAM_STARTING
steam && ("steam" in t || "client" in t || "proton" in t || "library" in t || "compatibility" in t) -> Topic.STEAM
else -> Topic.OTHER
}
}
/** The script's install lines are worth reading as they are; its other notes are not. */
internal fun readableScriptStep(scriptStep: String): Boolean {
val t = scriptStep.lowercase()
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
}
private const val TAIL_BYTES = 48L * 1024 private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""") private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""") private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
@@ -30,7 +30,7 @@ object OfflineMode {
private fun loginUsers(root: File) = File(root, "root/.local/share/Steam/config/loginusers.vdf") private fun loginUsers(root: File) = File(root, "root/.local/share/Steam/config/loginusers.vdf")
/** The account the client could sign in as offline: its name, "" when it recorded none, null when there is none. */ /** Whether the client has an account it could sign in as offline. */
fun account(context: Context): String? { fun account(context: Context): String? {
val file = loginUsers(LinuxRuntime.rootDir(context)) val file = loginUsers(LinuxRuntime.rootDir(context))
val text = try { val text = try {
@@ -39,7 +39,7 @@ object OfflineMode {
Log.w(TAG, "could not read loginusers.vdf", e); return null Log.w(TAG, "could not read loginusers.vdf", e); return null
} }
if (!REMEMBER.containsMatchIn(text)) return null if (!REMEMBER.containsMatchIn(text)) return null
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty() return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() } ?: "signed in"
} }
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false) fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
@@ -1,7 +1,6 @@
package com.droiddeck.launcher.session package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.Hashes import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.R
import android.content.Context import android.content.Context
import android.os.StatFs import android.os.StatFs
import android.util.Log import android.util.Log
@@ -60,72 +59,70 @@ object ProtonExtras {
/** Downloads, verifies and registers the latest build without waiting for another session. */ /** Downloads, verifies and registers the latest build without waiting for another session. */
@Synchronized @Synchronized
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress) return context.getString(R.string.pextra_busy) if (installInProgress) return "A compatibility tool install is already running"
installInProgress = true installInProgress = true
return try { installNow(context, tool, onProgress) } finally { installInProgress = false } return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
} }
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session) if (SessionState.running) return "Stop the active session before installing compatibility tools"
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required) if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
val asset = findLatestAsset(tool) ?: return context.getString(R.string.pextra_no_release, tool.name) val asset = findLatestAsset(tool) ?: return "Could not find an ARM64 release for ${tool.name}"
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() } val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}") val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete() if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L) val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) { if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
return context.getString(R.string.pextra_no_space, tool.name) return "At least 4 GB free plus the download size is required to install ${tool.name}"
} }
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag) onProgress("Downloading ${tool.name} ${asset.tag}", 0)
onProgress(downloading, 0)
var downloaded = false var downloaded = false
for (attempt in 0 until 5) { for (attempt in 0 until 5) {
downloaded = Downloader.downloadFile(asset.url, archive, true) { fraction -> downloaded = Downloader.downloadFile(asset.url, archive, true) { fraction ->
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100)) onProgress("Downloading ${tool.name} ${asset.tag}", if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
} }
if (downloaded) break if (downloaded) break
if (attempt < 4) { if (attempt < 4) {
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1) onProgress("Retrying download · attempt ${attempt + 2} of 5", -1)
try { Thread.sleep(3_000) } catch (_: InterruptedException) { try { Thread.sleep(3_000) } catch (_: InterruptedException) {
Thread.currentThread().interrupt() Thread.currentThread().interrupt()
return context.getString(R.string.pextra_interrupted) return "Download interrupted"
} }
} }
} }
if (!downloaded) return context.getString(R.string.pextra_download_failed) if (!downloaded) return "Download failed; the partial file is kept so a retry can resume"
if (asset.size > 0 && archive.length() != asset.size) { if (asset.size > 0 && archive.length() != asset.size) {
if (archive.length() > asset.size) { if (archive.length() > asset.size) {
archive.delete() archive.delete()
return context.getString(R.string.pextra_too_big) return "Download exceeded the release size and was deleted"
} }
return context.getString(R.string.pextra_incomplete) return "Download was incomplete; the partial file is kept for a resumable retry"
} }
// One checksum has to be found and has to match: GitHub's sha256 digest, else the // One checksum has to be found and has to match: GitHub's sha256 digest, else the
// release's own sha512 file. A download neither vouches for is not installed. // release's own sha512 file. A download neither vouches for is not installed.
onProgress(context.getString(R.string.pextra_verifying), -1) onProgress("Verifying download", -1)
val verified = when { val verified = when {
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true) asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
asset.sha512 != null -> { asset.sha512 != null -> {
val expected = Downloader.downloadString(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value } val expected = Downloader.downloadString(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
?: return context.getString(R.string.pextra_checksum_unreadable) ?: return "Could not read the release checksum; try again"
expected.equals(Hashes.sha512(archive), ignoreCase = true) expected.equals(Hashes.sha512(archive), ignoreCase = true)
} }
else -> { else -> {
archive.delete() archive.delete()
return context.getString(R.string.pextra_no_checksum, tool.name, asset.tag) return "${tool.name} ${asset.tag} publishes no checksum; nothing was installed"
} }
} }
if (!verified) { if (!verified) {
archive.delete() archive.delete()
return context.getString(R.string.pextra_checksum_mismatch) return "Checksum mismatch; the download was deleted"
} }
if (SessionState.running) return context.getString(R.string.pextra_session_started) if (SessionState.running) return "A session started during the download; stop it before installing compatibility tools"
val installing = context.getString(R.string.pextra_installing, tool.name) onProgress("Installing ${tool.name}", -1)
onProgress(installing, -1)
return try { return try {
val root = LinuxRuntime.rootDir(context) val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context) LinuxRuntime.writeAccounts(context)
@@ -149,17 +146,17 @@ object ProtonExtras {
lines.forEach { line -> lines.forEach { line ->
Log.i(TAG, line) Log.i(TAG, line)
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) { if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
onProgress(installing, -1) onProgress("Installing ${tool.name}", -1)
} }
} }
} }
val status = child.waitFor() val status = child.waitFor()
if (status != 0) context.getString(R.string.pextra_install_failed, tool.name, status) if (status != 0) "${tool.name} installation failed (exit $status)"
else { else {
archive.delete() archive.delete()
unqueue(context, tool) unqueue(context, tool)
if (EsyncPacks.enabled(context)) { if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1) onProgress("Fetching droiddeck-esync pack", -1)
try { try {
EsyncPacks.fetchWanted(context, root, onProgress) EsyncPacks.fetchWanted(context, root, onProgress)
} catch (t: Throwable) { } catch (t: Throwable) {
@@ -170,7 +167,7 @@ object ProtonExtras {
} }
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "install ${tool.id}", e) Log.e(TAG, "install ${tool.id}", e)
e.message ?: context.getString(R.string.pextra_could_not_install, tool.name) e.message ?: "Could not install ${tool.name}"
} }
} }
@@ -3,58 +3,43 @@ package com.droiddeck.launcher.session
import android.net.LocalServerSocket import android.net.LocalServerSocket
import android.content.SharedPreferences import android.content.SharedPreferences
import android.os.Build import android.os.Build
import android.os.CombinedVibration
import android.os.VibrationEffect import android.os.VibrationEffect
import android.os.Vibrator import android.os.Vibrator
import android.os.VibratorManager import android.os.VibratorManager
import android.util.Log import android.util.Log
import android.view.InputDevice
import androidx.annotation.RequiresApi
import com.droiddeck.launcher.core.SessionPart import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.PadBridge
import java.io.DataInputStream import java.io.DataInputStream
import kotlin.math.max import kotlin.math.max
/** /**
* Rumble for the pad, on the motors in the player's hands. * Rumble for the on-screen pad, on the phone itself.
* *
* When a game plays a force-feedback effect on the fake pad (or Steam Input sends the Deck's * When a game plays a force-feedback effect on the fake pad, the fake evdev layer inside the guest
* rumble report), the fake evdev layer inside the guest connects to the abstract socket [NAME] * connects to the abstract socket [NAME] and sends one packet: strong, weak, duration in ms and
* and sends one packet: strong, weak, duration in ms and the pad slot, four little-endian 16-bit * the pad slot, four little-endian 16-bit values. This listens for those and drives the device's
* values. This listens for those and plays the effect on the physical controller that last drove * vibrator with the stronger motor's strength for the effect's duration. Best effort both ways:
* the pad (PadBridge.activeControllerId) when Android exposes its motors - strong and weak * a missing listener costs the guest nothing, and a bad packet is dropped.
* separately where it has two - and otherwise on the device's own vibrator, with the stronger
* motor's strength: the on-screen pad, or a controller without rumble. Best effort both ways: a
* missing listener costs the guest nothing, and a bad packet is dropped.
*/ */
class RumbleComponent : SessionPart() { class RumbleComponent : SessionPart() {
@Volatile private var server: LocalServerSocket? = null @Volatile private var server: LocalServerSocket? = null
private var phone: Motors? = null private var vibrator: Vibrator? = null
/** Where the last effect went, so the next one (or a stop) can end it there. */
private var playing: Motors? = null
private var controllerId = PadBridge.NO_CONTROLLER
private var controller: Motors? = null
private var preferences: SharedPreferences? = null private var preferences: SharedPreferences? = null
private var enabled = false private var enabled = false
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == null || key == "rumble") refreshEnabled() if (key == null || key == "rumble") refreshEnabled()
} }
/** The motors of the controller with this input device id, or null when it has none. Tests swap it. */
internal var controllerMotors: (Int) -> Motors? = ::lookupController
@Synchronized private fun refreshEnabled() { @Synchronized private fun refreshEnabled() {
enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true
if (!enabled) { playing?.cancel(); playing = null } if (!enabled) vibrator?.cancel()
} }
override fun start() { override fun start() {
val ctx = app() ?: return val ctx = app() ?: return
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return } val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
val vibrator = if (Build.VERSION.SDK_INT >= 31) ctx.getSystemService(VibratorManager::class.java)?.defaultVibrator vibrator = if (Build.VERSION.SDK_INT >= 31) ctx.getSystemService(VibratorManager::class.java)?.defaultVibrator
else @Suppress("DEPRECATION") ctx.getSystemService(Vibrator::class.java) else @Suppress("DEPRECATION") ctx.getSystemService(Vibrator::class.java)
phone = vibrator?.takeIf { it.hasVibrator() }?.let { PhoneMotors(it) }
preferences = ControllerPrefs.prefs(ctx).also { it.registerOnSharedPreferenceChangeListener(preferenceListener) } preferences = ControllerPrefs.prefs(ctx).also { it.registerOnSharedPreferenceChangeListener(preferenceListener) }
refreshEnabled() refreshEnabled()
server = s server = s
@@ -64,7 +49,8 @@ class RumbleComponent : SessionPart() {
try { try {
val bytes = ByteArray(8) val bytes = ByteArray(8)
DataInputStream(client.inputStream).readFully(bytes) DataInputStream(client.inputStream).readFully(bytes)
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4)) val strong = u16(bytes, 0); val weak = u16(bytes, 2); val ms = u16(bytes, 4)
buzz(max(strong, weak), ms)
} catch (e: Exception) { } catch (e: Exception) {
// A partial packet or a closed peer: nothing to play. // A partial packet or a closed peer: nothing to play.
} finally { } finally {
@@ -79,11 +65,8 @@ class RumbleComponent : SessionPart() {
preferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener) preferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener)
preferences = null preferences = null
enabled = false enabled = false
playing?.cancel() vibrator?.cancel()
playing = null vibrator = null
phone = null
controller = null
controllerId = PadBridge.NO_CONTROLLER
val s = server val s = server
server = null server = null
try { s?.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ } try { s?.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ }
@@ -91,91 +74,24 @@ class RumbleComponent : SessionPart() {
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8) private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int) { @Synchronized private fun buzz(strength: Int, ms: Int) {
if (!enabled) return if (!enabled) return
val target = target() val vibrator = vibrator ?: return
if (target !== playing) { if (!vibrator.hasVibrator()) return
playing?.cancel() if (strength == 0 || ms == 0) { vibrator.cancel(); return }
playing = target val amplitude = (strength * 255L / 65535L).toInt().coerceIn(1, 255)
target?.let { Log.i(TAG, "rumble: playing on ${it.name}") } val duration = ms.toLong().coerceIn(1L, 5000L)
}
if (target == null) return
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); return }
try { try {
target.play(strong, weak, ms.toLong().coerceIn(1L, 5000L)) if (vibrator.hasAmplitudeControl()) vibrator.vibrate(VibrationEffect.createOneShot(duration, amplitude))
else vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE))
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "rumble: ${target.name}: $e") Log.w(TAG, "rumble: $e")
} }
} }
/** The active controller's motors when it has any, else the phone's. */
private fun target(): Motors? {
val id = PadBridge.activeControllerId()
if (id != controllerId) {
controllerId = id
controller = if (id == PadBridge.NO_CONTROLLER) null else try { controllerMotors(id) } catch (e: Exception) { null }
}
return controller ?: phone
}
/** One place an effect can play. Strengths are the evdev 0..65535 magnitudes. */
internal interface Motors {
val name: String
fun play(strong: Int, weak: Int, ms: Long)
fun cancel()
}
private class PhoneMotors(private val vibrator: Vibrator) : Motors {
override val name = "the device's vibrator"
override fun play(strong: Int, weak: Int, ms: Long) = vibrator.vibrate(oneShot(vibrator, max(strong, weak), ms))
override fun cancel() = vibrator.cancel()
}
/** Android 12+: each of the pad's motors on its own, the lower id being the strong one. */
@RequiresApi(31)
private class PadMotors(override val name: String, private val manager: VibratorManager, private val ids: IntArray) : Motors {
override fun play(strong: Int, weak: Int, ms: Long) {
val combined = CombinedVibration.startParallel()
var any = false
fun add(id: Int, strength: Int) {
if (strength == 0) return
combined.addVibrator(id, oneShot(manager.getVibrator(id), strength, ms))
any = true
}
if (ids.size >= 2) { add(ids[0], strong); add(ids[1], weak) } else add(ids[0], max(strong, weak))
if (any) manager.vibrate(combined.combine()) else manager.cancel()
}
override fun cancel() = manager.cancel()
}
/** Before Android 12 a pad has one vibrator. */
private class LegacyPadMotors(override val name: String, private val vibrator: Vibrator) : Motors {
override fun play(strong: Int, weak: Int, ms: Long) = vibrator.vibrate(oneShot(vibrator, max(strong, weak), ms))
override fun cancel() = vibrator.cancel()
}
companion object { companion object {
private const val TAG = "SessionService" private const val TAG = "SessionService"
/** Must match the fake evdev layer (fakeinput_steam.cpp). */ /** Must match the fake evdev layer (fakeinput_steam.cpp). */
const val NAME = "droiddeck-rumble" const val NAME = "droiddeck-rumble"
private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect {
val amplitude = if (vibrator.hasAmplitudeControl()) (strength * 255L / 65535L).toInt().coerceIn(1, 255)
else VibrationEffect.DEFAULT_AMPLITUDE
return VibrationEffect.createOneShot(ms, amplitude)
}
private fun lookupController(id: Int): Motors? {
val device = InputDevice.getDevice(id) ?: return null
val name = "\"${device.name}\""
if (Build.VERSION.SDK_INT >= 31) {
val manager = device.vibratorManager
val ids = manager.vibratorIds.sortedArray()
return if (ids.isEmpty()) null else PadMotors(name, manager, ids)
}
@Suppress("DEPRECATION")
val vibrator = device.vibrator
return if (vibrator.hasVibrator()) LegacyPadMotors(name, vibrator) else null
}
} }
} }
@@ -1,53 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.view.WindowManager
/** The virtual display advertised to the guest, before it is fitted onto the Android panel. */
object SessionDisplay {
const val MATCH_SCREEN = "screen"
const val DEFAULT_RESOLUTION = "1280x720"
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> =
if (choice == MATCH_SCREEN) screenSize(panel) else {
// Legacy displays may exceed the custom dialog's size limit. Keep their exact size.
val parts = choice.split('x').map { it.toIntOrNull() }
if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
else 1280 to 720
}
/** Fixed dimensions and the current panel, with no duplicate panel-size preset. */
fun resolutionOptions(panel: Pair<Int, Int>): List<String> =
listOf(DEFAULT_RESOLUTION, "1600x900", "1920x1080")
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN
fun panelSize(context: Context): Pair<Int, Int> {
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
@Suppress("DEPRECATION")
val mode = manager.defaultDisplay.mode
return maxOf(mode.physicalWidth, mode.physicalHeight) to minOf(mode.physicalWidth, mode.physicalHeight)
}
/** Interpret an older cap/aspect combination without altering the saved picture size. */
fun resolve(panel: Pair<Int, Int>, cap: Int, shape: String, custom: Pair<Int, Int>? = null): Pair<Int, Int> {
custom?.let { return it }
val panelW = maxOf(panel.first, panel.second).toFloat()
val panelH = minOf(panel.first, panel.second).toFloat().coerceAtLeast(1f)
// Auto retains wide panels but floors squarer ones at 16:9 for game compatibility.
// Match screen removes that floor; fixed 16:9 also keeps foldable sessions stable.
val aspect = when (shape) {
SessionPrefs.SHAPE_WIDE -> 16f / 9f
SessionPrefs.SHAPE_EXACT -> panelW / panelH
else -> maxOf(panelW / panelH, 16f / 9f)
}
val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt()
return ((height * aspect).toInt() and 1.inv()) to (height and 1.inv())
}
/** Mirrors gamescope's even-width 16:9 calculation, including near-16:9 rounding. */
fun canStretch16x9(size: Pair<Int, Int>): Boolean =
(size.second * 16 + 4) / 9 / 2 * 2 > size.first
}
@@ -41,7 +41,6 @@ object SessionFiles {
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard", "usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install", "usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale", "usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
"usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library", "usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library",
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists", "usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra", "usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
@@ -4,7 +4,6 @@ import android.content.ClipData
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import androidx.core.content.FileProvider import androidx.core.content.FileProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.LogRedactor import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File import java.io.File
@@ -76,6 +75,6 @@ object SessionLogShare {
.putExtra(Intent.EXTRA_SUBJECT, zip.nameWithoutExtension) .putExtra(Intent.EXTRA_SUBJECT, zip.nameWithoutExtension)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
send.clipData = ClipData.newRawUri(zip.name, uri) send.clipData = ClipData.newRawUri(zip.name, uri)
return Intent.createChooser(send, context.getString(R.string.logshare_chooser)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) return Intent.createChooser(send, "Share session logs").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
} }
} }
@@ -1,8 +1,6 @@
package com.droiddeck.launcher.session package com.droiddeck.launcher.session
import android.content.Context import android.content.Context
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.TextureFiltering import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.ScreenEffects import com.droiddeck.launcher.gpu.ScreenEffects
import org.json.JSONObject import org.json.JSONObject
@@ -20,12 +18,10 @@ object SessionPrefs {
const val OSC_STEAM_QAM = "steam-qam" const val OSC_STEAM_QAM = "steam-qam"
const val OSC_NEVER = "never" const val OSC_NEVER = "never"
/** What Back does in a Steam session, first press then second: the labels of the two orders. */ const val BACK_MENU_THEN_QAM = "1: menu 2: QAM"
val BACK_MENU_THEN_QAM = R.string.back_menu_then_qam const val BACK_QAM_THEN_MENU = "1: QAM 2: menu"
val BACK_QAM_THEN_MENU = R.string.back_qam_then_menu
@StringRes fun backActionsOrder(inverted: Boolean): String =
fun backActionsOrder(inverted: Boolean): Int =
if (inverted) BACK_QAM_THEN_MENU else BACK_MENU_THEN_QAM if (inverted) BACK_QAM_THEN_MENU else BACK_MENU_THEN_QAM
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE) private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
@@ -92,16 +88,27 @@ object SessionPrefs {
const val SHAPE_WIDE = "16:9" const val SHAPE_WIDE = "16:9"
const val SHAPE_EXACT = "exact" const val SHAPE_EXACT = "exact"
/** The choices the settings offer, in order. */
val shapeChoices = listOf(
SHAPE_AUTO to "Auto (16:9+)",
SHAPE_EXACT to "Match screen",
SHAPE_WIDE to "Always 16:9",
)
/** /**
* The shape of the display the session presents: the panel's own (never narrower than 16:9), * The shape of the display the session presents: the panel's own (never narrower than 16:9),
* exactly the panel's (a 4:3 or 3:2 handheld, drawn edge to edge), or a fixed 16:9. A foldable defaults to 16:9, which sits with modest bars on either of its * exactly the panel's (a 4:3 or 3:2 handheld, drawn edge to edge), or a fixed 16:9. A foldable defaults to 16:9, which sits with modest bars on either of its
* panels; the panel's own shape would fit one and leave a strip on the other, and gamescope's * panels; the panel's own shape would fit one and leave a strip on the other, and gamescope's
* display cannot change size once the session is up. * display cannot change size once the session is up.
*/ */
private fun shapeMode(context: Context): String = fun shapeMode(context: Context): String =
prefs(context).getString("shape", null) prefs(context).getString("shape", null)
?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO ?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO
fun setShapeMode(context: Context, mode: String) {
prefs(context).edit().putString("shape", mode).apply()
}
fun oscMode(context: Context): String = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO fun oscMode(context: Context): String = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO
fun setOscMode(context: Context, mode: String) { fun setOscMode(context: Context, mode: String) {
@@ -172,12 +179,9 @@ object SessionPrefs {
* Steam only: gamescope makes every game window the size of the screen. A game that resizes * Steam only: gamescope makes every game window the size of the screen. A game that resizes
* its own window when it loses focus (FlatOut) otherwise comes back smaller, drawn in a * its own window when it loses focus (FlatOut) otherwise comes back smaller, drawn in a
* corner; a game that sets its own resolution and never looks at its window again (Quake 3) * corner; a game that sets its own resolution and never looks at its window again (Quake 3)
* instead draws small in the bottom-left of the stretched one. A game whose resolution differs * instead draws small in the bottom-left of the stretched one. On unless turned off.
* from the screen's (DiRT 3 at 1280x720) fights it: it rebuilds its swapchain on every forced
* resize and the picture flickers between its own size and the screen's, often from the first
* menu, before the player can reach its resolution setting. Off unless turned on.
*/ */
fun forceFullscreen(context: Context): Boolean = prefs(context).getBoolean("forceFullscreen", false) fun forceFullscreen(context: Context): Boolean = prefs(context).getBoolean("forceFullscreen", true)
fun setForceFullscreen(context: Context, on: Boolean) { fun setForceFullscreen(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("forceFullscreen", on).apply() prefs(context).edit().putBoolean("forceFullscreen", on).apply()
@@ -508,33 +512,11 @@ object SessionPrefs {
* and the emulators under it get the same GPU headroom. Read once, when the session's display * and the emulators under it get the same GPU headroom. Read once, when the session's display
* is sized; a cap the user chose wins over the default. * is sized; a cap the user chose wins over the default.
*/ */
private fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 720) fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", defaultResolutionCap(mode))
/** Whether the user chose the mode's resolution (a cap or a custom size) rather than the default. */ /** Whether the user chose the mode's resolution (a cap or a custom size) rather than the default. */
fun resolutionChosen(context: Context, mode: String): Boolean = fun resolutionChosen(context: Context, mode: String): Boolean =
prefs(context).contains("displayResolution.$mode") || prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
/** One per-mode choice now owns both dimensions; old caps/shapes are read only for migration. */
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String {
val saved = prefs(context)
saved.getString("displayResolution.$mode", null)?.let { value ->
if (value == SessionDisplay.MATCH_SCREEN) return value
parseResolution(value)?.let { return "${it.first}x${it.second}" }
}
if (!resolutionChosen(context, mode) && !saved.contains("shape")) return SessionDisplay.DEFAULT_RESOLUTION
val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), customResolution(context, mode))
return if (legacy == SessionDisplay.screenSize(panel)) SessionDisplay.MATCH_SCREEN
else "${legacy.first}x${legacy.second}"
}
fun setResolutionChoice(context: Context, mode: String, choice: String) {
val value = if (choice == SessionDisplay.MATCH_SCREEN) choice else {
val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" }
"${size.first}x${size.second}"
}
prefs(context).edit().putString("displayResolution.$mode", value).apply()
}
/** /**
* The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults. * The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults.
@@ -614,13 +596,25 @@ object SessionPrefs {
prefs(context).edit().putString("theme", id).apply() prefs(context).edit().putString("theme", id).apply()
} }
/** What a mode gets when nothing was chosen. */
@Suppress("UNUSED_PARAMETER")
fun defaultResolutionCap(mode: String): Int = 720
fun setResolutionCap(context: Context, mode: String, cap: Int) {
prefs(context).edit().putInt("resolutionCap.$mode", cap).apply()
}
/** /**
* A fixed size for the session's display, per mode, or null. When set it replaces both the * A fixed size for the session's display, per mode, or null. When set it replaces both the
* cap and the shape: the compositor fits it to the panel with bars where the shapes differ. * cap and the shape: the compositor fits it to the panel with bars where the shapes differ.
*/ */
private fun customResolution(context: Context, mode: String): Pair<Int, Int>? = fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
parseResolution(prefs(context).getString("customRes.$mode", null)) parseResolution(prefs(context).getString("customRes.$mode", null))
fun setCustomResolution(context: Context, mode: String, size: Pair<Int, Int>?) {
prefs(context).edit().putString("customRes.$mode", size?.let { "${it.first}x${it.second}" }).apply()
}
/** "1024x768" (or ×, or *) to an even size inside 320x240..3840x2160; anything else is null. */ /** "1024x768" (or ×, or *) to an even size inside 320x240..3840x2160; anything else is null. */
fun parseResolution(text: String?): Pair<Int, Int>? { fun parseResolution(text: String?): Pair<Int, Int>? {
val parts = text?.trim()?.split('x', 'X', '×', '*')?.map { it.trim() } ?: return null val parts = text?.trim()?.split('x', 'X', '×', '*')?.map { it.trim() } ?: return null
@@ -673,43 +667,22 @@ object SessionPrefs {
val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120") val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120")
/** [fpsLimitChoices] labelled in the app's language. */
fun fpsLimitChoices(context: Context): List<Pair<Int, String>> =
fpsLimitChoices.map { (fps, label) -> fps to if (fps == 0) context.getString(R.string.frame_gen_off) else label }
/** /**
* How the compositor resizes the session onto the panel (WaylandCompositor.nativeSetUpscaler's * How the compositor resizes the session onto the panel (WaylandCompositor.nativeSetUpscaler's
* modes). Linear is the default; Nearest preserves hard pixel edges. Spatial filters work * modes): Off and Linear both filter bilinearly, Nearest keeps pixels square for 2D and old
* when enlarged; Sharpen only works at any size. The old Off/Linear and FSR/FSR Fit pairs * titles, the rest sharpen where the picture is enlarged; FSR (fit) rounds the picture to
* are equivalent on Wayland, so saved aliases resolve to one choice. * FSR's preferred size first. Sharpen only works at any size.
*/ */
val upscalerChoices = listOf( val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR", 0 to "Off", 1 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 5 to "AMD FSR 1 (fit)", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only", 8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
) )
/** The [upscalerChoices] labels that are words rather than product names. */ fun upscaler(context: Context): Int =
private val upscalerLabels = mapOf( prefs(context).getInt("upscaler", 0).takeIf { m -> upscalerChoices.any { it.first == m } } ?: 0
0 to R.string.sprefs_upscaler_linear, 2 to R.string.sprefs_upscaler_nearest,
8 to R.string.sprefs_upscaler_gsr_quality, 6 to R.string.sprefs_upscaler_sharpen,
)
/** [upscalerChoices] labelled in the app's language; the English list stays for the device report. */
fun upscalerChoices(context: Context): List<Pair<Int, String>> =
upscalerChoices.map { (mode, label) -> mode to (upscalerLabels[mode]?.let(context::getString) ?: label) }
fun canonicalUpscaler(mode: Int): Int = when (mode) {
1 -> 0
5 -> 4
else -> mode.takeIf { m -> upscalerChoices.any { it.first == m } } ?: 0
}
fun upscalerHasSharpness(mode: Int): Boolean = canonicalUpscaler(mode) in 3..8
fun upscaler(context: Context): Int = canonicalUpscaler(prefs(context).getInt("upscaler", 0))
fun setUpscaler(context: Context, mode: Int) { fun setUpscaler(context: Context, mode: Int) {
prefs(context).edit().putInt("upscaler", canonicalUpscaler(mode)).apply() prefs(context).edit().putInt("upscaler", mode).apply()
} }
fun upscaleSharpness(context: Context): Int = prefs(context).getInt("upscaleSharpness", 75).coerceIn(0, 100) fun upscaleSharpness(context: Context): Int = prefs(context).getInt("upscaleSharpness", 75).coerceIn(0, 100)
@@ -732,10 +705,6 @@ object SessionPrefs {
val textureAnisotropyChoices = TextureFiltering.ANISOTROPY.map { it to if (it == 0) "Off" else "${it}x" } val textureAnisotropyChoices = TextureFiltering.ANISOTROPY.map { it to if (it == 0) "Off" else "${it}x" }
/** [textureAnisotropyChoices] labelled in the app's language. */
fun textureAnisotropyChoices(context: Context): List<Pair<Int, String>> =
textureAnisotropyChoices.map { (value, label) -> value to if (value == 0) context.getString(R.string.frame_gen_off) else label }
val textureLodBiasChoices = TextureFiltering.LOD_BIAS.map { val textureLodBiasChoices = TextureFiltering.LOD_BIAS.map {
it to when (it) { it to when (it) {
TextureFiltering.LOD_BIAS_OFF -> "Off" TextureFiltering.LOD_BIAS_OFF -> "Off"
@@ -744,15 +713,6 @@ object SessionPrefs {
} }
} }
/** [textureLodBiasChoices] labelled in the app's language. */
fun textureLodBiasChoices(context: Context): List<Pair<String, String>> = textureLodBiasChoices.map { (value, label) ->
value to when (value) {
TextureFiltering.LOD_BIAS_OFF -> context.getString(R.string.frame_gen_off)
TextureFiltering.LOD_BIAS_AUTO -> context.getString(R.string.sprefs_lod_bias_auto)
else -> label
}
}
/** Anisotropic filtering forced on DirectX 9-11 games (core/TextureFiltering); 0 = the game's own. */ /** Anisotropic filtering forced on DirectX 9-11 games (core/TextureFiltering); 0 = the game's own. */
fun textureAnisotropy(context: Context): Int = fun textureAnisotropy(context: Context): Int =
prefs(context).getInt("textureAnisotropy", 0).takeIf { it in TextureFiltering.ANISOTROPY } ?: 0 prefs(context).getInt("textureAnisotropy", 0).takeIf { it in TextureFiltering.ANISOTROPY } ?: 0
@@ -59,9 +59,6 @@ import java.util.Locale
* The activity comes and goes on top of this; see [com.droiddeck.launcher.wayland.CompositorHost]. * The activity comes and goes on top of this; see [com.droiddeck.launcher.wayland.CompositorHost].
*/ */
class SessionService : Service() { class SessionService : Service() {
override fun attachBaseContext(newBase: android.content.Context) =
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(newBase))
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>() private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
/** The Steam Deck controller's sysfs binds (SteamDeckPad), when this session has one. */ /** The Steam Deck controller's sysfs binds (SteamDeckPad), when this session has one. */
private var deckBinds: List<String> = emptyList() private var deckBinds: List<String> = emptyList()
@@ -540,12 +537,6 @@ class SessionService : Service() {
guest.add("PATH=/usr/local/bin:/usr/bin:/bin") guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
guest.add("TERM=xterm-256color") guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8") guest.add("LANG=C.UTF-8")
// Steam's interface language: the app's (Setup's choice, or the system's). The system's
// region decides between Spain's and Latin American Spanish, which the app has one of.
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
com.droiddeck.launcher.core.AppLanguage.effective(this),
com.droiddeck.launcher.core.AppLanguage.system(this).country,
))
// Without this the session is UTC: the client's clock, its logs and every timestamp in a // Without this the session is UTC: the client's clock, its logs and every timestamp in a
// session bundle sit hours off the device's. Bannerlator carries the same line. // session bundle sit hours off the device's. Bannerlator carries the same line.
guest.add("TZ=" + java.util.TimeZone.getDefault().id) guest.add("TZ=" + java.util.TimeZone.getDefault().id)
@@ -802,7 +793,7 @@ class SessionService : Service() {
val library = GameStorage.effective(this) val library = GameStorage.effective(this)
var storageDiagnosticLibrary: File? = null var storageDiagnosticLibrary: File? = null
if (library != null) { if (library != null) {
val problem = GameStorage.prepare(this, library.path) val problem = GameStorage.prepare(library.path)
if (problem == null) { if (problem == null) {
File(LinuxRuntime.rootDir(this), "mnt/droiddeck-sd").mkdirs() File(LinuxRuntime.rootDir(this), "mnt/droiddeck-sd").mkdirs()
// Links, prefixes and Steam entries made before the rename still name the old path. // Links, prefixes and Steam entries made before the rename still name the old path.
@@ -1,69 +0,0 @@
package com.droiddeck.launcher.session
import java.util.Locale
/**
* Steam's name for a language: the API language codes the client and the Steamworks API use
* ("english", "schinese", "koreana"...), for every language Steam's interface comes in.
*/
object SteamLanguage {
const val DEFAULT = "english"
/** Every language the Steam client's interface is offered in. */
val all: Set<String> = setOf(
"arabic", "bulgarian", "schinese", "tchinese", "czech", "danish", "dutch", "english",
"finnish", "french", "german", "greek", "hungarian", "indonesian", "italian", "japanese",
"koreana", "norwegian", "polish", "portuguese", "brazilian", "romanian", "russian",
"spanish", "latam", "swedish", "thai", "turkish", "ukrainian", "vietnamese", "malay",
)
/** Spanish-speaking regions Steam serves with Latin American Spanish rather than Spain's. */
private val latinAmerica = setOf(
"419", "AR", "BO", "CL", "CO", "CR", "CU", "DO", "EC", "GT", "HN", "MX", "NI", "PA", "PE",
"PR", "PY", "SV", "US", "UY", "VE",
)
/**
* Steam's language for [locale]. [region] stands in for the locale's own when it has none: the
* app's Spanish carries no region, and a player in Mexico should get Latin American Spanish.
*/
fun forLocale(locale: Locale, region: String? = null): String {
val country = locale.country.ifEmpty { region.orEmpty() }
return when (locale.language) {
"ar" -> "arabic"
"bg" -> "bulgarian"
"cs" -> "czech"
"da" -> "danish"
"nl" -> "dutch"
"en" -> "english"
"fi" -> "finnish"
"fr" -> "french"
"de" -> "german"
"el" -> "greek"
"hu" -> "hungarian"
"id", "in" -> "indonesian"
"it" -> "italian"
"ms" -> "malay"
"ja" -> "japanese"
"ko" -> "koreana"
"nb", "no", "nn" -> "norwegian"
"pl" -> "polish"
"pt" -> if (country == "BR") "brazilian" else "portuguese"
"ro" -> "romanian"
"ru" -> "russian"
"es" -> if (country in latinAmerica) "latam" else "spanish"
"sv" -> "swedish"
"th" -> "thai"
"tr" -> "turkish"
"uk" -> "ukrainian"
"vi" -> "vietnamese"
"zh" -> when {
locale.script == "Hant" -> "tchinese"
locale.script == "Hans" -> "schinese"
country == "TW" || country == "HK" || country == "MO" -> "tchinese"
else -> "schinese"
}
else -> DEFAULT
}
}
}
@@ -1,21 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
object SteamRepair {
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
private fun request(context: Context) = File(home(context), ".bl-steam-repair")
private fun unconfirmed(context: Context) = File(home(context), ".local/share/Steam/package/droiddeck-unconfirmed")
fun queued(context: Context): Boolean = request(context).exists()
fun queue(context: Context): Boolean = runCatching {
request(context).apply { parentFile?.mkdirs() }.writeText("1\n")
}.isSuccess
fun clientShown(context: Context) {
unconfirmed(context).delete()
}
}
@@ -1,8 +1,6 @@
package com.droiddeck.launcher.store package com.droiddeck.launcher.store
import android.util.Log import android.util.Log
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.net.HttpURLConnection import java.net.HttpURLConnection
@@ -34,13 +32,13 @@ object FlathubApi {
) )
/** A category as Flathub's search filters it, with the name shown for it. */ /** A category as Flathub's search filters it, with the name shown for it. */
class Category(val id: String, @StringRes val label: Int) class Category(val id: String, val label: String)
val categories = listOf( val categories = listOf(
Category("Game", R.string.store_cat_games), Category("AudioVideo", R.string.store_cat_audio_video), Category("Graphics", R.string.store_cat_graphics), Category("Game", "Games"), Category("AudioVideo", "Audio & Video"), Category("Graphics", "Graphics"),
Category("Network", R.string.store_cat_internet), Category("Office", R.string.store_cat_office), Category("Development", R.string.store_cat_developer), Category("Network", "Internet"), Category("Office", "Office"), Category("Development", "Developer"),
Category("Education", R.string.store_cat_education), Category("Science", R.string.store_cat_science), Category("System", R.string.store_cat_system), Category("Education", "Education"), Category("Science", "Science"), Category("System", "System"),
Category("Utility", R.string.store_cat_utilities), Category("Utility", "Utilities"),
) )
/** Front-page collections: popular, trending, recently-updated, recently-added. */ /** Front-page collections: popular, trending, recently-updated, recently-added. */
@@ -8,7 +8,6 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.FlatpakManager import com.droiddeck.launcher.runtime.FlatpakManager
/** /**
@@ -50,7 +49,7 @@ object StoreState {
private set private set
private var searchSeq = 0 private var searchSeq = 0
val SECTIONS = listOf("popular" to R.string.store_section_popular, "trending" to R.string.store_section_trending, "recently-added" to R.string.store_section_new, "recently-updated" to R.string.store_section_updated) val SECTIONS = listOf("popular" to "Popular", "trending" to "Trending", "recently-added" to "New", "recently-updated" to "Updated")
fun refresh(context: Context) { fun refresh(context: Context) {
val app = context.applicationContext val app = context.applicationContext
@@ -98,7 +97,7 @@ object StoreState {
private fun run(context: Context, what: String, label: String, work: (Context, (String, Int) -> Unit) -> String?) { private fun run(context: Context, what: String, label: String, work: (Context, (String, Int) -> Unit) -> String?) {
if (busy != null) return if (busy != null) return
val app = context.applicationContext val app = context.applicationContext
busy = what; stage = app.getString(R.string.store_starting); percent = -1 busy = what; stage = "Starting…"; percent = -1
Thread({ Thread({
val problem = try { val problem = try {
work(app) { s, p -> main.post { stage = s; percent = p } } work(app) { s, p -> main.post { stage = s; percent = p } }
@@ -110,12 +109,12 @@ object StoreState {
main.post { main.post {
busy = null; stage = null; percent = -1 busy = null; stage = null; percent = -1
ready = r; installed = list ready = r; installed = list
if (problem != null) Toast.makeText(app, app.getString(R.string.store_problem, label, problem), Toast.LENGTH_LONG).show() if (problem != null) Toast.makeText(app, "$label: $problem", Toast.LENGTH_LONG).show()
} }
}, "store-$what").start() }, "store-$what").start()
} }
fun setup(context: Context) = run(context, "setup", context.getString(R.string.store_flatpak_setup)) { c, p -> FlatpakManager.setup(c, p) } fun setup(context: Context) = run(context, "setup", "Flatpak setup") { c, p -> FlatpakManager.setup(c, p) }
fun install(context: Context, id: String, name: String) = fun install(context: Context, id: String, name: String) =
run(context, id, name) { c, p -> FlatpakManager.install(c, id, p) } run(context, id, name) { c, p -> FlatpakManager.install(c, id, p) }
@@ -136,7 +135,7 @@ object StoreState {
val u = FlatpakManager.updates(app) val u = FlatpakManager.updates(app)
main.post { main.post {
checkingUpdates = false checkingUpdates = false
if (u != null) { updates = u; updatesChecked = true } else Toast.makeText(app, R.string.store_updates_check_failed, Toast.LENGTH_SHORT).show() if (u != null) { updates = u; updatesChecked = true } else Toast.makeText(app, "Could not check Flathub for updates", Toast.LENGTH_SHORT).show()
} }
}, "store-updates").start() }, "store-updates").start()
} }
@@ -1,23 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.res.Configuration
import androidx.compose.ui.unit.Density
import com.droiddeck.launcher.core.AppUiPrefs
import kotlin.math.roundToInt
internal fun scaledAppDensity(base: Density, percent: Int): Density {
val scale = AppUiPrefs.normalizeScale(percent) / 100f
return if (scale == 1f) base else Density(base.density * scale, base.fontScale)
}
/** Responsive layouts and popup height limits must see the same dp space as the scaled UI. */
internal fun scaledAppConfiguration(base: Configuration, percent: Int): Configuration {
val scale = AppUiPrefs.normalizeScale(percent) / 100f
if (scale == 1f) return base
return Configuration(base).apply {
if (densityDpi > 0) densityDpi = (densityDpi * scale).roundToInt()
if (screenWidthDp > 0) screenWidthDp = (screenWidthDp / scale).roundToInt()
if (screenHeightDp > 0) screenHeightDp = (screenHeightDp / scale).roundToInt()
if (smallestScreenWidthDp > 0) smallestScreenWidthDp = (smallestScreenWidthDp / scale).roundToInt()
}
}
@@ -108,6 +108,8 @@ fun ComponentsPage(
/** The GPU drivers tab ([GPU_TAB]): what it shows and does. */ /** The GPU drivers tab ([GPU_TAB]): what it shows and does. */
gpu: GpuDriversState = GpuDriversState(), gpu: GpuDriversState = GpuDriversState(),
gpuActions: GpuDriversActions = GpuDriversActions(), gpuActions: GpuDriversActions = GpuDriversActions(),
defaultProtonId: String? = null,
onDefaultProton: (String) -> Unit = {},
) { ) {
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
@@ -117,11 +119,13 @@ fun ComponentsPage(
var confirmTitle by remember { mutableStateOf("") } var confirmTitle by remember { mutableStateOf("") }
var about by remember { mutableStateOf(false) } var about by remember { mutableStateOf(false) }
var protonMenu by remember { mutableStateOf(false) } var protonMenu by remember { mutableStateOf(false) }
var defaultProtonMenu by remember { mutableStateOf(false) }
var confirmVerb by remember { mutableStateOf(R.string.comp_swap) } var confirmVerb by remember { mutableStateOf(R.string.comp_swap) }
val ctx = LocalContext.current val ctx = LocalContext.current
fun ask(title: String, body: String, verb: Int, action: () -> Unit) { confirmTitle = title; confirmVerb = verb; confirm = body to action } fun ask(title: String, body: String, verb: Int, action: () -> Unit) { confirmTitle = title; confirmVerb = verb; confirm = body to action }
// The GPU drivers tab's Advanced pages: one driver list on its own, full page. // The GPU drivers tab's Advanced pages: one driver list on its own, full page.
var driverPage by remember { mutableStateOf<String?>(null) } var driverPage by remember { mutableStateOf<String?>(null) }
val gpuScroll = rememberScrollState()
val gpuTab = comp == GPU_TAB val gpuTab = comp == GPU_TAB
when (driverPage) { when (driverPage) {
"rt" -> { "rt" -> {
@@ -172,34 +176,54 @@ fun ComponentsPage(
} }
if (narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) if (narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
// ---- which Proton, which component ------------------------------------------------------ // ---- Steam default Proton and the component editing target -----------------------------
val comps = ComponentsManager.COMPONENTS val comps = ComponentsManager.COMPONENTS
androidx.compose.foundation.layout.FlowRow( androidx.compose.foundation.layout.FlowRow(
horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().padding(top = 12.dp), modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
) { ) {
if (view != null && !gpuTab) Box { if (view != null && !gpuTab) {
ValueChip(view.proton.name, protonMenu, modifier = Modifier.widthIn(max = 300.dp).heightIn(min = 44.dp)) { protonMenu = !protonMenu } SettingsAnchor("default-proton", Modifier.widthIn(max = 300.dp)) { Column {
AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = stringResource(R.string.comp_proton), Text("Default Proton", fontSize = 12.sp, color = colors.onSurfaceVariant)
note = stringResource(R.string.comp_proton_note)) { first -> Box {
views.forEachIndexed { i, v -> val defaultName = views.firstOrNull { it.proton.id == defaultProtonId }?.proton?.name ?: "Choose default"
val swaps = v.components.values.count { it.activeFile != null } ValueChip(defaultName, defaultProtonMenu, modifier = Modifier.widthIn(max = 300.dp).heightIn(min = 44.dp)) { defaultProtonMenu = !defaultProtonMenu }
MenuItem( AnchoredMenu(defaultProtonMenu, onDismiss = { defaultProtonMenu = false }, title = "Default Proton",
v.proton.name, checked = v.proton.id == view.proton.id, note = stringResource(R.string.comp_proton_note)) { first ->
detail = (if (swaps > 0) stringResource(R.string.comp_swapped, v.proton.version, swaps) else stringResource(R.string.comp_all_original, v.proton.version)) views.forEachIndexed { i, v ->
.let { MenuItem(v.proton.name, checked = v.proton.id == defaultProtonId,
when (v.sync?.state) { focusRequester = if (i == 0) first else null,
"pack" -> stringResource(R.string.comp_esync_pack, it) ) { onDefaultProton(v.proton.id); defaultProtonMenu = false }
"wanted" -> stringResource(R.string.comp_esync_wanted, it) }
"builtin" -> stringResource(R.string.comp_esync_builtin, it) }
else -> it
}
}
.let { if (v.inUseByGame) stringResource(R.string.comp_game_running_suffix, it) else it },
focusRequester = if (i == 0) first else null,
) { onProton(v.proton.id); protonMenu = false }
} }
} } }
SettingsAnchor("editing-proton", Modifier.widthIn(max = 300.dp)) { Column {
Text("Editing components for", fontSize = 12.sp, color = colors.onSurfaceVariant)
Box {
ValueChip(view.proton.name, protonMenu, modifier = Modifier.widthIn(max = 300.dp).heightIn(min = 44.dp)) { protonMenu = !protonMenu }
AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = "Editing components for",
note = "Component changes apply to this Proton. The default Proton is selected separately above.") { first ->
views.forEachIndexed { i, v ->
val swaps = v.components.values.count { it.activeFile != null }
MenuItem(
v.proton.name, checked = v.proton.id == view.proton.id,
detail = (if (swaps > 0) stringResource(R.string.comp_swapped, v.proton.version, swaps) else stringResource(R.string.comp_all_original, v.proton.version))
.let {
when (v.sync?.state) {
"pack" -> stringResource(R.string.comp_esync_pack, it)
"wanted" -> stringResource(R.string.comp_esync_wanted, it)
"builtin" -> stringResource(R.string.comp_esync_builtin, it)
else -> it
}
}
.let { if (v.inUseByGame) stringResource(R.string.comp_game_running_suffix, it) else it },
focusRequester = if (i == 0) first else null,
) { onProton(v.proton.id); protonMenu = false }
}
}
}
} }
} }
val tabs = listOf(GPU_TAB) + comps val tabs = listOf(GPU_TAB) + comps
TabStrip(tabs.map { ComponentsManager.LABEL[it] ?: stringResource(R.string.comp_gpu_drivers) }, tabs.indexOf(comp).coerceAtLeast(0), { onComp(tabs[it]) }) TabStrip(tabs.map { ComponentsManager.LABEL[it] ?: stringResource(R.string.comp_gpu_drivers) }, tabs.indexOf(comp).coerceAtLeast(0), { onComp(tabs[it]) })
@@ -230,7 +254,7 @@ fun ComponentsPage(
// ---- the lists ------------------------------------------------------------------------------ // ---- the lists ------------------------------------------------------------------------------
when { when {
gpuTab -> Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { gpuTab -> Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(gpuScroll).padding(bottom = 16.dp)) {
GpuDriversPanel(gpu, gpuActions) { driverPage = it } GpuDriversPanel(gpu, gpuActions) { driverPage = it }
Row(modifier = Modifier.padding(top = 14.dp)) { Row(modifier = Modifier.padding(top = 14.dp)) {
SmallButton(stringResource(R.string.comp_import_zip), onClick = gpuActions.onImportZip) SmallButton(stringResource(R.string.comp_import_zip), onClick = gpuActions.onImportZip)
@@ -42,43 +42,43 @@ private fun Swatch(color: Int) {
@Composable @Composable
fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPrefs.Settings, a: ControllerActions) { fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPrefs.Settings, a: ControllerActions) {
ChoiceRow( ChoiceRow(
host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.ctrl_osc_hint), host, "controller-osc", stringResource(R.string.mode_osc), null,
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
oscMode, note = stringResource(R.string.mode_osc_note), onPick = a.onOsc, oscMode, note = stringResource(R.string.mode_osc_note), onPick = a.onOsc,
) )
val tintOpen = host.open == "controller-tint" val tintOpen = host.open == "controller-tint"
SettingsRow(stringResource(R.string.ctrl_color), stringResource(R.string.ctrl_color_hint), highlighted = tintOpen) { SettingsAnchor("controller-tint") { SettingsRow(stringResource(R.string.ctrl_color), null, highlighted = tintOpen) {
Box { Box {
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second?.let { stringResource(it) } ?: stringResource(R.string.ctrl_custom), tintOpen) { ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second ?: stringResource(R.string.ctrl_custom), tintOpen) {
host.open = if (tintOpen) null else "controller-tint" host.open = if (tintOpen) null else "controller-tint"
} }
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = stringResource(R.string.ctrl_color)) { firstItemFocus -> AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = stringResource(R.string.ctrl_color)) { firstItemFocus ->
ControllerPrefs.tints.forEachIndexed { index, (color, name) -> ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
MenuItem(stringResource(name), checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) { MenuItem(name, checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) {
a.onTint(color) a.onTint(color)
host.open = null host.open = null
} }
} }
} }
} }
} } }
ChoiceRow(host, "controller-opacity", stringResource(R.string.ctrl_opacity), null, ControllerPrefs.opacities.map { it to stringResource(R.string.ctrl_percent, it) }, c.opacity, onPick = a.onOpacity) ChoiceRow(host, "controller-opacity", stringResource(R.string.ctrl_opacity), null, ControllerPrefs.opacities.map { it to stringResource(R.string.ctrl_percent, it) }, c.opacity, onPick = a.onOpacity)
ChoiceRow(host, "controller-size", stringResource(R.string.ctrl_size), stringResource(R.string.ctrl_size_hint), ControllerPrefs.sizes.map { it to stringResource(R.string.ctrl_percent, it) }, c.size, onPick = a.onSize) ChoiceRow(host, "controller-size", stringResource(R.string.ctrl_size), null, ControllerPrefs.sizes.map { it to stringResource(R.string.ctrl_percent, it) }, c.size, onPick = a.onSize)
ToggleRow(host, "controller-stick-click", stringResource(R.string.ctrl_stick_click), stringResource(R.string.ctrl_stick_click_hint), c.stickClick, onChange = a.onStickClick) ToggleRow(host, "controller-stick-click", stringResource(R.string.ctrl_stick_click), stringResource(R.string.ctrl_stick_click_hint), c.stickClick, onChange = a.onStickClick)
ToggleRow(host, "controller-adaptive", stringResource(R.string.ctrl_adaptive), stringResource(R.string.ctrl_adaptive_hint), c.adaptiveSticks, onChange = a.onAdaptiveSticks) ToggleRow(host, "controller-adaptive", stringResource(R.string.ctrl_adaptive), stringResource(R.string.ctrl_adaptive_hint), c.adaptiveSticks, onChange = a.onAdaptiveSticks)
ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, c.rumble, onChange = a.onRumble) ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, c.rumble, onChange = a.onRumble)
ToggleRow(host, "controller-steam", stringResource(R.string.ctrl_steam_button), null, c.steamButton, onChange = a.onSteamButton) ToggleRow(host, "controller-steam", stringResource(R.string.ctrl_steam_button), null, c.steamButton, onChange = a.onSteamButton)
ToggleRow(host, "controller-qam", stringResource(R.string.ctrl_qam_button), null, c.qamButton, onChange = a.onQamButton) ToggleRow(host, "controller-qam", stringResource(R.string.ctrl_qam_button), null, c.qamButton, onChange = a.onQamButton)
ToggleRow(host, "controller-keyboard", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton, onChange = a.onKeyboardButton) ToggleRow(host, "controller-keyboard", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton, onChange = a.onKeyboardButton)
SettingsRow(stringResource(R.string.ctrl_layout), if (c.customLayout) stringResource(R.string.ctrl_layout_custom) else stringResource(R.string.ctrl_layout_default)) { SettingsAnchor("controller-layout") { SettingsRow(stringResource(R.string.ctrl_layout), if (c.customLayout) stringResource(R.string.ctrl_layout_custom) else stringResource(R.string.ctrl_layout_default)) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SecondaryButton(stringResource(R.string.ctrl_edit)) { a.onEditLayout() } SecondaryButton(stringResource(R.string.ctrl_edit)) { a.onEditLayout() }
SecondaryButton(stringResource(R.string.ctrl_reset), enabled = c.customLayout) { a.onResetLayout() } SecondaryButton(stringResource(R.string.ctrl_reset), enabled = c.customLayout) { a.onResetLayout() }
} }
} } }
val remapped = c.mapping.count { (id, target) -> id != target } val remapped = c.mapping.count { (id, target) -> id != target }
ActionRow(stringResource(R.string.ctrl_mapping), if (remapped == 0) stringResource(R.string.ctrl_mapping_default) else stringResource(R.string.ctrl_mapping_count, remapped, c.mapping.size), stringResource(R.string.ctrl_configure), a.onMapping) SettingsAnchor("controller-mapping") { ActionRow(stringResource(R.string.ctrl_mapping), if (remapped == 0) stringResource(R.string.ctrl_mapping_default) else stringResource(R.string.ctrl_mapping_count, remapped, c.mapping.size), stringResource(R.string.ctrl_configure), a.onMapping) }
ActionRow(stringResource(R.string.ctrl_reset_all), stringResource(R.string.ctrl_reset_all_hint), stringResource(R.string.ctrl_reset), a.onResetAll) SettingsAnchor("controller-reset") { ActionRow(stringResource(R.string.ctrl_reset_all), stringResource(R.string.ctrl_reset_all_hint), stringResource(R.string.ctrl_reset), a.onResetAll) }
} }
@Composable @Composable
@@ -90,9 +90,8 @@ fun ControllerMappingPage(mapping: Map<String, String>, onPick: (String, String)
onBack = onBack, onBack = onBack,
) { ) {
SettingsGroup(stringResource(R.string.ctrl_onscreen_buttons)) { SettingsGroup(stringResource(R.string.ctrl_onscreen_buttons)) {
val targets = ControllerPrefs.targets.map { (id, label) -> id to stringResource(label) }
for ((id, name) in ControllerPrefs.mappable) { for ((id, name) in ControllerPrefs.mappable) {
ChoiceRow(host, "map-$id", stringResource(name), null, targets, mapping[id] ?: id) { onPick(id, it) } ChoiceRow(host, "map-$id", name, null, ControllerPrefs.targets, mapping[id] ?: id) { onPick(id, it) }
} }
} }
SettingsGroup(stringResource(R.string.ctrl_defaults)) { SettingsGroup(stringResource(R.string.ctrl_defaults)) {
@@ -197,7 +197,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false), color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
) )
if (row.tag.isNotEmpty()) Text( if (row.tag.isNotEmpty()) Text(
driverTagLabel(row.tag), fontSize = 11.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = colors.onSurfaceVariant, row.tag, fontSize = 11.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = 8.dp).clip(RoundedCornerShape(5.dp)).background(Color.White.copy(alpha = 0.07f)) modifier = Modifier.padding(start = 8.dp).clip(RoundedCornerShape(5.dp)).background(Color.White.copy(alpha = 0.07f))
.padding(horizontal = 6.dp, vertical = 2.dp), .padding(horizontal = 6.dp, vertical = 2.dp),
) )
@@ -1,56 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
/**
* One line of text in a slot of fixed width - a rail label, a key cap - set as large as
* [maxSize] when it fits and smaller, down to [minSize], when it does not. Labels are as long as
* their language makes them ("Components" is "コンポーネント", "Componentes", "구성 요소"), so a
* fixed size cuts some of them off; below [minSize] the end is ellipsized rather than clipped.
*/
@Composable
fun FitText(
text: String,
maxSize: TextUnit,
minSize: TextUnit = 9.sp,
modifier: Modifier = Modifier,
fontWeight: FontWeight? = null,
color: Color = Color.Unspecified,
) {
BoxWithConstraints(modifier, contentAlignment = Alignment.Center) {
val measurer = rememberTextMeasurer()
val style = LocalTextStyle.current
val width = constraints.maxWidth
val size = remember(text, width, maxSize, minSize, fontWeight, style) {
if (width == Constraints.Infinity) return@remember maxSize
var s = maxSize.value
while (s > minSize.value) {
val measured = measurer.measure(
text, style.copy(fontSize = s.sp, fontWeight = fontWeight ?: style.fontWeight),
maxLines = 1, softWrap = false,
)
if (measured.size.width <= width) break
s -= 0.5f
}
s.coerceAtLeast(minSize.value).sp
}
Text(
text, fontSize = size, fontWeight = fontWeight, color = color, maxLines = 1, softWrap = false,
overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center,
)
}
}
@@ -119,6 +119,7 @@ internal fun Pane(
val pal = LocalPalette.current val pal = LocalPalette.current
// Pages keep drawing while they leave, so one can fold away instead of blinking out. // Pages keep drawing while they leave, so one can fold away instead of blinking out.
val pages = remember { HashMap<String, @Composable () -> Unit>() } val pages = remember { HashMap<String, @Composable () -> Unit>() }
val savedPages = androidx.compose.runtime.saveable.rememberSaveableStateHolder()
// Pages opened from a control (the cog), with where that control sat, in this pane's coordinates. // Pages opened from a control (the cog), with where that control sat, in this pane's coordinates.
val origins = remember { HashMap<String, Origin>() } val origins = remember { HashMap<String, Origin>() }
val paneAt = remember { arrayOf(Offset.Zero) } val paneAt = remember { arrayOf(Offset.Zero) }
@@ -154,6 +155,7 @@ internal fun Pane(
label = "pane", label = "pane",
) { key -> ) { key ->
val shown = if (page != null && key == s.pageKey) page else pages[key] val shown = if (page != null && key == s.pageKey) page else pages[key]
savedPages.SaveableStateProvider(key) {
if (shown != null) { if (shown != null) {
DisposableEffect(key) { onDispose { if (key != livePage) { pages.remove(key); origins.remove(key) } } } DisposableEffect(key) { onDispose { if (key != livePage) { pages.remove(key); origins.remove(key) } } }
val from = origins[key] val from = origins[key]
@@ -168,6 +170,7 @@ internal fun Pane(
} }
} }
else Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb) else Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb)
}
} }
} }
} }
@@ -209,10 +212,10 @@ private fun Content(
val narrow = LocalNarrowPane.current val narrow = LocalNarrowPane.current
val padH = if (narrow) 16.dp else 22.dp val padH = if (narrow) 16.dp else 22.dp
val padV = if (narrow) 12.dp else 18.dp val padV = if (narrow) 12.dp else 18.dp
// Setup scrolls inside itself, under its tabs. // Settings has its own search and scrolling.
if (selected == "setup") { if (selected == "settings") {
Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) { Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) {
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb) SettingsHub(s, a)
} }
return return
} }
@@ -307,7 +310,7 @@ private fun Content(
Column { Column {
Text(e.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) Text(e.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text( Text(
systemLabel(e).let { if (e.installed) it else stringResource(R.string.content_not_installed_suffix, it) }, e.system.replaceFirstChar { it.uppercase() }.let { if (e.installed) it else stringResource(R.string.content_not_installed_suffix, it) },
fontSize = 14.sp, color = colors.onSurfaceVariant, fontSize = 14.sp, color = colors.onSurfaceVariant,
) )
} }
@@ -334,7 +337,7 @@ private fun Content(
) )
} }
else Rise(5, Modifier.fillMaxWidth()) { else Rise(5, Modifier.fillMaxWidth()) {
ArtGrid(e.games.mapIndexed { index, g -> Tile(g.name, if (g.art != null) stringResource(R.string.content_rom_installed) else g.hostPath.extension.uppercase().ifEmpty { stringResource(R.string.content_rom_folder) }, g.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") } }, wide = e.games.none { it.art != null }) ArtGrid(e.games.mapIndexed { index, g -> Tile(g.name, if (g.art != null) "installed" else g.hostPath.extension.uppercase().ifEmpty { "folder" }, g.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") } }, wide = e.games.none { it.art != null })
} }
} else { } else {
if (pkg != null) Rise(2) { if (pkg != null) Rise(2) {
@@ -379,7 +382,7 @@ private fun Content(
Rise(0) { Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
BackLink(e.name) { onSelect("emu:${e.id}") } BackLink(e.name) { onSelect("emu:${e.id}") }
Eyebrow(stringResource(R.string.content_desktop_system, systemLabel(e))) Eyebrow(stringResource(R.string.content_desktop_system, e.system))
} }
} }
Rise(1) { Title(g.name) } Rise(1) { Title(g.name) }
@@ -391,7 +394,7 @@ private fun Content(
Actions { Actions {
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp)) Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
PrimaryButton(stringResource(R.string.content_launch_in, e.name), enabled = !s.busy, main = true) { a.onRom(g) } PrimaryButton(stringResource(R.string.content_launch_in, e.name), enabled = !s.busy, main = true) { a.onRom(g) }
if (s.busy) BusyChip(s) else ActionChip(g.hostPath.extension.uppercase().ifEmpty { stringResource(R.string.content_rom_folder) }, ok = false) if (s.busy) BusyChip(s) else ActionChip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false)
} }
} }
if (g.art != null && !narrow) Poster(g.art, g.name, Modifier.width(detailPosterWidth)) if (g.art != null && !narrow) Poster(g.art, g.name, Modifier.width(detailPosterWidth))
@@ -403,7 +406,7 @@ private fun Content(
Rise(4, Modifier.fillMaxWidth()) { Rise(4, Modifier.fillMaxWidth()) {
ArtGrid(others.map { x -> ArtGrid(others.map { x ->
val index = e.games.indexOf(x) val index = e.games.indexOf(x)
Tile(x.name, if (x.art != null) stringResource(R.string.content_rom_installed) else x.hostPath.extension.uppercase().ifEmpty { stringResource(R.string.content_rom_folder) }, x.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") } Tile(x.name, if (x.art != null) "installed" else x.hostPath.extension.uppercase().ifEmpty { "folder" }, x.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") }
}, wide = others.none { it.art != null }) }, wide = others.none { it.art != null })
} }
} }
@@ -419,6 +422,7 @@ private fun Content(
private fun DesktopCard(s: FrontEndState, a: FrontEndActions) { private fun DesktopCard(s: FrontEndState, a: FrontEndActions) {
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val actions: @Composable () -> Unit = { val actions: @Composable () -> Unit = {
Actions { Actions {
// Enabled without a runtime or the desktop: the session's loading screen installs them first. // Enabled without a runtime or the desktop: the session's loading screen installs them first.
@@ -427,33 +431,25 @@ private fun DesktopCard(s: FrontEndState, a: FrontEndActions) {
BusyChip(s) BusyChip(s)
} }
} }
// The button goes under the title unless the card is wide enough for both side by side: in some Column(
// languages its label alone takes half a small phone's pane. verticalArrangement = Arrangement.spacedBy(14.dp),
BoxWithConstraints(Modifier.fillMaxWidth()) { modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(16.dp),
val narrow = LocalNarrowPane.current || maxWidth < DesktopCardInlineWidth ) {
Column( Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
verticalArrangement = Arrangement.spacedBy(14.dp), Box(
modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(16.dp), contentAlignment = Alignment.Center,
) { modifier = Modifier.size(52.dp).clip(Shape14).background(colors.surfaceVariant).border(1.dp, pal.line2, Shape14),
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) { ) { Icon(Icons.Outlined.DesktopWindows, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(26.dp)) }
Box( Column(modifier = Modifier.weight(1f)) {
contentAlignment = Alignment.Center, Text(stringResource(R.string.content_linux_desktop), fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
modifier = Modifier.size(52.dp).clip(Shape14).background(colors.surfaceVariant).border(1.dp, pal.line2, Shape14), Text(stringResource(R.string.content_linux_desktop_hint), fontSize = 14.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
) { Icon(Icons.Outlined.DesktopWindows, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(26.dp)) }
Column(modifier = Modifier.weight(1f)) {
Text(stringResource(R.string.content_linux_desktop), fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(stringResource(R.string.content_linux_desktop_hint), fontSize = 14.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
if (!narrow) actions()
} }
if (narrow) actions() if (!narrow) actions()
} }
if (narrow) actions()
} }
} }
/** How wide the desktop card must be to keep its button beside the title. */
private val DesktopCardInlineWidth = 640.dp
/** What the Desktop page's grids hold: emulators, the user's own apps, and Add at the end. */ /** What the Desktop page's grids hold: emulators, the user's own apps, and Add at the end. */
private sealed class GridItem(val key: String) { private sealed class GridItem(val key: String) {
class Emu(val e: Library.Emulator) : GridItem("emu:${e.id}") class Emu(val e: Library.Emulator) : GridItem("emu:${e.id}")
@@ -461,33 +457,25 @@ private sealed class GridItem(val key: String) {
data object Add : GridItem("add") data object Add : GridItem("add")
} }
/** Wide tiles - three across, two on a small phone, or a list on a narrow page. */ /** Wide tiles - three across, or a list on a narrow page. */
@Composable @Composable
private fun LauncherGrid(items: List<GridItem>, first: Boolean, onSelect: (String) -> Unit, onAdd: () -> Unit = {}) { private fun LauncherGrid(items: List<GridItem>, first: Boolean, onSelect: (String) -> Unit, onAdd: () -> Unit = {}) {
BoxWithConstraints(Modifier.fillMaxWidth()) { val columns = if (LocalNarrowPane.current) 1 else 3
// A tile holds an icon, a name and an Install button: one much under 230dp wide leaves the Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) {
// name no room at all. items.chunked(columns).forEachIndexed { r, row ->
val columns = when { Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
LocalNarrowPane.current -> 1 row.forEachIndexed { i, item ->
maxWidth < 720.dp -> 2 key(item.key) {
else -> 3 val m = Modifier.weight(1f).fillMaxHeight()
} val isFirst = first && r == 0 && i == 0
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) { when (item) {
items.chunked(columns).forEachIndexed { r, row -> is GridItem.Emu -> EmulatorTile(item.e, m, isFirst) { onSelect(item.key) }
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) { is GridItem.User -> UserAppTile(item.app, m, isFirst) { onSelect(item.key) }
row.forEachIndexed { i, item -> GridItem.Add -> AddTile(m, isFirst, onAdd)
key(item.key) {
val m = Modifier.weight(1f).fillMaxHeight()
val isFirst = first && r == 0 && i == 0
when (item) {
is GridItem.Emu -> EmulatorTile(item.e, m, isFirst) { onSelect(item.key) }
is GridItem.User -> UserAppTile(item.app, m, isFirst) { onSelect(item.key) }
GridItem.Add -> AddTile(m, isFirst, onAdd)
}
} }
} }
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
} }
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
} }
} }
} }
@@ -673,14 +661,10 @@ private fun UpdateButton(app: UserApps.App, s: FrontEndState) {
* contrast - dimming it read as disabled rather than one press from installing. * contrast - dimming it read as disabled rather than one press from installing.
*/ */
@Composable @Composable
private fun systemLabel(e: Library.Emulator): String =
if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { it.uppercase() }
@Composable
private fun EmulatorTile(e: Library.Emulator, modifier: Modifier, isFirst: Boolean, onClick: () -> Unit) { private fun EmulatorTile(e: Library.Emulator, modifier: Modifier, isFirst: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
val system = systemLabel(e) val system = e.system.replaceFirstChar { it.uppercase() }
val detail = if (e.installed && e.id != "retroarch") "$system · " + pluralStringResource(R.plurals.mode_added_count, e.games.size, e.games.size) else system val detail = if (e.installed && e.id != "retroarch") "$system · " + pluralStringResource(R.plurals.mode_added_count, e.games.size, e.games.size) else system
TileFrame("emu:${e.id}", modifier, isFirst, filled = e.installed, onClick = onClick) { TileFrame("emu:${e.id}", modifier, isFirst, filled = e.installed, onClick = onClick) {
Image(painterResource(e.iconRes), contentDescription = null, modifier = Modifier.size(if (e.installed) 44.dp else 36.dp)) Image(painterResource(e.iconRes), contentDescription = null, modifier = Modifier.size(if (e.installed) 44.dp else 36.dp))
@@ -284,7 +284,7 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni
} }
} }
/** A page's title, with room at its right for controls or status. */ /** A page's title, with room at its right for a status chip. */
@Composable @Composable
internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit = {}) { internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit = {}) {
Row( Row(
@@ -93,14 +93,14 @@ internal fun SideRail(
val compact = LocalConfiguration.current.screenHeightDp < 420 val compact = LocalConfiguration.current.screenHeightDp < 420
// Under 600dp wide (4:3 and square screens) the labels would cost a fifth of the width. // Under 600dp wide (4:3 and square screens) the labels would cost a fifth of the width.
val iconOnly = isNarrowScreen() val iconOnly = isNarrowScreen()
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) || val settingsNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
Column( Column(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp), 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. // Every section on screen at once: items shrink (to 44dp, still a touch target) before the rail scrolls.
val count = 6 + (if (s.storeEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0) val count = 5 + (if (s.storeEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0)
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { 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) val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
Column( Column(
@@ -113,10 +113,9 @@ internal fun SideRail(
RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, fit, onFocus = { onFocusSelect("games") }) { onSelect("games") } RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, fit, onFocus = { onFocusSelect("games") }) { onSelect("games") }
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, fit, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") } RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, fit, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
if (s.storeEnabled) RailItem(stringResource(R.string.rail_store), Icons.Outlined.Storefront, "store", selected == "store", compact, iconOnly, fit, onFocus = { onFocusSelect("store") }) { onSelect("store") } if (s.storeEnabled) RailItem(stringResource(R.string.rail_store), Icons.Outlined.Storefront, "store", selected == "store", compact, iconOnly, fit, onFocus = { onFocusSelect("store") }) { onSelect("store") }
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", selected == "components", compact, iconOnly, fit, onFocus = { onFocusSelect("components") }) { onSelect("components") }
// Home mode's extra section goes last, so it shifts nothing above it. // Home mode's extra section goes last, so it shifts nothing above it.
if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, fit, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") } if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, fit, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
RailItem(stringResource(R.string.rail_setup), Icons.Outlined.Tune, "setup", selected == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, onFocus = { onFocusSelect("setup") }) { onSelect("setup") } RailItem(stringResource(R.string.settings_title), Icons.Outlined.Tune, "settings", selected == "settings", compact, iconOnly, fit, badge = settingsNeedsAttention, onFocus = { onFocusSelect("settings") }) { onSelect("settings") }
RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", selected == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, onFocus = { onFocusSelect("updates") }) { onSelect("updates") } RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", selected == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, onFocus = { onFocusSelect("updates") }) { onSelect("updates") }
} }
} }
@@ -174,7 +173,7 @@ private fun RailItem(
if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp)) if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp))
else Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) { else Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {
Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (height < 56.dp) 20.dp else 22.dp)) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (height < 56.dp) 20.dp else 22.dp))
FitText(label, maxSize = 12.sp, modifier = Modifier.padding(horizontal = 4.dp), fontWeight = FontWeight.SemiBold, color = fg) Text(label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = fg, maxLines = 1, softWrap = false)
} }
if (badge) Box( if (badge) Box(
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 7.dp else 8.dp, end = if (iconOnly) 9.dp else 18.dp) modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 7.dp else 8.dp, end = if (iconOnly) 9.dp else 18.dp)
@@ -100,10 +100,11 @@ class FrontEndState(
val shortcutLibraryScanning: Boolean = false, val shortcutLibraryScanning: Boolean = false,
val gameSyncFolder: String? = null, val gameSyncFolder: String? = null,
val pageKey: String? = null, val pageKey: String? = null,
val settingsCategory: SettingsCategory? = null,
val settingsMode: String = "steam",
val settingsTarget: String? = null,
val requestedRailTab: String? = null,
val theme: String = Themes.GRAPHITE, val theme: String = Themes.GRAPHITE,
/** The language picked in Setup, or AppLanguage.SYSTEM to follow the system. */
val language: String = "",
val appScale: Int = com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE,
val isHomeApp: Boolean = false, val isHomeApp: Boolean = false,
val homeScreenEnabled: Boolean = false, val homeScreenEnabled: Boolean = false,
val defaultHomeLabel: String? = null, val defaultHomeLabel: String? = null,
@@ -125,7 +126,7 @@ class FrontEndState(
val showPhantomGate: Boolean = false, val showPhantomGate: Boolean = false,
val launcherFullscreen: Boolean = true, val launcherFullscreen: Boolean = true,
val animationsEnabled: Boolean = true, val animationsEnabled: Boolean = true,
/** The Flathub Store, a beta the user turns on in Setup. */ /** The Flathub Store, a beta the user turns on in Settings. */
val storeEnabled: Boolean = false, val storeEnabled: Boolean = false,
/** The Updates page: DroidDeck's own builds and the channel followed. */ /** The Updates page: DroidDeck's own builds and the channel followed. */
val updates: UpdatesState = UpdatesState(), val updates: UpdatesState = UpdatesState(),
@@ -170,9 +171,12 @@ class FrontEndActions(
val onClearLogs: () -> Unit = {}, val onClearLogs: () -> Unit = {},
val onOffline: () -> Unit, val onOffline: () -> Unit,
val onPageBack: () -> Unit = {}, val onPageBack: () -> Unit = {},
val onCloseSettings: () -> Unit = {},
val onSettingsCategory: (SettingsCategory, String?) -> Unit = { _, _ -> },
val onSettingsMode: (String) -> Unit = {},
val onOpenUpdates: () -> Unit = {},
val onRailTabHandled: () -> Unit = {},
val onTheme: (String) -> Unit = {}, val onTheme: (String) -> Unit = {},
val onLanguage: (String) -> Unit = {},
val onAppScale: (Int) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {}, val onAnimationsEnabled: (Boolean) -> Unit = {},
val onStoreEnabled: (Boolean) -> Unit = {}, val onStoreEnabled: (Boolean) -> Unit = {},
@@ -182,10 +186,10 @@ class FrontEndActions(
val onBackActionsInverted: (Boolean) -> Unit = {}, val onBackActionsInverted: (Boolean) -> Unit = {},
val onRefreshPhantomStatus: () -> Unit = {}, val onRefreshPhantomStatus: () -> Unit = {},
val onOpenDeveloperOptions: (Int?) -> Unit = {}, val onOpenDeveloperOptions: (Int?) -> Unit = {},
val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit, val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless debugging is unavailable") },
val onFindWirelessAdbPort: (String, (Int?) -> Unit) -> Unit = { _, done -> done(null) }, val onFindWirelessAdbPort: (String, (Int?) -> Unit) -> Unit = { _, done -> done(null) },
val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit, val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless debugging is unavailable") },
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit, val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit = { _, done -> done("Wireless debugging is unavailable") },
val onCopyPhantomCommand: (Boolean) -> Unit = {}, val onCopyPhantomCommand: (Boolean) -> Unit = {},
val onDismissPhantomGate: () -> Unit = {}, val onDismissPhantomGate: () -> Unit = {},
val onStartWirelessAdbPairing: () -> Unit = {}, val onStartWirelessAdbPairing: () -> Unit = {},
@@ -343,14 +347,22 @@ internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusR
} }
@Composable @Composable
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) { fun FrontEndScreen(
s: FrontEndState,
a: FrontEndActions,
page: (@Composable () -> Unit)? = null,
settingsContent: (@Composable (FrontEndState, FrontEndActions, () -> Unit, (Boolean) -> Unit) -> Unit)? = null,
) {
val frontFocus = remember { FrontFocus() } val frontFocus = remember { FrontFocus() }
CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) } CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus, settingsContent) }
} }
@OptIn(ExperimentalComposeUiApi::class) @OptIn(ExperimentalComposeUiApi::class)
@Composable @Composable
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) { private fun FrontEndScreenBody(
s: FrontEndState, a: FrontEndActions, externalPage: (@Composable () -> Unit)?, frontFocus: FrontFocus,
settingsContent: (@Composable (FrontEndState, FrontEndActions, () -> Unit, (Boolean) -> Unit) -> Unit)?,
) {
var selected by rememberSaveable { mutableStateOf(if (s.shortcutPicker) "games" else "steam") } var selected by rememberSaveable { mutableStateOf(if (s.shortcutPicker) "games" else "steam") }
LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" } LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" }
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) } var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
@@ -370,6 +382,14 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
wirelessAdbDesiredEnabled = enabled wirelessAdbDesiredEnabled = enabled
showWirelessAdbFix = true showWirelessAdbFix = true
} }
val page: (@Composable () -> Unit)? = if (s.settingsCategory != null && settingsContent != null) {
{ settingsContent(s, a, requestDeveloperOptions, requestWirelessAdbFix) }
} else externalPage?.let { content ->
{ CompositionLocalProvider(LocalSettingsTarget provides s.settingsTarget, LocalSettingsAnchorsEnabled provides true) { content() } }
}
LaunchedEffect(s.requestedRailTab) {
s.requestedRailTab?.let { selected = it; a.onRailTabHandled() }
}
LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) { LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) {
if (phantomGateVisible) { if (phantomGateVisible) {
while (true) { while (true) {
@@ -388,7 +408,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop" selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop"
} }
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" } LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
// The Store turned off in Setup takes its page with it. // The Store turned off in Settings takes its page with it.
LaunchedEffect(s.storeEnabled) { if (!s.storeEnabled && selected == "store") selected = "steam" } LaunchedEffect(s.storeEnabled) { if (!s.storeEnabled && selected == "store") selected = "steam" }
// The last game uninstalled leaves the Games tab on its empty state. // The last game uninstalled leaves the Games tab on its empty state.
LaunchedEffect(s.steamGames.isEmpty()) { LaunchedEffect(s.steamGames.isEmpty()) {
@@ -397,23 +417,15 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
remember { Motion.refresh(ctx); true } remember { Motion.refresh(ctx); true }
val railSelection = when { val railSelection = when {
s.pageKey == "performance" || s.pageKey == "protons" || s.pageKey == "controller-mapping" -> "setup" s.pageKey != null -> "settings"
s.pageKey?.startsWith("settings:steam") == true -> "steam"
s.pageKey?.startsWith("settings:") == true -> "desktop"
selected.startsWith("app:") -> "games" selected.startsWith("app:") -> "games"
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") -> "desktop" selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") -> "desktop"
else -> s.pageKey ?: selected else -> selected
} }
// Bumped each time a rail item is picked, so a controller moves on into the new page.
var railPicks by remember { mutableStateOf(0) } var railPicks by remember { mutableStateOf(0) }
val showRailPage: (String, Boolean) -> Unit = { key, focusContent -> val showRailPage: (String, Boolean) -> Unit = { key, _ ->
// Components is a full page like Protons or Performance, opened over the current rail if (s.pageKey != null) a.onCloseSettings()
// selection rather than replacing it. selected = key
if (key == "components") a.onComponents(focusContent)
else {
if (s.pageKey != null) a.onPageBack()
selected = key
}
} }
val onRailFocus: (String) -> Unit = { key -> val onRailFocus: (String) -> Unit = { key ->
if (key != railSelection) showRailPage(key, false) if (key != railSelection) showRailPage(key, false)
@@ -71,14 +71,13 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.AppLanguage
import com.droiddeck.launcher.core.DeviceSupport import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.PhantomProcessLimit import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
// The Setup page: runtime and device checks, tools, frame generation and launch settings. // Existing launcher preference owners, grouped into Settings categories.
private enum class CheckState { OK, WARN, BUSY } private enum class CheckState { OK, WARN, BUSY }
@@ -123,30 +122,134 @@ private fun CheckRow(state: CheckState, title: String, detail: String?, divider:
if (divider) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) if (divider) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
} }
/** Settings owned by Setup's existing state/actions, split into hub categories. */
@Composable @Composable
internal fun SetupPanel( internal fun SetupContent(
s: FrontEndState,
a: FrontEndActions,
category: SettingsCategory,
host: MenuHost,
onOpenDeveloperOptions: () -> Unit,
onRequestWirelessAdb: (Boolean) -> Unit,
) {
when (category) {
SettingsCategory.GENERAL -> GeneralSettings(s, a, host)
SettingsCategory.DISPLAY -> DisplaySettings(s, a, host)
SettingsCategory.CONTROLS -> ControlsSettings(s, a, host)
SettingsCategory.AUDIO -> Unit
SettingsCategory.LIBRARY -> LibrarySettings(s, a)
SettingsCategory.SESSIONS -> SessionSettings(s, a, host)
SettingsCategory.COMPATIBILITY -> CompatibilitySettings(s, a)
SettingsCategory.SUPPORT -> SupportSettings(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
}
}
@Composable
private fun GeneralSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
SettingsGroup(stringResource(R.string.setup_launcher)) {
SettingsAnchor("theme") { SettingsRow(stringResource(R.string.setup_theme), null) {
Box {
ValueChip(Themes.byId(s.theme).label, host.open == "theme") { host.open = if (host.open == "theme") null else "theme" }
AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = stringResource(R.string.setup_theme)) { firstItemFocus ->
Themes.all.forEachIndexed { index, theme ->
MenuItem(theme.label, checked = s.theme == theme.id, focusRequester = if (index == 0) firstItemFocus else null) {
a.onTheme(theme.id)
host.open = null
}
}
}
}
} }
ToggleRow(host, "home-screen", stringResource(R.string.setup_home),
if (s.homeScreenEnabled) stringResource(R.string.setup_home_on) else stringResource(R.string.setup_home_off),
s.homeScreenEnabled) { a.onHomeScreen(it) }
ToggleRow(host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen),
if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off),
s.launcherFullscreen) { a.onLauncherFullscreen(it) }
ToggleRow(host, "launcher-animations", stringResource(R.string.setup_animations), null,
s.animationsEnabled, onChange = a.onAnimationsEnabled)
SettingsAnchor("default-home") {
if (s.homeScreenEnabled) ActionRow(stringResource(R.string.setup_default_home),
s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp)
else SettingsRow(stringResource(R.string.setup_default_home), "Enable Home screen above to choose DroidDeck as the default Home app.") {}
}
}
SettingsGroup(stringResource(R.string.setup_linux_apps)) {
ToggleRow(host, "store-enabled", stringResource(R.string.setup_store),
if (s.storeEnabled) stringResource(R.string.setup_store_on) else stringResource(R.string.setup_store_off),
s.storeEnabled, onChange = a.onStoreEnabled)
}
}
@Composable
private fun DisplaySettings(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
SettingsGroup("Display and graphics") {
SettingsAnchor("fg") { SettingsRow(stringResource(R.string.frame_gen_title), null) {
Box {
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
FrameGenMenu(s, a, host)
}
} }
}
}
@Composable
private fun ControlsSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
val controller = s.controller
if (controller != null && a.controller != null) SettingsAnchor("controller-actions") { SettingsGroup(stringResource(R.string.setup_controller)) {
ControllerRows(host, s.oscMode, controller, a.controller)
}
} else Note(stringResource(R.string.setup_controller_unavailable))
SettingsGroup(stringResource(R.string.setup_session)) {
ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), SessionPrefs.backActionsOrder(s.backActionsInverted),
listOf(false to SessionPrefs.BACK_MENU_THEN_QAM, true to SessionPrefs.BACK_QAM_THEN_MENU),
s.backActionsInverted, onPick = a.onBackActionsInverted)
}
}
@Composable
private fun LibrarySettings(s: FrontEndState, a: FrontEndActions) {
SettingsGroup("Library and files") {
val roms = s.romsDir ?: stringResource(R.string.setup_tool_roms_hint)
SettingsAnchor("files") { ActionRow(stringResource(R.string.setup_tool_files), null, "Open", a.onFiles) }
SettingsAnchor("roms") { ActionRow(stringResource(R.string.setup_tool_roms), roms, "Open", a.onRoms) }
}
}
@Composable
private fun SessionSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
SettingsGroup(stringResource(R.string.setup_session)) {
ToggleRow(host, "offline", stringResource(R.string.setup_offline),
s.offlineAccount?.let { stringResource(R.string.setup_signed_in, it) } ?: stringResource(R.string.setup_sign_in_first),
s.offline, enabled = s.offlineAccount != null, onChange = { a.onOffline() })
}
}
@Composable
private fun CompatibilitySettings(s: FrontEndState, a: FrontEndActions) {
SettingsGroup("Compatibility tools") {
SettingsAnchor("components") { ActionRow(stringResource(R.string.setup_card_components), stringResource(R.string.setup_card_components_hint), "Open") { a.onComponents(true) } }
SettingsAnchor("protons") { ActionRow(stringResource(R.string.setup_tool_protons), stringResource(R.string.setup_tool_protons_hint), "Open", a.onProtons) }
SettingsAnchor("performance") { ActionRow(stringResource(R.string.setup_tool_performance), null, "Open", a.onPerformance) }
}
}
@Composable
private fun SupportSettings(
s: FrontEndState, s: FrontEndState,
a: FrontEndActions, a: FrontEndActions,
onOpenDeveloperOptions: () -> Unit, onOpenDeveloperOptions: () -> Unit,
onRequestWirelessAdb: (Boolean) -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
) { ) {
val context = LocalContext.current
val host = rememberMenuHost() val host = rememberMenuHost()
val ctx = LocalContext.current
var processLimitBusy by remember { mutableStateOf(false) } var processLimitBusy by remember { mutableStateOf(false) }
var processLimitMessage by remember { mutableStateOf<String?>(null) } var processLimitMessage by remember { mutableStateOf<String?>(null) }
val setProcessLimit: (Boolean) -> Unit = { enabled -> var showLimitDetails by rememberSaveable { mutableStateOf(false) }
processLimitBusy = true val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
processLimitMessage = null val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() }
a.onSetPhantomProcessLimit(enabled) { error -> val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED
processLimitBusy = false val gpuName = remember { DeviceSupport.gpuName() }
if (error == null) {
a.onRefreshPhantomStatus()
} else {
processLimitMessage = ctx.getString(R.string.setup_limit_adb_failed)
onRequestWirelessAdb(enabled)
}
}
}
val runtime = when { val runtime = when {
s.busy -> stringResource(R.string.common_working) s.busy -> stringResource(R.string.common_working)
s.removalPending -> stringResource(R.string.setup_retry_removal) s.removalPending -> stringResource(R.string.setup_retry_removal)
@@ -154,244 +257,106 @@ internal fun SetupPanel(
s.available != null && s.available != s.installed -> stringResource(R.string.common_update) s.available != null && s.available != s.installed -> stringResource(R.string.common_update)
else -> stringResource(R.string.setup_manage) else -> stringResource(R.string.setup_manage)
} }
val colors = MaterialTheme.colorScheme val setProcessLimit: (Boolean) -> Unit = { enabled ->
val pal = LocalPalette.current processLimitBusy = true
// Tested hardware passes; an Adreno below it (a 610, say) warns rather than claiming support. processLimitMessage = null
val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() } a.onSetPhantomProcessLimit(enabled) { error ->
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED processLimitBusy = false
val gpuName = remember { DeviceSupport.gpuName(ctx) } if (error == null) a.onRefreshPhantomStatus()
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) else {
val signedIn = s.offlineAccount != null processLimitMessage = context.getString(R.string.setup_limit_adb_failed)
var showLimitDetails by rememberSaveable { mutableStateOf(false) } onRequestWirelessAdb(enabled)
// Four tabs instead of one long scroll; LB and RB turn them from anywhere on the page. Build }
// and credits are on the Updates page.
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_session), stringResource(R.string.setup_tab_launcher))
var tab by rememberSaveable { mutableStateOf(0) }
val tabFocus = remember { List(tabs.size) { FocusRequester() } }
var tabTurned by remember { mutableStateOf(false) }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
val inputModeManager = LocalInputModeManager.current
// The control a controller was on went with the old tab: it lands on the new tab itself.
LaunchedEffect(tab) {
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
androidx.compose.runtime.withFrameNanos { }
runCatching { tabFocus[tab].requestFocus() }
} }
} }
Rise(0, Modifier.fillMaxSize()) { SettingsGroup(stringResource(R.string.setup_system_check)) {
Column( Column(modifier = Modifier.fillMaxWidth().clip(Shape14).background(MaterialTheme.colorScheme.surface)
modifier = Modifier.fillMaxSize().bumpers( .border(1.dp, LocalPalette.current.line, Shape14)) {
onPrevious = { pick((tab + tabs.size - 1) % tabs.size) }, CheckRow(
onNext = { pick((tab + 1) % tabs.size) }, if (gpuOk) CheckState.OK else CheckState.WARN,
), when (gpu.support) {
) { com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_supported)
PageHeader(stringResource(R.string.setup_title)) { com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested)
TabStrip(tabs, tab, pick, Modifier.weight(1f), tabFocus) else -> stringResource(R.string.setup_gpu_unsupported)
} },
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { when (gpu.support) {
when (tab) { com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.name, gpuName)
0 -> { com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.name, gpu.supportText.replaceFirstChar { it.lowercase() })
SectionTitle(stringResource(R.string.setup_system_check), null) else -> stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
// What Steam needs, one row each: green when done, one button when not. The },
// process-limit controls only open under their row. )
Column(modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) { SettingsAnchor("runtime") { CheckRow(
CheckRow( when { s.busy -> CheckState.BUSY; !s.ready -> CheckState.WARN; else -> CheckState.OK },
if (gpuOk) CheckState.OK else CheckState.WARN, stringResource(R.string.setup_runtime),
when (gpu.support) { when {
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_supported) s.busy -> null
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested) s.removalPending -> stringResource(R.string.runtime_removal_incomplete)
else -> stringResource(R.string.setup_gpu_unsupported) !s.ready -> stringResource(R.string.setup_runtime_missing)
}, s.available != null && s.available != s.installed -> stringResource(R.string.setup_runtime_update, s.installed ?: stringResource(R.string.setup_installed))
when (gpu.support) { else -> stringResource(R.string.setup_runtime_current, s.installed ?: stringResource(R.string.setup_installed))
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.displayName(ctx), gpuName) },
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() }) divider = !s.busy,
else -> stringResource(R.string.setup_gpu_unsupported_detail, gpuName) ) { SecondaryButton(runtime, enabled = !s.busy && !s.runtimeActionsBlocked && !s.sessionRunning, compact = true, onClick = a.onRuntime) } }
}, if (s.busy) {
) Column(modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 10.dp)) {
CheckRow( Text(if (s.percent >= 0) stringResource(R.string.setup_runtime_progress, s.stage, s.percent) else s.stage,
when { s.busy -> CheckState.BUSY; !s.ready -> CheckState.WARN; else -> CheckState.OK }, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 5.dp))
stringResource(R.string.setup_runtime), if (s.percent >= 0) LinearProgressIndicator(progress = { s.percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
when { else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
s.busy -> null
s.removalPending -> stringResource(R.string.runtime_removal_incomplete)
!s.ready -> stringResource(R.string.setup_runtime_missing)
s.available != null && s.available != s.installed -> stringResource(R.string.setup_runtime_update, s.installed ?: stringResource(R.string.setup_installed))
else -> stringResource(R.string.setup_runtime_current, s.installed ?: stringResource(R.string.setup_installed))
},
divider = !s.busy,
) { SecondaryButton(runtime, enabled = !s.busy && !s.runtimeActionsBlocked && !s.sessionRunning, compact = true, onClick = a.onRuntime) }
if (s.busy) {
Column(modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 10.dp)) {
Text(
if (s.percent >= 0) stringResource(R.string.setup_runtime_progress, s.stage, s.percent) else s.stage,
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 5.dp),
)
if (s.percent >= 0) LinearProgressIndicator(progress = { s.percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
CheckRow(
if (limitBlocks) CheckState.WARN else CheckState.OK,
stringResource(R.string.setup_limit),
when (s.phantomProcessStatus) {
PhantomProcessStatus.ENABLED -> stringResource(R.string.setup_limit_on)
PhantomProcessStatus.UNSET -> stringResource(R.string.setup_limit_unset)
PhantomProcessStatus.UNREADABLE -> stringResource(R.string.setup_limit_unknown)
else -> PhantomProcessLimit.title(ctx, s.phantomProcessStatus)
},
) {
if (limitBlocks) PrimaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_fix_it), compact = true) { showLimitDetails = !showLimitDetails }
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
SecondaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true) { showLimitDetails = !showLimitDetails }
}
}
AnimatedVisibility(showLimitDetails, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
// One sentence and at most three buttons. The computer route and its
// raw command live on the full page Wireless debugging opens.
Column(modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, top = 4.dp, bottom = 10.dp)) {
Text(
if (limitBlocks) PhantomProcessLimit.gateInstructions(ctx, s.phantomProcessStatus)
else PhantomProcessLimit.instructions(ctx, s.phantomProcessStatus),
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
)
Actions {
if (limitBlocks) {
PrimaryButton(stringResource(R.string.setup_dev_options), compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton(stringResource(R.string.setup_use_wireless), compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
SecondaryButton(stringResource(R.string.setup_check_again), compact = true, onClick = a.onRefreshPhantomStatus)
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
}
}
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp))
processLimitMessage?.let { Text(it, fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp)) }
}
}
CheckRow(
if (signedIn) CheckState.OK else CheckState.WARN,
stringResource(R.string.setup_account),
s.offlineAccount?.let {
when {
it.isEmpty() -> stringResource(if (s.offline) R.string.setup_signed_in_offline_unnamed else R.string.setup_signed_in_unnamed)
s.offline -> stringResource(R.string.setup_signed_in_offline, it)
else -> stringResource(R.string.setup_signed_in, it)
}
} ?: stringResource(R.string.setup_sign_in),
divider = false,
)
}
SectionTitle(stringResource(R.string.setup_tools), null)
ToolGrid(s, a)
}
1 -> {
val controller = s.controller
if (controller != null && a.controller != null) SettingsGroup(stringResource(R.string.setup_controller)) {
ControllerRows(host, s.oscMode, controller, a.controller)
}
if (s.controller == null || a.controller == null) Note(stringResource(R.string.setup_controller_unavailable))
}
2 -> {
SettingsGroup(stringResource(R.string.setup_session)) {
ChoiceRow(
host, "back-actions", stringResource(R.string.mode_back), stringResource(SessionPrefs.backActionsOrder(s.backActionsInverted)),
listOf(
false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM),
true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU),
), s.backActionsInverted, onPick = a.onBackActionsInverted,
)
SettingsRow(stringResource(R.string.frame_gen_title), stringResource(R.string.frame_gen_hint)) {
Box {
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
FrameGenMenu(s, a, host)
}
}
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs)
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
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() }
}
}
3 -> {
SettingsGroup(stringResource(R.string.setup_launcher)) {
LanguageRow(host, s.language, a.onLanguage)
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent ->
percent to stringResource(
if (percent == com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) R.string.setup_app_scale_default
else R.string.ctrl_percent, percent,
)
}, s.appScale, onPick = a.onAppScale,
)
SettingsRow(stringResource(R.string.setup_theme), stringResource(R.string.setup_theme_hint)) {
Box {
ValueChip(stringResource(Themes.byId(s.theme).label), host.open == "theme") { host.open = if (host.open == "theme") null else "theme" }
AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = stringResource(R.string.setup_theme)) { firstItemFocus ->
Themes.all.forEachIndexed { index, theme ->
MenuItem(stringResource(theme.label), checked = s.theme == theme.id, focusRequester = if (index == 0) firstItemFocus else null) {
a.onTheme(theme.id)
host.open = null
}
}
}
}
}
ToggleRow(
host, "home-screen", stringResource(R.string.setup_home),
if (s.homeScreenEnabled) stringResource(R.string.setup_home_on) else stringResource(R.string.setup_home_off),
s.homeScreenEnabled,
) { a.onHomeScreen(it) }
ToggleRow(
host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen),
if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off),
s.launcherFullscreen,
) { a.onLauncherFullscreen(it) }
ToggleRow(host, "launcher-animations", stringResource(R.string.setup_animations), null,
s.animationsEnabled, onChange = a.onAnimationsEnabled)
if (s.homeScreenEnabled) {
ActionRow(stringResource(R.string.setup_default_home), s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp)
}
}
SettingsGroup(stringResource(R.string.setup_linux_apps)) {
ToggleRow(
host, "store-enabled", stringResource(R.string.setup_store),
if (s.storeEnabled) stringResource(R.string.setup_store_on)
else stringResource(R.string.setup_store_off),
s.storeEnabled,
) { a.onStoreEnabled(it) }
}
}
} }
} }
SettingsAnchor("phantom-process") { CheckRow(
if (limitBlocks) CheckState.WARN else CheckState.OK,
stringResource(R.string.setup_limit),
when (s.phantomProcessStatus) {
PhantomProcessStatus.ENABLED -> stringResource(R.string.setup_limit_on)
PhantomProcessStatus.UNSET -> stringResource(R.string.setup_limit_unset)
PhantomProcessStatus.UNREADABLE -> stringResource(R.string.setup_limit_unknown)
else -> PhantomProcessLimit.title(s.phantomProcessStatus)
},
) {
if (limitBlocks) PrimaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_fix_it), compact = true) { showLimitDetails = !showLimitDetails }
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) SecondaryButton(
if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true,
) { showLimitDetails = !showLimitDetails }
} }
AnimatedVisibility(showLimitDetails, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
Column(modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, top = 4.dp, bottom = 10.dp)) {
Text(if (limitBlocks) PhantomProcessLimit.gateInstructions(s.phantomProcessStatus) else PhantomProcessLimit.instructions(s.phantomProcessStatus),
fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp))
Actions {
if (limitBlocks) {
PrimaryButton(stringResource(R.string.setup_dev_options), compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton(stringResource(R.string.setup_use_wireless), compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
SecondaryButton(stringResource(R.string.setup_check_again), compact = true, onClick = a.onRefreshPhantomStatus)
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
}
}
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp))
processLimitMessage?.let { Text(it, fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp)) }
}
}
CheckRow(
if (s.offlineAccount != null) CheckState.OK else CheckState.WARN,
stringResource(R.string.setup_account),
s.offlineAccount?.let { if (s.offline) stringResource(R.string.setup_signed_in_offline, it) else stringResource(R.string.setup_signed_in, it) }
?: stringResource(R.string.setup_sign_in),
divider = false,
)
} }
} }
SettingsAnchor("session-logs") { SettingsGroup(stringResource(R.string.setup_session)) {
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
SettingsAnchor("latest-logs") { ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs) }
SettingsAnchor("saved-logs") { ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs) }
} }
SettingsGroup("More support") {
SettingsAnchor("updates") { ActionRow("DroidDeck updates", "Build information and release channel", "Open", a.onOpenUpdates) }
}
} }
/** The launcher's own tools as cards: four across, two by two on a narrow page. */ /** The launcher's own tools as cards: four across, two by two on a narrow page. */
@Composable
private fun ToolGrid(s: FrontEndState, a: FrontEndActions) {
val columns = if (LocalNarrowPane.current) 2 else 4
val tools = listOf(
ToolSpec(Icons.Outlined.Folder, stringResource(R.string.setup_tool_files), stringResource(R.string.setup_tool_files_hint), a.onFiles),
ToolSpec(Icons.Outlined.Extension, stringResource(R.string.setup_tool_protons), stringResource(R.string.setup_tool_protons_hint), a.onProtons),
ToolSpec(Icons.Outlined.Speed, stringResource(R.string.setup_tool_performance), stringResource(R.string.setup_tool_performance_hint), a.onPerformance),
ToolSpec(Icons.Outlined.VideogameAsset, stringResource(R.string.setup_tool_roms), s.romsDir ?: stringResource(R.string.setup_tool_roms_hint), a.onRoms),
)
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
for (row in tools.chunked(columns)) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
for (t in row) ToolCard(t, Modifier.weight(1f).fillMaxHeight())
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
}
}
private class ToolSpec(val icon: ImageVector, val title: String, val detail: String, val onClick: () -> Unit) private class ToolSpec(val icon: ImageVector, val title: String, val detail: String, val onClick: () -> Unit)
@Composable @Composable
@@ -478,32 +443,3 @@ private fun SettingCard(label: String, value: String, id: String, modifier: Modi
Text(value, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) Text(value, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
} }
} }
/**
* The app's language: "System default" (what Android uses, named in brackets) or one of the
* languages the app ships, each in its own script. Steam is set to the same language when it starts.
*/
@Composable
private fun LanguageRow(host: MenuHost, chosen: String, onPick: (String) -> Unit) {
val context = androidx.compose.ui.platform.LocalContext.current
val systemName = AppLanguage.displayName(AppLanguage.system(context))
val systemLabel = stringResource(R.string.setup_language_system, systemName)
SettingsRow(stringResource(R.string.setup_language), stringResource(R.string.setup_language_hint)) {
Box {
ValueChip(if (chosen == AppLanguage.SYSTEM) stringResource(R.string.setup_language_system_short) else AppLanguage.nativeName(chosen),
host.open == "language") { host.open = if (host.open == "language") null else "language" }
AnchoredMenu(host.open == "language", onDismiss = { if (host.open == "language") host.open = null }, title = stringResource(R.string.setup_language)) { firstItemFocus ->
MenuItem(systemLabel, checked = chosen == AppLanguage.SYSTEM, focusRequester = firstItemFocus) {
host.open = null
onPick(AppLanguage.SYSTEM)
}
AppLanguage.supported.forEach { tag ->
MenuItem(AppLanguage.nativeName(tag), checked = chosen == tag) {
host.open = null
onPick(tag)
}
}
}
}
}
}
@@ -217,7 +217,7 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
val fill by animateColorAsState(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f), Motion.tw(250), label = "secFill") val fill by animateColorAsState(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f), Motion.tw(250), label = "secFill")
Box( Box(
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).glideBorder(hot, Shape12, pal.signal, pal.line2) modifier = modifier.paneItem(LocalSettingsAnchorId.current?.let { "setting:$it:$text" } ?: "btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).glideBorder(hot, Shape12, pal.signal, pal.line2)
.alpha(if (enabled) 1f else 0.5f) .alpha(if (enabled) 1f else 0.5f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick)
@@ -52,13 +52,13 @@ import kotlinx.coroutines.withContext
// dialog, with each variable's actions in a menu off its value as everywhere else. // dialog, with each variable's actions in a menu off its value as everywhere else.
@Composable @Composable
fun GameEnvironmentRow(modifier: Modifier = Modifier, showHint: Boolean = true) { fun GameEnvironmentRow(modifier: Modifier = Modifier) {
var open by remember { mutableStateOf(false) } var open by remember { mutableStateOf(false) }
// Opened with a pad, the editor starts with focus in it; the dialog is a window of its own and // Opened with a pad, the editor starts with focus in it; the dialog is a window of its own and
// would otherwise give the pad nothing to move from. // would otherwise give the pad nothing to move from.
var byPad by remember { mutableStateOf(false) } var byPad by remember { mutableStateOf(false) }
val inputMode = LocalInputModeManager.current val inputMode = LocalInputModeManager.current
SettingsRow(stringResource(R.string.game_env_title), if (showHint) stringResource(R.string.game_env_hint) else null) { SettingsRow(stringResource(R.string.game_env_title), stringResource(R.string.game_env_hint)) {
SecondaryButton(stringResource(R.string.game_env_edit), modifier = modifier) { SecondaryButton(stringResource(R.string.game_env_edit), modifier = modifier) {
byPad = inputMode.inputMode == InputMode.Keyboard byPad = inputMode.inputMode == InputMode.Keyboard
open = true open = true
@@ -167,7 +167,7 @@ private fun DriverDropdown(rows: List<DriverRow>, selected: String, fallback: St
Column { Column {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { 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) 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(driverTagLabel(row.tag), fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = colors.onSurfaceVariant) 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) if (row.detail.isNotEmpty()) Text(row.detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
} }
@@ -200,11 +200,9 @@ private fun DeviceCard(s: GpuDriversState) {
Text(s.gpuName, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) Text(s.gpuName, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(listOf(s.soc, s.gpuFamily).filter { it.isNotEmpty() }.joinToString(" · "), fontSize = 13.sp, color = colors.onSurfaceVariant) Text(listOf(s.soc, s.gpuFamily).filter { it.isNotEmpty() }.joinToString(" · "), fontSize = 13.sp, color = colors.onSurfaceVariant)
} }
// The verdict shares the width with the GPU's name and wraps, rather than taking all it Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
// needs: a long one (in some languages) would squeeze the name to a letter a line.
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.weight(1f, fill = false)) {
Box(Modifier.size(7.dp).clip(CircleShape).background(tint)) Box(Modifier.size(7.dp).clip(CircleShape).background(tint))
Text(s.supportText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 3, overflow = TextOverflow.Ellipsis) Text(s.supportText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 2)
} }
} }
} }
@@ -0,0 +1,141 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.ScreenEffectLooks
import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.session.SessionPrefs
import java.util.Locale
import kotlin.math.roundToInt
/** Persistent graphics defaults shown in the launcher's settings page. */
@Composable
fun GraphicsSettingsContent(host: MenuHost, upscaler: Int, onUpscaler: (Int) -> Unit) {
val context = LocalContext.current
var effects by remember(context) { mutableStateOf(SessionPrefs.screenEffects(context)) }
var anisotropy by remember(context) { mutableIntStateOf(SessionPrefs.textureAnisotropy(context)) }
var lodBias by remember(context) { mutableStateOf(SessionPrefs.textureLodBias(context)) }
SettingsAdvanced("graphics-effects", stringResource(R.string.drawer_effects), targets = EFFECT_SETTING_IDS) {
ScreenEffectsSettings(
host = host,
effects = effects,
upscaler = upscaler,
onEffects = { value -> SessionPrefs.setScreenEffects(context, value); effects = value },
onUpscaler = onUpscaler,
grouped = false,
)
}
SettingsAdvanced("graphics-texture", stringResource(R.string.drawer_texture), targets = TEXTURE_SETTING_IDS) {
TextureFilteringSettings(
host = host,
anisotropy = anisotropy,
lodBias = lodBias,
onAnisotropy = { value -> SessionPrefs.setTextureAnisotropy(context, value); anisotropy = value },
onLodBias = { value -> SessionPrefs.setTextureLodBias(context, value); lodBias = value },
grouped = false,
)
}
}
/** Screen post-processing settings, shared by new sessions and applied live in the session drawer. */
@Composable
internal fun ScreenEffectsSettings(
host: MenuHost,
effects: ScreenEffects,
upscaler: Int,
onEffects: (ScreenEffects) -> Unit,
onUpscaler: (Int) -> Unit,
grouped: Boolean = true,
track: (String) -> Modifier = { Modifier },
) {
val look = ScreenEffectLooks.match(effects, upscaler)
val rows: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit = {
val looks = ScreenEffectLooks.LOOKS.map { it.name to it.name }
ChoiceRow(host, "effects-look", stringResource(R.string.drawer_look),
look?.desc ?: stringResource(R.string.drawer_effects_hint),
if (look == null) listOf(LOOK_CUSTOM to stringResource(R.string.drawer_look_custom)) + looks else looks,
look?.name ?: LOOK_CUSTOM, chipModifier = track("look"), hintLines = 2) { name ->
ScreenEffectLooks.LOOKS.firstOrNull { it.name == name }?.let { picked ->
picked.scalingMode?.let(onUpscaler)
onEffects(picked.effects)
}
}
ToggleRow(host, "effects-cas", stringResource(R.string.drawer_cas), null, effects.cas, chipModifier = track("cas")) { onEffects(effects.copy(cas = it)) }
SettingsAnchor("effects-cas-level") {
SliderRow(stringResource(R.string.drawer_cas_level), null, effects.casLevel, 0..100, step = 5, enabled = effects.cas,
format = { "$it%" }, modifier = track("cas-level").settingsTarget("effects-cas-level")) { onEffects(effects.copy(casLevel = it)) }
}
ToggleRow(host, "effects-fake-hdr", stringResource(R.string.drawer_fake_hdr), null, effects.hdr, chipModifier = track("fake-hdr")) { onEffects(effects.copy(hdr = it)) }
ToggleRow(host, "effects-deband", stringResource(R.string.drawer_deband), null, effects.deband, chipModifier = track("deband")) { onEffects(effects.copy(deband = it)) }
SettingsAnchor("effects-deband-strength") {
SliderRow(stringResource(R.string.drawer_deband_strength), null, effects.debandStrength, 0..200, step = 5, enabled = effects.deband,
format = { "$it%" }, modifier = track("deband-strength").settingsTarget("effects-deband-strength")) { onEffects(effects.copy(debandStrength = it)) }
}
SettingsAnchor("effects-brightness") {
SliderRow(stringResource(R.string.drawer_brightness), null, effects.brightness, -100..100, step = 2,
format = ::signed, modifier = track("brightness").settingsTarget("effects-brightness")) { onEffects(effects.copy(brightness = it)) }
}
SettingsAnchor("effects-contrast") {
SliderRow(stringResource(R.string.drawer_contrast), null, effects.contrast, -100..100, step = 2,
format = ::signed, modifier = track("contrast").settingsTarget("effects-contrast")) { onEffects(effects.copy(contrast = it)) }
}
SettingsAnchor("effects-gamma") {
SliderRow(stringResource(R.string.drawer_gamma), null, (effects.gamma * 100f).roundToInt(), 50..300, step = 5,
format = { String.format(Locale.US, "%.2f", it / 100f) }, modifier = track("gamma").settingsTarget("effects-gamma")) { onEffects(effects.copy(gamma = it / 100f)) }
}
SettingsAnchor("effects-saturation") {
SliderRow(stringResource(R.string.drawer_saturation), null, effects.saturation, 0..200, step = 5,
format = { "$it%" }, modifier = track("saturation").settingsTarget("effects-saturation")) { onEffects(effects.copy(saturation = it)) }
}
ToggleRow(host, "effects-fxaa", stringResource(R.string.drawer_fxaa), null, effects.fxaa, chipModifier = track("fxaa")) { onEffects(effects.copy(fxaa = it)) }
ToggleRow(host, "effects-toon", stringResource(R.string.drawer_toon), null, effects.toon, chipModifier = track("toon")) { onEffects(effects.copy(toon = it)) }
ToggleRow(host, "effects-crt", stringResource(R.string.drawer_crt), null, effects.crt, chipModifier = track("crt")) { onEffects(effects.copy(crt = it)) }
ToggleRow(host, "effects-ntsc", stringResource(R.string.drawer_ntsc), null, effects.ntsc, chipModifier = track("ntsc")) { onEffects(effects.copy(ntsc = it)) }
}
if (grouped) SettingsGroup(stringResource(R.string.drawer_effects), content = rows)
else androidx.compose.foundation.layout.Column(Modifier.fillMaxWidth(), content = rows)
}
/** DXVK filtering options saved as shared defaults and consumed by each game's next launch. */
@Composable
internal fun TextureFilteringSettings(
host: MenuHost,
anisotropy: Int,
lodBias: String,
onAnisotropy: (Int) -> Unit,
onLodBias: (String) -> Unit,
grouped: Boolean = true,
track: (String) -> Modifier = { Modifier },
) {
val rows: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit = {
ChoiceRow(host, "textures-anisotropy", stringResource(R.string.drawer_anisotropy), stringResource(R.string.drawer_texture_hint),
SessionPrefs.textureAnisotropyChoices, anisotropy, chipModifier = track("anisotropy"), onPick = onAnisotropy)
ChoiceRow(host, "textures-sharpness", stringResource(R.string.drawer_texture_sharpness), stringResource(R.string.drawer_texture_hint),
SessionPrefs.textureLodBiasChoices, lodBias, note = stringResource(R.string.drawer_texture_sharpness_note),
chipModifier = track("texture-sharpness"), onPick = onLodBias)
}
if (grouped) SettingsGroup(stringResource(R.string.drawer_texture), content = rows)
else androidx.compose.foundation.layout.Column(Modifier.fillMaxWidth(), content = rows)
}
private const val LOOK_CUSTOM = "__custom__"
private val EFFECT_SETTING_IDS = setOf(
"effects-look", "effects-cas", "effects-cas-level", "effects-fake-hdr", "effects-deband",
"effects-deband-strength", "effects-brightness", "effects-contrast", "effects-gamma",
"effects-saturation", "effects-fxaa", "effects-toon", "effects-crt", "effects-ntsc",
)
private val TEXTURE_SETTING_IDS = setOf("textures-anisotropy", "textures-sharpness")
private fun signed(value: Int) = if (value > 0) "+$value" else value.toString()
@@ -1,8 +1,6 @@
package com.droiddeck.launcher.ui package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.pluralStringResource
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -39,28 +37,19 @@ class DriverRow(val id: String, val name: String, val detail: String, val remova
} }
} }
/** A [DriverRow.tag] as shown, in the app's language. */
@Composable
internal fun driverTagLabel(tag: String): String = when (tag) {
DriverRow.BUNDLED -> stringResource(R.string.driver_tag_bundled)
DriverRow.DOWNLOADED -> stringResource(R.string.driver_tag_downloaded)
DriverRow.IMPORTED -> stringResource(R.string.driver_tag_imported)
DriverRow.BUNDLE -> stringResource(R.string.driver_tag_bundle)
else -> tag
}
/** A release driver (Banners-Turnip, WinNative) that is not installed yet; [key] is its asset name. */ /** A release driver (Banners-Turnip, WinNative) that is not installed yet; [key] is its asset name. */
class DownloadRow(val key: String, val label: String, val detail: String, val progress: Int? = null) class DownloadRow(val key: String, val label: String, val detail: String, val progress: Int? = null)
class ModeSettings( class ModeSettings(
val mode: String, val mode: String,
val resolution: String, val resolutionCap: Int,
val panelSize: Pair<Int, Int> = 1280 to 720, /** A fixed session size, or null for the cap and shape. */
val customResolution: Pair<Int, Int>? = null,
val shapeMode: String,
val hdr: Boolean, val hdr: Boolean,
val hdrReason: String?, val hdrReason: String?,
/** The GPU drivers in use, as the row that opens them on the Components page says it. */ /** The GPU drivers in use, as the row that opens them on the Components page says it. */
/** The drivers line; null shows Auto. */ val gpuDrivers: String = "Auto",
val gpuDrivers: String? = null,
/** Frames per second the session is capped at; 0 = none. */ /** Frames per second the session is capped at; 0 = none. */
val fpsLimit: Int = 0, val fpsLimit: Int = 0,
val upscaler: Int = 0, val upscaler: Int = 0,
@@ -78,20 +67,19 @@ class ModeSettings(
val mic: Boolean?, val mic: Boolean?,
val renderer: String?, val renderer: String?,
val gameStorage: String? = null, val gameStorage: String? = null,
val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(), val storageOptions: List<Pair<String, String>> = emptyList(),
/** Steam only: record allocation and sampled storage timings in the next session's Share logs. */ /** Steam only: record allocation and sampled storage timings in the next session's Share logs. */
val storageDiagnostics: Boolean = false, val storageDiagnostics: Boolean = false,
val fexPreset: String? = null, val fexPreset: String? = null,
/** Steam only: SessionPrefs.SYNC_* chosen for Proton games; null outside Steam. */ /** Steam only: SessionPrefs.SYNC_* chosen for Proton games; null outside Steam. */
val syncBackend: String? = null, val syncBackend: String? = null,
/** Steam only: forces game windows fullscreen (null = not a Steam page). */ /** Steam only: games are stretched to fill the screen (null = not a Steam page). */
val forceFullscreen: Boolean? = null, val forceFullscreen: Boolean? = null,
val stretch16x9: Boolean? = null, val stretch16x9: Boolean? = null,
/** Steam only: the client branch forced on the command line. */ /** Steam only: the client branch forced on the command line. */
val steamChannel: String? = null, val steamChannel: String? = null,
/** Steam only: enable the SteamOS client interface and its performance controls. */ /** Steam only: enable the SteamOS client interface and its performance controls. */
val steamDeckMode: Boolean = false, val steamDeckMode: Boolean = false,
val steamRepairQueued: Boolean = false,
/** Steam, Deck mode: the QAM's performance overlay (mangoapp) is started. */ /** Steam, Deck mode: the QAM's performance overlay (mangoapp) is started. */
val mangoapp: Boolean = true, val mangoapp: Boolean = true,
/** Steam only: what the pad is to the client (SessionPrefs.CONTROLLER_*); null outside Steam. */ /** Steam only: what the pad is to the client (SessionPrefs.CONTROLLER_*); null outside Steam. */
@@ -115,8 +103,6 @@ class ModeSettings(
val deckyChecking: Boolean = false, val deckyChecking: Boolean = false,
val deckyStage: String? = null, val deckyStage: String? = null,
val deckyPercent: Int = -1, val deckyPercent: Int = -1,
/** The stage is the Decky plugin's binary download. */
val deckyDownloadingBinary: Boolean = false,
val deckyEnabled: Boolean = false, val deckyEnabled: Boolean = false,
val deckySessionRunning: Boolean = false, val deckySessionRunning: Boolean = false,
) )
@@ -125,7 +111,10 @@ class ModeSettings(
class AddedGameRow(val folderPath: String, val folderName: String, val exePath: String, val exeName: String, val candidates: List<Pair<String, String>>) class AddedGameRow(val folderPath: String, val folderName: String, val exePath: String, val exeName: String, val candidates: List<Pair<String, String>>)
class ModeSettingsActions( class ModeSettingsActions(
val onResolution: (String) -> Unit, val onResolution: (Int) -> Unit,
/** Null clears it. */
val onCustomResolution: (Pair<Int, Int>?) -> Unit = {},
val onShape: (String) -> Unit,
val onHdr: (Boolean) -> Unit, val onHdr: (Boolean) -> Unit,
/** Opens the GPU drivers on the Components page: they are shared by every session. */ /** Opens the GPU drivers on the Components page: they are shared by every session. */
val onGpuDrivers: () -> Unit = {}, val onGpuDrivers: () -> Unit = {},
@@ -149,7 +138,6 @@ class ModeSettingsActions(
val onForceFullscreen: (Boolean) -> Unit = {}, val onForceFullscreen: (Boolean) -> Unit = {},
val onStretch16x9: (Boolean) -> Unit = {}, val onStretch16x9: (Boolean) -> Unit = {},
val onSteamChannel: (String) -> Unit = {}, val onSteamChannel: (String) -> Unit = {},
val onSteamRepair: () -> Unit = {},
val onSteamDeckMode: (Boolean) -> Unit = {}, val onSteamDeckMode: (Boolean) -> Unit = {},
val onMangoapp: (Boolean) -> Unit = {}, val onMangoapp: (Boolean) -> Unit = {},
val onSteamController: (String) -> Unit = {}, val onSteamController: (String) -> Unit = {},
@@ -169,158 +157,203 @@ class ModeSettingsActions(
val onDismiss: () -> Unit, val onDismiss: () -> Unit,
) )
private enum class ModeSettingsTab(val label: Int) {
DISPLAY(R.string.drawer_page_display),
CONTROLS(R.string.drawer_page_controls),
GAMES(R.string.game_settings_title),
AUDIO(R.string.mode_audio),
SESSION(R.string.mode_session),
STEAM(R.string.mode_tab_steam),
}
@Composable @Composable
fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
val steam = s.mode == SessionService.MODE_STEAM val steam = s.mode == SessionService.MODE_STEAM
val host = rememberMenuHost() val host = rememberMenuHost()
var confirmDeckyRemoval by remember { mutableStateOf(false) } val pageScroll = androidx.compose.foundation.rememberScrollState()
var explainWifiDiscovery by remember { mutableStateOf(false) }
var tabIndex by androidx.compose.runtime.saveable.rememberSaveable(s.mode) { mutableStateOf(0) }
val tabs = if (steam) ModeSettingsTab.entries else listOf(
ModeSettingsTab.DISPLAY, ModeSettingsTab.CONTROLS, ModeSettingsTab.SESSION,
)
val tab = tabs[tabIndex]
val scrolls = tabs.map { androidx.compose.foundation.rememberScrollState() }
val tabFocus = remember(s.mode) { tabs.map { androidx.compose.ui.focus.FocusRequester() } }
val firstChip = remember { androidx.compose.ui.focus.FocusRequester() } val firstChip = remember { androidx.compose.ui.focus.FocusRequester() }
fun selectTab(index: Int) { host.open = null; tabIndex = index } androidx.compose.runtime.LaunchedEffect(Unit) {
androidx.compose.runtime.LaunchedEffect(steam, tabIndex) { // One frame first: the box has to be laid out before it can take focus. Opened from the
// cog, focus starts on the first control (Resolution) so the d-pad works at once.
androidx.compose.runtime.withFrameNanos { } androidx.compose.runtime.withFrameNanos { }
runCatching { runCatching { firstChip.requestFocus() }
if (tab == ModeSettingsTab.DISPLAY) firstChip.requestFocus()
else tabFocus[tabIndex].requestFocus()
}
} }
SettingsPage( SettingsPage(
host, host,
title = null, title = if (steam) stringResource(R.string.mode_steam_title) else stringResource(R.string.mode_desktop_title),
onBack = a.onDismiss, onBack = a.onDismiss,
scroll = scrolls[tabIndex], scroll = pageScroll,
modifier = Modifier.bumpers(
onPrevious = { selectTab((tabIndex + tabs.size - 1) % tabs.size) },
onNext = { selectTab((tabIndex + 1) % tabs.size) },
),
header = {
TabStrip(tabs.map { stringResource(it.label) }, tabIndex, ::selectTab,
modifier = Modifier.fillMaxWidth(), focusRequesters = tabFocus)
},
) { ) {
if (tab == ModeSettingsTab.DISPLAY) { for (category in SettingsCategory.values()) {
val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution) ModeSettingsContent(s, a, category, host, firstChip)
SettingsGroup(stringResource(R.string.display_session)) { }
ResolutionRow(host, s.resolution, s.panelSize, a.onResolution, }
chipModifier = Modifier.focusRequester(firstChip)) }
if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) ||
com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) { /** Renders only the mode-specific rows for one Settings hub category. */
val canStretch = com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize) @Composable
ChoiceRow(host, "game-fit", stringResource(R.string.display_game_fit), fun ModeSettingsContent(
stringResource(if (canStretch) R.string.display_game_fit_hint else R.string.display_game_fit_unavailable), s: ModeSettings,
listOf(false to stringResource(R.string.display_preserve), true to stringResource(R.string.display_stretch)), a: ModeSettingsActions,
s.stretch16x9 && canStretch, enabled = canStretch, onPick = a.onStretch16x9) category: SettingsCategory,
host: MenuHost,
firstChip: androidx.compose.ui.focus.FocusRequester? = null,
) {
val steam = s.mode == SessionService.MODE_STEAM
var confirmDeckyRemoval by remember { mutableStateOf(false) }
var explainWifiDiscovery by remember { mutableStateOf(false) }
when (category) {
SettingsCategory.DISPLAY -> {
SettingsGroup(stringResource(R.string.mode_display)) {
val default = SessionPrefs.defaultResolutionCap(s.mode)
var editCustom by remember { mutableStateOf(false) }
val custom = s.customResolution
ChoiceRow(
host, "res", stringResource(R.string.mode_resolution), stringResource(R.string.common_applies_next_session),
listOf(720 to stringResource(R.string.mode_res_720), 900 to stringResource(R.string.mode_res_900), 1080 to stringResource(R.string.mode_res_1080), 0 to stringResource(R.string.mode_res_native))
.map { (cap, label) -> cap to (if (cap == default) stringResource(R.string.mode_res_default, label) else label) } +
(CUSTOM to (custom?.let { stringResource(R.string.mode_res_custom_value, it.first, it.second) } ?: stringResource(R.string.mode_res_custom))),
if (custom != null) CUSTOM else s.resolutionCap, note = stringResource(R.string.mode_res_note),
chipModifier = firstChip?.let { androidx.compose.ui.Modifier.focusRequester(it) } ?: androidx.compose.ui.Modifier,
onPick = { v -> if (v == CUSTOM) editCustom = true else { a.onCustomResolution(null); a.onResolution(v) } },
)
ChoiceRow(
host, "shape", stringResource(R.string.mode_ratio),
"Shared · " + if (custom != null) stringResource(R.string.mode_ratio_custom) else stringResource(R.string.mode_ratio_auto),
com.droiddeck.launcher.session.SessionPrefs.shapeChoices, s.shapeMode, enabled = custom == null, onPick = a.onShape,
)
ChoiceRow(
host, "fps", stringResource(R.string.mode_fps), stringResource(R.string.common_applies_next_session),
com.droiddeck.launcher.session.SessionPrefs.fpsLimitChoices, s.fpsLimit,
note = stringResource(R.string.mode_fps_note),
onPick = a.onFpsLimit,
)
ChoiceRow(
host, "upscaler", stringResource(R.string.drawer_scaling), "Shared · Applies next session.",
com.droiddeck.launcher.session.SessionPrefs.upscalerChoices, s.upscaler,
note = "The sharpening modes work only when the session is smaller than the screen; Linear, Nearest and Sharpen only work at any size. Costs a little GPU time.",
onPick = a.onUpscaler,
)
SettingsAnchor("upscale-sharpness") { SliderRow(
stringResource(R.string.drawer_scaling_sharpness), "Shared · Applies next session.", s.upscaleSharpness, 0..100, step = 5,
enabled = s.upscaler != 0, format = { "$it%" }, onChange = a.onUpscaleSharpness,
) }
if (editCustom) CustomResolutionDialog(
initial = custom,
onSave = { size -> editCustom = false; a.onCustomResolution(size) },
onDismiss = { editCustom = false },
)
}
SettingsGroup(stringResource(R.string.mode_hdr)) {
ToggleRow(
host, "hdr", stringResource(R.string.mode_hdr10),
s.hdrReason?.let { stringResource(R.string.mode_hdr_unavailable, it) }
?: stringResource(R.string.mode_hdr_restart),
checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr,
)
}
if (s.forceFullscreen != null) SettingsGroup(stringResource(R.string.mode_display)) {
ToggleRow(host, "fill", stringResource(R.string.mode_fill), stringResource(R.string.mode_fill_hint), s.forceFullscreen, onChange = a.onForceFullscreen)
if (s.stretch16x9 != null) ToggleRow(host, "stretch169", stringResource(R.string.mode_stretch169), stringResource(R.string.mode_stretch169_hint), s.stretch16x9, onChange = a.onStretch16x9)
}
if (steam) SettingsGroup(stringResource(R.string.mode_client)) {
ToggleRow(host, "mangoapp", stringResource(R.string.mode_mangoapp),
if (s.steamDeckMode) stringResource(R.string.mode_mangoapp_hint) else "Enable Steam Deck mode in Sessions to use this overlay. Applies next session.",
s.mangoapp, enabled = s.steamDeckMode, onChange = a.onMangoapp)
}
}
SettingsCategory.CONTROLS -> {
SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) {
ChoiceRow(
host, "touch", stringResource(R.string.mode_touch), "Shared · Applies next session.",
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), s.touchMode,
note = stringResource(R.string.mode_touch_note),
onPick = a.onTouch,
)
if (steam && s.steamController != null) ChoiceRow(
host, "controller", stringResource(R.string.mode_controller), stringResource(R.string.mode_controller_hint),
listOf(
SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360),
), s.steamController,
note = stringResource(R.string.mode_controller_note),
onPick = a.onSteamController,
)
}
}
SettingsCategory.AUDIO -> {
if (steam && s.directAudio != null && s.mic != null) SettingsGroup(stringResource(R.string.mode_audio)) {
ToggleRow(host, "da", stringResource(R.string.mode_directaudio), stringResource(R.string.mode_directaudio_hint), s.directAudio, onChange = a.onDirectAudio)
ChoiceRow(
host, "clientAudio", "Steam-menu audio", stringResource(R.string.mode_client_audio_hint),
listOf("classic" to stringResource(R.string.mode_client_audio_classic), "directaudio" to stringResource(R.string.mode_client_audio_direct)), if (s.clientDirectAudio) "directaudio" else "classic",
onPick = { id -> a.onClientDirectAudio(id == "directaudio") },
)
ToggleRow(host, "mic", stringResource(R.string.mode_mic), null, s.mic, onChange = a.onMic)
}
}
SettingsCategory.LIBRARY -> {
if (steam && s.addedGamesDirs != null) SettingsAnchor("added-games") { SettingsGroup(stringResource(R.string.mode_added_games)) {
for (dir in s.addedGamesDirs) {
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") }
SettingsAnchor("added-games:${dir}") { ActionRow(
dir.substringAfterLast('/').ifEmpty { dir }, dir + " · " + (if (n == 0) stringResource(R.string.mode_added_none) else pluralStringResource(R.plurals.mode_added_count, n, n)) + ". " + stringResource(R.string.added_games_forget_hint),
stringResource(R.string.common_forget), onClick = { a.onForgetAddedGamesDir(dir) },
) }
}
SettingsAnchor("added-games-add") { ActionRow(
if (s.addedGamesDirs.isEmpty()) stringResource(R.string.mode_games_folder) else stringResource(R.string.mode_games_folder_another),
stringResource(R.string.added_games_import_hint), stringResource(R.string.common_add_ellipsis), onClick = a.onPickAddedGamesDir,
) }
ToggleRow(host, "addedArt", stringResource(R.string.mode_added_art), stringResource(R.string.mode_added_art_hint), s.addedGamesArt, onChange = a.onAddedGamesArt)
for (g in s.addedGames) ChoiceRow(
host, "added:" + g.folderPath, g.folderName, if (s.addedGamesDirs.size > 1) stringResource(R.string.mode_added_launches_in, g.exeName, g.folderPath.substringBeforeLast('/').substringAfterLast('/')) else stringResource(R.string.mode_added_launches, g.exeName),
g.candidates + ("__pick__" to stringResource(R.string.mode_added_choose)), g.exePath,
note = stringResource(R.string.mode_added_exe_note),
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
)
} }
if (steam && s.gameStorage != null) SettingsAnchor("storage") { SettingsGroup(stringResource(R.string.mode_storage)) {
val custom = s.gameStorage.isNotEmpty() && s.gameStorage != "off" && s.storageOptions.none { it.second == s.gameStorage }
val options = buildList {
add("" to (if (s.storageOptions.isEmpty()) stringResource(R.string.mode_storage_auto_none) else stringResource(R.string.mode_storage_auto)))
add("off" to stringResource(R.string.mode_storage_internal))
for ((label, path) in s.storageOptions) add(path to label)
if (custom) add(s.gameStorage to stringResource(R.string.mode_storage_folder, s.gameStorage))
}
val open = host.open == "storage"
SettingsAnchor("storage-location") { SettingsRow(stringResource(R.string.mode_second_library), stringResource(R.string.second_library_import_hint), highlighted = open) {
androidx.compose.foundation.layout.Box {
ValueChip(options.firstOrNull { it.first == s.gameStorage }?.second?.substringBefore(" -") ?: "-", open) { host.open = if (open) null else "storage" }
AnchoredMenu(open, onDismiss = { if (host.open == "storage") host.open = null }, title = stringResource(R.string.mode_second_library), note = stringResource(R.string.mode_storage_note)) { firstItemFocus ->
options.forEachIndexed { index, (path, label) -> MenuItem(label, checked = path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) {
a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·")); host.open = null
} }
MenuItem(stringResource(R.string.mode_choose_folder), checked = false) { host.open = null; a.onPickGameStorageFolder() }
}
} }
} } }
SettingsGroup(stringResource(R.string.display_image_scaling)) { } }
ChoiceRow( }
host, "upscaler", stringResource(R.string.display_filter), null, SettingsCategory.SESSIONS -> {
SessionPrefs.upscalerChoices(LocalContext.current), s.upscaler, SettingsGroup(stringResource(R.string.mode_session)) {
note = stringResource(R.string.display_filter_note), onPick = a.onUpscaler, ChoiceRow(
) host, "suspend", stringResource(R.string.mode_suspend),
if (SessionPrefs.upscalerHasSharpness(s.upscaler)) SliderRow( stringResource(R.string.mode_suspend_hint),
stringResource(R.string.display_sharpness), null, s.upscaleSharpness, 0..100, step = 5, listOf(
format = { "$it%" }, onChange = a.onUpscaleSharpness, SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto),
) SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual),
} SessionPrefs.SUSPEND_NEVER to stringResource(R.string.common_never),
SettingsGroup(stringResource(R.string.display_frame_rate)) { ),
ChoiceRow(host, "fps", stringResource(R.string.mode_fps), stringResource(R.string.common_applies_next_session), s.suspendPolicy,
SessionPrefs.fpsLimitChoices(LocalContext.current), s.fpsLimit, note = stringResource(R.string.mode_fps_note), onPick = a.onFpsLimit) note = stringResource(R.string.mode_suspend_note),
} onPick = a.onSuspendPolicy,
SettingsGroup(stringResource(R.string.mode_hdr)) { )
ToggleRow(
host, "hdr", stringResource(R.string.mode_hdr10),
s.hdrReason?.let { stringResource(R.string.mode_hdr_unavailable, it) }
?: stringResource(R.string.mode_hdr_restart),
checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr,
)
}
SettingsGroup(stringResource(R.string.mode_drivers)) {
SettingsRow(stringResource(R.string.mode_gpu_drivers), stringResource(R.string.mode_gpu_drivers_hint)) {
ValueChip(s.gpuDrivers ?: stringResource(R.string.common_auto), open = false) { a.onGpuDrivers() }
}
}
} }
if (tab == ModeSettingsTab.CONTROLS) { SettingsGroup(stringResource(R.string.pip_title)) {
SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) { ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto),
ChoiceRow( if (s.pipSupported) null else "Picture-in-picture is unavailable on this device.",
host, "touch", stringResource(R.string.mode_touch), null, s.pipAutoEnter, enabled = s.pipSupported, onChange = a.onPipAutoEnter)
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), s.touchMode,
note = stringResource(R.string.mode_touch_note),
onPick = a.onTouch,
)
if (steam && s.oscMode != null) ChoiceRow(
host, "osc", stringResource(R.string.mode_osc), null,
listOf(
SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto),
SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam),
SessionPrefs.OSC_NEVER to stringResource(R.string.common_never),
), s.oscMode,
note = stringResource(R.string.mode_osc_note), onPick = a.onOsc,
)
if (steam && s.steamController != null) ChoiceRow(
host, "controller", stringResource(R.string.mode_controller), stringResource(R.string.mode_controller_hint),
listOf(
SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360),
), s.steamController,
note = stringResource(R.string.mode_controller_note),
onPick = a.onSteamController,
)
if (steam) ChoiceRow(
host, "back-actions", stringResource(R.string.mode_back), stringResource(SessionPrefs.backActionsOrder(s.backActionsInverted)),
listOf(
false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM),
true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU),
), s.backActionsInverted, onPick = a.onBackActionsInverted,
)
}
} }
if (tab == ModeSettingsTab.SESSION) { if (steam) SettingsGroup(stringResource(R.string.mode_startup)) {
SettingsGroup(stringResource(R.string.mode_session)) { ToggleRow(
ChoiceRow( host, "steam-startup", stringResource(R.string.mode_steam_startup),
host, "suspend", stringResource(R.string.mode_suspend), stringResource(R.string.mode_steam_startup_hint),
stringResource(R.string.mode_suspend_hint), s.runSteamAtStartup, onChange = a.onRunSteamAtStartup,
listOf( )
SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto),
SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual),
SessionPrefs.SUSPEND_NEVER to stringResource(R.string.common_never),
),
s.suspendPolicy,
note = stringResource(R.string.mode_suspend_note),
onPick = a.onSuspendPolicy,
)
}
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
s.pipAutoEnter, onChange = a.onPipAutoEnter)
}
if (steam) SettingsGroup(stringResource(R.string.mode_startup)) {
ToggleRow(
host, "steam-startup", stringResource(R.string.mode_steam_startup),
stringResource(R.string.mode_steam_startup_hint),
s.runSteamAtStartup, onChange = a.onRunSteamAtStartup,
)
}
} }
if (steam && tab == ModeSettingsTab.STEAM) SettingsGroup(stringResource(R.string.mode_decky)) { if (steam) SettingsAnchor("decky") { SettingsGroup(stringResource(R.string.mode_decky)) {
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null && val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
s.deckyInstalled != s.deckyLatestRelease.tag s.deckyInstalled != s.deckyLatestRelease.tag
val status = when { val status = when {
@@ -332,7 +365,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag) updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag)
else -> stringResource(R.string.mode_decky_current, s.deckyInstalled) else -> stringResource(R.string.mode_decky_current, s.deckyInstalled)
} }
SettingsRow(stringResource(R.string.mode_decky_loader), status) { SettingsAnchor("decky-loader") { SettingsRow(stringResource(R.string.mode_decky_loader), status) {
val action = when { val action = when {
s.deckyStage != null -> stringResource(R.string.common_working) s.deckyStage != null -> stringResource(R.string.common_working)
s.deckyChecking -> stringResource(R.string.common_checking) s.deckyChecking -> stringResource(R.string.common_checking)
@@ -353,65 +386,57 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
enabled = s.deckyStage == null && !s.deckySessionRunning, enabled = s.deckyStage == null && !s.deckySessionRunning,
) { confirmDeckyRemoval = true } ) { confirmDeckyRemoval = true }
} }
} } }
if (s.deckyInstalled != null) ToggleRow( ToggleRow(
host, "decky-enabled", stringResource(R.string.mode_decky), host, "decky-enabled", stringResource(R.string.mode_decky),
if (s.deckyEnabled) stringResource(R.string.mode_decky_on) if (s.deckyInstalled == null) "Install Decky Loader above to enable it."
else if (s.deckyEnabled) stringResource(R.string.mode_decky_on)
else stringResource(R.string.mode_decky_off), else stringResource(R.string.mode_decky_off),
s.deckyEnabled, s.deckyEnabled,
enabled = !s.deckySessionRunning && s.deckyStage == null, enabled = s.deckyInstalled != null && !s.deckySessionRunning && s.deckyStage == null,
onChange = a.onDeckyEnabled, onChange = a.onDeckyEnabled,
) )
SettingsRow( SettingsAnchor("decky-plugins") { SettingsRow(
stringResource(R.string.mode_decky_plugins), "Plugins",
stringResource(R.string.mode_decky_plugins_hint), "Install a plugin ZIP for the next Steam session.",
) { ) {
SecondaryButton( SecondaryButton(
if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip), if (s.deckyStage?.startsWith("Downloading plugin binary") == true) "Downloading…" else "Install from ZIP",
enabled = s.deckyInstalled != null && s.deckyStage == null && !s.deckySessionRunning, enabled = s.deckyInstalled != null && s.deckyStage == null && !s.deckySessionRunning,
onClick = a.onPickDeckyPluginZip, onClick = a.onPickDeckyPluginZip,
) )
} } }
if (s.deckyStage != null && s.deckyPercent >= 0) { if (s.deckyStage != null && s.deckyPercent >= 0) {
LinearProgressIndicator( LinearProgressIndicator(
progress = { s.deckyPercent / 100f }, progress = { s.deckyPercent / 100f },
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
) )
} }
} } }
if (steam && tab == ModeSettingsTab.STEAM && s.steamChannel != null) SettingsGroup(stringResource(R.string.mode_client)) { if (steam && s.steamChannel != null) SettingsGroup(stringResource(R.string.mode_client)) {
ToggleRow( ToggleRow(
host, "steamdeck", stringResource(R.string.mode_deck_mode), host, "steamdeck", stringResource(R.string.mode_deck_mode),
stringResource(R.string.mode_deck_mode_hint), stringResource(R.string.mode_deck_mode_hint),
s.steamDeckMode, onChange = a.onSteamDeckMode, s.steamDeckMode, onChange = a.onSteamDeckMode,
) )
if (s.steamDeckMode) ToggleRow(
host, "mangoapp", stringResource(R.string.mode_mangoapp),
stringResource(R.string.mode_mangoapp_hint),
s.mangoapp, onChange = a.onMangoapp,
)
// Deck mode fixes the branch (SessionPrefs.steamChannel); the choice is for Deck mode off. // Deck mode fixes the branch (SessionPrefs.steamChannel); the choice is for Deck mode off.
if (s.steamDeckMode) SettingsRow(stringResource(R.string.mode_branch), stringResource(R.string.mode_branch_deck)) {} if (s.steamDeckMode) SettingsAnchor("channel") {
SettingsRow(stringResource(R.string.mode_branch), stringResource(R.string.mode_branch_deck)) {}
}
else ChoiceRow( else ChoiceRow(
host, "channel", stringResource(R.string.mode_branch), stringResource(R.string.mode_branch_hint), host, "channel", stringResource(R.string.mode_branch), stringResource(R.string.mode_branch_hint),
listOf("publicbeta" to stringResource(R.string.mode_branch_public), "steamdeck_publicbeta" to stringResource(R.string.mode_branch_deck_beta)), s.steamChannel, listOf("publicbeta" to stringResource(R.string.mode_branch_public), "steamdeck_publicbeta" to stringResource(R.string.mode_branch_deck_beta)), s.steamChannel,
note = stringResource(R.string.mode_branch_note), note = stringResource(R.string.mode_branch_note),
onPick = a.onSteamChannel, onPick = a.onSteamChannel,
) )
SettingsRow(
stringResource(R.string.mode_steam_repair),
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
) {
SecondaryButton(stringResource(R.string.mode_steam_repair_button), enabled = !s.steamRepairQueued, onClick = a.onSteamRepair)
}
} }
if (steam && tab == ModeSettingsTab.STEAM && s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) { if (steam && s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
val hint = when { val hint = when {
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off) s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
!s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied) !s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied)
else -> stringResource(R.string.mode_wifi_discovery_hint) else -> stringResource(R.string.mode_wifi_discovery_hint)
} }
SettingsRow(stringResource(R.string.mode_wifi_discovery), hint) { SettingsAnchor("wifi") { SettingsRow(stringResource(R.string.mode_wifi_discovery), hint) {
Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)) { horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)) {
if (s.wifiDiscoveryBlocked || (s.wifiDiscovery && !s.wifiDiscoveryLocation)) { if (s.wifiDiscoveryBlocked || (s.wifiDiscovery && !s.wifiDiscoveryLocation)) {
@@ -422,43 +447,25 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
if (on) explainWifiDiscovery = true else a.onWifiDiscovery(false) if (on) explainWifiDiscovery = true else a.onWifiDiscovery(false)
} }
} }
} } }
} }
if ((tab == ModeSettingsTab.GAMES || (!steam && tab == ModeSettingsTab.DISPLAY)) && s.forceFullscreen != null) SettingsGroup(stringResource(R.string.display_window_compatibility)) { if (!steam && s.renderer != null) SettingsGroup(stringResource(R.string.mode_renderer)) {
ToggleRow(host, "fill", stringResource(R.string.display_force_fullscreen), ChoiceRow(host, "renderer", stringResource(R.string.mode_desktop_renderer), stringResource(R.string.mode_renderer_hint),
stringResource(R.string.display_force_fullscreen_hint), s.forceFullscreen, onChange = a.onForceFullscreen) listOf("vulkan" to stringResource(R.string.mode_renderer_vulkan), "gles2" to stringResource(R.string.mode_renderer_gles2), "pixman" to stringResource(R.string.mode_renderer_pixman)), s.renderer,
note = stringResource(R.string.mode_renderer_note), onPick = a.onRenderer)
} }
if (steam && tab == ModeSettingsTab.GAMES && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) { }
for (dir in s.addedGamesDirs) { SettingsCategory.COMPATIBILITY -> {
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") } SettingsGroup(stringResource(R.string.mode_drivers)) {
ActionRow( SettingsAnchor("gpu-drivers") { SettingsRow(stringResource(R.string.mode_gpu_drivers), stringResource(R.string.mode_gpu_drivers_hint)) {
dir.substringAfterLast('/').ifEmpty { dir }, dir + " · " + (if (n == 0) stringResource(R.string.mode_added_none) else pluralStringResource(R.plurals.mode_added_count, n, n)) + ". " + stringResource(R.string.added_games_forget_hint), ValueChip(s.gpuDrivers, open = false) { a.onGpuDrivers() }
stringResource(R.string.common_forget), onClick = { a.onForgetAddedGamesDir(dir) }, } }
)
}
ActionRow(
if (s.addedGamesDirs.isEmpty()) stringResource(R.string.mode_games_folder) else stringResource(R.string.mode_games_folder_another),
stringResource(R.string.added_games_import_hint),
stringResource(R.string.common_add_ellipsis), onClick = a.onPickAddedGamesDir,
)
ToggleRow(
host, "addedArt", stringResource(R.string.mode_added_art),
stringResource(R.string.mode_added_art_hint),
s.addedGamesArt, onChange = a.onAddedGamesArt,
)
for (g in s.addedGames) ChoiceRow(
host, "added:" + g.folderPath, g.folderName, if (s.addedGamesDirs.size > 1) stringResource(R.string.mode_added_launches_in, g.exeName, g.folderPath.substringBeforeLast('/').substringAfterLast('/')) else stringResource(R.string.mode_added_launches, g.exeName),
g.candidates + ("__pick__" to stringResource(R.string.mode_added_choose)), g.exePath,
note = stringResource(R.string.mode_added_exe_note),
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
)
} }
if (steam && tab == ModeSettingsTab.GAMES && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) { if (steam && s.fexPreset != null) {
if (s.syncBackend != null) SettingsRow( SettingsAdvanced("game-settings", stringResource(R.string.game_settings_title), targets = setOf("fex", "syncBackend", "game-env")) {
stringResource(R.string.sync_backend_title), if (s.syncBackend != null) SettingsAnchor("syncBackend") { SettingsRow(
stringResource(R.string.sync_backend_hint), stringResource(R.string.sync_backend_title), stringResource(R.string.sync_backend_hint),
) { ) { SegmentedTabs(
SegmentedTabs(
listOf( listOf(
SessionPrefs.SYNC_NTSYNC to stringResource(R.string.sync_backend_ntsync), SessionPrefs.SYNC_NTSYNC to stringResource(R.string.sync_backend_ntsync),
SessionPrefs.SYNC_FSYNC to stringResource(R.string.sync_backend_fsync), SessionPrefs.SYNC_FSYNC to stringResource(R.string.sync_backend_fsync),
@@ -466,75 +473,22 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
SessionPrefs.SYNC_WINESERVER to stringResource(R.string.sync_backend_wineserver), SessionPrefs.SYNC_WINESERVER to stringResource(R.string.sync_backend_wineserver),
), ),
s.syncBackend, s.syncBackend,
) { id -> host.open = null; a.onSyncBackend(id) } ) { id -> host.open = null; a.onSyncBackend(id) } } }
ChoiceRow(
host, "fex", stringResource(R.string.fex_preset_title), stringResource(R.string.fex_next_launch),
FexPreset.all.map { it.id to stringResource(it.label) }, s.fexPreset,
note = stringResource(FexPreset.byId(s.fexPreset).detail), onPick = a.onFexPreset,
)
SettingsAnchor("game-env") { GameEnvironmentRow() }
} }
ChoiceRow(
host, "fex", stringResource(R.string.fex_preset_title), stringResource(R.string.fex_next_launch),
FexPreset.all.map { it.id to stringResource(it.label) }, s.fexPreset,
note = stringResource(FexPreset.byId(s.fexPreset).detail), onPick = a.onFexPreset,
)
GameEnvironmentRow()
} }
if (steam && tab == ModeSettingsTab.AUDIO && s.directAudio != null && s.mic != null) SettingsGroup(stringResource(R.string.mode_audio)) { }
ToggleRow(host, "da", stringResource(R.string.mode_directaudio), stringResource(R.string.mode_directaudio_hint), s.directAudio, onChange = a.onDirectAudio) SettingsCategory.SUPPORT -> {
ChoiceRow( if (steam && s.gameStorage != null) SettingsAdvanced("storage-diagnostics", stringResource(R.string.mode_storage), targets = setOf("storageDiagnostics")) {
host, "clientAudio", stringResource(R.string.mode_client_audio), stringResource(R.string.mode_client_audio_hint), ToggleRow(host, "storageDiagnostics", stringResource(R.string.mode_storage_diagnostics), stringResource(R.string.mode_storage_diagnostics_hint), s.storageDiagnostics, onChange = a.onStorageDiagnostics)
listOf("classic" to stringResource(R.string.mode_client_audio_classic), "directaudio" to stringResource(R.string.mode_client_audio_direct)), if (s.clientDirectAudio) "directaudio" else "classic",
onPick = { id -> a.onClientDirectAudio(id == "directaudio") },
)
ToggleRow(host, "mic", stringResource(R.string.mode_mic), stringResource(R.string.mode_mic_hint), s.mic, onChange = a.onMic)
}
if (steam && tab == ModeSettingsTab.GAMES && s.gameStorage != null) SettingsGroup(stringResource(R.string.mode_storage)) {
val custom = s.gameStorage.isNotEmpty() && s.gameStorage != "off" && s.storageOptions.none { it.path == s.gameStorage }
// Each choice: its path, its menu line, the chip's shorter line, and the label it is saved with.
class StorageChoice(val path: String, val label: String, val chip: String, val saved: String)
val internal = stringResource(R.string.mode_storage_internal)
val options = buildList {
add(StorageChoice(
"", if (s.storageOptions.isEmpty()) stringResource(R.string.mode_storage_auto_none) else stringResource(R.string.mode_storage_auto),
stringResource(R.string.mode_storage_auto_short), "",
))
add(StorageChoice("off", internal, internal, ""))
for (o in s.storageOptions) add(StorageChoice(o.path, o.label, o.label, o.name))
if (custom) stringResource(R.string.mode_storage_folder, s.gameStorage).let { add(StorageChoice(s.gameStorage, it, it, it)) }
}
val open = host.open == "storage"
SettingsRow(
stringResource(R.string.mode_second_library),
stringResource(R.string.second_library_import_hint),
highlighted = open,
) {
androidx.compose.foundation.layout.Box {
ValueChip(options.firstOrNull { it.path == s.gameStorage }?.chip ?: "-", open) { host.open = if (open) null else "storage" }
AnchoredMenu(
open, onDismiss = { if (host.open == "storage") host.open = null }, title = stringResource(R.string.mode_second_library),
note = stringResource(R.string.mode_storage_note),
) { firstItemFocus ->
options.forEachIndexed { index, choice ->
MenuItem(choice.label, checked = choice.path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) {
a.onGameStorage(choice.path, choice.saved)
host.open = null
}
}
MenuItem(stringResource(R.string.mode_choose_folder), checked = false) { host.open = null; a.onPickGameStorageFolder() }
}
}
}
ToggleRow(
host, "storageDiagnostics", stringResource(R.string.mode_storage_diagnostics),
stringResource(R.string.mode_storage_diagnostics_hint), s.storageDiagnostics,
onChange = a.onStorageDiagnostics,
)
}
if (!steam && tab == ModeSettingsTab.DISPLAY && s.renderer != null) SettingsGroup(stringResource(R.string.mode_renderer)) {
ChoiceRow(
host, "renderer", stringResource(R.string.mode_desktop_renderer), stringResource(R.string.mode_renderer_hint),
listOf("vulkan" to stringResource(R.string.mode_renderer_vulkan), "gles2" to stringResource(R.string.mode_renderer_gles2), "pixman" to stringResource(R.string.mode_renderer_pixman)), s.renderer,
note = stringResource(R.string.mode_renderer_note),
onPick = a.onRenderer,
)
} }
}
SettingsCategory.GENERAL -> Unit
} }
if (explainWifiDiscovery) AlertDialog( if (explainWifiDiscovery) AlertDialog(
onDismissRequest = { explainWifiDiscovery = false }, onDismissRequest = { explainWifiDiscovery = false },
@@ -560,10 +514,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
) )
} }
/** The Resolution menu's "Custom…" entry. */
private const val CUSTOM = -1
/** Width × height for the session, with the common handheld shapes one tap away. */ /** Width × height for the session, with the common handheld shapes one tap away. */
@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class) @OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
@Composable @Composable
internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit) { private fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit) {
var w by remember { mutableStateOf(initial?.first?.toString() ?: "") } var w by remember { mutableStateOf(initial?.first?.toString() ?: "") }
var h by remember { mutableStateOf(initial?.second?.toString() ?: "") } var h by remember { mutableStateOf(initial?.second?.toString() ?: "") }
val parsed = SessionPrefs.parseResolution("${w}x$h") val parsed = SessionPrefs.parseResolution("${w}x$h")
@@ -1,7 +1,6 @@
package com.droiddeck.launcher.ui package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
import androidx.annotation.StringRes
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import android.view.KeyEvent import android.view.KeyEvent
import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateColorAsState
@@ -64,42 +63,40 @@ import androidx.compose.ui.unit.sp
* modifier for the next key, a second tap locks it, a third lets it go. A controller moves over the * modifier for the next key, a second tap locks it, a third lets it go. A controller moves over the
* keys with the d-pad and presses with A. * keys with the d-pad and presses with A.
*/ */
private data class PcKey(val label: String, val code: Int, val weight: Float = 1f, val shifted: String? = null, @StringRes val labelRes: Int = 0) private data class PcKey(val label: String, val code: Int, val weight: Float = 1f, val shifted: String? = null)
private fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted) private fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted)
private fun k(@StringRes labelRes: Int, code: Int, weight: Float = 1f) = PcKey("", code, weight, null, labelRes)
private val ROWS: List<List<PcKey>> = listOf( private val ROWS: List<List<PcKey>> = listOf(
listOf( listOf(
k(R.string.pckb_key_esc, 1), k("F1", 59), k("F2", 60), k("F3", 61), k("F4", 62), k("F5", 63), k("F6", 64), k("Esc", 1), k("F1", 59), k("F2", 60), k("F3", 61), k("F4", 62), k("F5", 63), k("F6", 64),
k("F7", 65), k("F8", 66), k("F9", 67), k("F10", 68), k("F11", 87), k("F12", 88), k("F7", 65), k("F8", 66), k("F9", 67), k("F10", 68), k("F11", 87), k("F12", 88),
k(R.string.pckb_key_ins, 110), k(R.string.pckb_key_del, 111), k(R.string.pckb_key_home, 102), k(R.string.pckb_key_end, 107), k(R.string.pckb_key_pgup, 104), k(R.string.pckb_key_pgdn, 109), k("Ins", 110), k("Del", 111), k("Home", 102), k("End", 107), k("PgUp", 104), k("PgDn", 109),
), ),
listOf( listOf(
k("`", 41, shifted = "~"), k("1", 2, shifted = "!"), k("2", 3, shifted = "@"), k("3", 4, shifted = "#"), k("`", 41, shifted = "~"), k("1", 2, shifted = "!"), k("2", 3, shifted = "@"), k("3", 4, shifted = "#"),
k("4", 5, shifted = "$"), k("5", 6, shifted = "%"), k("6", 7, shifted = "^"), k("7", 8, shifted = "&"), k("4", 5, shifted = "$"), k("5", 6, shifted = "%"), k("6", 7, shifted = "^"), k("7", 8, shifted = "&"),
k("8", 9, shifted = "*"), k("9", 10, shifted = "("), k("0", 11, shifted = ")"), k("-", 12, shifted = "_"), k("8", 9, shifted = "*"), k("9", 10, shifted = "("), k("0", 11, shifted = ")"), k("-", 12, shifted = "_"),
k("=", 13, shifted = "+"), k(R.string.pckb_key_backspace, 14, 2f), k("=", 13, shifted = "+"), k("⌫ Backspace", 14, 2f),
), ),
listOf( listOf(
k(R.string.pckb_key_tab, 15, 1.5f), k("q", 16), k("w", 17), k("e", 18), k("r", 19), k("t", 20), k("y", 21), k("Tab ⇥", 15, 1.5f), k("q", 16), k("w", 17), k("e", 18), k("r", 19), k("t", 20), k("y", 21),
k("u", 22), k("i", 23), k("o", 24), k("p", 25), k("[", 26, shifted = "{"), k("]", 27, shifted = "}"), k("u", 22), k("i", 23), k("o", 24), k("p", 25), k("[", 26, shifted = "{"), k("]", 27, shifted = "}"),
k("\\", 43, 1.5f, shifted = "|"), k("\\", 43, 1.5f, shifted = "|"),
), ),
listOf( listOf(
k(R.string.pckb_key_caps, 58, 1.75f), k("a", 30), k("s", 31), k("d", 32), k("f", 33), k("g", 34), k("h", 35), k("Caps", 58, 1.75f), k("a", 30), k("s", 31), k("d", 32), k("f", 33), k("g", 34), k("h", 35),
k("j", 36), k("k", 37), k("l", 38), k(";", 39, shifted = ":"), k("'", 40, shifted = "\""), k("j", 36), k("k", 37), k("l", 38), k(";", 39, shifted = ":"), k("'", 40, shifted = "\""),
k(R.string.pckb_key_enter, 28, 2.25f), k("Enter ⏎", 28, 2.25f),
), ),
listOf( listOf(
k(R.string.pckb_key_shift, 42, 2.25f), k("z", 44), k("x", 45), k("c", 46), k("v", 47), k("b", 48), k("n", 49), k("⇧ Shift", 42, 2.25f), k("z", 44), k("x", 45), k("c", 46), k("v", 47), k("b", 48), k("n", 49),
k("m", 50), k(",", 51, shifted = "<"), k(".", 52, shifted = ">"), k("/", 53, shifted = "?"), k("m", 50), k(",", 51, shifted = "<"), k(".", 52, shifted = ">"), k("/", 53, shifted = "?"),
k(R.string.pckb_key_shift, 54, 1.75f), k("↑", 103), k("⇧ Shift", 54, 1.75f), k("↑", 103),
), ),
listOf( listOf(
k(R.string.pckb_key_ctrl, 29, 1.5f), k(R.string.pckb_key_super, 125, 1.25f), k(R.string.pckb_key_alt, 56, 1.25f), k(R.string.pckb_key_space, 57, 6.25f), k("Ctrl", 29, 1.5f), k("Super", 125, 1.25f), k("Alt", 56, 1.25f), k("Space", 57, 6.25f),
k(R.string.pckb_key_altgr, 100, 1.25f), k(R.string.pckb_key_ctrl, 97, 1.25f), k("←", 105), k("↓", 108), k("→", 106), k("AltGr", 100, 1.25f), k("Ctrl", 97, 1.25f), k("←", 105), k("↓", 108), k("→", 106),
), ),
) )
@@ -174,7 +171,6 @@ fun PcKeyboard(
val state = mods[key.code] ?: MOD_OFF val state = mods[key.code] ?: MOD_OFF
val lit = state != MOD_OFF || (key.code == 58 && capsOn) val lit = state != MOD_OFF || (key.code == 58 && capsOn)
val label = when { val label = when {
key.labelRes != 0 -> stringResource(key.labelRes)
shifted && key.shifted != null -> key.shifted shifted && key.shifted != null -> key.shifted
key.label.length == 1 && key.label[0].isLetter() && (shifted xor capsOn) -> key.label.uppercase() key.label.length == 1 && key.label[0].isLetter() && (shifted xor capsOn) -> key.label.uppercase()
else -> key.label else -> key.label
@@ -9,7 +9,7 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
@@ -71,7 +71,6 @@ fun PerformancePage(
val coreItems = cores.map { it.core to it.label } val coreItems = cores.map { it.core to it.label }
SettingsPage( SettingsPage(
host, title = stringResource(R.string.perf_title), host, title = stringResource(R.string.perf_title),
lede = stringResource(R.string.perf_lede),
onBack = onDismiss, onBack = onDismiss,
) { ) {
SettingsGroup(stringResource(R.string.perf_client_cores_group)) { SettingsGroup(stringResource(R.string.perf_client_cores_group)) {
@@ -80,17 +79,17 @@ fun PerformancePage(
stringResource(R.string.perf_override_hint), stringResource(R.string.perf_override_hint),
clientOverride, onChange = onClientOverride, clientOverride, onChange = onClientOverride,
) )
MultiRow( SettingsAnchor("clientCores") { MultiRow(
host, "clientCores", stringResource(R.string.perf_client_cores), if (clientOverride) stringResource(R.string.perf_client_cores_on) else stringResource(R.string.perf_client_cores_off), host, "clientCores", stringResource(R.string.perf_client_cores), if (clientOverride) stringResource(R.string.perf_client_cores_on) else stringResource(R.string.perf_client_cores_off),
coreItems, clientCores, enabled = clientOverride, onToggle = onClientCore, coreItems, clientCores, enabled = clientOverride, onToggle = onClientCore,
) ) }
} }
SettingsGroup(stringResource(R.string.perf_game_cores_group)) { SettingsGroup(stringResource(R.string.perf_game_cores_group)) {
MultiRow( SettingsAnchor("gameCores") { MultiRow(
host, "gameCores", stringResource(R.string.perf_game_cores), host, "gameCores", stringResource(R.string.perf_game_cores),
stringResource(R.string.perf_game_cores_hint), stringResource(R.string.perf_game_cores_hint),
coreItems, gameCores, onToggle = onGameCore, coreItems, gameCores, onToggle = onGameCore,
) ) }
} }
SettingsGroup(stringResource(R.string.perf_client_ui)) { SettingsGroup(stringResource(R.string.perf_client_ui)) {
ToggleRow( ToggleRow(
@@ -162,7 +161,7 @@ fun PerformancePage(
SettingsGroup(stringResource(R.string.perf_identity)) { SettingsGroup(stringResource(R.string.perf_identity)) {
var draft by remember(guestHostname) { mutableStateOf(guestHostname) } var draft by remember(guestHostname) { mutableStateOf(guestHostname) }
val valid = SessionPrefs.validGuestHostname(draft) != null val valid = SessionPrefs.validGuestHostname(draft) != null
SettingsRow( SettingsAnchor("hostname") { SettingsRow(
stringResource(R.string.perf_hostname), stringResource(R.string.perf_hostname),
if (valid || draft.isBlank()) stringResource(R.string.perf_hostname_hint, SessionPrefs.DEFAULT_GUEST_HOSTNAME) if (valid || draft.isBlank()) stringResource(R.string.perf_hostname_hint, SessionPrefs.DEFAULT_GUEST_HOSTNAME)
else stringResource(R.string.perf_hostname_invalid), else stringResource(R.string.perf_hostname_invalid),
@@ -174,9 +173,9 @@ fun PerformancePage(
}, },
singleLine = true, isError = !valid && draft.isNotBlank(), singleLine = true, isError = !valid && draft.isNotBlank(),
placeholder = { Text(SessionPrefs.DEFAULT_GUEST_HOSTNAME) }, placeholder = { Text(SessionPrefs.DEFAULT_GUEST_HOSTNAME) },
modifier = Modifier.width(220.dp), modifier = Modifier.widthIn(max = 220.dp),
) )
} } }
} }
if (phantomWarning != null) { if (phantomWarning != null) {
Spacer(Modifier.height(16.dp)) Spacer(Modifier.height(16.dp))
@@ -202,7 +202,7 @@ private fun PairingProgress(stage: Stage, onCancel: () -> Unit) {
private fun StatusGroup(status: PhantomProcessStatus, compact: Boolean) { private fun StatusGroup(status: PhantomProcessStatus, compact: Boolean) {
SettingsGroup(stringResource(R.string.gate_status), compact = compact) { SettingsGroup(stringResource(R.string.gate_status), compact = compact) {
Column(Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { Column(Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(PhantomProcessLimit.title(LocalContext.current, status), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground) Text(PhantomProcessLimit.title(status), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground)
Body(stringResource(R.string.gate_polling)) Body(stringResource(R.string.gate_polling))
} }
} }
@@ -36,8 +36,6 @@ fun ProtonPage(
SettingsPage( SettingsPage(
host, host,
title = stringResource(R.string.setup_tool_protons), title = stringResource(R.string.setup_tool_protons),
eyebrow = stringResource(R.string.setup_title),
lede = stringResource(R.string.proton_lede),
onBack = onBack, onBack = onBack,
) { ) {
if (!runtimeReady) Text( if (!runtimeReady) Text(
@@ -1,39 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionDisplay
/** Pre-session resolution choice, applied when the session starts. */
@Composable
fun ResolutionRow(
host: MenuHost, choice: String, panel: Pair<Int, Int>, onPick: (String) -> Unit,
chipModifier: Modifier = Modifier,
) {
val custom = "custom"
val size = SessionDisplay.resolveChoice(panel, choice)
val screen = SessionDisplay.screenSize(panel)
val choices = SessionDisplay.resolutionOptions(panel)
val selected = if (size == screen) SessionDisplay.MATCH_SCREEN else choice
var editCustom by remember { mutableStateOf(false) }
val options = choices.map { value ->
val dimensions = SessionDisplay.resolveChoice(panel, value)
value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second)
else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
else "${dimensions.first}×${dimensions.second}"
} + (custom to if (selected in choices) stringResource(R.string.mode_res_custom)
else stringResource(R.string.mode_res_custom_value, size.first, size.second))
ChoiceRow(host, "resolution", stringResource(R.string.display_resolution),
stringResource(R.string.common_applies_next_session),
options, if (selected in choices) selected else custom, chipModifier = chipModifier,
onPick = { value -> if (value == custom) editCustom = true else onPick(value) })
if (editCustom) CustomResolutionDialog(size,
onSave = { value -> editCustom = false; onPick("${value.first}x${value.second}") },
onDismiss = { editCustom = false })
}
@@ -226,24 +226,22 @@ class SecondScreenPresentation(
} }
keys.addView(button) keys.addView(button)
} }
val ctrl = context.getString(R.string.pckb_key_ctrl) key("Esc", "\u001b")
val alt = context.getString(R.string.pckb_key_alt) key("Tab", "\t")
key(context.getString(R.string.pckb_key_esc), "\u001b") key("Ctrl", "") { button ->
key(context.getString(R.string.second_key_tab), "\t")
key(ctrl, "") { button ->
ctrlActive = !ctrlActive ctrlActive = !ctrlActive
button.text = if (ctrlActive) context.getString(R.string.second_key_on, ctrl) else ctrl button.text = if (ctrlActive) "Ctrl ✓" else "Ctrl"
} }
key(alt, "") { button -> key("Alt", "") { button ->
altActive = !altActive altActive = !altActive
button.text = if (altActive) context.getString(R.string.second_key_on, alt) else alt button.text = if (altActive) "Alt ✓" else "Alt"
} }
key("↑", "\u001b[A") key("↑", "\u001b[A")
key("↓", "\u001b[B") key("↓", "\u001b[B")
key("←", "\u001b[D") key("←", "\u001b[D")
key("→", "\u001b[C") key("→", "\u001b[C")
key(context.getString(R.string.second_key_ctrl_c), "\u0003") key("Ctrl+C", "\u0003")
key(context.getString(R.string.second_key_ctrl_d), "\u0004") key("Ctrl+D", "\u0004")
keyStrip.addView(keys) keyStrip.addView(keys)
root.addView(keyStrip, LinearLayout.LayoutParams(-1, -2)) root.addView(keyStrip, LinearLayout.LayoutParams(-1, -2))
@@ -1,19 +0,0 @@
package com.droiddeck.launcher.ui
/** Stable page identities keep focus and scroll positions when a secondary display comes and goes. */
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("touch"),
SECOND_SCREEN("second-screen:none"),
DISPLAY("hud"),
EFFECTS("look"),
GAMES("anisotropy"),
SESSION("suspend"),
}
internal fun sessionDrawerPages(hasSecondScreen: Boolean): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter { hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN }
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
val index = indexOf(current).coerceAtLeast(0)
return this[Math.floorMod(index + direction, size)]
}
@@ -17,7 +17,6 @@ import androidx.compose.ui.geometry.Size
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.Role
import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.LoadingState
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.FastOutSlowInEasing
@@ -71,9 +70,6 @@ import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.PlatformTextStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
// The session's loading screen, its paused screen and the HUD text style. // The session's loading screen, its paused screen and the HUD text style.
@@ -109,24 +105,31 @@ private fun loadStages(steam: Boolean): List<LoadStage> = if (steam) listOf(
) )
/** /**
* The checklist stage a loading line's [topic] belongs to, -1 when it says nothing about the stage. * The checklist stage a loading line belongs to, -1 when it says nothing about the stage. The lines
* The lines are the session script's "== STEP" milestones and the installer's own progress; they * are the session script's "== STEP" milestones and the installer's own progress; they arrive in
* arrive in order, and the screen never steps back. * order, and the screen never steps back.
*/ */
private fun stageOf(topic: LoadingState.Topic, steam: Boolean): Int = when (topic) { private fun stageOf(step: String, steam: Boolean): Int {
LoadingState.Topic.RUNTIME -> 0 val t = step.lowercase()
LoadingState.Topic.SESSION -> 1 return when {
LoadingState.Topic.DESKTOP -> if (steam) -1 else 1 "linux runtime" in t -> 0
LoadingState.Topic.STEAM_STARTING -> if (steam) 3 else -1 "starting the session" in t -> 1
LoadingState.Topic.STEAM -> if (steam) 2 else -1 !steam && "desktop" in t -> 1
LoadingState.Topic.OTHER -> -1 steam && "starting the steam client" in t -> 3
steam && ("steam" in t || "client" in t || "proton" in t || "library" in t || "compatibility" in t) -> 2
else -> -1
}
}
/** Download and install lines are worth reading as they are; the script's own notes are not. */
private fun readableStep(step: String): Boolean {
val t = step.lowercase()
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
} }
@Composable @Composable
fun LoadingOverlay( fun LoadingOverlay(
step: String, percent: Int, elapsed: String, hint: String, ended: Boolean, step: String, percent: Int, elapsed: String, hint: String, ended: Boolean,
/** What [step] is about, and whether it is a download or install line worth showing as it is (see [LoadingState]). */
topic: LoadingState.Topic, readable: Boolean,
title: String = stringResource(R.string.load_starting_steam), steam: Boolean = true, onCancel: (() -> Unit)? = null, title: String = stringResource(R.string.load_starting_steam), steam: Boolean = true, onCancel: (() -> Unit)? = null,
/** An ended session's exit status and log path, shown small under the advice. */ /** An ended session's exit status and log path, shown small under the advice. */
endedDetail: String? = null, endedDetail: String? = null,
@@ -141,12 +144,12 @@ fun LoadingOverlay(
var ball by remember { mutableStateOf<Pair<Offset, Float>?>(null) } var ball by remember { mutableStateOf<Pair<Offset, Float>?>(null) }
val stages = remember(steam) { loadStages(steam) } val stages = remember(steam) { loadStages(steam) }
var reached by remember { mutableStateOf(0) } var reached by remember { mutableStateOf(0) }
LaunchedEffect(step, topic, steam) { LaunchedEffect(step, steam) {
val at = stageOf(topic, steam) val at = stageOf(step, steam)
if (at > reached) reached = at if (at > reached) reached = at
} }
val active = reached.coerceAtMost(stages.lastIndex) val active = reached.coerceAtMost(stages.lastIndex)
val detail = if (percent >= 0 || readable) step.replaceFirstChar { it.uppercase() } else stringResource(stages[active].detail) val detail = if (percent >= 0 || readableStep(step)) step.replaceFirstChar { it.uppercase() } else stringResource(stages[active].detail)
val context = LocalContext.current val context = LocalContext.current
// The Steam tab's wall behind it, dimmed and slowed: starting Steam reads as the same place settling in. // The Steam tab's wall behind it, dimmed and slowed: starting Steam reads as the same place settling in.
val games by produceState(emptyList<Library.SteamGame>()) { val games by produceState(emptyList<Library.SteamGame>()) {
@@ -270,11 +273,7 @@ private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
.padding(horizontal = 12.dp), .padding(horizontal = 12.dp),
) { ) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).background(colors.onBackground)) { Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).background(colors.onBackground)) {
Text("B", color = colors.background, style = TextStyle( Text("B", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.background)
fontSize = 12.sp, lineHeight = 12.sp, fontWeight = FontWeight.Bold,
platformStyle = PlatformTextStyle(includeFontPadding = false),
lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.Both),
))
} }
Text(stringResource(R.string.common_cancel), fontSize = 13.sp, color = colors.onSurfaceVariant) Text(stringResource(R.string.common_cancel), fontSize = 13.sp, color = colors.onSurfaceVariant)
} }
@@ -28,24 +28,15 @@ import androidx.compose.foundation.layout.offset
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.icons.outlined.AutoFixHigh import androidx.compose.material.icons.outlined.AutoFixHigh
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.MoreHoriz import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.PowerSettingsNew import androidx.compose.material.icons.outlined.PowerSettingsNew
import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.ScreenShare
import androidx.compose.material.icons.outlined.PictureInPictureAlt
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
import androidx.compose.material.icons.outlined.Settings import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.clipToBounds
import android.view.Display import android.view.Display
import androidx.activity.compose.BackHandler import androidx.activity.compose.BackHandler
@@ -88,8 +79,6 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideInHorizontally
@@ -104,6 +93,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@@ -126,11 +116,10 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.core.TextureFiltering import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.gpu.ScreenEffectLooks
import com.droiddeck.launcher.gpu.ScreenEffects import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.ComponentsManager import com.droiddeck.launcher.session.ComponentsManager
@@ -139,33 +128,22 @@ import com.droiddeck.launcher.input.SecondScreenMode
import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collect
import java.util.Locale import java.util.Locale
private val SessionDrawerPage.title: Int get() = when (this) { private val drawerPageTitles = listOf(R.string.drawer_page_display, R.string.drawer_page_effects, R.string.drawer_page_controls, R.string.drawer_page_components, R.string.drawer_page_settings)
SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller
SessionDrawerPage.SECOND_SCREEN -> R.string.drawer_second_screen
SessionDrawerPage.DISPLAY -> R.string.drawer_page_display
SessionDrawerPage.EFFECTS -> R.string.drawer_page_effects
SessionDrawerPage.GAMES -> R.string.game_settings_title
SessionDrawerPage.SESSION -> R.string.mode_session
}
private val SessionDrawerPage.icon get() = when (this) { /** One icon per drawer page, in page order (QAM-style tabs). */
SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.AutoFixHigh, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings)
SessionDrawerPage.SECOND_SCREEN -> Icons.Outlined.ScreenShare
SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows private val drawerPageEntries = listOf("hud", "look", "touch", "cmp-proton", "suspend")
SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
}
private class DrawerFocus { private class DrawerFocus {
private val requesters = HashMap<String, FocusRequester>() private val requesters = HashMap<String, FocusRequester>()
private val last = mutableMapOf<SessionDrawerPage, String>() private val last = arrayOfNulls<String>(DRAWER_PAGES)
var focused by mutableStateOf<String?>(null) var focused by mutableStateOf<String?>(null)
private set private set
private fun requester(key: String) = requesters.getOrPut(key) { FocusRequester() } private fun requester(key: String) = requesters.getOrPut(key) { FocusRequester() }
fun track(page: SessionDrawerPage, key: String): Modifier = Modifier.focusRequester(requester(key)).onFocusChanged { fun track(page: Int, key: String): Modifier = Modifier.focusRequester(requester(key)).onFocusChanged {
if (it.isFocused) { if (it.isFocused) {
last[page] = key last[page] = key
focused = key focused = key
@@ -173,9 +151,9 @@ private class DrawerFocus {
} }
/** Where focus was last on [page], if anywhere. */ /** Where focus was last on [page], if anywhere. */
fun target(page: SessionDrawerPage) = last[page] fun target(page: Int) = last[page]
fun request(key: String) = runCatching { requester(key).requestFocus() } fun request(key: String) = runCatching { requester(key).requestFocus() }
fun forget(page: SessionDrawerPage) { last.remove(page) } fun forget(page: Int) { last[page] = null }
} }
/** Everything the drawer shows and does. */ /** Everything the drawer shows and does. */
@@ -189,13 +167,13 @@ class DrawerActions(
val frameGen: FrameGen.Mode, val frameGen: FrameGen.Mode,
val lossless: Lossless.State, val lossless: Lossless.State,
val oscMode: String, val oscMode: String,
val onScreenButtonsVisible: Boolean,
val suspendPolicy: String, val suspendPolicy: String,
val backActionsInverted: Boolean, val backActionsInverted: Boolean,
val touchMode: String, val touchMode: String,
val touchAuto: String, val touchAuto: String,
val shapeMode: String,
val fexPreset: String, val fexPreset: String,
/** Steam only: forces game windows fullscreen, changed live (null = not Steam). */ /** Steam only: games stretched to the screen's size, changed live (null = not Steam). */
val fillScreen: Boolean? = null, val fillScreen: Boolean? = null,
val upscaler: Int = 0, val upscaler: Int = 0,
val upscaleSharpness: Int = 75, val upscaleSharpness: Int = 75,
@@ -225,6 +203,7 @@ class DrawerActions(
val onSuspendPolicy: (String) -> Unit, val onSuspendPolicy: (String) -> Unit,
val onBackActionsInverted: (Boolean) -> Unit, val onBackActionsInverted: (Boolean) -> Unit,
val onTouch: (String) -> Unit, val onTouch: (String) -> Unit,
val onShape: (String) -> Unit,
val onFexPreset: (String) -> Unit, val onFexPreset: (String) -> Unit,
val onFillScreen: (Boolean) -> Unit = {}, val onFillScreen: (Boolean) -> Unit = {},
val onUpscaler: (Int) -> Unit = {}, val onUpscaler: (Int) -> Unit = {},
@@ -245,7 +224,7 @@ class DrawerActions(
/** Stop with the dialog's button's bounds on screen, for the flood to grow out of; null falls back to [onStop]. */ /** Stop with the dialog's button's bounds on screen, for the flood to grow out of; null falls back to [onStop]. */
val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null, val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null,
val onClose: () -> Unit, val onClose: () -> Unit,
/** Games tab: every Proton with what it uses; null until first read. */ /** Components tab: every Proton with what it uses; null until first read. */
val components: ComponentsManager.Snapshot? = null, val components: ComponentsManager.Snapshot? = null,
/** Re-reads the Protons (and runs swaps that waited for a game to close). */ /** Re-reads the Protons (and runs swaps that waited for a game to close). */
val onComponentsRefresh: () -> Unit = {}, val onComponentsRefresh: () -> Unit = {},
@@ -255,20 +234,16 @@ class DrawerActions(
@OptIn(ExperimentalComposeUiApi::class) @OptIn(ExperimentalComposeUiApi::class)
@Composable @Composable
internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions) { fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageChange: (Int) -> Unit, a: DrawerActions) {
val pages = sessionDrawerPages(a.steam && a.secondScreenDisplays.isNotEmpty())
val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER
LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) }
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
val host = rememberMenuHost() val host = rememberMenuHost()
var androidAppsExpanded by rememberSaveable { mutableStateOf(false) } var androidAppsExpanded by rememberSaveable { mutableStateOf(false) }
var advancedEffectsExpanded by rememberSaveable { mutableStateOf(false) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) } var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
var confirmStop by remember { mutableStateOf(false) } var confirmStop by remember { mutableStateOf(false) }
var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) } var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
var stopCoords by remember { mutableStateOf<LayoutCoordinates?>(null) } var stopCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
val pageScroll = remember { SessionDrawerPage.entries.associateWith { ScrollState(0) } } val pageScroll = remember { List(DRAWER_PAGES) { ScrollState(0) } }
val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil") val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil")
val focus = remember { DrawerFocus() } val focus = remember { DrawerFocus() }
val inputModeManager = LocalInputModeManager.current val inputModeManager = LocalInputModeManager.current
@@ -278,13 +253,13 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
} }
BackHandler(enabled = open && confirmStop) { confirmStop = false } BackHandler(enabled = open && confirmStop) { confirmStop = false }
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null } LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
LaunchedEffect(open, page) { if (open && page == SessionDrawerPage.GAMES) a.onComponentsRefresh() } LaunchedEffect(open, page) { if (open && page == DRAWER_PAGE_COMPONENTS) a.onComponentsRefresh() }
LaunchedEffect(open, controllerActive) { LaunchedEffect(open, controllerActive) {
if (open && !controllerActive) focusManager.clearFocus(force = true) if (open && !controllerActive) focusManager.clearFocus(force = true)
} }
// The page focus was last put on: turning to another (LB, RB, a tab) starts it at its first // The page focus was last put on: turning to another (LB, RB, a tab) starts it at its first
// option; anything else (a menu closing, the drawer opening again) goes back where it was. // option; anything else (a menu closing, the drawer opening again) goes back where it was.
var focusedPage by remember { mutableStateOf(page) } var focusedPage by remember { mutableIntStateOf(page) }
LaunchedEffect(open, page, controllerActive, host.open, appToChooseDisplay, confirmStop) { LaunchedEffect(open, page, controllerActive, host.open, appToChooseDisplay, confirmStop) {
if (!open) { if (!open) {
host.open = null host.open = null
@@ -294,8 +269,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (host.open != null || appToChooseDisplay != null || confirmStop) return@LaunchedEffect if (host.open != null || appToChooseDisplay != null || confirmStop) return@LaunchedEffect
val turned = page != focusedPage val turned = page != focusedPage
focusedPage = page focusedPage = page
// The page's top control: on Session that is Android apps, when it is shown. // The page's top control: on Settings that is Android apps, when it is shown.
val first = if (page == SessionDrawerPage.SESSION && a.isHomeApp) "apps" else page.firstControl val first = if (page == drawerPageEntries.lastIndex && a.isHomeApp) "apps" else drawerPageEntries[page]
if (turned) focus.forget(page) if (turned) focus.forget(page)
val target = focus.target(page) ?: first val target = focus.target(page) ?: first
repeat(24) { repeat(24) {
@@ -308,7 +283,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
} }
} }
if (open || veil > 0.01f) Box( if (open || veil > 0.01f) Box(
modifier = Modifier.fillMaxSize() modifier = Modifier.fillMaxSize().graphicsLayer { alpha = veil }.background(Color(0x8A000000))
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() }, .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() },
) )
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) { androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
@@ -374,21 +349,31 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
modifier = Modifier.fillMaxWidth().padding(top = if (short) 6.dp else 12.dp), modifier = Modifier.fillMaxWidth().padding(top = if (short) 6.dp else 12.dp),
) { ) {
DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) { DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) {
host.open = null; onPageChange(pages.step(page, -1)) host.open = null; onPageChange((page + DRAWER_PAGES - 1) % DRAWER_PAGES)
} }
DrawerPageTabs(page = page, pages = pages, compact = short, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) } DrawerPageTabs(page = page, compact = short, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) { DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) {
host.open = null; onPageChange(pages.step(page, 1)) host.open = null; onPageChange((page + 1) % DRAWER_PAGES)
} }
} }
Column( Column(
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)), modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll[page]),
) { CompositionLocalProvider(LocalChipMinWidth provides 120.dp) { ) { CompositionLocalProvider(LocalChipMinWidth provides 120.dp) {
when (page) { when (page) {
SessionDrawerPage.DISPLAY -> { 0 -> {
SettingsGroup(stringResource(R.string.drawer_page_display)) { SettingsGroup(stringResource(R.string.drawer_page_display)) {
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn,
chipModifier = focus.track(page, "hud"), onChange = a.onHud) chipModifier = focus.track(page, "hud"), onChange = a.onHud)
if (a.fillScreen != null) ToggleRow(
host, "fill", stringResource(R.string.drawer_fill), null, a.fillScreen,
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen,
)
ChoiceRow(host, "upscaler", stringResource(R.string.drawer_scaling), null,
SessionPrefs.upscalerChoices, a.upscaler,
chipModifier = focus.track(page, "upscaler"), onPick = a.onUpscaler)
SliderRow(stringResource(R.string.drawer_scaling_sharpness), null, a.upscaleSharpness, 0..100, step = 5,
enabled = a.upscaler != 0, format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"),
onChange = a.onUpscaleSharpness)
val fgOpen = host.open == "fg" val fgOpen = host.open == "fg"
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) { SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) {
@@ -398,27 +383,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
} }
} }
} }
SettingsGroup(stringResource(R.string.display_image_scaling)) {
ChoiceRow(host, "upscaler", stringResource(R.string.display_filter), null,
SessionPrefs.upscalerChoices(LocalContext.current), a.upscaler,
note = stringResource(R.string.display_filter_note),
chipModifier = focus.track(page, "upscaler"), onPick = a.onUpscaler)
if (SessionPrefs.upscalerHasSharpness(a.upscaler)) SliderRow(
stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5,
format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), onChange = a.onUpscaleSharpness)
}
if (a.fillScreen != null) SettingsGroup(stringResource(R.string.display_window_compatibility)) {
ToggleRow(host, "fill", stringResource(R.string.display_force_fullscreen),
stringResource(R.string.display_force_fullscreen_live), a.fillScreen,
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen)
}
} }
SessionDrawerPage.EFFECTS -> { DRAWER_PAGE_EFFECTS -> {
ScreenEffectsGroup(host, a, advancedEffectsExpanded, ScreenEffectsSettings(host, a.effects, a.upscaler, a.onEffects, a.onUpscaler) { key -> focus.track(page, key) }
onAdvancedToggle = { advancedEffectsExpanded = !advancedEffectsExpanded }) { key -> focus.track(page, key) } TextureFilteringSettings(host, a.textureAnisotropy, a.textureLodBias,
a.onTextureAnisotropy, a.onTextureLodBias) { key -> focus.track(page, key) }
} }
SessionDrawerPage.CONTROLLER -> { DRAWER_PAGE_COMPONENTS -> ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
SettingsGroup(stringResource(R.string.drawer_page_controller)) { DRAWER_PAGE_CONTROLS -> {
SettingsGroup(stringResource(R.string.drawer_page_controls)) {
ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null, ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch) a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
@@ -429,19 +402,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
a.controller?.let { c -> a.controller?.let { c ->
ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble, ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble,
chipModifier = focus.track(page, "rumble"), onChange = a.onRumble) chipModifier = focus.track(page, "rumble"), onChange = a.onRumble)
if (a.onScreenButtonsVisible) { ToggleRow(host, "steam-button", stringResource(R.string.ctrl_steam_button), null, c.steamButton,
if (a.steam) { chipModifier = focus.track(page, "steam-button"), onChange = a.onSteamButton)
ToggleRow(host, "steam-button", stringResource(R.string.ctrl_steam_button), null, c.steamButton, ToggleRow(host, "qam-button", stringResource(R.string.ctrl_qam_button), null, c.qamButton,
chipModifier = focus.track(page, "steam-button"), onChange = a.onSteamButton) chipModifier = focus.track(page, "qam-button"), onChange = a.onQamButton)
ToggleRow(host, "qam-button", stringResource(R.string.ctrl_qam_button), null, c.qamButton, ToggleRow(host, "keyboard-button", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton,
chipModifier = focus.track(page, "qam-button"), onChange = a.onQamButton) chipModifier = focus.track(page, "keyboard-button"), onChange = a.onKeyboardButton)
}
ToggleRow(host, "keyboard-button", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton,
chipModifier = focus.track(page, "keyboard-button"), onChange = a.onKeyboardButton)
}
} }
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), null, if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), null,
listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)), listOf(false to SessionPrefs.BACK_MENU_THEN_QAM, true to SessionPrefs.BACK_QAM_THEN_MENU),
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted) a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
} }
SettingsGroup(stringResource(R.string.drawer_keyboard)) { SettingsGroup(stringResource(R.string.drawer_keyboard)) {
@@ -454,23 +423,18 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
} }
} }
} }
} if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup(stringResource(R.string.drawer_second_screen)) {
SessionDrawerPage.SECOND_SCREEN -> { ChoiceRow(host, "second-screen-mode", stringResource(R.string.drawer_second_screen_shows), null,
SecondScreenGroup(host, a) { key -> focus.track(page, key) } (listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
} (if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()))
SessionDrawerPage.GAMES -> { .map { it to it.label },
Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp, a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", stringResource(R.string.drawer_page_display), null,
TextureFilteringGroup(host, a) { key -> focus.track(page, key) } a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) { chipModifier = focus.track(page, "second-screen-display"), onPick = a.onSecondScreenDisplay)
ChoiceRow(host, "fex", stringResource(R.string.fex_preset_title), null,
FexPreset.all.map { it.id to stringResource(it.label) }, a.fexPreset,
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
GameEnvironmentRow(modifier = focus.track(page, "game-env"), showHint = false)
} }
ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
} }
SessionDrawerPage.SESSION -> { else -> {
if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps)) { if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps)) {
SettingsRow(stringResource(R.string.drawer_launch_app), null) { SettingsRow(stringResource(R.string.drawer_launch_app), null) {
DrawerOutlineButton(if (androidAppsExpanded) stringResource(R.string.common_hide) else stringResource(R.string.common_show), modifier = focus.track(page, "apps")) { DrawerOutlineButton(if (androidAppsExpanded) stringResource(R.string.common_hide) else stringResource(R.string.common_show), modifier = focus.track(page, "apps")) {
@@ -502,7 +466,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SettingsGroup(stringResource(R.string.drawer_session_behavior)) { SettingsGroup(stringResource(R.string.drawer_session_behavior)) {
ChoiceRow( ChoiceRow(
host, "suspend", stringResource(R.string.mode_suspend), host, "suspend", stringResource(R.string.mode_suspend),
null, stringResource(R.string.drawer_suspend_hint),
listOf( listOf(
SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto), SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto),
SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual), SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual),
@@ -514,6 +478,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
onPick = a.onSuspendPolicy, onPick = a.onSuspendPolicy,
) )
} }
SettingsGroup(stringResource(R.string.drawer_next_session)) {
ChoiceRow(host, "shape", stringResource(R.string.mode_ratio), null,
SessionPrefs.shapeChoices, a.shapeMode,
chipModifier = focus.track(page, "shape"), onPick = a.onShape)
}
if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) {
ChoiceRow(host, "fex", stringResource(R.string.fex_preset_title), stringResource(R.string.fex_next_launch),
FexPreset.all.map { it.id to stringResource(it.label) }, a.fexPreset,
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
GameEnvironmentRow(modifier = focus.track(page, "game-env"))
}
SettingsGroup(stringResource(R.string.drawer_support)) { SettingsGroup(stringResource(R.string.drawer_support)) {
SettingsRow(stringResource(R.string.drawer_logs), stringResource(R.string.drawer_logs_hint)) { SettingsRow(stringResource(R.string.drawer_logs), stringResource(R.string.drawer_logs_hint)) {
DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs")) { DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs")) {
@@ -526,11 +501,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null, ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
a.pipAutoEnter, onChange = a.onPipAutoEnter) a.pipAutoEnter, onChange = a.onPipAutoEnter)
} }
Column(Modifier.fillMaxWidth().padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Spacer(Modifier.height(18.dp))
if (a.pipSupported) DrawerActionButton(stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, if (a.pipSupported) DrawerOutlineButton(stringResource(R.string.pip_title), modifier = focus.track(page, "pip")) {
modifier = focus.track(page, "pip")) { host.open = null; a.onPip() } host.open = null; a.onPip()
if (!a.isHomeApp) DrawerActionButton(stringResource(R.string.drawer_background), Icons.AutoMirrored.Outlined.ExitToApp, }
modifier = focus.track(page, "background")) { host.open = null; a.onBackground() } if (!a.isHomeApp) DrawerOutlineButton(stringResource(R.string.drawer_background), modifier = focus.track(page, "background")) {
host.open = null; a.onBackground()
} }
} }
} }
@@ -570,27 +546,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
} }
} }
@Composable
private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(8.dp)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.16f) else colors.surfaceVariant)
.glideBorder(hot, shape, pal.signal)
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick).padding(horizontal = 16.dp, vertical = 10.dp),
) {
Icon(icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(22.dp))
Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
}
}
@Composable @Composable
private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, onClick: () -> Unit) { private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
@@ -681,60 +636,58 @@ private fun DrawerBumper(label: String, description: String, modifier: Modifier
/** /**
* The drawer's page tabs, QAM-style: one icon per page standing in a line in page order. The * The drawer's page tabs, QAM-style: one icon per page standing in a line in page order. The
* selected one steps forward - full size, bright, a soft glow - while the others step back to * selected one steps forward - full size, bright, a soft glow - while the others step back to
* a little smaller and fade, and the whole line leans a little toward the selection. LB / RB still turn * half size and fade, and the whole line leans a little toward the selection. LB / RB still turn
* the page (the buttons beside it and the pad's bumpers); a tab can be tapped or picked with the * the page (the buttons beside it and the pad's bumpers); a tab can be tapped or picked with the
* pad like the dots it replaces. * pad like the dots it replaces.
*/ */
@Composable @Composable
private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPage>, modifier: Modifier = Modifier, compact: Boolean = false, onSelect: (SessionDrawerPage) -> Unit) { private fun DrawerPageTabs(page: Int, modifier: Modifier = Modifier, compact: Boolean = false, onSelect: (Int) -> Unit) {
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
val count = pages.size val count = drawerPageIcons.size
val selectedIndex = pages.indexOf(page)
val middle = (count - 1) / 2f val middle = (count - 1) / 2f
val motion = Motion.tw<Float>(340, easing = FastOutSlowInEasing) val motion = Motion.tw<Float>(340, easing = FastOutSlowInEasing)
androidx.compose.foundation.layout.BoxWithConstraints( androidx.compose.foundation.layout.BoxWithConstraints(
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(), modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(),
) { ) {
val tab = if (compact) 36f else 44f val tab = if (compact) 40f else 56f
// Fit the line to the room between LB and RB. Worst case is an end tab selected: full size // Fit the line to the room between LB and RB. Worst case is an end tab selected: full size
// ([tab] dp) and pushed outward by the lean, which scales with the spacing. So // ([tab] dp) and pushed outward by the lean, which scales with the spacing. So
// (count-1) * spacing * (1 + lean/spacingMax) + tab <= width // (count-1) * spacing * (1 + lean/64) + 56 <= width
val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(24f, DRAWER_TAB_SPACING_DP) // - never more than the mock's 64 dp, never tighter than 32 dp.
val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(32f, DRAWER_TAB_SPACING_DP)
val leanStep = DRAWER_TAB_LEAN_DP * spacing / DRAWER_TAB_SPACING_DP val leanStep = DRAWER_TAB_LEAN_DP * spacing / DRAWER_TAB_SPACING_DP
val lean by animateFloatAsState(-(selectedIndex - middle) * leanStep, motion, label = "tabLean") val lean by animateFloatAsState(-(page - middle) * leanStep, motion, label = "tabLean")
pages.forEachIndexed { index, item -> drawerPageIcons.forEachIndexed { index, icon ->
androidx.compose.runtime.key(item) { val selected = index == page
val selected = item == page val source = remember { MutableInteractionSource() }
val source = remember { MutableInteractionSource() } val focused = source.collectIsFocusedAsState().value
val focused = source.collectIsFocusedAsState().value val scale by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale")
val scale by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale") val alpha by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha")
val alpha by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha") val glow by animateFloatAsState(if (selected) 1f else 0f, motion, label = "tabGlow")
val glow by animateFloatAsState(if (selected) 1f else 0f, motion, label = "tabGlow") val pageDescription = stringResource(R.string.drawer_page_desc, stringResource(drawerPageTitles[index]))
val pageDescription = stringResource(R.string.drawer_page_desc, stringResource(item.title)) val tint by animateColorAsState(if (selected) colors.onBackground else colors.onSurfaceVariant, Motion.tw(340, easing = FastOutSlowInEasing), label = "tabTint")
val tint by animateColorAsState(if (selected) colors.onBackground else colors.onSurfaceVariant, Motion.tw(340, easing = FastOutSlowInEasing), label = "tabTint") val select = { onSelect(index) }
val select = { onSelect(item) } Box(
Box( contentAlignment = Alignment.Center,
contentAlignment = Alignment.Center, modifier = Modifier
modifier = Modifier .offset(x = ((index - middle) * spacing + lean).dp)
.offset(x = ((index - middle) * spacing + lean).dp) .size(tab.dp)
.size(tab.dp) .graphicsLayer { scaleX = scale; scaleY = scale; this.alpha = alpha }
.graphicsLayer { scaleX = scale; scaleY = scale; this.alpha = alpha } .clip(RoundedCornerShape(16.dp))
.clip(RoundedCornerShape(16.dp)) .background(
.background( Brush.radialGradient(
Brush.radialGradient( listOf(pal.signal.copy(alpha = 0.34f * glow), pal.signal.copy(alpha = 0.10f * glow), Color.Transparent),
listOf(pal.signal.copy(alpha = 0.34f * glow), pal.signal.copy(alpha = 0.10f * glow), Color.Transparent), ),
), )
) .glideBorder(focused, RoundedCornerShape(16.dp), colors.onBackground)
.glideBorder(focused, RoundedCornerShape(16.dp), colors.onBackground) .semantics { contentDescription = pageDescription }
.semantics { contentDescription = pageDescription } .hoverable(source)
.hoverable(source) .clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select) .controllerConfirm(onClick = select),
.controllerConfirm(onClick = select), ) {
) { Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(if (compact) 22.dp else 30.dp))
Icon(item.icon, contentDescription = null, tint = tint, modifier = Modifier.size(if (compact) 22.dp else 30.dp))
}
} }
} }
} }
@@ -743,123 +696,16 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
/** The Look row's value when the rows below match no Look. */ /** The Look row's value when the rows below match no Look. */
private const val LOOK_CUSTOM = "custom" private const val LOOK_CUSTOM = "custom"
/** Presets and simple effects first; detailed adjustments stay behind Advanced. */ /** Display, Effects, Controls, Components, Settings. */
@Composable const val DRAWER_PAGES = 5
private fun ScreenEffectsGroup(
host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit,
track: (String) -> Modifier,
) {
val e = a.effects
val preset = ScreenEffectLooks.match(e, a.upscaler)
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
SettingsGroup(stringResource(R.string.drawer_effects)) {
val presets = ScreenEffectLooks.LOOKS.map { it.name to stringResource(it.label) }
ChoiceRow(host, "look", stringResource(R.string.drawer_look), null,
if (preset == null) listOf(LOOK_CUSTOM to stringResource(R.string.drawer_look_custom)) + presets else presets,
preset?.name ?: LOOK_CUSTOM, chipModifier = track("look")) { name ->
ScreenEffectLooks.LOOKS.firstOrNull { it.name == name }?.let { picked ->
picked.scalingMode?.let(a.onUpscaler)
a.onEffects(picked.effects)
}
}
ToggleRow(host, "fxaa", stringResource(R.string.drawer_fxaa), null, e.fxaa, chipModifier = track("fxaa")) { a.onEffects(e.copy(fxaa = it)) }
ToggleRow(host, "toon", stringResource(R.string.drawer_toon), null, e.toon, chipModifier = track("toon")) { a.onEffects(e.copy(toon = it)) }
ToggleRow(host, "crt", stringResource(R.string.drawer_crt), null, e.crt, chipModifier = track("crt")) { a.onEffects(e.copy(crt = it)) }
ToggleRow(host, "ntsc", stringResource(R.string.drawer_ntsc), null, e.ntsc, chipModifier = track("ntsc")) { a.onEffects(e.copy(ntsc = it)) }
ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) }
}
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val rotation by animateFloatAsState(if (advancedExpanded) 180f else 0f, Motion.tw(180), label = "advancedArrow")
val description = stringResource(if (advancedExpanded) R.string.widgets_expanded else R.string.widgets_collapsed)
val toggle = { host.open = null; onAdvancedToggle() }
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = track("effects-advanced").fillMaxWidth().padding(top = 12.dp).heightIn(min = 48.dp)
.glideBorder(hot, RoundedCornerShape(8.dp), pal.signal)
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle).semantics { stateDescription = description }.padding(horizontal = 4.dp),
) {
Text(stringResource(R.string.drawer_effects_advanced).uppercase(), fontSize = 12.sp,
fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant)
Box(Modifier.weight(1f).height(1.dp).background(pal.line))
Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(22.dp).rotate(rotation))
}
AnimatedVisibility(advancedExpanded) {
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(colors.surface).border(1.dp, pal.line, RoundedCornerShape(14.dp))) {
ToggleRow(host, "cas", stringResource(R.string.drawer_cas), null, e.cas, chipModifier = track("cas")) { a.onEffects(e.copy(cas = it)) }
if (e.cas) SliderRow(stringResource(R.string.drawer_cas_level), null, e.casLevel, 0..100, step = 5,
format = { "$it%" }, modifier = track("cas-level")) { a.onEffects(e.copy(casLevel = it)) }
ToggleRow(host, "deband", stringResource(R.string.drawer_deband), null, e.deband, chipModifier = track("deband")) { a.onEffects(e.copy(deband = it)) }
if (e.deband) SliderRow(stringResource(R.string.drawer_deband_strength), null, e.debandStrength, 0..200, step = 5,
format = { "$it%" }, modifier = track("deband-strength")) { a.onEffects(e.copy(debandStrength = it)) }
SliderRow(stringResource(R.string.drawer_brightness), null, e.brightness, -100..100, step = 2,
format = ::signed, modifier = track("brightness")) { a.onEffects(e.copy(brightness = it)) }
SliderRow(stringResource(R.string.drawer_contrast), null, e.contrast, -100..100, step = 2,
format = ::signed, modifier = track("contrast")) { a.onEffects(e.copy(contrast = it)) }
SliderRow(stringResource(R.string.drawer_gamma), null, (e.gamma * 100f).roundToInt(), 50..300, step = 5,
format = { String.format(Locale.US, "%.2f", it / 100f) }, modifier = track("gamma")) { a.onEffects(e.copy(gamma = it / 100f)) }
SliderRow(stringResource(R.string.drawer_saturation), null, e.saturation, 0..200, step = 5,
format = { "$it%" }, modifier = track("saturation")) { a.onEffects(e.copy(saturation = it)) }
}
}
}
/** Secondary-display modes are mutually exclusive and apply immediately. */ private const val DRAWER_PAGE_EFFECTS = 1
@Composable private const val DRAWER_PAGE_CONTROLS = 2
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val modes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
Column(Modifier.fillMaxWidth().selectableGroup()) {
modes.forEach { mode ->
val selected = a.secondScreenMode == mode
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val pick = { host.open = null; a.onSecondScreenMode(mode) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = track("second-screen:${mode.id}").fillMaxWidth().heightIn(min = 56.dp)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, RoundedCornerShape(8.dp), pal.signal)
.hoverable(source)
.selectable(selected, interactionSource = source, indication = null, role = Role.RadioButton, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
Text(stringResource(mode.label), fontSize = 15.sp, color = colors.onBackground, modifier = Modifier.weight(1f))
RadioButton(selected, onClick = null,
colors = RadioButtonDefaults.colors(selectedColor = pal.signal, unselectedColor = colors.onSurfaceVariant))
}
}
}
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", stringResource(R.string.drawer_page_display), null,
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay)
}
}
/** Texture filtering on the Games page: DXVK options for the next DirectX 9-11 launch. */ private const val DRAWER_PAGE_COMPONENTS = 3
@Composable
private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
SettingsGroup(stringResource(R.string.drawer_texture)) {
ChoiceRow(host, "anisotropy", stringResource(R.string.drawer_anisotropy), null,
SessionPrefs.textureAnisotropyChoices(LocalContext.current), a.textureAnisotropy, chipModifier = track("anisotropy"), onPick = a.onTextureAnisotropy)
ChoiceRow(host, "texture-sharpness", stringResource(R.string.drawer_texture_sharpness), null,
SessionPrefs.textureLodBiasChoices(LocalContext.current), a.textureLodBias, note = stringResource(R.string.drawer_texture_sharpness_note),
chipModifier = track("texture-sharpness"), onPick = a.onTextureLodBias)
}
}
private fun signed(v: Int) = if (v > 0) "+$v" else "$v"
/** /**
* The Games tab's components: quick swaps between what is already installed, per Proton. A swap * The drawer's Components tab: quick swaps between what is already installed, per Proton. A swap
* into the Proton a running game uses waits until that game closes; downloading, importing and * into the Proton a running game uses waits until that game closes; downloading, importing and
* deleting stay on the Components page in the app. * deleting stay on the Components page in the app.
*/ */
@@ -983,14 +829,14 @@ private fun <T> DrawerStackedChoice(
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
} }
/** A close row of icons: inactive tabs stay legible while the active tab leads. */ /** The tab row's measure, from the approved mock: side tabs at half size, a little faded. */
private const val DRAWER_TAB_SPACING_DP = 48f private const val DRAWER_TAB_SPACING_DP = 64f
private const val DRAWER_TAB_LEAN_DP = 8f private const val DRAWER_TAB_LEAN_DP = 12f
private const val DRAWER_TAB_SIDE_SCALE = 0.8f private const val DRAWER_TAB_SIDE_SCALE = 0.5f
private const val DRAWER_TAB_SIDE_ALPHA = 0.8f private const val DRAWER_TAB_SIDE_ALPHA = 0.7f
/** Room between the Stop pill and the box that steps out under it: the pull. */ /** Room between the Stop pill and the box that steps out under it: the pull. */
private val StepPull = 6.dp private val StepPull = 6.dp
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.focus.onFocusChanged
import kotlinx.coroutines.flow.filterNotNull
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.unit.dp
@Composable
internal fun SettingsCategoryPage(
s: FrontEndState,
a: FrontEndActions,
category: SettingsCategory,
mode: String,
target: String?,
onOpenDeveloperOptions: () -> Unit,
onRequestWirelessAdb: (Boolean) -> Unit,
modeContent: @Composable (MenuHost) -> Unit,
) {
val host = rememberMenuHost()
val entry = remember { FocusRequester() }
val frontFocus = LocalFrontFocus.current
var hasFocus by remember { mutableStateOf(false) }
var lastItem by rememberSaveable { mutableStateOf<String?>(null) }
LaunchedEffect(frontFocus) {
snapshotFlow { if (hasFocus) frontFocus?.last else null }.filterNotNull().collect { lastItem = it }
}
val back = { if (host.open != null) host.open = null else a.onPageBack() }
BackHandler(enabled = host.open != null, onBack = back)
LaunchedEffect(category, mode) {
if (target == null) {
focusWithinFrames({ hasFocus }) {
val id = lastItem
if (id != null && (frontFocus?.attached?.get(id) ?: 0) > 0) frontFocus!!.items.getValue(id)
else entry
}
}
}
CompositionLocalProvider(LocalSettingsTarget provides target, LocalSettingsAnchorsEnabled provides true) {
SettingsPage(
host, category.title, back,
) {
if (category == SettingsCategory.DISPLAY || category == SettingsCategory.SESSIONS) {
SegmentedTabs(
settingsSessionModes, mode,
Modifier.padding(bottom = 10.dp), a.onSettingsMode,
)
}
Column(Modifier.fillMaxWidth().focusRequester(entry).onFocusChanged { hasFocus = it.hasFocus }.focusGroup()) {
if (category != SettingsCategory.SESSIONS || mode == "steam") {
SetupContent(s, a, category, host, onOpenDeveloperOptions, onRequestWirelessAdb)
}
modeContent(host)
}
}
}
}
@@ -0,0 +1,391 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.DisplaySettings
import androidx.compose.material.icons.outlined.FolderOpen
import androidx.compose.material.icons.outlined.Gamepad
import androidx.compose.material.icons.outlined.GraphicEq
import androidx.compose.material.icons.outlined.HelpOutline
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.core.PhantomProcessLimit
import kotlinx.coroutines.flow.filterNotNull
/** The settings taxonomy is shared by the hub, category pages, and the searchable index. */
enum class SettingsCategory(val title: String, val description: String) {
GENERAL("General", "Launcher appearance and home-screen behavior"),
DISPLAY("Display & graphics", "Resolution, effects, scaling, and frame generation"),
CONTROLS("Controls & input", "Controller layout, touch behavior, and button mapping"),
AUDIO("Audio & microphone", "Session audio and microphone options"),
LIBRARY("Library & storage", "Game folders, storage, ROMs, and file access"),
SESSIONS("Sessions", "Session startup, suspend, and client behavior"),
COMPATIBILITY("Compatibility & performance", "Proton, components, and performance tools"),
SUPPORT("Support & diagnostics", "System checks, logs, runtime, and app updates"),
}
data class SettingsEntry(
val target: String,
val category: SettingsCategory,
val title: String,
val description: String,
val aliases: List<String> = emptyList(),
/** Null means the target is available regardless of Steam/Desktop mode. */
val mode: String? = null,
) {
internal fun matches(query: String): Boolean {
val q = query.trim().lowercase()
if (q.isEmpty()) return false
return sequenceOf(title, description, category.title).plus(aliases.asSequence())
.any { it.lowercase().contains(q) }
}
}
/** Search data points into the existing settings rows and specialist pages; it stores no values. */
object SettingsCatalog {
val entries: List<SettingsEntry> = listOf(
SettingsEntry("theme", SettingsCategory.GENERAL, "Theme", "Choose the launcher color theme", listOf("appearance", "colors")),
SettingsEntry("home-screen", SettingsCategory.GENERAL, "Home screen", "Enable DroidDeck as an Android home app", listOf("launcher", "default launcher")),
SettingsEntry("default-home", SettingsCategory.GENERAL, "Default home app", "Choose DroidDeck as the Android home app", listOf("home app", "launcher app")),
SettingsEntry("launcher-fullscreen", SettingsCategory.GENERAL, "Fullscreen", "Show the launcher without Android system bars", listOf("immersive")),
SettingsEntry("launcher-animations", SettingsCategory.GENERAL, "Animations", "Enable or disable launcher motion", listOf("motion")),
SettingsEntry("store-enabled", SettingsCategory.GENERAL, "Linux app store", "Show the Flathub Store in the launcher", listOf("store", "flathub")),
SettingsEntry("res", SettingsCategory.DISPLAY, "Resolution", "Set the next session resolution", listOf("720p", "900p", "1080p", "native"), "steam"),
SettingsEntry("shape", SettingsCategory.DISPLAY, "Aspect ratio", "Choose how the session fits the screen", listOf("shape", "ratio"), "steam"),
SettingsEntry("fps", SettingsCategory.DISPLAY, "Frame-rate limit", "Limit the session frame rate", listOf("fps", "refresh rate"), "steam"),
SettingsEntry("upscaler", SettingsCategory.DISPLAY, "Upscaling", "Choose the session image scaling filter", listOf("sharpness", "scaling"), "steam"),
SettingsEntry("upscale-sharpness", SettingsCategory.DISPLAY, "Upscaling sharpness", "Adjust image sharpening", listOf("sharpening"), "steam"),
SettingsEntry("hdr", SettingsCategory.DISPLAY, "HDR", "Enable HDR output when supported", listOf("high dynamic range"), "steam"),
SettingsEntry("fill", SettingsCategory.DISPLAY, "Fill screen", "Stretch the session to fill the display", listOf("force fullscreen"), "steam"),
SettingsEntry("stretch169", SettingsCategory.DISPLAY, "Stretch to 16:9", "Stretch the session image to a 16:9 shape", listOf("widescreen stretch"), "steam"),
SettingsEntry("gpu-drivers", SettingsCategory.COMPATIBILITY, "GPU drivers", "Manage Android and Linux display drivers", listOf("turnip", "adreno", "vulkan"), "steam"),
SettingsEntry("fg", SettingsCategory.DISPLAY, "Frame generation", "Choose a frame-generation mode or import Lossless Scaling", listOf("lossless scaling", "lsfg")),
SettingsEntry("effects-look", SettingsCategory.DISPLAY, "Screen effects preset", "Choose a preset for image effects", listOf("look", "post-processing")),
SettingsEntry("effects-cas", SettingsCategory.DISPLAY, "Contrast adaptive sharpening", "Enable contrast adaptive sharpening", listOf("cas", "sharpness")),
SettingsEntry("effects-cas-level", SettingsCategory.DISPLAY, "Sharpening strength", "Adjust contrast adaptive sharpening", listOf("cas level")),
SettingsEntry("effects-fake-hdr", SettingsCategory.DISPLAY, "Fake HDR", "Add an HDR-style image effect", listOf("hdr effect")),
SettingsEntry("effects-deband", SettingsCategory.DISPLAY, "Debanding", "Reduce color banding in gradients", listOf("banding")),
SettingsEntry("effects-deband-strength", SettingsCategory.DISPLAY, "Debanding strength", "Adjust color banding reduction", listOf("banding strength")),
SettingsEntry("effects-brightness", SettingsCategory.DISPLAY, "Brightness", "Adjust the session image brightness", listOf("light")),
SettingsEntry("effects-contrast", SettingsCategory.DISPLAY, "Contrast", "Adjust the session image contrast", listOf("image contrast")),
SettingsEntry("effects-gamma", SettingsCategory.DISPLAY, "Gamma", "Adjust the session image gamma", listOf("midtones")),
SettingsEntry("effects-saturation", SettingsCategory.DISPLAY, "Saturation", "Adjust the session image saturation", listOf("color intensity")),
SettingsEntry("effects-fxaa", SettingsCategory.DISPLAY, "FXAA", "Enable fast approximate anti-aliasing", listOf("anti-aliasing")),
SettingsEntry("effects-toon", SettingsCategory.DISPLAY, "Toon effect", "Enable the toon image effect", listOf("cartoon")),
SettingsEntry("effects-crt", SettingsCategory.DISPLAY, "CRT effect", "Enable the CRT image effect", listOf("scanlines")),
SettingsEntry("effects-ntsc", SettingsCategory.DISPLAY, "NTSC effect", "Enable the NTSC image effect", listOf("composite video")),
SettingsEntry("textures-anisotropy", SettingsCategory.DISPLAY, "Texture anisotropy", "Choose texture filtering anisotropy", listOf("anisotropic filtering")),
SettingsEntry("textures-sharpness", SettingsCategory.DISPLAY, "Texture sharpness", "Adjust texture level-of-detail bias", listOf("lod bias", "texture filtering")),
SettingsEntry("touch", SettingsCategory.CONTROLS, "Touch mode", "Choose how touch input behaves in a session", listOf("touchpad", "direct touch"), "steam"),
SettingsEntry("controller-osc", SettingsCategory.CONTROLS, "On-screen controls", "Choose when the touch controls appear", listOf("overlay", "controller overlay"), "steam"),
SettingsEntry("controller", SettingsCategory.CONTROLS, "Controller type", "Choose the controller profile exposed to Steam", listOf("xbox", "steam deck"), "steam"),
SettingsEntry("back-actions", SettingsCategory.CONTROLS, "Back-button actions", "Choose the order of the Steam menu and Quick Access Menu", listOf("b button", "menu button", "qam")),
SettingsEntry("controller-mapping", SettingsCategory.CONTROLS, "Button mapping", "Remap controller buttons", listOf("mapping", "remap")),
SettingsEntry("controller-tint", SettingsCategory.CONTROLS, "Controller color", "Choose the on-screen controller color", listOf("tint")),
SettingsEntry("controller-layout", SettingsCategory.CONTROLS, "Controller layout", "Edit or reset the touch controller layout", listOf("custom layout")),
SettingsEntry("controller-reset", SettingsCategory.CONTROLS, "Reset controller settings", "Reset the on-screen controller configuration", listOf("reset all")),
SettingsEntry("controller-opacity", SettingsCategory.CONTROLS, "Controller opacity", "Adjust the on-screen controller opacity", listOf("transparency")),
SettingsEntry("controller-size", SettingsCategory.CONTROLS, "Controller size", "Adjust the on-screen controller size", listOf("scale")),
SettingsEntry("controller-stick-click", SettingsCategory.CONTROLS, "Stick click", "Enable stick-click controls", listOf("l3", "r3")),
SettingsEntry("controller-adaptive", SettingsCategory.CONTROLS, "Adaptive sticks", "Adjust stick behavior to the active game", listOf("stick sensitivity")),
SettingsEntry("controller-rumble", SettingsCategory.CONTROLS, "Controller rumble", "Enable controller vibration", listOf("vibration")),
SettingsEntry("controller-steam", SettingsCategory.CONTROLS, "Steam button", "Show the Steam button on the virtual controller", listOf("steam menu")),
SettingsEntry("controller-qam", SettingsCategory.CONTROLS, "Quick Access button", "Show the Quick Access button on the virtual controller", listOf("qam")),
SettingsEntry("controller-keyboard", SettingsCategory.CONTROLS, "On-screen keyboard button", "Show the keyboard button on the virtual controller", listOf("keyboard")),
SettingsEntry("controller-actions", SettingsCategory.CONTROLS, "Controller layout and mapping", "Edit the on-screen layout, remap buttons, or reset controller settings", listOf("color", "opacity", "size", "stick click", "adaptive sticks", "rumble", "steam button", "qam button", "keyboard button", "layout", "mapping", "reset")),
SettingsEntry("da", SettingsCategory.AUDIO, "Direct audio", "Configure direct game audio", listOf("audio output"), "steam"),
SettingsEntry("clientAudio", SettingsCategory.AUDIO, "Steam-menu audio", "Choose the audio mode for Steam menus", listOf("client audio", "steam client audio"), "steam"),
SettingsEntry("mic", SettingsCategory.AUDIO, "Microphone", "Allow session microphone input", listOf("recording", "voice chat"), "steam"),
SettingsEntry("added-games", SettingsCategory.LIBRARY, "Added games", "Manage imported game folders and launch files", listOf("non-steam games", "exe"), "steam"),
SettingsEntry("addedArt", SettingsCategory.LIBRARY, "Added game artwork", "Show artwork for imported games", listOf("game covers", "covers"), "steam"),
SettingsEntry("storage", SettingsCategory.LIBRARY, "Game storage", "Choose where Steam stores games", listOf("second library", "sd card"), "steam"),
SettingsEntry("storage-location", SettingsCategory.LIBRARY, "Second library", "Import or remove a second Steam library", listOf("library location", "sd card folder"), "steam"),
SettingsEntry("added-games-add", SettingsCategory.LIBRARY, "Add a game folder", "Import another folder of games", listOf("add games directory", "import folder"), "steam"),
SettingsEntry("roms", SettingsCategory.LIBRARY, "ROM folders", "Choose the folder scanned for ROMs", listOf("emulator games")),
SettingsEntry("files", SettingsCategory.LIBRARY, "File manager", "Browse files in the Linux runtime", listOf("file browser")),
SettingsEntry("suspend", SettingsCategory.SESSIONS, "Suspend behavior", "Choose how sessions respond to suspend", listOf("sleep", "suspend policy"), "steam"),
SettingsEntry("offline", SettingsCategory.SESSIONS, "Offline mode", "Use the signed-in account in offline mode", listOf("offline account")),
SettingsEntry("pip-auto", SettingsCategory.SESSIONS, "Picture-in-picture", "Automatically enter picture-in-picture", listOf("pip"), "steam"),
SettingsEntry("steam-startup", SettingsCategory.SESSIONS, "Start Steam on launch", "Start Steam automatically with DroidDeck", listOf("autostart"), "steam"),
SettingsEntry("steamdeck", SettingsCategory.SESSIONS, "Steam Deck mode", "Use the Steam Deck client interface", listOf("big picture", "deck mode"), "steam"),
SettingsEntry("mangoapp", SettingsCategory.DISPLAY, "Performance overlay", "Show the MangoHud performance overlay", listOf("mangohud", "mangoapp"), "steam"),
SettingsEntry("channel", SettingsCategory.SESSIONS, "Steam branch", "Choose the Steam client update branch", listOf("beta", "client channel"), "steam"),
SettingsEntry("wifi", SettingsCategory.SESSIONS, "Wi-Fi discovery", "Enable local network discovery for Steam", listOf("network", "remote play"), "steam"),
SettingsEntry("renderer", SettingsCategory.SESSIONS, "Desktop renderer", "Choose the Linux desktop renderer", listOf("desktop graphics"), SessionService.MODE_DESKTOP),
SettingsEntry("decky", SettingsCategory.SESSIONS, "Decky Loader", "Install and manage Decky Loader", listOf("decky loader", "plugin loader"), "steam"),
SettingsEntry("decky-enabled", SettingsCategory.SESSIONS, "Enable Decky Loader", "Start or stop Decky Loader with Steam", listOf("decky toggle"), "steam"),
SettingsEntry("decky-loader", SettingsCategory.SESSIONS, "Decky installation", "Install or repair the Decky loader", listOf("decky install", "decky status"), "steam"),
SettingsEntry("decky-plugins", SettingsCategory.SESSIONS, "Decky plugins", "Install a Decky plugin ZIP", listOf("plugin zip"), "steam"),
SettingsEntry("components", SettingsCategory.COMPATIBILITY, "Compatibility components", "Manage FEX, DXVK, and VKD3D-Proton", listOf("dxvk", "vkd3d", "fex")),
SettingsEntry("default-proton", SettingsCategory.COMPATIBILITY, "Default Proton", "Choose the synchronized Steam default", listOf("default-proton")),
SettingsEntry("editing-proton", SettingsCategory.COMPATIBILITY, "Editing components for", "Choose which Proton build to edit", listOf("component editing target")),
SettingsEntry("protons", SettingsCategory.COMPATIBILITY, "Proton versions", "Install and manage Proton builds", listOf("wine", "proton-ge", "installed proton")),
SettingsEntry("performance", SettingsCategory.COMPATIBILITY, "Performance", "Tune CPU cores and graphics compatibility options", listOf("cpu", "cores", "zink", "fsync")),
SettingsEntry("performance:override", SettingsCategory.COMPATIBILITY, "Per-app core limits", "Override the Steam client CPU core selection", listOf("client core override", "cpu affinity")),
SettingsEntry("performance:clientCores", SettingsCategory.COMPATIBILITY, "Steam client CPU cores", "Choose CPU cores available to the Steam client", listOf("steam cores", "client affinity")),
SettingsEntry("performance:gameCores", SettingsCategory.COMPATIBILITY, "Game CPU cores", "Choose CPU cores available to games", listOf("game affinity")),
SettingsEntry("performance:glthread", SettingsCategory.COMPATIBILITY, "GL threading", "Change GL threading behavior", listOf("gl thread")),
SettingsEntry("performance:zink", SettingsCategory.COMPATIBILITY, "Zink", "Change Zink lazy pipeline behavior", listOf("lazy pipeline")),
SettingsEntry("performance:noglerror", SettingsCategory.COMPATIBILITY, "Ignore GL errors", "Change OpenGL error handling", listOf("opengl errors")),
SettingsEntry("performance:gsrealtime", SettingsCategory.COMPATIBILITY, "Gamescope real-time priority", "Set Gamescope scheduling priority", listOf("realtime scheduling")),
SettingsEntry("performance:gpuclock", SettingsCategory.COMPATIBILITY, "Pin GPU clock", "Set the GPU clock policy", listOf("gpu clock")),
SettingsEntry("performance:sysmem", SettingsCategory.COMPATIBILITY, "Turnip system memory", "Change Turnip system memory behavior", listOf("tu sysmem")),
SettingsEntry("performance:xalia", SettingsCategory.COMPATIBILITY, "Xalia", "Change Xalia input behavior", listOf("no xalia")),
SettingsEntry("performance:syncfallback", SettingsCategory.COMPATIBILITY, "Esync fallback", "Change synchronization fallback behavior", listOf("esync")),
SettingsEntry("performance:fsyncfirst", SettingsCategory.COMPATIBILITY, "Fsync first", "Try fsync before other synchronization backends", listOf("fsync")),
SettingsEntry("performance:fastsync", SettingsCategory.COMPATIBILITY, "Fast sync", "Enable fast synchronization", listOf("wine sync")),
SettingsEntry("performance:seccomp", SettingsCategory.COMPATIBILITY, "Proot seccomp", "Change the proot seccomp setting", listOf("syscall filtering")),
SettingsEntry("performance:fastpath", SettingsCategory.COMPATIBILITY, "Proot fast path", "Enable the proot fast path", listOf("fast path")),
SettingsEntry("performance:hostname", SettingsCategory.COMPATIBILITY, "Guest hostname", "Set the Linux guest hostname", listOf("computer name")),
SettingsEntry("fex", SettingsCategory.COMPATIBILITY, "FEX preset", "Choose CPU translation settings for games", listOf("translation", "x86"), "steam"),
SettingsEntry("syncBackend", SettingsCategory.COMPATIBILITY, "Synchronization backend", "Choose the game synchronization backend", listOf("ntsync", "fsync", "esync"), "steam"),
SettingsEntry("game-env", SettingsCategory.COMPATIBILITY, "Game environment", "Edit per-game environment options", listOf("environment variables", "launch options"), "steam"),
SettingsEntry("storageDiagnostics", SettingsCategory.SUPPORT, "Storage diagnostics", "Collect diagnostics for game storage", listOf("storage logs"), "steam"),
SettingsEntry("runtime", SettingsCategory.SUPPORT, "Linux runtime", "Install, update, or manage the Linux runtime", listOf("runtime install", "container")),
SettingsEntry("logs", SettingsCategory.SUPPORT, "Session logs", "Enable, share, or clear session logs", listOf("diagnostics", "debug logs")),
SettingsEntry("updates", SettingsCategory.SUPPORT, "DroidDeck updates", "View build information and release channel", listOf("version", "build")),
SettingsEntry("phantom-process", SettingsCategory.SUPPORT, "Child-process limit", "Diagnose Android's process limit that can block Steam", listOf("phantom process", "developer options", "wireless debugging", "adb")),
)
fun search(query: String): List<SettingsEntry> = entries.filter { it.matches(query) }
}
private data class CategoryCard(val category: SettingsCategory, val icon: ImageVector)
@Composable
fun SettingsHub(s: FrontEndState, a: FrontEndActions) {
var query by rememberSaveable { mutableStateOf("") }
val frontFocus = LocalFrontFocus.current
var hasFocus by remember { mutableStateOf(false) }
var lastItem by rememberSaveable { mutableStateOf<String?>(null) }
LaunchedEffect(frontFocus) {
snapshotFlow { if (hasFocus) frontFocus?.last else null }.filterNotNull().collect { lastItem = it }
}
LaunchedEffect(Unit) {
if (frontFocus != null) focusWithinFrames({ hasFocus }) {
val id = lastItem
if (id != null && (frontFocus.attached[id] ?: 0) > 0) frontFocus.items.getValue(id)
else frontFocus.primary
}
}
DisposableEffect(frontFocus) {
frontFocus?.let { it.primaryAttached++ }
onDispose { frontFocus?.let { it.primaryAttached-- } }
}
val cards = listOf(
CategoryCard(SettingsCategory.GENERAL, Icons.Outlined.Home),
CategoryCard(SettingsCategory.DISPLAY, Icons.Outlined.DisplaySettings),
CategoryCard(SettingsCategory.CONTROLS, Icons.Outlined.Gamepad),
CategoryCard(SettingsCategory.AUDIO, Icons.Outlined.GraphicEq),
CategoryCard(SettingsCategory.LIBRARY, Icons.Outlined.FolderOpen),
CategoryCard(SettingsCategory.SESSIONS, Icons.Outlined.Settings),
CategoryCard(SettingsCategory.COMPATIBILITY, Icons.Outlined.Speed),
CategoryCard(SettingsCategory.SUPPORT, Icons.Outlined.HelpOutline),
)
Column(
modifier = Modifier.fillMaxSize().onFocusChanged { hasFocus = it.hasFocus }.focusGroup()
.verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
PageHeader("Settings")
HubSearchField(query = query, onQuery = { query = it }, frontFocus = frontFocus)
if (!s.ready || s.removalPending || PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) {
val (title, detail, target) = when {
s.removalPending -> Triple("Runtime needs attention", "Runtime removal needs to be completed before using the session.", "runtime")
!s.ready -> Triple("Linux runtime is not ready", "Install or repair the runtime to launch Steam.", "runtime")
else -> Triple("Android process limit may block Steam", "Review the child-process setting and available fixes.", "phantom-process")
}
SettingsAnchor(target) { ActionRow(title, detail, "Review") { a.onSettingsCategory(SettingsCategory.SUPPORT, target) } }
}
if (query.isBlank()) {
val columns = if (LocalNarrowPane.current) 1 else 2
cards.chunked(columns).forEach { row ->
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().heightIn(min = 72.dp)) {
row.forEach { card ->
SettingsCategoryCard(card, Modifier.weight(1f).paneItem("settings-category:${card.category.name}"), onClick = { a.onSettingsCategory(card.category, null) })
}
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
} else {
val results = SettingsCatalog.search(query)
if (results.isEmpty()) {
Note("No settings found for “${query.trim()}”.")
} else {
results.forEach { entry ->
SettingsSearchResult(entry, Modifier.paneItem("settings-search:${entry.target}")) { a.onSettingsCategory(entry.category, entry.target) }
}
}
}
}
}
@Composable
private fun HubSearchField(query: String, onQuery: (String) -> Unit, frontFocus: FrontFocus?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(14.dp)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().clip(shape).background(colors.surface)
.border(1.dp, pal.line2, shape).padding(horizontal = 14.dp, vertical = 11.dp),
) {
Icon(Icons.Outlined.Search, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
val onQueryLatest = rememberUpdatedState(onQuery)
AndroidView(
modifier = Modifier.weight(1f).height(30.dp)
.then(if (frontFocus == null) Modifier else Modifier.focusRequester(frontFocus.primary)),
factory = { context ->
EditText(context).apply {
isSingleLine = true
background = null
setPadding(0, 0, 0, 0)
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 15f)
hint = "Search settings"
contentDescription = "Search settings"
// Keep the hub visible while typing on landscape handhelds.
imeOptions = EditorInfo.IME_ACTION_SEARCH or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
setOnFocusChangeListener { _, focused ->
if (focused) frontFocus?.last = FrontFocus.PRIMARY
}
setOnEditorActionListener { _, action, _ ->
if (action == EditorInfo.IME_ACTION_SEARCH) {
(context.getSystemService(InputMethodManager::class.java)).hideSoftInputFromWindow(windowToken, 0)
clearFocus()
true
} else false
}
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onQueryLatest.value(s?.toString().orEmpty())
}
override fun afterTextChanged(s: Editable?) = Unit
})
}
},
update = { field ->
field.setTextColor(colors.onBackground.toArgb())
field.setHintTextColor(colors.onSurfaceVariant.toArgb())
if (field.text.toString() != query) {
field.setText(query)
field.setSelection(query.length)
}
},
)
if (query.isNotEmpty()) Text(
"Clear", color = pal.signal, fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
modifier = Modifier.clickable { onQuery("") }.padding(4.dp),
)
}
}
@Composable
private fun SettingsCategoryCard(card: CategoryCard, modifier: Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val focused = source.collectIsFocusedAsState().value
val hovered = source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(14.dp)
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = modifier.fillMaxSize().clip(shape)
.background(if (focused || hovered) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(focused, shape, pal.signal, pal.line)
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(14.dp),
) {
Icon(card.icon, contentDescription = null, tint = if (focused || hovered) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
Text(card.category.title, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
@Composable
private fun SettingsSearchResult(entry: SettingsEntry, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val focused = source.collectIsFocusedAsState().value
val hovered = source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(12.dp)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth().clip(shape)
.background(if (focused || hovered) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(focused, shape, pal.signal, pal.line)
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 11.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(entry.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
}
Spacer(Modifier.width(12.dp))
Text(entry.category.title, fontSize = 12.sp, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@@ -0,0 +1,47 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.session.SessionService
internal val settingsSessionModes = listOf(
SessionService.MODE_STEAM to "Steam",
SessionService.MODE_DESKTOP to "Desktop",
)
/** A specialist search returns to the category control that opens that specialist. */
internal fun settingsCategoryTarget(target: String?): String? = when {
target == "default-proton" || target == "editing-proton" -> "components"
target?.startsWith("performance:") == true -> "performance"
else -> target
}
sealed interface SettingsDestination {
val key: String
data class Category(
val category: SettingsCategory,
val mode: String = "steam",
val target: String? = null,
) : SettingsDestination {
override val key = "settings:${category.name}:$mode:${target.orEmpty()}"
}
data class Components(val tab: String? = null, val target: String? = null) : SettingsDestination {
override val key = "components"
}
data object Protons : SettingsDestination { override val key = "protons" }
data class Performance(val target: String? = null) : SettingsDestination { override val key = "performance:${target.orEmpty()}" }
data object Mapping : SettingsDestination { override val key = "controller-mapping" }
}
data class SettingsHistory(val destinations: List<SettingsDestination> = emptyList()) {
val current: SettingsDestination? get() = destinations.lastOrNull()
fun open(destination: SettingsDestination): SettingsHistory =
if (destination == current) this else copy(destinations = destinations + destination)
fun replace(destination: SettingsDestination): SettingsHistory =
copy(destinations = destinations.dropLast(1) + destination)
fun back(): SettingsHistory = copy(destinations = destinations.dropLast(1))
}
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff. Show more