mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
Rename the app SteamDeck → DroidDeck
App name, app ID and code package: DroidDeck, com.droiddeck.launcher (sources moved to com/droiddeck/launcher, the 68 JNI functions renamed with them). The new app ID installs beside SteamDeck rather than over it. Everywhere the name was the app's own: the sidebar title, the session report, share zips, the shell title, wake-lock and log tags, User-Agents, the Compose theme, the Download folder and switch files (droiddeck-env, -osc, -driver, -tu-debug, -no-pad, -pad-log, -no-hud, -wlr-renderer; the old names are not read), and inside the runtime (droiddeck-desktop, Firefox's droiddeck.js, the shortcuts tag, the rumble socket, debug and cache paths). Build scripts, CI artifact (droiddeck-apk), CMake project, README and the progress log follow. Kept on purpose: Valve's Steam Deck (the -steamdeck flag, steamdeck_publicbeta/stable, 'Steam Deck mode', the steamos.cloud package URLs) and names inside the hosted desktop package (steamdeck.png, steamdeck-steam, steamdeck-bigpicture). 'Desktop installed' now tests for labwc instead of the launcher the app stages itself. A committed __pycache__ .pyc is removed.
This commit is contained in:
1 parent
bd51571530
commit
ae6dcc9798
118 files changed
+498
-487
No files matched your search
@@ -0,0 +1,12 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.Application
|
||||
import com.droiddeck.launcher.session.CrashHandler
|
||||
|
||||
/** Process-wide setup: the crash handler, so a session's folder is finished even when we die. */
|
||||
class App : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
CrashHandler.install(this)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
|
||||
/** Receives the system Home launch and routes it without consuming KEYCODE_HOME. */
|
||||
class HomeActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
routeHome()
|
||||
}
|
||||
|
||||
private fun routeHome() {
|
||||
val destination = if (HomeApp.isActiveSteamSession()) {
|
||||
Intent(this, SessionActivity::class.java)
|
||||
.setAction(SessionService.ACTION_HOME_GUIDE)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
} else {
|
||||
Intent(this, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
}
|
||||
startActivity(destination)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.role.RoleManager
|
||||
import android.graphics.Bitmap
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
|
||||
/** Android Home role and the launchable Android apps shown by the in-session app drawer. */
|
||||
object HomeApp {
|
||||
data class LaunchableApp(
|
||||
val label: String,
|
||||
val packageName: String,
|
||||
val className: String,
|
||||
val icon: Bitmap?,
|
||||
)
|
||||
|
||||
fun isDefault(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val roles = context.getSystemService(RoleManager::class.java)
|
||||
if (roles?.isRoleAvailable(RoleManager.ROLE_HOME) == true) {
|
||||
return roles.isRoleHeld(RoleManager.ROLE_HOME)
|
||||
}
|
||||
}
|
||||
val home = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_HOME)
|
||||
.addCategory(Intent.CATEGORY_DEFAULT)
|
||||
return context.packageManager.resolveActivity(home, PackageManager.MATCH_DEFAULT_ONLY)
|
||||
?.activityInfo?.packageName == context.packageName
|
||||
}
|
||||
|
||||
fun defaultLabel(context: Context): String? {
|
||||
val pm = context.packageManager
|
||||
val home = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_HOME)
|
||||
.addCategory(Intent.CATEGORY_DEFAULT)
|
||||
val resolved = pm.resolveActivity(home, PackageManager.MATCH_DEFAULT_ONLY) ?: return null
|
||||
val activity = resolved.activityInfo ?: return null
|
||||
val label = runCatching { pm.getApplicationLabel(activity.applicationInfo).toString() }.getOrNull()
|
||||
return label?.trim()?.takeIf { it.isNotEmpty() }
|
||||
?: resolved.loadLabel(pm)?.toString()?.trim()?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
fun roleRequestIntent(context: Context): Intent? {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null
|
||||
val roles = context.getSystemService(RoleManager::class.java) ?: return null
|
||||
if (!roles.isRoleAvailable(RoleManager.ROLE_HOME) || roles.isRoleHeld(RoleManager.ROLE_HOME)) return null
|
||||
return roles.createRequestRoleIntent(RoleManager.ROLE_HOME)
|
||||
}
|
||||
|
||||
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
|
||||
|
||||
fun launchableApps(context: Context): List<LaunchableApp> {
|
||||
val pm = context.packageManager
|
||||
val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
val apps = pm.queryIntentActivities(launch, 0)
|
||||
.asSequence()
|
||||
.mapNotNull { result ->
|
||||
val activity = result.activityInfo ?: return@mapNotNull null
|
||||
if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null
|
||||
val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName }
|
||||
val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull()
|
||||
LaunchableApp(label, activity.packageName, activity.name, icon)
|
||||
}
|
||||
.distinctBy { it.packageName }
|
||||
.toList()
|
||||
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
|
||||
fun launch(context: Context, app: LaunchableApp) {
|
||||
val intent = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(ComponentName(app.packageName, app.className))
|
||||
context.startActivity(intent)
|
||||
}
|
||||
|
||||
fun isActiveSteamSession(): Boolean =
|
||||
SessionState.running && SessionState.mode == SessionService.MODE_STEAM
|
||||
|
||||
fun openSystemHomeSettings(context: Context) {
|
||||
try {
|
||||
context.startActivity(settingsIntent())
|
||||
} catch (_: Exception) {
|
||||
// A role request remains available on Android 10+ if the settings page is missing.
|
||||
val request = roleRequestIntent(context)
|
||||
if (request != null) context.startActivity(request)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,945 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import java.io.File
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipReleases
|
||||
import com.droiddeck.launcher.gpu.LsfgNative
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.ui.PackageRow
|
||||
import com.droiddeck.launcher.session.OfflineMode
|
||||
import com.droiddeck.launcher.session.ProtonExtras
|
||||
import com.droiddeck.launcher.session.SessionLogShare
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.ui.ProtonPage
|
||||
import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.core.CpuCores
|
||||
import com.droiddeck.launcher.ui.CoreRow
|
||||
import com.droiddeck.launcher.ui.PerformancePage
|
||||
import com.droiddeck.launcher.ui.ModeSettingsPage
|
||||
import com.droiddeck.launcher.ui.ModeSettings
|
||||
import com.droiddeck.launcher.ui.ModeSettingsActions
|
||||
import com.droiddeck.launcher.ui.DriverRow
|
||||
import com.droiddeck.launcher.ui.ConfirmDialog
|
||||
import com.droiddeck.launcher.ui.CreditsDialog
|
||||
import com.droiddeck.launcher.ui.FrontEndScreen
|
||||
import com.droiddeck.launcher.ui.FrontEndState
|
||||
import com.droiddeck.launcher.ui.FrontEndActions
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.RomsDialog
|
||||
import com.droiddeck.launcher.files.InAppFilePicker
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
|
||||
/**
|
||||
* The whole app outside a session: is the runtime installed, is there a newer one, frame
|
||||
* generation, and one button that starts Steam. Everything a Steam client can do - the library,
|
||||
* the store, downloads, settings - is the client's own job once [SessionActivity] has it on screen.
|
||||
*/
|
||||
class MainActivity : ComponentActivity() {
|
||||
private val ui = Handler(Looper.getMainLooper())
|
||||
|
||||
// The screen's state. Compose redraws whatever reads these when they change.
|
||||
private var installed by mutableStateOf<String?>(null)
|
||||
private var ready by mutableStateOf(false)
|
||||
private var available by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
||||
private var busy by mutableStateOf(false)
|
||||
private var stage by mutableStateOf("")
|
||||
private var percent by mutableIntStateOf(-1)
|
||||
private var failed by mutableStateOf(false)
|
||||
private var frameGenLabel by mutableStateOf("Off")
|
||||
private var showRemove by mutableStateOf(false)
|
||||
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
||||
private var glThread by mutableStateOf(true)
|
||||
private var noGlError by mutableStateOf(true)
|
||||
private var steamDeckMode by mutableStateOf(false)
|
||||
private var showFrameGen by mutableStateOf(false)
|
||||
private var showCredits by mutableStateOf(false)
|
||||
private var showProtons by mutableStateOf(false)
|
||||
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
|
||||
private var catalogLoading by mutableStateOf(false)
|
||||
private var packageRows by mutableStateOf<List<PackageRow>?>(null)
|
||||
private var pkgId by mutableStateOf<String?>(null)
|
||||
private var pkgStage by mutableStateOf<String?>(null)
|
||||
private var pkgPercent by mutableIntStateOf(-1)
|
||||
private var desktopInstalled by mutableStateOf(false)
|
||||
private var offlineAccount by mutableStateOf<String?>(null)
|
||||
private var offline by mutableStateOf(false)
|
||||
private var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
private var protonBusyId by mutableStateOf<String?>(null)
|
||||
private var protonStage by mutableStateOf<String?>(null)
|
||||
private var protonPercent by mutableIntStateOf(-1)
|
||||
private var showPerformance by mutableStateOf(false)
|
||||
private var clientOverride by mutableStateOf(false)
|
||||
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
|
||||
private var gameCores by mutableStateOf<Set<Int>>(emptySet())
|
||||
private var tuSysmem by mutableStateOf(false)
|
||||
private var zinkLazy by mutableStateOf(false)
|
||||
private var noXalia by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
private var directAudio by mutableStateOf(false)
|
||||
private var clientDirectAudio by mutableStateOf(false)
|
||||
private var mic by mutableStateOf(false)
|
||||
private var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
|
||||
private var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
||||
private var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
||||
private var releaseStatus by mutableStateOf("Not checked yet - tap refresh to look for new drivers")
|
||||
private var releaseChecking by mutableStateOf(false)
|
||||
private var canRestoreBundled by mutableStateOf(false)
|
||||
/** Asset name -> download percent, while it downloads. */
|
||||
private val releaseProgress = HashMap<String, Int>()
|
||||
private var linuxSteam by mutableStateOf("")
|
||||
private var linuxDesktop by mutableStateOf("")
|
||||
private var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||
private var androidSelected by mutableStateOf("")
|
||||
|
||||
// The app's own picker (files/), once per kind of pick: the two driver lists validate
|
||||
// differently, and the reason a zip is refused names the list it belongs in.
|
||||
private val pickLinuxDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = true) }
|
||||
}
|
||||
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = false) }
|
||||
}
|
||||
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
|
||||
SessionPrefs.setAddedGamesDirs(this, addedGamesDirs + path)
|
||||
addedGamesDirs = SessionPrefs.addedGamesDirs(this)
|
||||
addedGamesArt = SessionPrefs.addedGamesArt(this)
|
||||
refreshAddedGames()
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
private var pendingAddedGame: String? = null
|
||||
private val pickAddedGameExe = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
val folder = pendingAddedGame ?: return@registerForActivityResult
|
||||
pendingAddedGame = null
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
|
||||
SessionPrefs.setAddedGameExe(this, folder, path)
|
||||
refreshAddedGames()
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
private var addedGamesDirs by mutableStateOf<List<String>>(emptyList())
|
||||
private var addedGamesArt by mutableStateOf(true)
|
||||
@Volatile private var artFetchRunning = false
|
||||
private var addedGames by mutableStateOf<List<com.droiddeck.launcher.ui.AddedGameRow>>(emptyList())
|
||||
private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
|
||||
SessionPrefs.setRomsDir(this, path)
|
||||
romsDir = path
|
||||
}
|
||||
}
|
||||
// The mode whose settings dialog is open, with what it shows; refreshed by openModeSettings().
|
||||
private var settingsMode 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 steamChannel by mutableStateOf("publicbeta")
|
||||
private var theme by mutableStateOf("paper")
|
||||
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
|
||||
private var hdrOn by mutableStateOf(false)
|
||||
private var hdrReason by mutableStateOf<String?>(null)
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var renderer by mutableStateOf("pixman")
|
||||
private var gameStorage by mutableStateOf("")
|
||||
private var storageOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
|
||||
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
|
||||
}
|
||||
private var romsDir by mutableStateOf<String?>(null)
|
||||
private var steamGames by mutableStateOf<List<Library.SteamGame>>(emptyList())
|
||||
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
|
||||
private var runningLabel by mutableStateOf<String?>(null)
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var showRoms by mutableStateOf(false)
|
||||
private var homeAppSelected by mutableStateOf(false)
|
||||
private var defaultHomeLabel by mutableStateOf<String?>(null)
|
||||
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
|
||||
|
||||
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
refreshHomeAppState()
|
||||
}
|
||||
|
||||
/** The session surface rises over the front end instead of cutting to it. */
|
||||
override fun startActivity(intent: Intent?) {
|
||||
if (intent?.component?.className == SessionActivity::class.java.name) {
|
||||
when {
|
||||
protonBusyId != null || ProtonExtras.installInProgress -> {
|
||||
android.widget.Toast.makeText(this, "Wait for the compatibility tool install to finish", android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
pkgStage != null -> {
|
||||
android.widget.Toast.makeText(this, "Wait for the desktop app install to finish", android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
super.startActivity(intent)
|
||||
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
theme = SessionPrefs.theme(this)
|
||||
setContent {
|
||||
DroidDeckTheme(theme) {
|
||||
val sm = settingsMode
|
||||
val page: (@Composable () -> Unit)? = when {
|
||||
sm != null -> { { ModeSettingsHost(sm) } }
|
||||
showPerformance -> { { PerformanceHost() } }
|
||||
showProtons -> { { ProtonHost() } }
|
||||
else -> null
|
||||
}
|
||||
FrontEndScreen(
|
||||
FrontEndState(
|
||||
installed = installed, ready = ready, available = available?.version,
|
||||
busy = busy, stage = stage, percent = percent,
|
||||
desktopInstalled = desktopInstalled,
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
||||
frameGenEngine = FrameGen.engine(this), frameGenMultiplier = FrameGen.multiplier(this),
|
||||
lsfgReady = LsfgNative.isInstalled(this),
|
||||
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else null,
|
||||
theme = theme,
|
||||
isHomeApp = homeAppSelected,
|
||||
defaultHomeLabel = defaultHomeLabel,
|
||||
androidApps = androidApps,
|
||||
packages = packageRows,
|
||||
packageCatalogLoading = catalogLoading,
|
||||
packageBusyId = pkgId,
|
||||
packageStage = pkgStage,
|
||||
packagePercent = pkgPercent,
|
||||
sessionRunning = SessionState.running,
|
||||
),
|
||||
FrontEndActions(
|
||||
onPlay = { startSession(Intent(this, SessionActivity::class.java)) },
|
||||
onPlayDesktopUi = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"))
|
||||
},
|
||||
onSteamGame = { g ->
|
||||
startActivity(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"))
|
||||
},
|
||||
onDesktop = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP))
|
||||
},
|
||||
onEmulator = { e -> launchProgram(e.program) },
|
||||
onRom = { g ->
|
||||
val e = emulatorList.first { it.id == g.emulatorId }
|
||||
startActivity(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM, e.program)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, Library.launchArgs(e.id, g.guestPath).toTypedArray()))
|
||||
},
|
||||
// The activity re-attaches to the session that is running; nothing restarts.
|
||||
onResume = { startActivity(Intent(this, SessionActivity::class.java)) },
|
||||
onSteamSettings = { openModeSettings(SessionService.MODE_STEAM) },
|
||||
onDesktopSettings = { openModeSettings(SessionService.MODE_DESKTOP) },
|
||||
onInstallPackage = { id -> installPackage(id) },
|
||||
onRemovePackage = { id -> removePackage(id) },
|
||||
onRuntime = { onRuntimeButton() },
|
||||
onFrameGenPick = { engine, multiplier ->
|
||||
FrameGen.set(this, engine, multiplier)
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
},
|
||||
onProtons = { openProtons() },
|
||||
onPerformance = { refreshCores(); showProtons = false; showPerformance = true },
|
||||
onRoms = { showRoms = true },
|
||||
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
|
||||
onLogs = {
|
||||
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
},
|
||||
onShareLogs = {
|
||||
Thread({
|
||||
val zip = runCatching { SessionLogShare.zipLatest(this) }.getOrNull()
|
||||
ui.post {
|
||||
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))
|
||||
}
|
||||
}, "share-logs").start()
|
||||
},
|
||||
onOffline = {
|
||||
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
|
||||
offline = OfflineMode.enabled(this)
|
||||
},
|
||||
onCredits = { showCredits = true },
|
||||
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false },
|
||||
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
||||
onHomeApp = { manageHomeApp() },
|
||||
onAndroidApp = { app -> launchAndroidApp(app) },
|
||||
),
|
||||
page = page,
|
||||
)
|
||||
if (showRoms) RomsDialog(
|
||||
path = romsDir,
|
||||
onChoose = {
|
||||
showRoms = false
|
||||
pickRomsDir.launch(InAppFilePicker.buildDirIntent(this, "Choose the ROMs folder", romsDir))
|
||||
},
|
||||
onClear = { SessionPrefs.setRomsDir(this, ""); romsDir = null; showRoms = false },
|
||||
onDismiss = { showRoms = false },
|
||||
)
|
||||
showNonAdreno?.let { release ->
|
||||
ConfirmDialog(
|
||||
title = "Not an Adreno GPU",
|
||||
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 = "Install anyway",
|
||||
onConfirm = { showNonAdreno = null; install(release) },
|
||||
onDismiss = { showNonAdreno = null },
|
||||
)
|
||||
}
|
||||
if (showRemove) ConfirmDialog(
|
||||
title = "Remove Linux runtime",
|
||||
text = "This deletes the runtime, the Steam client inside it, and every game installed there.",
|
||||
confirm = "Remove",
|
||||
onConfirm = { Thread({ LinuxRuntimeInstaller.uninstall(this); ui.post { refresh() } }, "uninstall").start() },
|
||||
onDismiss = { showRemove = false },
|
||||
)
|
||||
if (showCredits) CreditsDialog { showCredits = false }
|
||||
}
|
||||
}
|
||||
|
||||
// The session's logs land in Downloads so a failed run can be handed over as a folder
|
||||
// rather than dug out of app-private storage. targetSdk 28 means the old permission still
|
||||
// grants exactly that.
|
||||
val wanted = ArrayList<String>()
|
||||
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||||
}
|
||||
// The microphone is on by default; ask once, with the storage prompt, so voice chat works
|
||||
// without a trip to the settings. A refusal is not asked again - the toggle asks when used.
|
||||
if (SessionPrefs.micEnabled(this) && !SessionPrefs.micAsked(this)
|
||||
&& checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
wanted.add(Manifest.permission.RECORD_AUDIO)
|
||||
SessionPrefs.setMicAsked(this)
|
||||
}
|
||||
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
|
||||
// A session folder left without its ending - the process was killed - gets it now.
|
||||
if (!SessionState.running) Thread({ SessionArtifacts.finishAbandoned(this) }, "finish-abandoned").start()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
refreshHomeAppState()
|
||||
refresh()
|
||||
// Added games' art (a store lookup for what the folders lack) starts here, not only when
|
||||
// the cog opens.
|
||||
refreshAddedGames()
|
||||
if (catalog == null) loadDesktopCatalog()
|
||||
if (!busy) Thread({ checkCatalog() }, "catalog").start()
|
||||
}
|
||||
|
||||
private fun refreshHomeAppState() {
|
||||
homeAppSelected = HomeApp.isDefault(this)
|
||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||
androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
|
||||
}
|
||||
|
||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp) {
|
||||
try {
|
||||
HomeApp.launch(this, app)
|
||||
} catch (_: Exception) {
|
||||
android.widget.Toast.makeText(this, "Could not open ${app.label}", android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun manageHomeApp() {
|
||||
val request = HomeApp.roleRequestIntent(this)
|
||||
if (request != null) {
|
||||
homeRoleRequest.launch(request)
|
||||
} else {
|
||||
HomeApp.openSystemHomeSettings(this)
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadDesktopCatalog() {
|
||||
if (catalogLoading || catalog != null) return
|
||||
catalogLoading = true
|
||||
Thread({
|
||||
val fetched = DesktopCatalog.fetch()
|
||||
ui.post {
|
||||
catalog = fetched
|
||||
catalogLoading = false
|
||||
refreshPackages()
|
||||
}
|
||||
}, "catalog-desktop").start()
|
||||
}
|
||||
|
||||
private fun openProtons() {
|
||||
settingsMode = null
|
||||
showPerformance = false
|
||||
showProtons = true
|
||||
refreshProtons()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProtonHost() {
|
||||
ProtonPage(
|
||||
rows = protonRows,
|
||||
busyId = protonBusyId,
|
||||
stage = protonStage,
|
||||
percent = protonPercent,
|
||||
runtimeReady = ready,
|
||||
sessionRunning = SessionState.running,
|
||||
onInstall = { id -> installProton(id) },
|
||||
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; refreshProtons() },
|
||||
onRemove = { id -> removeProton(id) },
|
||||
onBack = { showProtons = false },
|
||||
)
|
||||
}
|
||||
|
||||
private fun installProton(id: String) {
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
ProtonExtras.unqueue(this, tool)
|
||||
protonBusyId = id
|
||||
protonStage = "Starting…"
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
val problem = ProtonExtras.install(this, tool) { label, value ->
|
||||
ui.post { protonStage = label; protonPercent = value }
|
||||
}
|
||||
ui.post {
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
protonPercent = -1
|
||||
refreshProtons()
|
||||
if (problem != null) android.widget.Toast.makeText(this, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "install-proton-$id").start()
|
||||
}
|
||||
|
||||
private fun removeProton(id: String) {
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
protonBusyId = id
|
||||
protonStage = "Removing ${tool.name}…"
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
ProtonExtras.remove(this, tool)
|
||||
ui.post {
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
refreshProtons()
|
||||
}
|
||||
}, "remove-proton-$id").start()
|
||||
}
|
||||
|
||||
private fun refreshPackages() {
|
||||
packageRows = catalog?.map { PackageRow(it.id, it.kind, it.notes) }
|
||||
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
||||
}
|
||||
|
||||
private fun launchProgram(path: String) {
|
||||
startActivity(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM, path))
|
||||
}
|
||||
|
||||
private fun installPackage(id: String) {
|
||||
val entry = catalog?.firstOrNull { it.id == id } ?: return
|
||||
if (pkgStage != null || SessionState.running) return
|
||||
pkgId = id; pkgStage = "Starting…"; pkgPercent = -1
|
||||
Thread({
|
||||
val problem = DesktopCatalog.install(this, entry) { stage, percent ->
|
||||
ui.post { pkgStage = stage; pkgPercent = percent }
|
||||
}
|
||||
ui.post {
|
||||
pkgStage = null; pkgId = null
|
||||
if (problem != null) android.widget.Toast.makeText(this, "${entry.name}: $problem", android.widget.Toast.LENGTH_LONG).show()
|
||||
refreshPackages()
|
||||
refresh()
|
||||
}
|
||||
}, "install-pkg").start()
|
||||
}
|
||||
|
||||
private fun removePackage(id: String) {
|
||||
val entry = catalog?.firstOrNull { it.id == id } ?: return
|
||||
if (pkgStage != null || SessionState.running) return
|
||||
pkgId = id; pkgStage = if (entry.kind == "appimage") "Removing ${entry.name}…" else "Forgetting ${entry.name}…"; pkgPercent = -1
|
||||
Thread({
|
||||
DesktopCatalog.remove(this, entry)
|
||||
ui.post {
|
||||
pkgStage = null; pkgId = null
|
||||
refreshPackages()
|
||||
refresh()
|
||||
}
|
||||
}, "remove-pkg").start()
|
||||
}
|
||||
|
||||
/** Both driver lists as the dialog shows them, re-read from disk so an import or removal shows at once. */
|
||||
/** Everything the mode's cog shows, read fresh, then the dialog. */
|
||||
/** The Steam or Desktop settings page, in the front end's pane. */
|
||||
@Composable
|
||||
private fun ModeSettingsHost(mode: String) {
|
||||
ModeSettingsPage(
|
||||
ModeSettings(
|
||||
mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
|
||||
hdr = hdrOn, hdrReason = hdrReason,
|
||||
linuxRows = linuxRows,
|
||||
linuxSelected = if (mode == SessionService.MODE_STEAM) linuxSteam else linuxDesktop,
|
||||
androidRows = androidRows, androidSelected = androidSelected,
|
||||
touchMode = touchMode,
|
||||
suspendPolicy = suspendPolicy,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||
clientDirectAudio = clientDirectAudio,
|
||||
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
||||
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
storageOptions = storageOptions,
|
||||
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
||||
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
|
||||
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
|
||||
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
|
||||
addedGamesArt = addedGamesArt,
|
||||
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, releaseStatus = releaseStatus,
|
||||
releaseChecking = releaseChecking, canRestoreBundled = canRestoreBundled,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
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 },
|
||||
onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() },
|
||||
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
|
||||
onRemoveLinux = { id -> deleteDriver(id, linux = true) },
|
||||
onRefreshReleases = { checkLatestTurnip() },
|
||||
onDownloadDriver = { name -> downloadReleaseDriver(name) },
|
||||
onRestoreBundled = { TurnipDriver(this).restoreBundled(); refreshDrivers() },
|
||||
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() },
|
||||
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
|
||||
onRemoveAndroid = { id -> deleteDriver(id, linux = false) },
|
||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
|
||||
onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on },
|
||||
onMic = { on ->
|
||||
SessionPrefs.setMicEnabled(this, on)
|
||||
mic = on
|
||||
// The session checks the grant itself at start; asking here means the
|
||||
// answer is in before the first session that wants it.
|
||||
if (on && checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 2)
|
||||
}
|
||||
},
|
||||
onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
|
||||
onGameStorage = { path, label -> setGameStorage(path, label) },
|
||||
onPickGameStorageFolder = {
|
||||
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, "Choose the game storage folder", gameStorage.ifEmpty { null }))
|
||||
},
|
||||
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
|
||||
onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
|
||||
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() },
|
||||
onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() },
|
||||
onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() },
|
||||
onPickAddedGameExe = { folder ->
|
||||
pendingAddedGame = folder
|
||||
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder))
|
||||
},
|
||||
onDismiss = { settingsMode = null },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** The Performance page, in the front end's pane. */
|
||||
@Composable
|
||||
private fun PerformanceHost() {
|
||||
PerformancePage(
|
||||
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
|
||||
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores,
|
||||
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, steamDeckMode = steamDeckMode, noXalia = noXalia,
|
||||
prootNoSeccomp = prootNoSeccomp, phantomWarning = phantomWarning,
|
||||
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
||||
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
|
||||
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
|
||||
onGlThread = { on -> SessionPrefs.setGlThread(this, on); glThread = on },
|
||||
onNoGlError = { on -> SessionPrefs.setNoGlError(this, on); noGlError = on },
|
||||
onSteamDeckMode = { on -> SessionPrefs.setSteamDeckMode(this, on); steamDeckMode = on },
|
||||
onNoXalia = { on -> SessionPrefs.setNoXalia(this, on); noXalia = on },
|
||||
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
|
||||
onClientCore = { core, on ->
|
||||
clientCores = if (on) clientCores + core else clientCores - core
|
||||
SessionPrefs.setClientCpus(this, CpuCores.format(clientCores))
|
||||
},
|
||||
onGameCore = { core, on ->
|
||||
gameCores = if (on) gameCores + core else gameCores - core
|
||||
SessionPrefs.setGameCpus(this, CpuCores.format(gameCores))
|
||||
},
|
||||
onDismiss = { showPerformance = false },
|
||||
)
|
||||
}
|
||||
|
||||
/** The added games as the settings page lists them; a scan of the folder, on this thread (one level, small). */
|
||||
private fun refreshAddedGames() {
|
||||
addedGames = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
|
||||
com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, g.candidates.map { c -> c.path to c.name }.distinctBy { it.first })
|
||||
}
|
||||
// Art the games do not have yet, from Steam's store, off the main thread; the rail
|
||||
// redraws when something arrives.
|
||||
if (SessionPrefs.addedGamesArt(this) && !artFetchRunning) {
|
||||
artFetchRunning = true
|
||||
Thread({
|
||||
try {
|
||||
val games = com.droiddeck.launcher.frontend.AddedGames.scan(this)
|
||||
if (com.droiddeck.launcher.frontend.AddedGameArt.fetchMissing(this, games)) ui.post { refresh() }
|
||||
} finally {
|
||||
artFetchRunning = false
|
||||
}
|
||||
}, "added-art").start()
|
||||
}
|
||||
}
|
||||
|
||||
private fun openModeSettings(mode: String) {
|
||||
showPerformance = false
|
||||
showProtons = false
|
||||
refreshDrivers()
|
||||
resolutionCap = SessionPrefs.resolutionCap(this, mode)
|
||||
customResolution = SessionPrefs.customResolution(this, mode)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
steamChannel = SessionPrefs.steamChannel(this)
|
||||
addedGamesDirs = SessionPrefs.addedGamesDirs(this)
|
||||
refreshAddedGames()
|
||||
shapeMode = SessionPrefs.shapeMode(this)
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
directAudio = SessionPrefs.directAudio(this)
|
||||
clientDirectAudio = SessionPrefs.clientDirectAudio(this)
|
||||
mic = SessionPrefs.micEnabled(this)
|
||||
renderer = SessionPrefs.desktopRenderer(this)
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
storageOptions = GameStorage.options(this).map { it.label to it.path }
|
||||
settingsMode = mode
|
||||
}
|
||||
|
||||
/** A second Steam library, proven writable first; "" = internal only. */
|
||||
private fun setGameStorage(path: String, label: String) {
|
||||
if (path.isNotEmpty() && path != SessionPrefs.GAME_STORAGE_OFF) {
|
||||
val problem = GameStorage.prepare(path)
|
||||
if (problem != null) {
|
||||
android.widget.Toast.makeText(this, "Not usable: $problem", android.widget.Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
}
|
||||
SessionPrefs.setGameStorage(this, path, label)
|
||||
gameStorage = path
|
||||
}
|
||||
|
||||
private fun refreshDrivers() {
|
||||
val lm = LinuxVulkanDriverManager(this)
|
||||
fun origin(id: String) = if (TurnipReleases.isDownloaded(this, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
||||
linuxRows = LinuxVulkanDriver.optionValues(this).map { id ->
|
||||
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
|
||||
else DriverRow(
|
||||
id, lm.getDriverName(id),
|
||||
listOfNotNull(
|
||||
lm.getDriverVersion(id).takeIf { it.isNotEmpty() },
|
||||
lm.getMinGlibc(id).takeIf { it.isNotEmpty() }?.let { "glibc $it+" },
|
||||
).joinToString(" · "),
|
||||
true, origin(id),
|
||||
)
|
||||
}
|
||||
linuxSteam = SessionPrefs.linuxDriver(this, SessionService.MODE_STEAM)
|
||||
linuxDesktop = SessionPrefs.linuxDriver(this, SessionService.MODE_DESKTOP)
|
||||
val td = TurnipDriver(this)
|
||||
val auto = td.autoId()
|
||||
androidRows = buildList {
|
||||
add(DriverRow(
|
||||
TurnipDriver.AUTO, "Auto - picked by GPU",
|
||||
if (auto == "system") "system Vulkan: no bundled build for this GPU" else "${td.displayName(auto)} (bundled)",
|
||||
false,
|
||||
))
|
||||
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
|
||||
for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
|
||||
}
|
||||
canRestoreBundled = td.hiddenBundled().isNotEmpty()
|
||||
androidSelected = SessionPrefs.androidDriver(this)
|
||||
refreshReleaseRows()
|
||||
}
|
||||
|
||||
/**
|
||||
* Import off the main thread - a driver zip is a few MB and the glibc check reads the whole
|
||||
* library - then say what happened. A refusal's message is the user-facing reason.
|
||||
*/
|
||||
private fun importDriver(uri: Uri, linux: Boolean) {
|
||||
val name = displayNameOf(uri)
|
||||
Thread({
|
||||
val problem = try {
|
||||
if (linux) LinuxVulkanDriverManager(this).installDriver(uri, name)
|
||||
else TurnipDriver(this).installFromZip(uri, name)
|
||||
null
|
||||
} catch (e: IllegalArgumentException) {
|
||||
e.message
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "driver import", e)
|
||||
"Import failed: ${e.message}"
|
||||
}
|
||||
ui.post {
|
||||
android.widget.Toast.makeText(
|
||||
this, problem ?: "Imported ${name ?: "driver"}",
|
||||
if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
|
||||
).show()
|
||||
refreshDrivers()
|
||||
}
|
||||
}, "import-driver").start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a
|
||||
* session never starts on a driver that is gone; a release download is forgotten, so the menu
|
||||
* offers it again.
|
||||
*/
|
||||
private fun deleteDriver(id: String, linux: Boolean) {
|
||||
if (linux) {
|
||||
LinuxVulkanDriverManager(this).removeDriver(id)
|
||||
for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
|
||||
if (SessionPrefs.linuxDriver(this, mode) == id) SessionPrefs.setLinuxDriver(this, mode, "")
|
||||
}
|
||||
} else {
|
||||
val td = TurnipDriver(this)
|
||||
if (id in TurnipDriver.BUNDLED) td.hideBundled(id) else td.remove(id)
|
||||
if (SessionPrefs.androidDriver(this) == id) SessionPrefs.setAndroidDriver(this, TurnipDriver.AUTO)
|
||||
}
|
||||
TurnipReleases.forget(this, id)
|
||||
android.widget.Toast.makeText(this, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show()
|
||||
refreshDrivers()
|
||||
}
|
||||
|
||||
/** The download entries and the refresh line, from what the last check found. */
|
||||
private fun refreshReleaseRows() {
|
||||
val check = TurnipReleases.cached(this)
|
||||
val lm = LinuxVulkanDriverManager(this)
|
||||
val td = TurnipDriver(this)
|
||||
fun rows(linux: Boolean) = check?.assets.orEmpty()
|
||||
.filter { it.linux == linux }
|
||||
.filter { a -> TurnipReleases.installedId(this, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null }
|
||||
.map { a ->
|
||||
val mb = "%.1f MB".format(a.size / 1_048_576.0)
|
||||
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
|
||||
}
|
||||
linuxDownloads = rows(linux = true)
|
||||
androidDownloads = rows(linux = false)
|
||||
if (!releaseChecking) releaseStatus = when (check) {
|
||||
null -> "Not checked yet - tap refresh to look for new drivers"
|
||||
else -> "Latest: " + check.latest.joinToString(" · ") { "${it.first} ${it.second}" } +
|
||||
(if (check.failed.isEmpty()) "" else " · ${check.failed.joinToString()} unreachable") +
|
||||
" · checked ${ago(check.checkedAt)}"
|
||||
}
|
||||
}
|
||||
|
||||
private fun ago(t: Long): String {
|
||||
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
|
||||
return when {
|
||||
m < 1 -> "just now"
|
||||
m < 60 -> "$m min ago"
|
||||
m < 48 * 60 -> "${m / 60} h ago"
|
||||
else -> "${m / (24 * 60)} days ago"
|
||||
}
|
||||
}
|
||||
|
||||
/** Only when the user taps refresh: nothing goes online on its own. */
|
||||
private fun checkLatestTurnip() {
|
||||
if (releaseChecking) return
|
||||
releaseChecking = true
|
||||
releaseStatus = "Checking Banners-Turnip and WinNative…"
|
||||
Thread({
|
||||
val problem = try { TurnipReleases.refresh(this); null } catch (e: Exception) {
|
||||
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
|
||||
}
|
||||
ui.post {
|
||||
releaseChecking = false
|
||||
refreshReleaseRows()
|
||||
if (problem != null) releaseStatus = "Couldn't check: $problem"
|
||||
}
|
||||
}, "turnip-release-check").start()
|
||||
}
|
||||
|
||||
/** Download one release driver and import it through the same importer a picked zip uses. */
|
||||
private fun downloadReleaseDriver(assetName: String) {
|
||||
val asset = TurnipReleases.cached(this)?.assets?.firstOrNull { it.name == assetName } ?: return
|
||||
if (releaseProgress.containsKey(assetName)) return
|
||||
releaseProgress[assetName] = 0
|
||||
refreshReleaseRows()
|
||||
Thread({
|
||||
var file: java.io.File? = null
|
||||
val problem = try {
|
||||
file = TurnipReleases.download(this, asset) { pct ->
|
||||
ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() }
|
||||
}
|
||||
val uri = Uri.fromFile(file)
|
||||
val id = if (asset.linux) LinuxVulkanDriverManager(this).installDriver(uri, asset.name)
|
||||
else TurnipDriver(this).installFromZip(uri, asset.name)
|
||||
TurnipReleases.recordDownload(this, asset, id)
|
||||
null
|
||||
} catch (e: IllegalArgumentException) {
|
||||
e.message
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "release driver download", e)
|
||||
"Download failed: ${e.message}"
|
||||
} finally {
|
||||
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
|
||||
}
|
||||
ui.post {
|
||||
releaseProgress.remove(assetName)
|
||||
android.widget.Toast.makeText(
|
||||
this, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu",
|
||||
android.widget.Toast.LENGTH_LONG,
|
||||
).show()
|
||||
refreshDrivers()
|
||||
}
|
||||
}, "download-turnip").start()
|
||||
}
|
||||
|
||||
private fun displayNameOf(uri: Uri): String? = if (uri.scheme == "file") uri.lastPathSegment else try {
|
||||
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
/** The two masks as the dialog shows them; an empty stored list shows as every core ticked. */
|
||||
private fun refreshCores() {
|
||||
clientOverride = SessionPrefs.clientCpusOverride(this)
|
||||
glThread = SessionPrefs.glThread(this)
|
||||
noGlError = SessionPrefs.noGlError(this)
|
||||
steamDeckMode = SessionPrefs.steamDeckMode(this)
|
||||
clientCores = CpuCores.parse(SessionPrefs.clientCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
||||
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
||||
tuSysmem = SessionPrefs.tuSysmem(this)
|
||||
zinkLazy = SessionPrefs.zinkLazy(this)
|
||||
noXalia = SessionPrefs.noXalia(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
// Android 12 kills the children an app forks itself once there are more than a handful.
|
||||
// A session is nothing but those, so where this is on the OS ends the session and no log
|
||||
// of ours says why. We cannot change a secure setting from here - only say so.
|
||||
phantomWarning = runCatching {
|
||||
android.provider.Settings.Global.getString(contentResolver, "settings_enable_monitor_phantom_procs")
|
||||
}.getOrNull().let { v ->
|
||||
when (v?.lowercase()) {
|
||||
"false", "0" -> null
|
||||
else -> "Android 12 and later kill the extra processes an app starts for itself once there are more than a few, and a session is made of dozens: proot, gamescope, the client and its helpers, Wine. Where that is left on, the client dies with nothing in its log, because nothing in the session did it. Some phones have a \"restrict child processes\" switch in Developer options - turn it off. Otherwise, over adb:\n\n adb shell settings put global settings_enable_monitor_phantom_procs false\n\nThis phone " + (if (v == null) "has not been set either way, so the ROM's default applies." else "currently reports it as on.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshProtons() {
|
||||
protonRows = ProtonExtras.tools.map { ProtonRow(it.id, it.name, ProtonExtras.installed(this, it), ProtonExtras.queued(this, it)) }
|
||||
}
|
||||
|
||||
private fun refresh() {
|
||||
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
||||
offlineAccount = OfflineMode.account(this)
|
||||
offline = OfflineMode.enabled(this)
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
ready = LinuxRuntime.isInstalled(this)
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
runningLabel = if (SessionState.running) when (SessionState.mode) {
|
||||
SessionService.MODE_DESKTOP -> "Desktop"
|
||||
SessionService.MODE_RUN -> SessionState.program?.substringAfterLast('/')?.substringBefore('.') ?: "Program"
|
||||
else -> "Steam"
|
||||
} else null
|
||||
// The libraries, off the main thread: manifests and a folder scan.
|
||||
Thread({
|
||||
val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
|
||||
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art -> Library.SteamGame(g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId) }
|
||||
} else emptyList()
|
||||
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
||||
ui.post { steamGames = games; emulatorList = emus }
|
||||
}, "library").start()
|
||||
}
|
||||
|
||||
private fun onRuntimeButton() {
|
||||
if (busy) return
|
||||
val release = available
|
||||
if (installed != null && release?.version == installed) {
|
||||
// Nothing to install: offer the one destructive thing this screen can do.
|
||||
showRemove = true
|
||||
return
|
||||
}
|
||||
if (release == null) {
|
||||
Thread({ checkCatalog() }, "catalog").start()
|
||||
return
|
||||
}
|
||||
// The runtime draws with Turnip, an Adreno driver: on Mali, Xclipse or PowerVR the
|
||||
// compositor gets no usable Vulkan device and a session is sound over a black screen.
|
||||
// Said before the download, not after it; the user may still go ahead.
|
||||
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()) { showNonAdreno = release; return }
|
||||
install(release)
|
||||
}
|
||||
|
||||
/** Starts a session; with no runtime on a non-Adreno, the same warning Setup gives comes first, before any download. */
|
||||
private fun startSession(intent: Intent) {
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
|
||||
if (warn && available != null) showNonAdreno = available
|
||||
else startActivity(intent)
|
||||
}
|
||||
|
||||
private fun install(release: LinuxRuntimeInstaller.Release) {
|
||||
busy = true
|
||||
failed = false
|
||||
stage = "Starting…"
|
||||
percent = -1
|
||||
Thread({
|
||||
val ok = LinuxRuntimeInstaller.install(this, release) { s, p ->
|
||||
ui.post { stage = s; percent = p }
|
||||
}
|
||||
ui.post {
|
||||
busy = false
|
||||
failed = !ok
|
||||
refresh()
|
||||
}
|
||||
}, "install").start()
|
||||
}
|
||||
|
||||
private fun checkCatalog() {
|
||||
val release = LinuxRuntimeInstaller.fetchRelease()
|
||||
Log.i(TAG, "catalog: " + (release?.version ?: "unreachable"))
|
||||
ui.post { if (release != null) available = release }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MainActivity"
|
||||
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
|
||||
private val ZIP_EXT = listOf("zip")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,980 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.hardware.input.InputManager
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.Display
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.LsfgNative
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.input.EvdevKeys
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.LoadingState
|
||||
import com.droiddeck.launcher.session.PerfHints
|
||||
import com.droiddeck.launcher.session.PerfHud
|
||||
import com.droiddeck.launcher.session.PerfMode
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.wayland.HdrSupport
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.ui.CursorOverlay
|
||||
import com.droiddeck.launcher.ui.DrawerActions
|
||||
import com.droiddeck.launcher.ui.HudText
|
||||
import com.droiddeck.launcher.ui.LoadingOverlay
|
||||
import com.droiddeck.launcher.ui.SessionDrawer
|
||||
import com.droiddeck.launcher.ui.SessionPausedOverlay
|
||||
import com.droiddeck.launcher.ui.SecondScreenPresentation
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.wayland.CompositorHost
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The session's screen: our Wayland compositor presenting onto this activity's Surface, and the
|
||||
* input that reaches it. The session itself - gamescope, the Steam client, audio - belongs to
|
||||
* [SessionService] and keeps running when this activity does not exist, which is what lets the
|
||||
* user leave Big Picture for another app and come back to it still signed in and still
|
||||
* downloading.
|
||||
*
|
||||
* Three layers: the SurfaceView the compositor draws into, the on-screen pad (a canvas View,
|
||||
* since it is input rather than a menu), and one Compose layer on top for everything else -
|
||||
* the HUD line, the loading overlay, the drawer and its dialogs.
|
||||
*/
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private lateinit var loading: LoadingState
|
||||
private lateinit var hud: PerfHud
|
||||
private var padBridge: PadBridge? = null
|
||||
private var onScreenControls: OnScreenControls? = null
|
||||
private var keyboard: KeyboardHost? = null
|
||||
private var watching = true
|
||||
private lateinit var gestures: PointerGestures
|
||||
private lateinit var touchpad: TouchpadGestures
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f))
|
||||
private var cursorVisible by mutableStateOf(false)
|
||||
private val cursorHide = Runnable { cursorVisible = false }
|
||||
private val uiHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
// Compose reads these; the activity writes them.
|
||||
private var drawerOpen by mutableStateOf(false)
|
||||
private var hudOn by mutableStateOf(true)
|
||||
private var frameGenLabel by mutableStateOf("Off")
|
||||
private var frameGenEngine by mutableStateOf(FrameGen.ENGINE_OFF)
|
||||
private var frameGenMultiplier by mutableStateOf(2)
|
||||
private var fexPreset by mutableStateOf("")
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
|
||||
private var secondScreenMode by mutableStateOf(SecondScreenMode.NONE)
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private var selectedSecondScreenDisplay by mutableStateOf(-1)
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private var secondScreenPresentation: SecondScreenPresentation? = null
|
||||
private val displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
|
||||
}
|
||||
private var isHomeApp by mutableStateOf(false)
|
||||
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
|
||||
|
||||
/**
|
||||
* Shows the on-screen pad when nothing is plugged in and takes it away the moment something
|
||||
* is - a user with a controller in their hands should not be looking at buttons they cannot
|
||||
* press, and a user without one must not be left with no way to answer Big Picture.
|
||||
*/
|
||||
private val deviceListener = object : InputManager.InputDeviceListener {
|
||||
override fun onInputDeviceAdded(deviceId: Int) = updateOnScreenControls()
|
||||
override fun onInputDeviceRemoved(deviceId: Int) = updateOnScreenControls()
|
||||
override fun onInputDeviceChanged(deviceId: Int) = updateOnScreenControls()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
// Game-tier power policy for the whole session: a sustained clock floor, the panel's
|
||||
// fastest mode, and the OS told it is in gameplay. Logged so a slow device says why.
|
||||
Log.i(TAG, "perf: " + PerfMode.apply(this))
|
||||
goFullscreen()
|
||||
// The device's volume keys change the stream the session plays on (the relay and
|
||||
// PulseAudio are media playback); they are never forwarded to the guest.
|
||||
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
refreshSecondScreenDisplays()
|
||||
|
||||
// No runtime is not a reason to leave: the loading screen installs it (installThenStart,
|
||||
// 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")
|
||||
|
||||
val root = FrameLayout(this)
|
||||
surfaceView = SurfaceView(this)
|
||||
surfaceView.holder.addCallback(this)
|
||||
root.addView(surfaceView)
|
||||
|
||||
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
|
||||
padBridge = bridge
|
||||
onScreenControls = OnScreenControls(this, bridge).also { root.addView(it) }
|
||||
keyboard = KeyboardHost(this).also { root.addView(it) }
|
||||
gestures = PointerGestures(PointerGestures.slop(this), pointerListener)
|
||||
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
|
||||
// One arrow, ours: Android draws a system pointer for a mouse over any window, and the
|
||||
// session already draws the pointer it is sent.
|
||||
val noCursor = android.view.PointerIcon.getSystemIcon(this, android.view.PointerIcon.TYPE_NULL)
|
||||
root.pointerIcon = noCursor
|
||||
surfaceView.pointerIcon = noCursor
|
||||
|
||||
loading = LoadingState(this)
|
||||
if (!SessionState.running) {
|
||||
val needRuntime = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
|
||||
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
|
||||
!com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this)
|
||||
if (needRuntime || needDesktop) installThenStart(needRuntime, needDesktop)
|
||||
}
|
||||
hud = PerfHud(this)
|
||||
hud.onPresentingWindowChanged = {
|
||||
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
|
||||
}
|
||||
// A session that has already drawn is past its milestones; do not cover its picture.
|
||||
if (SessionState.running && SessionState.firstFrameSeen) {
|
||||
loading.visible = false
|
||||
hud.start()
|
||||
}
|
||||
readPrefs()
|
||||
|
||||
// One Compose layer for every menu and overlay. Touches nothing in it consumes fall
|
||||
// through to the pad and the game underneath.
|
||||
root.addView(ComposeView(this).apply {
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density)
|
||||
if (hud.text.isNotEmpty()) HudText(hud.text)
|
||||
if (loading.visible) LoadingOverlay(loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended)
|
||||
SessionDrawer(drawerOpen, DrawerActions(
|
||||
steam = SessionState.mode == SessionService.MODE_STEAM,
|
||||
isHomeApp = isHomeApp,
|
||||
androidApps = androidApps,
|
||||
hudOn = hudOn,
|
||||
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
|
||||
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
|
||||
oscMode = oscMode, touchMode = touchMode,
|
||||
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
|
||||
shapeMode = shapeMode, fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
onFrameGenPick = { engine, multiplier ->
|
||||
FrameGen.set(this@SessionActivity, engine, multiplier)
|
||||
readPrefs()
|
||||
applyFrameGen()
|
||||
},
|
||||
onKeyboard = { drawerOpen = false; keyboard?.toggle() },
|
||||
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({
|
||||
drawerOpen = false
|
||||
padBridge?.triggerQam()
|
||||
}) else null,
|
||||
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
|
||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
|
||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||
onSecondScreenMode = ::selectSecondScreenMode,
|
||||
onSecondScreenDisplay = ::selectSecondScreenDisplay,
|
||||
onLaunchAndroidApp = { app ->
|
||||
drawerOpen = false
|
||||
try {
|
||||
HomeApp.launch(this@SessionActivity, app)
|
||||
} catch (_: Exception) {
|
||||
Toast.makeText(this@SessionActivity, "Could not open ${app.label}", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
},
|
||||
onBackground = { drawerOpen = false; moveTaskToBack(true) },
|
||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||
onClose = { drawerOpen = false },
|
||||
))
|
||||
if (SessionState.suspended) SessionPausedOverlay {
|
||||
SessionService.resume(this@SessionActivity)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
setContentView(root)
|
||||
handleHomeGuideIntent(intent)
|
||||
|
||||
updateOnScreenControls()
|
||||
WaylandCompositor.setFirstFrameListener {
|
||||
SessionState.firstFrameSeen = true
|
||||
runOnUiThread {
|
||||
loading.visible = false
|
||||
hud.start()
|
||||
}
|
||||
}
|
||||
SessionState.endListener = endListener
|
||||
// Back opens the drawer (and closes it again). Leaving the session running in the
|
||||
// background and ending it are both actions in there, so neither can happen by accident
|
||||
// from a button a game might also be reading.
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
drawerOpen = !drawerOpen
|
||||
}
|
||||
})
|
||||
watchSession()
|
||||
}
|
||||
|
||||
private fun refreshHomeApp() {
|
||||
isHomeApp = HomeApp.isDefault(this)
|
||||
androidApps = if (isHomeApp) HomeApp.launchableApps(this) else emptyList()
|
||||
}
|
||||
|
||||
private fun sendSteamGuide() {
|
||||
drawerOpen = false
|
||||
padBridge?.applyTouch { state -> state.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
|
||||
uiHandler.postDelayed({
|
||||
padBridge?.applyTouch { state -> state.press(com.droiddeck.launcher.input.PadState.GUIDE, false) }
|
||||
}, 90)
|
||||
}
|
||||
|
||||
private fun handleHomeGuideIntent(incoming: Intent?) {
|
||||
if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return
|
||||
incoming.action = null
|
||||
setIntent(incoming)
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
}
|
||||
|
||||
private fun readPrefs() {
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
frameGenEngine = FrameGen.engine(this)
|
||||
frameGenMultiplier = FrameGen.multiplier(this)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
shapeMode = SessionPrefs.shapeMode(this)
|
||||
}
|
||||
|
||||
// ── Compositor ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** True while the loading screen is installing the Linux runtime or the desktop; the session waits for it. */
|
||||
@Volatile private var installingRuntime = false
|
||||
|
||||
/**
|
||||
* First Play (or Desktop) on a fresh install: the runtime, and for the desktop its package,
|
||||
* are downloaded and unpacked here, on the loading screen's own line and bar, and the session
|
||||
* starts when they are in. Nothing else changes.
|
||||
*/
|
||||
private fun installThenStart(runtime: Boolean, desktop: Boolean) {
|
||||
installingRuntime = true
|
||||
loading.step = if (runtime) "downloading the Linux runtime" else "downloading the desktop"
|
||||
loading.percent = -1
|
||||
Thread({
|
||||
val problem = (if (runtime) installRuntime() else null) ?: (if (desktop) installDesktop() else null)
|
||||
uiHandler.post {
|
||||
installingRuntime = false
|
||||
if (problem != null) { loading.showEnded(problem); return@post }
|
||||
loading.percent = -1
|
||||
loading.step = "Starting the session…"
|
||||
// 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)
|
||||
}
|
||||
}, "runtime-install").start()
|
||||
}
|
||||
|
||||
/** Reports one package's download on the loading screen: "<what> · 332 of 791 MB", checking, unpacking. */
|
||||
private fun progressFor(what: String, mb: Long) = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { stage, p ->
|
||||
uiHandler.post {
|
||||
loading.percent = p
|
||||
loading.step = when {
|
||||
stage.startsWith("Downloading") -> if (p >= 0 && mb > 0) "downloading $what · ${p * mb / 100} of $mb MB" else "downloading $what"
|
||||
stage.startsWith("Verifying") -> "checking $what"
|
||||
else -> "unpacking $what"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Null when the runtime is in, else the loading screen's closing line. */
|
||||
private fun installRuntime(): String? {
|
||||
val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease()
|
||||
?: return "Could not reach the runtime catalog. Check the connection and press Play again."
|
||||
val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release,
|
||||
progressFor("the Linux runtime", release.size / 1_000_000))
|
||||
return if (ok) null else "The Linux runtime did not install. Check the connection and press Play again."
|
||||
}
|
||||
|
||||
/** Null when the desktop package is in, else the loading screen's closing line. */
|
||||
private fun installDesktop(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.step = "downloading the desktop" }
|
||||
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.fetch()?.firstOrNull { it.id == "desktop" }
|
||||
?: return "Could not reach the desktop catalog. Check the connection and press Desktop again."
|
||||
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
|
||||
progressFor("the desktop", entry.size / 1_000_000))
|
||||
return problem?.let { "The desktop did not install ($it). Check the connection and press Desktop again." }
|
||||
}
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
if (installingRuntime) return
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
// The compositor hands this keymap to wl_keyboard clients, which is how the guest reads
|
||||
// the evdev codes we inject.
|
||||
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
|
||||
|
||||
// Turnip, not the system Adreno driver: importing the dma-bufs gamescope commits needs
|
||||
// VK_EXT_image_drm_format_modifier, which the system driver does not implement.
|
||||
val turnip = TurnipDriver(this)
|
||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
||||
|
||||
// The output size belongs to the session, not to the Surface: gamescope's display is
|
||||
// sized once when the session starts and cannot change. A foldable recreates the Surface
|
||||
// on the other panel, and recomputing the size there told the compositor a 21:9 buffer
|
||||
// was 16:9 - the picture came back squashed sideways. While a session runs, keep its size.
|
||||
val size = if (SessionState.running) SessionState.outputSize else outputSize()
|
||||
SessionState.outputSize = size
|
||||
onScreenControls?.setPicture(drawnRect())
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz()
|
||||
// Letterbox, never stretch or crop: the output can be a different shape from the panel,
|
||||
// and a game's picture must keep its proportions with bars, not lose its edges.
|
||||
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, ALIGN_CENTER)
|
||||
// The session's folder, claimed here because the compositor starts before the service and
|
||||
// opens its log once. The compositor reads the path from its environment; setting it after
|
||||
// it has started changes nothing, which is why the service copies the file in at teardown.
|
||||
if (!SessionState.running) {
|
||||
val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log")
|
||||
WaylandCompositor.setSessionLogFile(waylandLog)
|
||||
try {
|
||||
android.system.Os.setenv("BL_WAYLAND_LOG", waylandLog.path, true)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
|
||||
}
|
||||
}
|
||||
// HDR10: the gate is decided once, when the compositor starts (it lives for the whole app
|
||||
// process), from the panel's own word and the mode's setting. Zero-copy presentation is
|
||||
// what puts an HDR frame on a display layer tagged BT2020_PQ, so it is turned on with it.
|
||||
if (!CompositorHost.isStarted) {
|
||||
val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
|
||||
val probe = HdrSupport.probe(this)
|
||||
WaylandCompositor.nativeSetHdrDisplay(
|
||||
probe.displayId, probe.name, probe.formats, probe.hdr10,
|
||||
probe.maxLuminance, probe.maxAverageLuminance, probe.minLuminance,
|
||||
probe.ratioAvailable, probe.ratio, Build.VERSION.SDK_INT,
|
||||
)
|
||||
val wanted = SessionPrefs.hdr(this, mode)
|
||||
val on = wanted && probe.reason == null
|
||||
SessionState.hdr = on
|
||||
if (on) {
|
||||
try { android.system.Os.setenv("BANNER_WAYLAND_HDR", "1", true) } catch (e: Exception) { Log.w(TAG, "BANNER_WAYLAND_HDR", e) }
|
||||
WaylandCompositor.nativeSetZeroCopy(true)
|
||||
}
|
||||
WaylandCompositor.nativeSetHdrRequest(
|
||||
if (on) WaylandCompositor.HDR_MODE_ON else WaylandCompositor.HDR_MODE_OFF,
|
||||
"$mode session settings" + (if (wanted && !on) " (refused: ${probe.reason})" else ""),
|
||||
on, on,
|
||||
)
|
||||
Log.i(TAG, "hdr: " + (if (on) "on" else if (wanted) "wanted but ${probe.reason}" else "off") + " · display ${probe.formats.ifEmpty { "SDR" }}")
|
||||
}
|
||||
CompositorHost.startOrAttach(
|
||||
holder.surface, runtimeDir.path,
|
||||
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
||||
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(),
|
||||
)
|
||||
// ADPF: the compositor thread's frame intervals go to the power HAL against the panel's
|
||||
// period, so a long frame raises CPU clocks now rather than after the load averages up.
|
||||
PerfHints.arm(this, refreshHz())
|
||||
// The service owns everything below the compositor. It is started whenever no session is
|
||||
// running - NOT only when the compositor was just started: the compositor lives for the
|
||||
// whole process, so the second Play after a session ended used to re-attach the Surface,
|
||||
// start nothing, and leave the loading panel counting up over a dead session.
|
||||
if (!SessionState.running) {
|
||||
CompositorHost.newSession()
|
||||
SessionService.start(
|
||||
this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM,
|
||||
intent.getStringExtra(SessionService.EXTRA_PROGRAM),
|
||||
intent.getStringExtra(SessionService.EXTRA_STEAM_UI),
|
||||
intent.getStringExtra(SessionService.EXTRA_STEAM_URL),
|
||||
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
|
||||
)
|
||||
}
|
||||
applyFrameGen()
|
||||
}
|
||||
|
||||
private var surfaceW = 0
|
||||
private var surfaceH = 0
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
|
||||
val resized = surfaceW != 0 && (width != surfaceW || height != surfaceH)
|
||||
surfaceW = width
|
||||
surfaceH = height
|
||||
// The on-screen controls follow the picture: into the bars beside or under it when there are any.
|
||||
onScreenControls?.setPicture(drawnRect())
|
||||
if (resized) {
|
||||
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
|
||||
CompositorHost.resize(holder.surface) { applyFrameGen() }
|
||||
}
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
surfaceW = 0
|
||||
surfaceH = 0
|
||||
CompositorHost.detach(holder.surface)
|
||||
}
|
||||
|
||||
/**
|
||||
* The size the session renders at. gamescope is told this and scales its output onto whatever
|
||||
* the panel is, so a 1440p phone can run the client at 1080p without the client knowing.
|
||||
*/
|
||||
private fun outputSize(): Pair<Int, Int> {
|
||||
// The panel, not the window: resources.displayMetrics is what is left after the system
|
||||
// bars and the cutout are taken out.
|
||||
val bounds = if (Build.VERSION.SDK_INT >= 30) {
|
||||
windowManager.maximumWindowMetrics.bounds
|
||||
} else {
|
||||
val metrics = android.util.DisplayMetrics()
|
||||
@Suppress("DEPRECATION")
|
||||
windowManager.defaultDisplay.getRealMetrics(metrics)
|
||||
android.graphics.Rect(0, 0, metrics.widthPixels, metrics.heightPixels)
|
||||
}
|
||||
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.
|
||||
// "Exactly this panel" 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)
|
||||
// A custom resolution is taken as given; the compositor fits it to the panel.
|
||||
SessionPrefs.customResolution(this, mode)?.let { return it }
|
||||
val cap = SessionPrefs.resolutionCap(this, mode)
|
||||
val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt()
|
||||
val width = (height * aspect).toInt()
|
||||
// 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())
|
||||
}
|
||||
|
||||
private fun refreshHz(): Float {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
|
||||
val hz = display?.refreshRate ?: 60f
|
||||
return if (hz > 1f) hz else 60f
|
||||
}
|
||||
|
||||
/**
|
||||
* The saved frame-generation setting, pushed to the compositor. Off the main thread: LSFG's
|
||||
* first use translates the shader chain out of Lossless.dll, which takes seconds.
|
||||
*/
|
||||
private fun applyFrameGen() {
|
||||
val hz = refreshHz()
|
||||
Thread({
|
||||
val problem = FrameGen.apply(this, hz)
|
||||
if (problem != null) runOnUiThread { Toast.makeText(this, problem, Toast.LENGTH_LONG).show() }
|
||||
}, "frame-gen").start()
|
||||
}
|
||||
|
||||
// ── Session state ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Keeps the loading overlay current from the session log, and its clock moving. */
|
||||
private fun watchSession() {
|
||||
val handler = Handler(Looper.getMainLooper())
|
||||
var ticks = 0
|
||||
val poll = object : Runnable {
|
||||
override fun run() {
|
||||
if (!watching) return
|
||||
if (loading.visible && !loading.ended) {
|
||||
if (!installingRuntime) loading.update(this@SessionActivity, SessionState.logFile)
|
||||
if (ticks++ % 2 == 0) loading.tick()
|
||||
}
|
||||
handler.postDelayed(this, 500)
|
||||
}
|
||||
}
|
||||
handler.post(poll)
|
||||
}
|
||||
|
||||
private fun onSessionEnded(status: Int) {
|
||||
closeSecondScreen(reset = true)
|
||||
if (status == 0) {
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
// A session the guest asked for (the desktop's Steam launchers) takes this one's
|
||||
// place: the compositor stays, a new activity attaches and starts the service.
|
||||
SessionState.relaunch?.let { next ->
|
||||
SessionState.relaunch = null
|
||||
startActivity(next)
|
||||
}
|
||||
finish()
|
||||
}
|
||||
return
|
||||
}
|
||||
// What the log says about why, read off the main thread (notifyEnded arrives on it).
|
||||
Thread({
|
||||
val hint = sessionEndHint(SessionState.logFile)
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
showEnded(status, hint)
|
||||
}
|
||||
}, "session-end-hint").start()
|
||||
}
|
||||
|
||||
private fun showEnded(status: Int, hint: String?) {
|
||||
run {
|
||||
if (status != 0) {
|
||||
loading.showEnded(
|
||||
"The session ended ($status)\n${SessionState.logFile?.path ?: "-"}" +
|
||||
(if (hint != null) "\n\n$hint" else "")
|
||||
)
|
||||
// A moment on screen, so a failure is readable rather than a flash of black;
|
||||
// longer when there is advice to read.
|
||||
Handler(Looper.getMainLooper()).postDelayed({ finish() }, if (hint != null) 9000 else 4000)
|
||||
} else {
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One line of advice for a failure the log identifies, or null. The one this recognises: the
|
||||
* ENOSYS storm - dozens of `socket(): Function not implemented` / `shared memfd open() failed`
|
||||
* lines - which is proot's seccomp acceleration failing an x86 helper (Steam's xalia under
|
||||
* FEX) on some devices (a Fold 5, twice). The switch that answers it is in Performance, and a
|
||||
* user who never opens the log would not know.
|
||||
*/
|
||||
private fun sessionEndHint(log: File?): String? {
|
||||
if (log == null || !log.isFile) return null
|
||||
return try {
|
||||
var enosys = 0
|
||||
// The tail is where a dying session says why; 512 KB covers the storm without reading a 1 GB log.
|
||||
val size = log.length()
|
||||
java.io.RandomAccessFile(log, "r").use { f ->
|
||||
val start = maxOf(0L, size - 512L * 1024)
|
||||
f.seek(start)
|
||||
val bytes = ByteArray((size - start).toInt())
|
||||
f.readFully(bytes)
|
||||
String(bytes, Charsets.ISO_8859_1).lineSequence().forEach { line ->
|
||||
if (line.contains("Function not implemented")) enosys++
|
||||
}
|
||||
}
|
||||
if (enosys >= 8) {
|
||||
"The log shows $enosys \"Function not implemented\" errors: proot's seccomp acceleration is failing a helper on this device. " +
|
||||
"Try Performance \u2192 \"Run proot without seccomp\" (or \"Skip Steam's xalia helper\") and start again."
|
||||
} else null
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
// ── Input ───────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
// The device's own volume keys belong to Android: forwarded to the guest as keys they
|
||||
// changed nothing anyone could hear (a Pocket FIT report, on the desktop).
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
|
||||
// A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the
|
||||
// activity, which opens the drawer.
|
||||
val fromPad = event.device != null && PadBridge.isFromController(event.device)
|
||||
if (CompositorHost.isStarted && event.keyCode != KeyEvent.KEYCODE_BACK && !fromPad) {
|
||||
val down = event.action == KeyEvent.ACTION_DOWN
|
||||
if (down || event.action == KeyEvent.ACTION_UP) {
|
||||
var evdev = EvdevKeys.fromKeyCode(event.keyCode)
|
||||
// What the key stands for, and the key it would sit on without Shift - non-zero
|
||||
// only for a character Shift puts there: every capital and the symbol row.
|
||||
val ch = event.unicodeChar
|
||||
val plain = if (ch > 0) EvdevKeys.unshiftedChar(ch) else 0
|
||||
// A soft keyboard's symbol keys are in neither the table nor a scan code, so they
|
||||
// reached the session as nothing at all - a sign-in took an address without its @.
|
||||
// Work back from the character instead: which key carries it.
|
||||
if (evdev <= 0 && ch > 0) {
|
||||
val code = EvdevKeys.fromKeyCode(EvdevKeys.keycodeForChar(if (plain != 0) plain else ch))
|
||||
if (code > 0) evdev = code
|
||||
}
|
||||
// The modifier has to be made here. A soft keyboard reports Shift in the event's
|
||||
// meta state and sends no Shift key of its own, so a capital arrives as a key this
|
||||
// side already knows and came out lowercase. A hardware keyboard sends its own
|
||||
// Shift, and a second one would release the modifier while the key is still held.
|
||||
val shiftEvdev = if (evdev > 0 && plain != 0 && event.deviceId <= 0) 42 else 0
|
||||
if (evdev <= 0 && event.scanCode > 0) evdev = event.scanCode
|
||||
if (evdev > 0) {
|
||||
if (down) {
|
||||
if (shiftEvdev != 0) WaylandCompositor.nativeSendKey(shiftEvdev, 1)
|
||||
WaylandCompositor.nativeSendKey(evdev, 1)
|
||||
} else {
|
||||
WaylandCompositor.nativeSendKey(evdev, 0)
|
||||
if (shiftEvdev != 0) WaylandCompositor.nativeSendKey(shiftEvdev, 0)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (padBridge?.onMotionEvent(event) == true) return true
|
||||
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
/**
|
||||
* The pointer. Touch goes through [PointerGestures] (tap, hold, drag, two-finger scroll); a
|
||||
* mouse arrives with real buttons and a wheel and is forwarded as it is. Every position is
|
||||
* mapped through the letterboxed rectangle into the compositor's fixed 1920x1080 pointer
|
||||
* space, and the arrow is drawn where the app last sent the pointer.
|
||||
*/
|
||||
private val pointerListener = object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) = movePointer(x, y)
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
movePointer(x, y)
|
||||
WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
|
||||
}
|
||||
override fun onWheel(steps: Int) { WaylandCompositor.nativeSendSceneInput(4, steps, 0) }
|
||||
override fun onLongPress() {
|
||||
@Suppress("DEPRECATION")
|
||||
(getSystemService(VIBRATOR_SERVICE) as? android.os.Vibrator)?.vibrate(15)
|
||||
}
|
||||
}
|
||||
|
||||
private fun movePointer(x: Float, y: Float) {
|
||||
val width = surfaceView.width.takeIf { it > 0 } ?: return
|
||||
val height = surfaceView.height.takeIf { it > 0 } ?: return
|
||||
val out = SessionState.outputSize
|
||||
val scale = minOf(width / out.first.toFloat(), height / out.second.toFloat())
|
||||
val drawnW = out.first * scale
|
||||
val drawnH = out.second * scale
|
||||
val left = (width - drawnW) / 2f
|
||||
val top = (height - drawnH) / 2f
|
||||
val px = ((x - left) / drawnW * 1920f).toInt().coerceIn(0, 1919)
|
||||
val py = ((y - top) / drawnH * 1080f).toInt().coerceIn(0, 1079)
|
||||
WaylandCompositor.nativeSendPointer(1, px, py)
|
||||
showCursor(x.coerceIn(left, left + drawnW), y.coerceIn(top, top + drawnH))
|
||||
}
|
||||
|
||||
/** The arrow stays on a desktop; in a Steam session it shows for a moment after each move. */
|
||||
private fun showCursor(x: Float, y: Float) {
|
||||
cursorPos = androidx.compose.ui.geometry.Offset(x, y)
|
||||
cursorVisible = true
|
||||
uiHandler.removeCallbacks(cursorHide)
|
||||
if (SessionState.mode == SessionService.MODE_STEAM && SessionState.steamUi != "desktop") uiHandler.postDelayed(cursorHide, 2500)
|
||||
}
|
||||
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
if (!::displayManager.isInitialized) return
|
||||
val primaryId = display?.displayId ?: windowManager.defaultDisplay.displayId
|
||||
val candidates = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
|
||||
.asSequence()
|
||||
.filter { it.isValid && it.displayId != primaryId && (it.flags and Display.FLAG_PRESENTATION) != 0 }
|
||||
.map { target ->
|
||||
val mode = target.mode
|
||||
SecondScreenDisplay(target.displayId, "${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}")
|
||||
}
|
||||
.toList()
|
||||
val oldIds = secondScreenDisplays.map { it.id }.toSet()
|
||||
secondScreenDisplays = candidates
|
||||
val newIds = candidates.map { it.id }.toSet()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) {
|
||||
closeSecondScreen(reset = true)
|
||||
return
|
||||
}
|
||||
if (selectedSecondScreenDisplay !in newIds) selectedSecondScreenDisplay = candidates.firstOrNull()?.id ?: -1
|
||||
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) closeSecondScreen(reset = true)
|
||||
}
|
||||
|
||||
private fun selectSecondScreenDisplay(displayId: Int) {
|
||||
if (secondScreenDisplays.none { it.id == displayId }) return
|
||||
selectedSecondScreenDisplay = displayId
|
||||
if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode)
|
||||
}
|
||||
|
||||
private fun selectSecondScreenMode(mode: SecondScreenMode) {
|
||||
if (mode == SecondScreenMode.NONE) {
|
||||
closeSecondScreen(reset = true)
|
||||
return
|
||||
}
|
||||
if (secondScreenDisplays.isEmpty()) {
|
||||
secondScreenMode = SecondScreenMode.NONE
|
||||
return
|
||||
}
|
||||
if (selectedSecondScreenDisplay !in secondScreenDisplays.map { it.id }) {
|
||||
selectedSecondScreenDisplay = secondScreenDisplays.first().id
|
||||
}
|
||||
showSecondScreen(mode)
|
||||
}
|
||||
|
||||
private fun showSecondScreen(mode: SecondScreenMode) {
|
||||
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
|
||||
closeSecondScreen(reset = true)
|
||||
refreshSecondScreenDisplays()
|
||||
return
|
||||
}
|
||||
var presentation = secondScreenPresentation
|
||||
if (presentation?.display?.displayId != target.displayId) {
|
||||
presentation?.closeControls()
|
||||
presentation = SecondScreenPresentation(
|
||||
this, target,
|
||||
sendPointer = ::moveSecondScreenPointer,
|
||||
sendButton = { button, pressed ->
|
||||
WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
|
||||
},
|
||||
sendWheel = { steps -> WaylandCompositor.nativeSendSceneInput(4, steps, 0) },
|
||||
onSteamMenu = {
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) {
|
||||
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, false) }
|
||||
}, 90)
|
||||
}
|
||||
},
|
||||
onQam = {
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
|
||||
},
|
||||
)
|
||||
secondScreenPresentation = presentation
|
||||
}
|
||||
try {
|
||||
if (!presentation.isShowing) presentation.show()
|
||||
presentation.showMode(mode)
|
||||
secondScreenMode = mode
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not show second-screen controls on ${target.name}", e)
|
||||
closeSecondScreen(reset = true)
|
||||
}
|
||||
}
|
||||
|
||||
private fun moveSecondScreenPointer(x: Float, y: Float, width: Float, height: Float) {
|
||||
if (width <= 0f || height <= 0f) return
|
||||
val nx = (x / width).coerceIn(0f, 1f)
|
||||
val ny = (y / height).coerceIn(0f, 1f)
|
||||
WaylandCompositor.nativeSendPointer(1, (nx * 1919f).toInt(), (ny * 1079f).toInt())
|
||||
drawnRect()?.let { rect ->
|
||||
showCursor(rect.left + nx * rect.width(), rect.top + ny * rect.height())
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeSecondScreen(reset: Boolean) {
|
||||
secondScreenPresentation?.closeControls()
|
||||
secondScreenPresentation = null
|
||||
if (reset) secondScreenMode = SecondScreenMode.NONE
|
||||
}
|
||||
|
||||
/** Touchpad on the desktop, direct in Steam, unless the drawer says otherwise. */
|
||||
private fun usingTouchpad(): Boolean = when (SessionPrefs.touchMode(this)) {
|
||||
SessionPrefs.TOUCH_PAD -> true
|
||||
SessionPrefs.TOUCH_DIRECT -> false
|
||||
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
|
||||
}
|
||||
|
||||
/** The picture's rectangle inside the view: where the pointer may go. */
|
||||
private fun drawnRect(): android.graphics.RectF? {
|
||||
val width = surfaceView.width.takeIf { it > 0 } ?: return null
|
||||
val height = surfaceView.height.takeIf { it > 0 } ?: return null
|
||||
val out = SessionState.outputSize
|
||||
val scale = minOf(width / out.first.toFloat(), height / out.second.toFloat())
|
||||
val drawnW = out.first * scale
|
||||
val drawnH = out.second * scale
|
||||
val left = (width - drawnW) / 2f
|
||||
val top = (height - drawnH) / 2f
|
||||
return android.graphics.RectF(left, top, left + drawnW, top + drawnH)
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event)
|
||||
if (usingTouchpad()) {
|
||||
val rect = drawnRect() ?: return false
|
||||
if (touchpad.bounds != rect) {
|
||||
val fresh = touchpad.bounds.width() <= 1f
|
||||
touchpad.bounds = rect
|
||||
if (fresh) touchpad.place(rect.centerX(), rect.centerY())
|
||||
}
|
||||
return touchpad.onTouch(event)
|
||||
}
|
||||
return gestures.onTouch(event)
|
||||
}
|
||||
|
||||
/** A mouse: hover moves, buttons press, the wheel scrolls. Android sends buttons as touch
|
||||
* actions and hover as generic motion, so both paths land here. */
|
||||
private fun onMouse(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_HOVER_MOVE, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_HOVER_ENTER ->
|
||||
movePointer(event.x, event.y)
|
||||
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
|
||||
movePointer(event.x, event.y)
|
||||
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. */
|
||||
private fun updateOnScreenControls() {
|
||||
val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc")
|
||||
.takeIf { it.isFile }
|
||||
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
|
||||
?: SessionPrefs.oscMode(this)
|
||||
val controls = onScreenControls ?: return
|
||||
val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM
|
||||
controls.setButtonsOnly(buttonsOnly)
|
||||
val show = when (forced) {
|
||||
SessionPrefs.OSC_ALWAYS -> true
|
||||
SessionPrefs.OSC_STEAM_QAM -> true
|
||||
SessionPrefs.OSC_NEVER -> false
|
||||
else -> !PadBridge.anyControllerConnected()
|
||||
}
|
||||
if (show == (controls.visibility == View.VISIBLE)) return
|
||||
if (!show) controls.releaseAll()
|
||||
controls.visibility = if (show) View.VISIBLE else View.GONE
|
||||
Log.i(TAG, "on-screen controls " + when {
|
||||
!show -> "hidden"
|
||||
buttonsOnly -> "Steam + QAM"
|
||||
else -> "full pad"
|
||||
})
|
||||
}
|
||||
|
||||
// ── Lifecycle ───────────────────────────────────────────────────────────────────────────
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
refreshSecondScreenDisplays()
|
||||
if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode)
|
||||
SessionService.setActivityVisible(this, true)
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
displayManager.unregisterDisplayListener(displayListener)
|
||||
closeSecondScreen(reset = true)
|
||||
SessionService.setActivityVisible(this, false)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: android.content.Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
if (intent.action == SessionService.ACTION_HOME_GUIDE) {
|
||||
handleHomeGuideIntent(intent)
|
||||
} else if (intent.action == SessionService.ACTION_RESUME) {
|
||||
intent.action = null
|
||||
SessionService.resume(this)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
refreshHomeApp()
|
||||
if (intent?.action == SessionService.ACTION_RESUME) {
|
||||
intent.action = null
|
||||
SessionService.resume(this)
|
||||
}
|
||||
(getSystemService(INPUT_SERVICE) as? InputManager)
|
||||
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
|
||||
updateOnScreenControls()
|
||||
readPrefs()
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
(getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener)
|
||||
// A button held when the app goes away would stay held in the ring for the whole session.
|
||||
onScreenControls?.releaseAll()
|
||||
keyboard?.takeIf { it.shown }?.hide()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) goFullscreen()
|
||||
}
|
||||
|
||||
private fun goFullscreen() {
|
||||
@Suppress("DEPRECATION")
|
||||
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
||||
or View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
window.attributes = window.attributes.apply {
|
||||
layoutInDisplayCutoutMode =
|
||||
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Ours, so a finishing activity never unhooks the one that replaced it. */
|
||||
private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) }
|
||||
|
||||
override fun onDestroy() {
|
||||
// Deliberately does NOT end the session: this activity can be destroyed while the user is
|
||||
// in another app, and the whole point of the service is that Steam survives that.
|
||||
watching = false
|
||||
closeSecondScreen(reset = true)
|
||||
if (::hud.isInitialized) hud.stop()
|
||||
padBridge?.stop()
|
||||
if (SessionState.endListener === endListener) SessionState.endListener = null
|
||||
WaylandCompositor.setFirstFrameListener(null)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
/** Leaving the session sinks its surface back down onto the front end. */
|
||||
override fun finish() {
|
||||
super.finish()
|
||||
overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionActivity"
|
||||
/** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */
|
||||
private const val SCALE_FIT = 1
|
||||
private const val ALIGN_CENTER = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.droiddeck.launcher.audio;
|
||||
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.core.SessionPart;
|
||||
import com.droiddeck.launcher.core.HostProcess;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* The DirectAudio relay helper, which owns Android's speaker and microphone on behalf of a Linux
|
||||
* session.
|
||||
*
|
||||
* <p>Nothing inside the session can open Android's audio itself. A game is a glibc process in a
|
||||
* rootfs that binds no {@code /system}, and a glibc process cannot call libaaudio at all; the
|
||||
* session is also never given a way to spawn a bionic helper of its own. So the helper runs out
|
||||
* here, under the app's own uid, and the driver inside Wine talks to it over a unix socket. The uid
|
||||
* matters for more than tidiness: Android checks the microphone permission against whoever opens
|
||||
* the stream, so a helper started any other way could play but never record.
|
||||
*
|
||||
* <p>It is executed from the app's native library directory because Android will not execute a
|
||||
* binary from anywhere else - the same reason the PulseAudio daemon ships as {@code
|
||||
* libpulseaudio.so} despite being a program rather than a library.
|
||||
*
|
||||
* <p>Started before the client, because the driver asks once whether a helper is there, when Wine
|
||||
* picks an audio driver, and reports itself unavailable if not. Ported from Bannerlator (GPL-3.0);
|
||||
* the helper binary is the one built by The412Banner/directaudio's relay workflow.
|
||||
*/
|
||||
public class DirectAudioRelayComponent extends SessionPart {
|
||||
private static final String TAG = "DirectAudioRelay";
|
||||
/** The helper, named as a library so Android will run it. */
|
||||
public static final String BINARY = "libdirectaudiorelay.so";
|
||||
|
||||
private final File socketPath;
|
||||
/** Shared with PulseAudioComponent: one audio.log per session, appended by both. */
|
||||
private File logFile;
|
||||
/** Null when the microphone was not asked for; the helper then opens no input stream. */
|
||||
private final File micFifoPath;
|
||||
private volatile int pid = -1;
|
||||
|
||||
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
|
||||
this.socketPath = socketPath;
|
||||
this.micFifoPath = micFifoPath;
|
||||
}
|
||||
|
||||
/** Send the helper's output to this file as well as logcat. Set before {@link #start()}. */
|
||||
public void setLogFile(File file) {
|
||||
this.logFile = file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
stop();
|
||||
File binary = new File(app().getApplicationInfo().nativeLibraryDir, BINARY);
|
||||
if (!binary.isFile()) {
|
||||
Log.w(TAG, "helper missing at " + binary + "; DirectAudio will report itself unavailable");
|
||||
return;
|
||||
}
|
||||
File parent = socketPath.getParentFile();
|
||||
if (parent != null) {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
parent.mkdirs();
|
||||
}
|
||||
// A socket left by a session that did not shut down cleanly is not a listener, and the
|
||||
// helper would fail to bind onto it.
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
socketPath.delete();
|
||||
|
||||
// PulseAudio's pipe module insists on creating the pipe itself and fails if one is already
|
||||
// there. The helper creates one too when the path is missing, and it starts a few
|
||||
// milliseconds after the daemon is exec'd - well before the daemon has read its config. So
|
||||
// left to itself the helper won its own race, the daemon's mkfifo failed with EEXIST, and
|
||||
// the microphone was lost while everything else came up. Wait for the daemon to make the
|
||||
// pipe before the helper runs; it appears within a second, and if it never does the helper
|
||||
// starts anyway and creates it, which is the right thing when the daemon is not involved.
|
||||
if (micFifoPath != null) {
|
||||
long deadline = System.currentTimeMillis() + 3000L;
|
||||
while (!micFifoPath.exists() && System.currentTimeMillis() < deadline) {
|
||||
try {
|
||||
Thread.sleep(50L);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
Log.i(TAG, micFifoPath.exists() ? "microphone pipe made by the daemon; starting helper"
|
||||
: "daemon did not make the microphone pipe in 3 s; helper will make it");
|
||||
}
|
||||
|
||||
StringBuilder command = new StringBuilder(binary.getAbsolutePath());
|
||||
command.append(" --socket ").append(socketPath.getAbsolutePath());
|
||||
// Diagnostics into the session's audio.log: every 1000 callbacks the device buffer,
|
||||
// Android's own xrun count and the ring's fill, plus every buffer change.
|
||||
command.append(" --log");
|
||||
if (micFifoPath != null) {
|
||||
// The helper creates the pipe if it is not there. PulseAudio is told the same path and
|
||||
// reads from the other end of it.
|
||||
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
|
||||
}
|
||||
ArrayList<String> env = new ArrayList<>();
|
||||
env.add("HOME=" + app().getFilesDir());
|
||||
java.io.PrintWriter out = null;
|
||||
if (logFile != null) {
|
||||
try {
|
||||
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
|
||||
out.println("== DirectAudio relay helper starting"
|
||||
+ (micFifoPath != null ? " with the microphone" : " (no microphone)"));
|
||||
out.flush();
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "could not open " + logFile, e);
|
||||
}
|
||||
}
|
||||
final java.io.PrintWriter log = out;
|
||||
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
|
||||
app().getFilesDir(), null,
|
||||
line -> {
|
||||
Log.i(TAG, line);
|
||||
if (log != null) synchronized (log) { log.println(line); log.flush(); }
|
||||
});
|
||||
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
|
||||
+ (micFifoPath != null ? " mic=" + micFifoPath : " (no microphone)"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (pid != -1) {
|
||||
// The helper exits on a signal and tears down its streams; there is nothing below it to
|
||||
// orphan, unlike the proot tree.
|
||||
Process.killProcess(pid);
|
||||
pid = -1;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int suspendPid() {
|
||||
return pid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package com.droiddeck.launcher.audio;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
import com.droiddeck.launcher.core.SessionPart;
|
||||
import com.droiddeck.launcher.core.HostProcess;
|
||||
import com.droiddeck.launcher.core.TarZst;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* PulseAudio 13.0 running in the app process, with Android's AAudio as its sink, so the guest's
|
||||
* libpulse clients (Steam and everything it launches) have a server to talk to. The socket lives
|
||||
* in the app's files directory and is bound into the session at its own path, so PULSE_SERVER
|
||||
* needs no translating.
|
||||
*/
|
||||
public class PulseAudioComponent extends SessionPart {
|
||||
private static final String TAG = "PulseAudio";
|
||||
/** Where the guest reaches the daemon; the session exports PULSE_SERVER=unix:<this>. */
|
||||
public static final String SOCKET_NAME = "PS0";
|
||||
/** Identifies the bundled pulseaudio.tzst; a change here re-unpacks it over what a device has. */
|
||||
private static final String BUNDLE_STAMP = "2026-09-23-pa13-suspend-r5";
|
||||
|
||||
private final File workingDir;
|
||||
/** Where the daemon's own output is kept for this session, or null for logcat only. */
|
||||
private File logFile;
|
||||
/**
|
||||
* A named pipe carrying microphone audio, or null for no microphone. The bundle ships
|
||||
* module-aaudio-sink but no matching source, and the daemon runs where Android permits
|
||||
* recording - so pointing module-pipe-source at a pipe the DirectAudio relay helper writes
|
||||
* turns that one stream into a source the client can see, named DirectAudioMic.
|
||||
*/
|
||||
private final String micFifoPath;
|
||||
/** The DirectAudio relay's socket when the client's output should go through it, else null. */
|
||||
private String relaySocketPath;
|
||||
private volatile int pid = -1;
|
||||
|
||||
public PulseAudioComponent(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
/** As above, with a microphone fed from {@code micFifoPath}; null for output only. */
|
||||
public PulseAudioComponent(Context context, String micFifoPath) {
|
||||
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
|
||||
this.micFifoPath = micFifoPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route the daemon's output through the DirectAudio relay at this socket instead of an AAudio
|
||||
* stream of its own. The relay owns the stream outside proot, with its adaptive buffer; the
|
||||
* daemon only fills a shared ring. Set before {@link #start()}; the relay may start later.
|
||||
*/
|
||||
public void setRelaySocket(String path) {
|
||||
this.relaySocketPath = path;
|
||||
}
|
||||
|
||||
/** CRC-32 of the bundled pulseaudio.tzst, or "?" if it cannot be read. About 600 KB; cheap. */
|
||||
private String bundleChecksum() {
|
||||
java.util.zip.CRC32 crc = new java.util.zip.CRC32();
|
||||
byte[] buf = new byte[64 * 1024];
|
||||
try (java.io.InputStream in = app().getAssets().open("pulseaudio.tzst")) {
|
||||
int n;
|
||||
while ((n = in.read(buf)) > 0) crc.update(buf, 0, n);
|
||||
} catch (java.io.IOException e) {
|
||||
return "?";
|
||||
}
|
||||
return Long.toHexString(crc.getValue());
|
||||
}
|
||||
|
||||
/** Send the daemon's output to this file as well as logcat. Set before {@link #start()}. */
|
||||
public void setLogFile(File file) {
|
||||
this.logFile = file;
|
||||
}
|
||||
|
||||
public File socket() {
|
||||
return new File(workingDir, SOCKET_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
stop();
|
||||
if (!workingDir.isDirectory()) {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
workingDir.mkdirs();
|
||||
FileUtils.chmod(workingDir, 0771);
|
||||
}
|
||||
// The loadable modules (module-aaudio-sink - the app's own, from tools/aaudio-sink - the
|
||||
// native protocol, the pipe modules) ride in the apk; the daemon and its libraries come from the native library directory, the one
|
||||
// place an app may execute a file from. The bundle is unpacked once per BUNDLE_STAMP, not
|
||||
// once ever: an installed app kept the modules it unpacked on its first run, so a bundle
|
||||
// fixed in a later build never reached the device - which is how a 17.0 glibc build of
|
||||
// module-pipe-source sat beside the 13.0 daemon, failed to dlopen, and the microphone
|
||||
// never appeared. The stamp carries a checksum of the bundle itself, so any change to it -
|
||||
// a rebuilt sink module included - re-unpacks, whether or not BUNDLE_STAMP was bumped.
|
||||
File modulesDir = new File(workingDir, "modules");
|
||||
File stamp = new File(modulesDir, ".bundle");
|
||||
String have = FileUtils.readString(stamp);
|
||||
String want = BUNDLE_STAMP + "-" + bundleChecksum();
|
||||
if (!new File(modulesDir, "arm64/module-aaudio-sink.so").isFile()
|
||||
|| !new File(workingDir, "pactl").isFile()
|
||||
|| have == null || !want.equals(have.trim())) {
|
||||
Log.i(TAG, "unpacking pulseaudio.tzst (" + want + "; had " + have + ")");
|
||||
FileUtils.delete(modulesDir);
|
||||
if (TarZst.extractAsset(app(), "pulseaudio.tzst", workingDir)) {
|
||||
FileUtils.writeString(stamp, want);
|
||||
} else {
|
||||
Log.e(TAG, "pulseaudio.tzst did not unpack");
|
||||
}
|
||||
}
|
||||
File pactl = new File(workingDir, "pactl");
|
||||
if (pactl.isFile()) FileUtils.chmod(pactl, 0771);
|
||||
copyFromLibraryDir();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
socket().delete();
|
||||
// module-pipe-source creates the pipe with mkfifo and fails outright if one is already
|
||||
// there - EEXIST, reported as "Unknown error 17" - and the module then does not load at
|
||||
// all, so the source never appears and the client reports no microphone. Ours lives in the
|
||||
// app's files directory and survives a session, so after the very first run the path would
|
||||
// always be occupied. Removed here, before the daemon reads this config: the daemon makes
|
||||
// it, and the relay helper starts afterwards and is content to find one already made.
|
||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
new File(micFifoPath).delete();
|
||||
}
|
||||
ArrayList<String> config = new ArrayList<>();
|
||||
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
|
||||
+ socket().getAbsolutePath() + "\"");
|
||||
// volume=1.0 is not optional: with no volume argument module-aaudio-sink defaults
|
||||
// the sink to 0% and the session plays silence.
|
||||
// The sink's name is what the client's Audio settings show as the output device, so it
|
||||
// says which road the sound takes.
|
||||
if (relaySocketPath != null && !relaySocketPath.isEmpty()) {
|
||||
config.add("load-module module-directaudio-sink sink_name=DirectAudio socket=\"" + relaySocketPath + "\" performance_mode=1 adaptive=1 volume=1.0");
|
||||
config.add("set-default-sink DirectAudio");
|
||||
} else {
|
||||
// The classic sink: the adaptive AAudio module 0.1.5 shipped, unchanged.
|
||||
config.add("load-module module-aaudio-classic-sink sink_name=AAudioSink performance_mode=1 adaptive=1 volume=1.0");
|
||||
config.add("set-default-sink AAudioSink");
|
||||
}
|
||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||
// The format is the helper's, fixed at s16le/48000/mono: it resamples when the device
|
||||
// grants another input rate, so the daemon is never told a rate the bytes are not.
|
||||
// A pipe has no clock, so nothing here corrects drift - acceptable for voice.
|
||||
config.add("load-module module-pipe-source source_name=DirectAudioMic file=\""
|
||||
+ micFifoPath + "\" format=s16le rate=48000 channels=1");
|
||||
config.add("set-default-source DirectAudioMic");
|
||||
}
|
||||
FileUtils.writeString(new File(workingDir, "default.pa"), String.join("\n", config));
|
||||
|
||||
File modules = new File(workingDir, "modules/arm64");
|
||||
ArrayList<String> env = new ArrayList<>();
|
||||
env.add("LD_LIBRARY_PATH=/system/lib64:" + modules + ":" + workingDir.getAbsolutePath());
|
||||
env.add("HOME=" + workingDir);
|
||||
env.add("TMPDIR=" + workingDir);
|
||||
|
||||
String command = workingDir.getAbsolutePath() + "/libpulseaudio.so"
|
||||
+ " --system=false --disable-shm=true --fail=false"
|
||||
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
|
||||
// Info level: the classic sink reports the stream Android granted (burst, capacity,
|
||||
// starting buffer) only there, and that is what a stutter report needs.
|
||||
+ " --log-level=info";
|
||||
// A module that refuses to load, a pipe that could not be made, the daemon exiting at
|
||||
// startup: all of it used to reach logcat and nothing else, so a user's folder said nothing
|
||||
// at all about sound. Four separate faults hid behind "no input device" in one night.
|
||||
final java.io.PrintWriter out = openLog();
|
||||
pid = HostProcess.start(command, env.toArray(new String[0]), workingDir, null,
|
||||
line -> {
|
||||
Log.i(TAG, line);
|
||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (pid != -1) {
|
||||
Process.killProcess(pid);
|
||||
pid = -1;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean setSinkSuspended(boolean suspended) {
|
||||
File pactl = new File(workingDir, "pactl");
|
||||
if (!pactl.isFile() || pid <= 1) {
|
||||
Log.w(TAG, "cannot change sink state: PulseAudio control client or server unavailable");
|
||||
return false;
|
||||
}
|
||||
java.lang.Process process = null;
|
||||
try {
|
||||
File modules = new File(workingDir, "modules/arm64");
|
||||
ProcessBuilder builder = new ProcessBuilder(
|
||||
pactl.getAbsolutePath(), "suspend-sink", "@DEFAULT_SINK@", Boolean.toString(suspended));
|
||||
builder.directory(workingDir);
|
||||
builder.redirectErrorStream(true);
|
||||
builder.redirectOutput(new File("/dev/null"));
|
||||
builder.environment().put("LD_LIBRARY_PATH", "/system/lib64:" + modules + ":" + workingDir);
|
||||
builder.environment().put("HOME", workingDir.getAbsolutePath());
|
||||
builder.environment().put("TMPDIR", workingDir.getAbsolutePath());
|
||||
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
|
||||
process = builder.start();
|
||||
if (!process.waitFor(5, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
Log.w(TAG, "timed out changing sink state to suspended=" + suspended);
|
||||
return false;
|
||||
}
|
||||
int status = process.exitValue();
|
||||
if (status != 0) Log.w(TAG, "sink state change failed with exit " + status);
|
||||
return status == 0;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
Log.w(TAG, "interrupted changing sink state", e);
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "could not change sink state", e);
|
||||
return false;
|
||||
} finally {
|
||||
if (process != null && process.isAlive()) process.destroyForcibly();
|
||||
}
|
||||
}
|
||||
|
||||
/** The session's audio log, appended to by both the daemon and the relay helper. */
|
||||
private java.io.PrintWriter openLog() {
|
||||
if (logFile == null) return null;
|
||||
try {
|
||||
java.io.PrintWriter w = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
|
||||
w.println("== PulseAudio daemon starting" + (micFifoPath != null ? " with a microphone source" : ""));
|
||||
w.flush();
|
||||
return w;
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "could not open " + logFile, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void copyFromLibraryDir() {
|
||||
String[] libs = {"libltdl.so", "libpulseaudio.so", "libpulse.so",
|
||||
"libpulsecommon-13.0.so", "libpulsecore-13.0.so", "libsndfile.so", "libffi.so"};
|
||||
ClassLoader loader = PulseAudioComponent.class.getClassLoader();
|
||||
for (String lib : libs) {
|
||||
URL resource = loader != null ? loader.getResource("lib/arm64-v8a/" + lib) : null;
|
||||
if (resource == null) {
|
||||
Log.w(TAG, lib + " missing from the apk");
|
||||
continue;
|
||||
}
|
||||
File destination = new File(workingDir, lib);
|
||||
try (InputStream in = resource.openStream()) {
|
||||
Files.copy(in, destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
FileUtils.chmod(destination, 0771);
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "copy " + lib, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The device's cores as taskset names them, for the two masks a Steam session can carry.
|
||||
*
|
||||
* A list is stored the way taskset's `-c` takes it - comma-separated core numbers - so what the
|
||||
* dialog produces is what the session script and the Proton wrappers consume unchanged.
|
||||
*/
|
||||
object CpuCores {
|
||||
/** Core numbers present on this device, in order. */
|
||||
val all: List<Int> by lazy { (0 until Runtime.getRuntime().availableProcessors()).toList() }
|
||||
|
||||
/** The core's ceiling in GHz for the dialog's labels, or null where the kernel hides it. */
|
||||
fun maxGhz(core: Int): Double? =
|
||||
FileUtils.readString(File("/sys/devices/system/cpu/cpu$core/cpufreq/cpuinfo_max_freq"))
|
||||
?.trim()?.toLongOrNull()?.let { it / 1_000_000.0 }
|
||||
|
||||
fun parse(list: String): Set<Int> =
|
||||
list.split(',').mapNotNull { it.trim().toIntOrNull() }.filter { it in all }.toSet()
|
||||
|
||||
fun format(cores: Set<Int>): String = cores.sorted().joinToString(",")
|
||||
|
||||
/** The stored list, or every core when nothing (or nothing valid) is stored. */
|
||||
fun listOrAll(list: String): String {
|
||||
val cores = parse(list)
|
||||
return format(if (cores.isEmpty()) all.toSet() else cores)
|
||||
}
|
||||
|
||||
/**
|
||||
* The list only when it is a real restriction, else "". Empty, absent, or naming every core
|
||||
* all mean "no preference": pinning a process to all cores is what the scheduler does
|
||||
* unaided, and passing it would only put a meaningless line in the session log. Bannerlator's
|
||||
* rule, kept for the game mask.
|
||||
*/
|
||||
fun restrictionOrEmpty(list: String): String {
|
||||
val cores = parse(list)
|
||||
return if (cores.isEmpty() || cores.size >= all.size) "" else format(cores)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* `device.txt`: what this device is and what the session was told to do, written the moment a
|
||||
* session starts so a log can be read months later without asking the reporter a single question.
|
||||
*
|
||||
* **Nothing identifying goes in here.** No serial number, no Android ID, no IMEI, no account name,
|
||||
* no network names - only what the hardware is, what the ROM is, and which of our own settings
|
||||
* were in effect. The one thing that comes close is the build fingerprint, which names the ROM and
|
||||
* its build date and is the same string on every unit of that model.
|
||||
*/
|
||||
object DeviceReport {
|
||||
private const val TAG = "DeviceReport"
|
||||
|
||||
fun write(context: Context, target: File, mode: String) {
|
||||
try {
|
||||
target.writeText(build(context, mode))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not write $target", e)
|
||||
}
|
||||
}
|
||||
|
||||
fun build(context: Context, mode: String): String {
|
||||
val b = StringBuilder()
|
||||
fun h(title: String) {
|
||||
b.append('\n').append(title).append('\n').append("-".repeat(title.length)).append('\n')
|
||||
}
|
||||
fun k(key: String, value: Any?) {
|
||||
b.append(key.padEnd(24)).append(value ?: "unknown").append('\n')
|
||||
}
|
||||
|
||||
b.append("DroidDeck session report\n")
|
||||
b.append("========================\n")
|
||||
k("Written", SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.US).format(Date()))
|
||||
k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (labwc/LXQt)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" })
|
||||
|
||||
h("App")
|
||||
runCatching {
|
||||
val info = context.packageManager.getPackageInfo(context.packageName, 0)
|
||||
k("Version", "${info.versionName} (${info.longVersionCode})")
|
||||
}
|
||||
k("Package", context.packageName)
|
||||
k("targetSdk", context.applicationInfo.targetSdkVersion)
|
||||
k("Native lib dir", context.applicationInfo.nativeLibraryDir)
|
||||
|
||||
h("Device")
|
||||
k("Model", "${Build.MANUFACTURER} ${Build.MODEL}")
|
||||
k("Device / product", "${Build.DEVICE} / ${Build.PRODUCT}")
|
||||
k("Board / hardware", "${Build.BOARD} / ${Build.HARDWARE}")
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
k("SoC", "${Build.SOC_MANUFACTURER} ${Build.SOC_MODEL}")
|
||||
}
|
||||
k("Android", "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
|
||||
k("Security patch", Build.VERSION.SECURITY_PATCH)
|
||||
k("Build", Build.DISPLAY)
|
||||
k("Fingerprint", Build.FINGERPRINT)
|
||||
k("Kernel", System.getProperty("os.version"))
|
||||
k("ABIs", Build.SUPPORTED_ABIS.joinToString(", "))
|
||||
|
||||
h("CPU and memory")
|
||||
k("Cores", CpuCores.all.size)
|
||||
b.append("Core ceilings ")
|
||||
b.append(CpuCores.all.joinToString(", ") { c ->
|
||||
"cpu$c " + (CpuCores.maxGhz(c)?.let { String.format(Locale.US, "%.2f GHz", it) } ?: "?")
|
||||
})
|
||||
b.append('\n')
|
||||
runCatching {
|
||||
val mi = ActivityManager.MemoryInfo()
|
||||
(context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(mi)
|
||||
k("RAM total", FileUtils.sizeToString(mi.totalMem))
|
||||
k("RAM available", FileUtils.sizeToString(mi.availMem))
|
||||
}
|
||||
runCatching {
|
||||
val fs = StatFs(context.filesDir.path)
|
||||
k("App storage free", FileUtils.sizeToString(fs.availableBlocksLong * fs.blockSizeLong))
|
||||
}
|
||||
runCatching {
|
||||
val fs = StatFs(Environment.getExternalStorageDirectory().path)
|
||||
k("Shared storage free", FileUtils.sizeToString(fs.availableBlocksLong * fs.blockSizeLong))
|
||||
}
|
||||
|
||||
h("GPU")
|
||||
k("KGSL gpu_model", readSys("/sys/class/kgsl/kgsl-3d0/gpu_model"))
|
||||
k("KGSL chip id", readSys("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))
|
||||
k("System Vulkan ICD", if (File("/vendor/lib64/hw/vulkan.adreno.so").exists()) "/vendor/lib64/hw/vulkan.adreno.so" else "not at the usual path")
|
||||
|
||||
h("Display")
|
||||
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
|
||||
k("Session refresh", String.format(Locale.US, "%.2f Hz", SessionState.refreshHz))
|
||||
k("Shape setting", SessionPrefs.shapeMode(context))
|
||||
k("Custom resolution (Steam)", SessionPrefs.customResolution(context, SessionService.MODE_STEAM)?.let { "${it.first}x${it.second}" } ?: "off")
|
||||
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"))
|
||||
|
||||
h("Drivers")
|
||||
val turnip = TurnipDriver(context)
|
||||
val androidChoice = SessionPrefs.androidDriver(context)
|
||||
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice)
|
||||
k(" name / version", "${turnip.displayName(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)} ${turnip.driverVersion(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)}".trim())
|
||||
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
|
||||
val lm = LinuxVulkanDriverManager(context)
|
||||
for (m in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
|
||||
val id = SessionPrefs.linuxDriver(context, m)
|
||||
val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
|
||||
else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() +
|
||||
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
|
||||
if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]"
|
||||
k("Linux driver ($m)", label)
|
||||
}
|
||||
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
|
||||
|
||||
h("Runtime")
|
||||
k("Installed version", LinuxRuntimeInstaller.installedVersion(context))
|
||||
k("Runtime ready", LinuxRuntime.isInstalled(context))
|
||||
k("Desktop installed", DesktopCatalog.desktopInstalled(context))
|
||||
k("Runtime root", LinuxRuntime.rootDir(context).path)
|
||||
|
||||
h("Settings in effect")
|
||||
k("Client core override", SessionPrefs.clientCpusOverride(context))
|
||||
k(" client cores", CpuCores.listOrAll(SessionPrefs.clientCpus(context)))
|
||||
k(" game cores", CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(context)).ifEmpty { "every core (nothing sent)" })
|
||||
k("Turnip sysmem", SessionPrefs.tuSysmem(context))
|
||||
k("Zink lazy descriptors", SessionPrefs.zinkLazy(context))
|
||||
k("Threaded GL (glthread)", SessionPrefs.glThread(context))
|
||||
k("No GL error checks", SessionPrefs.noGlError(context))
|
||||
k("Steam Deck mode", SessionPrefs.steamDeckMode(context))
|
||||
k("FEX preset", SessionPrefs.fexPreset(context).ifEmpty { "FEX defaults" })
|
||||
k("Skip xalia", SessionPrefs.noXalia(context))
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic")
|
||||
k("Microphone", SessionPrefs.micEnabled(context))
|
||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||
k("Touch mode", SessionPrefs.touchMode(context))
|
||||
k("Performance HUD", SessionPrefs.hudEnabled(context))
|
||||
k("Game storage", when (val g = SessionPrefs.gameStorage(context)) {
|
||||
"" -> "automatic (" + (com.droiddeck.launcher.session.GameStorage.effective(context)?.path ?: "no card present") + ")"
|
||||
SessionPrefs.GAME_STORAGE_OFF -> "internal only"
|
||||
else -> g
|
||||
})
|
||||
|
||||
h("Android process limits")
|
||||
// Android 12 kills "phantom" processes - the children an app forks itself rather than
|
||||
// starting through the framework - once there are more than a handful of them. A session is
|
||||
// nothing but those: proot, gamescope, Xwayland, the client, its helpers, Wine, FEX. Where
|
||||
// this is left on, the OS kills the session and nothing in our logs says why, because
|
||||
// nothing in the session did it. Some ROMs expose it in Developer options as a
|
||||
// "restrict child processes" switch; otherwise it is
|
||||
// adb shell settings put global settings_enable_monitor_phantom_procs false
|
||||
val phantom = runCatching {
|
||||
Settings.Global.getString(context.contentResolver, "settings_enable_monitor_phantom_procs")
|
||||
}.getOrNull()
|
||||
k("Phantom proc monitor", when (phantom?.lowercase()) {
|
||||
"false", "0" -> "disabled (good - the OS will not kill the session's children)"
|
||||
null, "" -> "not set (ROM default, usually ENABLED - see the note below)"
|
||||
else -> "ENABLED (the OS may kill the session with no log; turn off \"restrict child processes\")"
|
||||
})
|
||||
|
||||
h("Device switch files in Download")
|
||||
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
|
||||
"droiddeck-osc", "droiddeck-no-pad", "droiddeck-pad-log",
|
||||
"droiddeck-no-hud", "droiddeck-wlr-renderer")) {
|
||||
val f = File(Environment.getExternalStorageDirectory(), "Download/$name")
|
||||
if (f.isFile) k(name, FileUtils.readString(f)?.trim()?.replace('\n', ' ')?.ifEmpty { "(present, empty)" } ?: "(present)")
|
||||
}
|
||||
|
||||
b.append("\nNothing identifying is collected here: no serial number, no device or advertising\n")
|
||||
b.append("id, no account name, no network names. Safe to attach to a bug report as it is.\n")
|
||||
return b.toString()
|
||||
}
|
||||
|
||||
private fun readSys(path: String): String? = FileUtils.readString(File(path))?.trim()?.ifEmpty { null }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.os.Build
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Whether this device can draw a Linux session at all.
|
||||
*
|
||||
* The runtime draws with Turnip, an Adreno driver. On Mali, Xclipse and PowerVR the compositor
|
||||
* gets no usable Vulkan device and a session comes up as sound over a black screen - a failure
|
||||
* with nothing in it to read. The app cannot fix that, so it says so before the download rather
|
||||
* than after it. Adreno is recognised by what only Qualcomm's stack has: the KGSL node, or the
|
||||
* vendor's own Vulkan driver at its usual path.
|
||||
*/
|
||||
object DeviceSupport {
|
||||
fun adreno(): Boolean =
|
||||
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. */
|
||||
fun gpuName(): String {
|
||||
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 { "this GPU" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.droiddeck.launcher.core;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* The two fetches this app makes: the runtime catalog (a few hundred bytes of JSON) and the
|
||||
* runtime tarball itself (~790 MB). Plain HttpURLConnection - nothing here needs a client library,
|
||||
* and one fewer dependency is one fewer thing that can fail a release build.
|
||||
*/
|
||||
public final class Downloader {
|
||||
private static final String TAG = "Downloader";
|
||||
private static final int TIMEOUT_MS = 30_000;
|
||||
|
||||
private Downloader() {}
|
||||
|
||||
public static String downloadString(String url) {
|
||||
HttpURLConnection connection = null;
|
||||
try {
|
||||
connection = open(url);
|
||||
if (connection.getResponseCode() / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + connection.getResponseCode());
|
||||
return null;
|
||||
}
|
||||
try (InputStream in = connection.getInputStream();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
FileUtils.copy(in, out);
|
||||
return new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "GET " + url, e);
|
||||
return null;
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads to {@code destination}, reporting a 0..1 fraction (or -1 when the server sends no
|
||||
* length). {@code resume} continues a partial file with a Range request, which is what makes a
|
||||
* 790 MB download survive a dropped connection instead of starting over.
|
||||
*/
|
||||
public static boolean downloadFile(String url, File destination, boolean resume,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
HttpURLConnection connection = null;
|
||||
long have = resume && destination.isFile() ? destination.length() : 0;
|
||||
try {
|
||||
connection = open(url);
|
||||
if (have > 0) connection.setRequestProperty("Range", "bytes=" + have + "-");
|
||||
int code = connection.getResponseCode();
|
||||
boolean appending = code == HttpURLConnection.HTTP_PARTIAL;
|
||||
if (code / 100 != 2) {
|
||||
// The server ignored or refused the range: start the file again.
|
||||
if (have > 0) {
|
||||
connection.disconnect();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
destination.delete();
|
||||
return downloadFile(url, destination, false, progress);
|
||||
}
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
return false;
|
||||
}
|
||||
if (!appending) have = 0;
|
||||
long length = connection.getContentLengthLong();
|
||||
long total = length < 0 ? -1 : length + have;
|
||||
File parent = destination.getParentFile();
|
||||
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
|
||||
parent.mkdirs();
|
||||
long written = have;
|
||||
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
|
||||
OutputStream out = new FileOutputStream(destination, appending)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
long lastReport = 0;
|
||||
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
|
||||
out.write(buffer, 0, read);
|
||||
written += read;
|
||||
// A callback per 64 KB would be tens of thousands of UI hops; once per MB is
|
||||
// enough to move a progress bar smoothly.
|
||||
if (progress != null && written - lastReport > (1 << 20)) {
|
||||
lastReport = written;
|
||||
progress.accept(total > 0 ? written / (float) total : -1f);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (progress != null) progress.accept(1f);
|
||||
return total <= 0 || written >= total;
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "download " + url, e);
|
||||
return false;
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpURLConnection open(String url) throws java.io.IOException {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setConnectTimeout(TIMEOUT_MS);
|
||||
connection.setReadTimeout(TIMEOUT_MS);
|
||||
connection.setInstanceFollowRedirects(true);
|
||||
connection.setRequestProperty("User-Agent", "DroidDeck-Android");
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
/**
|
||||
* FEXCore presets for the x86 games the Steam client launches, Bannerlator's table carried over
|
||||
* so a preset means the same thing in both apps. Each is a set of FEX_* variables put into the
|
||||
* session's environment; the games under FEX inherit them from the client. The default is FEX's
|
||||
* own defaults - no variables at all - which is what every session has run on so far.
|
||||
*
|
||||
* TSO = x86's total store ordering emulated on ARM: safest, slowest. MULTIBLOCK compiles more per
|
||||
* block. X87REDUCEDPRECISION trades x87 exactness for speed. SMCCHECKS=none is the risky one -
|
||||
* anything that writes its own code at runtime (JIT, .NET, DRM) can misbehave. DENUVO keeps the
|
||||
* checks at full and hides the hypervisor bit, which its anti-tamper looks for.
|
||||
*/
|
||||
object FexPreset {
|
||||
class Preset(val id: String, val label: String, val detail: String, val env: List<String>)
|
||||
|
||||
private fun tso(main: Int, vector: Int, memcpy: Int, halfBarrier: Int) = listOf(
|
||||
"FEX_TSOENABLED=$main", "FEX_VECTORTSOENABLED=$vector", "FEX_MEMCPYSETTSOENABLED=$memcpy", "FEX_HALFBARRIERTSOENABLED=$halfBarrier",
|
||||
)
|
||||
|
||||
val all: List<Preset> = listOf(
|
||||
Preset("", "FEX defaults", "Uses FEX defaults.", emptyList()),
|
||||
Preset("STABILITY", "Stability", "Safest, slowest settings.", tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=0")),
|
||||
Preset("COMPATIBILITY", "Compatibility", "Full TSO with multiblock.", tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=1")),
|
||||
Preset("INTERMEDIATE", "Intermediate", "Balanced TSO with reduced x87 precision.", tso(1, 0, 0, 1) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
|
||||
Preset("PERFORMANCE", "Performance", "All TSO disabled; multiblock.", tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
|
||||
Preset("PERFORMANCE_TSO", "Performance + TSO", "Performance settings with main TSO enabled.", tso(1, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
|
||||
Preset("EXTREME", "Extreme", "Disables self-modifying-code checks. JIT games and DRM may break.",
|
||||
tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=none", "FEX_DISABLEL2CACHE=1", "FEX_DYNAMICL1CACHE=1", "FEX_DYNAMICL1CACHEINCREASECOUNTHEURISTIC=250", "FEX_DYNAMICL1CACHEDECREASECOUNTHEURISTIC=50")),
|
||||
Preset("EXTREME_TSO", "Extreme + TSO", "Extreme settings with main TSO enabled.",
|
||||
tso(1, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=none", "FEX_DISABLEL2CACHE=1", "FEX_DYNAMICL1CACHE=1", "FEX_DYNAMICL1CACHEINCREASECOUNTHEURISTIC=250", "FEX_DYNAMICL1CACHEDECREASECOUNTHEURISTIC=50")),
|
||||
Preset("EXTREME_GN", "Extreme-gn", "Performance with TSC and metadata hints. Try before Extreme.",
|
||||
tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMALLTSCSCALE=1", "FEX_VOLATILEMETADATA=1")),
|
||||
Preset("DENUVO", "Denuvo", "Performance with full code checks and the hypervisor bit hidden.",
|
||||
tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=full", "FEX_HIDEHYPERVISORBIT=1")),
|
||||
)
|
||||
|
||||
fun byId(id: String): Preset = all.firstOrNull { it.id == id } ?: all[0]
|
||||
|
||||
/** The variables for the session's environment, in KEY=VALUE form; empty for the default. */
|
||||
fun env(id: String): List<String> = byId(id).env
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.core;
|
||||
|
||||
import android.content.Context;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
|
||||
public final class FileUtils {
|
||||
private static final String TAG = "FileUtils";
|
||||
|
||||
private FileUtils() {}
|
||||
|
||||
/** Recursive delete that does not follow symlinks - a rootfs is full of them. */
|
||||
public static void delete(File file) {
|
||||
if (file == null || !file.exists() && !isSymlink(file)) return;
|
||||
if (file.isDirectory() && !isSymlink(file)) {
|
||||
File[] children = file.listFiles();
|
||||
if (children != null) for (File child : children) delete(child);
|
||||
}
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
file.delete();
|
||||
}
|
||||
|
||||
private static boolean isSymlink(File file) {
|
||||
try {
|
||||
return Files.isSymbolicLink(file.toPath());
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Empties a directory without removing it. */
|
||||
public static void clear(File dir) {
|
||||
if (dir == null || !dir.isDirectory()) return;
|
||||
File[] children = dir.listFiles();
|
||||
if (children != null) for (File child : children) delete(child);
|
||||
}
|
||||
|
||||
public static boolean writeString(File file, String content) {
|
||||
try {
|
||||
File parent = file.getParentFile();
|
||||
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
|
||||
parent.mkdirs();
|
||||
Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8));
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
Log.w(TAG, "write " + file, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String readString(File file) {
|
||||
try {
|
||||
return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void symlink(String target, String linkPath) {
|
||||
try {
|
||||
Os.symlink(target, linkPath);
|
||||
} catch (ErrnoException e) {
|
||||
Log.w(TAG, "symlink " + linkPath + " -> " + target + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void chmod(File file, int mode) {
|
||||
try {
|
||||
Os.chmod(file.getAbsolutePath(), mode);
|
||||
} catch (ErrnoException e) {
|
||||
Log.w(TAG, "chmod " + file + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Copies an asset out of the apk, creating the parent directory. */
|
||||
public static boolean copyAsset(Context context, String assetPath, File destination) {
|
||||
File parent = destination.getParentFile();
|
||||
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
|
||||
parent.mkdirs();
|
||||
try (InputStream in = context.getAssets().open(assetPath);
|
||||
OutputStream out = new FileOutputStream(destination)) {
|
||||
copy(in, out);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
Log.w(TAG, "copy asset " + assetPath, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void copy(InputStream in, OutputStream out) throws IOException {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) out.write(buffer, 0, read);
|
||||
}
|
||||
|
||||
public static String sizeToString(long bytes) {
|
||||
if (bytes >= 1L << 30) return String.format(java.util.Locale.US, "%.1f GB", bytes / (float) (1L << 30));
|
||||
if (bytes >= 1L << 20) return String.format(java.util.Locale.US, "%.0f MB", bytes / (float) (1L << 20));
|
||||
return bytes + " B";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
/** The variables a host process is started with, in the order they were set. */
|
||||
class HostEnvironment {
|
||||
private val entries = LinkedHashMap<String, String>()
|
||||
|
||||
operator fun set(name: String, value: String) {
|
||||
entries[name] = value
|
||||
}
|
||||
|
||||
/** `NAME=VALUE` lines, the shape ProcessBuilder and proot take. */
|
||||
fun asArray(): Array<String> = entries.map { (name, value) -> "$name=$value" }.toTypedArray()
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.util.function.Consumer
|
||||
|
||||
/**
|
||||
* Starts a process on the Android side - proot, the audio daemon, logcat - and hands back its pid.
|
||||
*
|
||||
* The pid matters: stopping a session means killing that exact process (proot runs with
|
||||
* --kill-on-exit, so the guest tree goes with it), and java.lang.Process does not expose it before
|
||||
* API 33, so it is read from the implementation's private field. Output can be drained line by
|
||||
* line to a callback; without one it goes to /dev/null, never to a pipe nobody reads, which would
|
||||
* block the child the moment the pipe filled.
|
||||
*/
|
||||
object HostProcess {
|
||||
private const val TAG = "HostProcess"
|
||||
|
||||
/**
|
||||
* @param command the program and its arguments as one line; a backslash escapes a space, since
|
||||
* paths under /data are full of them.
|
||||
* @param env `NAME=VALUE` lines added to the app's own environment (proot needs nothing from
|
||||
* the inherited set, and the guest starts with `env -i` anyway), or null.
|
||||
* @param onExit told the exit status from a waiting thread, or null.
|
||||
* @param onLine told each line of stdout and stderr, or null to discard both.
|
||||
* @return the pid, or -1 when the process could not be started.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int {
|
||||
val argv = split(command)
|
||||
if (argv.isEmpty()) return -1
|
||||
return try {
|
||||
val builder = ProcessBuilder(argv)
|
||||
if (dir != null) builder.directory(dir)
|
||||
env?.forEach { line ->
|
||||
val eq = line.indexOf('=')
|
||||
if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1)
|
||||
}
|
||||
builder.redirectErrorStream(true)
|
||||
if (onLine == null) builder.redirectOutput(File("/dev/null"))
|
||||
val process = builder.start()
|
||||
val pid = pidOf(process)
|
||||
Log.i(TAG, "started pid $pid: $command")
|
||||
if (onLine != null) {
|
||||
Thread({
|
||||
try {
|
||||
process.inputStream.bufferedReader().useLines { lines -> lines.forEach { onLine.accept(it) } }
|
||||
} catch (e: Exception) {
|
||||
// The process ended or the pipe closed; nothing more to read.
|
||||
}
|
||||
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
|
||||
}
|
||||
if (onExit != null) {
|
||||
Thread({
|
||||
var status = -1
|
||||
try { status = process.waitFor() } catch (e: InterruptedException) { /* reported as -1 */ }
|
||||
onExit.accept(status)
|
||||
}, "proc-wait-$pid").apply { priority = Thread.NORM_PRIORITY - 1; start() }
|
||||
}
|
||||
pid
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not start: $command", e)
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
private fun pidOf(process: Process): Int = try {
|
||||
val field = process.javaClass.getDeclaredField("pid")
|
||||
field.isAccessible = true
|
||||
val pid = field.getInt(process)
|
||||
field.isAccessible = false
|
||||
pid
|
||||
} catch (e: Exception) {
|
||||
-1
|
||||
}
|
||||
|
||||
/** Splits a command line on spaces; a backslash keeps the space that follows it. */
|
||||
@JvmStatic
|
||||
fun split(command: String): List<String> {
|
||||
val parts = ArrayList<String>()
|
||||
val current = StringBuilder()
|
||||
var escaped = false
|
||||
for (c in command) {
|
||||
when {
|
||||
escaped -> { current.append(c); escaped = false }
|
||||
c == '\\' -> escaped = true
|
||||
c == ' ' -> if (current.isNotEmpty()) { parts.add(current.toString()); current.setLength(0) }
|
||||
else -> current.append(c)
|
||||
}
|
||||
}
|
||||
if (current.isNotEmpty()) parts.add(current.toString())
|
||||
return parts
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
/**
|
||||
* Scrubs credentials out of a log line before it is written somewhere a user will share.
|
||||
*
|
||||
* The Steam client's own logs are the reason this exists: they carry the account's session token
|
||||
* (logged as a bare number after "Using JWT"), machine-auth GUIDs, `token=`/`sessionid=` pairs,
|
||||
* Steam Guard codes, 32-hex WebAPI keys and the account's SteamID. A session folder from this app
|
||||
* is meant to be attached to a bug report as it is, so none of that may be in it.
|
||||
*
|
||||
* Ported from Bannerlator's {@code SteamLogRedactor} (GPL-3.0), which was written against real
|
||||
* client logs; the account-name registration is left out because this app never learns it.
|
||||
*
|
||||
* What is deliberately KEPT, because it is what makes a log worth reading: EResult codes, CM host
|
||||
* names and IP addresses, timings, token expiry dates, app IDs, pids, connection-state changes and
|
||||
* file paths. A SteamID is masked rather than deleted - first four and last four digits survive -
|
||||
* so a reader can still tell two accounts' lines apart without the value identifying either.
|
||||
*/
|
||||
object LogRedactor {
|
||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||
/** "Using JWT 25484942796017334" - the client logs its session token as digits, not base64. */
|
||||
private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})")
|
||||
/** A 3-part base64url JWT logged verbatim (a refresh or access token). */
|
||||
private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}")
|
||||
/** Machine-auth and other GUIDs. */
|
||||
private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b")
|
||||
/**
|
||||
* key=value secrets. A bare `key` is excluded on purpose so "key=english" survives; a real
|
||||
* WebAPI key is caught by [WEBAPI_KEY]. The value class excludes `<` and `>` so running this
|
||||
* twice over an already-scrubbed line changes nothing.
|
||||
*/
|
||||
private val SECRET_KV = Regex(
|
||||
"(?i)\\b(access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
|
||||
"auth[_-]?ticket|ticket|sessionid|steamloginsecure|webapikey|api[_-]?key|" +
|
||||
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)" +
|
||||
"(\\s*[=:]\\s*|=)([^\\s\"'<>&;,]{4,})"
|
||||
)
|
||||
/** A Steam Guard code, only where the text around it says that is what it is. */
|
||||
private val GUARD_CODE = Regex(
|
||||
"(?i)((?:steam\\s*)?guard\\s*code[\\s:=]*|two[\\s-]?factor[\\s:=]*|2fa[\\s:=]*)([A-Za-z0-9]{5})"
|
||||
)
|
||||
/** Exactly 32 hex - a WebAPI key. Bounded so a 40-hex depot chunk id is left alone. */
|
||||
private val WEBAPI_KEY = Regex("\\b[0-9A-Fa-f]{32}\\b")
|
||||
/** A long opaque run after a sensitive word, for anything the rules above missed. */
|
||||
private val RESIDUAL = Regex(
|
||||
"(?i)\\b(jwt|token|ticket|sessionid|steamloginsecure|machineauth)\\b[\\s=:]*([A-Za-z0-9+/=_\\-]{12,})"
|
||||
)
|
||||
private val LONG_TOKEN = Regex("[A-Za-z0-9_\\-]{88,}")
|
||||
private val STEAMID64 = Regex("\\b(76561)(\\d{8})(\\d{4})\\b")
|
||||
private val STEAMID3 = Regex("\\[U:1:(\\d+)]")
|
||||
|
||||
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
|
||||
fun redact(line: String): String {
|
||||
if (line.isEmpty()) return line
|
||||
return try {
|
||||
var out = line
|
||||
out = GUID.replace(out, "<redacted:guid>")
|
||||
out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}<redacted:jwt>" }
|
||||
out = JWT_BASE64.replace(out, "<redacted:jwt>")
|
||||
out = SECRET_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>" }
|
||||
out = GUARD_CODE.replace(out) { "${it.groupValues[1]}<redacted:code>" }
|
||||
out = WEBAPI_KEY.replace(out, "<redacted:key>")
|
||||
// Mask, not delete: the last four digits let a reader correlate lines to one account.
|
||||
out = STEAMID64.replace(out) { "${it.groupValues[1]}********${it.groupValues[3]}" }
|
||||
out = STEAMID3.replace(out) { m ->
|
||||
val id = m.groupValues[1]
|
||||
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
||||
}
|
||||
out = EMAIL.replace(out, "<redacted:email>")
|
||||
out = RESIDUAL.replace(out) { "${it.groupValues[1]}=<redacted:token>" }
|
||||
out = LONG_TOKEN.replace(out, "<redacted:token>")
|
||||
out
|
||||
} catch (t: Throwable) {
|
||||
// A log line is never worth crashing a session over, but an unscrubbed one must not
|
||||
// reach the file either.
|
||||
"<redaction failed; line withheld>"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.net.Inet4Address
|
||||
import java.net.Inet6Address
|
||||
|
||||
/**
|
||||
* `network.txt`: what the session was given to work with, for the reports that say "the client
|
||||
* thinks WiFi is off" or "Firefox cannot resolve anything".
|
||||
*
|
||||
* The runtime has no NetworkManager, so the client's own network panel is blind by design and says
|
||||
* so in ways that read like a fault. What actually matters is further down: whether the phone had
|
||||
* a validated link, which DNS servers the app wrote into the runtime's `resolv.conf`, and whether
|
||||
* the session can reach a name and an address at all.
|
||||
*
|
||||
* **No network names.** The SSID is identifying and is deliberately not collected; the transport
|
||||
* type, the addresses' families and the DNS servers are what a diagnosis needs.
|
||||
*/
|
||||
object NetworkReport {
|
||||
private const val TAG = "NetworkReport"
|
||||
|
||||
fun write(context: Context, target: File) {
|
||||
try {
|
||||
target.writeText(build(context))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not write $target", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun build(context: Context): String = buildString {
|
||||
append("Network as the session starts\n")
|
||||
append("=============================\n")
|
||||
append("The SSID is deliberately not recorded. Transport, address families and DNS are.\n\n")
|
||||
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||
val network = cm?.activeNetwork
|
||||
if (cm == null || network == null) {
|
||||
append("Active network none - the phone reports no connection\n")
|
||||
} else {
|
||||
val caps = cm.getNetworkCapabilities(network)
|
||||
val transport = when {
|
||||
caps == null -> "unknown"
|
||||
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "WiFi"
|
||||
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "cellular"
|
||||
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "ethernet"
|
||||
caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> "VPN"
|
||||
else -> "other"
|
||||
}
|
||||
append("Transport ").append(transport).append('\n')
|
||||
append("Validated ")
|
||||
.append(caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) ?: "unknown")
|
||||
.append(" (false with a working link usually means a captive portal)\n")
|
||||
append("Metered ")
|
||||
.append(caps?.let { !it.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) } ?: "unknown")
|
||||
.append('\n')
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && caps != null) {
|
||||
append("Link speed down ").append(caps.linkDownstreamBandwidthKbps)
|
||||
.append(" kbps / up ").append(caps.linkUpstreamBandwidthKbps).append(" kbps\n")
|
||||
}
|
||||
val link = cm.getLinkProperties(network)
|
||||
append("Interface ").append(link?.interfaceName ?: "unknown").append('\n')
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
append("MTU ").append(link?.mtu ?: 0).append('\n')
|
||||
}
|
||||
val v4 = link?.linkAddresses.orEmpty().count { it.address is Inet4Address }
|
||||
val v6 = link?.linkAddresses.orEmpty().count { it.address is Inet6Address }
|
||||
append("Addresses ").append(v4).append(" IPv4, ").append(v6).append(" IPv6")
|
||||
.append(if (v4 == 0) " (no IPv4 - Steam's content servers need it)" else "").append('\n')
|
||||
append("DNS from the system ")
|
||||
.append(link?.dnsServers.orEmpty().joinToString(", ") { it.hostAddress ?: "?" }.ifEmpty { "none" })
|
||||
.append('\n')
|
||||
append("Search domains ").append(link?.domains ?: "none").append('\n')
|
||||
}
|
||||
|
||||
append("\nWhat the runtime was given\n")
|
||||
append("--------------------------\n")
|
||||
// The app writes this file from the live link at every change; it is what everything inside
|
||||
// the session resolves with, so a mismatch with the system's list above is the bug itself.
|
||||
val resolv = File(LinuxRuntime.rootDir(context), "etc/resolv.conf")
|
||||
if (resolv.isFile) {
|
||||
append("etc/resolv.conf:\n")
|
||||
FileUtils.readString(resolv)?.lines()?.forEach { append(" ").append(it).append('\n') }
|
||||
} else {
|
||||
append("etc/resolv.conf does not exist yet - written when the session's link is published.\n")
|
||||
}
|
||||
val netdev = File(LinuxRuntime.rootDir(context), "etc/bannerlator-net")
|
||||
if (netdev.isFile) {
|
||||
append("\netc/bannerlator-net (the link as the session sees it):\n")
|
||||
FileUtils.readString(netdev)?.lines()?.forEach { append(" ").append(it).append('\n') }
|
||||
}
|
||||
append("\nproot makes no network namespace, so the session uses the phone's connection\n")
|
||||
append("directly: IPv4 and IPv6 both pass through, and there is nothing to forward.\n")
|
||||
append("The Steam client's own network panel drives NetworkManager over D-Bus, which this\n")
|
||||
append("runtime does not have - \"wifi is off\" there is cosmetic and not evidence.\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import java.io.BufferedWriter
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* `app.log`: what the app itself said while the session ran, and `crash.log`: what Android's crash
|
||||
* buffer holds if something died hard.
|
||||
*
|
||||
* Everything this app decides is reported through `Log` - which driver was chosen and why, the
|
||||
* audio line, a rival client being stopped, the session's exit status, a helper that was missing.
|
||||
* None of it reaches a user's folder, so a report used to arrive with the settings visible in
|
||||
* `device.txt` and no record of what actually happened. An app may always read back its own log
|
||||
* entries, so the simplest complete answer is to run `logcat` filtered to our own pid and keep
|
||||
* what it says.
|
||||
*
|
||||
* `logcat -b crash` earns its own file: proot once died before `main` over a missing library, and
|
||||
* that appeared in the crash buffer and *nowhere else* - not in the session log, not in the main
|
||||
* buffer. It is the first thing to read when a session "exits instantly".
|
||||
*
|
||||
* Both are best-effort. Where a ROM refuses to hand an app its own entries the files are written
|
||||
* with a line saying so, which is better than their absence looking like silence.
|
||||
*/
|
||||
object SessionLogCapture {
|
||||
private const val TAG = "SessionLogCapture"
|
||||
|
||||
private var pid = -1
|
||||
private var writer: BufferedWriter? = null
|
||||
private var target: File? = null
|
||||
|
||||
/** Start mirroring this process's log lines into [target]. Safe to call twice. */
|
||||
@Synchronized
|
||||
fun start(target: File) {
|
||||
stop()
|
||||
try {
|
||||
val out = target.bufferedWriter()
|
||||
out.write("The app's own log for this session (logcat, this process only).\n")
|
||||
out.write("Lines the app wrote before the session folder existed are in logcat only.\n\n")
|
||||
out.flush()
|
||||
writer = out
|
||||
this.target = target
|
||||
// -T 1 starts at the newest line rather than replaying the whole buffer; -v threadtime
|
||||
// keeps the timestamps and thread ids that make two logs line up.
|
||||
pid = HostProcess.start(
|
||||
"/system/bin/logcat -v threadtime -T 1 --pid=" + Process.myPid(),
|
||||
null, target.parentFile, null,
|
||||
) { line ->
|
||||
synchronized(this) {
|
||||
try {
|
||||
writer?.apply { write(line); newLine(); flush() }
|
||||
} catch (e: Exception) {
|
||||
// A full or unmounted card must not take the session with it.
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pid == -1) {
|
||||
out.write("logcat could not be started; this ROM may not hand an app its own entries.\n")
|
||||
out.flush()
|
||||
}
|
||||
Log.i(TAG, "app log -> $target (logcat pid $pid)")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not start the app log", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops the capture only if it is the one writing into [dir]: a newer session's is left alone. */
|
||||
@Synchronized
|
||||
fun stopFor(dir: File) {
|
||||
val t = target ?: return
|
||||
if (t.parentFile?.absolutePath == dir.absolutePath) stop()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
target = null
|
||||
if (pid != -1) {
|
||||
try {
|
||||
Process.killProcess(pid)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "logcat would not stop", e)
|
||||
}
|
||||
pid = -1
|
||||
}
|
||||
try {
|
||||
writer?.close()
|
||||
} catch (e: Exception) {
|
||||
// nothing useful to do with a failure to close a log
|
||||
}
|
||||
writer = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Dump Android's crash buffer into [target]. Called at teardown: a session that was killed is
|
||||
* exactly when this matters, and the buffer keeps its entries after the process is gone.
|
||||
*/
|
||||
fun dumpCrashBuffer(target: File) {
|
||||
try {
|
||||
val lines = StringBuilder()
|
||||
val done = java.util.concurrent.CountDownLatch(1)
|
||||
// Wait on the process ENDING, not on the first line arriving: the lines come through a
|
||||
// callback on another thread, so a poll for "is it empty yet" declared an empty buffer
|
||||
// every time and still cost the wait. exec() returns a pid, never an exit status - the
|
||||
// first version printed that pid as "rc", which was nonsense in the file.
|
||||
val pid = HostProcess.start(
|
||||
"/system/bin/logcat -b crash -d -v threadtime -t 400", null, target.parentFile,
|
||||
{ done.countDown() },
|
||||
) { line -> synchronized(lines) { lines.append(line).append('\n') } }
|
||||
val finished = pid != -1 && done.await(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
val body = synchronized(lines) { lines.toString() }
|
||||
target.writeText(
|
||||
"Android's crash buffer, as it stood when this session ended.\n" +
|
||||
"Not only this app: anything on the device that crashed is in here, which is the\n" +
|
||||
"point - a session killed by the system leaves its trace here and nowhere else.\n\n" +
|
||||
when {
|
||||
body.isNotEmpty() -> body
|
||||
pid == -1 -> "(logcat could not be started at all)\n"
|
||||
!finished -> "(logcat did not finish within 10 s; nothing captured)\n"
|
||||
else -> "(the crash buffer is empty - nothing on the device has crashed recently)\n"
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not dump the crash buffer", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.core;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
/**
|
||||
* One thing a running session depends on beside the guest process itself: the audio daemon, the
|
||||
* rumble listener, the battery the client reads, the network-link file. The session starts its
|
||||
* parts in order before the guest and stops them in reverse after it. A part is handed the
|
||||
* application context, never an activity's, so nothing here can keep a screen alive.
|
||||
*/
|
||||
public abstract class SessionPart {
|
||||
private Context app;
|
||||
|
||||
public final void attach(Context context) {
|
||||
this.app = context.getApplicationContext();
|
||||
}
|
||||
|
||||
/** The application context, valid after {@link #attach}. */
|
||||
protected final Context app() {
|
||||
return app;
|
||||
}
|
||||
|
||||
public abstract void start();
|
||||
|
||||
public abstract void stop();
|
||||
|
||||
public int suspendPid() {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.core;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.apache.commons.compress.compressors.zstandard.ZstdCompressorInputStream;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* The small zstd tarballs that ship inside the apk (the Turnip driver, the PulseAudio modules).
|
||||
* The runtime rootfs is not one of these - it needs hard links and symlinks preserved, which
|
||||
* {@link com.droiddeck.launcher.runtime.LinuxRuntimeInstaller} handles itself.
|
||||
*/
|
||||
public final class TarZst {
|
||||
private static final String TAG = "TarZst";
|
||||
|
||||
private TarZst() {}
|
||||
|
||||
public static boolean extractAsset(Context context, String assetPath, File destination) {
|
||||
try (InputStream in = context.getAssets().open(assetPath)) {
|
||||
return extract(in, destination);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "extract " + assetPath, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean extract(InputStream source, File destination) {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
destination.mkdirs();
|
||||
try (InputStream in = new ZstdCompressorInputStream(new BufferedInputStream(source, 1 << 16));
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
||||
String base = destination.getCanonicalPath() + File.separator;
|
||||
TarArchiveEntry entry;
|
||||
while ((entry = tar.getNextTarEntry()) != null) {
|
||||
File file = new File(destination, entry.getName());
|
||||
if (!file.getCanonicalPath().startsWith(base)) continue;
|
||||
if (entry.isDirectory()) {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
file.mkdirs();
|
||||
continue;
|
||||
}
|
||||
File parent = file.getParentFile();
|
||||
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
|
||||
parent.mkdirs();
|
||||
if (entry.isSymbolicLink()) {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
file.delete();
|
||||
FileUtils.symlink(entry.getLinkName(), file.getAbsolutePath());
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile()) continue;
|
||||
try (OutputStream out = new FileOutputStream(file)) {
|
||||
FileUtils.copy(tar, out);
|
||||
}
|
||||
if ((entry.getMode() & 0111) != 0) //noinspection ResultOfMethodCallIgnored
|
||||
file.setExecutable(true, false);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "extract into " + destination, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Badge
|
||||
import androidx.compose.material3.BadgedBox
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.annotation.DrawableRes
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/** One tappable entry in a [CollapsibleRail] (a container tab, a file-manager location, …). */
|
||||
data class RailItem(
|
||||
val label: String,
|
||||
val icon: ImageVector,
|
||||
val selected: Boolean,
|
||||
/** >0 shows a small accent count badge on the item's icon (expanded and collapsed). */
|
||||
val badge: Int = 0,
|
||||
// onClick stays LAST so existing call sites can pass it as a trailing lambda; badge is an
|
||||
// optional named param before it (default 0).
|
||||
val onClick: () -> Unit,
|
||||
)
|
||||
|
||||
/** A group of [RailItem]s under an optional small section header (STORAGE / QUICK / FAVORITES …). */
|
||||
data class RailSection(val header: String?, val items: List<RailItem>)
|
||||
|
||||
/**
|
||||
* The tiny under-icon label for a COLLAPSED rail item. The rail width never changes, so labels must
|
||||
* fit the narrow (~58dp) column: multi-word names wrap to a second line; single words too long to
|
||||
* fit are abbreviated; short ones pass through. (Explicit abbreviations first, then a length guard.)
|
||||
*/
|
||||
private fun collapsedLabel(label: String): String {
|
||||
when (label) {
|
||||
"ENVIROMENT" -> return "ENVIRON" // the app's existing (mis)spelling, kept uppercase
|
||||
"WIN COMPONENTS" -> return "WIN COMP"
|
||||
"Downloads" -> return "Downlds"
|
||||
}
|
||||
if (label.contains(' ')) return label // multi-word → wraps to 2 lines
|
||||
return if (label.length > 9) label.take(8) + "…" else label
|
||||
}
|
||||
|
||||
/** A rail item's 20dp icon, with a small accent count badge on its corner when [badge] > 0. */
|
||||
@Composable
|
||||
private fun RailItemIcon(item: RailItem, tint: androidx.compose.ui.graphics.Color) {
|
||||
if (item.badge > 0) {
|
||||
BadgedBox(
|
||||
badge = {
|
||||
Badge(
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary,
|
||||
) { Text(if (item.badge > 9) "9+" else item.badge.toString(), fontSize = 8.sp) }
|
||||
},
|
||||
) {
|
||||
Icon(item.icon, contentDescription = item.label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
} else {
|
||||
Icon(item.icon, contentDescription = item.label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** A secondary link shown under the header (e.g. "What is all this?", "Reset to app defaults"). */
|
||||
data class RailLink(val label: String, val icon: ImageVector, val onClick: () -> Unit)
|
||||
|
||||
/**
|
||||
* State for a [CollapsibleRail], with the app-wide unified rule:
|
||||
* - PORTRAIT → always collapsed (icon-only), the toggle is HIDDEN and it can never expand.
|
||||
* - LANDSCAPE → expanded by default; the user's collapse choice is remembered PER-SCREEN
|
||||
* ([screenKey]) and is NOT overridden by rotation. portrait→landscape restores that choice.
|
||||
*
|
||||
* Backed by rememberSaveable (survives process death) and by the fact the app UI activity keeps
|
||||
* orientation in configChanges (no recreate) so the selected item / fields / scroll are preserved.
|
||||
*/
|
||||
class RailState internal constructor(
|
||||
val collapsed: Boolean,
|
||||
/** True in portrait: the rail is locked collapsed and must not show an expand toggle. */
|
||||
val portraitLocked: Boolean,
|
||||
val onToggle: () -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun rememberRailState(screenKey: String): RailState {
|
||||
val context = LocalContext.current
|
||||
// The same file the File Manager keeps its own browse settings in (no androidx.preference here).
|
||||
val prefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
|
||||
val isLandscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE
|
||||
|
||||
val choseKey = "rail_${screenKey}_userChose"
|
||||
val collapsedKey = "rail_${screenKey}_collapsed"
|
||||
|
||||
// Keep the landscape choice in saveable state regardless of orientation so portrait→landscape
|
||||
// restores it. In portrait we simply report collapsed+locked and ignore it.
|
||||
var userChose by rememberSaveable(screenKey) { mutableStateOf(prefs.getBoolean(choseKey, false)) }
|
||||
var landscapeCollapsed by rememberSaveable(screenKey) {
|
||||
mutableStateOf(if (prefs.getBoolean(choseKey, false)) prefs.getBoolean(collapsedKey, false) else false)
|
||||
}
|
||||
|
||||
if (!isLandscape) {
|
||||
return RailState(collapsed = true, portraitLocked = true, onToggle = {})
|
||||
}
|
||||
return RailState(
|
||||
collapsed = landscapeCollapsed,
|
||||
portraitLocked = false,
|
||||
onToggle = {
|
||||
landscapeCollapsed = !landscapeCollapsed
|
||||
userChose = true
|
||||
prefs.edit()
|
||||
.putBoolean(choseKey, true)
|
||||
.putBoolean(collapsedKey, landscapeCollapsed)
|
||||
.apply()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared collapsible left rail (mockup "Option 3"): app glyph + title, optional links, and the
|
||||
* navigation items, replacing a top tab bar so content runs full height beside it. Width animates
|
||||
* 190dp ↔ 58dp. When collapsed it is icon-only (the caller surfaces the active item's name over the
|
||||
* content). Used by the container editors, File Manager and Save Manager.
|
||||
*
|
||||
* [footer] is an optional slot pinned to the bottom of the rail (a weighted spacer pushes it down),
|
||||
* for a persistent per-screen summary (e.g. the Save Manager's "N games need syncing" line). The
|
||||
* caller renders whatever it wants there and can key it off [RailState.collapsed] to go icon-only.
|
||||
*/
|
||||
@Composable
|
||||
fun CollapsibleRail(
|
||||
state: RailState,
|
||||
title: String,
|
||||
sections: List<RailSection>,
|
||||
modifier: Modifier = Modifier,
|
||||
links: List<RailLink> = emptyList(),
|
||||
footer: (@Composable ColumnScope.() -> Unit)? = null,
|
||||
// Optional header glyph (a themed drawable). When null the rail shows its plain solid square.
|
||||
// Used by the container editors to show the wine-glass container icon; other rails leave it null.
|
||||
@DrawableRes headerIcon: Int? = null,
|
||||
// When true each item gets a rounded outlined-button look (the selected one takes the accent
|
||||
// border + accent-dim fill), matching the File Manager's "New Folder" button. Off by default so
|
||||
// the container/save rails keep their lighter flat rows (5 stacked outlined tabs read too heavy).
|
||||
outlinedItems: Boolean = false,
|
||||
) {
|
||||
val collapsed = state.collapsed
|
||||
val width by animateDpAsState(if (collapsed) 58.dp else 190.dp, label = "railWidth")
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.width(width)
|
||||
.fillMaxHeight()
|
||||
.background(MaterialTheme.colorScheme.surfaceContainerHigh)
|
||||
) {
|
||||
// ── Header: app glyph + title + collapse handle (handle hidden when portrait-locked) ──
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = if (collapsed) Arrangement.Center else Arrangement.Start,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = if (collapsed) 0.dp else 10.dp, vertical = 8.dp)
|
||||
) {
|
||||
if (headerIcon != null) {
|
||||
Icon(
|
||||
painter = painterResource(headerIcon),
|
||||
contentDescription = title,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(22.dp)
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(MaterialTheme.colorScheme.primary)
|
||||
)
|
||||
}
|
||||
if (!collapsed) {
|
||||
Spacer(Modifier.width(9.dp))
|
||||
Text(
|
||||
title,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (!state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) {
|
||||
Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Collapsed (landscape only) → an expand handle; portrait is locked with no handle.
|
||||
if (collapsed && !state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) {
|
||||
Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Links ──
|
||||
if (links.isNotEmpty()) {
|
||||
if (collapsed) {
|
||||
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
links.forEach { link ->
|
||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) {
|
||||
Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
links.forEach { link ->
|
||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) {
|
||||
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(link.label, fontSize = 11.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
|
||||
|
||||
// ── Sections + items (SCROLLABLE so a tall rail - e.g. many File Manager favourites - is
|
||||
// fully reachable in both orientations; the header above and footer below stay pinned) ──
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.verticalScroll(rememberScrollState())
|
||||
) {
|
||||
sections.forEach { section ->
|
||||
if (!collapsed && section.header != null) {
|
||||
Text(
|
||||
section.header,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
|
||||
fontSize = 9.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.6.sp,
|
||||
modifier = Modifier.padding(start = 14.dp, top = 10.dp, bottom = 2.dp),
|
||||
)
|
||||
} else if (collapsed && section.header != null && section != sections.first()) {
|
||||
HorizontalDivider(
|
||||
color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f),
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
section.items.forEach { item ->
|
||||
val active = item.selected
|
||||
// Outlined variant: each item is a rounded outlined button; selected = accent border +
|
||||
// accent-dim fill. Flat variant (default): a simple accent-tinted highlight for selected.
|
||||
val shape = RoundedCornerShape(9.dp)
|
||||
val base = Modifier.fillMaxWidth()
|
||||
val styled = if (outlinedItems) {
|
||||
base
|
||||
.padding(horizontal = 6.dp, vertical = 3.dp)
|
||||
.clip(shape)
|
||||
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.16f) else MaterialTheme.colorScheme.surface.copy(alpha = 0.4f))
|
||||
.border(
|
||||
1.dp,
|
||||
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
|
||||
shape,
|
||||
)
|
||||
.clickable(onClick = item.onClick)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
|
||||
} else {
|
||||
base
|
||||
.clickable(onClick = item.onClick)
|
||||
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
|
||||
}
|
||||
val iconTint = if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
val labelColor = if (active) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
if (collapsed) {
|
||||
// Icon-only width is unchanged - a TINY label goes UNDER the icon (2 lines max,
|
||||
// centre-aligned, wrapping/abbreviated) so every button stays identifiable without
|
||||
// widening the rail.
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = styled,
|
||||
) {
|
||||
RailItemIcon(item, iconTint)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
collapsedLabel(item.label),
|
||||
color = labelColor,
|
||||
fontSize = 7.5.sp,
|
||||
lineHeight = 8.5.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
textAlign = TextAlign.Center,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
modifier = styled,
|
||||
) {
|
||||
RailItemIcon(item, iconTint)
|
||||
Spacer(Modifier.width(11.dp))
|
||||
Text(
|
||||
item.label,
|
||||
color = labelColor,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.3.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // end scrollable section list (its weight fills the gap so the footer stays pinned)
|
||||
|
||||
// ── Optional pinned footer (e.g. the sync summary) ──
|
||||
if (footer != null) {
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
|
||||
footer()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Portrait counterpart to [CollapsibleRail]: the same navigation [items] laid out as a horizontal
|
||||
* icon-over-label bar pinned across the top, with an accent underline under the selected one. Mirrors
|
||||
* the container editor's top tab bar so every editor reads the same - pin this in portrait wherever a
|
||||
* [CollapsibleRail] is used in landscape. Optional [links] (Help / Reset …) are appended after a
|
||||
* faint separator, exactly like the rail's links.
|
||||
*
|
||||
* (The container editor still carries its own private copy of this bar; new screens should prefer
|
||||
* this shared one, and the container editor can migrate to it later.)
|
||||
*/
|
||||
@Composable
|
||||
fun RailTopTabs(
|
||||
items: List<RailItem>,
|
||||
modifier: Modifier = Modifier,
|
||||
links: List<RailLink> = emptyList(),
|
||||
) {
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
items.forEach { item ->
|
||||
TopTabCell(
|
||||
icon = item.icon,
|
||||
label = item.label,
|
||||
selected = item.selected,
|
||||
onClick = item.onClick,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
if (links.isNotEmpty()) {
|
||||
// Faint separator: everything past here is an action button, not a tab.
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 2.dp)
|
||||
.width(1.dp)
|
||||
.height(30.dp)
|
||||
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
|
||||
)
|
||||
links.forEach { link ->
|
||||
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
|
||||
/** One cell of [RailTopTabs] - icon over a small label, with an accent underline (zero-width when
|
||||
* unselected, so every cell keeps the same height). Mirrors the container editor's TopCell. */
|
||||
@Composable
|
||||
private fun TopTabCell(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 6.dp, horizontal = 1.dp),
|
||||
) {
|
||||
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
label,
|
||||
color = tint,
|
||||
fontSize = 8.5.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.2.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.height(2.dp)
|
||||
.width(if (selected) 16.dp else 0.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONArray
|
||||
|
||||
/**
|
||||
* Persists the File Manager's favourite / bookmarked directories.
|
||||
*
|
||||
* Stores an ordered (insertion-order) list of absolute path strings as a JSON array
|
||||
* under "file_manager_favorites" in SharedPreferences "file_manager_prefs". Only the
|
||||
* absolute path is kept - everything shown on a favourite card (drive label, container
|
||||
* name, display path) is derived live, so a renamed or deleted container resolves
|
||||
* correctly for free.
|
||||
*/
|
||||
object FavoritesStore {
|
||||
|
||||
private const val PREFS_NAME = "file_manager_prefs"
|
||||
private const val KEY = "file_manager_favorites"
|
||||
|
||||
private fun prefs(context: Context) =
|
||||
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
|
||||
/** Ordered list of favourited absolute paths (insertion order). */
|
||||
fun list(context: Context): List<String> {
|
||||
val raw = prefs(context).getString(KEY, null) ?: return emptyList()
|
||||
return runCatching {
|
||||
val arr = JSONArray(raw)
|
||||
buildList { for (i in 0 until arr.length()) add(arr.getString(i)) }
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
fun isFavorite(context: Context, path: String): Boolean = list(context).contains(path)
|
||||
|
||||
/** Add [path] if not already present (deduped); keeps insertion order. */
|
||||
fun add(context: Context, path: String) {
|
||||
val current = list(context)
|
||||
if (current.contains(path)) return
|
||||
save(context, current + path)
|
||||
}
|
||||
|
||||
fun remove(context: Context, path: String) {
|
||||
val current = list(context)
|
||||
if (!current.contains(path)) return
|
||||
save(context, current.filterNot { it == path })
|
||||
}
|
||||
|
||||
/** Toggle [path]; returns true if it is now a favourite, false if it was removed. */
|
||||
fun toggle(context: Context, path: String): Boolean =
|
||||
if (isFavorite(context, path)) {
|
||||
remove(context, path); false
|
||||
} else {
|
||||
add(context, path); true
|
||||
}
|
||||
|
||||
private fun save(context: Context, paths: List<String>) {
|
||||
val arr = JSONArray()
|
||||
paths.forEach { arr.put(it) }
|
||||
prefs(context).edit().putString(KEY, arr.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
|
||||
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
|
||||
class FileManagerActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
||||
FileManagerScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,130 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The file operations the File Manager needs, as Bannerlator's FileUtils has them: a delete that
|
||||
* says whether it worked, a copy and a move that report bytes as they go, and the size format
|
||||
* the rows use. Kept apart from core/FileUtils, whose callers want a quiet delete.
|
||||
*/
|
||||
object FileOps {
|
||||
private const val TAG = "FileOps"
|
||||
|
||||
/** Byte-accurate copy progress (copied/total bytes), reported as the copy proceeds. */
|
||||
fun interface ProgressCallback { fun onProgress(copiedBytes: Long, totalBytes: Long) }
|
||||
|
||||
fun formatBytes(bytes: Long): String {
|
||||
if (bytes <= 0) return "0 bytes"
|
||||
val units = arrayOf("bytes", "KB", "MB", "GB", "TB")
|
||||
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]
|
||||
}
|
||||
|
||||
fun isSymlink(file: File): Boolean = try { Files.isSymbolicLink(file.toPath()) } catch (e: Exception) { false }
|
||||
|
||||
/** Recursive delete that never follows a symlink; true when everything went. */
|
||||
fun delete(target: File?): Boolean {
|
||||
if (target == null) return false
|
||||
if (target.isDirectory && !isSymlink(target)) {
|
||||
if (!clear(target)) return false
|
||||
}
|
||||
return target.delete()
|
||||
}
|
||||
|
||||
fun clear(dir: File): Boolean {
|
||||
val children = dir.listFiles() ?: return true
|
||||
var ok = true
|
||||
for (child in children) if (!delete(child)) ok = false
|
||||
return ok
|
||||
}
|
||||
|
||||
/** Recursive total size in bytes of files under [f] (skips symlinks). Used to size a progress bar. */
|
||||
fun totalSize(f: File?): Long {
|
||||
if (f == null || !f.exists() || isSymlink(f)) return 0
|
||||
if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it) } ?: 0
|
||||
return f.length()
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves [src] to [dst], relinking instead of copying whenever possible. A rename is instant
|
||||
* regardless of size but only works within one filesystem; renameTo returning false is the
|
||||
* signal that a boundary was crossed, so it doubles as the check, and the fallback is
|
||||
* copy-then-delete. Only attempted when the destination does not exist: renaming onto an
|
||||
* existing directory does not merge.
|
||||
*/
|
||||
fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean {
|
||||
if (sameFile(src, dst)) return true
|
||||
if (!dst.exists() && src.renameTo(dst)) {
|
||||
progress?.onProgress(1, 1)
|
||||
return true
|
||||
}
|
||||
if (!copyWithProgress(src, dst, progress)) return false
|
||||
return delete(src)
|
||||
}
|
||||
|
||||
/** A copy that reports byte progress, smooth even within one large file. */
|
||||
fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean {
|
||||
val total = maxOf(totalSize(src), 1L)
|
||||
return copyWithProgress(src, dst, longArrayOf(0), total, progress)
|
||||
}
|
||||
|
||||
private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?): Boolean {
|
||||
if (isSymlink(src)) return true
|
||||
if (sameFile(src, dst)) return true
|
||||
if (src.isDirectory && isWithin(dst, src)) {
|
||||
Log.e(TAG, "Refusing to copy directory into itself: $src -> $dst")
|
||||
return false
|
||||
}
|
||||
if (src.isDirectory) {
|
||||
if (!dst.exists() && !dst.mkdirs()) return false
|
||||
var allOk = true
|
||||
src.list()?.forEach { name ->
|
||||
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress)) {
|
||||
Log.e(TAG, "Failed to copy: ${File(src, name)}")
|
||||
allOk = false
|
||||
}
|
||||
}
|
||||
return allOk
|
||||
}
|
||||
val parent = dst.parentFile
|
||||
if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false
|
||||
val chunk = 4L * 1024 * 1024 // report progress every 4 MiB
|
||||
try {
|
||||
FileInputStream(src).channel.use { input ->
|
||||
FileOutputStream(dst).channel.use { output ->
|
||||
val size = input.size()
|
||||
var position = 0L
|
||||
while (position < size) {
|
||||
val transferred = input.transferTo(position, minOf(chunk, size - position), output)
|
||||
if (transferred <= 0) break
|
||||
position += transferred
|
||||
done[0] += transferred
|
||||
progress?.onProgress(done[0], total)
|
||||
}
|
||||
if (position < size) throw IOException("Incomplete copy: $position/$size bytes")
|
||||
}
|
||||
}
|
||||
return true
|
||||
} catch (e: IOException) {
|
||||
Log.e(TAG, "Failed to copy file: $src to $dst", e)
|
||||
dst.delete()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private fun sameFile(a: File, b: File): Boolean =
|
||||
try { a.canonicalPath == b.canonicalPath } catch (e: IOException) { a.absolutePath == b.absolutePath }
|
||||
|
||||
/** True when [child] is [ancestor] itself or lives anywhere inside it. */
|
||||
private fun isWithin(child: File, ancestor: File): Boolean {
|
||||
val c = try { child.canonicalPath } catch (e: IOException) { child.absolutePath }
|
||||
val a = try { ancestor.canonicalPath } catch (e: IOException) { ancestor.absolutePath }
|
||||
return c == a || c.startsWith(a + File.separator)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Themed host for [FileManagerScreen] in pick mode. Launched through [InAppFilePicker] and answers with the
|
||||
* picked path in [EXTRA_SELECTED_FILE] on RESULT_OK.
|
||||
*
|
||||
* Extras:
|
||||
* - [EXTRA_EXTENSIONS] allowed lowercase extensions, no dot; absent or empty = all files
|
||||
* - [EXTRA_PICK_DIRECTORY] true to pick a folder instead of a file
|
||||
* - [EXTRA_INITIAL_DIRECTORY] where to open; absent = the last folder picked from, then internal storage
|
||||
* - [EXTRA_PICKER_TITLE] the header
|
||||
*/
|
||||
class FilePickerActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// targetSdk 28: the old storage permission is exactly what lets us list the card.
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
|
||||
val extensions = intent.getStringArrayExtra(EXTRA_EXTENSIONS)?.toList() ?: emptyList()
|
||||
val pickDir = intent.getBooleanExtra(EXTRA_PICK_DIRECTORY, false)
|
||||
val title = intent.getStringExtra(EXTRA_PICKER_TITLE)
|
||||
// The screen remembers the folder it last picked from; an explicit start wins over it.
|
||||
val prefs = getSharedPreferences("file_manager", MODE_PRIVATE)
|
||||
val initialDir = (intent.getStringExtra(EXTRA_INITIAL_DIRECTORY) ?: prefs.getString("lastFilePickerDir", null))
|
||||
?.let { File(it) }?.takeIf { it.isDirectory }
|
||||
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
||||
FileManagerScreen(
|
||||
pickMode = true,
|
||||
pickDirMode = pickDir,
|
||||
pickExtensions = extensions,
|
||||
initialDir = initialDir,
|
||||
pickerTitle = title ?: if (pickDir) "Choose a folder" else "Choose a file",
|
||||
onPick = { file ->
|
||||
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
|
||||
finish()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
// The screen re-lists on its own when the grant lands; nothing to relay.
|
||||
if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_EXTENSIONS = "extensions"
|
||||
const val EXTRA_PICK_DIRECTORY = "pickDirectory"
|
||||
const val EXTRA_INITIAL_DIRECTORY = "initialDirectory"
|
||||
const val EXTRA_PICKER_TITLE = "pickerTitle"
|
||||
const val EXTRA_SELECTED_FILE = "selectedFile"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The app's own file picker, the way Bannerlator's File Manager offers its pick mode: one intent
|
||||
* builder per kind of pick, and the picked path read back from the result. Every import on the
|
||||
* main screen goes through here rather than Android's document picker, which cannot show an SD
|
||||
* card as a card, remembers nothing, and hands back a content URI the runtime cannot bind.
|
||||
*/
|
||||
object InAppFilePicker {
|
||||
/** Pick one file. [extensions] are lowercase, without the dot; empty = any file. */
|
||||
fun buildIntent(
|
||||
context: Context,
|
||||
extensions: List<String> = emptyList(),
|
||||
title: String? = null,
|
||||
initialDir: String? = null,
|
||||
): Intent = Intent(context, FilePickerActivity::class.java).apply {
|
||||
putExtra(FilePickerActivity.EXTRA_EXTENSIONS, extensions.toTypedArray())
|
||||
title?.let { putExtra(FilePickerActivity.EXTRA_PICKER_TITLE, it) }
|
||||
initialDir?.let { putExtra(FilePickerActivity.EXTRA_INITIAL_DIRECTORY, it) }
|
||||
}
|
||||
|
||||
/** Pick a folder: only folders are listed, and "Use this folder" returns the one open. */
|
||||
fun buildDirIntent(
|
||||
context: Context,
|
||||
title: String? = null,
|
||||
initialDir: String? = null,
|
||||
): Intent = Intent(context, FilePickerActivity::class.java).apply {
|
||||
putExtra(FilePickerActivity.EXTRA_PICK_DIRECTORY, true)
|
||||
title?.let { putExtra(FilePickerActivity.EXTRA_PICKER_TITLE, it) }
|
||||
initialDir?.let { putExtra(FilePickerActivity.EXTRA_INITIAL_DIRECTORY, it) }
|
||||
}
|
||||
|
||||
fun pickedPath(data: Intent?): String? = data?.getStringExtra(FilePickerActivity.EXTRA_SELECTED_FILE)
|
||||
|
||||
fun pickedFile(data: Intent?): File? = pickedPath(data)?.let { File(it) }
|
||||
|
||||
/** The picked file as the `file:` URI the import code already accepts. */
|
||||
fun pickedUri(data: Intent?): Uri? = pickedFile(data)?.let { Uri.fromFile(it) }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
// Shared outlined-card look for the app's popup menus, matching the FileManager / CommunityCard
|
||||
// idiom (surfaceContainer fill, 1dp outline, rounded 10dp). Applied to a DropdownMenu's modifier so
|
||||
// the popup reads as an outlined card. Keep all three menu call-sites on this so they stay identical.
|
||||
@Composable
|
||||
internal fun Modifier.outlinedMenuCard(): Modifier {
|
||||
val cs = MaterialTheme.colorScheme
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
return this
|
||||
.clip(shape)
|
||||
.background(cs.surfaceContainer)
|
||||
.border(1.dp, cs.outline, shape)
|
||||
}
|
||||
|
||||
// The thin low-alpha separator that sits between items inside an outlined menu card.
|
||||
@Composable
|
||||
internal fun MenuItemDivider() {
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f))
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
|
||||
// Single source of truth for the app's AlertDialogs: a drop-in wrapper around the Material3
|
||||
// slot-based AlertDialog that adds a 1dp outline around the whole popup box - matching the
|
||||
// outline that Modifier.outlinedMenuCard() (MenuStyle.kt) puts on the app's menus. Signature
|
||||
// mirrors androidx.compose.material3.AlertDialog exactly (compose-bom 2024.02.00 → material3
|
||||
// 1.2.0), so every call site can swap AlertDialog( → OutlinedAlertDialog( unchanged. The
|
||||
// border shares the dialog's shape so its corner radius follows the rounded dialog.
|
||||
@Composable
|
||||
internal fun OutlinedAlertDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
confirmButton: @Composable () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
dismissButton: (@Composable () -> Unit)? = null,
|
||||
icon: (@Composable () -> Unit)? = null,
|
||||
title: (@Composable () -> Unit)? = null,
|
||||
text: (@Composable () -> Unit)? = null,
|
||||
shape: Shape = AlertDialogDefaults.shape,
|
||||
containerColor: Color = AlertDialogDefaults.containerColor,
|
||||
iconContentColor: Color = AlertDialogDefaults.iconContentColor,
|
||||
titleContentColor: Color = AlertDialogDefaults.titleContentColor,
|
||||
textContentColor: Color = AlertDialogDefaults.textContentColor,
|
||||
tonalElevation: Dp = AlertDialogDefaults.TonalElevation,
|
||||
properties: DialogProperties = DialogProperties()
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismissRequest,
|
||||
confirmButton = confirmButton,
|
||||
modifier = modifier.border(1.dp, MaterialTheme.colorScheme.outline, shape),
|
||||
dismissButton = dismissButton,
|
||||
icon = icon,
|
||||
title = title,
|
||||
text = text,
|
||||
shape = shape,
|
||||
containerColor = containerColor,
|
||||
iconContentColor = iconContentColor,
|
||||
titleContentColor = titleContentColor,
|
||||
textContentColor = textContentColor,
|
||||
tonalElevation = tonalElevation,
|
||||
properties = properties
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* Extracts the embedded application icon from a Windows PE executable (.exe).
|
||||
*
|
||||
* Walks the PE resource directory to the first RT_GROUP_ICON, picks the largest /
|
||||
* deepest-colour entry it references, then decodes that RT_ICON image. Icon images
|
||||
* are either PNG (Vista+) - decoded directly - or a classic DIB (BITMAPINFOHEADER +
|
||||
* XOR pixels + 1-bpp AND mask) - decoded by hand here.
|
||||
*
|
||||
* Everything is best-effort: any malformed/oversized/unsupported input returns null.
|
||||
*/
|
||||
object PeIconExtractor {
|
||||
|
||||
private const val RT_ICON = 3
|
||||
private const val RT_GROUP_ICON = 14
|
||||
private const val MAX_RES_SECTION = 64 * 1024 * 1024 // don't slurp absurd resource sections
|
||||
private const val MAX_ICON_DIM = 1024
|
||||
|
||||
fun extract(file: File): Bitmap? = try {
|
||||
RandomAccessFile(file, "r").use { parse(it) }
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun parse(raf: RandomAccessFile): Bitmap? {
|
||||
val dos = read(raf, 0, 0x40) ?: return null
|
||||
if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null // "MZ"
|
||||
val peOff = u32(dos, 0x3C).toInt()
|
||||
|
||||
val coff = read(raf, peOff.toLong(), 24) ?: return null
|
||||
if (u8(coff, 0) != 0x50 || u8(coff, 1) != 0x45 || u8(coff, 2) != 0 || u8(coff, 3) != 0) return null // "PE\0\0"
|
||||
val numSections = u16(coff, 6)
|
||||
val sizeOpt = u16(coff, 20)
|
||||
if (numSections <= 0 || numSections > 96 || sizeOpt <= 0) return null
|
||||
|
||||
val optOff = peOff + 24L
|
||||
val opt = read(raf, optOff, sizeOpt) ?: return null
|
||||
val magic = u16(opt, 0)
|
||||
val ddOff = if (magic == 0x20B) 112 else 96 // PE32+ vs PE32 data-directory offset
|
||||
val resDirEntry = ddOff + 2 * 8 // data directory index 2 = resource table
|
||||
if (resDirEntry + 8 > opt.size) return null
|
||||
val resRVA = u32(opt, resDirEntry).toInt()
|
||||
val resSize = u32(opt, resDirEntry + 4).toInt()
|
||||
if (resRVA == 0 || resSize == 0) return null
|
||||
|
||||
val secTabOff = optOff + sizeOpt
|
||||
val secTab = read(raf, secTabOff, numSections * 40) ?: return null
|
||||
|
||||
var secVA = 0
|
||||
var secPtr = 0L
|
||||
var secRaw = 0
|
||||
var found = false
|
||||
for (i in 0 until numSections) {
|
||||
val o = i * 40
|
||||
if (o + 40 > secTab.size) break
|
||||
val va = u32(secTab, o + 12).toInt()
|
||||
val vSize = u32(secTab, o + 8).toInt()
|
||||
val raw = u32(secTab, o + 16).toInt()
|
||||
val pRaw = u32(secTab, o + 20)
|
||||
val span = max(vSize, raw)
|
||||
if (resRVA >= va && resRVA < va + span) {
|
||||
secVA = va; secPtr = pRaw; secRaw = raw; found = true; break
|
||||
}
|
||||
}
|
||||
if (!found || secRaw <= 0 || secRaw > MAX_RES_SECTION) return null
|
||||
|
||||
val res = read(raf, secPtr, secRaw) ?: return null
|
||||
val resDirStart = resRVA - secVA
|
||||
if (resDirStart < 0 || resDirStart + 16 > res.size) return null
|
||||
|
||||
// RT_GROUP_ICON -> first group's data entry -> GRPICONDIR
|
||||
val grpTypeDir = findIdSubdir(res, resDirStart, RT_GROUP_ICON, resDirStart) ?: return null
|
||||
val grpData = firstDataEntry(res, grpTypeDir, resDirStart) ?: return null
|
||||
val grp = dataEntryBytes(res, grpData, secVA) ?: return null
|
||||
if (grp.size < 6) return null
|
||||
|
||||
val count = u16(grp, 4)
|
||||
if (count <= 0) return null
|
||||
var bestId = -1
|
||||
var bestScore = -1L
|
||||
for (i in 0 until count) {
|
||||
val e = 6 + i * 14
|
||||
if (e + 14 > grp.size) break
|
||||
var w = u8(grp, e); if (w == 0) w = 256
|
||||
var h = u8(grp, e + 1); if (h == 0) h = 256
|
||||
val bits = u16(grp, e + 6)
|
||||
val id = u16(grp, e + 12)
|
||||
val score = w.toLong() * h * 1000 + bits
|
||||
if (score > bestScore) { bestScore = score; bestId = id }
|
||||
}
|
||||
if (bestId < 0) return null
|
||||
|
||||
// RT_ICON with the chosen id -> image bytes
|
||||
val iconTypeDir = findIdSubdir(res, resDirStart, RT_ICON, resDirStart) ?: return null
|
||||
val iconIdDir = findIdSubdir(res, iconTypeDir, bestId, resDirStart) ?: return null
|
||||
val iconData = firstDataEntry(res, iconIdDir, resDirStart) ?: return null
|
||||
val img = dataEntryBytes(res, iconData, secVA) ?: return null
|
||||
|
||||
return decodeIcon(img)
|
||||
}
|
||||
|
||||
// ── resource-directory navigation ──
|
||||
|
||||
/** Resolve the sub-directory under [dirIdx] whose id matches [wantId]; null if absent or not a directory. */
|
||||
private fun findIdSubdir(res: ByteArray, dirIdx: Int, wantId: Int, resDirStart: Int): Int? {
|
||||
if (dirIdx + 16 > res.size) return null
|
||||
val total = u16(res, dirIdx + 12) + u16(res, dirIdx + 14)
|
||||
val start = dirIdx + 16
|
||||
for (i in 0 until total) {
|
||||
val e = start + i * 8
|
||||
if (e + 8 > res.size) break
|
||||
val id = u32(res, e)
|
||||
val off = u32(res, e + 4)
|
||||
if (id and 0x80000000L == 0L && id.toInt() == wantId) {
|
||||
if (off and 0x80000000L != 0L) return resDirStart + (off and 0x7FFFFFFFL).toInt()
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Descend the first entry of each level until an IMAGE_RESOURCE_DATA_ENTRY; returns its index. */
|
||||
private fun firstDataEntry(res: ByteArray, dirIdx: Int, resDirStart: Int): Int? {
|
||||
if (dirIdx + 16 > res.size) return null
|
||||
if (u16(res, dirIdx + 12) + u16(res, dirIdx + 14) == 0) return null
|
||||
val e = dirIdx + 16
|
||||
if (e + 8 > res.size) return null
|
||||
val off = u32(res, e + 4)
|
||||
return if (off and 0x80000000L != 0L) {
|
||||
firstDataEntry(res, resDirStart + (off and 0x7FFFFFFFL).toInt(), resDirStart)
|
||||
} else {
|
||||
resDirStart + off.toInt()
|
||||
}
|
||||
}
|
||||
|
||||
/** Read the bytes an IMAGE_RESOURCE_DATA_ENTRY points at (its OffsetToData is an RVA). */
|
||||
private fun dataEntryBytes(res: ByteArray, entryIdx: Int, secVA: Int): ByteArray? {
|
||||
if (entryIdx < 0 || entryIdx + 8 > res.size) return null
|
||||
val rva = u32(res, entryIdx).toInt()
|
||||
val size = u32(res, entryIdx + 4).toInt()
|
||||
val start = rva - secVA
|
||||
if (size <= 0 || start < 0 || start + size > res.size) return null
|
||||
return res.copyOfRange(start, start + size)
|
||||
}
|
||||
|
||||
// ── icon image decoding ──
|
||||
|
||||
private fun decodeIcon(b: ByteArray): Bitmap? {
|
||||
if (b.size >= 8 && u8(b, 0) == 0x89 && u8(b, 1) == 0x50 && u8(b, 2) == 0x4E && u8(b, 3) == 0x47) {
|
||||
return runCatching { BitmapFactory.decodeByteArray(b, 0, b.size) }.getOrNull()
|
||||
}
|
||||
return runCatching { decodeDib(b) }.getOrNull()
|
||||
}
|
||||
|
||||
private fun decodeDib(b: ByteArray): Bitmap? {
|
||||
if (b.size < 40) return null
|
||||
val headerSize = u32(b, 0).toInt()
|
||||
val width = s32(b, 4)
|
||||
val heightFull = s32(b, 8)
|
||||
val height = heightFull / 2 // DIB icon height counts XOR + AND mask
|
||||
val bitCount = u16(b, 14)
|
||||
if (width <= 0 || height <= 0 || width > MAX_ICON_DIM || height > MAX_ICON_DIM) return null
|
||||
|
||||
val clrUsed = u32(b, 32).toInt()
|
||||
val numColors = if (bitCount <= 8) (if (clrUsed != 0) clrUsed else 1 shl bitCount) else 0
|
||||
val paletteOff = headerSize
|
||||
val palette = IntArray(numColors)
|
||||
for (i in 0 until numColors) {
|
||||
val o = paletteOff + i * 4
|
||||
if (o + 4 > b.size) break
|
||||
palette[i] = (0xFF shl 24) or (u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o)
|
||||
}
|
||||
|
||||
val xorStart = paletteOff + numColors * 4
|
||||
val rowSize = ((bitCount * width + 31) / 32) * 4
|
||||
val andRowSize = ((width + 31) / 32) * 4
|
||||
val andStart = xorStart + rowSize * height
|
||||
|
||||
// 32-bit icons sometimes ship an all-zero alpha channel; fall back to the AND mask then.
|
||||
var hasAlpha = false
|
||||
if (bitCount == 32) {
|
||||
var y = 0
|
||||
loop@ while (y < height && !hasAlpha) {
|
||||
var x = 0
|
||||
while (x < width) {
|
||||
val o = xorStart + y * rowSize + x * 4 + 3
|
||||
if (o < b.size && b[o].toInt() != 0) { hasAlpha = true; break@loop }
|
||||
x++
|
||||
}
|
||||
y++
|
||||
}
|
||||
}
|
||||
|
||||
val pixels = IntArray(width * height)
|
||||
for (y in 0 until height) {
|
||||
val srcRow = height - 1 - y
|
||||
for (x in 0 until width) {
|
||||
val argb: Int = when (bitCount) {
|
||||
32 -> {
|
||||
val o = xorStart + srcRow * rowSize + x * 4
|
||||
if (o + 4 > b.size) 0 else {
|
||||
val color = (u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o)
|
||||
if (hasAlpha) (u8(b, o + 3) shl 24) or color
|
||||
else maskAlpha(b, andStart, andRowSize, srcRow, x) or color
|
||||
}
|
||||
}
|
||||
24 -> {
|
||||
val o = xorStart + srcRow * rowSize + x * 3
|
||||
if (o + 3 > b.size) 0 else
|
||||
maskAlpha(b, andStart, andRowSize, srcRow, x) or
|
||||
(u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o)
|
||||
}
|
||||
8 -> {
|
||||
val o = xorStart + srcRow * rowSize + x
|
||||
val idx = if (o < b.size) u8(b, o) else 0
|
||||
val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF
|
||||
maskAlpha(b, andStart, andRowSize, srcRow, x) or col
|
||||
}
|
||||
4 -> {
|
||||
val o = xorStart + srcRow * rowSize + x / 2
|
||||
val byte = if (o < b.size) u8(b, o) else 0
|
||||
val idx = if (x % 2 == 0) byte shr 4 else byte and 0x0F
|
||||
val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF
|
||||
maskAlpha(b, andStart, andRowSize, srcRow, x) or col
|
||||
}
|
||||
1 -> {
|
||||
val o = xorStart + srcRow * rowSize + x / 8
|
||||
val byte = if (o < b.size) u8(b, o) else 0
|
||||
val idx = (byte shr (7 - x % 8)) and 1
|
||||
val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF
|
||||
maskAlpha(b, andStart, andRowSize, srcRow, x) or col
|
||||
}
|
||||
else -> return null
|
||||
}
|
||||
pixels[y * width + x] = argb
|
||||
}
|
||||
}
|
||||
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
|
||||
}
|
||||
|
||||
/** AND-mask alpha for a pixel: returns 0xFF000000 (opaque) or 0 (transparent), shifted into place. */
|
||||
private fun maskAlpha(b: ByteArray, andStart: Int, andRowSize: Int, srcRow: Int, x: Int): Int {
|
||||
val o = andStart + srcRow * andRowSize + x / 8
|
||||
if (o >= b.size) return 0xFF shl 24
|
||||
val bit = (b[o].toInt() shr (7 - x % 8)) and 1
|
||||
return if (bit == 1) 0 else (0xFF shl 24)
|
||||
}
|
||||
|
||||
// ── little-endian readers ──
|
||||
|
||||
private fun u8(b: ByteArray, off: Int): Int = b[off].toInt() and 0xFF
|
||||
private fun u16(b: ByteArray, off: Int): Int = u8(b, off) or (u8(b, off + 1) shl 8)
|
||||
private fun u32(b: ByteArray, off: Int): Long =
|
||||
u8(b, off).toLong() or (u8(b, off + 1).toLong() shl 8) or
|
||||
(u8(b, off + 2).toLong() shl 16) or (u8(b, off + 3).toLong() shl 24)
|
||||
|
||||
private fun s32(b: ByteArray, off: Int): Int = u32(b, off).toInt()
|
||||
|
||||
private fun read(raf: RandomAccessFile, pos: Long, len: Int): ByteArray? {
|
||||
if (len <= 0 || pos < 0) return null
|
||||
val fileLen = raf.length()
|
||||
if (pos >= fileLen) return null
|
||||
val n = minOf(len.toLong(), fileLen - pos).toInt()
|
||||
if (n <= 0) return null
|
||||
val buf = ByteArray(n)
|
||||
raf.seek(pos)
|
||||
raf.readFully(buf)
|
||||
return buf
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.storage.StorageManager
|
||||
import android.os.storage.StorageVolume
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* A storage volume offered in the file manager's drive menu.
|
||||
*
|
||||
* [dir] is the best path we found for the volume: its root when that is listable, otherwise the
|
||||
* deepest directory we can actually read on the way down to the app-specific directory. A volume
|
||||
* always gets exactly one entry, even if several paths lead to it.
|
||||
*/
|
||||
data class StorageRoot(
|
||||
val label: String,
|
||||
val dir: File,
|
||||
val removable: Boolean,
|
||||
/** False when no path on the volume could be listed; the entry is still shown. */
|
||||
val readable: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Enumerates mounted storage volumes.
|
||||
*
|
||||
* Listing `/storage` is not enough on its own: a volume can be absent from this process's mount
|
||||
* view (notably after a container exits and the app process is restarted onto a stale storage
|
||||
* sandbox) even though it is mounted and healthy. The framework knows about it regardless, so the
|
||||
* volume set is built from several independent sources:
|
||||
*
|
||||
* 1. [StorageManager.getStorageVolumes] - the authoritative list, read over Binder.
|
||||
* 2. [Context.getExternalFilesDirs] - per-app directories, granted separately from shared storage.
|
||||
* 3. `/storage` and `/mnt/media_rw` directory listings - the filesystem view, as a backstop.
|
||||
*
|
||||
* Those sources overlap heavily: one SD card is reachable as `/storage/<uuid>`, as
|
||||
* `/mnt/media_rw/<uuid>`, and via its app-specific directory, and typically only some of them are
|
||||
* readable. So paths are grouped by the *volume* they belong to rather than by path, and each
|
||||
* volume contributes a single entry pointing at the best path available for it.
|
||||
*/
|
||||
object StorageRoots {
|
||||
|
||||
private const val EMULATED_PREFIX = "/storage/emulated"
|
||||
private const val INTERNAL_PATH = "/storage/emulated/0"
|
||||
|
||||
/** Identifies the physical volume a path belongs to; paths sharing a key are the same card. */
|
||||
private const val PRIMARY_KEY = "primary"
|
||||
|
||||
private class Volume(val key: String) {
|
||||
var label: String? = null
|
||||
var removable: Boolean = key != PRIMARY_KEY
|
||||
/** Candidate directories, best-guess first. */
|
||||
val candidates = LinkedHashSet<File>()
|
||||
/** App-specific directories, used to find a readable path inside an unreadable root. */
|
||||
val seeds = LinkedHashSet<File>()
|
||||
}
|
||||
|
||||
fun list(context: Context): List<StorageRoot> {
|
||||
val volumes = LinkedHashMap<String, Volume>()
|
||||
|
||||
fun volumeOf(key: String) = volumes.getOrPut(key) { Volume(key) }
|
||||
|
||||
// Internal storage is never removable and never absent; seed it first so it heads the menu.
|
||||
volumeOf(PRIMARY_KEY).apply {
|
||||
label = "Internal"
|
||||
removable = false
|
||||
candidates += File(INTERNAL_PATH)
|
||||
}
|
||||
|
||||
val appDirs = appSpecificDirs(context)
|
||||
val storageManager = context.getSystemService(StorageManager::class.java)
|
||||
|
||||
// 1 + 2 - framework-reported volumes. Authoritative, and unaffected by our mount view.
|
||||
storageManager?.storageVolumes.orEmpty()
|
||||
.filter { isMounted(it.state) }
|
||||
.forEach { volume ->
|
||||
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
|
||||
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: return@forEach)
|
||||
entry.removable = !volume.isPrimary && volume.isRemovable
|
||||
if (entry.label == null) entry.label = labelFor(context, volume, uuid)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
volume.directory?.let { entry.candidates += it }
|
||||
}
|
||||
if (uuid != null) {
|
||||
entry.candidates += File("/storage/$uuid")
|
||||
// Last resort only: the raw mount is normally unreadable to an app, so it must
|
||||
// never outrank /storage/<uuid> and must never become an entry of its own.
|
||||
entry.candidates += File("/mnt/media_rw/$uuid")
|
||||
}
|
||||
appDirs.filter { belongsTo(storageManager!!, it, volume) }.forEach { entry.seeds += it }
|
||||
}
|
||||
|
||||
// 3 - filesystem backstop, for any volume the framework did not report.
|
||||
File("/storage").listFiles().orEmpty().forEach { child ->
|
||||
if (!child.isDirectory || child.name == "self" || child.name == "emulated") return@forEach
|
||||
volumeOf(child.name).candidates += child
|
||||
}
|
||||
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
|
||||
if (child.isDirectory) volumeOf(child.name).candidates += child
|
||||
}
|
||||
|
||||
// App-specific directories, which stay reachable when shared storage is not.
|
||||
appDirs.forEach { dir ->
|
||||
val root = volumeRootOf(dir) ?: return@forEach
|
||||
val entry = volumeOf(if (isEmulated(root)) PRIMARY_KEY else root.name)
|
||||
entry.candidates += root
|
||||
entry.seeds += dir
|
||||
}
|
||||
|
||||
val roots = volumes.values.map { it.toRoot() }
|
||||
val internal = roots.filter { !it.removable }
|
||||
val removable = roots.filter { it.removable }.sortedBy { it.label }
|
||||
return disambiguate(internal + removable)
|
||||
}
|
||||
|
||||
private fun Volume.toRoot(): StorageRoot {
|
||||
// Prefer a path we can actually list; a readable child beats an unreadable root.
|
||||
val dir = candidates.firstOrNull(::canBrowse)
|
||||
?: candidates.firstNotNullOfOrNull { root -> seeds.firstNotNullOfOrNull { deepestReadable(root, it) } }
|
||||
?: seeds.firstOrNull(::canBrowse)
|
||||
// Report the volume anyway; an entry that lists empty beats one that silently vanished.
|
||||
?: candidates.firstOrNull()
|
||||
?: File("/storage/$key")
|
||||
|
||||
return StorageRoot(
|
||||
label = label ?: defaultLabel(),
|
||||
dir = dir,
|
||||
removable = removable,
|
||||
readable = canBrowse(dir),
|
||||
)
|
||||
}
|
||||
|
||||
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. */
|
||||
private fun disambiguate(roots: List<StorageRoot>): List<StorageRoot> {
|
||||
val counts = roots.groupingBy { it.label }.eachCount()
|
||||
return roots.map { root ->
|
||||
if (counts.getValue(root.label) == 1) root else root.copy(label = "${root.label} (${root.dir.name})")
|
||||
}
|
||||
}
|
||||
|
||||
/** Walks up from [seed] towards [root] and returns the highest directory we can list. */
|
||||
private fun deepestReadable(root: File, seed: File): File? {
|
||||
var current: File? = seed.absoluteFile
|
||||
var best: File? = null
|
||||
while (current != null && isWithin(current, root)) {
|
||||
if (canBrowse(current)) best = current
|
||||
current = current.parentFile
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/** `/storage/ABCD-1234/Android/data/<pkg>/files` -> `/storage/ABCD-1234`. */
|
||||
private fun volumeRootOf(appDir: File): File? =
|
||||
generateSequence(appDir.absoluteFile) { it.parentFile }
|
||||
.firstOrNull { it.name.equals("Android", ignoreCase = true) }
|
||||
?.parentFile
|
||||
|
||||
private fun appSpecificDirs(context: Context): List<File> =
|
||||
context.getExternalFilesDirs(null)
|
||||
.orEmpty()
|
||||
.filterNotNull()
|
||||
.filter { isMounted(Environment.getExternalStorageState(it)) }
|
||||
|
||||
private fun belongsTo(storageManager: StorageManager, dir: File, volume: StorageVolume): Boolean {
|
||||
val owner = storageManager.getStorageVolume(dir) ?: return false
|
||||
if (owner.isPrimary != volume.isPrimary) return false
|
||||
val ownerUuid = owner.uuid
|
||||
val volumeUuid = volume.uuid
|
||||
return if (!ownerUuid.isNullOrBlank() || !volumeUuid.isNullOrBlank()) {
|
||||
ownerUuid == volumeUuid
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Names a volume the way the rest of the file manager does. The framework description is only
|
||||
* used when it says something more useful than "SD card" - on some devices it is a bare disk
|
||||
* 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 {
|
||||
if (volume.isPrimary) return "Internal"
|
||||
if (volume.isRemovable) return "SD card"
|
||||
val description = volume.getDescription(context)?.trim()
|
||||
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||
?: uuid
|
||||
?: "Storage"
|
||||
}
|
||||
|
||||
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
|
||||
|
||||
private fun isMounted(state: String?): Boolean =
|
||||
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY
|
||||
|
||||
private fun canBrowse(dir: File?): Boolean =
|
||||
dir != null && dir.isDirectory && dir.canRead() && dir.listFiles() != null
|
||||
|
||||
private fun isWithin(child: File, ancestor: File): Boolean {
|
||||
val c = canonicalPath(child)
|
||||
val a = canonicalPath(ancestor)
|
||||
return c == a || c.startsWith("$a/")
|
||||
}
|
||||
|
||||
private fun canonicalPath(file: File): String =
|
||||
try {
|
||||
file.canonicalPath
|
||||
} catch (e: Exception) {
|
||||
file.absolutePath
|
||||
}.trimEnd('/')
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.files.PeIconExtractor
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
/**
|
||||
* Artwork for an added game: what the user put in the game's folder first, else what Steam's
|
||||
* store has for the same title, fetched once into the app's cache. Four pieces, named the way
|
||||
* the client names them in its grid folder: the portrait capsule, the wide header, the hero
|
||||
* background and the logo; plus an icon pulled out of the game's own .exe. The session hands
|
||||
* the paths to the runtime's shortcuts writer, which copies them into the client's grid.
|
||||
*/
|
||||
object AddedGameArt {
|
||||
private const val TAG = "AddedGameArt"
|
||||
private const val STORE_SEARCH = "https://store.steampowered.com/api/storesearch/?l=english&cc=US&term="
|
||||
private const val CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps/"
|
||||
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
|
||||
|
||||
class Art(val portrait: File?, val header: File?, val hero: File?, val logo: File?, val icon: File?) {
|
||||
val any get() = portrait != null || header != null || hero != null || logo != null
|
||||
}
|
||||
|
||||
private val IMAGE = listOf("png", "jpg", "jpeg")
|
||||
private val PORTRAIT = listOf("cover", "poster", "grid", "boxart", "capsule", "folder", "library_600x900", "portrait")
|
||||
private val HEADER = listOf("header", "banner", "library_header", "wide")
|
||||
private val HERO = listOf("hero", "background", "library_hero")
|
||||
private val LOGO = listOf("logo")
|
||||
|
||||
private fun cacheDir(context: Context, game: AddedGames.Game) = File(context.filesDir, "added-art/${game.appId}")
|
||||
|
||||
/** An image in the folder (or its `art` subfolder) under one of the given names, any image extension. */
|
||||
private fun find(folder: File, names: List<String>): File? {
|
||||
val dirs = listOf(folder, File(folder, "art"), File(folder, ".art"))
|
||||
for (dir in dirs) for (name in names) for (ext in IMAGE) {
|
||||
val f = File(dir, "$name.$ext")
|
||||
if (f.isFile) return f
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** What the folder itself offers; the file named after the folder counts as the portrait. */
|
||||
private fun local(game: AddedGames.Game): Art {
|
||||
val folder = game.folder
|
||||
return Art(
|
||||
portrait = find(folder, PORTRAIT + listOf(folder.name)),
|
||||
header = find(folder, HEADER),
|
||||
hero = find(folder, HERO),
|
||||
logo = find(folder, LOGO),
|
||||
icon = listOf("icon.png", "icon.ico").map { File(folder, it) }.firstOrNull { it.isFile },
|
||||
)
|
||||
}
|
||||
|
||||
/** The folder's art, else the cached Steam art, without touching the network. */
|
||||
fun resolve(context: Context, game: AddedGames.Game): Art {
|
||||
val own = local(game)
|
||||
val cache = cacheDir(context, game)
|
||||
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
|
||||
return Art(
|
||||
portrait = own.portrait ?: cached("p.jpg"),
|
||||
header = own.header ?: cached("header.jpg"),
|
||||
hero = own.hero ?: cached("hero.jpg"),
|
||||
logo = own.logo ?: cached("logo.png"),
|
||||
icon = own.icon ?: exeIcon(context, game),
|
||||
)
|
||||
}
|
||||
|
||||
/** The first icon inside the game's .exe, kept as a PNG beside the cached art. */
|
||||
private fun exeIcon(context: Context, game: AddedGames.Game): File? {
|
||||
val cache = cacheDir(context, game)
|
||||
val png = File(cache, "icon.png")
|
||||
if (png.isFile) return png
|
||||
val none = File(cache, "icon.none")
|
||||
if (none.isFile) return null
|
||||
cache.mkdirs()
|
||||
val bitmap = runCatching { PeIconExtractor.extract(game.exe) }.getOrNull()
|
||||
if (bitmap == null) { none.writeText(""); return null }
|
||||
val tmp = File(cache, "icon.png.tmp")
|
||||
tmp.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
return if (tmp.renameTo(png)) png else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks the games up on Steam's store and fetches the art that is missing, once per game
|
||||
* (a miss is retried after a week). Blocking: run it off the main thread. Returns true when
|
||||
* anything new arrived.
|
||||
*/
|
||||
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean {
|
||||
if (!SessionPrefs.addedGamesArt(context)) return false
|
||||
var changed = false
|
||||
for (game in games) {
|
||||
if (local(game).portrait != null) continue
|
||||
val cache = cacheDir(context, game)
|
||||
val lookup = File(cache, "steam-appid")
|
||||
if (File(cache, "p.jpg").isFile) continue
|
||||
if (lookup.isFile && (lookup.readText().trim() != "none" || System.currentTimeMillis() - lookup.lastModified() < RETRY_AFTER_MS)) {
|
||||
val id = lookup.readText().trim()
|
||||
if (id == "none") continue
|
||||
if (download(id, cache)) changed = true
|
||||
continue
|
||||
}
|
||||
cache.mkdirs()
|
||||
val id = runCatching { search(game.name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()
|
||||
if (id == null) { lookup.writeText("none"); continue }
|
||||
lookup.writeText(id)
|
||||
Log.i(TAG, "${game.name}: Steam app $id")
|
||||
if (download(id, cache)) changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
private fun normalize(s: String) = s.lowercase().replace(Regex("[^a-z0-9]"), "")
|
||||
|
||||
/** The Steam appid whose store name matches the folder name best, or null for no match. */
|
||||
private fun search(name: String): String? {
|
||||
val term = name.replace(Regex("(?i)\\b(complete|definitive|legendary|goty|game of the year|deluxe|ultimate|remastered)( edition)?\\b"), " ").trim().ifEmpty { name }
|
||||
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
|
||||
val items = JSONObject(json).optJSONArray("items") ?: return null
|
||||
val want = normalize(name)
|
||||
val wantShort = normalize(term)
|
||||
var best: String? = null
|
||||
var bestScore = 0
|
||||
for (i in 0 until items.length()) {
|
||||
val item = items.getJSONObject(i)
|
||||
val got = normalize(item.optString("name"))
|
||||
val score = when {
|
||||
got == want -> 4
|
||||
got == wantShort -> 3
|
||||
got.startsWith(wantShort) || wantShort.startsWith(got) -> 2
|
||||
i == 0 -> 1
|
||||
else -> 0
|
||||
}
|
||||
if (score > bestScore) { bestScore = score; best = item.optString("id") }
|
||||
}
|
||||
return best?.takeIf { it.isNotEmpty() && bestScore >= 1 }
|
||||
}
|
||||
|
||||
private fun download(id: String, cache: File): Boolean {
|
||||
var got = false
|
||||
for ((remote, localName) in listOf(
|
||||
"library_600x900.jpg" to "p.jpg", "header.jpg" to "header.jpg", "library_hero.jpg" to "hero.jpg", "logo.png" to "logo.png",
|
||||
)) {
|
||||
val dst = File(cache, localName)
|
||||
if (dst.isFile) continue
|
||||
val bytes = get("$CDN$id/$remote") ?: continue
|
||||
val tmp = File(cache, "$localName.tmp")
|
||||
tmp.writeBytes(bytes)
|
||||
if (tmp.renameTo(dst)) got = true
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
private fun get(url: String): ByteArray? {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 10_000
|
||||
c.readTimeout = 15_000
|
||||
c.setRequestProperty("User-Agent", "DroidDeck-launcher")
|
||||
return try {
|
||||
if (c.responseCode != 200) null else c.inputStream.use { it.readBytes() }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "$url: ${e.message}"); null
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.util.zip.CRC32
|
||||
|
||||
/**
|
||||
* The user's own Windows games, added to the Steam client's library.
|
||||
*
|
||||
* A Games folder is scanned one level deep: each subfolder is one game, and the program to launch
|
||||
* is the .exe in it that looks most like the game - the one named after the folder, else the
|
||||
* largest, never an installer, redistributable or crash reporter - unless the user picked one
|
||||
* for that game. Each game becomes a non-Steam shortcut in the client, under the ARM64 Proton,
|
||||
* with the appid the client itself would derive, so launching from the rail and from the
|
||||
* client's own library are the same thing. Any number of Games folders, from anywhere on the
|
||||
* device: each is bound into the session under /root/Games on its own.
|
||||
*/
|
||||
object AddedGames {
|
||||
private const val TAG = "AddedGames"
|
||||
|
||||
class Game(
|
||||
val folder: File, val name: String, val exe: File, val guestExe: String, val guestDir: String,
|
||||
/** The client's 32-bit appid for this shortcut, as an unsigned value. */
|
||||
val appId: Long,
|
||||
/** What steam://rungameid/ takes for a shortcut. */
|
||||
val gameId: Long,
|
||||
val candidates: List<File>,
|
||||
) {
|
||||
fun folderName(): String = folder.name
|
||||
}
|
||||
|
||||
/** One Games folder and where the session sees it. */
|
||||
class Root(val host: File, val guest: String)
|
||||
|
||||
/**
|
||||
* The chosen folders with their guest paths: /root/Games/<folder name>, or with a short hash of
|
||||
* the host path when two chosen folders share a name (so a folder's guest path, and with it
|
||||
* every shortcut's appid, does not change when another folder is added or removed).
|
||||
*/
|
||||
fun roots(context: Context): List<Root> {
|
||||
val hosts = SessionPrefs.addedGamesDirs(context).map { File(it) }
|
||||
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
||||
return hosts.map { host ->
|
||||
val name = host.name.ifEmpty { "games" }
|
||||
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
||||
Root(host, "$GUEST_DIR/$guestName")
|
||||
}
|
||||
}
|
||||
|
||||
private val SKIP = Regex(
|
||||
"(?i)^(unins.*|setup.*|.*redist.*|vcredist.*|dxsetup.*|dxwebsetup.*|.*crash.*|.*report.*|dotnet.*|directx.*|.*prereq.*" +
|
||||
"|.*installer.*|.*uninstall.*|.*updater?.*|.*config(ur.*)?|.*settings.*|.*editor.*|.*server.*|.*benchmark.*|.*helper.*|.*eac.*|.*easyanticheat.*|.*battleye.*)\\.exe$",
|
||||
)
|
||||
|
||||
/** Where a host path appears inside the session, or null when the session cannot see it. */
|
||||
/** Under here the chosen Games folders are bound inside the session, one each. */
|
||||
const val GUEST_DIR = "/root/Games"
|
||||
|
||||
fun guestPath(context: Context, host: File): String? {
|
||||
val path = host.absolutePath
|
||||
// The Games folders are bound on their own, so a folder anywhere - an SD card, a USB
|
||||
// drive - works without being inside one of the other binds.
|
||||
for (root in roots(context)) {
|
||||
val dir = root.host.absolutePath
|
||||
if (path == dir) return root.guest
|
||||
if (path.startsWith("$dir/")) return root.guest + "/" + path.removePrefix("$dir/")
|
||||
}
|
||||
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let { roms ->
|
||||
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
|
||||
}
|
||||
GameStorage.effective(context)?.let { lib ->
|
||||
if (path.startsWith("${lib.path}/")) return "/mnt/bannerlator-sd/" + path.removePrefix("${lib.path}/")
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The .exe files a game folder offers, best first. */
|
||||
fun candidates(folder: File): List<File> {
|
||||
val exes = ArrayList<File>()
|
||||
val roots = listOf(folder) + (folder.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList())
|
||||
for (dir in roots) {
|
||||
dir.listFiles { f -> f.isFile && f.name.endsWith(".exe", ignoreCase = true) && !SKIP.matches(f.name) }
|
||||
?.let { exes.addAll(it) }
|
||||
}
|
||||
val key = folder.name.lowercase().replace(Regex("[^a-z0-9]"), "")
|
||||
return exes.sortedWith(
|
||||
compareByDescending<File> { it.parentFile == folder }
|
||||
.thenByDescending { it.nameWithoutExtension.lowercase().replace(Regex("[^a-z0-9]"), "").let { n -> n == key || key.startsWith(n) || n.startsWith(key) } }
|
||||
.thenByDescending { it.length() },
|
||||
)
|
||||
}
|
||||
|
||||
fun scan(context: Context): List<Game> {
|
||||
val out = ArrayList<Game>()
|
||||
for (root in roots(context)) {
|
||||
val dir = root.host
|
||||
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
|
||||
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) scanGame(context, folder, out)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
|
||||
run {
|
||||
val candidates = candidates(folder)
|
||||
val chosen = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||
val exe = chosen ?: candidates.firstOrNull() ?: return
|
||||
val guestExe = guestPath(context, exe)
|
||||
if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return }
|
||||
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
|
||||
val name = folder.name
|
||||
val crc = CRC32().apply { update(("\"$guestExe\"" + name).toByteArray()) }.value
|
||||
val appId = crc or 0x80000000L
|
||||
out.add(Game(folder, name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, candidates))
|
||||
}
|
||||
}
|
||||
|
||||
/** The list the session hands the runtime's shortcuts writer; one file per session start. */
|
||||
fun writeListing(context: Context, games: List<Game>): File {
|
||||
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
||||
val json = StringBuilder("[")
|
||||
games.forEachIndexed { i, g ->
|
||||
if (i > 0) json.append(',')
|
||||
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
|
||||
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
|
||||
// The art, as the session sees it: the app's cache is bound at its own path, a file in
|
||||
// the game's folder at the folder's guest path.
|
||||
val art = AddedGameArt.resolve(context, g)
|
||||
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
|
||||
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
|
||||
if (pieces.isNotEmpty()) json.append(",\"art\":{").append(pieces.joinToString(",") { (k, v) -> quote(k) + ":" + quote(v) }).append('}')
|
||||
json.append('}')
|
||||
}
|
||||
file.writeText(json.append(']').toString())
|
||||
return file
|
||||
}
|
||||
|
||||
private fun artGuestPath(context: Context, file: File): String? {
|
||||
val files = context.filesDir.absolutePath
|
||||
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
|
||||
return guestPath(context, file)
|
||||
}
|
||||
|
||||
private fun quote(s: String) = "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* What the front end lists: the Steam client's installed games (from its own appmanifests, both
|
||||
* libraries) and each emulator's games (files in the ROMs folder, by extension, with a system
|
||||
* folder as a hint). Read on a worker thread; nothing here is cached beyond one screen refresh.
|
||||
*/
|
||||
object Library {
|
||||
/** [gameId] is what steam://rungameid/ takes: the appid for a Steam title, the shortcut id for an added game. */
|
||||
class SteamGame(val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong())
|
||||
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>) {
|
||||
/** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */
|
||||
val iconRes: Int get() = when (id) {
|
||||
"rpcs3" -> R.drawable.emu_rpcs3; "pcsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
|
||||
"duckstation" -> R.drawable.emu_duckstation; "melonds" -> R.drawable.emu_melonds; "cemu" -> R.drawable.emu_cemu
|
||||
"ppsspp" -> R.drawable.emu_ppsspp; else -> R.drawable.emu_retroarch
|
||||
}
|
||||
}
|
||||
|
||||
/** The client's own tools and runtimes live in steamapps beside the games; they are not titles. */
|
||||
private val NOT_GAMES = setOf(228980, 1493710, 3127680, 4183110, 4427310, 4185400)
|
||||
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
||||
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
||||
|
||||
fun steamGames(context: Context): List<SteamGame> {
|
||||
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||
val cache = File(root, "appcache/librarycache")
|
||||
val libraries = listOfNotNull(
|
||||
root to "internal",
|
||||
GameStorage.effective(context)?.let { File(it.path) to it.label },
|
||||
)
|
||||
val out = LinkedHashMap<Int, SteamGame>()
|
||||
for ((library, label) in libraries) {
|
||||
val steamapps = File(library, "steamapps")
|
||||
steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }
|
||||
?.sortedBy { it.name }?.forEach { manifest ->
|
||||
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
|
||||
if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach
|
||||
val text = try { manifest.readText() } catch (e: Exception) { return@forEach }
|
||||
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
|
||||
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||
// StateFlags 4 = fully installed; anything else is downloading, updating or broken.
|
||||
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
||||
val dir = File(cache, appId.toString())
|
||||
val art = listOf("library_600x900.jpg", "logo.png", "library_header.jpg", "header.jpg")
|
||||
.map { File(dir, it) }.firstOrNull { it.isFile }
|
||||
out[appId] = SteamGame(appId, name, art, label)
|
||||
}
|
||||
}
|
||||
return out.values.toList()
|
||||
}
|
||||
|
||||
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>)
|
||||
private val specs = listOf(
|
||||
Spec("rpcs3", "RPCS3", "PS3", "/opt/appimages/rpcs3.AppImage", listOf("ps3"), setOf("iso")),
|
||||
Spec("pcsx2", "PCSX2", "PS2", "/opt/appimages/pcsx2.AppImage", listOf("ps2"), setOf("iso", "chd", "cso", "gz")),
|
||||
Spec("dolphin", "Dolphin", "GameCube / Wii", "/opt/appimages/dolphin.AppImage", listOf("gc", "gamecube", "wii"), setOf("iso", "rvz", "gcz", "wbfs", "ciso")),
|
||||
Spec("duckstation", "DuckStation", "PS1", "/opt/appimages/duckstation.AppImage", listOf("ps1", "psx"), setOf("cue", "chd", "pbp", "iso", "bin", "img", "ecm", "m3u")),
|
||||
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi")),
|
||||
Spec("cemu", "Cemu", "Wii U", "/opt/appimages/cemu.AppImage", listOf("wiiu", "wii u"), setOf("wua", "wud", "wux", "rpx")),
|
||||
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
|
||||
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
|
||||
)
|
||||
private val installedIds = mapOf(
|
||||
"rpcs3" to "rpcs3", "pcsx2" to "pcsx2", "dolphin" to "dolphin", "duckstation" to "duckstation",
|
||||
"melonds" to "melonds", "cemu" to "cemu", "ppsspp" to "emulators", "retroarch" to "emulators",
|
||||
)
|
||||
|
||||
/** Desktop catalog package that supplies this emulator. */
|
||||
fun packageId(emulatorId: String): String? = installedIds[emulatorId]
|
||||
|
||||
/** Every emulator the app knows, installed or not, with the games its system folder holds. */
|
||||
fun emulators(context: Context, installedPackage: (String) -> Boolean): List<Emulator> {
|
||||
val romsRoot = SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
|
||||
return specs.map { spec ->
|
||||
val games = ArrayList<Rom>()
|
||||
if (romsRoot != null && spec.exts.isNotEmpty()) {
|
||||
// The system's folder(s), matched without regard to case, then the root itself for
|
||||
// a file left loose there - and one folder deeper, since a dump usually comes as a
|
||||
// folder named for the game with the image inside it.
|
||||
val systemDirs = romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() in spec.folders }.orEmpty().toList()
|
||||
val dirs = LinkedHashSet<File>()
|
||||
for (top in systemDirs + romsRoot) {
|
||||
dirs.add(top)
|
||||
top.listFiles { f -> f.isDirectory }?.forEach { dirs.add(it) }
|
||||
}
|
||||
for (dir in dirs) {
|
||||
// A PS3 disc dump is a folder with PS3_GAME in it; RPCS3 boots the folder.
|
||||
if (spec.id == "rpcs3" && File(dir, "PS3_GAME").isDirectory) {
|
||||
val rel = dir.relativeTo(romsRoot).path
|
||||
games.add(Rom(dir.name, dir, "/root/ROMs/$rel", spec.id))
|
||||
continue
|
||||
}
|
||||
dir.listFiles()?.sortedBy { it.name.lowercase() }?.forEach { f ->
|
||||
val ext = f.extension.lowercase()
|
||||
// A .bin beside a .cue is a track, not a game.
|
||||
if (f.isFile && ext in spec.exts && !(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) {
|
||||
val rel = f.relativeTo(romsRoot).path
|
||||
games.add(Rom(f.nameWithoutExtension.removeSuffix(".dec"), f, "/root/ROMs/$rel", spec.id))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (spec.id == "rpcs3") games.addAll(rpcs3Installed(context))
|
||||
Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), games)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What RPCS3 has installed on its own HDD - packages (PSN games) land in dev_hdd0/game/<ID>
|
||||
* with a PARAM.SFO for the title and an EBOOT to boot - as RPCS3's own file list would show
|
||||
* them. Not in the ROMs folder, so listed from RPCS3's home in the runtime.
|
||||
*/
|
||||
private fun rpcs3Installed(context: Context): List<Rom> {
|
||||
val hdd = File(LinuxRuntime.rootDir(context), "root/.config/rpcs3/dev_hdd0/game")
|
||||
return hdd.listFiles { f -> f.isDirectory }?.sortedBy { it.name }?.mapNotNull { dir ->
|
||||
val eboot = File(dir, "USRDIR/EBOOT.BIN")
|
||||
val sfo = File(dir, "PARAM.SFO")
|
||||
if (!eboot.isFile || !sfo.isFile) return@mapNotNull null
|
||||
val fields = readSfo(sfo)
|
||||
// Only games: patches, DLC and save data live here too, with their own categories.
|
||||
if (fields["CATEGORY"]?.let { it == "HG" || it == "DG" || it == "GD" } == false) return@mapNotNull null
|
||||
val title = fields["TITLE"]?.trim()?.takeIf { it.isNotEmpty() } ?: dir.name
|
||||
Rom(title, eboot, "/root/.config/rpcs3/dev_hdd0/game/${dir.name}/USRDIR/EBOOT.BIN", "rpcs3",
|
||||
art = File(dir, "ICON0.PNG").takeIf { it.isFile })
|
||||
} ?: emptyList()
|
||||
}
|
||||
|
||||
/** The string fields of a PARAM.SFO (the PSP/PS3 metadata file): a small binary table. */
|
||||
private fun readSfo(file: File): Map<String, String> {
|
||||
val out = HashMap<String, String>()
|
||||
try {
|
||||
val b = file.readBytes()
|
||||
if (b.size < 20 || b[0] != 0.toByte() || b[1] != 'P'.code.toByte()) return out
|
||||
fun u32(at: Int) = (b[at].toInt() and 0xff) or ((b[at + 1].toInt() and 0xff) shl 8) or ((b[at + 2].toInt() and 0xff) shl 16) or ((b[at + 3].toInt() and 0xff) shl 24)
|
||||
fun u16(at: Int) = (b[at].toInt() and 0xff) or ((b[at + 1].toInt() and 0xff) shl 8)
|
||||
val keys = u32(8); val data = u32(12); val count = u32(16)
|
||||
for (i in 0 until count) {
|
||||
val e = 20 + i * 16
|
||||
if (e + 16 > b.size) break
|
||||
val keyOff = u16(e); val fmt = u16(e + 2); val len = u32(e + 4); val dataOff = u32(e + 12)
|
||||
val keyStart = keys + keyOff
|
||||
var keyEnd = keyStart
|
||||
while (keyEnd < b.size && b[keyEnd] != 0.toByte()) keyEnd++
|
||||
val key = String(b, keyStart, keyEnd - keyStart, Charsets.US_ASCII)
|
||||
if (fmt == 0x0204 || fmt == 0x0004) { // utf8 string (null-terminated or not)
|
||||
val start = data + dataOff
|
||||
val end = minOf(b.size, start + len)
|
||||
var stop = start
|
||||
while (stop < end && b[stop] != 0.toByte()) stop++
|
||||
out[key] = String(b, start, stop - start, Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// unreadable metadata: the folder name stands in
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** How the emulator is told which game to boot, on its command line. */
|
||||
fun launchArgs(emulatorId: String, guestPath: String): List<String> = when (emulatorId) {
|
||||
"rpcs3" -> listOf("--no-gui", guestPath)
|
||||
"dolphin" -> listOf("-e", guestPath)
|
||||
"cemu" -> listOf("-g", guestPath)
|
||||
else -> listOf(guestPath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
|
||||
/**
|
||||
* The frame-generation setting and how it reaches the compositor.
|
||||
*
|
||||
* Both engines generate on gamescope's final output inside our compositor, so they work for any
|
||||
* game with nothing changed in the runtime. Win-FG is our own and needs nothing; LSFG needs the
|
||||
* shader chain from the user's copy of Lossless Scaling (see [LsfgNative]). Every compositor
|
||||
* setter is a value store on the native side, so this can be applied before the compositor is
|
||||
* up and changed live from the main screen while a session runs.
|
||||
*/
|
||||
object FrameGen {
|
||||
const val ENGINE_OFF = "off"
|
||||
const val ENGINE_WINFG = "winfg"
|
||||
const val ENGINE_LSFG = "lsfg"
|
||||
|
||||
/** Win-FG's Performance preset, pinned: changing it live rebuilds the whole chain. */
|
||||
private const val WINFG_PERF_PRESET = 2
|
||||
/** Bidirectional flow with the occlusion gate - the chain's own default. */
|
||||
private const val WINFG_MODEL = 4
|
||||
/** Optical-flow resolution as a fraction of the output; Bannerlator's per-engine defaults. */
|
||||
private const val FLOW_SCALE_WINFG = 0.60f
|
||||
private const val FLOW_SCALE_LSFG = 0.80f
|
||||
|
||||
private const val PREFS = "frame_gen"
|
||||
|
||||
fun engine(context: Context): String =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("engine", ENGINE_OFF) ?: ENGINE_OFF
|
||||
|
||||
fun multiplier(context: Context): Int =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getInt("multiplier", 2).coerceIn(2, 4)
|
||||
|
||||
fun set(context: Context, engine: String, multiplier: Int) {
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||
.putString("engine", engine).putInt("multiplier", multiplier).apply()
|
||||
}
|
||||
|
||||
/** "Off", "Win-FG 2×", "LSFG 3×" - for the main screen. */
|
||||
fun label(context: Context): String = when (engine(context)) {
|
||||
ENGINE_WINFG -> "Win-FG ${multiplier(context)}×"
|
||||
ENGINE_LSFG -> "LSFG ${multiplier(context)}×"
|
||||
else -> "Off"
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes the saved setting into the compositor. Returns a message for the user when the
|
||||
* engine cannot run (LSFG without Lossless Scaling), or null.
|
||||
*/
|
||||
fun apply(context: Context, refreshHz: Float): String? {
|
||||
val engine = engine(context)
|
||||
val multiplier = multiplier(context)
|
||||
var problem: String? = null
|
||||
when (engine) {
|
||||
ENGINE_LSFG -> {
|
||||
val status = LsfgNative.ensureCache(context)
|
||||
if (status != LsfgNative.STATUS_OK) {
|
||||
problem = if (status == LsfgNative.STATUS_NOT_INSTALLED)
|
||||
"LSFG needs Lossless Scaling installed from the Steam client"
|
||||
else "LSFG: " + LsfgNative.statusName(status)
|
||||
Log.w(TAG, problem)
|
||||
WaylandCompositor.nativeSetFrameGenArmed(false, 0)
|
||||
return problem
|
||||
}
|
||||
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG)
|
||||
WaylandCompositor.nativeSetLsfgCachePath(LsfgNative.cacheFile(context).absolutePath)
|
||||
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz)
|
||||
WaylandCompositor.nativeSetFrameGenArmed(true, multiplier)
|
||||
}
|
||||
ENGINE_WINFG -> {
|
||||
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_WINFG)
|
||||
WaylandCompositor.nativeSetWinFgTuning(WINFG_MODEL, WINFG_PERF_PRESET)
|
||||
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_WINFG, refreshHz)
|
||||
WaylandCompositor.nativeSetFrameGenArmed(true, multiplier)
|
||||
}
|
||||
else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0)
|
||||
}
|
||||
Log.i(TAG, "frame generation: $engine x$multiplier at ${refreshHz}Hz")
|
||||
return problem
|
||||
}
|
||||
|
||||
/**
|
||||
* Off, or an engine at 2x/3x/4x; saved on pick, then [onChanged]. The LSFG rows are greyed
|
||||
* and unpickable until Lossless Scaling is installed in the Steam client - the engine cannot
|
||||
* run without its DLL, so offering it would only produce a setting that silently does nothing.
|
||||
*/
|
||||
fun showPicker(activity: android.app.Activity, onChanged: () -> Unit) {
|
||||
val lsfgReady = LsfgNative.isInstalled(activity)
|
||||
val lsfgNote = if (lsfgReady) "" else " - install Lossless Scaling in Steam"
|
||||
val choices = listOf("Off",
|
||||
"Win-FG 2×", "Win-FG 3×", "Win-FG 4×",
|
||||
"LSFG 2×$lsfgNote", "LSFG 3×$lsfgNote", "LSFG 4×$lsfgNote")
|
||||
val current = when (engine(activity)) {
|
||||
ENGINE_WINFG -> multiplier(activity) - 1
|
||||
ENGINE_LSFG -> if (lsfgReady) multiplier(activity) + 2 else 0
|
||||
else -> 0
|
||||
}
|
||||
val adapter = object : android.widget.ArrayAdapter<String>(
|
||||
activity, android.R.layout.simple_list_item_single_choice, choices) {
|
||||
override fun isEnabled(position: Int) = lsfgReady || position < 4
|
||||
override fun areAllItemsEnabled() = lsfgReady
|
||||
override fun getView(position: Int, convertView: android.view.View?, parent: android.view.ViewGroup): android.view.View {
|
||||
val view = super.getView(position, convertView, parent)
|
||||
view.isEnabled = isEnabled(position)
|
||||
view.alpha = if (isEnabled(position)) 1f else 0.38f
|
||||
return view
|
||||
}
|
||||
}
|
||||
android.app.AlertDialog.Builder(activity)
|
||||
.setTitle(com.droiddeck.launcher.R.string.frame_gen_title)
|
||||
.setSingleChoiceItems(adapter, current) { dialog, which ->
|
||||
when (which) {
|
||||
0 -> set(activity, ENGINE_OFF, 2)
|
||||
in 1..3 -> set(activity, ENGINE_WINFG, which + 1)
|
||||
else -> set(activity, ENGINE_LSFG, which - 2)
|
||||
}
|
||||
dialog.dismiss()
|
||||
onChanged()
|
||||
}
|
||||
.setNeutralButton(android.R.string.ok, null)
|
||||
.show()
|
||||
}
|
||||
|
||||
private const val TAG = "FrameGen"
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.droiddeck.launcher.gpu;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The Vulkan driver a session draws with inside the runtime: in Steam mode the native client's
|
||||
* own UI (OpenGL through the runtime's Zink), every game it launches (D3D through Proton's
|
||||
* DXVK/VKD3D) and gamescope's compositing; in desktop mode every program on the desktop. One
|
||||
* choice per mode covers all of it.
|
||||
*
|
||||
* <p>Distinct from the Android driver the app's compositor loads to put the finished frame on the
|
||||
* screen ({@link TurnipDriver}), which every session ends in - and NOT interchangeable with it:
|
||||
* these are glibc processes, that one is bionic.
|
||||
*
|
||||
* <p>"" (the default) means the driver the runtime was built with, at
|
||||
* {@code usr/lib/libvulkan_freedreno.so} inside it - nothing is set and nothing is touched.
|
||||
* Otherwise the value is an imported driver's id ({@link LinuxVulkanDriverManager}), and the
|
||||
* session is handed that driver's ICD manifest in {@code BL_VK_DRIVER}: the session script points
|
||||
* the Vulkan loader at it with {@code VK_DRIVER_FILES} after checking both the manifest and the
|
||||
* library are readable from inside, so the runtime itself is never modified and the choice is
|
||||
* reversible. Ported from Bannerlator's {@code LinuxVulkanDriver} (GPL-3.0); the choice lives in
|
||||
* {@code SessionPrefs} per mode here rather than on a shortcut.
|
||||
*/
|
||||
public final class LinuxVulkanDriver {
|
||||
private static final String TAG = "LinuxVulkanDriver";
|
||||
/** Env var the session reads; its value is an absolute ICD manifest path. */
|
||||
public static final String ENV = "BL_VK_DRIVER";
|
||||
|
||||
public static final String HELP_TEXT =
|
||||
"The driver the Steam client, the games it launches and the desktop's programs render on, "
|
||||
+ "inside the Linux runtime. Imported \"-Linux\" Turnip zips only: these are Linux processes "
|
||||
+ "and cannot load an Android or Wayland driver. Frames still reach the screen through the "
|
||||
+ "display driver below. Takes effect at the next session start.";
|
||||
|
||||
private LinuxVulkanDriver() {}
|
||||
|
||||
/** Stored values in editor order: the runtime's own driver, then each imported one. */
|
||||
public static List<String> optionValues(Context context) {
|
||||
ArrayList<String> values = new ArrayList<>();
|
||||
values.add("");
|
||||
values.addAll(new LinuxVulkanDriverManager(context).enumerateInstalledDrivers());
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Label for a stored value. An id that is no longer installed says so - the launch path falls
|
||||
* back to the runtime's own driver for it.
|
||||
*/
|
||||
public static String optionLabel(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
|
||||
String ver = m.getDriverVersion(value);
|
||||
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
|
||||
}
|
||||
|
||||
/**
|
||||
* The ICD manifest path to hand the session, or null to leave the runtime's own driver alone.
|
||||
* An id whose import is gone resolves to null rather than failing the launch.
|
||||
*/
|
||||
public static String resolveIcdPath(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return null;
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
String icd = m.getIcdPath(value);
|
||||
if (icd == null) {
|
||||
Log.w(TAG, "imported Linux driver \"" + value + "\" is gone; using the runtime's own driver");
|
||||
return null;
|
||||
}
|
||||
Log.i(TAG, "Linux session draws with imported driver " + value + " (" + icd + ")");
|
||||
return icd;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package com.droiddeck.launcher.gpu;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.Uri;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/**
|
||||
* Imported LINUX Vulkan drivers: glibc Turnip ICDs ({@code Turnip-<tag>[-variant]-Linux.zip} from
|
||||
* Banners-Turnip) for the runtime - the gamescope session that runs Valve's native ARM64 Steam
|
||||
* client, and the labwc desktop beside it. This is the driver that DRAWS there: the client's own UI
|
||||
* (OpenGL through the runtime's Zink), every game the client launches (D3D through Proton's
|
||||
* DXVK/VKD3D) and everything on the desktop. Putting the frame on the screen stays the Android
|
||||
* driver's job, in the app's compositor ({@link TurnipDriver}).
|
||||
*
|
||||
* <p>Not interchangeable with that one: the client and its games are glibc processes and cannot
|
||||
* load a bionic object at all, and this one cannot be loaded by the app. The check that separates
|
||||
* them is the libc the driver links against - {@code libc.so.6} here, {@code libc.so} there.
|
||||
*
|
||||
* <p>Layout (under the app's files dir, which the session sees by its full host path):
|
||||
* <pre>
|
||||
* files/linux_vulkan_drivers/<id>/
|
||||
* libvulkan_freedreno.so the driver
|
||||
* icd.json generated Vulkan ICD manifest; library_path = the .so's ABSOLUTE path
|
||||
* meta.json name / driverVersion / minGlibc, our own schema
|
||||
* </pre>
|
||||
* The session gets {@code icd.json}'s path in {@code BL_VK_DRIVER} and exports it as
|
||||
* {@code VK_DRIVER_FILES}, so nothing inside the runtime is modified and the choice is reversible.
|
||||
*
|
||||
* <p>Ported from Bannerlator's {@code LinuxVulkanDriverManager} (GPL-3.0), unchanged in behaviour.
|
||||
*/
|
||||
public class LinuxVulkanDriverManager {
|
||||
private static final String TAG = "LinuxVulkanDriver";
|
||||
public static final String DIR_NAME = "linux_vulkan_drivers";
|
||||
public static final String LIB_NAME = "libvulkan_freedreno.so";
|
||||
public static final String ICD_NAME = "icd.json";
|
||||
public static final String META_NAME = "meta.json";
|
||||
|
||||
private final Context context;
|
||||
private final File rootDir;
|
||||
|
||||
public LinuxVulkanDriverManager(Context context) {
|
||||
this.context = context;
|
||||
this.rootDir = new File(context.getFilesDir(), DIR_NAME);
|
||||
if (!rootDir.exists()) rootDir.mkdirs();
|
||||
}
|
||||
|
||||
public File getDriverDir(String id) {
|
||||
return new File(rootDir, id);
|
||||
}
|
||||
|
||||
/** Installed = has the .so AND the generated manifest (a half-extracted dir is never offered). */
|
||||
public boolean isInstalled(String id) {
|
||||
if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return false;
|
||||
File dir = getDriverDir(id);
|
||||
return new File(dir, LIB_NAME).isFile() && new File(dir, ICD_NAME).isFile();
|
||||
}
|
||||
|
||||
/** Absolute path of the driver's ICD manifest, or null when the id isn't installed. */
|
||||
public String getIcdPath(String id) {
|
||||
return isInstalled(id) ? new File(getDriverDir(id), ICD_NAME).getAbsolutePath() : null;
|
||||
}
|
||||
|
||||
public List<String> enumerateInstalledDrivers() {
|
||||
ArrayList<String> ids = new ArrayList<>();
|
||||
File[] dirs = rootDir.listFiles();
|
||||
if (dirs == null) return ids;
|
||||
for (File d : dirs) if (d.isDirectory() && isInstalled(d.getName())) ids.add(d.getName());
|
||||
Collections.sort(ids);
|
||||
return ids;
|
||||
}
|
||||
|
||||
private JSONObject readMeta(String id) {
|
||||
try {
|
||||
File meta = new File(getDriverDir(id), META_NAME);
|
||||
if (!meta.isFile()) return null;
|
||||
return new JSONObject(FileUtils.readString(meta));
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String getDriverName(String id) {
|
||||
JSONObject m = readMeta(id);
|
||||
String name = m != null ? m.optString("name", "") : "";
|
||||
return name.isEmpty() ? id : name;
|
||||
}
|
||||
|
||||
public String getDriverVersion(String id) {
|
||||
JSONObject m = readMeta(id);
|
||||
return m != null ? m.optString("driverVersion", "") : "";
|
||||
}
|
||||
|
||||
/** The glibc the driver asks for, as its zip recorded it ("" when the zip did not say). */
|
||||
public String getMinGlibc(String id) {
|
||||
JSONObject m = readMeta(id);
|
||||
return m != null ? m.optString("minGlibc", "") : "";
|
||||
}
|
||||
|
||||
public void removeDriver(String id) {
|
||||
if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return;
|
||||
Log.d(TAG, "removing imported Linux Vulkan driver " + id);
|
||||
FileUtils.delete(getDriverDir(id));
|
||||
// A mode still set to this id falls back to the runtime's own driver at launch (logged there).
|
||||
}
|
||||
|
||||
/**
|
||||
* Import a {@code -Linux.zip}. Returns the new driver id.
|
||||
* @throws IllegalArgumentException with a user-facing reason when the zip is not an importable
|
||||
* Linux driver; {@link IOException} on read/extract failures.
|
||||
*/
|
||||
public String installDriver(Uri zipUri, String displayName) throws IOException {
|
||||
File tmpDir = new File(rootDir, ".tmp-" + System.currentTimeMillis());
|
||||
FileUtils.delete(tmpDir);
|
||||
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
|
||||
boolean keep = false;
|
||||
try {
|
||||
String soName = null;
|
||||
JSONObject zipMeta = null;
|
||||
try (InputStream is = context.getContentResolver().openInputStream(zipUri);
|
||||
ZipInputStream zis = new ZipInputStream(is)) {
|
||||
if (is == null) throw new IOException("cannot open " + zipUri);
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
if (entry.isDirectory()) continue;
|
||||
// Flatten: only the base name matters, and it also defeats zip-slip paths.
|
||||
String base = new File(entry.getName()).getName();
|
||||
if (base.isEmpty()) continue;
|
||||
if (base.startsWith("libvulkan_freedreno") && base.endsWith(".so")) {
|
||||
if (soName != null) Log.w(TAG, "zip has several libvulkan_freedreno*.so; using the first (" + soName + ")");
|
||||
else {
|
||||
Files.copy(zis, new File(tmpDir, LIB_NAME).toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
soName = base;
|
||||
}
|
||||
} else if (base.equals(META_NAME)) {
|
||||
try {
|
||||
zipMeta = new JSONObject(new String(readAll(zis), StandardCharsets.UTF_8));
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "meta.json unreadable, ignoring: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
// The zip's own freedreno_icd.aarch64.json is dropped on purpose: its
|
||||
// library_path is relative to itself, and we write an absolute one below.
|
||||
}
|
||||
}
|
||||
if (soName == null) {
|
||||
throw new IllegalArgumentException("No libvulkan_freedreno*.so in this zip. An Android "
|
||||
+ "(AdrenoTools) or -Wayland Turnip zip is not a Linux runtime driver.");
|
||||
}
|
||||
File so = new File(tmpDir, LIB_NAME);
|
||||
if (!isAarch64Elf(so)) {
|
||||
throw new IllegalArgumentException(soName + " is not a 64-bit AArch64 ELF shared library.");
|
||||
}
|
||||
// The one check that actually separates this from the bionic builds. Both sonames
|
||||
// are in the driver's .dynstr, so a byte scan is enough and needs no ELF parsing:
|
||||
// glibc's is versioned ("libc.so.6"), bionic's is not ("libc.so").
|
||||
if (!containsAscii(so, "libc.so.6")) {
|
||||
throw new IllegalArgumentException(soName + " is not a glibc driver - it links Android's libc. "
|
||||
+ "The Linux runtime needs a \"-Linux\" zip; a plain or \"-Wayland\" Turnip cannot be "
|
||||
+ "loaded by the Steam client at all.");
|
||||
}
|
||||
String kind = zipMeta != null ? zipMeta.optString("kind", "") : "";
|
||||
if (!kind.isEmpty() && !"linux-vulkan-icd".equals(kind)) {
|
||||
Log.w(TAG, "meta.json says kind=" + kind + ", importing anyway (the binary is glibc)");
|
||||
}
|
||||
|
||||
String name = zipMeta != null ? zipMeta.optString("name", "") : "";
|
||||
String version = zipMeta != null ? zipMeta.optString("driverVersion", "") : "";
|
||||
String minGlibc = zipMeta != null ? zipMeta.optString("minGlibc", "") : "";
|
||||
if (name.isEmpty()) {
|
||||
name = displayName != null ? displayName : "linux-driver";
|
||||
if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4);
|
||||
}
|
||||
String id = uniqueId(sanitizeId(name));
|
||||
File dir = getDriverDir(id);
|
||||
|
||||
// ICD manifest: absolute library_path, so the loader never depends on cwd and the guest
|
||||
// reads it at the same path the app wrote (the files dir is bound into the session).
|
||||
JSONObject icd = new JSONObject();
|
||||
icd.put("file_format_version", "1.0.0");
|
||||
JSONObject icdBody = new JSONObject();
|
||||
icdBody.put("library_path", new File(dir, LIB_NAME).getAbsolutePath());
|
||||
icdBody.put("api_version", "1.1.274");
|
||||
icd.put("ICD", icdBody);
|
||||
if (!FileUtils.writeString(new File(tmpDir, ICD_NAME), icd.toString(2))) throw new IOException("cannot write icd.json");
|
||||
|
||||
JSONObject meta = new JSONObject();
|
||||
meta.put("schemaVersion", 1);
|
||||
meta.put("kind", "linux-vulkan-icd");
|
||||
meta.put("name", name);
|
||||
meta.put("driverVersion", version);
|
||||
meta.put("libc", "glibc");
|
||||
meta.put("minGlibc", minGlibc);
|
||||
meta.put("sourceLibraryName", soName);
|
||||
meta.put("importedAt", System.currentTimeMillis());
|
||||
if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json");
|
||||
|
||||
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
|
||||
keep = true;
|
||||
Log.i(TAG, "imported Linux Vulkan driver " + id + " (" + soName + ", minGlibc=" + minGlibc + ") -> " + dir);
|
||||
return id;
|
||||
} catch (org.json.JSONException e) {
|
||||
throw new IOException("manifest write failed: " + e.getMessage());
|
||||
} finally {
|
||||
if (!keep) FileUtils.delete(tmpDir);
|
||||
}
|
||||
}
|
||||
|
||||
private String uniqueId(String base) {
|
||||
String id = base;
|
||||
int n = 2;
|
||||
while (getDriverDir(id).exists()) id = base + "-" + (n++);
|
||||
return id;
|
||||
}
|
||||
|
||||
static String sanitizeId(String name) {
|
||||
String s = name.trim().replaceAll("[^A-Za-z0-9._-]+", "_").replaceAll("^[._]+", "");
|
||||
if (s.length() > 64) s = s.substring(0, 64);
|
||||
return s.isEmpty() ? "linux-driver" : s;
|
||||
}
|
||||
|
||||
/** ELF magic, EI_CLASS = 64-bit, EI_DATA = little-endian, e_machine = 0xB7 (AArch64). */
|
||||
static boolean isAarch64Elf(File f) {
|
||||
try (FileInputStream in = new FileInputStream(f)) {
|
||||
byte[] h = new byte[20];
|
||||
int n = 0;
|
||||
while (n < h.length) {
|
||||
int r = in.read(h, n, h.length - n);
|
||||
if (r < 0) break;
|
||||
n += r;
|
||||
}
|
||||
if (n < 20) return false;
|
||||
if (h[0] != 0x7f || h[1] != 'E' || h[2] != 'L' || h[3] != 'F') return false;
|
||||
if (h[4] != 2 || h[5] != 1) return false;
|
||||
int machine = (h[18] & 0xff) | ((h[19] & 0xff) << 8);
|
||||
return machine == 0xB7;
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] readAll(InputStream in) throws IOException {
|
||||
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
|
||||
byte[] buf = new byte[8192];
|
||||
int r;
|
||||
while ((r = in.read(buf)) > 0) bos.write(buf, 0, r);
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
static boolean containsAscii(File f, String needle) {
|
||||
byte[] nb = needle.getBytes(StandardCharsets.US_ASCII);
|
||||
try (InputStream in = new FileInputStream(f)) {
|
||||
byte[] buf = new byte[1 << 16];
|
||||
int carry = 0;
|
||||
int r;
|
||||
while ((r = in.read(buf, carry, buf.length - carry)) > 0) {
|
||||
int len = carry + r;
|
||||
for (int i = 0; i + nb.length <= len; i++) {
|
||||
int j = 0;
|
||||
while (j < nb.length && buf[i + j] == nb[j]) j++;
|
||||
if (j == nb.length) return true;
|
||||
}
|
||||
// Keep the last needle-1 bytes so a match across a buffer boundary is still found.
|
||||
carry = Math.min(nb.length - 1, len);
|
||||
System.arraycopy(buf, len - carry, buf, 0, carry);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.droiddeck.launcher.gpu;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* LSFG frame generation's shader chain: extracted from the user's own copy of Lossless Scaling
|
||||
* and cached on device.
|
||||
*
|
||||
* <p>The 25 compute shaders are not redistributable. They live as resources inside the user's
|
||||
* paid {@code Lossless.dll} (Steam app 993090), which in this app the user installs from the
|
||||
* Steam client itself - so the DLL sits in the runtime's own Steam library. It is mapped
|
||||
* read-only and parsed as data, never loaded or executed. Extraction is slow enough to be worth
|
||||
* doing once (the DXBC chain is translated to SPIR-V), so the result is cached, keyed on the
|
||||
* DLL's size and hash. Call {@link #ensureCache} off the main thread.
|
||||
*
|
||||
* <p>Ported from Bannerlator's LsfgNative; the native side is the same lsfg_jni.cpp compiled into
|
||||
* the compositor library.
|
||||
*/
|
||||
public final class LsfgNative {
|
||||
private static final String TAG = "LsfgNative";
|
||||
|
||||
static { System.loadLibrary("bannerwayland"); }
|
||||
|
||||
private LsfgNative() {}
|
||||
|
||||
// Mirrors lsfg::DllStatus.
|
||||
public static final int STATUS_OK = 0;
|
||||
public static final int STATUS_NOT_INSTALLED = 1;
|
||||
public static final int STATUS_UNREADABLE_FILE = 2;
|
||||
public static final int STATUS_NOT_PORTABLE_EXECUTABLE = 3;
|
||||
public static final int STATUS_MISSING_SHADERS = 4;
|
||||
public static final int STATUS_TRANSLATION_FAILED = 5;
|
||||
public static final int STATUS_CACHE_UNUSABLE = 6;
|
||||
|
||||
private static native int nativeValidateDll(String dllPath);
|
||||
private static native int nativeDllVariant(String dllPath, boolean preferFp16);
|
||||
private static native int nativeBuildCache(String dllPath, String cachePath, boolean preferFp16);
|
||||
private static native boolean nativeCacheMatchesSource(String cachePath, String dllPath);
|
||||
private static native int nativeCacheVariant(String cachePath);
|
||||
private static native String nativeStatusName(int status);
|
||||
private static native String nativeVariantName(int variant);
|
||||
|
||||
/** Where Lossless Scaling lands when installed from the client inside the runtime. */
|
||||
public static File losslessDll(Context context) {
|
||||
return new File(LinuxRuntime.rootDir(context),
|
||||
"root/.local/share/Steam/steamapps/common/Lossless Scaling/Lossless.dll");
|
||||
}
|
||||
|
||||
/** Where the translated SPIR-V chain is cached. */
|
||||
public static File cacheFile(Context context) {
|
||||
return new File(context.getFilesDir(), "lsfg-native/shaders.cache");
|
||||
}
|
||||
|
||||
public static boolean isInstalled(Context context) {
|
||||
return losslessDll(context).isFile();
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure a usable cache exists for the installed DLL, building it if the DLL is new or
|
||||
* changed. Returns a {@code STATUS_*} code; {@link #STATUS_OK} means the engine can start.
|
||||
*/
|
||||
public static int ensureCache(Context context) {
|
||||
File dll = losslessDll(context);
|
||||
if (!dll.isFile()) return STATUS_NOT_INSTALLED;
|
||||
File cache = cacheFile(context);
|
||||
try {
|
||||
if (cache.isFile() && nativeCacheMatchesSource(cache.getPath(), dll.getPath())) {
|
||||
return STATUS_OK;
|
||||
}
|
||||
int status = nativeValidateDll(dll.getPath());
|
||||
if (status != STATUS_OK) {
|
||||
Log.w(TAG, "Lossless.dll rejected: " + statusName(status));
|
||||
return status;
|
||||
}
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
cache.getParentFile().mkdirs();
|
||||
status = nativeBuildCache(dll.getPath(), cache.getPath(), true);
|
||||
Log.i(TAG, "cache build: " + statusName(status)
|
||||
+ (status == STATUS_OK ? " (" + nativeVariantName(nativeCacheVariant(cache.getPath())) + ")" : ""));
|
||||
return status;
|
||||
} catch (Throwable t) {
|
||||
Log.e(TAG, "ensureCache", t);
|
||||
return STATUS_CACHE_UNUSABLE;
|
||||
}
|
||||
}
|
||||
|
||||
public static String statusName(int status) {
|
||||
try {
|
||||
return nativeStatusName(status);
|
||||
} catch (Throwable t) {
|
||||
return "status " + status;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
package com.droiddeck.launcher.gpu;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.Uri;
|
||||
import android.os.Environment;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
import com.droiddeck.launcher.core.TarZst;
|
||||
import com.droiddeck.launcher.session.SessionPrefs;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/**
|
||||
* The Vulkan driver the in-app compositor runs on. It has to be Turnip: the system Adreno driver
|
||||
* does not implement VK_EXT_image_drm_format_modifier, so importing the dma-bufs gamescope hands
|
||||
* over fails and the session renders nothing. Two builds ship in the apk, one per Adreno
|
||||
* generation, and the GPU decides which is unpacked - unless the user has imported an AdrenoTools
|
||||
* zip of their own and chosen it, which then wins.
|
||||
*
|
||||
* <p>The guest's own Turnip is a different copy entirely - a glibc build inside the rootfs, or an
|
||||
* imported one ({@link LinuxVulkanDriverManager}). This one is the bionic build the app process
|
||||
* loads through adrenotools, and it is what every session ends in: whatever draws inside the
|
||||
* runtime, this is the driver that puts the frame on the panel.
|
||||
*
|
||||
* <p>Every driver, bundled or imported, lives under {@code files/graphics_driver/<id>/} with a
|
||||
* {@code meta.json} whose {@code libraryName} names the .so beside it - the AdrenoTools layout.
|
||||
* The import path is ported from Bannerlator's {@code AdrenotoolsManager} (GPL-3.0), including
|
||||
* the refusal of zips that belong in the Linux runtime list: a "-Linux" (glibc) Turnip names no
|
||||
* library on purpose, and installed here it would put the compositor on the system Vulkan - a
|
||||
* black screen wearing a driver's name.
|
||||
*/
|
||||
public final class TurnipDriver {
|
||||
private static final String TAG = "TurnipDriver";
|
||||
/** Adreno 7xx (8 Gen 2/3, e.g. the Pocket FIT's A750). */
|
||||
private static final String DRIVER_A7XX = "turnip25.1.0";
|
||||
/** Adreno 8xx (8 Elite, e.g. a Fold 8's A830). */
|
||||
private static final String DRIVER_A8XX = "turnip-sdk36";
|
||||
/** The two the apk carries; never removable, unpacked on demand. */
|
||||
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(DRIVER_A7XX, DRIVER_A8XX));
|
||||
/** Overrides the pick, for a device we cannot reach: a7xx, a8xx or system. */
|
||||
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
|
||||
/** Bundled drivers the user deleted: hidden from the list, their unpacked copy removed. */
|
||||
private static final String PREFS = "graphics_driver";
|
||||
private static final String KEY_HIDDEN = "hiddenBundled";
|
||||
/** Stored choice meaning "pick by GPU" - the default, and what a removed import falls back to. */
|
||||
public static final String AUTO = "";
|
||||
|
||||
public static final String HELP_TEXT =
|
||||
"The driver the app's compositor puts frames on the screen with - the last step of every "
|
||||
+ "session, Steam or desktop. AdrenoTools zips only (vulkan.adXXXX.so): a \"-Linux\" Turnip "
|
||||
+ "belongs in the Linux runtime list above and is refused here. The compositor loads its "
|
||||
+ "driver once per app process, so a change takes effect after the app is fully closed and "
|
||||
+ "started again.";
|
||||
|
||||
private final Context context;
|
||||
private final File contentDir;
|
||||
|
||||
public TurnipDriver(Context context) {
|
||||
this.context = context;
|
||||
this.contentDir = new File(context.getFilesDir(), "graphics_driver");
|
||||
}
|
||||
|
||||
/** Absolute directory holding the driver, with a trailing slash - adrenotools wants both. */
|
||||
public String driverPath(String driverId) {
|
||||
return new File(contentDir, driverId).getAbsolutePath() + "/";
|
||||
}
|
||||
|
||||
public String libraryName(String driverId) {
|
||||
JSONObject meta = readMeta(driverId);
|
||||
return meta != null ? meta.optString("libraryName", null) : null;
|
||||
}
|
||||
|
||||
/** meta.json's "name", or the id when it has none. */
|
||||
public String displayName(String driverId) {
|
||||
JSONObject meta = readMeta(driverId);
|
||||
String name = meta != null ? meta.optString("name", "") : "";
|
||||
return name.isEmpty() ? driverId : name;
|
||||
}
|
||||
|
||||
public String driverVersion(String driverId) {
|
||||
JSONObject meta = readMeta(driverId);
|
||||
return meta != null ? meta.optString("driverVersion", "") : "";
|
||||
}
|
||||
|
||||
private JSONObject readMeta(String driverId) {
|
||||
if (driverId == null || driverId.isEmpty() || driverId.contains("/") || driverId.contains("..")) return null;
|
||||
File meta = new File(new File(contentDir, driverId), "meta.json");
|
||||
String content = FileUtils.readString(meta);
|
||||
if (content == null) return null;
|
||||
try {
|
||||
return new JSONObject(content);
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "meta.json for " + driverId, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** An imported driver is installed when its meta.json names a library that is there. */
|
||||
public boolean isInstalled(String driverId) {
|
||||
String library = libraryName(driverId);
|
||||
return library != null && !library.isEmpty() && new File(new File(contentDir, driverId), library).isFile();
|
||||
}
|
||||
|
||||
/**
|
||||
* The bundled drivers the list shows: {@link #BUNDLED} minus the ones the user deleted. A deleted
|
||||
* one still lives in the apk and Auto still unpacks it on a GPU that needs it, so deleting can
|
||||
* never leave a device without a driver; it only leaves the list.
|
||||
*/
|
||||
public List<String> visibleBundled() {
|
||||
java.util.Set<String> hidden = hiddenBundled();
|
||||
ArrayList<String> out = new ArrayList<>();
|
||||
for (String id : BUNDLED) if (!hidden.contains(id)) out.add(id);
|
||||
return out;
|
||||
}
|
||||
|
||||
public java.util.Set<String> hiddenBundled() {
|
||||
return new java.util.HashSet<>(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.getStringSet(KEY_HIDDEN, java.util.Collections.<String>emptySet()));
|
||||
}
|
||||
|
||||
/** "Delete" for a bundled driver: remove its unpacked copy and hide it from the list. */
|
||||
public void hideBundled(String driverId) {
|
||||
if (!BUNDLED.contains(driverId)) return;
|
||||
FileUtils.delete(new File(contentDir, driverId));
|
||||
java.util.Set<String> hidden = hiddenBundled();
|
||||
hidden.add(driverId);
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY_HIDDEN, hidden).apply();
|
||||
Log.i(TAG, "bundled driver " + driverId + " hidden by the user");
|
||||
}
|
||||
|
||||
public void restoreBundled() {
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().remove(KEY_HIDDEN).apply();
|
||||
}
|
||||
|
||||
/** Imported drivers only - the bundled two are listed by {@link #BUNDLED}. */
|
||||
public List<String> enumerateImported() {
|
||||
ArrayList<String> ids = new ArrayList<>();
|
||||
File[] dirs = contentDir.listFiles();
|
||||
if (dirs == null) return ids;
|
||||
for (File d : dirs) {
|
||||
String id = d.getName();
|
||||
if (d.isDirectory() && !BUNDLED.contains(id) && !id.startsWith(".") && isInstalled(id)) ids.add(id);
|
||||
}
|
||||
Collections.sort(ids);
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** The bundled build the GPU would pick on its own, for the "Auto" row's label. */
|
||||
public String autoId() {
|
||||
String id = chooseByDevice();
|
||||
return id == null ? "system" : id;
|
||||
}
|
||||
|
||||
public void remove(String driverId) {
|
||||
if (driverId == null || driverId.isEmpty() || BUNDLED.contains(driverId)
|
||||
|| driverId.contains("/") || driverId.contains("..")) return;
|
||||
Log.d(TAG, "removing imported driver " + driverId);
|
||||
FileUtils.delete(new File(contentDir, driverId));
|
||||
if (driverId.equals(SessionPrefs.androidDriver(context))) SessionPrefs.setAndroidDriver(context, AUTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Import an AdrenoTools zip. Returns the new driver id.
|
||||
* @throws IllegalArgumentException with a user-facing reason when the zip is not an AdrenoTools
|
||||
* driver - including when it is a Linux runtime driver, which says which list it belongs in;
|
||||
* {@link IOException} on read/extract failures.
|
||||
*/
|
||||
public String installFromZip(Uri zipUri, String displayName) throws IOException {
|
||||
if (!contentDir.exists()) contentDir.mkdirs();
|
||||
File tmpDir = new File(contentDir, ".tmp-" + System.currentTimeMillis());
|
||||
FileUtils.delete(tmpDir);
|
||||
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
|
||||
boolean keep = false;
|
||||
try {
|
||||
try (InputStream is = context.getContentResolver().openInputStream(zipUri);
|
||||
ZipInputStream zis = new ZipInputStream(is)) {
|
||||
if (is == null) throw new IOException("cannot open " + zipUri);
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
if (entry.isDirectory()) continue;
|
||||
// Flatten: adrenotools reads the .so beside meta.json, and a base name also
|
||||
// defeats zip-slip paths.
|
||||
String base = new File(entry.getName()).getName();
|
||||
if (base.isEmpty()) continue;
|
||||
Files.copy(zis, new File(tmpDir, base).toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
String rejected = rejectionReason(tmpDir);
|
||||
if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected);
|
||||
|
||||
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
|
||||
String name = meta != null ? meta.optString("name", "") : "";
|
||||
if (name.isEmpty()) {
|
||||
name = displayName != null ? displayName : "adrenotools-driver";
|
||||
if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4);
|
||||
}
|
||||
String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name));
|
||||
File dir = new File(contentDir, id);
|
||||
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
|
||||
keep = true;
|
||||
Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir);
|
||||
return id;
|
||||
} finally {
|
||||
if (!keep) FileUtils.delete(tmpDir);
|
||||
}
|
||||
}
|
||||
|
||||
private static JSONObject readMetaFile(File metaFile) {
|
||||
try {
|
||||
return new JSONObject(FileUtils.readString(metaFile));
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a just-extracted zip is not something adrenotools can be pointed at, or null when it is.
|
||||
* The kinds refused by name are the other driver lists' zips, which carry a meta.json too.
|
||||
*/
|
||||
private static String rejectionReason(File dir) {
|
||||
File metaFile = new File(dir, "meta.json");
|
||||
if (!metaFile.isFile()) return "no meta.json";
|
||||
String libraryName, kind;
|
||||
try {
|
||||
JSONObject meta = new JSONObject(FileUtils.readString(metaFile));
|
||||
libraryName = meta.optString("libraryName", "");
|
||||
kind = meta.optString("kind", "");
|
||||
} catch (Exception e) {
|
||||
return "meta.json is unreadable (" + e.getMessage() + ")";
|
||||
}
|
||||
if ("linux-vulkan-icd".equals(kind))
|
||||
return "this is a Linux runtime driver (import it under \"Linux runtime driver\")";
|
||||
if ("wayland-game-driver".equals(kind))
|
||||
return "this is a Wayland game driver, which this app has no use for";
|
||||
if (libraryName.isEmpty())
|
||||
return "meta.json names no libraryName, so nothing could be handed to AdrenoTools";
|
||||
File library = new File(dir, libraryName);
|
||||
if (!library.isFile())
|
||||
return "meta.json names " + libraryName + ", which is not in the zip";
|
||||
if (!LinuxVulkanDriverManager.isAarch64Elf(library))
|
||||
return libraryName + " is not a 64-bit AArch64 ELF shared library";
|
||||
// A glibc build that happens to carry a libraryName would load nothing in this process.
|
||||
if (LinuxVulkanDriverManager.containsAscii(library, "libc.so.6"))
|
||||
return libraryName + " links glibc - a \"-Linux\" Turnip, which belongs under \"Linux runtime driver\"";
|
||||
return null;
|
||||
}
|
||||
|
||||
private String uniqueId(String base) {
|
||||
String id = base;
|
||||
int n = 2;
|
||||
while (new File(contentDir, id).exists()) id = base + "-" + (n++);
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unpacks the driver this device needs and returns its id, or null to fall back to the system
|
||||
* Vulkan loader (which means a black session on Adreno, but is better than refusing to start
|
||||
* on a GPU neither build covers).
|
||||
*/
|
||||
public String install() {
|
||||
String id = choose();
|
||||
if (id == null) return null;
|
||||
File dir = new File(contentDir, id);
|
||||
if (!new File(dir, "meta.json").isFile()) {
|
||||
FileUtils.delete(dir);
|
||||
if (!TarZst.extractAsset(context, "graphics_driver/adrenotools-" + id + ".tzst", dir)) {
|
||||
Log.e(TAG, "could not unpack " + id);
|
||||
FileUtils.delete(dir);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
String library = libraryName(id);
|
||||
if (library == null || !new File(dir, library).isFile()) {
|
||||
Log.e(TAG, id + " unpacked without " + library);
|
||||
return null;
|
||||
}
|
||||
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's choice first - an imported driver, or one of the bundled two pinned by hand -
|
||||
* then the Downloads override, then the GPU. A chosen import that has since been removed logs
|
||||
* and falls through, so a stale preference never blocks a session.
|
||||
*/
|
||||
private String choose() {
|
||||
String chosen = SessionPrefs.androidDriver(context);
|
||||
if (chosen != null && !chosen.isEmpty()) {
|
||||
if (BUNDLED.contains(chosen)) {
|
||||
Log.i(TAG, "driver pinned by the user: " + chosen);
|
||||
return chosen;
|
||||
}
|
||||
if (isInstalled(chosen)) {
|
||||
Log.i(TAG, "imported driver chosen by the user: " + chosen);
|
||||
return chosen;
|
||||
}
|
||||
Log.w(TAG, "chosen driver \"" + chosen + "\" is gone; picking by GPU");
|
||||
}
|
||||
return chooseByDevice();
|
||||
}
|
||||
|
||||
private String chooseByDevice() {
|
||||
File override = new File(Environment.getExternalStorageDirectory(), OVERRIDE_FILE);
|
||||
String forced = override.isFile() ? FileUtils.readString(override) : null;
|
||||
if (forced != null) {
|
||||
forced = forced.trim().toLowerCase(java.util.Locale.US);
|
||||
Log.i(TAG, "driver forced by " + override + ": " + forced);
|
||||
if (forced.startsWith("system")) return null;
|
||||
if (forced.startsWith("a8")) return DRIVER_A8XX;
|
||||
if (forced.startsWith("a7")) return DRIVER_A7XX;
|
||||
}
|
||||
String model = gpuModel();
|
||||
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
|
||||
if (model != null) {
|
||||
// "Adreno750", "adreno_830" - the generation is the first digit of the three.
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(\\d)\\d\\d").matcher(model);
|
||||
if (m.find()) {
|
||||
char generation = m.group(1).charAt(0);
|
||||
if (generation >= '8') return DRIVER_A8XX;
|
||||
if (generation == '7') return DRIVER_A7XX;
|
||||
}
|
||||
}
|
||||
// Nothing to go on: Android 16 shipped with the 8 Elite, so treat a new device as 8xx.
|
||||
return android.os.Build.VERSION.SDK_INT >= 36 ? DRIVER_A8XX : DRIVER_A7XX;
|
||||
}
|
||||
|
||||
/** KGSL names the GPU here, and this file is world-readable where /dev/kgsl-3d0 is not. */
|
||||
private static String gpuModel() {
|
||||
for (String path : new String[]{
|
||||
"/sys/class/kgsl/kgsl-3d0/gpu_model",
|
||||
"/sys/class/kgsl/kgsl-3d0/gpu_chipid"}) {
|
||||
String value = FileUtils.readString(new File(path));
|
||||
if (value != null && !value.trim().isEmpty()) return value.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* Driver downloads from the Turnip release repos, offered in both driver menus. Checked only when
|
||||
* the user taps refresh - the result is remembered, so the menu shows the last check without going
|
||||
* online. A download goes through the same importer as a zip picked by hand, so it gets the same
|
||||
* checks and lands as an ordinary imported driver.
|
||||
*
|
||||
* Each repo's recent releases are read newest first and every driver variant is offered from the
|
||||
* newest release that carries it: a repo that stops publishing one variant (Banners-Turnip's A8xx
|
||||
* Linux build after v26.3.0-20260923) still offers its last one, and a repo with two release lines
|
||||
* (WinNative's Android `v1.x` and Linux `linux-v0.x`) offers the newest of each.
|
||||
*/
|
||||
object TurnipReleases {
|
||||
private const val PREFS = "turnip_releases"
|
||||
private const val KEY_RELEASE = "latest"
|
||||
private const val KEY_DOWNLOADS = "downloads"
|
||||
|
||||
/** [label] names the variant for the menu: the GPUs it is for, and a build flavour. */
|
||||
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String)
|
||||
/** [latest] = each source's newest release tag, for the refresh line. */
|
||||
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
|
||||
|
||||
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Pair<Boolean, String>?)
|
||||
|
||||
private val SOURCES = listOf(
|
||||
// Turnip-<tag>[-variant][-Linux|-Wayland].zip; -Wayland is for a path this app does not have.
|
||||
Source("Banners-Turnip", "The412Banner/Banners-Turnip") { name, tag ->
|
||||
val prefix = "Turnip-$tag"
|
||||
if (!name.startsWith(prefix) || !name.endsWith(".zip")) return@Source null
|
||||
var variant = name.removePrefix(prefix).removeSuffix(".zip")
|
||||
if (variant.endsWith("-Wayland")) return@Source null
|
||||
val linux = variant.endsWith("-Linux")
|
||||
variant = variant.removeSuffix("-Linux")
|
||||
linux to when {
|
||||
variant.isEmpty() -> "Adreno 6xx/7xx"
|
||||
variant == "-A8xx" -> "Adreno 8xx"
|
||||
variant.startsWith("-710-720") -> "Adreno 710/720" + if (variant.contains("Test")) " (test)" else ""
|
||||
else -> variant.trimStart('-')
|
||||
}
|
||||
},
|
||||
// WN-Turnip-<ver>-<b|p>_Axxx.zip (Android) and WN-Linux-Turnip-<ver>-<b|p>_Axxx.zip (Linux):
|
||||
// b = Balanced, p = Performance, Axxx = every Adreno.
|
||||
Source("WinNative", "WinNative-Emu/Drivers") { name, _ ->
|
||||
val m = Regex("""^WN-(Linux-)?Turnip-[^-]+-([a-z]+)_(\w+)\.zip$""").find(name) ?: return@Source null
|
||||
val flavour = when (m.groupValues[2]) { "b" -> "Balanced"; "p" -> "Performance"; else -> m.groupValues[2] }
|
||||
val gpus = if (m.groupValues[3] == "Axxx") "all Adreno" else m.groupValues[3]
|
||||
(m.groupValues[1].isNotEmpty()) to "$gpus · $flavour"
|
||||
},
|
||||
)
|
||||
|
||||
/** The result of the last check, or null when the user has never checked. */
|
||||
fun cached(context: Context): Check? {
|
||||
val raw = prefs(context).getString(KEY_RELEASE, null) ?: return null
|
||||
return runCatching { parse(JSONObject(raw)) }.getOrNull()
|
||||
}
|
||||
|
||||
/**
|
||||
* Read every source now and remember the result. A source that fails is named in [Check.failed]
|
||||
* and the others still count; throws only when every source failed.
|
||||
*/
|
||||
fun refresh(context: Context): Check {
|
||||
val assets = JSONArray()
|
||||
val latest = JSONArray()
|
||||
val failed = ArrayList<String>()
|
||||
var lastError: Exception? = null
|
||||
for (src in SOURCES) {
|
||||
try {
|
||||
val releases = JSONArray(get("https://api.github.com/repos/${src.repo}/releases?per_page=15"))
|
||||
val seen = HashSet<String>()
|
||||
var newest: String? = null
|
||||
for (i in 0 until releases.length()) {
|
||||
val r = releases.getJSONObject(i)
|
||||
if (r.optBoolean("draft")) continue
|
||||
val tag = r.getString("tag_name")
|
||||
if (newest == null) newest = tag
|
||||
val list = r.optJSONArray("assets") ?: continue
|
||||
for (j in 0 until list.length()) {
|
||||
val a = list.getJSONObject(j)
|
||||
val name = a.getString("name")
|
||||
val (linux, label) = src.classify(name, tag) ?: continue
|
||||
// Newest first: the first release carrying a variant is the one offered.
|
||||
if (!seen.add("$linux|$label")) continue
|
||||
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
|
||||
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
|
||||
.put("linux", linux).put("label", label))
|
||||
}
|
||||
}
|
||||
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
|
||||
} catch (e: Exception) {
|
||||
failed.add(src.label)
|
||||
lastError = e
|
||||
}
|
||||
}
|
||||
if (failed.size == SOURCES.size) throw lastError ?: IOException("no source answered")
|
||||
val stored = JSONObject().put("assets", assets).put("latest", latest)
|
||||
.put("failed", JSONArray(failed)).put("checkedAt", System.currentTimeMillis())
|
||||
prefs(context).edit().putString(KEY_RELEASE, stored.toString()).apply()
|
||||
return parse(stored)
|
||||
}
|
||||
|
||||
private fun get(url: String): String {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 15_000
|
||||
c.readTimeout = 20_000
|
||||
c.setRequestProperty("Accept", "application/vnd.github+json")
|
||||
c.setRequestProperty("User-Agent", "DroidDeck-app")
|
||||
try {
|
||||
val code = c.responseCode
|
||||
if (code == 403 || code == 429) throw IOException("GitHub's rate limit was hit - try again later")
|
||||
if (code != 200) throw IOException("GitHub answered HTTP $code")
|
||||
return c.inputStream.bufferedReader().use { it.readText() }
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun parse(json: JSONObject): Check {
|
||||
val out = ArrayList<Asset>()
|
||||
val list = json.getJSONArray("assets")
|
||||
for (i in 0 until list.length()) {
|
||||
val a = list.getJSONObject(i)
|
||||
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
|
||||
a.optLong("size"), a.getBoolean("linux"), a.getString("label")))
|
||||
}
|
||||
val latest = ArrayList<Pair<String, String>>()
|
||||
val l = json.optJSONArray("latest") ?: JSONArray()
|
||||
for (i in 0 until l.length()) l.getJSONObject(i).let { latest.add(it.getString("source") to it.getString("tag")) }
|
||||
val failed = ArrayList<String>()
|
||||
val f = json.optJSONArray("failed") ?: JSONArray()
|
||||
for (i in 0 until f.length()) failed.add(f.getString(i))
|
||||
return Check(out, latest, failed, json.optLong("checkedAt"))
|
||||
}
|
||||
|
||||
/** The id an asset was installed as, when it was downloaded before and is still installed. */
|
||||
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
|
||||
downloads(context).optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
|
||||
|
||||
/** True when [id] came from a release download rather than a zip picked by hand. */
|
||||
fun isDownloaded(context: Context, id: String): Boolean {
|
||||
val d = downloads(context)
|
||||
return d.keys().asSequence().any { d.optString(it) == id }
|
||||
}
|
||||
|
||||
fun recordDownload(context: Context, asset: Asset, id: String) {
|
||||
prefs(context).edit().putString(KEY_DOWNLOADS, downloads(context).put(asset.name, id).toString()).apply()
|
||||
}
|
||||
|
||||
/** Forget a deleted driver, so its release offers the download again. */
|
||||
fun forget(context: Context, id: String) {
|
||||
val d = downloads(context)
|
||||
val keys = d.keys().asSequence().filter { d.optString(it) == id }.toList()
|
||||
if (keys.isEmpty()) return
|
||||
keys.forEach { d.remove(it) }
|
||||
prefs(context).edit().putString(KEY_DOWNLOADS, d.toString()).apply()
|
||||
}
|
||||
|
||||
/** Download an asset into the cache; the caller imports it and deletes the file. */
|
||||
fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File {
|
||||
val target = File(context.cacheDir, asset.name)
|
||||
val c = URL(asset.url).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 15_000
|
||||
c.readTimeout = 60_000
|
||||
c.setRequestProperty("User-Agent", "DroidDeck-app")
|
||||
c.instanceFollowRedirects = true
|
||||
try {
|
||||
if (c.responseCode != 200) throw IOException("download answered HTTP ${c.responseCode}")
|
||||
val total = c.contentLengthLong.takeIf { it > 0 } ?: asset.size
|
||||
c.inputStream.use { input ->
|
||||
FileOutputStream(target).use { out ->
|
||||
val buf = ByteArray(1 shl 16)
|
||||
var done = 0L
|
||||
var last = -1
|
||||
while (true) {
|
||||
val r = input.read(buf)
|
||||
if (r <= 0) break
|
||||
out.write(buf, 0, r)
|
||||
done += r
|
||||
val pct = if (total > 0) (done * 100 / total).toInt() else 0
|
||||
if (pct != last) { last = pct; progress(pct) }
|
||||
}
|
||||
}
|
||||
}
|
||||
return target
|
||||
} catch (e: Exception) {
|
||||
FileUtils.delete(target)
|
||||
throw e
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun downloads(context: Context): JSONObject =
|
||||
runCatching { JSONObject(prefs(context).getString(KEY_DOWNLOADS, "{}")!!) }.getOrDefault(JSONObject())
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.input;
|
||||
|
||||
import android.view.KeyEvent;
|
||||
|
||||
/**
|
||||
* Android key codes to Linux evdev codes, for the keys we inject into the compositor's
|
||||
* wl_keyboard. A hardware keyboard is how an account name and password are typed on the client's
|
||||
* first run, so this matters before any game does.
|
||||
*
|
||||
* <p>evdev's order is not alphabetical: the numbers are the physical positions of a PC keyboard,
|
||||
* which is what the compositor's xkb keymap is written against. Table taken from Bannerlator's
|
||||
* Wayland path unchanged.
|
||||
*/
|
||||
public final class EvdevKeys {
|
||||
private EvdevKeys() {}
|
||||
|
||||
public static int fromKeyCode(int kc) {
|
||||
switch (kc) {
|
||||
// Letters (evdev order is NOT alphabetical)
|
||||
case KeyEvent.KEYCODE_A: return 30; case KeyEvent.KEYCODE_B: return 48;
|
||||
case KeyEvent.KEYCODE_C: return 46; case KeyEvent.KEYCODE_D: return 32;
|
||||
case KeyEvent.KEYCODE_E: return 18; case KeyEvent.KEYCODE_F: return 33;
|
||||
case KeyEvent.KEYCODE_G: return 34; case KeyEvent.KEYCODE_H: return 35;
|
||||
case KeyEvent.KEYCODE_I: return 23; case KeyEvent.KEYCODE_J: return 36;
|
||||
case KeyEvent.KEYCODE_K: return 37; case KeyEvent.KEYCODE_L: return 38;
|
||||
case KeyEvent.KEYCODE_M: return 50; case KeyEvent.KEYCODE_N: return 49;
|
||||
case KeyEvent.KEYCODE_O: return 24; case KeyEvent.KEYCODE_P: return 25;
|
||||
case KeyEvent.KEYCODE_Q: return 16; case KeyEvent.KEYCODE_R: return 19;
|
||||
case KeyEvent.KEYCODE_S: return 31; case KeyEvent.KEYCODE_T: return 20;
|
||||
case KeyEvent.KEYCODE_U: return 22; case KeyEvent.KEYCODE_V: return 47;
|
||||
case KeyEvent.KEYCODE_W: return 17; case KeyEvent.KEYCODE_X: return 45;
|
||||
case KeyEvent.KEYCODE_Y: return 21; case KeyEvent.KEYCODE_Z: return 44;
|
||||
// Digit row
|
||||
case KeyEvent.KEYCODE_1: return 2; case KeyEvent.KEYCODE_2: return 3;
|
||||
case KeyEvent.KEYCODE_3: return 4; case KeyEvent.KEYCODE_4: return 5;
|
||||
case KeyEvent.KEYCODE_5: return 6; case KeyEvent.KEYCODE_6: return 7;
|
||||
case KeyEvent.KEYCODE_7: return 8; case KeyEvent.KEYCODE_8: return 9;
|
||||
case KeyEvent.KEYCODE_9: return 10; case KeyEvent.KEYCODE_0: return 11;
|
||||
// Whitespace / edit
|
||||
case KeyEvent.KEYCODE_ENTER: return 28; case KeyEvent.KEYCODE_NUMPAD_ENTER: return 28;
|
||||
case KeyEvent.KEYCODE_SPACE: return 57; case KeyEvent.KEYCODE_TAB: return 15;
|
||||
case KeyEvent.KEYCODE_DEL: return 14; /* backspace */
|
||||
case KeyEvent.KEYCODE_FORWARD_DEL: return 111; case KeyEvent.KEYCODE_ESCAPE: return 1;
|
||||
// Modifiers
|
||||
case KeyEvent.KEYCODE_SHIFT_LEFT: return 42; case KeyEvent.KEYCODE_SHIFT_RIGHT: return 54;
|
||||
case KeyEvent.KEYCODE_CTRL_LEFT: return 29; case KeyEvent.KEYCODE_CTRL_RIGHT: return 97;
|
||||
case KeyEvent.KEYCODE_ALT_LEFT: return 56; case KeyEvent.KEYCODE_ALT_RIGHT: return 100;
|
||||
case KeyEvent.KEYCODE_CAPS_LOCK: return 58;
|
||||
// Arrows / nav
|
||||
case KeyEvent.KEYCODE_DPAD_UP: return 103; case KeyEvent.KEYCODE_DPAD_DOWN: return 108;
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT: return 105; case KeyEvent.KEYCODE_DPAD_RIGHT: return 106;
|
||||
case KeyEvent.KEYCODE_MOVE_HOME: return 102; case KeyEvent.KEYCODE_MOVE_END: return 107;
|
||||
case KeyEvent.KEYCODE_PAGE_UP: return 104; case KeyEvent.KEYCODE_PAGE_DOWN: return 109;
|
||||
case KeyEvent.KEYCODE_INSERT: return 110;
|
||||
// Punctuation
|
||||
case KeyEvent.KEYCODE_GRAVE: return 41; case KeyEvent.KEYCODE_MINUS: return 12;
|
||||
case KeyEvent.KEYCODE_EQUALS: return 13; case KeyEvent.KEYCODE_LEFT_BRACKET: return 26;
|
||||
case KeyEvent.KEYCODE_RIGHT_BRACKET: return 27; case KeyEvent.KEYCODE_BACKSLASH: return 43;
|
||||
case KeyEvent.KEYCODE_SEMICOLON: return 39; case KeyEvent.KEYCODE_APOSTROPHE: return 40;
|
||||
case KeyEvent.KEYCODE_SLASH: return 53; case KeyEvent.KEYCODE_COMMA: return 51;
|
||||
case KeyEvent.KEYCODE_PERIOD: return 52;
|
||||
// Function row
|
||||
case KeyEvent.KEYCODE_F1: return 59; case KeyEvent.KEYCODE_F2: return 60;
|
||||
case KeyEvent.KEYCODE_F3: return 61; case KeyEvent.KEYCODE_F4: return 62;
|
||||
case KeyEvent.KEYCODE_F5: return 63; case KeyEvent.KEYCODE_F6: return 64;
|
||||
case KeyEvent.KEYCODE_F7: return 65; case KeyEvent.KEYCODE_F8: return 66;
|
||||
case KeyEvent.KEYCODE_F9: return 67; case KeyEvent.KEYCODE_F10: return 68;
|
||||
case KeyEvent.KEYCODE_F11: return 87; case KeyEvent.KEYCODE_F12: return 88;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The character a key carries when Shift is not held, for a character that needs it - so '@'
|
||||
* gives '2' and 'A' gives 'a'. Returns 0 when the character is typed without Shift, which is
|
||||
* also the answer for anything this layout does not place on a key. US layout, which is what
|
||||
* the session's keymap is.
|
||||
*/
|
||||
public static int unshiftedChar(int ch) {
|
||||
if (ch >= 'A' && ch <= 'Z') return Character.toLowerCase(ch);
|
||||
int at = SHIFTED_CHARS.indexOf(ch);
|
||||
return at >= 0 ? PLAIN_CHARS.charAt(at) : 0;
|
||||
}
|
||||
|
||||
// Index-aligned: the symbol, and the key it shares with Shift held.
|
||||
private static final String SHIFTED_CHARS = "!@#$%^&*()_+{}|:\"<>?~";
|
||||
private static final String PLAIN_CHARS = "1234567890-=[]\\;',./`";
|
||||
|
||||
/** The Android key code that carries an unshifted character, or 0 when nothing does. */
|
||||
public static int keycodeForChar(int ch) {
|
||||
if (ch >= 'a' && ch <= 'z') return KeyEvent.KEYCODE_A + (ch - 'a');
|
||||
if (ch >= '0' && ch <= '9') return KeyEvent.KEYCODE_0 + (ch - '0');
|
||||
switch (ch) {
|
||||
case '-': return KeyEvent.KEYCODE_MINUS;
|
||||
case '=': return KeyEvent.KEYCODE_EQUALS;
|
||||
case '[': return KeyEvent.KEYCODE_LEFT_BRACKET;
|
||||
case ']': return KeyEvent.KEYCODE_RIGHT_BRACKET;
|
||||
case '\\': return KeyEvent.KEYCODE_BACKSLASH;
|
||||
case ';': return KeyEvent.KEYCODE_SEMICOLON;
|
||||
case '\'': return KeyEvent.KEYCODE_APOSTROPHE;
|
||||
case ',': return KeyEvent.KEYCODE_COMMA;
|
||||
case '.': return KeyEvent.KEYCODE_PERIOD;
|
||||
case '/': return KeyEvent.KEYCODE_SLASH;
|
||||
case '`': return KeyEvent.KEYCODE_GRAVE;
|
||||
case ' ': return KeyEvent.KEYCODE_SPACE;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,689 @@
|
||||
package com.droiddeck.launcher.input;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.channels.FileChannel;
|
||||
|
||||
/**
|
||||
* Fake evdev transport for the emulated Xbox 360 pads.
|
||||
*
|
||||
* <p>Replaces the old append-file transport (which desynced after ~15 min when an
|
||||
* unlooped {@code channel.write} left a partial event in the file and the
|
||||
* IOException was swallowed) with a fixed-size mmap RING BUFFER shared with the
|
||||
* native reader in {@code fakeinput.cpp}. Delta events are published into the
|
||||
* ring under a monotonic {@code write_seq}; an authoritative absolute-state
|
||||
* snapshot is published alongside under a seqlock so the native reader can replay
|
||||
* a full keyframe to heal any desync (open, ring overflow) without duplicate
|
||||
* input. Ring layout (magic/version/offsets) is a paired ABI with the native
|
||||
* {@code FakeInputRingHeader} - keep the two in lockstep.
|
||||
*/
|
||||
public class FakeInputWriter {
|
||||
private static final String TAG = "FakeInputWriter";
|
||||
|
||||
// Event types
|
||||
public static final short EV_SYN = 0x00;
|
||||
public static final short EV_KEY = 0x01;
|
||||
public static final short EV_ABS = 0x03;
|
||||
public static final short EV_MSC = 0x04;
|
||||
|
||||
// Event codes
|
||||
public static final short MSC_SCAN = 0x04;
|
||||
public static final short SYN_REPORT = 0x00;
|
||||
|
||||
// Xbox 360 controller button codes
|
||||
public static final short BTN_A = 0x130;
|
||||
public static final short BTN_B = 0x131;
|
||||
public static final short BTN_X = 0x133;
|
||||
public static final short BTN_Y = 0x134;
|
||||
public static final short BTN_TL = 0x136;
|
||||
public static final short BTN_TR = 0x137;
|
||||
public static final short BTN_SELECT = 0x13A;
|
||||
public static final short BTN_START = 0x13B;
|
||||
public static final short BTN_THUMBL = 0x13D;
|
||||
public static final short BTN_MODE = 0x13C;
|
||||
public static final short BTN_THUMBR = 0x13E;
|
||||
|
||||
// Absolute axis codes
|
||||
public static final short ABS_X = 0x00;
|
||||
public static final short ABS_Y = 0x01;
|
||||
public static final short ABS_RX = 0x03;
|
||||
public static final short ABS_RY = 0x04;
|
||||
public static final short ABS_GAS = 0x09;
|
||||
public static final short ABS_BRAKE = 0x0A;
|
||||
public static final short ABS_HAT0X = 0x10;
|
||||
public static final short ABS_HAT0Y = 0x11;
|
||||
|
||||
// Button mapping (bit i of the snapshot buttons word)
|
||||
private static final short[] BUTTON_MAP = {
|
||||
BTN_A, BTN_B, BTN_X, BTN_Y, BTN_TL, BTN_TR,
|
||||
BTN_SELECT, BTN_START, BTN_THUMBL, BTN_THUMBR,
|
||||
BTN_MODE
|
||||
};
|
||||
/** Bit 10 of the snapshot word. The first ten are PadState's own bit order; the Steam
|
||||
* button is not, because PadState keeps 10 and 11 for the triggers. */
|
||||
private static final int SNAPSHOT_IDX_MODE = 10;
|
||||
|
||||
private static final int EVENT_SIZE = 24;
|
||||
static final int MAX_EVENTS_PER_UPDATE = 32;
|
||||
private static final int BUFFER_SIZE = EVENT_SIZE * MAX_EVENTS_PER_UPDATE;
|
||||
private static final int MAX_FAKE_INPUT_SLOTS = 4;
|
||||
|
||||
// Ring layout - MUST match FakeInputRingHeader in fakeinput.cpp.
|
||||
private static final int RING_CAPACITY_EVENTS = 4096;
|
||||
private static final int RING_HEADER_SIZE = 64;
|
||||
private static final int RING_SIZE = RING_HEADER_SIZE + (RING_CAPACITY_EVENTS * EVENT_SIZE);
|
||||
private static final int RING_MAGIC = 0x46494252; // FIBR
|
||||
private static final int RING_VERSION = 2;
|
||||
private static final int RING_MAGIC_OFFSET = 0;
|
||||
private static final int RING_VERSION_OFFSET = 4;
|
||||
private static final int RING_EVENT_SIZE_OFFSET = 8;
|
||||
private static final int RING_CAPACITY_OFFSET = 12;
|
||||
private static final int RING_WRITE_SEQ_OFFSET = 16;
|
||||
private static final int RING_GENERATION_OFFSET = 24;
|
||||
// Authoritative absolute-state snapshot the native reader replays as a full
|
||||
// keyframe to heal any delta-stream desync. Written under a seqlock
|
||||
// (RING_SNAPSHOT_SEQ_OFFSET: odd = write in progress).
|
||||
private static final int RING_SNAPSHOT_SEQ_OFFSET = 32;
|
||||
private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40;
|
||||
private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8]
|
||||
private static final String RING_DIR_NAME = "fakeinput-rings";
|
||||
|
||||
private static final Object RING_LOCK = new Object();
|
||||
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
|
||||
|
||||
static {
|
||||
System.loadLibrary("sdnative");
|
||||
}
|
||||
|
||||
private static native void nativeStoreFence();
|
||||
|
||||
private final File eventFile;
|
||||
private final int slot;
|
||||
private final ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
|
||||
|
||||
private boolean isOpen = false;
|
||||
private volatile boolean destroyed = false;
|
||||
|
||||
private final boolean[] prevButtonStates = new boolean[12];
|
||||
private int prevThumbLX, prevThumbLY, prevThumbRX, prevThumbRY;
|
||||
private int prevTriggerL, prevTriggerR;
|
||||
private int prevHatX, prevHatY;
|
||||
private boolean hasChanges = false;
|
||||
// If a publish fails after prev* state has already advanced, the next frame
|
||||
// must re-emit the whole state once; otherwise an unchanged control would stay
|
||||
// silent and the ring snapshot would never catch up.
|
||||
private boolean pendingFullResend = false;
|
||||
private boolean forceResend = false;
|
||||
|
||||
public FakeInputWriter(String fakeInputPath, int slot) {
|
||||
this.slot = slot;
|
||||
this.eventFile = new File(fakeInputPath, "event" + slot);
|
||||
this.buffer.order(ByteOrder.LITTLE_ENDIAN);
|
||||
}
|
||||
|
||||
private static final class RingSlot {
|
||||
ByteBuffer data;
|
||||
File ringFile;
|
||||
FileChannel ringChannel;
|
||||
RandomAccessFile ringRaf;
|
||||
String exportPath;
|
||||
long generation;
|
||||
boolean active;
|
||||
boolean everActivated;
|
||||
}
|
||||
|
||||
// ---- Static ring management (shared by all writers + the env exporter) ----
|
||||
|
||||
public static void prepareRingSlots(File fakeInputDir, int slotCount) {
|
||||
int boundedSlotCount = Math.max(0, Math.min(slotCount, MAX_FAKE_INPUT_SLOTS));
|
||||
synchronized (RING_LOCK) {
|
||||
for (int slot = 0; slot < boundedSlotCount; slot++) {
|
||||
ensureRingSlotLocked(slot, fakeInputDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares every slot ring and returns the {@code slot=path;...} spec the native
|
||||
* reader consumes via FAKE_EVDEV_MEMFD_PATHS.
|
||||
*/
|
||||
public static String getRingEnv(File fakeInputDir) {
|
||||
synchronized (RING_LOCK) {
|
||||
prepareRingSlotsLocked(fakeInputDir, MAX_FAKE_INPUT_SLOTS);
|
||||
return buildRingEnvLocked();
|
||||
}
|
||||
}
|
||||
|
||||
public static void releaseAllRingSlots() {
|
||||
synchronized (RING_LOCK) {
|
||||
for (int slot = 0; slot < RING_SLOTS.length; slot++) {
|
||||
releaseRingSlotLocked(slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String buildRingEnvLocked() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (int slot = 0; slot < RING_SLOTS.length; slot++) {
|
||||
RingSlot ringSlot = RING_SLOTS[slot];
|
||||
if (ringSlot == null || ringSlot.data == null || ringSlot.exportPath == null) {
|
||||
continue;
|
||||
}
|
||||
if (builder.length() > 0) {
|
||||
builder.append(';');
|
||||
}
|
||||
builder.append(slot).append('=').append(ringSlot.exportPath);
|
||||
}
|
||||
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) {
|
||||
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) {
|
||||
data.order(ByteOrder.LITTLE_ENDIAN);
|
||||
data.putInt(RING_MAGIC_OFFSET, RING_MAGIC);
|
||||
data.putInt(RING_VERSION_OFFSET, RING_VERSION);
|
||||
data.putInt(RING_EVENT_SIZE_OFFSET, EVENT_SIZE);
|
||||
data.putInt(RING_CAPACITY_OFFSET, RING_CAPACITY_EVENTS);
|
||||
data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
|
||||
data.putLong(RING_GENERATION_OFFSET, 0L);
|
||||
data.putLong(RING_SNAPSHOT_SEQ_OFFSET, 0L);
|
||||
data.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, 0);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
data.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void releaseRingSlotLocked(int slot) {
|
||||
RingSlot ringSlot = RING_SLOTS[slot];
|
||||
if (ringSlot == null) {
|
||||
return;
|
||||
}
|
||||
ringSlot.data = null;
|
||||
if (ringSlot.ringChannel != null) {
|
||||
try {
|
||||
ringSlot.ringChannel.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
ringSlot.ringChannel = null;
|
||||
}
|
||||
if (ringSlot.ringRaf != null) {
|
||||
try {
|
||||
ringSlot.ringRaf.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
ringSlot.ringRaf = null;
|
||||
}
|
||||
if (ringSlot.ringFile != null && ringSlot.ringFile.exists()) {
|
||||
ringSlot.ringFile.delete();
|
||||
}
|
||||
RING_SLOTS[slot] = null;
|
||||
}
|
||||
|
||||
private static void prepareRingSlotsLocked(File fakeInputDir, int slotCount) {
|
||||
int boundedSlotCount = Math.max(0, Math.min(slotCount, MAX_FAKE_INPUT_SLOTS));
|
||||
for (int slot = 0; slot < boundedSlotCount; slot++) {
|
||||
ensureRingSlotLocked(slot, fakeInputDir);
|
||||
}
|
||||
}
|
||||
|
||||
private static RingSlot ensureRingSlotLocked(int slot, File fakeInputDir) {
|
||||
if (slot < 0 || slot >= MAX_FAKE_INPUT_SLOTS || fakeInputDir == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
File desiredRingFile = getRingFile(fakeInputDir, slot);
|
||||
if (desiredRingFile == null) {
|
||||
return null;
|
||||
}
|
||||
desiredRingFile = desiredRingFile.getAbsoluteFile();
|
||||
RingSlot existing = RING_SLOTS[slot];
|
||||
if (existing != null && existing.data != null) {
|
||||
if (existing.ringFile != null && existing.ringFile.equals(desiredRingFile)) {
|
||||
return existing;
|
||||
}
|
||||
releaseRingSlotLocked(slot);
|
||||
}
|
||||
|
||||
RingSlot fileRingSlot = createFileRingSlotLocked(slot, desiredRingFile);
|
||||
if (fileRingSlot != null) {
|
||||
RING_SLOTS[slot] = fileRingSlot;
|
||||
return fileRingSlot;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static RingSlot createFileRingSlotLocked(int slot, File ringFile) {
|
||||
File ringDir = ringFile.getParentFile();
|
||||
if (ringDir == null || (!ringDir.exists() && !ringDir.mkdirs())) {
|
||||
Log.e(TAG, "Failed to create fake input ring directory for slot " + slot);
|
||||
return null;
|
||||
}
|
||||
|
||||
RandomAccessFile raf = null;
|
||||
FileChannel channel = null;
|
||||
try {
|
||||
raf = new RandomAccessFile(ringFile, "rw");
|
||||
raf.setLength(RING_SIZE);
|
||||
channel = raf.getChannel();
|
||||
ByteBuffer data = channel.map(FileChannel.MapMode.READ_WRITE, 0, RING_SIZE);
|
||||
initializeRingHeader(data);
|
||||
|
||||
RingSlot ringSlot = new RingSlot();
|
||||
ringSlot.data = data;
|
||||
ringSlot.ringFile = ringFile.getAbsoluteFile();
|
||||
ringSlot.ringRaf = raf;
|
||||
ringSlot.ringChannel = channel;
|
||||
ringSlot.exportPath = getCanonicalOrAbsolutePath(ringFile);
|
||||
Log.i(TAG, "Created fake input file ring for slot " + slot + ": " + ringSlot.exportPath);
|
||||
return ringSlot;
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "Failed to create fake input file ring for slot " + slot + ": " + e.getMessage());
|
||||
if (channel != null) {
|
||||
try {
|
||||
channel.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
if (raf != null) {
|
||||
try {
|
||||
raf.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private RingSlot ensureRingSlot() {
|
||||
synchronized (RING_LOCK) {
|
||||
return ensureRingSlotLocked(this.slot, this.eventFile.getParentFile());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean activateRingSlot() {
|
||||
RingSlot ringSlot = ensureRingSlot();
|
||||
if (ringSlot == null || ringSlot.data == null) {
|
||||
return false;
|
||||
}
|
||||
synchronized (ringSlot) {
|
||||
if (!ringSlot.active) {
|
||||
if (ringSlot.everActivated) {
|
||||
ringSlot.generation++;
|
||||
} else {
|
||||
ringSlot.everActivated = true;
|
||||
}
|
||||
ringSlot.data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
|
||||
clearSnapshotLocked(ringSlot.data);
|
||||
ringSlot.data.putLong(RING_GENERATION_OFFSET, ringSlot.generation);
|
||||
ringSlot.active = true;
|
||||
Log.d(TAG, "Activated fake input ring for slot " + this.slot
|
||||
+ " generation=" + ringSlot.generation);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void deactivateRingSlot() {
|
||||
RingSlot ringSlot;
|
||||
synchronized (RING_LOCK) {
|
||||
ringSlot = this.slot >= 0 && this.slot < RING_SLOTS.length ? RING_SLOTS[this.slot] : null;
|
||||
}
|
||||
if (ringSlot == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (ringSlot) {
|
||||
if (ringSlot.active && ringSlot.data != null) {
|
||||
ringSlot.generation++;
|
||||
ringSlot.data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
|
||||
clearSnapshotLocked(ringSlot.data);
|
||||
ringSlot.data.putLong(RING_GENERATION_OFFSET, ringSlot.generation);
|
||||
Log.i(TAG, "Deactivated fake input ring for slot " + this.slot
|
||||
+ " generation=" + ringSlot.generation);
|
||||
}
|
||||
ringSlot.active = false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean flushBufferToRing() {
|
||||
RingSlot ringSlot = ensureRingSlot();
|
||||
if (ringSlot == null || ringSlot.data == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Raw byte copy: endianness is irrelevant since we never interpret
|
||||
// multi-byte fields out of the source here.
|
||||
ByteBuffer source = this.buffer.duplicate();
|
||||
synchronized (ringSlot) {
|
||||
ByteBuffer ring = ringSlot.data;
|
||||
long writeSeq = ring.getLong(RING_WRITE_SEQ_OFFSET);
|
||||
int sourceLimit = source.limit();
|
||||
while (source.remaining() >= EVENT_SIZE) {
|
||||
int eventIndex = (int) (writeSeq % RING_CAPACITY_EVENTS);
|
||||
int targetOffset = RING_HEADER_SIZE + (eventIndex * EVENT_SIZE);
|
||||
// Bulk-copy one event (EVENT_SIZE bytes) instead of byte-by-byte.
|
||||
// Bound the source to a single event, position the ring at the slot,
|
||||
// then let put(ByteBuffer) move the whole block. Mutating the ring's
|
||||
// Java position is harmless: the native reader uses a raw pointer, not
|
||||
// this position. API-26 safe (no JDK 13+ absolute bulk put).
|
||||
source.limit(source.position() + EVENT_SIZE);
|
||||
ring.position(targetOffset);
|
||||
ring.put(source);
|
||||
source.limit(sourceLimit);
|
||||
writeSeq++;
|
||||
}
|
||||
// Publish the resulting absolute state. prev* now hold the post-update
|
||||
// values, i.e. exactly the state the events just written transition to.
|
||||
writeSnapshotLocked(ring);
|
||||
nativeStoreFence();
|
||||
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Publishes the full absolute controller state for the native reader to replay
|
||||
// as a keyframe. seqlock: bump to odd, write fields, bump to even, with
|
||||
// store-store fences so the reader's acquire loads see consistent payloads.
|
||||
private void writeSnapshotLocked(ByteBuffer ring) {
|
||||
int buttons = 0;
|
||||
for (int i = 0; i < BUTTON_MAP.length; i++) {
|
||||
if (this.prevButtonStates[i]) {
|
||||
buttons |= (1 << i);
|
||||
}
|
||||
}
|
||||
long seq = ring.getLong(RING_SNAPSHOT_SEQ_OFFSET);
|
||||
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1); // odd: write in progress
|
||||
nativeStoreFence();
|
||||
ring.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, buttons);
|
||||
// Axis order must match the native kSnapshotAxisCodes:
|
||||
// X, Y, RX, RY, GAS(=triggerR), BRAKE(=triggerL), HAT0X, HAT0Y.
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET, clampShort(this.prevThumbLX));
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 2, clampShort(this.prevThumbLY));
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 4, clampShort(this.prevThumbRX));
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 6, clampShort(this.prevThumbRY));
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 8, clampShort(this.prevTriggerR));
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 10, clampShort(this.prevTriggerL));
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 12, clampShort(this.prevHatX));
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 14, clampShort(this.prevHatY));
|
||||
nativeStoreFence();
|
||||
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 2); // even: write complete
|
||||
}
|
||||
|
||||
private static short clampShort(int value) {
|
||||
if (value > Short.MAX_VALUE) {
|
||||
return Short.MAX_VALUE;
|
||||
}
|
||||
if (value < Short.MIN_VALUE) {
|
||||
return Short.MIN_VALUE;
|
||||
}
|
||||
return (short) value;
|
||||
}
|
||||
|
||||
private static void clearSnapshotLocked(ByteBuffer ring) {
|
||||
long seq = ring.getLong(RING_SNAPSHOT_SEQ_OFFSET);
|
||||
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1);
|
||||
nativeStoreFence();
|
||||
ring.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, 0);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0);
|
||||
}
|
||||
nativeStoreFence();
|
||||
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 2);
|
||||
}
|
||||
|
||||
private boolean flushBuffer() {
|
||||
return flushBufferToRing();
|
||||
}
|
||||
|
||||
public synchronized boolean open() {
|
||||
if (destroyed)
|
||||
return false;
|
||||
if (isOpen)
|
||||
return true;
|
||||
|
||||
try {
|
||||
eventFile.getParentFile().mkdirs();
|
||||
if (!eventFile.exists()) {
|
||||
eventFile.createNewFile();
|
||||
}
|
||||
if (!activateRingSlot()) {
|
||||
if (eventFile.exists()) {
|
||||
eventFile.delete();
|
||||
}
|
||||
Log.e(TAG, "Failed to open fake input mmap ring: " + eventFile.getAbsolutePath());
|
||||
return false;
|
||||
}
|
||||
isOpen = true;
|
||||
Log.i(TAG, "Opened fake input: " + eventFile.getAbsolutePath());
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "Failed to open: " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void close() {
|
||||
isOpen = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset all input state to neutral (all buttons released, axes zeroed).
|
||||
* This keeps the ring active so games that cache the file descriptor can still
|
||||
* reconnect.
|
||||
*/
|
||||
public synchronized void reset() {
|
||||
if (!isOpen && !open())
|
||||
return;
|
||||
|
||||
buffer.clear();
|
||||
hasChanges = false;
|
||||
|
||||
// Release all buttons
|
||||
for (int i = 0; i < BUTTON_MAP.length; i++) {
|
||||
if (prevButtonStates[i]) {
|
||||
prevButtonStates[i] = false;
|
||||
writeEvent(EV_MSC, MSC_SCAN, BUTTON_MAP[i]);
|
||||
writeEvent(EV_KEY, BUTTON_MAP[i], 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Zero all axes
|
||||
if (prevThumbLX != 0) {
|
||||
prevThumbLX = 0;
|
||||
writeEvent(EV_ABS, ABS_X, 0);
|
||||
}
|
||||
if (prevThumbLY != 0) {
|
||||
prevThumbLY = 0;
|
||||
writeEvent(EV_ABS, ABS_Y, 0);
|
||||
}
|
||||
if (prevThumbRX != 0) {
|
||||
prevThumbRX = 0;
|
||||
writeEvent(EV_ABS, ABS_RX, 0);
|
||||
}
|
||||
if (prevThumbRY != 0) {
|
||||
prevThumbRY = 0;
|
||||
writeEvent(EV_ABS, ABS_RY, 0);
|
||||
}
|
||||
if (prevTriggerL != 0) {
|
||||
prevTriggerL = 0;
|
||||
writeEvent(EV_ABS, ABS_BRAKE, 0);
|
||||
}
|
||||
if (prevTriggerR != 0) {
|
||||
prevTriggerR = 0;
|
||||
writeEvent(EV_ABS, ABS_GAS, 0);
|
||||
}
|
||||
if (prevHatX != 0) {
|
||||
prevHatX = 0;
|
||||
writeEvent(EV_ABS, ABS_HAT0X, 0);
|
||||
}
|
||||
if (prevHatY != 0) {
|
||||
prevHatY = 0;
|
||||
writeEvent(EV_ABS, ABS_HAT0Y, 0);
|
||||
}
|
||||
|
||||
if (hasChanges) {
|
||||
writeEvent(EV_SYN, SYN_REPORT, 0);
|
||||
buffer.flip();
|
||||
if (!flushBuffer())
|
||||
Log.e(TAG, "Reset write error: fake input mmap ring unavailable");
|
||||
}
|
||||
Log.i(TAG, "Reset fake input to neutral state: " + eventFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
public synchronized void softRelease() {
|
||||
reset();
|
||||
close();
|
||||
Log.i(TAG, "Soft released fake input: " + eventFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
/**
|
||||
* Full destroy - reset, tear the ring generation down, and delete the discovery node.
|
||||
*/
|
||||
public synchronized void destroy() {
|
||||
destroyed = true;
|
||||
reset();
|
||||
close();
|
||||
deactivateRingSlot();
|
||||
if (eventFile != null && eventFile.exists()) {
|
||||
boolean deleted = eventFile.delete();
|
||||
Log.i(TAG, "Deleted fake input discovery node: " + eventFile.getAbsolutePath() + " (" + deleted + ")");
|
||||
}
|
||||
}
|
||||
|
||||
private void writeEvent(short type, short code, int value) {
|
||||
long timeMs = System.currentTimeMillis();
|
||||
buffer.putLong(timeMs / 1000);
|
||||
buffer.putLong((timeMs % 1000) * 1000);
|
||||
buffer.putShort(type);
|
||||
buffer.putShort(code);
|
||||
buffer.putInt(value);
|
||||
hasChanges = true;
|
||||
}
|
||||
|
||||
private void writeButton(int idx, boolean pressed) {
|
||||
if (idx < 0 || idx >= BUTTON_MAP.length)
|
||||
return;
|
||||
if (!forceResend && prevButtonStates[idx] == pressed)
|
||||
return;
|
||||
prevButtonStates[idx] = pressed;
|
||||
writeEvent(EV_MSC, MSC_SCAN, BUTTON_MAP[idx]);
|
||||
writeEvent(EV_KEY, BUTTON_MAP[idx], pressed ? 1 : 0);
|
||||
}
|
||||
|
||||
public synchronized void writePad(PadState state) {
|
||||
if (!isOpen && !open())
|
||||
return;
|
||||
|
||||
// Keep the ring delta-first for latency. Full event frames are only used as
|
||||
// a one-shot repair after a failed publish; normal open/overflow recovery is
|
||||
// handled by the native snapshot keyframe.
|
||||
forceResend = pendingFullResend;
|
||||
pendingFullResend = false;
|
||||
if (forceResend) {
|
||||
Log.d(TAG, "Re-emitting full gamepad state after failed publish for slot " + slot);
|
||||
}
|
||||
|
||||
buffer.clear();
|
||||
hasChanges = false;
|
||||
|
||||
// Buttons
|
||||
for (int i = 0; i < 10; i++) {
|
||||
writeButton(i, state.isDown(i));
|
||||
}
|
||||
// The Steam button. In a Linux session this is what opens the client's own in-game menu,
|
||||
// and the client looks for it where an Xbox pad keeps it: evdev BTN_MODE, which SDL then
|
||||
// reports as button 8 - exactly the "guide:b8" in the mapping Steam writes for this pad.
|
||||
writeButton(SNAPSHOT_IDX_MODE,
|
||||
state.isDown(PadState.GUIDE));
|
||||
|
||||
// Sticks
|
||||
int lx = (int) (state.leftX * 32767);
|
||||
int ly = (int) (state.leftY * 32767);
|
||||
int rx = (int) (state.rightX * 32767);
|
||||
int ry = (int) (state.rightY * 32767);
|
||||
|
||||
// The fake evdev ring is event-queue semantics, so unchanged axes normally
|
||||
// stay silent; forceResend overrides that to emit a complete keyframe.
|
||||
if (forceResend || lx != prevThumbLX) {
|
||||
prevThumbLX = lx;
|
||||
writeEvent(EV_ABS, ABS_X, lx);
|
||||
}
|
||||
if (forceResend || ly != prevThumbLY) {
|
||||
prevThumbLY = ly;
|
||||
writeEvent(EV_ABS, ABS_Y, ly);
|
||||
}
|
||||
if (forceResend || rx != prevThumbRX) {
|
||||
prevThumbRX = rx;
|
||||
writeEvent(EV_ABS, ABS_RX, rx);
|
||||
}
|
||||
if (forceResend || ry != prevThumbRY) {
|
||||
prevThumbRY = ry;
|
||||
writeEvent(EV_ABS, ABS_RY, ry);
|
||||
}
|
||||
|
||||
// L2 and R2 (Triggers)
|
||||
int tl = (int) (state.leftTrigger * 255);
|
||||
int tr = (int) (state.rightTrigger * 255);
|
||||
if (forceResend || tl != prevTriggerL) {
|
||||
prevTriggerL = tl;
|
||||
writeEvent(EV_ABS, ABS_BRAKE, tl);
|
||||
}
|
||||
if (forceResend || tr != prevTriggerR) {
|
||||
prevTriggerR = tr;
|
||||
writeEvent(EV_ABS, ABS_GAS, tr);
|
||||
}
|
||||
|
||||
// D-pad
|
||||
int hatX = state.hatX();
|
||||
int hatY = state.hatY();
|
||||
if (forceResend || hatX != prevHatX) {
|
||||
prevHatX = hatX;
|
||||
writeEvent(EV_ABS, ABS_HAT0X, hatX);
|
||||
}
|
||||
if (forceResend || hatY != prevHatY) {
|
||||
prevHatY = hatY;
|
||||
writeEvent(EV_ABS, ABS_HAT0Y, hatY);
|
||||
}
|
||||
|
||||
// Detect change else no need to write
|
||||
if (hasChanges) {
|
||||
writeEvent(EV_SYN, SYN_REPORT, 0);
|
||||
buffer.flip();
|
||||
if (!flushBuffer()) {
|
||||
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
|
||||
// Couldn't publish; re-assert the whole state on the next frame.
|
||||
pendingFullResend = true;
|
||||
}
|
||||
}
|
||||
forceResend = false;
|
||||
}
|
||||
|
||||
public boolean isOpen() {
|
||||
return isOpen;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.text.InputType
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.inputmethod.BaseInputConnection
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.InputConnection
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
|
||||
/**
|
||||
* A place for the soft keyboard to land. Steam's UI and the games under it are X11 clients of
|
||||
* gamescope and know nothing of Wayland text input, so everything the keyboard produces has to
|
||||
* become key events: what the IME commits as text is turned into the key presses that would have
|
||||
* typed it (Shift included, from the key character map), and handed to the activity, whose key
|
||||
* path turns them into evdev codes for the compositor. Backspace, Enter and the keys an IME sends
|
||||
* directly go the same way.
|
||||
*
|
||||
* Invisible and unfocusable until asked for: a focused View would take D-pad and stick motion
|
||||
* away from the pad.
|
||||
*/
|
||||
class KeyboardHost(
|
||||
context: Context,
|
||||
private val sendKeyEvent: (KeyEvent) -> Boolean,
|
||||
) : View(context) {
|
||||
constructor(activity: Activity) : this(activity, { activity.dispatchKeyEvent(it) })
|
||||
|
||||
private val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
|
||||
var shown = false
|
||||
private set
|
||||
|
||||
init {
|
||||
isFocusable = false
|
||||
isFocusableInTouchMode = false
|
||||
visibility = VISIBLE // present in the tree, draws nothing
|
||||
layoutParams = android.widget.FrameLayout.LayoutParams(1, 1)
|
||||
}
|
||||
|
||||
override fun onCheckIsTextEditor(): Boolean = shown
|
||||
|
||||
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
|
||||
if (!shown) return null
|
||||
// No suggestions and no autocorrect: the keyboard sends what was pressed, key by key, which
|
||||
// is what a password field on the other side needs.
|
||||
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
|
||||
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
|
||||
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_FULLSCREEN or
|
||||
EditorInfo.IME_FLAG_NO_EXTRACT_UI
|
||||
return KeyConnection()
|
||||
}
|
||||
|
||||
fun toggle() = if (shown) hide() else show()
|
||||
|
||||
fun show() {
|
||||
shown = true
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
requestFocus()
|
||||
imm.restartInput(this)
|
||||
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
fun hide() {
|
||||
shown = false
|
||||
imm.hideSoftInputFromWindow(windowToken, 0)
|
||||
isFocusable = false
|
||||
isFocusableInTouchMode = false
|
||||
clearFocus()
|
||||
}
|
||||
|
||||
private inner class KeyConnection : BaseInputConnection(this, false) {
|
||||
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
if (text.isNullOrEmpty()) return true
|
||||
// The key events that type this text on a US layout - a capital arrives as Shift
|
||||
// down, the letter, Shift up. Characters the map cannot place are sent as a bare
|
||||
// key event carrying the character, which the activity's key path works back from.
|
||||
val events = map.getEvents(text.toString().toCharArray())
|
||||
if (events != null) {
|
||||
for (event in events) sendKeyEvent(event)
|
||||
} else {
|
||||
for (ch in text) {
|
||||
val t = System.currentTimeMillis()
|
||||
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
|
||||
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
|
||||
sendKeyEvent(CharKeyEvent(down, ch))
|
||||
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = true
|
||||
override fun finishComposingText(): Boolean = true
|
||||
|
||||
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
|
||||
repeat(beforeLength) { tap(KeyEvent.KEYCODE_DEL) }
|
||||
repeat(afterLength) { tap(KeyEvent.KEYCODE_FORWARD_DEL) }
|
||||
return true
|
||||
}
|
||||
|
||||
override fun sendKeyEvent(event: KeyEvent): Boolean = this@KeyboardHost.sendKeyEvent(event)
|
||||
|
||||
override fun performEditorAction(actionCode: Int): Boolean {
|
||||
tap(KeyEvent.KEYCODE_ENTER)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun tap(keyCode: Int) {
|
||||
val t = System.currentTimeMillis()
|
||||
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
|
||||
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
|
||||
}
|
||||
|
||||
override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence = ""
|
||||
override fun getTextAfterCursor(n: Int, flags: Int): CharSequence = ""
|
||||
override fun getSelectedText(flags: Int): CharSequence? = null
|
||||
}
|
||||
|
||||
/** A key event that carries a character the key map could not place. */
|
||||
private class CharKeyEvent(origin: KeyEvent, private val ch: Char) : KeyEvent(origin) {
|
||||
override fun getUnicodeChar(): Int = ch.code
|
||||
override fun getUnicodeChar(metaState: Int): Int = ch.code
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* A pad drawn on the screen for devices that have no controller attached.
|
||||
*
|
||||
* It writes into the same [PadBridge] a physical pad does, so the Steam client sees one Xbox pad
|
||||
* whichever is being used, and the two can be used at once. A d-pad, two sticks, the four face
|
||||
* buttons, the bumpers, and the three centre buttons: enough to drive Big Picture and to play,
|
||||
* and no control editor.
|
||||
*
|
||||
* Where the controls go follows the picture. The compositor letterboxes the session's output onto
|
||||
* the panel, and a foldable or a wide phone has bars beside or above and below it that are empty
|
||||
* black: the controls take the bars first, and only overlay the picture when there are none wide
|
||||
* enough. Only the controls themselves take touches; everything else falls through to the
|
||||
* activity, where it moves the mouse pointer.
|
||||
*/
|
||||
@SuppressLint("ViewConstructor")
|
||||
class OnScreenControls(context: Context, private val pad: PadBridge) : View(context) {
|
||||
|
||||
private class Control(
|
||||
val id: String,
|
||||
val label: String,
|
||||
/** A PadState button number, or -1. */
|
||||
val button: Int,
|
||||
/** A d-pad direction (0 up, 1 right, 2 down, 3 left), or -1. */
|
||||
val dpad: Int,
|
||||
/** 0 = left stick, 1 = right stick, -1 = a button. */
|
||||
val stick: Int,
|
||||
val radius: Float,
|
||||
) {
|
||||
var cx = 0f
|
||||
var cy = 0f
|
||||
var pressedBy = -1 // the pointer id holding it, or -1
|
||||
/** A stick's knob offset from its centre, in [-radius, radius]. */
|
||||
var kx = 0f
|
||||
var ky = 0f
|
||||
/** A stick that moved or was let go: its axes are written once, then left alone. */
|
||||
var dirty = false
|
||||
fun contains(x: Float, y: Float, radius: Float = this.radius): Boolean {
|
||||
val dx = x - cx
|
||||
val dy = y - cy
|
||||
// A generous hit area: a finger on glass is not a mouse, and a miss in Big Picture
|
||||
// means the user thinks the pad does not work.
|
||||
val r = radius * 1.25f
|
||||
return dx * dx + dy * dy <= r * r
|
||||
}
|
||||
/** Moves the knob towards the finger, clamped to the base. */
|
||||
fun drag(x: Float, y: Float) {
|
||||
var dx = x - cx
|
||||
var dy = y - cy
|
||||
val d = sqrt(dx * dx + dy * dy)
|
||||
if (d > radius) { dx = dx / d * radius; dy = dy / d * radius }
|
||||
kx = dx; ky = dy; dirty = true
|
||||
}
|
||||
}
|
||||
|
||||
private val density = resources.displayMetrics.density
|
||||
private fun dp(value: Float) = value * density
|
||||
|
||||
private val controls = listOf(
|
||||
Control("up", "▲", -1, 0, -1, dp(26f)),
|
||||
Control("right", ">", -1, 1, -1, dp(26f)),
|
||||
Control("down", "▼", -1, 2, -1, dp(26f)),
|
||||
Control("left", "<", -1, 3, -1, dp(26f)),
|
||||
Control("ls", "L", -1, -1, 0, dp(48f)),
|
||||
Control("rs", "R", -1, -1, 1, dp(48f)),
|
||||
Control("a", "A", 0, -1, -1, dp(30f)),
|
||||
Control("b", "B", 1, -1, -1, dp(30f)),
|
||||
Control("x", "X", 2, -1, -1, dp(30f)),
|
||||
Control("y", "Y", 3, -1, -1, dp(30f)),
|
||||
Control("lb", "LB", 4, -1, -1, dp(24f)),
|
||||
Control("rb", "RB", 5, -1, -1, dp(24f)),
|
||||
Control("select", "⧉", 6, -1, -1, dp(20f)),
|
||||
Control("start", "☰", 7, -1, -1, dp(20f)),
|
||||
// The client's own in-game menu; the interposer publishes it as BTN_MODE.
|
||||
Control("guide", "◉", PadState.GUIDE, -1, -1, dp(22f)),
|
||||
Control("qam", "⋯", -1, -1, -1, dp(22f)),
|
||||
)
|
||||
|
||||
private var buttonsOnly = false
|
||||
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = dp(1.5f)
|
||||
}
|
||||
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
typeface = android.graphics.Typeface.DEFAULT_BOLD
|
||||
}
|
||||
|
||||
/** Where the session's picture is drawn on this view, or null when the whole view is picture. */
|
||||
private var picture: RectF? = null
|
||||
|
||||
/** The activity tells the controls where the picture lands; the layout follows it. */
|
||||
fun setPicture(rect: RectF?) {
|
||||
val same = (rect == null && picture == null) || (rect != null && picture != null && rect == picture)
|
||||
if (same) return
|
||||
picture = rect?.let { RectF(it) }
|
||||
if (width > 0 && height > 0) { layoutControls(width.toFloat(), height.toFloat()); invalidate() }
|
||||
}
|
||||
|
||||
fun setButtonsOnly(enabled: Boolean) {
|
||||
if (buttonsOnly == enabled) return
|
||||
releaseAll()
|
||||
buttonsOnly = enabled
|
||||
if (width > 0 && height > 0) layoutControls(width.toFloat(), height.toFloat())
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
super.onSizeChanged(w, h, oldw, oldh)
|
||||
layoutControls(w.toFloat(), h.toFloat())
|
||||
}
|
||||
|
||||
/**
|
||||
* Three layouts: side bars (a wide panel showing 16:9), bottom band (a squarer panel showing
|
||||
* a wide picture), and the overlay when neither bar is wide enough for a cluster. Thumbs reach
|
||||
* the bottom corners in every one; nothing is placed where a game's own HUD usually is.
|
||||
*/
|
||||
private fun layoutControls(w: Float, h: Float) {
|
||||
if (buttonsOnly) {
|
||||
val inset = dp(44f)
|
||||
place("guide", inset, h - inset)
|
||||
place("qam", w - inset, h - inset)
|
||||
return
|
||||
}
|
||||
val p = picture
|
||||
val sideBar = if (p != null) minOf(p.left, w - p.right) else 0f
|
||||
val bottomBand = if (p != null) h - p.bottom else 0f
|
||||
val margin = dp(34f)
|
||||
when {
|
||||
// A cluster (d-pad or face buttons) is ~156 dp across; a stick above it needs the height.
|
||||
sideBar >= dp(160f) && p != null -> {
|
||||
val lx = p.left / 2f
|
||||
val rx = p.right + (w - p.right) / 2f
|
||||
val bottom = h - margin - dp(74f)
|
||||
dpadAt(lx, bottom)
|
||||
faceAt(rx, bottom)
|
||||
place("ls", lx, bottom - dp(196f))
|
||||
place("rs", rx, bottom - dp(196f))
|
||||
place("lb", lx, bottom - dp(196f) - dp(96f))
|
||||
place("rb", rx, bottom - dp(196f) - dp(96f))
|
||||
place("select", lx, h - margin + dp(8f))
|
||||
place("start", rx, h - margin + dp(8f))
|
||||
place("guide", w / 2f, h - dp(22f))
|
||||
}
|
||||
bottomBand >= dp(190f) && p != null -> {
|
||||
val cy = p.bottom + bottomBand / 2f + dp(12f)
|
||||
val dx = margin + dp(74f)
|
||||
val fx = w - margin - dp(74f)
|
||||
dpadAt(dx, cy)
|
||||
faceAt(fx, cy)
|
||||
place("ls", dx + dp(150f), cy)
|
||||
place("rs", fx - dp(150f), cy)
|
||||
place("lb", dx, p.bottom + dp(30f))
|
||||
place("rb", fx, p.bottom + dp(30f))
|
||||
val centre = w / 2f
|
||||
place("select", centre - dp(60f), h - dp(30f))
|
||||
place("guide", centre, h - dp(30f))
|
||||
place("start", centre + dp(60f), h - dp(30f))
|
||||
}
|
||||
else -> {
|
||||
val dx = margin + dp(74f)
|
||||
val fx = w - margin - dp(74f)
|
||||
val bottom = h - margin - dp(74f)
|
||||
dpadAt(dx, bottom)
|
||||
faceAt(fx, bottom)
|
||||
place("ls", dx + dp(142f), bottom)
|
||||
place("rs", fx - dp(142f), bottom)
|
||||
place("lb", margin + dp(46f), h - margin - dp(196f))
|
||||
place("rb", w - margin - dp(46f), h - margin - dp(196f))
|
||||
val centre = w / 2f
|
||||
place("select", centre - dp(60f), h - margin - dp(26f))
|
||||
place("guide", centre, h - margin - dp(26f))
|
||||
place("start", centre + dp(60f), h - margin - dp(26f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun dpadAt(x: Float, y: Float) {
|
||||
val step = dp(52f)
|
||||
place("up", x, y - step)
|
||||
place("down", x, y + step)
|
||||
place("left", x - step, y)
|
||||
place("right", x + step, y)
|
||||
}
|
||||
|
||||
private fun faceAt(x: Float, y: Float) {
|
||||
val step = dp(50f)
|
||||
place("a", x, y + step)
|
||||
place("b", x + step, y)
|
||||
place("x", x - step, y)
|
||||
place("y", x, y - step)
|
||||
}
|
||||
|
||||
private fun place(id: String, x: Float, y: Float) {
|
||||
val control = controls.firstOrNull { it.id == id } ?: return
|
||||
control.cx = x
|
||||
control.cy = y
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
for (control in controls) {
|
||||
if (!isVisible(control)) continue
|
||||
val held = control.pressedBy != -1
|
||||
val radius = controlRadius(control)
|
||||
if (control.stick >= 0) {
|
||||
// The base, then the knob where the finger holds it.
|
||||
fill.color = if (held) Color.argb(60, 199, 125, 255) else Color.argb(50, 20, 12, 30)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, fill)
|
||||
stroke.color = if (held) Color.argb(200, 235, 212, 255) else Color.argb(90, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, stroke)
|
||||
val knob = radius * 0.46f
|
||||
fill.color = if (held) Color.argb(170, 199, 125, 255) else Color.argb(110, 60, 40, 90)
|
||||
canvas.drawCircle(control.cx + control.kx, control.cy + control.ky, knob, fill)
|
||||
stroke.color = if (held) Color.argb(230, 245, 230, 255) else Color.argb(140, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx + control.kx, control.cy + control.ky, knob, stroke)
|
||||
text.color = if (held) Color.WHITE else Color.argb(150, 225, 210, 245)
|
||||
text.textSize = knob * 0.8f
|
||||
canvas.drawText(control.label, control.cx + control.kx, control.cy + control.ky + text.textSize * 0.35f, text)
|
||||
continue
|
||||
}
|
||||
fill.color = if (held) Color.argb(150, 199, 125, 255) else Color.argb(70, 20, 12, 30)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, fill)
|
||||
stroke.color = if (held) Color.argb(220, 235, 212, 255) else Color.argb(110, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, stroke)
|
||||
text.color = if (held) Color.WHITE else Color.argb(190, 225, 210, 245)
|
||||
val label = if (buttonsOnly && control.id == "guide") "Steam" else control.label
|
||||
text.textSize = if (buttonsOnly && control.id == "guide") dp(11f) else radius * 0.85f
|
||||
canvas.drawText(label, control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val index = event.actionIndex
|
||||
val control = controlAt(event.getX(index), event.getY(index)) ?: return false
|
||||
control.pressedBy = event.getPointerId(index)
|
||||
if (control.stick >= 0) control.drag(event.getX(index), event.getY(index))
|
||||
apply()
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
var changed = false
|
||||
for (index in 0 until event.pointerCount) {
|
||||
val pointer = event.getPointerId(index)
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
// A stick keeps its finger wherever it goes: the knob follows, clamped.
|
||||
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
|
||||
if (stick != null) { stick.drag(x, y); changed = true; continue }
|
||||
// A finger that slides off a button releases it, and one that slides onto
|
||||
// another presses that - which is how a d-pad is used in practice.
|
||||
val over = controlAt(x, y)?.takeIf { it.stick < 0 }
|
||||
for (control in controls) {
|
||||
if (control.stick < 0 && control.pressedBy == pointer && control !== over) {
|
||||
control.pressedBy = -1
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (over != null && over.pressedBy == -1) {
|
||||
over.pressedBy = pointer
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (changed) apply()
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
val pointer = event.getPointerId(event.actionIndex)
|
||||
var changed = false
|
||||
for (control in controls) {
|
||||
if (control.pressedBy == pointer || event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
if (control.pressedBy != -1) changed = true
|
||||
control.pressedBy = -1
|
||||
if (control.stick >= 0 && (control.kx != 0f || control.ky != 0f)) control.dirty = true
|
||||
control.kx = 0f; control.ky = 0f
|
||||
}
|
||||
}
|
||||
if (changed) apply()
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun controlAt(x: Float, y: Float): Control? =
|
||||
controls.firstOrNull { isVisible(it) && it.contains(x, y, controlRadius(it)) }
|
||||
|
||||
private fun isVisible(control: Control): Boolean =
|
||||
!buttonsOnly || control.id == "guide" || control.id == "qam"
|
||||
|
||||
private fun controlRadius(control: Control): Float =
|
||||
if (buttonsOnly && (control.id == "guide" || control.id == "qam")) dp(30f) else control.radius
|
||||
|
||||
private fun apply() {
|
||||
if (buttonsOnly) {
|
||||
val guidePressed = controls.first { it.id == "guide" }.pressedBy != -1
|
||||
val qamPressed = controls.first { it.id == "qam" }.pressedBy != -1
|
||||
pad.setSystemButtons(guidePressed, qamPressed)
|
||||
} else {
|
||||
pad.setSystemButtons(false, false)
|
||||
pad.applyTouch { state ->
|
||||
for (control in controls) {
|
||||
val held = control.pressedBy != -1
|
||||
when {
|
||||
control.stick >= 0 && !control.dirty -> {}
|
||||
control.stick == 0 -> { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius; control.dirty = false }
|
||||
control.stick == 1 -> { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius; control.dirty = false }
|
||||
control.dpad == 0 -> state.up = held
|
||||
control.dpad == 1 -> state.right = held
|
||||
control.dpad == 2 -> state.down = held
|
||||
control.dpad == 3 -> state.left = held
|
||||
control.button >= 0 -> state.press(control.button, held)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** Everything up, for when the controls are hidden mid-press. */
|
||||
fun releaseAll() {
|
||||
if (controls.none { it.pressedBy != -1 } && !buttonsOnly) return
|
||||
controls.forEach { it.pressedBy = -1; if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true; it.kx = 0f; it.ky = 0f }
|
||||
apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package com.droiddeck.launcher.input;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.view.InputDevice;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* A physical controller, republished as a synthetic evdev device the Steam client can see.
|
||||
*
|
||||
* <p>Android hands a gamepad to the foreground activity as key and motion events; the Steam client
|
||||
* inside the runtime never sees that. What it does scan is {@code /dev/input}, which the session's
|
||||
* interposer (libfakeinput.so) serves out of the shared-memory rings written here. So the path is:
|
||||
* Android event → {@link PadState} → {@link FakeInputWriter} ring → interposer → evdev node →
|
||||
* SDL → Big Picture.
|
||||
*
|
||||
* <p>The identity the interposer reports is an Xbox 360 pad, which is what makes SDL apply a known
|
||||
* mapping without the user configuring anything.
|
||||
*/
|
||||
public final class PadBridge {
|
||||
private static final String TAG = "PadBridge";
|
||||
/** Slot 0 is the one the session exports; extra slots would each show as another pad. */
|
||||
private static final int SLOT = 0;
|
||||
private static final float DEAD_ZONE = 0.12f;
|
||||
private static final long QAM_GUIDE_LEAD_MS = 80;
|
||||
private static final long QAM_A_HOLD_MS = 120;
|
||||
private static final long QAM_GUIDE_TAIL_MS = 40;
|
||||
|
||||
private final FakeInputWriter writer;
|
||||
private final PadState state = new PadState();
|
||||
private final PadState effectiveState = new PadState();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private boolean open;
|
||||
private boolean systemGuidePressed;
|
||||
private boolean systemQamPressed;
|
||||
private boolean qamChordActive;
|
||||
private boolean qamSyntheticAPressed;
|
||||
private int qamChordGeneration;
|
||||
|
||||
public PadBridge(File fakeInputDir) {
|
||||
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
|
||||
}
|
||||
|
||||
/** Opens the ring; safe to call more than once. */
|
||||
public synchronized boolean start() {
|
||||
if (!open) {
|
||||
open = writer.open();
|
||||
Log.i(TAG, "ring slot " + SLOT + (open ? " open" : " NOT open"));
|
||||
}
|
||||
return open;
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
qamChordActive = false;
|
||||
qamSyntheticAPressed = false;
|
||||
qamChordGeneration++;
|
||||
if (open) {
|
||||
state.clear();
|
||||
writer.writePad(state);
|
||||
writer.close();
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the device this event came from is a gamepad or joystick, not the touchscreen. */
|
||||
public static boolean isFromController(InputDevice device) {
|
||||
if (device == null) return false;
|
||||
// A virtual device is the system's own synthetic input, not a pad somebody is holding -
|
||||
// counting it would hide the on-screen controls with nothing to replace them.
|
||||
if (device.isVirtual()) return false;
|
||||
int sources = device.getSources();
|
||||
return (sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD
|
||||
|| (sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK;
|
||||
}
|
||||
|
||||
/** Whether any real controller is attached right now. */
|
||||
public static boolean anyControllerConnected() {
|
||||
for (int id : InputDevice.getDeviceIds()) {
|
||||
if (isFromController(InputDevice.getDevice(id))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @return true when the event was a pad button and has been consumed. */
|
||||
public synchronized boolean onKeyEvent(KeyEvent event) {
|
||||
if (!isFromController(event.getDevice())) return false;
|
||||
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
|
||||
switch (event.getKeyCode()) {
|
||||
case KeyEvent.KEYCODE_BUTTON_A: state.press(0, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_B: state.press(1, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_X: state.press(2, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_Y: state.press(3, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_L1: state.press(4, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_R1: state.press(5, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_SELECT:
|
||||
case KeyEvent.KEYCODE_BACK: state.press(6, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_START:
|
||||
case KeyEvent.KEYCODE_MENU: state.press(7, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBL: state.press(8, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBR: state.press(9, pressed); break;
|
||||
// The client's own in-game menu is opened by this one; the interposer publishes it as
|
||||
// BTN_MODE, which SDL reports as the "guide" button.
|
||||
case KeyEvent.KEYCODE_BUTTON_MODE:
|
||||
case KeyEvent.KEYCODE_HOME: state.press(PadState.GUIDE, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_L2: state.leftTrigger = pressed ? 1f : 0f; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_R2: state.rightTrigger = pressed ? 1f : 0f; break;
|
||||
case KeyEvent.KEYCODE_DPAD_UP: state.up = pressed; break;
|
||||
case KeyEvent.KEYCODE_DPAD_RIGHT: state.right = pressed; break;
|
||||
case KeyEvent.KEYCODE_DPAD_DOWN: state.down = pressed; break;
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT: state.left = pressed; break;
|
||||
default: return false;
|
||||
}
|
||||
publish();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return true when the event was a pad's sticks/triggers and has been consumed. */
|
||||
public synchronized boolean onMotionEvent(MotionEvent event) {
|
||||
if (!isFromController(event.getDevice())) return false;
|
||||
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
|
||||
state.leftX = axis(event, MotionEvent.AXIS_X);
|
||||
// Android's Y axis grows downwards and evdev's ABS_Y does too, so no flip here: what the
|
||||
// pad reports as "down" is what the client is told.
|
||||
state.leftY = axis(event, MotionEvent.AXIS_Y);
|
||||
state.rightX = axis(event, MotionEvent.AXIS_Z);
|
||||
state.rightY = axis(event, MotionEvent.AXIS_RZ);
|
||||
float lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
|
||||
float rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
|
||||
// Some pads only report the triggers on BRAKE/GAS.
|
||||
if (lt == 0f) lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
|
||||
if (rt == 0f) rt = event.getAxisValue(MotionEvent.AXIS_GAS);
|
||||
state.leftTrigger = lt;
|
||||
state.rightTrigger = rt;
|
||||
float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
|
||||
float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
|
||||
state.up = hatY < -0.5f;
|
||||
state.right = hatX > 0.5f;
|
||||
state.down = hatY > 0.5f;
|
||||
state.left = hatX < -0.5f;
|
||||
publish();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The on-screen controls' way in: they mutate the same state a physical pad writes, so the
|
||||
* client only ever sees one device and a user can use both at once without them fighting.
|
||||
*/
|
||||
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
|
||||
mutation.accept(state);
|
||||
publish();
|
||||
}
|
||||
|
||||
/** Touch-only Steam and QAM buttons, merged with physical input without changing its state. */
|
||||
public synchronized void setSystemButtons(boolean guidePressed, boolean qamPressed) {
|
||||
if (systemGuidePressed == guidePressed && systemQamPressed == qamPressed) return;
|
||||
boolean qamStarted = qamPressed && !systemQamPressed;
|
||||
systemGuidePressed = guidePressed;
|
||||
systemQamPressed = qamPressed;
|
||||
if (qamStarted) startQamChord();
|
||||
else publish();
|
||||
}
|
||||
|
||||
/** Starts the same Guide-then-A sequence used by the touch QAM button. */
|
||||
public synchronized void triggerQam() {
|
||||
startQamChord();
|
||||
}
|
||||
|
||||
private void startQamChord() {
|
||||
if (qamChordActive) return;
|
||||
qamChordActive = true;
|
||||
int generation = ++qamChordGeneration;
|
||||
publish();
|
||||
mainHandler.postDelayed(() -> pressQamA(generation), QAM_GUIDE_LEAD_MS);
|
||||
}
|
||||
|
||||
private synchronized void pressQamA(int generation) {
|
||||
if (generation != qamChordGeneration || !qamChordActive) return;
|
||||
qamSyntheticAPressed = true;
|
||||
publish();
|
||||
mainHandler.postDelayed(() -> releaseQamA(generation), QAM_A_HOLD_MS);
|
||||
}
|
||||
|
||||
private synchronized void releaseQamA(int generation) {
|
||||
if (generation != qamChordGeneration || !qamChordActive) return;
|
||||
qamSyntheticAPressed = false;
|
||||
publish();
|
||||
mainHandler.postDelayed(() -> releaseQamGuide(generation), QAM_GUIDE_TAIL_MS);
|
||||
}
|
||||
|
||||
private synchronized void releaseQamGuide(int generation) {
|
||||
if (generation != qamChordGeneration || !qamChordActive) return;
|
||||
qamChordActive = false;
|
||||
publish();
|
||||
}
|
||||
|
||||
private void publish() {
|
||||
if (!open && !start()) return;
|
||||
if (systemGuidePressed || qamChordActive) {
|
||||
effectiveState.copyFrom(state);
|
||||
effectiveState.press(PadState.GUIDE, true);
|
||||
if (qamSyntheticAPressed) {
|
||||
effectiveState.press(PadState.A, state.isDown(PadState.A) || qamSyntheticAPressed);
|
||||
}
|
||||
writer.writePad(effectiveState);
|
||||
} else {
|
||||
writer.writePad(state);
|
||||
}
|
||||
}
|
||||
|
||||
private static float axis(MotionEvent event, int axis) {
|
||||
float value = event.getAxisValue(axis);
|
||||
return Math.abs(value) < DEAD_ZONE ? 0f : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
/**
|
||||
* What one Xbox-shaped pad is doing right now: two sticks and two triggers as -1..1 / 0..1, the
|
||||
* four d-pad directions, and a bitmask of the buttons numbered the way the fake evdev node
|
||||
* reports them. Written by whatever drives the pad (a physical controller, the on-screen one, or
|
||||
* both at once) and read by [FakeInputWriter] into the guest's input ring.
|
||||
*/
|
||||
class PadState {
|
||||
@JvmField var leftX = 0f
|
||||
@JvmField var leftY = 0f
|
||||
@JvmField var rightX = 0f
|
||||
@JvmField var rightY = 0f
|
||||
@JvmField var leftTrigger = 0f
|
||||
@JvmField var rightTrigger = 0f
|
||||
@JvmField var up = false
|
||||
@JvmField var right = false
|
||||
@JvmField var down = false
|
||||
@JvmField var left = false
|
||||
private var buttons = 0
|
||||
|
||||
fun press(button: Int, down: Boolean) {
|
||||
buttons = if (down) buttons or (1 shl button) else buttons and (1 shl button).inv()
|
||||
}
|
||||
|
||||
fun isDown(button: Int): Boolean = buttons and (1 shl button) != 0
|
||||
|
||||
/** The d-pad as a hat: -1 left, 1 right; -1 up, 1 down. Opposites cancel to 0. */
|
||||
fun hatX(): Int = if (right && !left) 1 else if (left && !right) -1 else 0
|
||||
fun hatY(): Int = if (down && !up) 1 else if (up && !down) -1 else 0
|
||||
|
||||
fun copyFrom(other: PadState) {
|
||||
leftX = other.leftX; leftY = other.leftY; rightX = other.rightX; rightY = other.rightY
|
||||
leftTrigger = other.leftTrigger; rightTrigger = other.rightTrigger
|
||||
up = other.up; right = other.right; down = other.down; left = other.left
|
||||
buttons = other.buttons
|
||||
}
|
||||
|
||||
/** Everything released and centred. */
|
||||
fun clear() {
|
||||
leftX = 0f; leftY = 0f; rightX = 0f; rightY = 0f
|
||||
leftTrigger = 0f; rightTrigger = 0f
|
||||
up = false; right = false; down = false; left = false
|
||||
buttons = 0
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val A = 0
|
||||
const val B = 1
|
||||
const val X = 2
|
||||
const val Y = 3
|
||||
const val LB = 4
|
||||
const val RB = 5
|
||||
const val SELECT = 6
|
||||
const val START = 7
|
||||
const val L3 = 8
|
||||
const val R3 = 9
|
||||
/** The Steam/Guide button, which the fake evdev node reports as BTN_MODE. */
|
||||
const val GUIDE = 12
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewConfiguration
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Touch as a mouse, the way a remote desktop does it: where you touch is where the pointer goes.
|
||||
*
|
||||
* - tap ............................ left click
|
||||
* - drag ........................... moves the pointer, no button (hover)
|
||||
* - hold, then lift ................ right click
|
||||
* - hold, then drag ................ left-button drag (a window by its title bar, a selection)
|
||||
* - two fingers up / down .......... scroll wheel
|
||||
*
|
||||
* The listener gets pointer positions in the view's pixels; the activity maps them onto the
|
||||
* compositor. Mouse events are not handled here - a mouse has real buttons.
|
||||
*/
|
||||
class PointerGestures(
|
||||
private val slopPx: Float,
|
||||
private val listener: Listener,
|
||||
) {
|
||||
interface Listener {
|
||||
fun onMove(x: Float, y: Float)
|
||||
/** [button] is an evdev code: BTN_LEFT, BTN_RIGHT. */
|
||||
fun onButton(button: Int, pressed: Boolean, x: Float, y: Float)
|
||||
fun onWheel(steps: Int)
|
||||
fun onLongPress()
|
||||
}
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var downX = 0f
|
||||
private var downY = 0f
|
||||
private var downAt = 0L
|
||||
private var moved = false
|
||||
private var held = false // the long press fired
|
||||
private var dragging = false // left button down after a hold
|
||||
private var scrolling = false
|
||||
private var scrollAnchorY = 0f
|
||||
private val longPress = Runnable {
|
||||
held = true
|
||||
listener.onLongPress()
|
||||
}
|
||||
|
||||
fun onTouch(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
downX = event.x; downY = event.y; downAt = event.eventTime
|
||||
moved = false; held = false; dragging = false; scrolling = false
|
||||
listener.onMove(event.x, event.y)
|
||||
handler.postDelayed(longPress, HOLD_MS)
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
// A second finger: scrolling, and whatever the first one was doing is off.
|
||||
handler.removeCallbacks(longPress)
|
||||
if (dragging) { listener.onButton(BTN_LEFT, false, event.x, event.y); dragging = false }
|
||||
scrolling = true
|
||||
scrollAnchorY = event.getY(0)
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (scrolling) {
|
||||
val dy = event.getY(0) - scrollAnchorY
|
||||
val steps = (dy / SCROLL_STEP_PX).toInt()
|
||||
if (steps != 0) {
|
||||
// Finger down = content up = wheel "up", which the compositor takes as negative.
|
||||
listener.onWheel(-steps)
|
||||
scrollAnchorY += steps * SCROLL_STEP_PX
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (!moved && (abs(event.x - downX) > slopPx || abs(event.y - downY) > slopPx)) {
|
||||
moved = true
|
||||
handler.removeCallbacks(longPress)
|
||||
if (held) {
|
||||
// Held, then moved: a drag with the left button, from where the hold was.
|
||||
dragging = true
|
||||
listener.onButton(BTN_LEFT, true, downX, downY)
|
||||
}
|
||||
}
|
||||
if (moved) listener.onMove(event.x, event.y)
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
handler.removeCallbacks(longPress)
|
||||
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL
|
||||
when {
|
||||
scrolling -> {}
|
||||
dragging -> listener.onButton(BTN_LEFT, false, event.x, event.y)
|
||||
held && !moved && !cancelled -> {
|
||||
listener.onButton(BTN_RIGHT, true, downX, downY)
|
||||
listener.onButton(BTN_RIGHT, false, downX, downY)
|
||||
}
|
||||
!moved && !cancelled && event.eventTime - downAt < TAP_MS -> {
|
||||
listener.onButton(BTN_LEFT, true, downX, downY)
|
||||
listener.onButton(BTN_LEFT, false, downX, downY)
|
||||
}
|
||||
}
|
||||
scrolling = false; dragging = false; held = false
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_UP -> return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val BTN_LEFT = 0x110
|
||||
const val BTN_RIGHT = 0x111
|
||||
const val BTN_MIDDLE = 0x112
|
||||
private const val HOLD_MS = 450L
|
||||
private const val TAP_MS = 350L
|
||||
private const val SCROLL_STEP_PX = 40f
|
||||
|
||||
fun slop(context: android.content.Context) = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
/** The control surface shown on a secondary Android display during a Linux session. */
|
||||
enum class SecondScreenMode(val id: String, val label: String) {
|
||||
NONE("none", "None"),
|
||||
KEYBOARD_TRACKPAD("keyboard-trackpad", "Keyboard + trackpad"),
|
||||
TERMINAL("terminal", "Terminal"),
|
||||
}
|
||||
|
||||
data class SecondScreenDisplay(val id: Int, val label: String)
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.MotionEvent
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* The screen as a touchpad, the way Bannerlator's desktop containers work: the arrow is where it
|
||||
* was, and a finger dragged anywhere moves it from there.
|
||||
*
|
||||
* - drag one finger .................. moves the pointer (relative, with a little acceleration)
|
||||
* - tap .............................. left click, where the pointer is
|
||||
* - second finger taps while one holds right click
|
||||
* - two-finger tap ................... right click
|
||||
* - two fingers up / down ............ scroll wheel
|
||||
* - hold still, then drag ............ left-button drag
|
||||
* - double-tap, hold, drag ........... left-button drag as well
|
||||
*
|
||||
* Positions handed to the listener are the pointer's, in the view's pixels; the caller keeps them
|
||||
* inside the picture.
|
||||
*/
|
||||
class TouchpadGestures(
|
||||
private val slopPx: Float,
|
||||
private val listener: PointerGestures.Listener,
|
||||
) {
|
||||
/** The pointer, tracked here since every move is relative. */
|
||||
var x = 0f
|
||||
private set
|
||||
var y = 0f
|
||||
private set
|
||||
var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f)
|
||||
var sensitivity = 1.15f
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var lastX = 0f
|
||||
private var lastY = 0f
|
||||
private var downAt = 0L
|
||||
private var lastTapAt = 0L
|
||||
private var travelled = 0f
|
||||
private var dragging = false
|
||||
private var held = false
|
||||
private var secondDownAt = 0L
|
||||
private var secondWasTap = false
|
||||
private var twoFingers = false
|
||||
private var scrollAnchorY = 0f
|
||||
private var scrolled = false
|
||||
private val longPress = Runnable {
|
||||
held = true
|
||||
dragging = true
|
||||
listener.onLongPress()
|
||||
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
|
||||
}
|
||||
|
||||
fun place(px: Float, py: Float) {
|
||||
x = px.coerceIn(bounds.left, bounds.right)
|
||||
y = py.coerceIn(bounds.top, bounds.bottom)
|
||||
}
|
||||
|
||||
fun onTouch(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
lastX = event.x; lastY = event.y
|
||||
downAt = event.eventTime
|
||||
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
|
||||
// A tap shortly before this touch: holding now drags (double-tap-and-hold).
|
||||
if (event.eventTime - lastTapAt < DOUBLE_TAP_MS) {
|
||||
dragging = true
|
||||
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
|
||||
} else {
|
||||
dragging = false
|
||||
handler.postDelayed(longPress, HOLD_MS)
|
||||
}
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
handler.removeCallbacks(longPress)
|
||||
twoFingers = true
|
||||
secondDownAt = event.eventTime
|
||||
secondWasTap = true
|
||||
scrollAnchorY = (event.getY(0) + event.getY(1)) / 2f
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (twoFingers && event.pointerCount >= 2) {
|
||||
val mid = (event.getY(0) + event.getY(1)) / 2f
|
||||
val dy = mid - scrollAnchorY
|
||||
val steps = (dy / SCROLL_STEP_PX).toInt()
|
||||
if (steps != 0) {
|
||||
listener.onWheel(-steps)
|
||||
scrollAnchorY += steps * SCROLL_STEP_PX
|
||||
scrolled = true
|
||||
secondWasTap = false
|
||||
}
|
||||
return true
|
||||
}
|
||||
val dx = event.x - lastX
|
||||
val dy = event.y - lastY
|
||||
lastX = event.x; lastY = event.y
|
||||
travelled += abs(dx) + abs(dy)
|
||||
if (travelled > slopPx) {
|
||||
handler.removeCallbacks(longPress)
|
||||
// A little acceleration: a slow finger is precise, a fast one crosses the screen.
|
||||
val speed = (abs(dx) + abs(dy))
|
||||
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
|
||||
place(x + dx * gain, y + dy * gain)
|
||||
listener.onMove(x, y)
|
||||
}
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_UP -> {
|
||||
// The second finger lifting quickly, with nothing scrolled: a right click.
|
||||
if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TAP_MS && !scrolled) {
|
||||
listener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
|
||||
listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
|
||||
secondWasTap = false
|
||||
}
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
handler.removeCallbacks(longPress)
|
||||
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL
|
||||
when {
|
||||
dragging -> listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
|
||||
twoFingers -> {
|
||||
// Both fingers down and up together, no scroll: a right click.
|
||||
if (secondWasTap && !scrolled && !cancelled && event.eventTime - downAt < TAP_MS * 2) {
|
||||
listener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
|
||||
listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
|
||||
}
|
||||
}
|
||||
!cancelled && travelled <= slopPx && event.eventTime - downAt < TAP_MS -> {
|
||||
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
|
||||
listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
|
||||
lastTapAt = event.eventTime
|
||||
}
|
||||
}
|
||||
dragging = false; held = false; twoFingers = false
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val HOLD_MS = 500L
|
||||
private const val TAP_MS = 300L
|
||||
private const val DOUBLE_TAP_MS = 300L
|
||||
private const val SCROLL_STEP_PX = 36f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The hosted packages that go into the runtime on request - the desktop, the emulators, and the
|
||||
* builds we mirror or make ourselves - described by desktop.json beside the runtime's own catalog.
|
||||
*
|
||||
* Two kinds. A `tar` extracts over the rootfs like the runtime itself (the same extractor, links
|
||||
* and modes preserved). An `appimage` is one file dropped in /opt/appimages with a .desktop entry
|
||||
* written for it; proot has no FUSE, so it runs extracted (APPIMAGE_EXTRACT_AND_RUN).
|
||||
*/
|
||||
object DesktopCatalog {
|
||||
private const val TAG = "DesktopCatalog"
|
||||
const val CATALOG_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/desktop.json"
|
||||
|
||||
class Entry(
|
||||
val id: String, val name: String, val tier: Int, val version: String, val kind: String,
|
||||
val url: String, val sha256: String, val size: Long, val notes: String,
|
||||
/** For an appimage: the icon name and menu category of its .desktop entry. */
|
||||
val icon: String, val category: String,
|
||||
)
|
||||
|
||||
fun fetch(): List<Entry>? {
|
||||
val body = Downloader.downloadString(CATALOG_URL) ?: return null
|
||||
return try {
|
||||
val json = JSONObject(body)
|
||||
val arr = json.getJSONArray("packages")
|
||||
(0 until arr.length()).map { i ->
|
||||
val o = arr.getJSONObject(i)
|
||||
Entry(
|
||||
o.getString("id"), o.getString("name"), o.optInt("tier", 1), o.optString("version", ""),
|
||||
o.optString("kind", "tar"), o.getString("url"), o.optString("sha256", ""),
|
||||
o.optLong("size", 0L), o.optString("notes", ""),
|
||||
o.optString("icon", "applications-games"), o.optString("category", "Game"),
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "catalog: $e"); null
|
||||
}
|
||||
}
|
||||
|
||||
private fun marker(context: Context, id: String) = File(LinuxRuntime.rootDir(context), ".droiddeck-pkg-$id")
|
||||
|
||||
/** The installed version of a package, or null. */
|
||||
fun installed(context: Context, id: String): String? =
|
||||
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
// labwc comes with the hosted desktop package itself (its launcher is staged by the app at
|
||||
// every session, so it cannot tell whether the package is there); SessionFiles uses the same test.
|
||||
fun desktopInstalled(context: Context): Boolean =
|
||||
File(LinuxRuntime.rootDir(context), "usr/bin/labwc").isFile
|
||||
|
||||
/** Downloads, verifies and installs one package. Returns null on success, else a message. */
|
||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (!root.isDirectory) return "The Linux runtime is not installed"
|
||||
val download = File(context.cacheDir, "pkg-${entry.id}.download")
|
||||
try {
|
||||
listener?.onProgress("Downloading ${entry.name}", 0)
|
||||
val ok = Downloader.downloadFile(entry.url, download, true) { f ->
|
||||
listener?.onProgress("Downloading ${entry.name}", if (f < 0) -1 else Math.round(f * 100f))
|
||||
}
|
||||
if (!ok) return "Download failed"
|
||||
if (entry.sha256.isNotEmpty()) {
|
||||
listener?.onProgress("Verifying", -1)
|
||||
val actual = LinuxRuntimeInstaller.sha256(download)
|
||||
if (!entry.sha256.equals(actual, ignoreCase = true)) return "Checksum mismatch - nothing was changed"
|
||||
}
|
||||
listener?.onProgress("Installing ${entry.name}", -1)
|
||||
when (entry.kind) {
|
||||
"appimage" -> {
|
||||
val dir = File(root, "opt/appimages").apply { mkdirs() }
|
||||
val target = File(dir, "${entry.id}.AppImage")
|
||||
// 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)
|
||||
else download.renameTo(target)
|
||||
if (!placed) return "Could not place the AppImage"
|
||||
target.setExecutable(true, false)
|
||||
FileUtils.writeString(File(root, "usr/share/applications/droiddeck-${entry.id}.desktop"),
|
||||
"[Desktop Entry]\nType=Application\nName=${entry.name}\n" +
|
||||
"Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/${entry.id}.AppImage\n" +
|
||||
"Icon=${entry.icon}\nTerminal=false\nCategories=${entry.category};\n")
|
||||
}
|
||||
else -> if (!LinuxRuntimeInstaller.extract(download, root, listener)) return "Extraction failed"
|
||||
}
|
||||
FileUtils.writeString(marker(context, entry.id), entry.version)
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "install ${entry.id}", e)
|
||||
return e.message ?: "Install failed"
|
||||
} finally {
|
||||
download.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun unzipAppImage(zip: File, target: File): Boolean {
|
||||
try {
|
||||
java.util.zip.ZipInputStream(java.io.BufferedInputStream(java.io.FileInputStream(zip))).use { zin ->
|
||||
var entry = zin.nextEntry
|
||||
while (entry != null) {
|
||||
if (!entry.isDirectory && entry.name.endsWith(".AppImage", ignoreCase = true)) {
|
||||
java.io.FileOutputStream(target).use { out -> FileUtils.copy(zin, out) }
|
||||
return true
|
||||
}
|
||||
entry = zin.nextEntry
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "unzip ${zip.name}", e)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an appimage package outright. A tar package is spread through the rootfs and is
|
||||
* not tracked file by file; only its marker is dropped, which offers it again.
|
||||
*/
|
||||
fun remove(context: Context, entry: Entry) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (entry.kind == "appimage") {
|
||||
File(root, "opt/appimages/${entry.id}.AppImage").delete()
|
||||
File(root, "usr/share/applications/droiddeck-${entry.id}.desktop").delete()
|
||||
}
|
||||
marker(context, entry.id).delete()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.Inet4Address
|
||||
import java.net.Inet6Address
|
||||
|
||||
/**
|
||||
* The device's network link, published for the Linux runtime's processes.
|
||||
*
|
||||
* Android denies an app the rtnetlink dump behind getifaddrs() and if_nameindex(), the hardware
|
||||
* address ioctl and every table under /proc/net. Wine builds its adapter, address, route and
|
||||
* neighbour tables from those, so a game under the runtime saw no adapter, no address, no gateway
|
||||
* and no MAC - and one that checks its adapters before going online waited for good. The link the
|
||||
* app can see through ConnectivityManager is written here, kept current while the session runs,
|
||||
* and the session shim answers whatever the kernel refuses from it (tools/linuxfs/preload/netif.c).
|
||||
*
|
||||
* Shape follows WinNative's LinuxNetworkLinkComponent (maxjivi05, f76a5c4a), GPL-3.0.
|
||||
*/
|
||||
class LinuxNetworkLinkComponent(
|
||||
context: Context,
|
||||
private val rootDir: File,
|
||||
) : SessionPart() {
|
||||
private val appContext = context.applicationContext
|
||||
private val connectivity =
|
||||
appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
private val lock = Any()
|
||||
private var callback: ConnectivityManager.NetworkCallback? = null
|
||||
|
||||
/** Called before the session starts, so its first process already sees the link. */
|
||||
fun publish() = write(connectivity.activeNetwork?.let(connectivity::getLinkProperties))
|
||||
|
||||
override fun start() {
|
||||
val registered = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) = write(properties)
|
||||
override fun onLost(network: Network) = write(null)
|
||||
}
|
||||
synchronized(lock) { callback = registered }
|
||||
connectivity.registerDefaultNetworkCallback(registered)
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
val registered = synchronized(lock) { callback.also { callback = null } } ?: return
|
||||
try {
|
||||
connectivity.unregisterNetworkCallback(registered)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Log.w(TAG, "Network callback was already gone", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(properties: LinkProperties?) {
|
||||
val file = File(rootDir, LINK_FILE)
|
||||
synchronized(lock) {
|
||||
try {
|
||||
file.parentFile?.mkdirs()
|
||||
val staged = File(file.path + ".staged")
|
||||
staged.writeText(describe(properties))
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not publish the network link", e)
|
||||
}
|
||||
writeResolver(properties)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's resolver, from the network it is actually on. glibc reads /etc/resolv.conf,
|
||||
* and the image ships two public servers there, which is why Steam resolves at all - but a
|
||||
* captive portal, a private-DNS network or a v6-only carrier wants the network's own
|
||||
* servers. Those come first, IPv4 before IPv6 and never a link-local one (Android lists
|
||||
* fe80:: resolvers a guest cannot reach; handing Bannerlator's Wine guests exactly that was
|
||||
* the Pale Moon "no internet"). The public ones stay as fallback so nothing is ever worse
|
||||
* than the image was.
|
||||
*/
|
||||
private fun writeResolver(properties: LinkProperties?) {
|
||||
val own = properties?.dnsServers.orEmpty()
|
||||
.filter { !it.isLinkLocalAddress && !it.isLoopbackAddress && !it.isAnyLocalAddress }
|
||||
.sortedBy { if (it is Inet4Address) 0 else 1 }
|
||||
.mapNotNull { it.hostAddress?.substringBefore('%') }
|
||||
val servers = (own + listOf("8.8.8.8", "1.1.1.1", "2001:4860:4860::8888")).distinct().take(6)
|
||||
val text = buildString {
|
||||
append("# Written by the app from the device's active network; edits are overwritten.\n")
|
||||
for (server in servers) append("nameserver $server\n")
|
||||
append("options timeout:2 attempts:2\n")
|
||||
}
|
||||
try {
|
||||
val etc = File(rootDir, "etc")
|
||||
val staged = File(etc, "resolv.conf.staged")
|
||||
staged.writeText(text)
|
||||
if (!staged.renameTo(File(etc, "resolv.conf"))) throw IOException("Could not replace resolv.conf")
|
||||
val hosts = File(etc, "hosts")
|
||||
if (!hosts.isFile || !hosts.readText().contains("localhost")) {
|
||||
hosts.writeText("127.0.0.1 localhost\n::1 localhost\n")
|
||||
}
|
||||
Log.i(TAG, "resolver: " + servers.joinToString(" "))
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not write the resolver", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun describe(properties: LinkProperties?): String {
|
||||
val addresses = properties?.linkAddresses.orEmpty()
|
||||
.filter { it.address is Inet4Address || it.address is Inet6Address }
|
||||
val name = properties?.interfaceName?.takeIf { addresses.isNotEmpty() } ?: OFFLINE_NAME
|
||||
val mtu = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) properties?.mtu ?: 0 else 0
|
||||
return buildString {
|
||||
append("if $name $LINK_INDEX ${if (mtu > 0) mtu else DEFAULT_MTU}\n")
|
||||
append("mac ${seededMac()}\n")
|
||||
if (addresses.isEmpty()) {
|
||||
append("addr $OFFLINE_ADDRESS\n")
|
||||
return@buildString
|
||||
}
|
||||
for (address in addresses) {
|
||||
append("addr ${address.address.hostAddress?.substringBefore('%')} ${address.prefixLength}\n")
|
||||
}
|
||||
for (family in listOf(Inet4Address::class.java, Inet6Address::class.java)) {
|
||||
val gateway = properties?.routes.orEmpty()
|
||||
.firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress }
|
||||
?.gateway ?: continue
|
||||
append("gw ${gateway.hostAddress?.substringBefore('%')}\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A stable, locally administered address for this device. Android hides the real one, and a
|
||||
* title should see the same hardware identity every session.
|
||||
*/
|
||||
private fun seededMac(): String {
|
||||
val id = Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) ?: "bannerlator"
|
||||
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
|
||||
val b0 = (bytes[0].toInt() and 0xfc) or 0x02
|
||||
return listOf(b0, bytes[1].toInt(), bytes[2].toInt(), bytes[3].toInt(), bytes[4].toInt(), bytes[5].toInt())
|
||||
.joinToString(":") { "%02x".format(it and 0xff) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "LinuxNetworkLink"
|
||||
private const val LINK_FILE = "etc/bannerlator-net"
|
||||
private const val LINK_INDEX = 2
|
||||
private const val DEFAULT_MTU = 1500
|
||||
private const val OFFLINE_NAME = "eth0"
|
||||
private const val OFFLINE_ADDRESS = "10.0.0.2 24"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.droiddeck.launcher.runtime;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Process;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.system.StructStat;
|
||||
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The glibc arm64 rootfs at {@code files/linuxfs} and the proot invocation that runs a program in
|
||||
* it as this app's own uid. It is a second runtime beside the Wine imagefs, not a container: no
|
||||
* Wine, no box64, no FEX. proot is packaged as {@code libproot.so} so the installer places it, with
|
||||
* its loader, in the native library directory - the only place an app on targetSdk 28 may execute
|
||||
* a file from.
|
||||
*
|
||||
* <p>Ported from WinNative's gamescope runtime (GPL-3.0).
|
||||
*/
|
||||
public final class LinuxRuntime {
|
||||
public static final String DIR = "linuxfs";
|
||||
public static final String SESSION_SCRIPT = "/usr/local/bin/bannerlator-session";
|
||||
public static final String MODE_DESKTOP = "desktop";
|
||||
public static final String MODE_STEAM = "steam";
|
||||
public static final String MODE_RUN = "run";
|
||||
/** Shortcut extra naming which of the modes above a Linux entry launches. */
|
||||
public static final String EXTRA_LINUX_MODE = "linux_mode";
|
||||
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
|
||||
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
|
||||
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
||||
|
||||
public static File debugLogDir() {
|
||||
return new File(android.os.Environment.getExternalStoragePublicDirectory(
|
||||
android.os.Environment.DIRECTORY_DOWNLOADS), DEBUG_LOG_DIR);
|
||||
}
|
||||
|
||||
private LinuxRuntime() {}
|
||||
|
||||
public static File rootDir(Context context) {
|
||||
return new File(context.getFilesDir(), DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's own small tree beside the rootfs: the fake evdev nodes and their rings. In
|
||||
* Bannerlator these lived in the Wine imagefs; here there is no Wine, so the session owns them.
|
||||
* Bound into the guest at its own host path, so nothing needs translating.
|
||||
*/
|
||||
public static File sessionRoot(Context context) {
|
||||
return new File(context.getFilesDir(), "session");
|
||||
}
|
||||
|
||||
/** Where the runtime carries the host-side proot; see tools/linuxfs/prebuilt/proot/README.md. */
|
||||
private static final String HOST_DIR = "opt/android-host";
|
||||
|
||||
/**
|
||||
* proot, preferred from the installed runtime and falling back to the copy in the apk.
|
||||
*
|
||||
* <p>It is an Android binary rather than part of the rootfs - it is what creates the rootfs -
|
||||
* but it travels in the runtime tarball so that reinstalling the app cannot replace the one
|
||||
* binary everything else depends on, and so a device with no working packaged proot can still
|
||||
* run the runtime.
|
||||
*/
|
||||
public static File prootBinary(Context context) {
|
||||
File shipped = new File(rootDir(context), HOST_DIR + "/proot");
|
||||
if (shipped.isFile()) return shipped;
|
||||
return new File(context.getApplicationInfo().nativeLibraryDir, "libproot.so");
|
||||
}
|
||||
|
||||
public static File prootLoader(Context context) {
|
||||
File shipped = new File(rootDir(context), HOST_DIR + "/loader");
|
||||
if (shipped.isFile()) return shipped;
|
||||
return new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so");
|
||||
}
|
||||
|
||||
/** proot links against libtalloc, which sits beside it; empty when the apk copy is in use. */
|
||||
public static String prootLibraryPath(Context context) {
|
||||
File dir = new File(rootDir(context), HOST_DIR);
|
||||
return new File(dir, "proot").isFile() ? dir.getPath() : "";
|
||||
}
|
||||
|
||||
/** The rootfs is present with gamescope and the session script the launcher hands control to. */
|
||||
public static boolean isInstalled(Context context) {
|
||||
File root = rootDir(context);
|
||||
return new File(root, "usr/bin/gamescope").isFile()
|
||||
&& new File(root, SESSION_SCRIPT.substring(1)).isFile()
|
||||
&& prootBinary(context).isFile()
|
||||
&& prootLoader(context).isFile();
|
||||
}
|
||||
|
||||
/** The Vulkan ICD manifest the rootfs ships for the device GPU, or null when it has none. */
|
||||
public static File vulkanIcd(Context context) {
|
||||
File icdDir = new File(rootDir(context), "usr/share/vulkan/icd.d");
|
||||
File[] manifests = icdDir.listFiles((dir, name) -> name.endsWith(".json"));
|
||||
if (manifests == null) return null;
|
||||
for (File manifest : manifests) {
|
||||
if (manifest.getName().contains("freedreno")) return manifest;
|
||||
}
|
||||
return manifests.length > 0 ? manifests[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The proot command line running {@code guestCommand} inside the rootfs. Host paths the session
|
||||
* needs - the app's files directory for the compositor and audio sockets, external storage for
|
||||
* the user's games - are bound at their own paths, so nothing on either side needs translating
|
||||
* and proot never touches the fds a dma-buf travels in. Android has no /dev/shm; a directory
|
||||
* under the cache stands in, which glibc's shm_open and Chromium's shared memory accept.
|
||||
*/
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> guestCommand) {
|
||||
return command(context, sessionRoot, runtimeDir, externalStorage, null, guestCommand);
|
||||
}
|
||||
|
||||
/** As above, plus {@code host:guest} bind specs - the installed games handed to Steam. */
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand) {
|
||||
File root = rootDir(context);
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.add(prootBinary(context).getPath());
|
||||
cmd.add("--kill-on-exit");
|
||||
// Android's app seccomp policy traps the whole set*id family. Xwayland's Popen() calls
|
||||
// setgid()/setuid() before it execs xkbcomp and _exit(127)s when they fail, so without
|
||||
// this the keymap never compiles and Xwayland dies. -i makes proot answer those calls
|
||||
// itself while still reporting our real ids, so nothing inside sees a different user.
|
||||
int uid = Process.myUid();
|
||||
cmd.add("-i");
|
||||
cmd.add(uid + ":" + uid);
|
||||
cmd.add("-r");
|
||||
cmd.add(root.getPath());
|
||||
cmd.add("-w");
|
||||
cmd.add("/root");
|
||||
bind(cmd, "/dev");
|
||||
bind(cmd, "/proc");
|
||||
bind(cmd, "/sys");
|
||||
bind(cmd, "/dev/urandom:/dev/random");
|
||||
bind(cmd, "/proc/self/fd:/dev/fd");
|
||||
bind(cmd, "/proc/self/fd/0:/dev/stdin");
|
||||
bind(cmd, "/proc/self/fd/1:/dev/stdout");
|
||||
bind(cmd, "/proc/self/fd/2:/dev/stderr");
|
||||
bind(cmd, new File(root, "etc/bannerlator/empty").getPath() + ":/sys/fs/selinux");
|
||||
bind(cmd, context.getFilesDir().getPath());
|
||||
bind(cmd, context.getCacheDir().getPath());
|
||||
bind(cmd, runtimeDir.getPath());
|
||||
if (sessionRoot != null) bind(cmd, sessionRoot.getPath());
|
||||
if (externalStorage != null && externalStorage.isDirectory()) {
|
||||
bind(cmd, externalStorage.getPath());
|
||||
}
|
||||
File shm = new File(context.getCacheDir(), "shm");
|
||||
shm.mkdirs();
|
||||
bind(cmd, shm.getPath() + ":/dev/shm");
|
||||
|
||||
// Android denies apps these; glibc, Steam and libcap read them at startup.
|
||||
File fakeProc = new File(root, "etc/bannerlator/proc");
|
||||
// libpci picks its procfs backend on whether it can read the /proc/bus/pci directory, which
|
||||
// the app can, then die()s - exit(1) on the calling process - on the devices file inside
|
||||
// it, which the app cannot. Chromium loads libpci in its GPU process to name the video
|
||||
// card, so that exit kills the process; after a few tries CEF gives up on hardware and
|
||||
// draws the rest of the session on SwiftShader: the client's interface rendered on the
|
||||
// CPU. An empty list is the truthful answer from in here - nothing the app can see is on
|
||||
// a PCI bus. Created at session start rather than shipped in the rootfs so an installed
|
||||
// runtime is fixed too, and the table's guard below binds it only when the real file
|
||||
// cannot be read, so it can never stand in front of real data. (WinNative, maxjivi05,
|
||||
// deff1ac6, via Bannerlator 8fb668d1: 44 -> 85 fps scrolling the Big Picture library on a
|
||||
// OnePlus 15, GPU-process crashes 12 -> 0.)
|
||||
File pciDevices = new File(fakeProc, "pci_devices");
|
||||
if (!pciDevices.isFile()) {
|
||||
try {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
pciDevices.getParentFile().mkdirs();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
pciDevices.createNewFile();
|
||||
} catch (java.io.IOException e) {
|
||||
// It then fails the isFile() test below and the session runs as it did before.
|
||||
}
|
||||
}
|
||||
String[][] procFiles = {
|
||||
{"pci_devices", "/proc/bus/pci/devices"},
|
||||
{"stat", "/proc/stat"},
|
||||
{"version", "/proc/version"},
|
||||
{"loadavg", "/proc/loadavg"},
|
||||
{"uptime", "/proc/uptime"},
|
||||
{"vmstat", "/proc/vmstat"},
|
||||
{"cap_last_cap", "/proc/sys/kernel/cap_last_cap"},
|
||||
{"overflowuid", "/proc/sys/kernel/overflowuid"},
|
||||
{"overflowgid", "/proc/sys/kernel/overflowgid"},
|
||||
};
|
||||
for (String[] entry : procFiles) {
|
||||
File fake = new File(fakeProc, entry[0]);
|
||||
if (fake.isFile() && !new File(entry[1]).canRead()) {
|
||||
bind(cmd, fake.getPath() + ":" + entry[1]);
|
||||
}
|
||||
}
|
||||
bindGpuNode(context, cmd);
|
||||
if (extraBinds != null) {
|
||||
for (String spec : extraBinds) bind(cmd, spec);
|
||||
}
|
||||
cmd.addAll(guestCommand);
|
||||
return cmd;
|
||||
}
|
||||
|
||||
/**
|
||||
* An app process may not open {@code /dev/dri} - the nodes exist but are labelled
|
||||
* {@code graphics_device}, which stock policy grants surfaceflinger and not us - yet libdrm and
|
||||
* everything built on it identify a GPU by its render node, and gamescope refuses to offer
|
||||
* linux-dmabuf without one. The KGSL device Turnip actually drives ({@code gpu_device}, which we
|
||||
* may open) stands in: it appears as a render node with the sysfs entries libdrm reads, and our
|
||||
* Turnip build reports the same device numbers for it.
|
||||
*/
|
||||
private static void bindGpuNode(Context context, List<String> cmd) {
|
||||
StructStat st;
|
||||
try {
|
||||
st = Os.stat(KGSL_DEVICE);
|
||||
} catch (ErrnoException e) {
|
||||
return;
|
||||
}
|
||||
long dev = st.st_rdev;
|
||||
long major = ((dev >> 8) & 0xfff) | ((dev >> 32) & ~0xfffL);
|
||||
long minor = (dev & 0xff) | ((dev >> 12) & ~0xffL);
|
||||
String node = "renderD" + minor;
|
||||
File base = new File(context.getCacheDir(), "drm");
|
||||
File dri = new File(base, "dri");
|
||||
File device = new File(base, "sys/" + major + ":" + minor + "/device");
|
||||
File drm = new File(device, "drm/" + node);
|
||||
try {
|
||||
if ((!dri.isDirectory() && !dri.mkdirs()) || (!drm.isDirectory() && !drm.mkdirs())) {
|
||||
return;
|
||||
}
|
||||
new File(dri, node).createNewFile();
|
||||
Files.write(new File(drm, "dev").toPath(),
|
||||
(major + ":" + minor + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
Files.write(new File(device, "uevent").toPath(),
|
||||
"DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n".getBytes(StandardCharsets.UTF_8));
|
||||
File subsystem = new File(device, "subsystem");
|
||||
if (!Files.isSymbolicLink(subsystem.toPath())) {
|
||||
Os.symlink("/sys/bus/platform", subsystem.getPath());
|
||||
}
|
||||
} catch (IOException | ErrnoException e) {
|
||||
return;
|
||||
}
|
||||
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
|
||||
bind(cmd, dri.getPath() + ":/dev/dri");
|
||||
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
|
||||
}
|
||||
|
||||
private static void bind(List<String> cmd, String spec) {
|
||||
cmd.add("-b");
|
||||
cmd.add(spec);
|
||||
}
|
||||
|
||||
/** X access control and Steam look the session user up by uid: the app uid is root inside. */
|
||||
public static void writeAccounts(Context context) throws IOException {
|
||||
File root = rootDir(context);
|
||||
int uid = Process.myUid();
|
||||
Files.write(new File(root, "etc/passwd").toPath(),
|
||||
("root:x:" + uid + ":" + uid + ":root:/root:/bin/bash\n").getBytes(StandardCharsets.UTF_8));
|
||||
Files.write(new File(root, "etc/group").toPath(),
|
||||
("root:x:" + uid + ":\n").getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package com.droiddeck.launcher.runtime;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
|
||||
import com.droiddeck.launcher.core.Downloader;
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.apache.commons.compress.compressors.zstandard.ZstdCompressorInputStream;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* Downloads and unpacks the Linux runtime rootfs into {@code files/linuxfs}. It is opt-in: nothing
|
||||
* fetches it until the user asks for it, and a gamescope session refuses to start without it.
|
||||
*
|
||||
* <p>The catalog row names the build, its URL and its sha256, so an interrupted or corrupted
|
||||
* download is caught before anything is written into the app's files directory.
|
||||
*/
|
||||
public final class LinuxRuntimeInstaller {
|
||||
private static final String TAG = "LinuxRuntimeInstaller";
|
||||
|
||||
/** Catalog row, beside the other component catalogs in winlator-contents. */
|
||||
public static final String CATALOG_URL =
|
||||
"https://raw.githubusercontent.com/The412Banner/winlator-contents/main/linuxfs.json";
|
||||
|
||||
private static final String VERSION_FILE = ".version";
|
||||
|
||||
public interface ProgressListener {
|
||||
/** {@code percent} is -1 while the size is unknown. */
|
||||
void onProgress(String stage, int percent);
|
||||
}
|
||||
|
||||
public static final class Release {
|
||||
public final String version;
|
||||
public final String url;
|
||||
public final String sha256;
|
||||
public final long size;
|
||||
|
||||
Release(String version, String url, String sha256, long size) {
|
||||
this.version = version;
|
||||
this.url = url;
|
||||
this.sha256 = sha256;
|
||||
this.size = size;
|
||||
}
|
||||
}
|
||||
|
||||
private LinuxRuntimeInstaller() {}
|
||||
|
||||
/** The build currently unpacked, or null when the runtime is not installed. */
|
||||
public static String installedVersion(Context context) {
|
||||
File marker = new File(LinuxRuntime.rootDir(context), VERSION_FILE);
|
||||
if (!marker.isFile() || !LinuxRuntime.isInstalled(context)) return null;
|
||||
String v = FileUtils.readString(marker);
|
||||
return v == null ? null : v.trim();
|
||||
}
|
||||
|
||||
/** The catalog's current build, or null when it cannot be reached or read. */
|
||||
public static Release fetchRelease() {
|
||||
String body = Downloader.downloadString(CATALOG_URL);
|
||||
if (body == null || body.isEmpty()) return null;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
String version = json.optString("version", "");
|
||||
String url = json.optString("url", "");
|
||||
String sha256 = json.optString("sha256", "");
|
||||
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) return null;
|
||||
return new Release(version, url, sha256, json.optLong("size", 0L));
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "catalog: " + e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's home directory, carried across an update rather than replaced with the tarball's
|
||||
* empty one. Steam installs itself here - the client, the signed-in account and every
|
||||
* downloaded game - so replacing the rootfs wholesale used to delete all three and leave the
|
||||
* user re-downloading Steam and signing in again, with their library gone.
|
||||
*/
|
||||
private static final String USER_DATA = "root";
|
||||
|
||||
/**
|
||||
* Downloads {@code release} and replaces whatever is installed with it. Returns false and
|
||||
* leaves the existing runtime alone if the download or the checksum fails; the new rootfs is
|
||||
* only moved into place once it has been unpacked whole.
|
||||
*
|
||||
* <p>{@link #USER_DATA} survives the swap: the system is replaced, what the user put in it is
|
||||
* not. An update therefore keeps Steam, the login and the installed games.
|
||||
*/
|
||||
public static boolean install(Context context, Release release, ProgressListener listener) {
|
||||
File archive = new File(context.getCacheDir(), "linuxfs.tar.zst");
|
||||
try {
|
||||
if (listener != null) listener.onProgress("Downloading", 0);
|
||||
// Downloader reports a 0..1 fraction, or -1 while the total size is unknown.
|
||||
boolean ok = Downloader.downloadFile(release.url, archive, true, (fraction) -> {
|
||||
if (listener != null) {
|
||||
listener.onProgress("Downloading",
|
||||
fraction < 0 ? -1 : Math.round(fraction * 100f));
|
||||
}
|
||||
});
|
||||
if (!ok) {
|
||||
Log.w(TAG, "download failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (listener != null) listener.onProgress("Verifying", -1);
|
||||
String actual = sha256(archive);
|
||||
if (!release.sha256.equalsIgnoreCase(actual)) {
|
||||
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Unpack beside the live rootfs and swap, so a failure here cannot leave a half
|
||||
// runtime that isInstalled() would happily launch.
|
||||
File root = LinuxRuntime.rootDir(context);
|
||||
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
|
||||
FileUtils.delete(staging);
|
||||
if (!staging.mkdirs()) return false;
|
||||
if (listener != null) listener.onProgress("Extracting", -1);
|
||||
if (!extract(archive, staging, listener)) {
|
||||
FileUtils.delete(staging);
|
||||
return false;
|
||||
}
|
||||
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
||||
|
||||
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
|
||||
FileUtils.delete(old);
|
||||
if (root.isDirectory() && !root.renameTo(old)) {
|
||||
FileUtils.delete(staging);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Carry the user's home over before the new rootfs takes the name. A rename inside the
|
||||
// same filesystem, so a 30 GB library costs nothing and cannot half-copy; the tarball's
|
||||
// own empty /root is dropped first so the rename has somewhere to land. If this fails
|
||||
// the update is abandoned and the previous runtime is put back untouched - shipping a
|
||||
// working system with the user's games gone is the worse outcome.
|
||||
File keptFrom = new File(old, USER_DATA);
|
||||
if (keptFrom.isDirectory()) {
|
||||
File keptTo = new File(staging, USER_DATA);
|
||||
FileUtils.delete(keptTo);
|
||||
if (!keptFrom.renameTo(keptTo)) {
|
||||
Log.w(TAG, "could not carry " + USER_DATA + " across the update; rolling back");
|
||||
FileUtils.delete(staging);
|
||||
old.renameTo(root);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!staging.renameTo(root)) {
|
||||
if (old.isDirectory()) old.renameTo(root);
|
||||
return false;
|
||||
}
|
||||
FileUtils.delete(old);
|
||||
return LinuxRuntime.isInstalled(context);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "install", e);
|
||||
return false;
|
||||
} finally {
|
||||
archive.delete();
|
||||
}
|
||||
}
|
||||
|
||||
public static void uninstall(Context context) {
|
||||
FileUtils.delete(LinuxRuntime.rootDir(context));
|
||||
}
|
||||
|
||||
/**
|
||||
* A whole-rootfs tar, which is not the shape the shared extractor handles: a distribution
|
||||
* rootfs is full of hard links (one binary under several names), and an entry written as an
|
||||
* 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.
|
||||
*/
|
||||
public static boolean extract(File archive, File destination, ProgressListener listener) {
|
||||
long entries = 0;
|
||||
try (InputStream in = new ZstdCompressorInputStream(
|
||||
new BufferedInputStream(new FileInputStream(archive), 1 << 16));
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
||||
TarArchiveEntry entry;
|
||||
String base = destination.getCanonicalPath() + File.separator;
|
||||
while ((entry = tar.getNextTarEntry()) != null) {
|
||||
File file = new File(destination, entry.getName());
|
||||
// Refuse anything that would land outside the runtime directory.
|
||||
if (!(file.getCanonicalPath() + (entry.isDirectory() ? File.separator : "")).startsWith(base)
|
||||
&& !file.getCanonicalPath().equals(destination.getCanonicalPath())) {
|
||||
Log.w(TAG, "skipping entry outside the rootfs: " + entry.getName());
|
||||
continue;
|
||||
}
|
||||
if (entry.isDirectory()) {
|
||||
file.mkdirs();
|
||||
continue;
|
||||
}
|
||||
File parent = file.getParentFile();
|
||||
if (parent != null && !parent.isDirectory()) parent.mkdirs();
|
||||
|
||||
if (entry.isSymbolicLink()) {
|
||||
file.delete();
|
||||
FileUtils.symlink(entry.getLinkName(), file.getAbsolutePath());
|
||||
} else if (entry.isLink()) {
|
||||
// A hard link to an earlier entry. Link where the filesystem allows it and
|
||||
// fall back to a copy, which costs space but always works.
|
||||
File target = new File(destination, entry.getLinkName());
|
||||
file.delete();
|
||||
try {
|
||||
Files.createLink(file.toPath(), target.toPath());
|
||||
} catch (IOException | UnsupportedOperationException e) {
|
||||
if (target.isFile()) {
|
||||
Files.copy(target.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
try (OutputStream out = new FileOutputStream(file)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
int read;
|
||||
while ((read = tar.read(buffer)) != -1) out.write(buffer, 0, read);
|
||||
}
|
||||
if ((entry.getMode() & 0111) != 0) file.setExecutable(true, false);
|
||||
} else {
|
||||
continue; // device nodes and fifos: the runtime binds the real ones
|
||||
}
|
||||
if (++entries % 2000 == 0 && listener != null) {
|
||||
listener.onProgress("Extracting", -1);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "extract", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String sha256(File file) throws Exception {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (InputStream in = new BufferedInputStream(new FileInputStream(file), 1 << 16)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
int read;
|
||||
while ((read = in.read(buffer)) != -1) digest.update(buffer, 0, read);
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : digest.digest()) sb.append(String.format("%02x", b));
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.BatteryManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* The battery the Steam client can see.
|
||||
*
|
||||
* 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
|
||||
* 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 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
|
||||
* over `/sys/class/power_supply`, refreshed every few seconds while the session runs.
|
||||
*
|
||||
* Values: charge in µAh from the charge counter; energy in µWh from charge × voltage; power in µW
|
||||
* from |current| × voltage; time to empty from charge ÷ |average current| while discharging. Where
|
||||
* a device reports no current, the client still gets status and percentage.
|
||||
*/
|
||||
class BatteryComponent(val dir: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
|
||||
override fun start() {
|
||||
running = true
|
||||
write()
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
if (running) write()
|
||||
}
|
||||
}, "battery-sysfs").apply { isDaemon = true; start() }
|
||||
Log.i(TAG, "battery: BAT0/BAT1 written to ${dir.path} every ${PERIOD_MS / 1000} s")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
|
||||
private fun write() {
|
||||
val ctx = app() ?: return
|
||||
try {
|
||||
val bm = ctx.getSystemService(BatteryManager::class.java)
|
||||
val sticky: Intent? = ctx.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
val status = sticky?.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN) ?: BatteryManager.BATTERY_STATUS_UNKNOWN
|
||||
val level = sticky?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
|
||||
val scale = sticky?.getIntExtra(BatteryManager.EXTRA_SCALE, 100)?.takeIf { it > 0 } ?: 100
|
||||
val pct = if (level >= 0) level * 100 / scale else (bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: 50)
|
||||
val voltageUv = ((sticky?.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) ?: 0).toLong() * 1000L).takeIf { it > 0 } ?: 3_800_000L
|
||||
val tempDeci = sticky?.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) ?: 0
|
||||
val tech = sticky?.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY)?.takeIf { it.isNotBlank() } ?: "Li-ion"
|
||||
val chargeNowUah = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER)?.takeIf { it > 0 && it != Long.MIN_VALUE } ?: 0L
|
||||
val currentNowUa = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)?.takeIf { it != Long.MIN_VALUE } ?: 0L
|
||||
val currentAvgUa = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE)?.takeIf { it != Long.MIN_VALUE && it != 0L } ?: currentNowUa
|
||||
// Android's sign convention varies by vendor; the status says which way the current flows.
|
||||
val discharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING
|
||||
val chargeFullUah = if (chargeNowUah > 0 && pct > 0) chargeNowUah * 100 / pct else 0L
|
||||
val energyNowUwh = chargeNowUah * voltageUv / 1_000_000L
|
||||
val energyFullUwh = chargeFullUah * voltageUv / 1_000_000L
|
||||
val powerNowUw = abs(currentNowUa) * voltageUv / 1_000_000L
|
||||
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
|
||||
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
|
||||
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
|
||||
val statusText = when (status) {
|
||||
BatteryManager.BATTERY_STATUS_CHARGING -> "Charging"
|
||||
BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging"
|
||||
BatteryManager.BATTERY_STATUS_FULL -> "Full"
|
||||
BatteryManager.BATTERY_STATUS_NOT_CHARGING -> "Not charging"
|
||||
else -> "Unknown"
|
||||
}
|
||||
val capacityLevel = when {
|
||||
status == BatteryManager.BATTERY_STATUS_FULL || pct >= 100 -> "Full"
|
||||
pct <= 5 -> "Critical"
|
||||
pct <= 15 -> "Low"
|
||||
else -> "Normal"
|
||||
}
|
||||
for (name in listOf("BAT0", "BAT1")) {
|
||||
val bat = File(dir, name).apply { mkdirs() }
|
||||
val attrs = linkedMapOf(
|
||||
"type" to "Battery",
|
||||
"present" to "1",
|
||||
"status" to statusText,
|
||||
"capacity" to pct.toString(),
|
||||
"capacity_level" to capacityLevel,
|
||||
"technology" to tech,
|
||||
"voltage_now" to voltageUv.toString(),
|
||||
"voltage_min_design" to voltageUv.toString(),
|
||||
"current_now" to currentNowUa.toString(),
|
||||
"current_avg" to currentAvgUa.toString(),
|
||||
"charge_now" to chargeNowUah.toString(),
|
||||
"charge_full" to chargeFullUah.toString(),
|
||||
"charge_full_design" to chargeFullUah.toString(),
|
||||
"energy_now" to energyNowUwh.toString(),
|
||||
"energy_full" to energyFullUwh.toString(),
|
||||
"energy_full_design" to energyFullUwh.toString(),
|
||||
"power_now" to powerNowUw.toString(),
|
||||
"time_to_empty_now" to timeToEmptyS.toString(),
|
||||
"time_to_empty_avg" to timeToEmptyS.toString(),
|
||||
"time_to_full_now" to timeToFullS.toString(),
|
||||
"time_to_full_avg" to timeToFullS.toString(),
|
||||
"temp" to tempDeci.toString(),
|
||||
"model_name" to android.os.Build.MODEL.replace(' ', '_'),
|
||||
"manufacturer" to android.os.Build.MANUFACTURER.replace(' ', '_'),
|
||||
"scope" to "System",
|
||||
)
|
||||
for ((k, v) in attrs) put(File(bat, k), v + "\n")
|
||||
val uevent = StringBuilder("POWER_SUPPLY_NAME=$name\n")
|
||||
for ((k, v) in attrs) uevent.append("POWER_SUPPLY_").append(k.uppercase()).append('=').append(v).append('\n')
|
||||
put(File(bat, "uevent"), uevent.toString())
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "battery: could not write", t)
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomic per file: a reader in the guest never sees a half-written value. */
|
||||
private fun put(target: File, text: String) {
|
||||
val tmp = File(target.parentFile, "." + target.name + ".tmp")
|
||||
tmp.writeText(text)
|
||||
if (!tmp.renameTo(target)) { target.writeText(text); tmp.delete() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val PERIOD_MS = 5_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.io.PrintWriter
|
||||
import java.io.StringWriter
|
||||
|
||||
/**
|
||||
* The last thing that runs when our own code throws on any thread: the stack trace into the
|
||||
* session's folder, then the folder's ending ([SessionArtifacts.collect]), then Android's own
|
||||
* handler so the crash is still reported and still lands in the crash buffer. Bounded, because
|
||||
* a handler that hangs turns a crash into a frozen app: the collect gets a few seconds and the
|
||||
* process dies regardless.
|
||||
*
|
||||
* A native crash (the compositor, a JNI call) never reaches here - the process is gone before
|
||||
* Java sees anything. [SessionArtifacts.finishAbandoned] at the next start covers that case.
|
||||
*/
|
||||
object CrashHandler {
|
||||
private const val TAG = "CrashHandler"
|
||||
|
||||
fun install(context: Context) {
|
||||
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
try {
|
||||
Log.e(TAG, "uncaught on ${thread.name}", error)
|
||||
val dir = SessionPaths.current()
|
||||
if (dir != null && dir.isDirectory) {
|
||||
val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
|
||||
File(dir, "crash-app.txt").writeText(
|
||||
"The app itself crashed on thread \"${thread.name}\":\n\n$trace"
|
||||
)
|
||||
val worker = Thread({ SessionArtifacts.collect(context, dir, "app crash") }, "crash-collect")
|
||||
worker.start()
|
||||
worker.join(8000)
|
||||
}
|
||||
// The session's tree would outlive us otherwise, and block the next launch.
|
||||
OrphanReaper.reap("app crash")
|
||||
} catch (e: Throwable) {
|
||||
// Nothing more to do for a crash inside the crash handler.
|
||||
} finally {
|
||||
previous?.uncaughtException(thread, error) ?: Runtime.getRuntime().halt(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.os.storage.StorageManager
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Where a second Steam library can live on this device.
|
||||
*
|
||||
* An SD card is offered through the app's own folder on it ({@code Android/data/<pkg>/files/steam}):
|
||||
* the one place on a card a targetSdk-28 app may write without a permission prompt, and a real
|
||||
* filesystem path the session can bind. Any other folder comes from the File Manager's pick mode
|
||||
* and is checked for writing before it is accepted. Both are FUSE-backed on Android and stream
|
||||
* slowly (intro movies, big asset loads); internal stays the default and the dialog says so.
|
||||
*/
|
||||
object GameStorage {
|
||||
class Option(val label: String, val path: String)
|
||||
|
||||
/** Every removable volume, as its app folder, with the free space it has. */
|
||||
fun options(context: Context): List<Option> {
|
||||
val sm = context.getSystemService(StorageManager::class.java)
|
||||
return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir ->
|
||||
val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false }
|
||||
if (!removable) return@mapNotNull null
|
||||
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
|
||||
val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: "SD card"
|
||||
Option("$name · ${free(dir)} free", File(dir, "steam").absolutePath)
|
||||
}
|
||||
}
|
||||
|
||||
fun free(dir: File): String = try {
|
||||
FileUtils.sizeToString(StatFs(dir.path).availableBytes)
|
||||
} catch (e: Exception) {
|
||||
"?"
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
fun prepare(path: String): String? {
|
||||
val root = File(path)
|
||||
val steamapps = File(root, "steamapps")
|
||||
if (!steamapps.isDirectory && !steamapps.mkdirs()) return "cannot create folders in $path"
|
||||
val probe = File(steamapps, ".writable")
|
||||
return try {
|
||||
if (!probe.createNewFile() && !probe.isFile) "cannot write in $path" else { probe.delete(); null }
|
||||
} catch (e: Exception) {
|
||||
"cannot write in $path (${e.message})"
|
||||
}
|
||||
}
|
||||
|
||||
/** The root the session binds, from the setting: automatic = the first card in the phone. */
|
||||
fun effective(context: Context): Option? {
|
||||
val pref = SessionPrefs.gameStorage(context)
|
||||
return when {
|
||||
pref == SessionPrefs.GAME_STORAGE_OFF -> null
|
||||
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.label.substringBefore(" ·"), it.path) }
|
||||
else -> Option(SessionPrefs.gameStorageLabel(context), pref)
|
||||
}
|
||||
}
|
||||
|
||||
/** The label the client shows for a chosen folder: its last name, or the volume's. */
|
||||
fun labelFor(context: Context, path: String): String =
|
||||
options(context).firstOrNull { it.path == path }?.label?.substringBefore(" ·")
|
||||
?: File(path).name.ifEmpty { "Folder" }
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
/**
|
||||
* The loading overlay's state: what to say, read out of the session log, and a clock so a user
|
||||
* can see that time is passing even when the log is quiet. The runtime script marks its
|
||||
* milestones with "== STEP"; the client's own bootstrap does not, but it does print its download
|
||||
* progress, and lifting that out is the difference between "starting the Steam client" for three
|
||||
* minutes and a percentage that moves.
|
||||
*/
|
||||
class LoadingState(context: Context) {
|
||||
var visible by mutableStateOf(true)
|
||||
var step by mutableStateOf("Starting the session…")
|
||||
var percent by mutableIntStateOf(-1)
|
||||
var elapsed by mutableStateOf("")
|
||||
var hint by mutableStateOf("")
|
||||
var ended by mutableStateOf(false)
|
||||
|
||||
private val hints = context.resources.getStringArray(com.droiddeck.launcher.R.array.loading_hints)
|
||||
private val startedAt = SystemClock.elapsedRealtime()
|
||||
|
||||
/** Once a second: the clock and the hint. */
|
||||
fun tick() {
|
||||
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
||||
elapsed = String.format(java.util.Locale.US, "%d:%02d elapsed · still working", seconds / 60, seconds % 60)
|
||||
hint = hints[((seconds / 8) % hints.size).toInt()]
|
||||
}
|
||||
|
||||
fun showEnded(message: String) {
|
||||
visible = true
|
||||
ended = true
|
||||
step = message
|
||||
}
|
||||
|
||||
/** Re-reads the end of the log and updates the line and the bar. */
|
||||
fun update(context: Context, log: File?) {
|
||||
val state = read(context, log) ?: return
|
||||
step = state.first
|
||||
percent = state.second
|
||||
}
|
||||
|
||||
/** Only the tail is read: the client alone writes megabytes an hour. */
|
||||
private fun read(context: Context, log: File?): Pair<String, Int>? {
|
||||
if (log == null || !log.isFile) return null
|
||||
val text = try {
|
||||
RandomAccessFile(log, "r").use { file ->
|
||||
val length = file.length()
|
||||
val want = minOf(length, TAIL_BYTES)
|
||||
file.seek(length - want)
|
||||
val bytes = ByteArray(want.toInt())
|
||||
file.readFully(bytes)
|
||||
String(bytes, StandardCharsets.UTF_8)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
return null
|
||||
}
|
||||
var stepAt = -1
|
||||
var stepText: String? = null
|
||||
var downloadAt = -1
|
||||
var downloadPercent = -1
|
||||
var clientDownloadAt = -1
|
||||
var clientDownload: String? = null
|
||||
var clientPercent = -1
|
||||
var offset = 0
|
||||
for (line in text.split('\n')) {
|
||||
val at = offset
|
||||
offset += line.length + 1
|
||||
if (line.startsWith("== STEP ")) {
|
||||
stepAt = at
|
||||
stepText = line.substringAfter("== STEP ").substringAfter(' ')
|
||||
val m = INSTALL_COUNT.find(line)
|
||||
if (m != null) {
|
||||
clientDownloadAt = at
|
||||
clientDownload = m.groupValues[1]
|
||||
clientPercent = m.groupValues[2].toInt() * 100 / maxOf(1, m.groupValues[3].toInt())
|
||||
}
|
||||
} else {
|
||||
val m = UPDATE_PROGRESS.find(line)
|
||||
if (m != null) {
|
||||
downloadAt = at
|
||||
val done = m.groupValues[1].toLong()
|
||||
val total = maxOf(1L, m.groupValues[2].toLong())
|
||||
downloadPercent = (done * 100 / total).toInt()
|
||||
}
|
||||
}
|
||||
}
|
||||
return when {
|
||||
downloadAt > stepAt && downloadPercent >= 0 ->
|
||||
Pair("Downloading the Steam client update · $downloadPercent%", downloadPercent)
|
||||
clientDownloadAt == stepAt && clientDownload != null ->
|
||||
Pair("Downloading the Steam client · $clientDownload", clientPercent)
|
||||
stepText != null -> Pair(stepText, -1)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAIL_BYTES = 48L * 1024
|
||||
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
|
||||
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Starting the Steam client signed out of Valve's servers.
|
||||
*
|
||||
* The client can run without a connection - installed games launch, Proton and the frame-gen are
|
||||
* all local - but only if it has credentials from an earlier successful sign-in. Two keys in
|
||||
* loginusers.vdf decide what it does when it cannot reach a CM: WantsOfflineMode makes it go
|
||||
* offline on its own, SkipOfflineModeWarning stops it asking first. Both are read once, while the
|
||||
* client starts, which is why this belongs to the main screen and not to the in-session drawer:
|
||||
* changing it during a session would write the file and change nothing until the next launch.
|
||||
*
|
||||
* The client rewrites this file when it exits, so the request is kept as our own preference and
|
||||
* written into the file again at every session start.
|
||||
*/
|
||||
object OfflineMode {
|
||||
private const val TAG = "OfflineMode"
|
||||
private const val KEY = "steam_offline"
|
||||
private val WANTS = Regex("""^(\s*"WantsOfflineMode"\s*")([01])(".*)$""")
|
||||
private val SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
|
||||
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
|
||||
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
private fun loginUsers(root: File) = File(root, "root/.local/share/Steam/config/loginusers.vdf")
|
||||
|
||||
/** Whether the client has an account it could sign in as offline. */
|
||||
fun account(context: Context): String? {
|
||||
val file = loginUsers(LinuxRuntime.rootDir(context))
|
||||
val text = try {
|
||||
if (file.isFile) file.readText() else return null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not read loginusers.vdf", e); return null
|
||||
}
|
||||
if (!REMEMBER.containsMatchIn(text)) return null
|
||||
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() } ?: "signed in"
|
||||
}
|
||||
|
||||
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
|
||||
|
||||
fun setEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean(KEY, on).apply()
|
||||
apply(context, LinuxRuntime.rootDir(context))
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the request into loginusers.vdf. Every account block gets the same answer: the client
|
||||
* signs in as one of them and we have no say in which. Keys the file does not carry are added
|
||||
* beside the account's name; a file without an account block is left alone, since there is
|
||||
* nothing to be offline as.
|
||||
*/
|
||||
fun apply(context: Context, root: File) {
|
||||
val file = loginUsers(root)
|
||||
if (!file.isFile) return
|
||||
val want = if (enabled(context)) "1" else "0"
|
||||
try {
|
||||
val lines = file.readLines()
|
||||
val out = ArrayList<String>(lines.size + 4)
|
||||
var sawWants = false
|
||||
var sawSkip = false
|
||||
var changed = false
|
||||
for (line in lines) {
|
||||
val wants = WANTS.matchEntire(line)
|
||||
val skip = SKIP.matchEntire(line)
|
||||
when {
|
||||
wants != null -> {
|
||||
sawWants = true
|
||||
if (wants.groupValues[2] != want) changed = true
|
||||
out.add(wants.groupValues[1] + want + wants.groupValues[3])
|
||||
}
|
||||
skip != null -> {
|
||||
sawSkip = true
|
||||
if (skip.groupValues[2] != want) changed = true
|
||||
out.add(skip.groupValues[1] + want + skip.groupValues[3])
|
||||
}
|
||||
else -> {
|
||||
out.add(line)
|
||||
if (line.contains("\"AccountName\"")) {
|
||||
val indent = line.takeWhile { it == ' ' || it == '\t' }
|
||||
if (!lines.any { WANTS.matchEntire(it) != null }) {
|
||||
out.add("$indent\"WantsOfflineMode\"\t\t\"$want\""); changed = true
|
||||
}
|
||||
if (!lines.any { SKIP.matchEntire(it) != null }) {
|
||||
out.add("$indent\"SkipOfflineModeWarning\"\t\t\"$want\""); changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!changed) return
|
||||
val staged = File(file.parentFile, "loginusers.vdf.staged")
|
||||
staged.writeText(out.joinToString("\n", postfix = "\n"))
|
||||
if (!staged.renameTo(file)) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not replace loginusers.vdf")
|
||||
return
|
||||
}
|
||||
Log.i(TAG, "offline=$want (wants=$sawWants skip=$sawSkip)")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not write loginusers.vdf", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Kills every process of this app's uid other than the app itself.
|
||||
*
|
||||
* A session is a tree of processes under proot, and proot dies with the app only when the app's
|
||||
* own teardown runs. When the app is killed or crashes instead, the tree stays: proot holding the
|
||||
* rootfs, gamescope holding the GPU, Steam holding its lock file - and the next session never
|
||||
* comes up, or comes up beside a client that is already running. A user on a Thor Pro had to
|
||||
* force-stop the app before every launch. Everything of ours that should be alive between
|
||||
* sessions is inside the app process, so at session start anything else under our uid is a
|
||||
* leftover, and this sweeps it. Each pid is checked by uid at kill time, never by name.
|
||||
*/
|
||||
object OrphanReaper {
|
||||
private const val TAG = "OrphanReaper"
|
||||
|
||||
fun reap(reason: String): Int {
|
||||
val me = android.os.Process.myPid()
|
||||
val uid = android.os.Process.myUid()
|
||||
var killed = 0
|
||||
File("/proc").listFiles()?.forEach { entry ->
|
||||
val pid = entry.name.toIntOrNull() ?: return@forEach
|
||||
if (pid == me || pid <= 1) return@forEach
|
||||
if (uidOf(pid) != uid) return@forEach
|
||||
val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" }
|
||||
try {
|
||||
android.os.Process.killProcess(pid)
|
||||
killed++
|
||||
Log.i(TAG, "killed leftover $pid ($name) - $reason")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not kill $pid ($name)", e)
|
||||
}
|
||||
}
|
||||
if (killed > 0) Log.i(TAG, "$killed leftover process(es) from an earlier session - $reason")
|
||||
return killed
|
||||
}
|
||||
|
||||
private fun uidOf(pid: Int): Int {
|
||||
return try {
|
||||
File("/proc/$pid/status").useLines { lines ->
|
||||
lines.firstOrNull { it.startsWith("Uid:") }
|
||||
?.substringAfter("Uid:")?.trim()?.split(Regex("\\s+"))?.firstOrNull()?.toIntOrNull() ?: -1
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
-1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.PerformanceHintManager
|
||||
import android.util.Log
|
||||
import androidx.annotation.RequiresApi
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* ADPF (Android 12+): a PerformanceHintManager session over the compositor thread, told the
|
||||
* panel's frame period as its target and each presented frame's interval as the actual. When a
|
||||
* frame runs long the power HAL raises CPU clocks for the next one at once, instead of the
|
||||
* governor waiting for the load average to climb - the difference between a menu that stutters
|
||||
* on the first scroll and one that does not.
|
||||
*
|
||||
* The session may only carry this process's threads, so the guest (gamescope, the Steam client
|
||||
* under FEX) cannot join it; they are covered by the app-wide game category and sustained mode.
|
||||
* Below API 31 nothing here runs; on a power HAL without hint sessions createHintSession returns
|
||||
* null and the log says so.
|
||||
*/
|
||||
object PerfHints {
|
||||
private const val TAG = "PerfHints"
|
||||
|
||||
@Volatile private var session: PerformanceHintManager.Session? = null
|
||||
@Volatile private var target = 0L
|
||||
/** Compositor thread only. */
|
||||
private var last = 0L
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
/** Reports leave the compositor thread: each one is a binder call to the power HAL. */
|
||||
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "adpf-report").apply { isDaemon = true } }
|
||||
|
||||
/** Opens the session once the compositor thread exists (it is started just before this). */
|
||||
fun arm(context: Context, refreshHz: Float) {
|
||||
if (Build.VERSION.SDK_INT < 31) { Log.i(TAG, "adpf: needs Android 12; this is API ${Build.VERSION.SDK_INT}"); return }
|
||||
val wanted = (1_000_000_000.0 / refreshHz.coerceAtLeast(30f)).toLong()
|
||||
val s = session
|
||||
if (s != null) {
|
||||
if (wanted != target) { target = wanted; try { s.updateTargetWorkDuration(wanted) } catch (t: Throwable) { Log.w(TAG, "adpf: retarget", t) } }
|
||||
return
|
||||
}
|
||||
target = wanted
|
||||
val app = context.applicationContext
|
||||
var tries = 0
|
||||
main.post(object : Runnable {
|
||||
override fun run() {
|
||||
if (session != null) return
|
||||
val tid = try { WaylandCompositor.nativeCompositorTid() } catch (t: Throwable) { 0 }
|
||||
if (tid == 0) {
|
||||
if (++tries < 30) main.postDelayed(this, 100) else Log.w(TAG, "adpf: the compositor thread never reported its tid")
|
||||
return
|
||||
}
|
||||
open(app, tid)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@RequiresApi(31)
|
||||
private fun open(app: Context, tid: Int) {
|
||||
val pm = app.getSystemService(PerformanceHintManager::class.java)
|
||||
if (pm == null) { Log.i(TAG, "adpf: no PerformanceHintManager on this device"); return }
|
||||
val s = try { pm.createHintSession(intArrayOf(tid), target) } catch (t: Throwable) { Log.w(TAG, "adpf: createHintSession", t); null }
|
||||
if (s == null) { Log.i(TAG, "adpf: unsupported here (the power HAL has no hint sessions)"); return }
|
||||
last = 0L
|
||||
session = s
|
||||
Log.i(TAG, "adpf: session on compositor thread $tid · target ${target / 1000} µs · HAL wants updates every ${pm.preferredUpdateRateNanos / 1000} µs")
|
||||
}
|
||||
|
||||
/** Compositor thread, once per presented game frame; the interval since the last is the actual. */
|
||||
@JvmStatic
|
||||
fun onFrame() {
|
||||
val s = session ?: return
|
||||
val now = System.nanoTime()
|
||||
val prev = last
|
||||
last = now
|
||||
if (prev == 0L) return
|
||||
val dt = now - prev
|
||||
// Under half a millisecond is a double present; over half a second is a pause, not a frame.
|
||||
if (dt < 500_000L || dt > 500_000_000L) return
|
||||
worker.execute {
|
||||
try { s.reportActualWorkDuration(dt) } catch (t: Throwable) { Log.w(TAG, "adpf: report failed, session dropped", t); session = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* The numbers behind the top-right line: the game's own frame rate and, when frame generation
|
||||
* is on, what the screen is actually being shown - "60 → 118 fps" is the proof that the engine
|
||||
* is doing something, and "FG starting" or a reason is the proof that it is not.
|
||||
*
|
||||
* The base rate is counted here from the compositor's per-frame callback, so it is right with or
|
||||
* without an engine. The presented rate comes from the engine's own telemetry while it generates.
|
||||
*/
|
||||
class PerfHud(context: Context) {
|
||||
/** Empty when the HUD is off or not yet started. */
|
||||
var text by mutableStateOf("")
|
||||
private set
|
||||
|
||||
private val context = context.applicationContext
|
||||
private val frames = AtomicInteger()
|
||||
private var lastTick = 0L
|
||||
private var running = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
/** The session's own switch (drawer), with the Downloads file as a device-side override. */
|
||||
private val enabled: Boolean
|
||||
get() = SessionPrefs.hudEnabled(context)
|
||||
&& !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
|
||||
|
||||
/** Told, on the main thread, when the window presenting frames changes. */
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
private var lastWindow: String? = null
|
||||
|
||||
private val listener = object : WaylandCompositor.GameListener {
|
||||
override fun onGameSurface(window: String?, gpuName: String?) {
|
||||
// gamescope forwards a fullscreen game's own buffers straight through and its composited
|
||||
// output when the Steam menu is up; each is a different window here. Compositor thread.
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
}
|
||||
}
|
||||
override fun onGameFrame() { frames.incrementAndGet() }
|
||||
}
|
||||
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val dt = (now - lastTick).coerceAtLeast(1L) / 1000f
|
||||
lastTick = now
|
||||
text = line(frames.getAndSet(0) / dt)
|
||||
handler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-reads the switch: starts or stops to match it. */
|
||||
fun refresh() {
|
||||
if (enabled) start() else stop()
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (!enabled || running) return
|
||||
running = true
|
||||
lastTick = SystemClock.elapsedRealtime()
|
||||
frames.set(0)
|
||||
WaylandCompositor.setGameListener(listener)
|
||||
handler.post(tick)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
WaylandCompositor.setGameListener(null)
|
||||
text = ""
|
||||
}
|
||||
|
||||
private fun line(base: Float): String {
|
||||
val engine = FrameGen.engine(context)
|
||||
if (engine == FrameGen.ENGINE_OFF) return fps(base)
|
||||
val name = if (engine == FrameGen.ENGINE_LSFG) "LSFG" else "Win-FG"
|
||||
val multiplier = FrameGen.multiplier(context)
|
||||
val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null }
|
||||
val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 }
|
||||
return when {
|
||||
problem == 1 -> "$name: unsupported"
|
||||
problem == 2 -> "$name: engine failed"
|
||||
stats != null && stats[3] > 1f -> {
|
||||
val source = if (stats[2] > 1f) stats[2] else base
|
||||
String.format(Locale.US, "%s %d× %.0f → %.0f fps", name, multiplier, source, stats[3])
|
||||
}
|
||||
else -> String.format(Locale.US, "%s %d× %s · FG starting", name, multiplier, fps(base))
|
||||
}
|
||||
}
|
||||
|
||||
private fun fps(value: Float) = String.format(Locale.US, "%.0f fps", value)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.GameManager
|
||||
import android.app.GameState
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* What a session tells Android about itself so the SoC is run for a game, not for an app.
|
||||
*
|
||||
* The manifest already makes the app a game (appCategory + game_mode_config); this is the
|
||||
* per-window half, applied when the session activity is created:
|
||||
*
|
||||
* - sustained performance mode (Android 7+): a clock floor that does not throttle away after
|
||||
* two minutes, which suits an hour in Big Picture better than a boost that fades;
|
||||
* - the panel's fastest mode at its current size (Android 6+): a 120 Hz phone is switched to
|
||||
* 120 Hz for the menu, not only when a game votes for it;
|
||||
* - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases
|
||||
* its boost on loading screens or menus keeps it up.
|
||||
*
|
||||
* Every step is version-guarded and skipped silently below its API; the returned line is what
|
||||
* the session log shows, which is the first thing to read on a device that feels slow.
|
||||
*/
|
||||
object PerfMode {
|
||||
private const val TAG = "PerfMode"
|
||||
|
||||
fun apply(a: Activity): String {
|
||||
val parts = ArrayList<String>(3)
|
||||
|
||||
// Sustained performance mode.
|
||||
parts += if (Build.VERSION.SDK_INT >= 24) {
|
||||
val pm = a.getSystemService(PowerManager::class.java)
|
||||
if (pm?.isSustainedPerformanceModeSupported == true) {
|
||||
try { a.window.setSustainedPerformanceMode(true); "sustained mode on" } catch (t: Throwable) { Log.w(TAG, "sustained mode", t); "sustained mode refused" }
|
||||
} else "sustained mode unsupported"
|
||||
} else "sustained mode needs Android 7"
|
||||
|
||||
// The fastest display mode at the panel's current size.
|
||||
parts += try {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay
|
||||
if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else {
|
||||
val cur = display.mode
|
||||
val best = display.supportedModes
|
||||
.filter { it.physicalWidth == cur.physicalWidth && it.physicalHeight == cur.physicalHeight }
|
||||
.maxByOrNull { it.refreshRate }
|
||||
if (best != null && best.modeId != cur.modeId && best.refreshRate > cur.refreshRate + 0.5f) {
|
||||
a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = best.modeId }
|
||||
"display ${cur.refreshRate.toInt()} → ${best.refreshRate.toInt()} Hz (mode ${best.modeId})"
|
||||
} else "display ${cur.refreshRate.toInt()} Hz"
|
||||
}
|
||||
} catch (t: Throwable) { Log.w(TAG, "display mode", t); "display mode failed" }
|
||||
|
||||
// GameManager: what mode the OS put us in, and that we are playing.
|
||||
parts += if (Build.VERSION.SDK_INT >= 31) {
|
||||
val gm = a.getSystemService(GameManager::class.java)
|
||||
if (gm == null) "no GameManager" else {
|
||||
val mode = when (gm.gameMode) {
|
||||
GameManager.GAME_MODE_PERFORMANCE -> "performance"
|
||||
GameManager.GAME_MODE_BATTERY -> "battery"
|
||||
GameManager.GAME_MODE_STANDARD -> "standard"
|
||||
else -> "unsupported"
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
try { gm.setGameState(GameState(false, GameState.MODE_GAMEPLAY_INTERRUPTIBLE)) } catch (t: Throwable) { Log.w(TAG, "game state", t) }
|
||||
}
|
||||
"game mode $mode"
|
||||
}
|
||||
} else "game mode needs Android 12"
|
||||
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.StatFs
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import org.json.JSONArray
|
||||
|
||||
/** Immediate download and installation of the optional ARM64 Proton builds. */
|
||||
object ProtonExtras {
|
||||
private const val TAG = "ProtonExtras"
|
||||
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
|
||||
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
|
||||
@Volatile
|
||||
var installInProgress = false
|
||||
private set
|
||||
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||
|
||||
private data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long)
|
||||
|
||||
val tools = listOf(
|
||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
||||
)
|
||||
|
||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||
private fun requests(context: Context) = File(home(context), ".bl-proton-extra")
|
||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||
|
||||
/** The installed build's directory name (e.g. GE-Proton11-7), or null. */
|
||||
fun installed(context: Context, tool: Tool): String? =
|
||||
toolsDir(context).listFiles()
|
||||
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && File(it, "toolmanifest.vdf").isFile }
|
||||
?.maxByOrNull { it.name }?.name
|
||||
|
||||
/** A request left by an earlier app version, still consumed by the session shim. */
|
||||
fun queued(context: Context, tool: Tool): Boolean =
|
||||
requestLines(context).any { it.trim() == tool.id || it.trim().startsWith(tool.id + " ") }
|
||||
|
||||
fun unqueue(context: Context, tool: Tool) {
|
||||
val lines = requestLines(context).filterNot { it.trim() == tool.id || it.trim().startsWith(tool.id + " ") }
|
||||
val file = requests(context)
|
||||
if (lines.isEmpty()) file.delete()
|
||||
else file.writeText(lines.joinToString("\n") + "\n")
|
||||
}
|
||||
|
||||
/** Deletes the installed build; Steam discovers its absence on its next start. */
|
||||
fun remove(context: Context, tool: Tool) {
|
||||
installed(context, tool)?.let { File(toolsDir(context), it).deleteRecursively() }
|
||||
}
|
||||
|
||||
/** Downloads, verifies and registers the latest build without waiting for another session. */
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return "A compatibility tool install is already running"
|
||||
installInProgress = true
|
||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return "Stop the active session before installing compatibility tools"
|
||||
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
|
||||
|
||||
val asset = findLatestAsset(tool) ?: return "Could not find an ARM64 release for ${tool.name}"
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||
return "At least 4 GB free plus the download size is required to install ${tool.name}"
|
||||
}
|
||||
|
||||
onProgress("Downloading ${tool.name} ${asset.tag}", 0)
|
||||
var downloaded = false
|
||||
for (attempt in 0 until 5) {
|
||||
downloaded = Downloader.downloadFile(asset.url, archive, true) { fraction ->
|
||||
onProgress("Downloading ${tool.name} ${asset.tag}", if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
||||
}
|
||||
if (downloaded) break
|
||||
if (attempt < 4) {
|
||||
onProgress("Retrying download · attempt ${attempt + 2} of 5", -1)
|
||||
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
return "Download interrupted"
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!downloaded) return "Download failed; the partial file is kept so a retry can resume"
|
||||
if (asset.size > 0 && archive.length() != asset.size) {
|
||||
if (archive.length() > asset.size) {
|
||||
archive.delete()
|
||||
return "Download exceeded the release size and was deleted"
|
||||
}
|
||||
return "Download was incomplete; the partial file is kept for a resumable retry"
|
||||
}
|
||||
|
||||
asset.sha512?.let { checksumUrl ->
|
||||
onProgress("Verifying download", -1)
|
||||
val checksumText = Downloader.downloadString(checksumUrl)
|
||||
val expected = checksumText?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
||||
if (expected != null && !expected.equals(sha512(archive), ignoreCase = true)) {
|
||||
archive.delete()
|
||||
return "Checksum mismatch; the download was deleted"
|
||||
}
|
||||
}
|
||||
|
||||
if (SessionState.running) return "A session started during the download; stop it before installing compatibility tools"
|
||||
onProgress("Installing ${tool.name}", -1)
|
||||
return try {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
|
||||
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
|
||||
val guest = listOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
|
||||
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
|
||||
"/usr/local/bin/bannerlator-proton-extra", "/root/.local/share/Steam", archive.absolutePath,
|
||||
)
|
||||
val command = LinuxRuntime.command(context, null, runtimeDir, null, guest)
|
||||
val process = ProcessBuilder(command)
|
||||
.directory(root)
|
||||
.redirectErrorStream(true)
|
||||
val hostEnv = process.environment()
|
||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
|
||||
hostEnv["PROOT_TMP_DIR"] = context.cacheDir.path
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
|
||||
val child = process.start()
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
Log.i(TAG, line)
|
||||
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
|
||||
onProgress("Installing ${tool.name}", -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
val status = child.waitFor()
|
||||
if (status != 0) "${tool.name} installation failed (exit $status)"
|
||||
else {
|
||||
archive.delete()
|
||||
unqueue(context, tool)
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "install ${tool.id}", e)
|
||||
e.message ?: "Could not install ${tool.name}"
|
||||
}
|
||||
}
|
||||
|
||||
private fun findLatestAsset(tool: Tool): Asset? {
|
||||
val releases = Downloader.downloadString(RELEASES.format(tool.repo)) ?: return null
|
||||
return try {
|
||||
val array = JSONArray(releases)
|
||||
for (i in 0 until array.length()) {
|
||||
val release = array.getJSONObject(i)
|
||||
if (release.optBoolean("draft", false)) continue
|
||||
val assets = release.optJSONArray("assets") ?: continue
|
||||
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
|
||||
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
|
||||
val name = archive.optString("name")
|
||||
val stem = name.substringBefore(".tar")
|
||||
val checksum = entries.firstOrNull {
|
||||
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
|
||||
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
|
||||
return Asset(
|
||||
release.optString("tag_name"), name,
|
||||
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
|
||||
archive.optLong("size", 0L),
|
||||
)
|
||||
}
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "release metadata for ${tool.id}", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha512(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-512")
|
||||
file.inputStream().buffered().use { input ->
|
||||
val buffer = ByteArray(4 * 1024 * 1024)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
||||
}
|
||||
|
||||
private fun requestLines(context: Context): List<String> =
|
||||
FileUtils.readString(requests(context))?.lines()?.filter { it.isNotBlank() } ?: emptyList()
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
|
||||
/**
|
||||
* Other apps on the device that sign into the user's Steam account with their own client. Steam
|
||||
* allows one session per account: the moment one of them signs in, ours is signed out - which
|
||||
* shows up as "Session Replaced" in the client's log 2-3 seconds after every login, and looks
|
||||
* like a bug in this app.
|
||||
*
|
||||
* Installed is the most a normal app can know (since Android 7 `getRunningAppProcesses()` returns
|
||||
* only the caller's own), so the list is checked for presence and then asked to stop.
|
||||
* `killBackgroundProcesses` is a normal permission: it ends an app's background processes and
|
||||
* leaves anything in the foreground alone - and background is exactly the case that keeps
|
||||
* happening, because GameHub declares boot receivers and is running from the moment the phone
|
||||
* starts without ever having been opened. Telling someone to close an app they never opened is
|
||||
* not much help. Ported from Bannerlator's Linux session (GPL-3.0).
|
||||
*/
|
||||
object RivalClients {
|
||||
private const val TAG = "RivalClients"
|
||||
|
||||
private val PACKAGES = arrayOf(
|
||||
"com.xiaoji.egggame", // GameHub
|
||||
)
|
||||
|
||||
fun installed(context: Context): List<String> =
|
||||
PACKAGES.filter { pkg ->
|
||||
try { context.packageManager.getPackageInfo(pkg, 0); true } catch (e: Throwable) { false }
|
||||
}
|
||||
|
||||
fun name(pkg: String): String = if (pkg == "com.xiaoji.egggame") "GameHub" else pkg
|
||||
|
||||
/**
|
||||
* Stop the installed rivals' background processes before the client starts, and say so. A
|
||||
* rival in the foreground survives this, so the wording covers that case too. Call on the main
|
||||
* thread; the Toast is shown from here.
|
||||
*/
|
||||
fun stopBeforeSession(context: Context) {
|
||||
val rivals = installed(context)
|
||||
if (rivals.isEmpty()) return
|
||||
val who = name(rivals[0])
|
||||
Log.w(TAG, "competing Steam client installed: $rivals")
|
||||
var asked = false
|
||||
try {
|
||||
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
|
||||
if (am != null) {
|
||||
for (pkg in rivals) am.killBackgroundProcesses(pkg)
|
||||
asked = true
|
||||
Log.i(TAG, "asked Android to stop background processes of $rivals")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "could not stop competing Steam clients", t)
|
||||
}
|
||||
Toast.makeText(
|
||||
context,
|
||||
if (asked) "Closed $who in the background - it signs into your Steam account."
|
||||
else "If $who is open, close it first - it signs into your Steam account and will sign this client out.",
|
||||
Toast.LENGTH_LONG,
|
||||
).show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.net.LocalServerSocket
|
||||
import android.os.Build
|
||||
import android.os.VibrationEffect
|
||||
import android.os.Vibrator
|
||||
import android.os.VibratorManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.DataInputStream
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* Rumble for the on-screen pad, on the phone itself.
|
||||
*
|
||||
* When a game plays a force-feedback effect on the fake pad, the fake evdev layer inside the guest
|
||||
* connects to the abstract socket [NAME] and sends one packet: strong, weak, duration in ms and
|
||||
* the pad slot, four little-endian 16-bit values. This listens for those and drives the device's
|
||||
* vibrator with the stronger motor's strength for the effect's duration. Best effort both ways:
|
||||
* a missing listener costs the guest nothing, and a bad packet is dropped.
|
||||
*/
|
||||
class RumbleComponent : SessionPart() {
|
||||
@Volatile private var server: LocalServerSocket? = null
|
||||
|
||||
override fun start() {
|
||||
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
|
||||
server = s
|
||||
Thread({
|
||||
while (server === s) {
|
||||
val client = try { s.accept() } catch (e: Exception) { break }
|
||||
try {
|
||||
val bytes = ByteArray(8)
|
||||
DataInputStream(client.inputStream).readFully(bytes)
|
||||
val strong = u16(bytes, 0); val weak = u16(bytes, 2); val ms = u16(bytes, 4)
|
||||
buzz(max(strong, weak), ms)
|
||||
} catch (e: Exception) {
|
||||
// A partial packet or a closed peer: nothing to play.
|
||||
} finally {
|
||||
try { client.close() } catch (e: Exception) { /* already gone */ }
|
||||
}
|
||||
}
|
||||
}, "rumble").apply { isDaemon = true; start() }
|
||||
Log.i(TAG, "rumble: listening on @$NAME")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
val s = server ?: return
|
||||
server = null
|
||||
try { s.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ }
|
||||
}
|
||||
|
||||
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
|
||||
|
||||
private fun buzz(strength: Int, ms: Int) {
|
||||
val ctx = app() ?: return
|
||||
val vibrator: Vibrator = if (Build.VERSION.SDK_INT >= 31) ctx.getSystemService(VibratorManager::class.java)?.defaultVibrator ?: return
|
||||
else @Suppress("DEPRECATION") (ctx.getSystemService(Vibrator::class.java) ?: return)
|
||||
if (!vibrator.hasVibrator()) return
|
||||
if (strength == 0 || ms == 0) { vibrator.cancel(); return }
|
||||
val amplitude = (strength * 255L / 65535L).toInt().coerceIn(1, 255)
|
||||
val duration = ms.toLong().coerceIn(1L, 5000L)
|
||||
try {
|
||||
if (vibrator.hasAmplitudeControl()) vibrator.vibrate(VibrationEffect.createOneShot(duration, amplitude))
|
||||
else vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "rumble: $e")
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
/** Must match the fake evdev layer (fakeinput_steam.cpp). */
|
||||
const val NAME = "droiddeck-rumble"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.core.SessionLogCapture
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Finishes a session's folder: the compositor's log, the Steam client's logs scrubbed line by
|
||||
* line, Android's crash buffer, and a marker that says the folder is complete.
|
||||
*
|
||||
* Three callers, because a session ends three ways. [collect] runs at an ordinary stop. The
|
||||
* app's uncaught-exception handler ([CrashHandler]) runs it as the process dies, so a crash in
|
||||
* our own code leaves a full folder and not a half one. And [finishAbandoned] runs at the next
|
||||
* app start for a folder that has no marker: the process was killed outright (Android's phantom
|
||||
* process killer, a native crash in the compositor, the battery) and nothing of ours got to run.
|
||||
* Everything written *during* the session - session.log, app.log, wayland.log, audio.log, the
|
||||
* device report - is already on disk at that point; only the pieces gathered at the end were
|
||||
* missing, and the crash buffer keeps its entries after the process is gone, which is the whole
|
||||
* reason it is worth coming back for.
|
||||
*/
|
||||
object SessionArtifacts {
|
||||
private const val TAG = "SessionArtifacts"
|
||||
|
||||
/** Written last; a folder without it did not get its ending. */
|
||||
const val COMPLETE_MARKER = ".complete"
|
||||
|
||||
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
|
||||
fun collect(context: Context, dir: File, reason: String) {
|
||||
try {
|
||||
val wayland = File(dir, "wayland.log")
|
||||
if (!wayland.exists()) {
|
||||
WaylandCompositor.currentLogFile()?.takeIf { it.isFile }?.let { src ->
|
||||
src.copyTo(wayland, overwrite = true)
|
||||
}
|
||||
}
|
||||
copySteamLogs(context, dir)
|
||||
// A session the system killed leaves its trace here and nowhere else.
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting session artifacts", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Steam's logs: redacted into steam/, never copied verbatim. */
|
||||
private fun copySteamLogs(context: Context, dir: File) {
|
||||
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
|
||||
if (!logs.isDirectory) return
|
||||
val out = File(dir, "steam").apply { mkdirs() }
|
||||
logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
|
||||
try {
|
||||
File(out, src.name).bufferedWriter().use { w ->
|
||||
src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${src.name}", e)
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
||||
}
|
||||
|
||||
/**
|
||||
* Every session folder without a marker gets its ending now. Only the newest of them gets the
|
||||
* Steam logs - the runtime holds one set, and it belongs to the last session that ran; an
|
||||
* older folder would be handed logs that are not its own. Runs on a worker thread at app
|
||||
* start; nothing here touches the session that is about to begin.
|
||||
*/
|
||||
fun finishAbandoned(context: Context) {
|
||||
val parent = LinuxRuntime.debugLogDir()
|
||||
val abandoned = parent.listFiles { f ->
|
||||
f.isDirectory && f.name.startsWith("session-") && !File(f, COMPLETE_MARKER).exists()
|
||||
}?.sortedBy { it.name } ?: return
|
||||
if (abandoned.isEmpty()) return
|
||||
val current = SessionPaths.current()
|
||||
abandoned.forEachIndexed { i, dir ->
|
||||
if (dir == current) return@forEachIndexed
|
||||
val newest = i == abandoned.lastIndex
|
||||
try {
|
||||
File(dir, "ended-without-teardown.txt").writeText(
|
||||
"This session's process ended without running its own teardown - killed by\n" +
|
||||
"Android, a native crash, or the device going down - so the files below were\n" +
|
||||
"gathered when the app next started, at ${now()}.\n" +
|
||||
"The logs written during the session (session.log, app.log, wayland.log,\n" +
|
||||
"audio.log, device.txt) were on disk already and are as they were left.\n" +
|
||||
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
|
||||
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n"
|
||||
)
|
||||
if (newest) {
|
||||
copySteamLogs(context, dir)
|
||||
}
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
|
||||
Log.i(TAG, "finished the abandoned session folder $dir")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not finish $dir", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/** Everything the session needs written into the runtime before it starts. */
|
||||
object SessionFiles {
|
||||
private const val TAG = "SessionFiles"
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
/** Where the DirectAudio driver lives inside the runtime; the wrappers get it as BL_DIRECTAUDIO. */
|
||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||
|
||||
/**
|
||||
* The libraries and scripts the session runs, refreshed from the apk at every launch.
|
||||
*
|
||||
* The runtime image carries its own copies, but a runtime installed months ago carries the
|
||||
* copies of that day and a device has no way to replace them from outside the app. Staging
|
||||
* them here is how a fix inside the session shim, the controller reader or one of the scripts
|
||||
* reaches an already-installed runtime without a ~790 MB re-download. Each lands through a
|
||||
* rename, so a session that still has one mapped keeps the file it opened.
|
||||
*/
|
||||
fun stage(context: Context, root: File) {
|
||||
val files = arrayOf(
|
||||
"libblsession.so" to "usr/local/lib/libblsession.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
|
||||
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
|
||||
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
|
||||
"usr/local/bin/bannerlator-steam-library" to "usr/local/bin/bannerlator-steam-library",
|
||||
"usr/local/bin/bannerlator-seed-redists" to "usr/local/bin/bannerlator-seed-redists",
|
||||
"usr/local/bin/bannerlator-proton-extra" to "usr/local/bin/bannerlator-proton-extra",
|
||||
"usr/local/bin/bannerlator-netmanager" to "usr/local/bin/bannerlator-netmanager",
|
||||
"usr/local/bin/bannerlator-steam-launch" to "usr/local/bin/bannerlator-steam-launch",
|
||||
"usr/local/bin/bannerlator-desktop-games" to "usr/local/bin/bannerlator-desktop-games",
|
||||
"usr/local/bin/bannerlator-steam-shim" to "usr/local/bin/bannerlator-steam-shim",
|
||||
"usr/local/bin/bannerlator-steam-shortcuts" to "usr/local/bin/bannerlator-steam-shortcuts",
|
||||
// The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus
|
||||
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
|
||||
"usr/bin/steamos-update" to "usr/bin/steamos-update",
|
||||
"usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch",
|
||||
"usr/bin/jupiter-biosupdate" to "usr/bin/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-priv-write" to "usr/bin/steamos-polkit-helpers/steamos-priv-write",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-set-timezone" to "usr/bin/steamos-polkit-helpers/steamos-set-timezone",
|
||||
// On device the client called these four by their polkit-helpers path, not /usr/bin: the
|
||||
// "Update Error" dialog was steamos-update missing there.
|
||||
"usr/bin/steamos-polkit-helpers/steamos-update" to "usr/bin/steamos-polkit-helpers/steamos-update",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-select-branch" to "usr/bin/steamos-polkit-helpers/steamos-select-branch",
|
||||
"usr/bin/steamos-polkit-helpers/jupiter-biosupdate" to "usr/bin/steamos-polkit-helpers/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/jupiter-dock-updater" to "usr/bin/steamos-polkit-helpers/jupiter-dock-updater",
|
||||
)
|
||||
// The desktop's launcher and labwc defaults, only where the desktop package is installed:
|
||||
// staging them into a runtime without it would make the desktop look present when it is not.
|
||||
val desktop = arrayOf(
|
||||
"usr/local/bin/droiddeck-desktop" to "usr/local/bin/droiddeck-desktop",
|
||||
"etc/xdg/labwc/autostart" to "etc/xdg/labwc/autostart",
|
||||
"etc/xdg/labwc/rc.xml" to "etc/xdg/labwc/rc.xml",
|
||||
"etc/xdg/lxqt/panel.conf" to "etc/xdg/lxqt/panel.conf",
|
||||
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
|
||||
)
|
||||
// The patched gamescope (tools/gamescope): the runtime's own version rebuilt with the ARM64
|
||||
// client fixes, over /usr/local/bin so it comes first in the session's PATH. Only when the
|
||||
// apk carries it - a build without the asset leaves the runtime's copy alone.
|
||||
// Valve's mangoapp (tools/mangoapp) - Deck mode's performance overlay - with the five
|
||||
// libraries the runtime lacks beside it, and the wrapper on PATH that points it at them.
|
||||
val mangoapp = listOf(
|
||||
"usr/local/bin/mangoapp",
|
||||
"usr/local/lib/mangoapp/mangoapp",
|
||||
"usr/local/lib/mangoapp/libfmt.so.10",
|
||||
"usr/local/lib/mangoapp/libspdlog.so.1.13",
|
||||
"usr/local/lib/mangoapp/libglfw.so.3",
|
||||
"usr/local/lib/mangoapp/libtraceevent.so.1",
|
||||
"usr/local/lib/mangoapp/libtracefs.so.1",
|
||||
).map { it to it }
|
||||
val optional = (arrayOf(
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
) + mangoapp).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
val all = (if (File(root, "usr/bin/labwc").isFile) files + desktop else files) + optional
|
||||
for ((asset, relative) in all) {
|
||||
val target = File(root, relative)
|
||||
val staged = File(target.parentFile, target.name + ".staged")
|
||||
var installed = false
|
||||
try {
|
||||
target.parentFile?.mkdirs()
|
||||
context.assets.open("linuxfs/$asset").use { input ->
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setExecutable(true, false) && staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage $relative", e)
|
||||
} finally {
|
||||
if (!installed) staged.delete()
|
||||
}
|
||||
if (!installed) Log.e(TAG, "$relative NOT staged")
|
||||
}
|
||||
// The DirectAudio driver for games under Proton: the glibc build of winedirectaudio, which
|
||||
// the Proton wrappers add to WINEDLLPATH when the session asks for it (BL_DIRECTAUDIO).
|
||||
// Staged like the scripts, so a driver fix reaches an installed runtime without re-hosting.
|
||||
val directAudio = arrayOf(
|
||||
"aarch64-unix/winedirectaudio.so",
|
||||
"aarch64-windows/winedirectaudio.drv",
|
||||
"i386-windows/winedirectaudio.drv",
|
||||
)
|
||||
for (relative in directAudio) {
|
||||
val target = File(root, "$DIRECTAUDIO_DIR/lib/wine/$relative")
|
||||
val staged = File(target.parentFile, target.name + ".staged")
|
||||
var installed = false
|
||||
try {
|
||||
target.parentFile?.mkdirs()
|
||||
context.assets.open("directaudio/linux-wine11/$relative").use { input ->
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setReadable(true, false) && staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage DirectAudio $relative", e)
|
||||
} finally {
|
||||
if (!installed) staged.delete()
|
||||
}
|
||||
if (!installed) Log.e(TAG, "DirectAudio $relative NOT staged")
|
||||
}
|
||||
// What every process in the session preloads. LD_PRELOAD in the environment would not
|
||||
// survive: the Steam client rebuilds it for each process it starts and appends its own
|
||||
// overlay entry without a separator, which silently drops whatever was there.
|
||||
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
val etc = File(root, "etc").apply { mkdirs() }
|
||||
val staged = File(etc, "ld.so.preload.staged")
|
||||
if (!FileUtils.writeString(staged, preload.toString())
|
||||
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write ld.so.preload")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
|
||||
* folder rather than dug out of app-private storage - but the session script redirects its own
|
||||
* output there with `exec`, and a redirection a non-interactive shell cannot open ends that
|
||||
* shell. So a public directory is used only once it is proven writable; otherwise the app's
|
||||
* own files directory, which is bound into the session anyway, stands in.
|
||||
*/
|
||||
fun logDirectory(context: Context): File {
|
||||
val public = LinuxRuntime.debugLogDir()
|
||||
if (public.isDirectory || public.mkdirs()) {
|
||||
val probe = File(public, ".writable")
|
||||
try {
|
||||
if (probe.createNewFile() || probe.isFile) {
|
||||
probe.delete()
|
||||
return public
|
||||
}
|
||||
} catch (ignored: Exception) {
|
||||
}
|
||||
}
|
||||
Log.w(TAG, "$public is not writable (storage permission?); logging to files/logs")
|
||||
return File(context.filesDir, "logs").apply { mkdirs() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
/**
|
||||
* Zips the most recent session's log folder and hands it to Android's share sheet. Works where
|
||||
* the folder could not be written to Downloads (no storage permission, or a device that refuses
|
||||
* it) and landed in the app's private files instead, which a user cannot otherwise reach.
|
||||
*/
|
||||
object SessionLogShare {
|
||||
/** The newest session folder in either place logs are written, or null if there is none. */
|
||||
fun latest(context: Context): File? =
|
||||
listOf(LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
|
||||
.flatMap { dir -> dir.listFiles { f -> f.isDirectory && f.name.startsWith("session-") }?.toList() ?: emptyList() }
|
||||
.maxByOrNull { it.name }
|
||||
|
||||
/** Builds the zip (blocking). Returns null when there is no session to share. */
|
||||
fun zipLatest(context: Context): File? {
|
||||
val folder = latest(context) ?: return null
|
||||
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { z ->
|
||||
folder.walkTopDown().filter { it.isFile }.forEach { f ->
|
||||
z.putNextEntry(ZipEntry(folder.name + "/" + f.relativeTo(folder).path))
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
z.closeEntry()
|
||||
}
|
||||
}
|
||||
return zip
|
||||
}
|
||||
|
||||
fun shareIntent(context: Context, zip: File): Intent {
|
||||
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", zip)
|
||||
val send = Intent(Intent.ACTION_SEND)
|
||||
.setType("application/zip")
|
||||
.putExtra(Intent.EXTRA_STREAM, uri)
|
||||
.putExtra(Intent.EXTRA_SUBJECT, zip.nameWithoutExtension)
|
||||
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
send.clipData = ClipData.newRawUri(zip.name, uri)
|
||||
return Intent.createChooser(send, "Share session logs").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded:
|
||||
*
|
||||
* ```
|
||||
* Download/DroidDeck/session-20260921-161256/
|
||||
* device.txt what this device is, and every setting the session ran with
|
||||
* session.log the guest session: proot, gamescope, the client's stdout
|
||||
* wayland.log the app's compositor
|
||||
* steam.log the Steam client's own log, scrubbed (Steam mode)
|
||||
* steam/ the rest of the client's logs, scrubbed (Steam mode)
|
||||
* desktop.log labwc, the panel and the programs on it (desktop mode)
|
||||
* ```
|
||||
*
|
||||
* The folder is claimed by whoever starts first - the activity starts the compositor before the
|
||||
* service starts the session - so both write into the same one, and a recreated activity (a
|
||||
* foldable opening mid-session) joins the folder in progress instead of opening another.
|
||||
*/
|
||||
object SessionPaths {
|
||||
private const val TAG = "SessionPaths"
|
||||
|
||||
@Volatile
|
||||
private var dir: File? = null
|
||||
|
||||
/**
|
||||
* The folder for the session now starting, or the one already in progress. With logs turned
|
||||
* off on the main screen the folder lives in the app's cache instead of Downloads - the
|
||||
* scripts and the compositor still need somewhere to write - and [release] deletes it.
|
||||
*/
|
||||
@Synchronized
|
||||
fun beginOrCurrent(context: Context): File {
|
||||
dir?.let { if (it.isDirectory) return it }
|
||||
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
|
||||
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
|
||||
else File(context.cacheDir, "session-logs")
|
||||
val made = File(parent, "session-$stamp")
|
||||
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
|
||||
dir = made
|
||||
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
|
||||
return made
|
||||
}
|
||||
|
||||
/** The current session's folder, or null between sessions. */
|
||||
fun current(): File? = dir
|
||||
|
||||
/**
|
||||
* The ending session takes its folder with it: the next session (one that replaces this one
|
||||
* in place) then claims a folder of its own instead of sharing, and this one's collector
|
||||
* finishes the folder it was handed. Called on the main thread as the session stops.
|
||||
*/
|
||||
@Synchronized
|
||||
fun take(): File? {
|
||||
val ended = dir
|
||||
dir = null
|
||||
return ended
|
||||
}
|
||||
|
||||
/** A file in the current session's folder, or null between sessions. */
|
||||
fun file(name: String): File? = dir?.let { File(it, name) }
|
||||
|
||||
/** Let the next session claim a new folder. Called when a session ends. */
|
||||
@Synchronized
|
||||
fun release(context: Context, ended: File) {
|
||||
// Only the session that owns the folder lets go of it (take() usually has already): the
|
||||
// next session may have claimed its own by the time the last one's collector gets here.
|
||||
if (dir == ended) dir = null
|
||||
// A folder kept in the cache was never meant to outlive its session.
|
||||
if (ended != null && ended.path.startsWith(context.cacheDir.path)) {
|
||||
com.droiddeck.launcher.core.FileUtils.delete(ended)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
|
||||
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
|
||||
object SessionPrefs {
|
||||
const val SUSPEND_AUTO = "auto"
|
||||
const val SUSPEND_MANUAL = "manual"
|
||||
const val SUSPEND_NEVER = "never"
|
||||
|
||||
const val OSC_AUTO = "auto"
|
||||
const val OSC_ALWAYS = "always"
|
||||
const val OSC_STEAM_QAM = "steam-qam"
|
||||
const val OSC_NEVER = "never"
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true)
|
||||
|
||||
fun setHudEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hud", on).apply()
|
||||
}
|
||||
|
||||
const val TOUCH_AUTO = "auto"
|
||||
const val TOUCH_PAD = "touchpad"
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
|
||||
/** How touch drives the pointer: a touchpad (drag moves it from where it is) or direct
|
||||
* (it jumps under the finger). Auto = touchpad on the desktop, direct in Steam. */
|
||||
fun touchMode(context: Context): String = prefs(context).getString("touch", TOUCH_AUTO) ?: TOUCH_AUTO
|
||||
|
||||
fun setTouchMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("touch", mode).apply()
|
||||
}
|
||||
|
||||
const val SHAPE_AUTO = "auto"
|
||||
const val SHAPE_WIDE = "16:9"
|
||||
const val SHAPE_EXACT = "exact"
|
||||
|
||||
/** The choices the settings offer, in order. */
|
||||
val shapeChoices = listOf(
|
||||
SHAPE_AUTO to "The panel's shape (16:9 or wider)",
|
||||
SHAPE_EXACT to "Exactly this panel (4:3, 3:2…)",
|
||||
SHAPE_WIDE to "16:9 with bars",
|
||||
)
|
||||
|
||||
/**
|
||||
* 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
|
||||
* 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.
|
||||
*/
|
||||
fun shapeMode(context: Context): String =
|
||||
prefs(context).getString("shape", null)
|
||||
?: 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 setOscMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("osc", mode).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The imported glibc Turnip a mode draws with inside the runtime, keyed by
|
||||
* SessionService.MODE_STEAM / MODE_DESKTOP so Steam and the desktop can differ; "" = the
|
||||
* driver built into the runtime. Resolved by LinuxVulkanDriver at session start.
|
||||
*/
|
||||
fun linuxDriver(context: Context, mode: String): String =
|
||||
prefs(context).getString("linuxDriver.$mode", "") ?: ""
|
||||
|
||||
fun setLinuxDriver(context: Context, mode: String, id: String) {
|
||||
prefs(context).edit().putString("linuxDriver.$mode", id).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The Steam client's own sound through the DirectAudio relay instead of the classic AAudio
|
||||
* sink. Off by default: on an AYN Thor (Android 13, 20 ms bursts) the relay path stayed choppy
|
||||
* where the classic sink - the one 0.1.5 shipped - was fine.
|
||||
*/
|
||||
fun clientDirectAudio(context: Context): Boolean = prefs(context).getBoolean("clientDirectAudio", false)
|
||||
|
||||
fun setClientDirectAudio(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("clientDirectAudio", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* DirectAudio for games: their Wine audio driver talks to the relay helper on this side. On
|
||||
* unless the user turned it off.
|
||||
*/
|
||||
fun directAudio(context: Context): Boolean = prefs(context).getBoolean("directAudio", true)
|
||||
|
||||
fun setDirectAudio(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("directAudio", on).apply()
|
||||
}
|
||||
|
||||
/** The microphone for voice chat, on unless turned off; used only once RECORD_AUDIO is granted. */
|
||||
fun micEnabled(context: Context): Boolean = prefs(context).getBoolean("mic", true)
|
||||
|
||||
/** Whether the app has already asked for the microphone once at start-up. */
|
||||
fun micAsked(context: Context): Boolean = prefs(context).getBoolean("micAsked", false)
|
||||
|
||||
fun setMicAsked(context: Context) {
|
||||
prefs(context).edit().putBoolean("micAsked", true).apply()
|
||||
}
|
||||
|
||||
fun setMicEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("mic", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the client's own core pick is overridden. When on, BL_CLIENT_CPUS is sent even when
|
||||
* it names every core - unlike a game mask, the point here is to undo a pin Steam applies to
|
||||
* itself, and the scheduler's default is exactly what Steam's choice takes away.
|
||||
*/
|
||||
fun clientCpusOverride(context: Context): Boolean = prefs(context).getBoolean("clientCpusOverride", false)
|
||||
|
||||
fun setClientCpusOverride(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("clientCpusOverride", on).apply()
|
||||
}
|
||||
|
||||
/** Comma-separated core list for the client (taskset -c syntax); "" = every core. */
|
||||
fun clientCpus(context: Context): String = prefs(context).getString("clientCpus", "") ?: ""
|
||||
|
||||
fun setClientCpus(context: Context, list: String) {
|
||||
prefs(context).edit().putString("clientCpus", list).apply()
|
||||
}
|
||||
|
||||
/** Comma-separated core list for games (taskset -c syntax); "" = every core = nothing sent. */
|
||||
fun gameCpus(context: Context): String = prefs(context).getString("gameCpus", "") ?: ""
|
||||
|
||||
fun setGameCpus(context: Context, list: String) {
|
||||
prefs(context).edit().putString("gameCpus", list).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Steam's xalia helper is kept out of the session (PROTON_USE_XALIA=0).
|
||||
*
|
||||
* xalia is an x86 Windows program Proton launches to give Windows programs gamepad navigation.
|
||||
* Under FEX it cannot load the session's aarch64 preload shim, so its socket() and memfd calls
|
||||
* reach the vendor's seccomp filter raw; where that answers ENOSYS - a Galaxy Fold, measured -
|
||||
* it storms, and the session dies seconds after Big Picture appears.
|
||||
*/
|
||||
fun noXalia(context: Context): Boolean = prefs(context).getBoolean("noXalia", false)
|
||||
|
||||
fun setNoXalia(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("noXalia", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether proot runs without its seccomp acceleration (PROOT_NO_SECCOMP=1).
|
||||
*
|
||||
* proot normally installs a seccomp filter so only the syscalls it must rewrite stop in the
|
||||
* tracer; everything else runs untraced, which is most of proot's speed. Where a vendor kernel
|
||||
* handles that filter badly the wrong calls are trapped or refused - ENOSYS from calls that
|
||||
* plainly exist is the signature - and the fallback is to trace everything instead: slower,
|
||||
* but correct. Max's advice for devices whose kernels "don't work well with it".
|
||||
*/
|
||||
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
|
||||
|
||||
fun setProotNoSeccomp(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
/** Turnip's sysmem rendering (TU_DEBUG=sysmem) for the runtime's driver: bypasses GMEM tiling. */
|
||||
fun tuSysmem(context: Context): Boolean = prefs(context).getBoolean("tuSysmem", false)
|
||||
|
||||
fun setTuSysmem(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("tuSysmem", on).apply()
|
||||
}
|
||||
|
||||
/*
|
||||
* The client's interface is drawn Chromium -> ANGLE -> Zink -> Turnip, and that chain is what
|
||||
* limits its menus (~14 fps on an Adreno 840 while a game ran 89). These make the chain
|
||||
* cheaper rather than asking for more; the three environment switches are on by default,
|
||||
* Deck mode off. Bannerlator's LinuxTuning, carried over; none device-proven here yet.
|
||||
*/
|
||||
/** mesa_glthread=true: GL marshalled off the calling thread. */
|
||||
fun glThread(context: Context): Boolean = prefs(context).getBoolean("glThread", true)
|
||||
fun setGlThread(context: Context, on: Boolean) { prefs(context).edit().putBoolean("glThread", on).apply() }
|
||||
|
||||
/** MESA_NO_ERROR=1: no GL error checking. */
|
||||
fun noGlError(context: Context): Boolean = prefs(context).getBoolean("noGlError", true)
|
||||
fun setNoGlError(context: Context, on: Boolean) { prefs(context).edit().putBoolean("noGlError", on).apply() }
|
||||
|
||||
/** `steam -steamdeck -steamos3`: the client as SteamOS runs it. Expects Deck hardware; untested. */
|
||||
fun steamDeckMode(context: Context): Boolean = prefs(context).getBoolean("steamDeckMode", false)
|
||||
fun setSteamDeckMode(context: Context, on: Boolean) { prefs(context).edit().putBoolean("steamDeckMode", on).apply() }
|
||||
|
||||
/** Zink's lazy descriptor mode (ZINK_DESCRIPTORS=lazy) for the client's GL-on-Vulkan UI. On by default. */
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
|
||||
fun setZinkLazy(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("zinkLazy", on).apply()
|
||||
}
|
||||
|
||||
/** The Android driver the compositor loads: "" = pick by GPU, else a bundled or imported id. */
|
||||
@JvmStatic
|
||||
fun androidDriver(context: Context): String = prefs(context).getString("androidDriver", "") ?: ""
|
||||
|
||||
@JvmStatic
|
||||
fun setAndroidDriver(context: Context, id: String) {
|
||||
prefs(context).edit().putString("androidDriver", id).apply()
|
||||
}
|
||||
|
||||
// ── Storage the session can see ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The folder on this device that every session shows at `/root/ROMs`, for the emulators on the
|
||||
* desktop. "" = none chosen. All of internal storage is at `/root/Storage` regardless.
|
||||
*/
|
||||
fun romsDir(context: Context): String =
|
||||
prefs(context).getString("romsDir", "") ?: ""
|
||||
|
||||
fun setRomsDir(context: Context, path: String) {
|
||||
prefs(context).edit().putString("romsDir", path).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a session writes its folder under Download/DroidDeck. Off, the same logs are kept in
|
||||
* the app's cache for the session's lifetime (the scripts need somewhere to write) and thrown
|
||||
* away at the end, so nothing accumulates in Downloads.
|
||||
*/
|
||||
fun logsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("logs", true)
|
||||
|
||||
fun setLogsEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("logs", on).apply()
|
||||
}
|
||||
|
||||
// ── Per-mode display ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The tallest the session's display may be, in pixels, for MODE_STEAM / MODE_DESKTOP:
|
||||
* 0 = the panel's own height, otherwise a cap. Both modes default to 720p: the client's CEF
|
||||
* is the heaviest thing in a session, Big Picture is drawn for a TV at arm's length, and on
|
||||
* a handheld panel 720p is where its menus stay responsive on a regular flagship; the desktop
|
||||
* 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.
|
||||
*/
|
||||
fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", defaultResolutionCap(mode))
|
||||
|
||||
/** The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults. */
|
||||
fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", "") ?: ""
|
||||
|
||||
fun setFexPreset(context: Context, id: String) {
|
||||
prefs(context).edit().putString("fexPreset", id).apply()
|
||||
}
|
||||
|
||||
/** The Steam client branch forced on the command line: "publicbeta" (every session so far) or "steamdeck_publicbeta" (Armada's). */
|
||||
fun steamChannel(context: Context): String =
|
||||
prefs(context).getString("steamChannel", null)
|
||||
// Deck mode on the publicbeta channel reinstalls the same client at every start (the
|
||||
// client reports "installed version 0" against that manifest and exits 42 to apply it,
|
||||
// losing the launch URL each time); on steamdeck_publicbeta the second launch comes up
|
||||
// clean. Seen on device 2026-09-23. So Deck mode takes the Deck channel unless chosen.
|
||||
?: if (steamDeckMode(context)) "steamdeck_publicbeta" else "publicbeta"
|
||||
|
||||
fun setSteamChannel(context: Context, id: String) {
|
||||
prefs(context).edit().putString("steamChannel", id).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The folders of the user's own Windows games (one game per subfolder), any number of them
|
||||
* from anywhere on the device. The single folder an earlier build kept is carried in.
|
||||
*/
|
||||
fun addedGamesDirs(context: Context): List<String> {
|
||||
val p = prefs(context)
|
||||
val list = p.getString("addedGamesDirs", null)
|
||||
if (list != null) return list.split('\n').filter { it.isNotEmpty() }
|
||||
val old = p.getString("addedGamesDir", "") ?: ""
|
||||
return if (old.isEmpty()) emptyList() else listOf(old)
|
||||
}
|
||||
|
||||
fun setAddedGamesDirs(context: Context, dirs: List<String>) {
|
||||
prefs(context).edit().putString("addedGamesDirs", dirs.distinct().joinToString("\n")).remove("addedGamesDir").apply()
|
||||
}
|
||||
|
||||
/** Whether added games without art of their own get Steam's store art fetched for them. */
|
||||
fun addedGamesArt(context: Context): Boolean = prefs(context).getBoolean("addedGamesArt", true)
|
||||
|
||||
fun setAddedGamesArt(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("addedGamesArt", on).apply()
|
||||
}
|
||||
|
||||
/** The .exe the user chose for one game folder (by its path), "" = the scanner's pick. */
|
||||
fun addedGameExe(context: Context, folderPath: String): String = prefs(context).getString("addedExe:$folderPath", "") ?: ""
|
||||
|
||||
fun setAddedGameExe(context: Context, folderPath: String, path: String) {
|
||||
prefs(context).edit().putString("addedExe:$folderPath", path).apply()
|
||||
}
|
||||
|
||||
/** The app's colour theme (ui/Themes ids); Paper on black unless chosen otherwise. */
|
||||
fun theme(context: Context): String = prefs(context).getString("theme", "paper") ?: "paper"
|
||||
|
||||
fun setTheme(context: Context, id: String) {
|
||||
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
|
||||
* cap and the shape: the compositor fits it to the panel with bars where the shapes differ.
|
||||
*/
|
||||
fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
|
||||
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. */
|
||||
fun parseResolution(text: String?): Pair<Int, Int>? {
|
||||
val parts = text?.trim()?.split('x', 'X', '×', '*')?.map { it.trim() } ?: return null
|
||||
if (parts.size != 2) return null
|
||||
val w = parts[0].toIntOrNull() ?: return null
|
||||
val h = parts[1].toIntOrNull() ?: return null
|
||||
if (w !in 320..3840 || h !in 240..2160) return null
|
||||
return Pair(w and 1.inv(), h and 1.inv())
|
||||
}
|
||||
|
||||
/**
|
||||
* What the desktop shell composites with: pixman (software, the default - the Adreno stand-in
|
||||
* is not a DRM render node, so labwc's gbm allocator cannot use it), or gles2 / vulkan for a
|
||||
* device that has a real node. `Download/droiddeck-wlr-renderer` still overrides it.
|
||||
*/
|
||||
fun desktopRenderer(context: Context): String = prefs(context).getString("desktopRenderer", "pixman") ?: "pixman"
|
||||
|
||||
fun setDesktopRenderer(context: Context, renderer: String) {
|
||||
prefs(context).edit().putString("desktopRenderer", renderer).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* HDR10 output for MODE_STEAM / MODE_DESKTOP. Off by default. Honoured only when the panel
|
||||
* lists HDR10 (HdrSupport), and decided when the compositor starts, which is once per app
|
||||
* process: a change applies after the app is fully closed and opened again.
|
||||
*/
|
||||
fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean("hdr.$mode", false)
|
||||
|
||||
fun setHdr(context: Context, mode: String, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a
|
||||
* fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices.
|
||||
*/
|
||||
fun prefMode(mode: String): String = if (mode == SessionService.MODE_RUN) SessionService.MODE_STEAM else mode
|
||||
|
||||
fun suspendPolicy(context: Context, mode: String): String =
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
||||
?.takeIf { it == SUSPEND_AUTO || it == SUSPEND_MANUAL || it == SUSPEND_NEVER }
|
||||
?: SUSPEND_MANUAL
|
||||
|
||||
fun setSuspendPolicy(context: Context, mode: String, policy: String) {
|
||||
val normalized = policy.takeIf { it == SUSPEND_AUTO || it == SUSPEND_MANUAL || it == SUSPEND_NEVER }
|
||||
?: SUSPEND_MANUAL
|
||||
prefs(context).edit().putString("suspendPolicy.${prefMode(mode)}", normalized).apply()
|
||||
}
|
||||
|
||||
// ── Game storage ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A second Steam library on this device: the folder bound at /mnt/bannerlator-sd and
|
||||
* registered with the client, which then asks where to install every game and shows both
|
||||
* on its Storage page. "" = automatic: the SD card when one is in the phone (the default,
|
||||
* so the choice is made inside the client like anywhere else); GAME_STORAGE_OFF = internal
|
||||
* only; otherwise the folder chosen.
|
||||
*/
|
||||
fun gameStorage(context: Context): String = prefs(context).getString("gameStorage", "") ?: ""
|
||||
|
||||
const val GAME_STORAGE_OFF = "off"
|
||||
|
||||
fun gameStorageLabel(context: Context): String = prefs(context).getString("gameStorageLabel", "SD Card") ?: "SD Card"
|
||||
|
||||
fun setGameStorage(context: Context, path: String, label: String) {
|
||||
prefs(context).edit().putString("gameStorage", path).putString("gameStorageLabel", label).apply()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,59 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
/**
|
||||
* The little that the activity and the service have to agree on. Process-wide rather than passed
|
||||
* through intents, because both halves live in one process and the point of the split is that
|
||||
* either can outlive the other.
|
||||
*/
|
||||
object SessionState {
|
||||
@Volatile
|
||||
var running = false
|
||||
var suspended by mutableStateOf(false)
|
||||
/** MODE_RUN: the program inside the runtime the session was started for. */
|
||||
var program: String? = null
|
||||
var programArgs: List<String> = emptyList()
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI, else Big Picture; and a steam:// URL to hand it. */
|
||||
var steamUi: String? = null
|
||||
var steamUrl: String? = null
|
||||
/** A session the guest asked for (the desktop's Steam launchers): started by the activity once this one has ended. */
|
||||
var relaunch: android.content.Intent? = null
|
||||
/** HDR10 was asked for and the panel can show it: the compositor was told, and the session
|
||||
* gets DXVK_HDR=1 and gamescope --hdr-enabled. Decided by the activity before the compositor starts. */
|
||||
@JvmStatic var hdr = false
|
||||
|
||||
/** Which session this is: SessionService.MODE_STEAM or MODE_DESKTOP. */
|
||||
@Volatile
|
||||
var mode = "steam"
|
||||
|
||||
/** The size gamescope was told to render at; set by the activity before the service starts. */
|
||||
@Volatile
|
||||
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
|
||||
|
||||
@Volatile
|
||||
var refreshHz: Float = 60f
|
||||
|
||||
/** The compositor has presented a frame, so the loading panel is behind us for this session. */
|
||||
@Volatile
|
||||
var firstFrameSeen = false
|
||||
|
||||
/** Where this session is writing its log, for the "it ended" message. */
|
||||
@Volatile
|
||||
var logFile: File? = null
|
||||
|
||||
/** The fake evdev directory, once the service has prepared the rings. */
|
||||
@Volatile
|
||||
var fakeInputDir: File? = null
|
||||
|
||||
/** Told when the session ends, so a visible activity can close itself. */
|
||||
@Volatile
|
||||
var endListener: ((Int) -> Unit)? = null
|
||||
|
||||
fun notifyEnded(status: Int) {
|
||||
endListener?.invoke(status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.os.Process
|
||||
import java.io.File
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
internal class SessionSuspendController(
|
||||
private val sessionRoot: () -> Int,
|
||||
private val helperRoots: () -> List<Int>,
|
||||
private val suspendAudio: () -> Unit,
|
||||
private val resumeAudio: () -> Unit,
|
||||
) {
|
||||
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
|
||||
|
||||
private data class ProcessRecord(
|
||||
val pid: Int,
|
||||
val started: Long,
|
||||
val role: Role,
|
||||
)
|
||||
|
||||
private data class ProcessInfo(
|
||||
val pid: Int,
|
||||
val parent: Int,
|
||||
val started: Long,
|
||||
val state: Char,
|
||||
)
|
||||
|
||||
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
|
||||
@Volatile private var closing = false
|
||||
private var frozen = emptyList<ProcessRecord>()
|
||||
|
||||
fun freeze(completion: (Boolean) -> Unit) {
|
||||
submit {
|
||||
if (closing) {
|
||||
completion(false)
|
||||
return@submit
|
||||
}
|
||||
if (frozen.isNotEmpty()) {
|
||||
val fullyFrozen = frozen.any { it.role == Role.SESSION_ROOT } && frozen.all(::isStoppedOrGone)
|
||||
if (!fullyFrozen && restore(frozen)) frozen = emptyList()
|
||||
completion(fullyFrozen)
|
||||
return@submit
|
||||
}
|
||||
val records = LinkedHashMap<Pair<Int, Long>, ProcessRecord>()
|
||||
val root = sessionRoot()
|
||||
if (root <= 1) {
|
||||
completion(false)
|
||||
return@submit
|
||||
}
|
||||
runAudio(suspendAudio)
|
||||
val helpers = helperRoots().filter { it > 1 && it != root }.distinct()
|
||||
var stablePasses = 0
|
||||
var complete = false
|
||||
repeat(10) { pass ->
|
||||
if (closing) {
|
||||
restore(records.values.toList())
|
||||
runAudio(resumeAudio)
|
||||
completion(false)
|
||||
return@submit
|
||||
}
|
||||
val includeRoots = pass >= 2
|
||||
addSnapshot(records, root, helpers, includeRoots)
|
||||
stop(records.values.toList(), includeRoots)
|
||||
Thread.sleep(if (pass == 0) 70L else 35L)
|
||||
val rootCaptured = records.values.any { it.role == Role.SESSION_ROOT }
|
||||
if (rootCaptured && records.isNotEmpty() && records.values.all(::isStoppedOrGone)) {
|
||||
stablePasses++
|
||||
if (stablePasses >= 2) complete = true
|
||||
} else {
|
||||
stablePasses = 0
|
||||
}
|
||||
}
|
||||
if (complete) {
|
||||
frozen = records.values.toList()
|
||||
completion(true)
|
||||
} else {
|
||||
val restored = restore(records.values.toList())
|
||||
runAudio(resumeAudio)
|
||||
if (!restored) frozen = records.values.toList()
|
||||
completion(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun resume(completion: (Boolean) -> Unit) {
|
||||
submit {
|
||||
val records = frozen
|
||||
runAudio(resumeAudio)
|
||||
val resumed = restore(records)
|
||||
if (resumed) frozen = emptyList()
|
||||
completion(resumed)
|
||||
}
|
||||
}
|
||||
|
||||
fun closeAndResume(completion: () -> Unit) {
|
||||
closing = true
|
||||
submit {
|
||||
restore(frozen)
|
||||
frozen = emptyList()
|
||||
completion()
|
||||
executor.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
private fun submit(task: () -> Unit) {
|
||||
try {
|
||||
executor.execute {
|
||||
try {
|
||||
task()
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
} catch (_: RuntimeException) {
|
||||
task()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runAudio(action: () -> Unit) {
|
||||
try {
|
||||
action()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun addSnapshot(
|
||||
records: MutableMap<Pair<Int, Long>, ProcessRecord>,
|
||||
root: Int,
|
||||
helpers: List<Int>,
|
||||
includeRoots: Boolean,
|
||||
) {
|
||||
val processes = readProcesses()
|
||||
val byPid = processes.associateBy { it.pid }
|
||||
for (process in descendants(root, processes, byPid)) {
|
||||
records[process.pid to process.started] = ProcessRecord(process.pid, process.started, Role.SESSION_CHILD)
|
||||
}
|
||||
for (helper in helpers) {
|
||||
for (process in descendants(helper, processes, byPid)) {
|
||||
records[process.pid to process.started] = ProcessRecord(process.pid, process.started, Role.HELPER_CHILD)
|
||||
}
|
||||
}
|
||||
if (includeRoots) {
|
||||
byPid[root]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.SESSION_ROOT) }
|
||||
for (helper in helpers) {
|
||||
byPid[helper]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun descendants(root: Int, processes: List<ProcessInfo>, byPid: Map<Int, ProcessInfo>): List<ProcessInfo> {
|
||||
if (root !in byPid) return emptyList()
|
||||
val children = HashMap<Int, MutableList<ProcessInfo>>()
|
||||
for (process in processes) children.getOrPut(process.parent) { ArrayList() }.add(process)
|
||||
val excluded = Process.myPid()
|
||||
val found = ArrayList<ProcessInfo>()
|
||||
val seen = HashSet<Int>()
|
||||
val queue = ArrayDeque<Int>().apply { add(root) }
|
||||
while (queue.isNotEmpty()) {
|
||||
val parent = queue.removeFirst()
|
||||
for (child in children[parent].orEmpty()) {
|
||||
if (child.pid <= 1 || child.pid == excluded || !seen.add(child.pid)) continue
|
||||
found.add(child)
|
||||
queue.add(child.pid)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private fun readProcesses(): List<ProcessInfo> =
|
||||
File("/proc").listFiles().orEmpty().mapNotNull { entry ->
|
||||
val pid = entry.name.toIntOrNull() ?: return@mapNotNull null
|
||||
readProcess(pid)
|
||||
}
|
||||
|
||||
private fun readProcess(pid: Int): ProcessInfo? {
|
||||
val stat = try {
|
||||
File("/proc/$pid/stat").readText()
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
}
|
||||
val close = stat.lastIndexOf(')')
|
||||
if (close < 0 || close + 2 >= stat.length) return null
|
||||
val fields = stat.substring(close + 2).trim().split(Regex("\\s+"))
|
||||
if (fields.size < 20) return null
|
||||
return try {
|
||||
ProcessInfo(pid, fields[1].toInt(), fields[19].toLong(), fields[0].first())
|
||||
} catch (_: NumberFormatException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun stop(records: List<ProcessRecord>, includeRoots: Boolean) {
|
||||
val descendants = records.filter { it.role == Role.SESSION_CHILD || it.role == Role.HELPER_CHILD }
|
||||
val session = records.filter { it.role == Role.SESSION_ROOT }
|
||||
val helpers = records.filter { it.role == Role.HELPER_ROOT }
|
||||
for (record in descendants) send(record, SIGSTOP)
|
||||
if (includeRoots) {
|
||||
for (record in session) send(record, SIGSTOP)
|
||||
for (record in helpers) send(record, SIGSTOP)
|
||||
}
|
||||
}
|
||||
|
||||
private fun restore(records: List<ProcessRecord>): Boolean {
|
||||
val ordered = records.sortedBy {
|
||||
when (it.role) {
|
||||
Role.SESSION_ROOT -> 0
|
||||
Role.HELPER_ROOT -> 1
|
||||
Role.SESSION_CHILD -> 2
|
||||
Role.HELPER_CHILD -> 3
|
||||
}
|
||||
}
|
||||
for (record in ordered) send(record, SIGCONT)
|
||||
repeat(8) {
|
||||
Thread.sleep(25L)
|
||||
if (ordered.all(::isRunningOrGone)) return true
|
||||
}
|
||||
return ordered.all(::isRunningOrGone)
|
||||
}
|
||||
|
||||
private fun send(record: ProcessRecord, signal: Int) {
|
||||
val current = readProcess(record.pid) ?: return
|
||||
if (current.started != record.started) return
|
||||
try {
|
||||
Process.sendSignal(record.pid, signal)
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun isStoppedOrGone(record: ProcessRecord): Boolean {
|
||||
val current = readProcess(record.pid) ?: return true
|
||||
if (current.started != record.started) return true
|
||||
return current.state == 'T' || current.state == 't' || current.state == 'Z' || current.state == 'X'
|
||||
}
|
||||
|
||||
private fun isRunningOrGone(record: ProcessRecord): Boolean {
|
||||
val current = readProcess(record.pid) ?: return true
|
||||
if (current.started != record.started) return true
|
||||
return current.state != 'T' && current.state != 't'
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SIGSTOP = 19
|
||||
const val SIGCONT = 18
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import java.io.File
|
||||
|
||||
/** Immutable launch context for the optional PTY shell attached to the active Linux runtime. */
|
||||
object SessionTerminal {
|
||||
private data class Launch(
|
||||
val command: Array<String>,
|
||||
val hostEnvironment: Array<String>,
|
||||
val workingDirectory: String,
|
||||
val generation: Int,
|
||||
)
|
||||
|
||||
@Volatile private var launch: Launch? = null
|
||||
|
||||
fun prepare(
|
||||
command: List<String>,
|
||||
hostEnvironment: Array<String>,
|
||||
workingDirectory: File,
|
||||
generation: Int,
|
||||
) {
|
||||
launch = Launch(command.toTypedArray(), hostEnvironment.copyOf(), workingDirectory.path, generation)
|
||||
}
|
||||
|
||||
fun create(client: TerminalSessionClient): TerminalSession? {
|
||||
val current = launch ?: return null
|
||||
if (!SessionState.running) return null
|
||||
return TerminalSession(
|
||||
current.command.first(), current.workingDirectory, current.command,
|
||||
current.hostEnvironment, 3000, client,
|
||||
).also { it.mSessionName = "DroidDeck Linux shell" }
|
||||
}
|
||||
|
||||
fun clear(generation: Int? = null) {
|
||||
val current = launch ?: return
|
||||
if (generation == null || current.generation == generation) launch = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
|
||||
@Composable
|
||||
fun CursorOverlay(position: Offset, visible: Boolean, scale: Float) {
|
||||
if (!visible) return
|
||||
Canvas(modifier = Modifier.fillMaxSize()) {
|
||||
val s = 11f * scale
|
||||
val path = Path().apply {
|
||||
moveTo(position.x, position.y)
|
||||
lineTo(position.x, position.y + s * 1.45f)
|
||||
lineTo(position.x + s * 0.36f, position.y + s * 1.12f)
|
||||
lineTo(position.x + s * 0.62f, position.y + s * 1.62f)
|
||||
lineTo(position.x + s * 0.84f, position.y + s * 1.52f)
|
||||
lineTo(position.x + s * 0.58f, position.y + s * 1.02f)
|
||||
lineTo(position.x + s * 1.02f, position.y + s * 1.02f)
|
||||
close()
|
||||
}
|
||||
drawPath(path, Color.White)
|
||||
drawPath(path, Color(0xFF1B0730), style = Stroke(width = 1.5f * scale))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
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.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
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.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Refresh
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
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.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
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
|
||||
|
||||
/**
|
||||
* One driver list as a full page - the Runtime driver or the Display driver - opened from the
|
||||
* session's settings page. Installed drivers are picked by tapping the row and each carries a trash
|
||||
* can (the "Auto"/"Runtime default" row is a setting, not a driver, so it has none); what the last
|
||||
* check of the release repos found is offered below; the refresh button beside the title is the
|
||||
* only thing that goes online.
|
||||
*/
|
||||
@Composable
|
||||
fun DriverPage(
|
||||
title: String,
|
||||
hint: String,
|
||||
rows: List<DriverRow>,
|
||||
selected: String,
|
||||
downloads: List<DownloadRow>,
|
||||
status: String,
|
||||
checking: Boolean,
|
||||
importLabel: String,
|
||||
canRestore: Boolean,
|
||||
onSelect: (String) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
onRefresh: () -> Unit,
|
||||
onDownload: (String) -> Unit,
|
||||
onImport: () -> Unit,
|
||||
onRestore: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val host = rememberMenuHost()
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var confirm by remember { mutableStateOf<DriverRow?>(null) }
|
||||
// Back (the controller's B too) closes this page only, back to the session's settings.
|
||||
BackHandler(onBack = onBack)
|
||||
// D-pad: up from the first driver lands on refresh; the page opens with the driver in use focused.
|
||||
val refreshFocus = remember { FocusRequester() }
|
||||
val selectedFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { runCatching { selectedFocus.requestFocus() } }
|
||||
val refreshSrc = remember { MutableInteractionSource() }
|
||||
val refreshHot = refreshSrc.collectIsFocusedAsState().value || refreshSrc.collectIsHoveredAsState().value
|
||||
SettingsPage(
|
||||
host, title = title, onBack = onBack, lede = "$hint\n$status",
|
||||
action = {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(40.dp).clip(RoundedCornerShape(10.dp))
|
||||
.background(if (refreshHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.border(if (refreshHot) 2.dp else 1.dp, if (refreshHot) pal.signal else pal.line, RoundedCornerShape(10.dp))
|
||||
.focusRequester(refreshFocus)
|
||||
.hoverable(refreshSrc)
|
||||
.clickable(interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh),
|
||||
) {
|
||||
if (checking) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
|
||||
else Icon(Icons.Outlined.Refresh, contentDescription = "Check for new drivers", tint = colors.onBackground, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
},
|
||||
) {
|
||||
SettingsGroup("Installed") {
|
||||
val focusRow = rows.firstOrNull { it.id == selected } ?: rows.firstOrNull()
|
||||
rows.forEachIndexed { i, row ->
|
||||
InstalledRow(
|
||||
row, row.id == selected, onSelect = { onSelect(row.id) }, onDelete = { confirm = row },
|
||||
modifier = Modifier
|
||||
.then(if (row === focusRow) Modifier.focusRequester(selectedFocus) else Modifier)
|
||||
.then(if (i == 0) Modifier.focusProperties { up = refreshFocus } else Modifier),
|
||||
)
|
||||
}
|
||||
}
|
||||
SettingsGroup("Available to download") {
|
||||
if (downloads.isEmpty()) Text(
|
||||
"Nothing new from the last check. Tap the refresh button to look for newer releases.",
|
||||
fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 14.dp),
|
||||
) else for (d in downloads) {
|
||||
SettingsRow(d.label, d.detail) {
|
||||
val p = d.progress
|
||||
if (p == null) SecondaryButton("Download") { onDownload(d.key) }
|
||||
else Column(horizontalAlignment = Alignment.End, modifier = Modifier.width(120.dp)) {
|
||||
Text("$p%", fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
LinearProgressIndicator(progress = { p / 100f }, modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 14.dp)) {
|
||||
SecondaryButton(importLabel, onClick = onImport)
|
||||
if (canRestore) FocusText("Restore built-in drivers", pal.signal, onClick = onRestore)
|
||||
}
|
||||
}
|
||||
confirm?.let { row ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirm = null },
|
||||
title = { Text("Delete ${row.name}?") },
|
||||
text = {
|
||||
Text(
|
||||
if (row.tag == DriverRow.BUNDLED) "It is built into the app, so this removes its unpacked files and hides it. \"Restore built-in drivers\" brings it back, and Auto still uses it on a GPU that needs it."
|
||||
else "Its files are removed from the app." + if (row.id == selected) " It is the driver in use, so the default takes its place." else "",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
// Opens on Cancel, so a stray A press on a controller never deletes anything.
|
||||
confirmButton = { FocusText("Delete", colors.error) { confirm = null; onDelete(row.id) } },
|
||||
dismissButton = {
|
||||
val cancelFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { runCatching { cancelFocus.requestFocus() } }
|
||||
FocusText("Cancel", colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit, onDelete: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
// Two focus targets side by side - the driver itself, and its trash can - so a controller's
|
||||
// d-pad right reaches the trash can and left comes back. (Inside one clickable row the trash
|
||||
// can was a child of the focused area and "right" had nowhere to go.) The row's outline still
|
||||
// follows the driver part, so it looks the same.
|
||||
val mainFocus = remember { FocusRequester() }
|
||||
val delFocus = remember { FocusRequester() }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(3.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.14f) else if (selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent)
|
||||
.border(2.dp, if (hot) pal.signal else Color.Transparent, shape),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.weight(1f).then(modifier).focusRequester(mainFocus)
|
||||
.then(if (row.removable) Modifier.focusProperties { right = delFocus } else Modifier)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect)
|
||||
.padding(horizontal = 11.dp, vertical = 8.dp),
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(20.dp).border(2.dp, if (selected) pal.signal else colors.onSurfaceVariant, CircleShape),
|
||||
) { if (selected) Box(Modifier.size(10.dp).background(pal.signal, CircleShape)) }
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
row.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (row.tag.isNotEmpty()) Text(
|
||||
row.tag, fontSize = 9.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))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
if (row.detail.isNotEmpty()) Text(row.detail, fontSize = 11.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
|
||||
}
|
||||
}
|
||||
if (row.removable) {
|
||||
val delSrc = remember { MutableInteractionSource() }
|
||||
val delHot = delSrc.collectIsFocusedAsState().value || delSrc.collectIsHoveredAsState().value
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(end = 8.dp).size(40.dp).clip(RoundedCornerShape(10.dp))
|
||||
.background(if (delHot) colors.error.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.border(2.dp, if (delHot) colors.error else Color.Transparent, RoundedCornerShape(10.dp))
|
||||
.focusRequester(delFocus)
|
||||
.focusProperties { left = mainFocus }
|
||||
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete),
|
||||
) { Icon(Icons.Outlined.Delete, contentDescription = "Delete ${row.name}", tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
/** A text button that shows where controller focus is: an outline in its own colour. */
|
||||
@Composable
|
||||
private fun FocusText(text: String, color: Color, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
Text(
|
||||
text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = color,
|
||||
modifier = modifier.clip(shape)
|
||||
.background(if (hot) color.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.border(2.dp, if (hot) color else Color.Transparent, shape)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick)
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,929 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.Crossfade
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.CubicBezierEasing
|
||||
import androidx.compose.animation.core.FiniteAnimationSpec
|
||||
import androidx.compose.animation.core.MutableTransitionState
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.snap
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
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.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
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.alpha
|
||||
import androidx.compose.ui.draw.blur
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.zIndex
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class FrontEndState(
|
||||
val installed: String?,
|
||||
val ready: Boolean,
|
||||
val available: String?,
|
||||
val busy: Boolean,
|
||||
val stage: String,
|
||||
val percent: Int,
|
||||
val desktopInstalled: Boolean,
|
||||
val offlineAccount: String?,
|
||||
val offline: Boolean,
|
||||
val frameGenLabel: String,
|
||||
val romsDir: String?,
|
||||
val logsEnabled: Boolean,
|
||||
val steamGames: List<Library.SteamGame>,
|
||||
val emulators: List<Library.Emulator>,
|
||||
val running: String?,
|
||||
val frameGenEngine: String = FrameGen.ENGINE_OFF,
|
||||
val frameGenMultiplier: Int = 2,
|
||||
val lsfgReady: Boolean = false,
|
||||
val pageKey: String? = null,
|
||||
val theme: String = Themes.PAPER,
|
||||
val isHomeApp: Boolean = false,
|
||||
val defaultHomeLabel: String? = null,
|
||||
val androidApps: List<com.droiddeck.launcher.HomeApp.LaunchableApp> = emptyList(),
|
||||
val packages: List<PackageRow>? = null,
|
||||
val packageCatalogLoading: Boolean = false,
|
||||
val packageBusyId: String? = null,
|
||||
val packageStage: String? = null,
|
||||
val packagePercent: Int = -1,
|
||||
val sessionRunning: Boolean = false,
|
||||
)
|
||||
|
||||
class FrontEndActions(
|
||||
val onPlay: () -> Unit,
|
||||
val onPlayDesktopUi: () -> Unit,
|
||||
val onSteamGame: (Library.SteamGame) -> Unit,
|
||||
val onDesktop: () -> Unit,
|
||||
val onEmulator: (Library.Emulator) -> Unit,
|
||||
val onRom: (Library.Rom) -> Unit,
|
||||
val onResume: () -> Unit,
|
||||
val onSteamSettings: () -> Unit,
|
||||
val onDesktopSettings: () -> Unit,
|
||||
val onInstallPackage: (String) -> Unit,
|
||||
val onRemovePackage: (String) -> Unit,
|
||||
val onRuntime: () -> Unit,
|
||||
val onFrameGenPick: (engine: String, multiplier: Int) -> Unit,
|
||||
val onProtons: () -> Unit,
|
||||
val onPerformance: () -> Unit,
|
||||
val onRoms: () -> Unit,
|
||||
val onFiles: () -> Unit,
|
||||
val onLogs: () -> Unit,
|
||||
val onShareLogs: () -> Unit = {},
|
||||
val onOffline: () -> Unit,
|
||||
val onCredits: () -> Unit,
|
||||
val onPageBack: () -> Unit = {},
|
||||
val onTheme: (String) -> Unit = {},
|
||||
val onHomeApp: () -> Unit = {},
|
||||
val onAndroidApp: (com.droiddeck.launcher.HomeApp.LaunchableApp) -> Unit = {},
|
||||
)
|
||||
|
||||
|
||||
internal object Motion {
|
||||
var scale = 1f
|
||||
val Ease = CubicBezierEasing(0.2f, 0.8f, 0.2f, 1f)
|
||||
fun ms(base: Int) = (base * scale).roundToInt()
|
||||
fun <T> tw(base: Int, delay: Int = 0): FiniteAnimationSpec<T> = if (scale == 0f) snap() else tween(ms(base), ms(delay), Ease)
|
||||
fun <T> sp(damping: Float = 0.7f, stiffness: Float = Spring.StiffnessMediumLow): FiniteAnimationSpec<T> =
|
||||
if (scale == 0f) snap() else spring(damping, stiffness)
|
||||
}
|
||||
|
||||
private val Shape10 = RoundedCornerShape(10.dp)
|
||||
private val Shape12 = RoundedCornerShape(12.dp)
|
||||
|
||||
private fun hueOf(name: String) = (name.hashCode().toUInt() % 360u).toFloat()
|
||||
private fun tint(h: Float, s: Float = 0.7f, v: Float = 0.58f) = Color.hsv(h, s, v)
|
||||
private fun artBrush(h: Float) = Brush.linearGradient(listOf(tint(h), tint((h + 32f) % 360f, 0.65f, 0.30f), tint((h + 64f) % 360f, 0.6f, 0.14f)))
|
||||
|
||||
@Composable
|
||||
internal fun Rise(i: Int, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
|
||||
val state = remember { MutableTransitionState(false) }.apply { targetState = true }
|
||||
AnimatedVisibility(
|
||||
visibleState = state, modifier = modifier,
|
||||
enter = fadeIn(Motion.tw(450, i * 60)) + slideInVertically(Motion.tw(450, i * 60)) { it / 3 },
|
||||
exit = fadeOut(Motion.tw(120)),
|
||||
label = "rise",
|
||||
) { content() }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Modifier.staggerIn(i: Int): Modifier {
|
||||
val t = remember { Animatable(0f) }
|
||||
LaunchedEffect(Unit) { t.animateTo(1f, Motion.tw(360, i * 30)) }
|
||||
return graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 10.dp.toPx() }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Modifier.shine(trigger: Boolean, strength: Float = 0.22f): Modifier {
|
||||
val x = remember { Animatable(-1f) }
|
||||
LaunchedEffect(trigger) { if (trigger) { x.snapTo(-1f); x.animateTo(1f, Motion.tw(800)) } }
|
||||
return drawWithContent {
|
||||
drawContent()
|
||||
val p = x.value
|
||||
if (p > -1f && p < 1f) {
|
||||
val w = size.width
|
||||
val c = w * 0.5f + p * w * 0.9f
|
||||
drawRect(
|
||||
Brush.linearGradient(
|
||||
listOf(Color.Transparent, Color.White.copy(alpha = strength), Color.Transparent),
|
||||
start = Offset(c - w * 0.35f, 0f), end = Offset(c + w * 0.35f, size.height),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
|
||||
var selected by rememberSaveable { mutableStateOf("steam") }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val ctx = LocalContext.current
|
||||
BackHandler(enabled = s.pageKey != null && page != null) { a.onPageBack() }
|
||||
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
|
||||
remember { Motion.scale = Settings.Global.getFloat(ctx.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f); true }
|
||||
|
||||
BoxWithConstraints(modifier = Modifier.fillMaxSize().background(colors.background).systemBarsPadding()) {
|
||||
val wide = maxWidth >= 640.dp
|
||||
val railSelection = when {
|
||||
s.pageKey == "performance" || s.pageKey == "protons" -> "setup"
|
||||
s.pageKey?.startsWith("settings:steam") == true -> "steam"
|
||||
s.pageKey?.startsWith("settings:") == true -> "desktop"
|
||||
selected.startsWith("app:") -> "steam"
|
||||
selected.startsWith("emu:") || selected.startsWith("rom:") -> "desktop"
|
||||
else -> s.pageKey ?: selected
|
||||
}
|
||||
val rail: @Composable () -> Unit = {
|
||||
Rail(
|
||||
s, railSelection,
|
||||
onSelect = { key ->
|
||||
if (s.pageKey != null) a.onPageBack()
|
||||
selected = key
|
||||
},
|
||||
a,
|
||||
modifier = if (wide) Modifier.width(236.dp).fillMaxHeight() else Modifier.fillMaxWidth().height(maxHeight * 0.42f),
|
||||
)
|
||||
}
|
||||
val content: @Composable (Modifier) -> Unit = { m -> Pane(s, selected, a, page, m) { selected = it } }
|
||||
if (wide) Row(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxHeight()) }
|
||||
else Column(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxWidth()) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun Rail(
|
||||
s: FrontEndState, selected: String,
|
||||
onSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(
|
||||
modifier = modifier.background(colors.surface).verticalScroll(rememberScrollState()).padding(horizontal = 10.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 8.dp, bottom = 10.dp)) {
|
||||
Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(30.dp))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column {
|
||||
Text("DroidDeck", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
val status = when {
|
||||
s.busy -> if (s.percent >= 0) "${s.stage} ${s.percent}%" else s.stage
|
||||
!s.ready -> "runtime not installed"
|
||||
s.available != null && s.available != s.installed -> "runtime update available"
|
||||
else -> null
|
||||
}
|
||||
if (status != null) Text(status, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp))
|
||||
}
|
||||
|
||||
var lastRunning by remember { mutableStateOf("") }
|
||||
if (s.running != null) lastRunning = s.running
|
||||
AnimatedVisibility(
|
||||
s.running != null,
|
||||
enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)) + slideInVertically(Motion.sp(0.6f)) { -it / 2 },
|
||||
exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)),
|
||||
) { RunningTile(lastRunning, a.onResume) }
|
||||
|
||||
val pal = LocalPalette.current
|
||||
var navOrigin by remember { mutableStateOf(Offset.Zero) }
|
||||
val positions = remember { mutableStateMapOf<String, Rect>() }
|
||||
Box(modifier = Modifier.fillMaxWidth().onGloballyPositioned { val o = it.positionInRoot(); if (o != navOrigin) navOrigin = o }) {
|
||||
val target = positions[selected]?.translate(-navOrigin)
|
||||
val y by animateFloatAsState(target?.top ?: 0f, Motion.sp(0.72f, Spring.StiffnessLow), label = "indY")
|
||||
val x by animateFloatAsState(target?.left ?: 0f, Motion.sp(0.9f), label = "indX")
|
||||
val h by animateFloatAsState(target?.height ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indH")
|
||||
val w by animateFloatAsState(target?.width ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indW")
|
||||
val alpha by animateFloatAsState(if (target != null) 1f else 0f, Motion.tw(250), label = "indA")
|
||||
val density = LocalDensity.current
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.offset { IntOffset(x.roundToInt(), y.roundToInt()) }
|
||||
.width(with(density) { w.toDp() }).height(with(density) { h.toDp() })
|
||||
.alpha(alpha)
|
||||
.graphicsLayer { shadowElevation = 6.dp.toPx(); shape = Shape10; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
|
||||
.clip(Shape10)
|
||||
.background(Brush.linearGradient(listOf(colors.primary, pal.primary2))),
|
||||
)
|
||||
val register: (String, LayoutCoordinates) -> Unit = { key, c ->
|
||||
val o = c.positionInRoot(); val r = Rect(o.x, o.y, o.x + c.size.width, o.y + c.size.height)
|
||||
if (positions[key] != r) positions[key] = r
|
||||
}
|
||||
val unregister: (String) -> Unit = { positions.remove(it) }
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
if (s.isHomeApp) {
|
||||
NavItem("Android apps", "android-apps", selected == "android-apps", count = s.androidApps.size,
|
||||
register = register, unregister = unregister) { onSelect("android-apps") }
|
||||
}
|
||||
NavItem("Steam", "steam", selected == "steam", count = s.steamGames.size, register = register, unregister = unregister) { onSelect("steam") }
|
||||
NavItem("Desktop", "desktop", selected == "desktop", count = s.emulators.count { it.installed }, register = register, unregister = unregister) { onSelect("desktop") }
|
||||
NavItem("Setup", "setup", selected == "setup", register = register, unregister = unregister) { onSelect("setup") }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
"credits", fontSize = 11.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(Shape10).clickable(onClick = a.onCredits).padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RunningTile(name: String, onResume: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val shift by animateFloatAsState(if (hot) 3f else 0f, Motion.sp(0.6f), label = "runShift")
|
||||
val pulse = rememberInfiniteTransition(label = "pulse")
|
||||
val ring by pulse.animateFloat(0.4f, 1.6f, infiniteRepeatable(tween(1600, easing = Motion.Ease), RepeatMode.Restart), label = "ring")
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)
|
||||
.graphicsLayer { translationX = shift.dp.toPx() }
|
||||
.clip(Shape12)
|
||||
.background(Brush.linearGradient(listOf(pal.signal.copy(alpha = 0.22f), pal.signal.copy(alpha = 0.06f))))
|
||||
.border(1.dp, pal.signal.copy(alpha = if (hot) 0.8f else 0.35f), Shape12)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onResume)
|
||||
.padding(horizontal = 10.dp, vertical = 9.dp),
|
||||
) {
|
||||
Box(modifier = Modifier.size(14.dp), contentAlignment = Alignment.Center) {
|
||||
Box(modifier = Modifier.size(14.dp).graphicsLayer { scaleX = ring; scaleY = ring; alpha = (1.6f - ring) / 1.2f }.border(1.5.dp, pal.good, CircleShape))
|
||||
Box(modifier = Modifier.size(7.dp).clip(CircleShape).background(pal.good))
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(name, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text("Resume", fontSize = 11.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NavItem(
|
||||
label: String, key: String, current: Boolean, small: Boolean = false, tiny: Boolean = false, muted: Boolean = false,
|
||||
caret: Boolean? = null, count: Int? = null, value: String? = null, i: Int = 0,
|
||||
register: ((String, LayoutCoordinates) -> Unit)? = null, unregister: ((String) -> Unit)? = null, onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val focused by src.collectIsFocusedAsState()
|
||||
val hovered by src.collectIsHoveredAsState()
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val fg by animateColorAsState(if (current) colors.onPrimary else if (muted) colors.onSurfaceVariant else colors.onBackground, Motion.tw(280), label = "navFg")
|
||||
val sub by animateColorAsState(if (current) colors.onPrimary else colors.onSurfaceVariant, Motion.tw(280), label = "navSub")
|
||||
val ring by animateColorAsState(if (focused) LocalPalette.current.signal else Color.Transparent, Motion.tw(180), label = "navRing")
|
||||
val scale by animateFloatAsState(if (pressed) 0.98f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "navScale")
|
||||
val rot by animateFloatAsState(if (caret == true) 90f else 0f, Motion.sp(0.6f), label = "caret")
|
||||
if (key != "x") DisposableEffect(key) { onDispose { unregister?.invoke(key) } }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.then(if (register != null && key != "x") Modifier.onGloballyPositioned { register(key, it) } else Modifier)
|
||||
.then(if (small && i >= 0 && register != null) Modifier.staggerIn(i) else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(Shape10)
|
||||
.background(if (hovered && !current) Color.White.copy(alpha = 0.04f) else if (current && hovered) Color.White.copy(alpha = 0.08f) else Color.Transparent)
|
||||
.border(1.5.dp, ring, Shape10)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = if (small) 7.dp else 9.dp),
|
||||
) {
|
||||
if (caret != null) {
|
||||
Text("›", fontSize = 16.sp, color = sub, modifier = Modifier.width(14.dp).rotate(rot))
|
||||
}
|
||||
Text(
|
||||
label, fontSize = if (tiny) 13.sp else if (small) 14.sp else 15.sp,
|
||||
fontWeight = if (tiny) FontWeight.Normal else if (small) FontWeight.Medium else FontWeight.SemiBold,
|
||||
color = fg, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (value != null) Text(value, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (count != null) Text(
|
||||
count.toString(), fontSize = 11.sp, color = sub,
|
||||
modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(if (current) colors.onPrimary.copy(alpha = 0.16f) else colors.background).padding(horizontal = 7.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun Pane(s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier, onSelect: (String) -> Unit) {
|
||||
Box(modifier = modifier) {
|
||||
val wash: Pair<File?, Float> = when {
|
||||
s.pageKey != null && page != null -> null to 250f
|
||||
selected == "steam" -> null to 268f
|
||||
selected == "desktop" -> null to 200f
|
||||
selected.startsWith("app:") -> s.steamGames.firstOrNull { "app:${it.appId}" == selected }.let { it?.art to hueOf(it?.name ?: "") }
|
||||
selected.startsWith("emu:") -> null to hueOf(selected)
|
||||
selected.startsWith("rom:") -> romFor(s, selected).let { it?.second?.art to hueOf(it?.second?.name ?: "") }
|
||||
selected == "android-apps" -> null to hueOf("android-apps")
|
||||
else -> null to 268f
|
||||
}
|
||||
Backdrop(wash)
|
||||
AnimatedContent(
|
||||
targetState = if (page != null && s.pageKey != null) s.pageKey else selected,
|
||||
transitionSpec = {
|
||||
(fadeIn(Motion.tw(300, 80)) + slideInVertically(Motion.tw(420, 80)) { it / 24 })
|
||||
.togetherWith(fadeOut(Motion.tw(170)) + slideOutVertically(Motion.tw(170)) { -it / 40 })
|
||||
.apply { targetContentZIndex = 1f }
|
||||
},
|
||||
label = "pane",
|
||||
) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Backdrop(wash: Pair<File?, Float>) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Crossfade(targetState = wash, animationSpec = Motion.tw(700), label = "backdrop") { (art, hue) ->
|
||||
val canBlur = Build.VERSION.SDK_INT >= 31
|
||||
Box(modifier = Modifier.fillMaxSize().alpha(if (canBlur) 0.28f else 0.18f).then(if (canBlur) Modifier.blur(70.dp) else Modifier)) {
|
||||
if (art != null && canBlur) {
|
||||
AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.5f; scaleY = 1.5f })
|
||||
} else {
|
||||
Box(modifier = Modifier.fillMaxSize().background(Brush.radialGradient(listOf(tint(hue, 0.8f, 0.55f), Color.Transparent), center = Offset(0.3f, 0.3f), radius = 900f)))
|
||||
Box(modifier = Modifier.fillMaxSize().background(Brush.radialGradient(listOf(tint((hue + 60f) % 360f, 0.7f, 0.45f), Color.Transparent), center = Offset(1600f, 1400f), radius = 900f)))
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color.Transparent, colors.background.copy(alpha = 0.35f)))))
|
||||
}
|
||||
|
||||
private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, Library.Rom>? {
|
||||
val parts = selected.split(":")
|
||||
val e = s.emulators.firstOrNull { it.id == parts.getOrNull(1) } ?: return null
|
||||
val g = e.games.getOrNull(parts.getOrNull(2)?.toIntOrNull() ?: -1) ?: return null
|
||||
return e to g
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier, onSelect: (String) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(modifier = modifier.padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
when {
|
||||
selected == "android-apps" && s.isHomeApp -> {
|
||||
Rise(0) { Eyebrow("Android apps") }
|
||||
Rise(1) { Title("Installed apps") }
|
||||
Rise(2) { SectionTitle("Apps", s.androidApps.size.toString()) }
|
||||
if (s.androidApps.isEmpty()) Rise(3) { Note("No launchable Android apps found.") }
|
||||
else Rise(3, Modifier.weight(1f).fillMaxWidth()) {
|
||||
ArtGrid(s.androidApps.map { app ->
|
||||
Tile(
|
||||
app.label,
|
||||
null,
|
||||
null,
|
||||
"android:${app.packageName}",
|
||||
onClick = { a.onAndroidApp(app) },
|
||||
iconBitmap = app.icon,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
selected == "steam" -> {
|
||||
Rise(0) { Eyebrow("Steam") }
|
||||
Rise(3) {
|
||||
Actions {
|
||||
// Enabled without a runtime: the session's loading screen installs it first.
|
||||
PrimaryButton("Play", enabled = !s.busy, onClick = a.onPlay)
|
||||
SecondaryButton("Steam Desktop UI", enabled = !s.busy, onClick = a.onPlayDesktopUi)
|
||||
Cog(a.onSteamSettings)
|
||||
}
|
||||
}
|
||||
Rise(4) { SectionTitle("Installed", "${s.steamGames.size} game${if (s.steamGames.size == 1) "" else "s"}") }
|
||||
if (s.steamGames.isEmpty()) Rise(5) { Note("No games installed.") }
|
||||
else Rise(5, Modifier.weight(1f).fillMaxWidth()) { ArtGrid(s.steamGames.map { g -> Tile(g.name, g.library, g.art, "steam:${g.appId}", null) { onSelect("app:${g.appId}") } }) }
|
||||
}
|
||||
selected.startsWith("app:") -> {
|
||||
val g = s.steamGames.firstOrNull { "app:${it.appId}" == selected }
|
||||
if (g == null) Note("That game is no longer installed.") else {
|
||||
Rise(0) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(
|
||||
"‹ Steam", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable { onSelect("steam") }.padding(horizontal = 6.dp, vertical = 4.dp),
|
||||
)
|
||||
Eyebrow(g.library)
|
||||
}
|
||||
}
|
||||
Rise(1) { Title(g.name) }
|
||||
Rise(2) {
|
||||
Row {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Actions {
|
||||
PrimaryButton("Launch", enabled = s.ready && !s.busy) { a.onSteamGame(g) }
|
||||
Cog(a.onSteamSettings)
|
||||
Chip(if (s.ready) "● ready" else "runtime missing", ok = s.ready)
|
||||
}
|
||||
}
|
||||
Poster(g.art, g.name, Modifier.width(120.dp))
|
||||
}
|
||||
}
|
||||
val others = s.steamGames.filter { it !== g }
|
||||
if (others.isNotEmpty()) {
|
||||
Rise(3) { SectionTitle("More from the library", null) }
|
||||
Rise(4, Modifier.weight(1f).fillMaxWidth()) { ArtGrid(others.map { x -> Tile(x.name, x.library, x.art, "steam:${x.appId}", null) { onSelect("app:${x.appId}") } }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
selected == "desktop" -> {
|
||||
Rise(0) { Eyebrow("Desktop") }
|
||||
Rise(3) {
|
||||
Actions {
|
||||
// Enabled without a runtime or the desktop: the session's loading screen installs them first.
|
||||
PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, onClick = a.onDesktop)
|
||||
Cog(a.onDesktopSettings)
|
||||
}
|
||||
}
|
||||
Rise(4) { SectionTitle("Emulators", "${s.emulators.count { it.installed }} installed · ${s.emulators.count { !it.installed }} available") }
|
||||
Rise(5, Modifier.weight(1f).fillMaxWidth()) {
|
||||
ArtGrid(s.emulators.map { e -> Tile(e.name, if (e.installed) (if (e.id == "retroarch") null else "${e.games.size} game${if (e.games.size == 1) "" else "s"}") else "Select to install", null, "emu:${e.id}", e.iconRes, dim = !e.installed) { onSelect("emu:${e.id}") } })
|
||||
}
|
||||
}
|
||||
selected == "setup" -> SetupPanel(s, a)
|
||||
selected.startsWith("emu:") -> {
|
||||
val e = s.emulators.firstOrNull { "emu:${it.id}" == selected }
|
||||
if (e == null) Note("Not installed.") else {
|
||||
val pkgId = Library.packageId(e.id)
|
||||
val pkg = pkgId?.let { id -> s.packages?.firstOrNull { it.id == id } }
|
||||
Rise(0) {
|
||||
Text(
|
||||
"‹ Desktop", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable { onSelect("desktop") }.padding(horizontal = 6.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
Rise(1) { Title(e.name) }
|
||||
if (e.installed) {
|
||||
Rise(3) {
|
||||
Actions {
|
||||
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
|
||||
PrimaryButton("Open ${e.name}", enabled = s.ready && !s.busy) { a.onEmulator(e) }
|
||||
SecondaryButton("ROMs folder", onClick = a.onRoms)
|
||||
if (pkg != null) SecondaryButton(
|
||||
if (pkg.kind == "appimage") "Remove" else "Forget",
|
||||
enabled = s.packageBusyId == null && !s.sessionRunning,
|
||||
) { a.onRemovePackage(pkg.id) }
|
||||
}
|
||||
}
|
||||
Rise(4) { SectionTitle("Games", e.games.size.toString()) }
|
||||
if (e.games.isEmpty()) Rise(5) {
|
||||
Note(
|
||||
if (s.romsDir == null) "Choose a ROMs folder."
|
||||
else if (e.id == "retroarch") "Browse to /root/ROMs in RetroArch."
|
||||
else "Add ${e.system} games to ROMs/${e.system.substringBefore(' ')}.",
|
||||
)
|
||||
}
|
||||
else Rise(5, Modifier.weight(1f).fillMaxWidth()) {
|
||||
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 {
|
||||
if (pkg != null) Rise(2) {
|
||||
Actions {
|
||||
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
|
||||
PrimaryButton(
|
||||
if (s.packageBusyId == pkg.id) "Installing…" else "Install ${e.name}",
|
||||
enabled = s.packageBusyId == null && s.ready && !s.packageCatalogLoading && !s.sessionRunning,
|
||||
) { a.onInstallPackage(pkg.id) }
|
||||
if (s.sessionRunning) Chip("Stop session to install", ok = false)
|
||||
else if (!s.ready) Chip("Runtime required", ok = false)
|
||||
}
|
||||
}
|
||||
Rise(3) {
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 8.dp)) {
|
||||
Note(when {
|
||||
s.packageCatalogLoading -> "Loading install details…"
|
||||
pkg == null -> "Install details are unavailable right now. Try again when the package catalog is reachable."
|
||||
!s.ready -> "Install the Linux runtime from Setup before installing desktop apps."
|
||||
s.sessionRunning -> "Stop the active session before installing desktop apps."
|
||||
pkg.notes.isNotBlank() -> pkg.notes
|
||||
else -> "Install ${e.name} into the Linux desktop runtime."
|
||||
})
|
||||
}
|
||||
}
|
||||
if (s.packageBusyId == pkg?.id) Rise(4) {
|
||||
val stage = s.packageStage
|
||||
Text(
|
||||
if (stage != null && s.packagePercent >= 0) "$stage · ${s.packagePercent}%" else stage ?: "Starting…",
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp),
|
||||
)
|
||||
if (s.packagePercent >= 0) LinearProgressIndicator(progress = { s.packagePercent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
|
||||
}
|
||||
if (pkg?.kind == "tar") Rise(5) { Note("Forgetting this package hides it from Desktop; its files remain in the Linux runtime.") }
|
||||
}
|
||||
}
|
||||
}
|
||||
selected.startsWith("rom:") -> {
|
||||
val pair = romFor(s, selected)
|
||||
if (pair == null) Note("That game is gone from the ROMs folder.") else {
|
||||
val (e, g) = pair
|
||||
Rise(0) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(
|
||||
"‹ ${e.name}", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable { onSelect("emu:${e.id}") }.padding(horizontal = 6.dp, vertical = 4.dp),
|
||||
)
|
||||
Eyebrow("Desktop · ${e.system}")
|
||||
}
|
||||
}
|
||||
Rise(1) { Title(g.name) }
|
||||
Rise(2) {
|
||||
Row {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(g.guestPath, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.clip(RoundedCornerShape(8.dp)).background(colors.surface).padding(horizontal = 10.dp, vertical = 6.dp))
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Actions {
|
||||
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
|
||||
PrimaryButton("Launch in ${e.name}", enabled = s.ready && !s.busy) { a.onRom(g) }
|
||||
Chip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false)
|
||||
}
|
||||
}
|
||||
if (g.art != null) Poster(g.art, g.name, Modifier.width(120.dp))
|
||||
}
|
||||
}
|
||||
val others = e.games.filter { it !== g }
|
||||
if (others.isNotEmpty()) {
|
||||
Rise(3) { SectionTitle("Also in ${e.name}", null) }
|
||||
Rise(4, Modifier.weight(1f).fillMaxWidth()) {
|
||||
ArtGrid(others.map { x ->
|
||||
val index = e.games.indexOf(x)
|
||||
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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> Note("Select an item.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
|
||||
val host = rememberMenuHost()
|
||||
val runtime = when {
|
||||
s.busy -> "Working…"
|
||||
!s.ready -> "Install"
|
||||
s.available != null && s.available != s.installed -> "Update"
|
||||
else -> "Manage"
|
||||
}
|
||||
Rise(0, Modifier.fillMaxSize()) {
|
||||
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
|
||||
Rise(0) { Eyebrow("Setup") }
|
||||
Rise(1) { Title("Setup") }
|
||||
SettingsGroup("Launcher tools") {
|
||||
ActionRow("Files", "Browse and manage files", "Open", a.onFiles)
|
||||
ActionRow("Compatibility tools", "Install ARM64 Proton builds", "Manage", a.onProtons)
|
||||
ActionRow("Performance", "CPU core assignment", "Configure", a.onPerformance)
|
||||
ActionRow("ROMs folder", s.romsDir ?: "Choose where emulator games are stored", "Choose", a.onRoms)
|
||||
}
|
||||
SettingsGroup("Session") {
|
||||
SettingsRow("Frame generation", "Select the frame generation mode") {
|
||||
Box {
|
||||
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
|
||||
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") {
|
||||
val need = if (s.lsfgReady) null else "Install Lossless Scaling in Steam"
|
||||
MenuItem("Off", checked = s.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
||||
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_WINFG && s.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
|
||||
for (m in 2..4) MenuItem("LSFG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_LSFG && s.frameGenMultiplier == m, enabled = s.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsRow("Session logs", "${if (s.logsEnabled) "Enabled" else "Disabled"} · logs are saved after each session") {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton(if (s.logsEnabled) "Turn off" else "Turn on") { a.onLogs() }
|
||||
SecondaryButton("Share latest") { a.onShareLogs() }
|
||||
}
|
||||
}
|
||||
SettingsRow("Offline mode", s.offlineAccount?.let { if (s.offline) "Enabled for $it" else "Signed in as $it" } ?: "Sign in to Steam first") {
|
||||
SecondaryButton(if (s.offline) "Turn off" else "Turn on", enabled = s.offlineAccount != null) { a.onOffline() }
|
||||
}
|
||||
}
|
||||
SettingsGroup("Application") {
|
||||
ActionRow("Linux runtime", "${s.installed ?: "Not installed"}${if (s.available != null && s.available != s.installed) " · update available" else ""}", runtime, a.onRuntime)
|
||||
SettingsRow("Theme", "Choose the launcher appearance") {
|
||||
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 = "Theme") {
|
||||
for (t in Themes.all) MenuItem(t.label, checked = s.theme == t.id) { a.onTheme(t.id); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
ActionRow("Default Home app", s.defaultHomeLabel ?: "Choose a Home app", "Choose", a.onHomeApp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Tile(
|
||||
val title: String, val sub: String?, val art: File?, val key: String,
|
||||
val iconRes: Int? = null, val dim: Boolean = false, val iconBitmap: Bitmap? = null,
|
||||
val onClick: () -> Unit,
|
||||
)
|
||||
|
||||
|
||||
@Composable
|
||||
internal fun Eyebrow(t: String) {
|
||||
val pal = LocalPalette.current
|
||||
val rule = remember { Animatable(0f) }
|
||||
LaunchedEffect(Unit) { rule.animateTo(1f, Motion.tw(600, 120)) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Box(modifier = Modifier.width(18.dp).height(1.5.dp).graphicsLayer { scaleX = rule.value; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0f, 0.5f) }.background(pal.signal))
|
||||
Text(t.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = pal.signal)
|
||||
}
|
||||
}
|
||||
@Composable internal fun Title(t: String) = Text(t, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(top = 4.dp, bottom = 4.dp))
|
||||
@Composable internal fun Lede(t: String) = Text(t, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 12.dp))
|
||||
@Composable
|
||||
private fun SectionTitle(t: String, detail: String?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 8.dp)) {
|
||||
Text(t.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant)
|
||||
if (detail != null) Text(detail, fontSize = 11.sp, color = colors.onBackground)
|
||||
Box(modifier = Modifier.weight(1f).height(1.dp).background(LocalPalette.current.line))
|
||||
}
|
||||
}
|
||||
@Composable private fun Note(t: String) = Text(t, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.fillMaxWidth().clip(Shape12).background(MaterialTheme.colorScheme.surface).border(1.dp, LocalPalette.current.line2, Shape12).padding(12.dp))
|
||||
@Composable private fun Actions(content: @Composable () -> Unit) = Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { content() }
|
||||
|
||||
@Composable
|
||||
private fun Chip(t: String, ok: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Text(
|
||||
t, fontSize = 11.sp, color = if (ok) pal.good else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, RoundedCornerShape(99.dp)).padding(horizontal = 9.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
|
||||
@Composable
|
||||
private fun PrimaryButton(text: String, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src) && enabled
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "btnScale")
|
||||
val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift")
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
|
||||
.clip(Shape12)
|
||||
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
|
||||
.shine(hot, 0.45f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 18.dp, vertical = 11.dp),
|
||||
) {
|
||||
Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = if (enabled) colors.onPrimary else colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SecondaryButton(text: String, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src) && enabled
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "secScale")
|
||||
val pal = LocalPalette.current
|
||||
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "secEdge")
|
||||
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(
|
||||
modifier = Modifier.graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12)
|
||||
.alpha(if (enabled) 1f else 0.5f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 11.dp),
|
||||
) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Cog(onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val rot by animateFloatAsState(if (hot) 90f else 0f, Motion.sp(0.55f), label = "cog")
|
||||
val pal = LocalPalette.current
|
||||
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "cogEdge")
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(42.dp).clip(Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, Shape12)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick),
|
||||
) { Icon(Icons.Filled.Settings, "Settings", tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(18.dp).rotate(rot)) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Poster(art: File?, name: String, modifier: Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val t = remember { Animatable(0f) }
|
||||
LaunchedEffect(Unit) { t.animateTo(1f, Motion.sp(0.6f, Spring.StiffnessLow)) }
|
||||
Box(
|
||||
modifier = modifier.padding(start = 16.dp).aspectRatio(2f / 3f)
|
||||
.graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 16.dp.toPx(); rotationZ = (1f - t.value) * 2f; scaleX = 0.94f + 0.06f * t.value; scaleY = scaleX; shadowElevation = 22.dp.toPx(); shape = Shape12; clip = false }
|
||||
.clip(Shape12).background(artBrush(hueOf(name))),
|
||||
) {
|
||||
if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
else Text(name, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.align(Alignment.BottomStart).padding(8.dp), maxLines = 3, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun ArtGrid(tiles: List<Tile>, wide: Boolean = false) {
|
||||
val square = tiles.isNotEmpty() && tiles.all { it.art == null && (it.iconRes != null || it.iconBitmap != null) }
|
||||
// Thumbnails to recognise a game by, not posters; icon tiles are squares.
|
||||
val minSize = if (square) 64.dp else if (wide) 92.dp else 70.dp
|
||||
val gap = 8.dp
|
||||
// Laid out whole, not lazily: the pad's focus search only finds tiles that exist, and a lazy
|
||||
// grid composes only the rows on screen, so a press towards the next row bounced back among
|
||||
// the visible tiles. A few hundred tiles lay out fine; the scroll follows the focused one.
|
||||
BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
|
||||
val avail = maxWidth - 8.dp
|
||||
val cols = ((avail + gap) / (minSize + gap)).toInt().coerceAtLeast(1)
|
||||
val tileWidth = (avail - gap * (cols - 1)) / cols
|
||||
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(top = 6.dp, bottom = 14.dp, start = 4.dp, end = 4.dp)) {
|
||||
for (row in tiles.chunked(cols)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(gap), modifier = Modifier.fillMaxWidth().padding(bottom = gap)) {
|
||||
for (t in row) key(t.key) {
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.97f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "tileScale")
|
||||
val lift by animateFloatAsState(if (hot) -5f else 0f, Motion.sp(0.6f), label = "tileLift")
|
||||
val elev by animateFloatAsState(if (hot) 18f else 2f, Motion.tw(300), label = "tileElev")
|
||||
val pal = LocalPalette.current
|
||||
val ring by animateColorAsState(if (hot) pal.signal else Color.Transparent, Motion.tw(220), label = "tileRing")
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale; translationY = lift.dp.toPx(); shadowElevation = elev.dp.toPx(); shape = Shape12; clip = false; ambientShadowColor = if (hot) pal.signal else Color.Black; spotShadowColor = if (hot) pal.signal else Color.Black; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, 0.9f) }
|
||||
.clip(Shape12)
|
||||
.background(colors.surface)
|
||||
.border(1.5.dp, ring, Shape12)
|
||||
.alpha(if (t.dim && !hot) 0.55f else 1f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = t.onClick),
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxWidth().shine(hot)) {
|
||||
Art(t.art, t.iconRes, t.title, Modifier.fillMaxWidth(), wide, t.iconBitmap)
|
||||
androidx.compose.animation.AnimatedVisibility(
|
||||
visible = hot, modifier = Modifier.align(Alignment.Center),
|
||||
enter = scaleIn(Motion.sp(0.5f), initialScale = 0.5f) + fadeIn(Motion.tw(200)),
|
||||
exit = scaleOut(Motion.tw(150), targetScale = 0.6f) + fadeOut(Motion.tw(150)),
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(if (square) 26.dp else 32.dp).graphicsLayer { shadowElevation = 10.dp.toPx(); shape = CircleShape; clip = false; spotShadowColor = pal.signal }.clip(CircleShape).background(pal.signal),
|
||||
) { Text("›", fontSize = if (square) 16.sp else 20.sp, color = Color.White) }
|
||||
}
|
||||
}
|
||||
Column(modifier = Modifier.padding(horizontal = 6.dp, vertical = 5.dp)) {
|
||||
Text(t.title, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (t.sub != null) Text(t.sub, fontSize = 8.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Art(art: File?, iconRes: Int?, label: String, modifier: Modifier, wide: Boolean = false, iconBitmap: Bitmap? = null) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val ratio = if (art == null && (iconRes != null || iconBitmap != null)) 1f else if (wide) 16f / 9f else 2f / 3f
|
||||
Box(modifier = modifier.aspectRatio(ratio).background(if (art == null && iconRes == null && iconBitmap == null) artBrush(hueOf(label)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surface)))) {
|
||||
when {
|
||||
art != null -> AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
iconRes != null -> Image(painterResource(iconRes), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(if (wide) 10.dp else 8.dp))
|
||||
iconBitmap != null -> Image(bitmap = iconBitmap.asImageBitmap(), contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(8.dp))
|
||||
else -> {
|
||||
Spacer(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Color.Transparent, 0.45f to Color.Transparent, 1f to Color.Black.copy(alpha = 0.55f))))
|
||||
Text(label, fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color.White.copy(alpha = 0.92f), modifier = Modifier.align(Alignment.BottomStart).padding(5.dp), maxLines = 3, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(title) },
|
||||
text = { Text(text) },
|
||||
confirmButton = { TextButton(onClick = { onDismiss(); onConfirm() }) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CreditsDialog(onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Credits") },
|
||||
text = {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text("The412Banner: app, compositor, runtime, and Steam session.", style = MaterialTheme.typography.bodyMedium)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text("maxjivi05: gamescope runtime and controller support, based on WinNative.", style = MaterialTheme.typography.bodyMedium)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"GPL-3.0. Steam, Steam Deck, and Proton are Valve trademarks. Not affiliated with Valve. Third-party software remains under its authors' licenses.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
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.focus.focusRequester
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
|
||||
/** [tag] is shown beside the name: [BUNDLED], [DOWNLOADED], [IMPORTED], or "" for Auto / Runtime default. */
|
||||
class DriverRow(val id: String, val name: String, val detail: String, val removable: Boolean, val tag: String = "") {
|
||||
companion object {
|
||||
const val BUNDLED = "BUNDLED"
|
||||
const val DOWNLOADED = "DOWNLOADED"
|
||||
const val IMPORTED = "IMPORTED"
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 ModeSettings(
|
||||
val mode: String,
|
||||
val resolutionCap: Int,
|
||||
/** A fixed session size, or null for the cap and shape. */
|
||||
val customResolution: Pair<Int, Int>? = null,
|
||||
val shapeMode: String,
|
||||
val hdr: Boolean,
|
||||
val hdrReason: String?,
|
||||
val linuxRows: List<DriverRow>,
|
||||
val linuxSelected: String,
|
||||
val androidRows: List<DriverRow>,
|
||||
val androidSelected: String,
|
||||
val touchMode: String,
|
||||
val suspendPolicy: String,
|
||||
/** Steam only. */
|
||||
val oscMode: String?,
|
||||
val directAudio: Boolean?,
|
||||
val clientDirectAudio: Boolean = false,
|
||||
val mic: Boolean?,
|
||||
val renderer: String?,
|
||||
val gameStorage: String? = null,
|
||||
val storageOptions: List<Pair<String, String>> = emptyList(),
|
||||
val fexPreset: String? = null,
|
||||
/** Steam only: the client branch forced on the command line. */
|
||||
val steamChannel: String? = null,
|
||||
/** Steam only: the user's own games folder and what was found in it. */
|
||||
/** The chosen Games folders (null = not a Steam page). */
|
||||
val addedGamesDirs: List<String>? = null,
|
||||
val addedGames: List<AddedGameRow> = emptyList(),
|
||||
val addedGamesArt: Boolean = true,
|
||||
/** Latest Banners-Turnip release: what each driver menu offers to download, and the refresh line. */
|
||||
val linuxDownloads: List<DownloadRow> = emptyList(),
|
||||
val androidDownloads: List<DownloadRow> = emptyList(),
|
||||
val releaseStatus: String = "Not checked yet - tap refresh to look for new drivers",
|
||||
val releaseChecking: Boolean = false,
|
||||
/** A bundled display driver was deleted: the page offers to restore it. */
|
||||
val canRestoreBundled: Boolean = false,
|
||||
)
|
||||
|
||||
/** One added game as the settings page shows it: its folder, the chosen .exe, the other .exe files it could be. */
|
||||
class AddedGameRow(val folderPath: String, val folderName: String, val exePath: String, val exeName: String, val candidates: List<Pair<String, String>>)
|
||||
|
||||
class ModeSettingsActions(
|
||||
val onResolution: (Int) -> Unit,
|
||||
/** Null clears it. */
|
||||
val onCustomResolution: (Pair<Int, Int>?) -> Unit = {},
|
||||
val onShape: (String) -> Unit,
|
||||
val onHdr: (Boolean) -> Unit,
|
||||
val onSelectLinux: (String) -> Unit,
|
||||
val onImportLinux: () -> Unit,
|
||||
val onRemoveLinux: (String) -> Unit,
|
||||
val onRefreshReleases: () -> Unit = {},
|
||||
/** Asset name of the release driver to download. */
|
||||
val onDownloadDriver: (String) -> Unit = {},
|
||||
val onRestoreBundled: () -> Unit = {},
|
||||
val onSelectAndroid: (String) -> Unit,
|
||||
val onImportAndroid: () -> Unit,
|
||||
val onRemoveAndroid: (String) -> Unit,
|
||||
val onTouch: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onOsc: (String) -> Unit,
|
||||
val onDirectAudio: (Boolean) -> Unit,
|
||||
val onClientDirectAudio: (Boolean) -> Unit = {},
|
||||
val onMic: (Boolean) -> Unit,
|
||||
val onRenderer: (String) -> Unit,
|
||||
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
|
||||
val onPickGameStorageFolder: () -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit = {},
|
||||
val onSteamChannel: (String) -> Unit = {},
|
||||
val onPickAddedGamesDir: () -> Unit = {},
|
||||
val onForgetAddedGamesDir: (path: String) -> Unit = {},
|
||||
val onAddedGamesArt: (Boolean) -> Unit = {},
|
||||
val onAddedGameExe: (folderPath: String, path: String) -> Unit = { _, _ -> },
|
||||
val onPickAddedGameExe: (folderPath: String) -> Unit = {},
|
||||
val onDismiss: () -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
// The two driver lists open as full pages over this one ("rt" = runtime, "panel" = display).
|
||||
// Coming back restores this page as it was left: the same scroll position, and controller focus
|
||||
// on the driver box that opened the page.
|
||||
var driverPage by remember { mutableStateOf<String?>(null) }
|
||||
var returnTo by remember { mutableStateOf<String?>(null) }
|
||||
val pageScroll = androidx.compose.foundation.rememberScrollState()
|
||||
val runtimeChip = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
val displayChip = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
val firstChip = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
fun openDriverPage(key: String) { returnTo = key; driverPage = key }
|
||||
androidx.compose.runtime.LaunchedEffect(driverPage) {
|
||||
if (driverPage == null) {
|
||||
// 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; back
|
||||
// from a driver page, it returns to the driver box that opened it.
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
val target = when (returnTo) { "rt" -> runtimeChip; "panel" -> displayChip; else -> firstChip }
|
||||
runCatching { target.requestFocus() }
|
||||
}
|
||||
}
|
||||
when (driverPage) {
|
||||
"rt" -> {
|
||||
DriverPage(
|
||||
title = "Runtime driver",
|
||||
hint = (if (steam) "Used by Steam and games." else "Used by desktop apps.") + " Applies next session.",
|
||||
rows = s.linuxRows, selected = s.linuxSelected, downloads = s.linuxDownloads,
|
||||
status = s.releaseStatus, checking = s.releaseChecking, importLabel = "Import Turnip zip…", canRestore = false,
|
||||
onSelect = a.onSelectLinux, onDelete = a.onRemoveLinux, onRefresh = a.onRefreshReleases,
|
||||
onDownload = a.onDownloadDriver, onImport = a.onImportLinux, onRestore = {}, onBack = { driverPage = null },
|
||||
)
|
||||
return
|
||||
}
|
||||
"panel" -> {
|
||||
DriverPage(
|
||||
title = "Display driver",
|
||||
hint = "Used by the compositor in both modes. Restart the app to apply.",
|
||||
rows = s.androidRows, selected = s.androidSelected, downloads = s.androidDownloads,
|
||||
status = s.releaseStatus, checking = s.releaseChecking, importLabel = "Import an AdrenoTools zip…",
|
||||
canRestore = s.canRestoreBundled,
|
||||
onSelect = a.onSelectAndroid, onDelete = a.onRemoveAndroid, onRefresh = a.onRefreshReleases,
|
||||
onDownload = a.onDownloadDriver, onImport = a.onImportAndroid, onRestore = a.onRestoreBundled,
|
||||
onBack = { driverPage = null },
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
SettingsPage(
|
||||
host,
|
||||
title = if (steam) "Steam session" else "Desktop session",
|
||||
onBack = a.onDismiss,
|
||||
scroll = pageScroll,
|
||||
) {
|
||||
SettingsGroup("Display") {
|
||||
val default = SessionPrefs.defaultResolutionCap(s.mode)
|
||||
var editCustom by remember { mutableStateOf(false) }
|
||||
val custom = s.customResolution
|
||||
ChoiceRow(
|
||||
host, "res", "Resolution", "Applies next session.",
|
||||
listOf(720 to "Up to 720p", 900 to "Up to 900p", 1080 to "Up to 1080p", 0 to "The panel's own")
|
||||
.map { (cap, label) -> cap to (if (cap == default) "$label - the default" else label) } +
|
||||
(CUSTOM to (custom?.let { "Custom · ${it.first}×${it.second}" } ?: "Custom…")),
|
||||
if (custom != null) CUSTOM else s.resolutionCap, note = "720p can improve menu responsiveness.",
|
||||
chipModifier = androidx.compose.ui.Modifier.focusRequester(firstChip),
|
||||
onPick = { v -> if (v == CUSTOM) editCustom = true else { a.onCustomResolution(null); a.onResolution(v) } },
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "shape", "Shape",
|
||||
if (custom != null) "Set by the custom resolution." else "The panel's shape stays at 16:9 or wider; pick Exactly this panel for a 4:3 or 3:2 screen.",
|
||||
com.droiddeck.launcher.session.SessionPrefs.shapeChoices, s.shapeMode, enabled = custom == null, onPick = a.onShape,
|
||||
)
|
||||
if (editCustom) CustomResolutionDialog(
|
||||
initial = custom,
|
||||
onSave = { size -> editCustom = false; a.onCustomResolution(size) },
|
||||
onDismiss = { editCustom = false },
|
||||
)
|
||||
}
|
||||
SettingsGroup("HDR") {
|
||||
ToggleRow(
|
||||
host, "hdr", "HDR10 output",
|
||||
s.hdrReason?.let { "Not available: $it." }
|
||||
?: "Restart the app to apply.",
|
||||
checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Drivers") {
|
||||
SettingsRow("Runtime driver", (if (steam) "Used by Steam and games." else "Used by desktop apps.") + " Applies next session.") {
|
||||
ValueChip(
|
||||
s.linuxRows.firstOrNull { it.id == s.linuxSelected }?.name ?: "Runtime default", open = false,
|
||||
modifier = androidx.compose.ui.Modifier.focusRequester(runtimeChip),
|
||||
) { openDriverPage("rt") }
|
||||
}
|
||||
SettingsRow("Display driver", "Used by the compositor in both modes. Restart the app to apply.") {
|
||||
ValueChip(
|
||||
s.androidRows.firstOrNull { it.id == s.androidSelected }?.name ?: "Auto - picked by GPU", open = false,
|
||||
modifier = androidx.compose.ui.Modifier.focusRequester(displayChip),
|
||||
) { openDriverPage("panel") }
|
||||
}
|
||||
}
|
||||
SettingsGroup(if (steam) "Touch & controls" else "Touch") {
|
||||
ChoiceRow(
|
||||
host, "touch", "Touch", null,
|
||||
listOf("auto" to "Auto", "touchpad" to "Touchpad", "direct" to "Direct"), s.touchMode,
|
||||
note = "Auto uses touchpad on desktop and direct input in Steam. Touchpad: drag to move, tap to click.",
|
||||
onPick = a.onTouch,
|
||||
)
|
||||
if (steam && s.oscMode != null) ChoiceRow(
|
||||
host, "osc", "On-screen controls", null,
|
||||
listOf(
|
||||
SessionPrefs.OSC_AUTO to "Auto",
|
||||
SessionPrefs.OSC_ALWAYS to "Always",
|
||||
SessionPrefs.OSC_STEAM_QAM to "Steam + QAM",
|
||||
SessionPrefs.OSC_NEVER to "Never",
|
||||
), s.oscMode,
|
||||
note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Session") {
|
||||
ChoiceRow(
|
||||
host, "suspend", "Background behavior",
|
||||
"How this session behaves when the app leaves the screen or the display turns off.",
|
||||
listOf(
|
||||
SessionPrefs.SUSPEND_AUTO to "Auto",
|
||||
SessionPrefs.SUSPEND_MANUAL to "Manual",
|
||||
SessionPrefs.SUSPEND_NEVER to "Never",
|
||||
),
|
||||
s.suspendPolicy,
|
||||
note = "Auto pauses in the background and resumes when visible. Manual pauses there and waits for Resume. Never keeps the session running.",
|
||||
onPick = a.onSuspendPolicy,
|
||||
)
|
||||
}
|
||||
if (steam && s.steamChannel != null) SettingsGroup("Client") {
|
||||
ChoiceRow(
|
||||
host, "channel", "Client branch", "The Steam client build the session forces. Applies at the next session start; the client may update itself once.",
|
||||
listOf("publicbeta" to "Public beta", "steamdeck_publicbeta" to "Steam Deck public beta"), s.steamChannel,
|
||||
note = "Public beta is what every session ran on before. Steam Deck public beta is the channel Deck mode needs (on public beta it reinstalls the same client at every start) and the one Armada bootstraps from; Deck mode picks it unless you choose here.",
|
||||
onPick = a.onSteamChannel,
|
||||
)
|
||||
}
|
||||
if (steam && s.addedGamesDirs != null) SettingsGroup("Added games") {
|
||||
for (dir in s.addedGamesDirs) {
|
||||
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") }
|
||||
ActionRow(
|
||||
dir.substringAfterLast('/').ifEmpty { dir }, dir + " · " + (if (n == 0) "no game folders with a .exe found" else "$n game${if (n == 1) "" else "s"}") + ". Forget: the games leave the client's library at the next session start; nothing on disk is touched.",
|
||||
"Forget", onClick = { a.onForgetAddedGamesDir(dir) },
|
||||
)
|
||||
}
|
||||
ActionRow(
|
||||
if (s.addedGamesDirs.isEmpty()) "Games folder" else "Another games folder",
|
||||
"Your own Windows games, one subfolder each, anywhere: internal storage, the SD card, a USB drive. As many folders as you like. Each game goes into the client's library as a non-Steam game under the ARM64 Proton, at the next session start.",
|
||||
"Add…", onClick = a.onPickAddedGamesDir,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "addedArt", "Artwork from Steam",
|
||||
"A game with no art of its own gets the store's capsule, header, hero and logo for the same title, looked up by folder name. Your own art wins: drop cover.jpg (or poster, boxart, folder, the folder's name), header.jpg, hero.jpg, logo.png or icon.png into the game's folder or its art subfolder.",
|
||||
s.addedGamesArt, onChange = a.onAddedGamesArt,
|
||||
)
|
||||
for (g in s.addedGames) ChoiceRow(
|
||||
host, "added:" + g.folderPath, g.folderName, "Launches ${g.exeName}" + (if (s.addedGamesDirs.size > 1) " · in " + g.folderPath.substringBeforeLast('/').substringAfterLast('/') else ""),
|
||||
g.candidates + ("__pick__" to "Choose another file…"), g.exePath,
|
||||
note = "The .exe files found in the game's folder; the one named after the folder, else the largest, is picked unless you choose.",
|
||||
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
|
||||
)
|
||||
}
|
||||
if (steam && s.fexPreset != null) SettingsGroup("Games") {
|
||||
ChoiceRow(
|
||||
host, "fex", "FEX preset", "Applies on next game launch.",
|
||||
FexPreset.all.map { it.id to it.label }, s.fexPreset,
|
||||
note = FexPreset.byId(s.fexPreset).detail, onPick = a.onFexPreset,
|
||||
)
|
||||
}
|
||||
if (steam && s.directAudio != null && s.mic != null) SettingsGroup("Audio") {
|
||||
ToggleRow(host, "da", "DirectAudio for games", "Bypasses PulseAudio for lower latency in games.", s.directAudio, onChange = a.onDirectAudio)
|
||||
ChoiceRow(
|
||||
host, "clientAudio", "Steam client audio", "Classic is the AAudio sink from 0.1.5. DirectAudio goes through the relay. Applies next session.",
|
||||
listOf("classic" to "Classic", "directaudio" to "DirectAudio"), if (s.clientDirectAudio) "directaudio" else "classic",
|
||||
onPick = { id -> a.onClientDirectAudio(id == "directaudio") },
|
||||
)
|
||||
ToggleRow(host, "mic", "Microphone", "Uses the device microphone for voice chat.", s.mic, onChange = a.onMic)
|
||||
}
|
||||
if (steam && s.gameStorage != null) SettingsGroup("Game storage") {
|
||||
val custom = s.gameStorage.isNotEmpty() && s.gameStorage != "off" && s.storageOptions.none { it.second == s.gameStorage }
|
||||
val options = buildList {
|
||||
add("" to ("Automatic - the SD card when one is in" + (if (s.storageOptions.isEmpty()) " (none right now)" else "")))
|
||||
add("off" to "Internal only")
|
||||
for ((label, path) in s.storageOptions) add(path to label)
|
||||
if (custom) add(s.gameStorage to "Folder: ${s.gameStorage}")
|
||||
}
|
||||
val open = host.open == "storage"
|
||||
SettingsRow(
|
||||
"Second library",
|
||||
"Adds a library location in Steam. Applies next session.",
|
||||
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 = "Second library",
|
||||
note = "Games that stream assets from SD or shared storage may stutter. Keep them internal.",
|
||||
) {
|
||||
for ((path, label) in options) MenuItem(label, checked = path == s.gameStorage) {
|
||||
a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·"))
|
||||
host.open = null
|
||||
}
|
||||
MenuItem("Choose a folder…", checked = false) { host.open = null; a.onPickGameStorageFolder() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!steam && s.renderer != null) SettingsGroup("Renderer") {
|
||||
ChoiceRow(
|
||||
host, "renderer", "Desktop renderer", "Composites the desktop.",
|
||||
listOf("pixman" to "pixman - software", "gles2" to "gles2", "vulkan" to "vulkan"), s.renderer,
|
||||
note = "GLES2 and Vulkan require a DRM render node, unavailable on most devices.", onPick = a.onRenderer,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The Resolution menu's "Custom…" entry. */
|
||||
private const val CUSTOM = -1
|
||||
|
||||
/** Width × height for the session, with the common handheld shapes one tap away. */
|
||||
@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit) {
|
||||
var w by remember { mutableStateOf(initial?.first?.toString() ?: "") }
|
||||
var h by remember { mutableStateOf(initial?.second?.toString() ?: "") }
|
||||
val parsed = SessionPrefs.parseResolution("${w}x$h")
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Custom resolution") },
|
||||
text = {
|
||||
androidx.compose.foundation.layout.Column {
|
||||
Text(
|
||||
"The session's display size. It replaces the cap and the shape; a size that does not match the panel's shape gets bars.",
|
||||
fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
androidx.compose.foundation.layout.Row(
|
||||
verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
) {
|
||||
val numbers = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
w, { v -> w = v.filter(Char::isDigit).take(4) }, label = { Text("Width") },
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text("×", fontSize = 18.sp, modifier = Modifier.padding(horizontal = 10.dp))
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
h, { v -> h = v.filter(Char::isDigit).take(4) }, label = { Text("Height") },
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
androidx.compose.foundation.layout.FlowRow(
|
||||
horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.padding(top = 10.dp),
|
||||
) {
|
||||
for ((pw, ph, tag) in listOf(Triple(960, 720, "4:3"), Triple(1024, 768, "4:3"), Triple(1280, 960, "4:3"), Triple(1280, 800, "16:10"), Triple(1152, 648, "16:9"), Triple(1280, 720, "16:9"))) {
|
||||
androidx.compose.material3.AssistChip(
|
||||
onClick = { w = pw.toString(); h = ph.toString() },
|
||||
label = { Text("$pw×$ph · $tag", fontSize = 12.sp) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (parsed == null && (w.isNotEmpty() || h.isNotEmpty())) Text(
|
||||
"Between 320×240 and 3840×2160.", fontSize = 12.sp, color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { androidx.compose.material3.TextButton(enabled = parsed != null, onClick = { parsed?.let(onSave) }) { Text("Use") } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
/** Package metadata shown on an emulator's own detail page. */
|
||||
class PackageRow(
|
||||
val id: String,
|
||||
val kind: String,
|
||||
val notes: String,
|
||||
)
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
class CoreRow(val core: Int, val label: String)
|
||||
|
||||
@Composable
|
||||
fun PerformancePage(
|
||||
cores: List<CoreRow>,
|
||||
clientOverride: Boolean,
|
||||
clientCores: Set<Int>,
|
||||
gameCores: Set<Int>,
|
||||
tuSysmem: Boolean,
|
||||
zinkLazy: Boolean,
|
||||
glThread: Boolean,
|
||||
noGlError: Boolean,
|
||||
steamDeckMode: Boolean,
|
||||
noXalia: Boolean,
|
||||
prootNoSeccomp: Boolean,
|
||||
phantomWarning: String?,
|
||||
onClientOverride: (Boolean) -> Unit,
|
||||
onTuSysmem: (Boolean) -> Unit,
|
||||
onZinkLazy: (Boolean) -> Unit,
|
||||
onGlThread: (Boolean) -> Unit,
|
||||
onNoGlError: (Boolean) -> Unit,
|
||||
onSteamDeckMode: (Boolean) -> Unit,
|
||||
onNoXalia: (Boolean) -> Unit,
|
||||
onProotNoSeccomp: (Boolean) -> Unit,
|
||||
onClientCore: (Int, Boolean) -> Unit,
|
||||
onGameCore: (Int, Boolean) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val host = rememberMenuHost()
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val coreItems = cores.map { it.core to it.label }
|
||||
SettingsPage(
|
||||
host, title = "Performance",
|
||||
lede = "CPU cores and session fixes. Applies next session.",
|
||||
onBack = onDismiss,
|
||||
) {
|
||||
SettingsGroup("Steam client cores") {
|
||||
ToggleRow(
|
||||
host, "override", "Override Steam's own core choice",
|
||||
"Pins Steam, its UI helper, and gamescope to the cores below. Reapplied every few seconds.",
|
||||
clientOverride, onChange = onClientOverride,
|
||||
)
|
||||
MultiRow(
|
||||
host, "clientCores", "Client cores", if (clientOverride) "Choose cores for Steam." else "Enable the override to choose.",
|
||||
coreItems, clientCores, enabled = clientOverride, onToggle = onClientCore,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Game cores") {
|
||||
MultiRow(
|
||||
host, "gameCores", "Game cores",
|
||||
"Choose cores for games. All selected lets Android schedule across every core.",
|
||||
coreItems, gameCores, onToggle = onGameCore,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Client interface") {
|
||||
ToggleRow(
|
||||
host, "glthread", "Threaded GL",
|
||||
"May improve Steam menu responsiveness. Device impact is unverified.",
|
||||
glThread, onChange = onGlThread,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "zink", "Zink: lazy descriptors",
|
||||
"Recommended for drivers without descriptor buffers.",
|
||||
zinkLazy, onChange = onZinkLazy,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "noglerror", "Skip GL error checks",
|
||||
"Disables per-call GL validation.",
|
||||
noGlError, onChange = onNoGlError,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "deck", "Steam Deck mode",
|
||||
"Runs the client with -droiddeck. SteamOS helpers and battery info are provided.",
|
||||
steamDeckMode, onChange = onSteamDeckMode,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Session fixes") {
|
||||
ToggleRow(
|
||||
host, "sysmem", "Turnip: sysmem rendering",
|
||||
"Required on Adreno 710/720/722. May fix corruption on other Adreno GPUs, but can reduce performance.",
|
||||
tuSysmem, onChange = onTuSysmem,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "xalia", "Skip Steam's xalia helper",
|
||||
"Disables Proton's gamepad navigation helper. Try if sessions crash at startup.",
|
||||
noXalia, onChange = onNoXalia,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "seccomp", "Run proot without seccomp",
|
||||
"May fix missing syscall errors on some kernels, but can reduce performance.",
|
||||
prootNoSeccomp, onChange = onProotNoSeccomp,
|
||||
)
|
||||
}
|
||||
if (phantomWarning != null) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(colors.error.copy(alpha = 0.08f))
|
||||
.border(1.dp, colors.error.copy(alpha = 0.4f), RoundedCornerShape(12.dp)).padding(12.dp),
|
||||
) {
|
||||
Text("Android is set to kill this session", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error)
|
||||
Text(phantomWarning, fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
class ProtonRow(val id: String, val name: String, val installed: String?, val queued: Boolean)
|
||||
|
||||
@Composable
|
||||
fun ProtonPage(
|
||||
rows: List<ProtonRow>,
|
||||
busyId: String?,
|
||||
stage: String?,
|
||||
percent: Int,
|
||||
runtimeReady: Boolean,
|
||||
sessionRunning: Boolean,
|
||||
onInstall: (String) -> Unit,
|
||||
onCancel: (String) -> Unit,
|
||||
onRemove: (String) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val host = rememberMenuHost()
|
||||
val colors = MaterialTheme.colorScheme
|
||||
SettingsPage(
|
||||
host,
|
||||
title = "Compatibility tools",
|
||||
eyebrow = "Setup",
|
||||
lede = "Download and install an ARM64 Proton build now, then select it per game in Steam > Properties > Compatibility.",
|
||||
onBack = onBack,
|
||||
) {
|
||||
if (!runtimeReady) Text(
|
||||
"Install the Linux runtime from Setup before managing compatibility tools.",
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp, bottom = 6.dp),
|
||||
)
|
||||
if (sessionRunning) Text(
|
||||
"Stop the active session before installing or removing a compatibility tool.",
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp, bottom = 6.dp),
|
||||
)
|
||||
SettingsGroup("Available builds") {
|
||||
for (row in rows) {
|
||||
SettingsRow(
|
||||
row.name,
|
||||
when {
|
||||
row.installed != null -> "Installed ${row.installed}"
|
||||
row.queued -> "Pending from an earlier request"
|
||||
else -> "Not installed"
|
||||
},
|
||||
) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
when {
|
||||
row.installed != null -> SecondaryButton("Remove", enabled = busyId == null && runtimeReady && !sessionRunning) { onRemove(row.id) }
|
||||
busyId != null -> SecondaryButton(if (busyId == row.id) "Installing…" else "Install", enabled = false) {}
|
||||
else -> SecondaryButton("Install now", enabled = runtimeReady && !sessionRunning) { onInstall(row.id) }
|
||||
}
|
||||
if (row.queued && row.installed == null && busyId == null) {
|
||||
SecondaryButton("Cancel queued", enabled = !sessionRunning) { onCancel(row.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (busyId == row.id) Column(modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 10.dp)) {
|
||||
Text(
|
||||
if (stage != null && percent >= 0) "$stage · $percent%" else stage ?: "Starting…",
|
||||
fontSize = 11.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 5.dp),
|
||||
)
|
||||
if (percent >= 0) LinearProgressIndicator(progress = { percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun RomsDialog(path: String?, onChoose: () -> Unit, onClear: () -> Unit, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("ROMs folder") },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"This folder appears as /root/ROMs in each session. Internal storage is available at /root/Storage.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
path ?: "No folder chosen",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (path != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"Applies next session. SD cards are supported.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onChoose) { Text(if (path == null) "Choose folder" else "Change folder") } },
|
||||
dismissButton = {
|
||||
if (path != null) TextButton(onClick = onClear) { Text("Forget") }
|
||||
else TextButton(onClick = onDismiss) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Presentation
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.Gravity
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowManager
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.Button
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.HorizontalScrollView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SessionTerminal
|
||||
import com.termux.terminal.TerminalEmulator
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
|
||||
/** Touch controls drawn on a second Android display while the compositor remains on the main one. */
|
||||
class SecondScreenPresentation(
|
||||
private val sessionActivity: SessionActivity,
|
||||
display: Display,
|
||||
private val sendPointer: (x: Float, y: Float, width: Float, height: Float) -> Unit,
|
||||
private val sendButton: (button: Int, pressed: Boolean) -> Unit,
|
||||
private val sendWheel: (steps: Int) -> Unit,
|
||||
private val onSteamMenu: () -> Unit,
|
||||
private val onQam: () -> Unit,
|
||||
) : Presentation(sessionActivity, display) {
|
||||
private val root = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setBackgroundColor(Color.rgb(15, 18, 22))
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
private var currentMode = SecondScreenMode.NONE
|
||||
private var keyboardHost: KeyboardHost? = null
|
||||
private var terminalSession: TerminalSession? = null
|
||||
private var terminalView: TerminalView? = null
|
||||
private var terminalPid = -1
|
||||
private var ctrlActive = false
|
||||
private var altActive = false
|
||||
private var created = false
|
||||
|
||||
init {
|
||||
setCancelable(false)
|
||||
setCanceledOnTouchOutside(false)
|
||||
setOnDismissListener { closeTerminal() }
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
created = true
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
|
||||
setContentView(root)
|
||||
applyImmersiveMode()
|
||||
renderMode()
|
||||
}
|
||||
|
||||
fun showMode(mode: SecondScreenMode) {
|
||||
if (currentMode == mode && isShowing) return
|
||||
currentMode = mode
|
||||
if (created) renderMode()
|
||||
}
|
||||
|
||||
/** Releases the auxiliary Linux shell before the window is dismissed. */
|
||||
fun closeControls() {
|
||||
closeTerminal()
|
||||
keyboardHost?.hide()
|
||||
keyboardHost = null
|
||||
dismiss()
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (currentMode == SecondScreenMode.KEYBOARD_TRACKPAD) {
|
||||
if (sessionActivity.dispatchKeyEvent(event)) return true
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) applyImmersiveMode()
|
||||
}
|
||||
|
||||
private fun renderMode() {
|
||||
keyboardHost?.hide()
|
||||
keyboardHost = null
|
||||
closeTerminal()
|
||||
root.removeAllViews()
|
||||
if (currentMode == SecondScreenMode.NONE) return
|
||||
|
||||
when (currentMode) {
|
||||
SecondScreenMode.KEYBOARD_TRACKPAD -> renderKeyboardAndTrackpad()
|
||||
SecondScreenMode.TERMINAL -> renderTerminal()
|
||||
SecondScreenMode.NONE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderKeyboardAndTrackpad() {
|
||||
val panel = FrameLayout(context)
|
||||
panel.addView(trackpadView(), FrameLayout.LayoutParams(-1, -1))
|
||||
val controls = LinearLayout(context).apply {
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
setPadding(dp(12), dp(8), dp(12), dp(8))
|
||||
setBackgroundColor(0xE6191E24.toInt())
|
||||
}
|
||||
controls.addView(TextView(context).apply {
|
||||
text = "Trackpad"
|
||||
textSize = 14f
|
||||
setTextColor(Color.WHITE)
|
||||
}, LinearLayout.LayoutParams(0, -2, 1f))
|
||||
val keyboardButton = Button(context).apply {
|
||||
text = "Show keyboard"
|
||||
setOnClickListener {
|
||||
val host = keyboardHost ?: return@setOnClickListener
|
||||
if (host.shown) {
|
||||
host.hide()
|
||||
text = "Show keyboard"
|
||||
} else {
|
||||
host.show()
|
||||
text = "Hide keyboard"
|
||||
}
|
||||
}
|
||||
}
|
||||
controls.addView(keyboardButton)
|
||||
controls.addView(Button(context).apply {
|
||||
text = "STEAM"
|
||||
contentDescription = "Open Steam menu"
|
||||
setOnClickListener { onSteamMenu() }
|
||||
})
|
||||
controls.addView(Button(context).apply {
|
||||
text = "…"
|
||||
contentDescription = "Open Quick Access Menu"
|
||||
setOnClickListener { onQam() }
|
||||
})
|
||||
panel.addView(controls, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
|
||||
root.addView(panel, weightParams())
|
||||
val host = KeyboardHost(context) { sessionActivity.dispatchKeyEvent(it) }
|
||||
keyboardHost = host
|
||||
root.addView(host, ViewGroup.LayoutParams(1, 1))
|
||||
}
|
||||
|
||||
private fun trackpadView(): View = TrackpadView(context)
|
||||
|
||||
private fun renderTerminal() {
|
||||
val bar = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
setPadding(dp(8), dp(4), dp(8), dp(4))
|
||||
setBackgroundColor(Color.rgb(27, 32, 38))
|
||||
}
|
||||
bar.addView(TextView(context).apply {
|
||||
text = "Linux terminal"
|
||||
textSize = 14f
|
||||
setTextColor(Color.WHITE)
|
||||
}, LinearLayout.LayoutParams(0, -2, 1f))
|
||||
bar.addView(Button(context).apply {
|
||||
text = "Keyboard"
|
||||
setOnClickListener { showTerminalKeyboard() }
|
||||
})
|
||||
root.addView(bar, LinearLayout.LayoutParams(-1, -2))
|
||||
|
||||
val terminalClient = TerminalClient()
|
||||
val view = TerminalView(context, null).apply {
|
||||
setTerminalViewClient(terminalClient)
|
||||
setTextSize(dp(14))
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
terminalView = view
|
||||
val session = SessionTerminal.create(terminalClient)
|
||||
if (session == null) {
|
||||
root.addView(TextView(context).apply {
|
||||
text = "The Linux session is not ready for a terminal yet."
|
||||
setTextColor(Color.WHITE)
|
||||
gravity = Gravity.CENTER
|
||||
}, LinearLayout.LayoutParams(-1, 0, 1f))
|
||||
return
|
||||
}
|
||||
terminalSession = session
|
||||
|
||||
val keyStrip = HorizontalScrollView(context).apply { isHorizontalScrollBarEnabled = false }
|
||||
val keys = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; setPadding(dp(4), dp(2), dp(4), dp(2)) }
|
||||
fun key(label: String, input: String, onClick: ((Button) -> Unit)? = null) {
|
||||
val button = Button(context).apply {
|
||||
text = label
|
||||
setOnClickListener { if (onClick != null) onClick(this) else session.write(input) }
|
||||
}
|
||||
keys.addView(button)
|
||||
}
|
||||
key("Esc", "\u001b")
|
||||
key("Tab", "\t")
|
||||
key("Ctrl", "") { button ->
|
||||
ctrlActive = !ctrlActive
|
||||
button.text = if (ctrlActive) "Ctrl ✓" else "Ctrl"
|
||||
}
|
||||
key("Alt", "") { button ->
|
||||
altActive = !altActive
|
||||
button.text = if (altActive) "Alt ✓" else "Alt"
|
||||
}
|
||||
key("↑", "\u001b[A")
|
||||
key("↓", "\u001b[B")
|
||||
key("←", "\u001b[D")
|
||||
key("→", "\u001b[C")
|
||||
key("Ctrl+C", "\u0003")
|
||||
key("Ctrl+D", "\u0004")
|
||||
keyStrip.addView(keys)
|
||||
root.addView(keyStrip, LinearLayout.LayoutParams(-1, -2))
|
||||
|
||||
root.addView(view, LinearLayout.LayoutParams(-1, 0, 1f))
|
||||
view.attachSession(session)
|
||||
|
||||
view.post {
|
||||
registerTerminalPid()
|
||||
view.requestFocus()
|
||||
showTerminalKeyboard()
|
||||
}
|
||||
}
|
||||
|
||||
private fun showTerminalKeyboard() {
|
||||
terminalView?.let { view ->
|
||||
view.requestFocus()
|
||||
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
|
||||
.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
|
||||
private fun registerTerminalPid() {
|
||||
val pid = terminalSession?.pid ?: -1
|
||||
if (pid > 1 && pid != terminalPid) {
|
||||
terminalPid = pid
|
||||
SessionService.registerTerminalProcess(context, pid)
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeTerminal() {
|
||||
terminalView?.let { view ->
|
||||
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
|
||||
.hideSoftInputFromWindow(view.windowToken, 0)
|
||||
}
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: (terminalSession?.pid ?: -1)
|
||||
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
|
||||
terminalPid = -1
|
||||
terminalSession = null
|
||||
terminalView = null
|
||||
ctrlActive = false
|
||||
altActive = false
|
||||
}
|
||||
|
||||
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
|
||||
|
||||
private fun weightParams() = LinearLayout.LayoutParams(-1, 0, 1f)
|
||||
|
||||
private fun applyImmersiveMode() {
|
||||
@Suppress("DEPRECATION")
|
||||
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
||||
or View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
}
|
||||
|
||||
private inner class TrackpadView(context: Context) : View(context) {
|
||||
private val gestures = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(),
|
||||
object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) {
|
||||
sendPointer(x, y, width.toFloat(), height.toFloat())
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
sendPointer(x, y, width.toFloat(), height.toFloat())
|
||||
sendButton(button, pressed)
|
||||
}
|
||||
|
||||
override fun onWheel(steps: Int) = sendWheel(steps)
|
||||
override fun onLongPress() { performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS) }
|
||||
})
|
||||
|
||||
init { isFocusable = true }
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
gestures.bounds = android.graphics.RectF(0f, 0f, w.toFloat(), h.toFloat())
|
||||
if (oldw == 0 || oldh == 0) gestures.place(w / 2f, h / 2f)
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
canvas.drawColor(Color.BLACK)
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean = gestures.onTouch(event)
|
||||
}
|
||||
|
||||
private inner class TerminalClient : TerminalSessionClient, TerminalViewClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {
|
||||
terminalView?.onScreenUpdated()
|
||||
}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = Unit
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: finishedSession.pid
|
||||
if (pid > 1) SessionService.terminalProcessExited(context, pid)
|
||||
terminalPid = -1
|
||||
terminalView?.onScreenUpdated()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
(context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager)
|
||||
.setPrimaryClip(android.content.ClipData.newPlainText("Terminal", text))
|
||||
}
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val clip = (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).primaryClip
|
||||
if (clip != null && clip.itemCount > 0) session.write(clip.getItemAt(0).coerceToText(context).toString())
|
||||
}
|
||||
override fun onBell(session: TerminalSession) {
|
||||
terminalView?.performHapticFeedback(android.view.HapticFeedbackConstants.KEYBOARD_TAP)
|
||||
}
|
||||
override fun onColorsChanged(changedSession: TerminalSession) {
|
||||
terminalView?.invalidate()
|
||||
}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {
|
||||
terminalView?.setTerminalCursorBlinkerRate(if (state) 600 else 0)
|
||||
}
|
||||
override fun getTerminalCursorStyle(): Int = TerminalEmulator.TERMINAL_CURSOR_STYLE_BLOCK
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, e.message, e) }
|
||||
|
||||
override fun onScale(scale: Float): Float = 1f
|
||||
override fun onSingleTapUp(e: MotionEvent) = showTerminalKeyboard()
|
||||
override fun shouldBackButtonBeMappedToEscape(): Boolean = true
|
||||
override fun shouldEnforceCharBasedInput(): Boolean = false
|
||||
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
|
||||
override fun isTerminalViewSelected(): Boolean = true
|
||||
override fun copyModeChanged(copyMode: Boolean) = Unit
|
||||
override fun onKeyDown(keyCode: Int, e: KeyEvent, session: TerminalSession): Boolean = false
|
||||
override fun onKeyUp(keyCode: Int, e: KeyEvent): Boolean = false
|
||||
override fun onLongPress(event: MotionEvent): Boolean = false
|
||||
override fun readControlKey(): Boolean = ctrlActive
|
||||
override fun readAltKey(): Boolean = altActive
|
||||
override fun readShiftKey(): Boolean = false
|
||||
override fun readFnKey(): Boolean = false
|
||||
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession): Boolean = false
|
||||
override fun onEmulatorSet() {
|
||||
terminalView?.onScreenUpdated()
|
||||
registerTerminalPid()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.PressInteraction
|
||||
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.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
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.draw.clip
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import kotlinx.coroutines.flow.collect
|
||||
|
||||
@Composable
|
||||
fun HudText(text: String) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) {
|
||||
Text(
|
||||
text,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.padding(12.dp)
|
||||
.background(Color(0x8C000000))
|
||||
.padding(horizontal = 8.dp, vertical = 3.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun LoadingOverlay(step: String, percent: Int, elapsed: String, hint: String, ended: Boolean) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = androidx.compose.foundation.layout.Arrangement.Center,
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color.Black)
|
||||
.clickable(interactionSource = MutableInteractionSource(), indication = null) {}
|
||||
.padding(32.dp),
|
||||
) {
|
||||
Image(painterResource(R.drawable.logo), contentDescription = null, modifier = Modifier.size(64.dp))
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Text(if (ended) "The session ended" else "Steam is loading", color = Color.White, fontSize = 17.sp)
|
||||
Text(step, color = Color(0xFFB8C4D0), fontSize = 13.sp, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 6.dp))
|
||||
if (!ended) {
|
||||
Spacer(Modifier.height(14.dp))
|
||||
if (percent >= 0) LinearProgressIndicator(progress = { percent / 100f }, modifier = Modifier.width(220.dp))
|
||||
else LinearProgressIndicator(modifier = Modifier.width(220.dp))
|
||||
Text(elapsed, color = Color(0xFF667788), fontSize = 11.sp, modifier = Modifier.padding(top = 8.dp))
|
||||
Text(
|
||||
hint, color = Color(0xFF667788), fontSize = 11.sp, textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(top = 18.dp).widthIn(max = 360.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SessionPausedOverlay(onResume: () -> Unit) {
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color(0xF20B0D10))
|
||||
.clickable(interactionSource = interactionSource, indication = null) {},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
) {
|
||||
OutlinedButton(onClick = onResume) {
|
||||
Text("Resume session")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Everything the drawer shows and does. */
|
||||
class DrawerActions(
|
||||
val steam: Boolean,
|
||||
val isHomeApp: Boolean,
|
||||
val androidApps: List<HomeApp.LaunchableApp>,
|
||||
val hudOn: Boolean,
|
||||
val frameGenEngine: String,
|
||||
val frameGenMultiplier: Int,
|
||||
val lsfgReady: Boolean,
|
||||
val oscMode: String,
|
||||
val touchMode: String,
|
||||
val touchAuto: String,
|
||||
val shapeMode: String,
|
||||
val fexPreset: String,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
val onFrameGenPick: (engine: String, multiplier: Int) -> Unit,
|
||||
val onKeyboard: () -> Unit,
|
||||
val onSteamMenu: (() -> Unit)?,
|
||||
val onQam: (() -> Unit)?,
|
||||
val onOsc: (String) -> Unit,
|
||||
val onTouch: (String) -> Unit,
|
||||
val onShape: (String) -> Unit,
|
||||
val onFexPreset: (String) -> Unit,
|
||||
val onSecondScreenMode: (SecondScreenMode) -> Unit,
|
||||
val onSecondScreenDisplay: (Int) -> Unit,
|
||||
val onLaunchAndroidApp: (HomeApp.LaunchableApp) -> Unit,
|
||||
val onBackground: () -> Unit,
|
||||
val onStop: () -> Unit,
|
||||
val onClose: () -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val host = rememberMenuHost()
|
||||
var androidAppsExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil")
|
||||
if (open || veil > 0.01f) Box(
|
||||
modifier = Modifier.fillMaxSize().graphicsLayer { alpha = veil }.background(Color(0x8A000000))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() },
|
||||
)
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
|
||||
AnimatedVisibility(
|
||||
open,
|
||||
enter = slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)),
|
||||
exit = slideOutHorizontally(Motion.tw(240)) { it } + fadeOut(Motion.tw(200)),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxHeight()
|
||||
.width(340.dp)
|
||||
.background(pal.background.copy(alpha = 0.97f))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 14.dp, vertical = 16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 4.dp, bottom = 6.dp)) {
|
||||
Box(modifier = Modifier.size(10.dp).clip(CircleShape).background(Brush.linearGradient(listOf(colors.primary, pal.primary2))))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(if (a.steam) "Steam" else "Desktop", fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
}
|
||||
if (a.onSteamMenu != null && a.onQam != null) {
|
||||
val qamInteraction = remember { MutableInteractionSource() }
|
||||
var qamStartedOnPress by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(qamInteraction) {
|
||||
qamInteraction.interactions.collect { interaction ->
|
||||
if (interaction is PressInteraction.Press) {
|
||||
qamStartedOnPress = true
|
||||
host.open = null
|
||||
a.onQam.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 12.dp),
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = { host.open = null; a.onSteamMenu.invoke() },
|
||||
modifier = Modifier.weight(1f).height(48.dp),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
) {
|
||||
Text("STEAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
host.open = null
|
||||
if (!qamStartedOnPress) a.onQam.invoke()
|
||||
qamStartedOnPress = false
|
||||
},
|
||||
interactionSource = qamInteraction,
|
||||
modifier = Modifier.weight(1f).height(48.dp).semantics { contentDescription = "Open Quick Access Menu" },
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
) {
|
||||
Text("…", fontSize = 22.sp, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (a.isHomeApp) SettingsGroup("Android apps") {
|
||||
ActionRow("Launch an app", null, if (androidAppsExpanded) "Hide" else "Show") {
|
||||
androidAppsExpanded = !androidAppsExpanded
|
||||
}
|
||||
if (androidAppsExpanded) {
|
||||
if (a.androidApps.isEmpty()) {
|
||||
Text("No launchable apps found", fontSize = 12.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
|
||||
} else {
|
||||
for (app in a.androidApps) {
|
||||
MenuItem(
|
||||
app.label,
|
||||
checked = false,
|
||||
leading = {
|
||||
app.icon?.let { icon ->
|
||||
Image(
|
||||
bitmap = icon.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(26.dp).clip(RoundedCornerShape(6.dp)),
|
||||
)
|
||||
}
|
||||
},
|
||||
) { a.onLaunchAndroidApp(app) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SettingsGroup("Now") {
|
||||
ToggleRow(host, "hud", "Performance HUD", null, a.hudOn, onChange = a.onHud)
|
||||
val fgOpen = host.open == "fg"
|
||||
val fgLabel = when (a.frameGenEngine) {
|
||||
FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×"
|
||||
FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×"
|
||||
else -> "Off"
|
||||
}
|
||||
SettingsRow("Frame generation", null, highlighted = fgOpen) {
|
||||
Box {
|
||||
ValueChip(fgLabel, fgOpen) { host.open = if (fgOpen) null else "fg" }
|
||||
AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") {
|
||||
val need = if (a.lsfgReady) null else "install Lossless Scaling in Steam"
|
||||
MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
||||
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
|
||||
for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
ChoiceRow(
|
||||
host, "touch", "Touch", null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"), a.touchMode,
|
||||
onPick = a.onTouch,
|
||||
)
|
||||
if (a.steam) ChoiceRow(
|
||||
host, "osc", "On-screen controls", null,
|
||||
listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never"), a.oscMode,
|
||||
onPick = a.onOsc,
|
||||
)
|
||||
ActionRow("Keyboard", null, "Show") { host.open = null; a.onKeyboard() }
|
||||
}
|
||||
|
||||
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
||||
ChoiceRow(
|
||||
host, "second-screen-mode", "Controls", null,
|
||||
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL)
|
||||
.map { it to it.label }, a.secondScreenMode,
|
||||
onPick = a.onSecondScreenMode,
|
||||
)
|
||||
if (a.secondScreenDisplays.size > 1) ChoiceRow(
|
||||
host, "second-screen-display", "Display", null,
|
||||
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
|
||||
onPick = a.onSecondScreenDisplay,
|
||||
)
|
||||
}
|
||||
|
||||
SettingsGroup("Next session") {
|
||||
ChoiceRow(
|
||||
host, "shape", "Display shape", null,
|
||||
SessionPrefs.shapeChoices, a.shapeMode, onPick = a.onShape,
|
||||
)
|
||||
if (a.steam) ChoiceRow(
|
||||
host, "fex", "FEX preset", null,
|
||||
FexPreset.all.map { it.id to it.label }, a.fexPreset, note = FexPreset.byId(a.fexPreset).detail, onPick = a.onFexPreset,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Row(
|
||||
horizontalArrangement = if (a.isHomeApp) Arrangement.End else Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (!a.isHomeApp) SecondaryButton("Send to background") { host.open = null; a.onBackground() }
|
||||
DangerButton("Stop session") { host.open = null; a.onStop() }
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DangerButton(text: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
|
||||
Box(
|
||||
modifier = Modifier.clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp))
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 11.dp),
|
||||
) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.error, maxLines = 1) }
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.MutableTransitionState
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
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.ColumnScope
|
||||
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.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
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.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.TransformOrigin
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntRect
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupPositionProvider
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
|
||||
|
||||
private val RowShape = RoundedCornerShape(12.dp)
|
||||
private val GroupShape = RoundedCornerShape(14.dp)
|
||||
|
||||
class MenuHost {
|
||||
var open by mutableStateOf<String?>(null)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun rememberMenuHost(): MenuHost = remember { MenuHost() }
|
||||
|
||||
private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
|
||||
override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {
|
||||
var x = anchorBounds.right - popupContentSize.width
|
||||
if (x < 8) x = 8
|
||||
var y = anchorBounds.bottom + gap
|
||||
if (y + popupContentSize.height > windowSize.height - 8) y = anchorBounds.top - gap - popupContentSize.height
|
||||
if (y < 8) y = 8
|
||||
return IntOffset(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.() -> Unit) {
|
||||
val state = remember { MutableTransitionState(false) }
|
||||
state.targetState = open
|
||||
if (!state.currentState && !state.targetState && state.isIdle) return
|
||||
val gap = with(LocalDensity.current) { 6.dp.roundToPx() }
|
||||
val provider = remember(gap) { BelowEndProvider(gap) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Popup(popupPositionProvider = provider, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) {
|
||||
AnimatedVisibility(
|
||||
visibleState = state,
|
||||
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f, transformOrigin = TransformOrigin(1f, 0f)),
|
||||
exit = fadeOut(Motion.tw(140)) + scaleOut(Motion.tw(140), targetScale = 0.96f, transformOrigin = TransformOrigin(1f, 0f)),
|
||||
label = "menu",
|
||||
) {
|
||||
// A long list (a driver menu with its downloads) must not run off the screen: the menu is
|
||||
// capped at most of the window's height and its entries scroll under the fixed title.
|
||||
val maxHeight = (androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp * 0.86f).dp
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.widthIn(min = 220.dp, max = 340.dp)
|
||||
.heightIn(max = maxHeight)
|
||||
.shadow(24.dp, RowShape, ambientColor = Color.Black, spotColor = Color.Black)
|
||||
.clip(RowShape)
|
||||
.background(pal.surfaceVariant.copy(alpha = 0.95f))
|
||||
.border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape)
|
||||
.padding(6.dp),
|
||||
) {
|
||||
if (title != null) Text(
|
||||
title.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 6.dp),
|
||||
)
|
||||
Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content() }
|
||||
if (note != null) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
Text(note, fontSize = 11.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun MenuItem(
|
||||
label: String, checked: Boolean, enabled: Boolean = true, detail: String? = null,
|
||||
trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift")
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.graphicsLayer { translationX = shift.dp.toPx() }
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent)
|
||||
.alpha(if (enabled) 1f else 0.4f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 9.dp),
|
||||
) {
|
||||
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f))
|
||||
if (leading != null) {
|
||||
leading()
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(label, fontSize = 13.5.sp, color = if (checked) pal.signal else colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
if (detail != null) Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (trailing != null) { Spacer(Modifier.width(8.dp)); trailing() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val pal = LocalPalette.current
|
||||
val edge by animateColorAsState(if (open || hot) pal.signal else pal.line2, Motion.tw(200), label = "chipEdge")
|
||||
val rot by animateFloatAsState(if (open) 180f else 0f, Motion.sp(0.6f), label = "chipCaret")
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween,
|
||||
modifier = modifier
|
||||
.widthIn(min = 150.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(colors.surfaceVariant)
|
||||
.border(1.dp, edge, RoundedCornerShape(10.dp))
|
||||
.alpha(if (enabled) 1f else 0.5f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = text,
|
||||
transitionSpec = { (fadeIn(Motion.tw(260)) + slideInVertically(Motion.tw(260)) { it / 2 }) togetherWith (fadeOut(Motion.tw(160)) + slideOutVertically(Motion.tw(160)) { -it / 2 }) },
|
||||
label = "chipText",
|
||||
) { t -> Text(t, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("▾", fontSize = 10.sp, color = colors.onSurfaceVariant, modifier = Modifier.rotate(rot))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SettingsGroup(title: String, content: @Composable ColumnScope.() -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 6.dp)) {
|
||||
Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant)
|
||||
Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line))
|
||||
}
|
||||
Column(modifier = Modifier.fillMaxWidth().clip(GroupShape).background(colors.surface).border(1.dp, pal.line, GroupShape)) { content() }
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, control: @Composable () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val bg by animateColorAsState(if (highlighted) pal.signal.copy(alpha = 0.10f) else Color.Transparent, Motion.tw(200), label = "rowBg")
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) {
|
||||
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
if (hint != null) Text(hint, fontSize = 11.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
|
||||
}
|
||||
control()
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun <T> ChoiceRow(
|
||||
host: MenuHost, key: String, label: String, hint: String?,
|
||||
options: List<Pair<T, String>>, selected: T, enabled: Boolean = true, note: String? = null,
|
||||
/** For the box itself - a page's FocusRequester for its first control. */
|
||||
chipModifier: Modifier = Modifier,
|
||||
onPick: (T) -> Unit,
|
||||
) {
|
||||
val open = host.open == key
|
||||
SettingsRow(label, hint, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) {
|
||||
for ((value, text) in options) MenuItem(text, checked = value == selected) { onPick(value); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, onChange: (Boolean) -> Unit) =
|
||||
ChoiceRow(host, key, label, hint, listOf(true to "On", false to "Off"), checked, enabled, onPick = onChange)
|
||||
|
||||
@Composable
|
||||
fun MultiRow(
|
||||
host: MenuHost, key: String, label: String, hint: String?,
|
||||
items: List<Pair<Int, String>>, selected: Set<Int>, enabled: Boolean = true, note: String? = null,
|
||||
onToggle: (Int, Boolean) -> Unit,
|
||||
) {
|
||||
val open = host.open == key
|
||||
val summary = when {
|
||||
selected.size >= items.size -> "All ${items.size}"
|
||||
selected.isEmpty() -> "None"
|
||||
else -> "${selected.size} of ${items.size}"
|
||||
}
|
||||
SettingsRow(label, hint, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(summary, open, enabled) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) {
|
||||
for ((value, text) in items) {
|
||||
val on = value in selected
|
||||
MenuItem(text, checked = on) { onToggle(value, !on) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit) {
|
||||
SettingsRow(label, hint) { SecondaryButton(button, onClick = onClick) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SettingsPage(
|
||||
host: MenuHost,
|
||||
title: String,
|
||||
onBack: () -> Unit,
|
||||
eyebrow: String? = null,
|
||||
lede: String? = null,
|
||||
/** A small control at the right of the title (the driver pages' refresh button). */
|
||||
action: (@Composable () -> Unit)? = null,
|
||||
/** Pass one held above the page to keep its scroll position across a page opened over it. */
|
||||
scroll: androidx.compose.foundation.ScrollState? = null,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val scrollState = scroll ?: rememberScrollState()
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val dim by animateFloatAsState(if (host.open != null) 0.6f else 1f, Motion.tw(220), label = "pageDim")
|
||||
Column(modifier = Modifier.fillMaxSize().padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
Rise(0) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// Outlined when a controller's focus is on it, like every other control here.
|
||||
val backSrc = remember { MutableInteractionSource() }
|
||||
val backHot = backSrc.collectIsFocusedAsState().value || backSrc.collectIsHoveredAsState().value
|
||||
Text(
|
||||
"‹ Back", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (backHot) LocalPalette.current.signal else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.border(2.dp, if (backHot) LocalPalette.current.signal else Color.Transparent, RoundedCornerShape(8.dp))
|
||||
.hoverable(backSrc).clickable(interactionSource = backSrc, indication = null, onClick = onBack)
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp),
|
||||
)
|
||||
if (eyebrow != null) {
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Eyebrow(eyebrow)
|
||||
}
|
||||
}
|
||||
}
|
||||
Rise(1) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.weight(1f)) { Title(title) }
|
||||
if (action != null) action()
|
||||
}
|
||||
}
|
||||
if (lede != null) Rise(2) { Lede(lede) }
|
||||
Rise(3, Modifier.weight(1f).fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxSize().graphicsLayer { alpha = dim }.verticalScroll(scrollState).padding(bottom = 24.dp)) { content() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
class Palette(
|
||||
val id: String, val label: String, val detail: String,
|
||||
val background: Color, val surface: Color, val surfaceVariant: Color, val line: Color, val line2: Color,
|
||||
val onBackground: Color, val onSurfaceVariant: Color,
|
||||
val primary: Color, val primary2: Color, val onPrimary: Color, val signal: Color,
|
||||
val good: Color, val error: Color = Color(0xFFFF8A80),
|
||||
)
|
||||
|
||||
object Themes {
|
||||
const val PAPER = "paper"
|
||||
const val ICON_BLUE = "blue"
|
||||
const val ELECTRIC = "electric"
|
||||
|
||||
val all: List<Palette> = listOf(
|
||||
Palette(
|
||||
PAPER, "Paper on black", "White is the primary, the icon's blue is the signal for rules, rings and dots.",
|
||||
background = Color(0xFF000000), surface = Color(0xFF0F0F10), surfaceVariant = Color(0xFF191A1C), line = Color(0xFF262729), line2 = Color(0xFF343638),
|
||||
onBackground = Color(0xFFF9F9F9), onSurfaceVariant = Color(0xFF8E9196),
|
||||
primary = Color(0xFFF9F9F9), primary2 = Color(0xFFD9DADD), onPrimary = Color(0xFF000000), signal = Color(0xFF136CE0),
|
||||
good = Color(0xFF4CD37F),
|
||||
),
|
||||
Palette(
|
||||
ICON_BLUE, "Icon blue", "Black ground, white type, the blue for everything selected, focused or pressed.",
|
||||
background = Color(0xFF050608), surface = Color(0xFF0E1116), surfaceVariant = Color(0xFF161B23), line = Color(0xFF1F2630), line2 = Color(0xFF2A3340),
|
||||
onBackground = Color(0xFFF2F4F7), onSurfaceVariant = Color(0xFF8A93A0),
|
||||
primary = Color(0xFF136CE0), primary2 = Color(0xFF0B4FB0), onPrimary = Color(0xFFFFFFFF), signal = Color(0xFF136CE0),
|
||||
good = Color(0xFF4CD37F),
|
||||
),
|
||||
Palette(
|
||||
ELECTRIC, "Electric navy", "The blue brighter, on surfaces that lean navy instead of grey.",
|
||||
background = Color(0xFF070A10), surface = Color(0xFF0F1522), surfaceVariant = Color(0xFF16203A), line = Color(0xFF1E2A47), line2 = Color(0xFF2A3A5E),
|
||||
onBackground = Color(0xFFEEF3FF), onSurfaceVariant = Color(0xFF8B9AB8),
|
||||
primary = Color(0xFF2E86FF), primary2 = Color(0xFF136CE0), onPrimary = Color(0xFFFFFFFF), signal = Color(0xFF2E86FF),
|
||||
good = Color(0xFF4CD37F),
|
||||
),
|
||||
)
|
||||
|
||||
fun byId(id: String): Palette = all.firstOrNull { it.id == id } ?: all[0]
|
||||
}
|
||||
|
||||
val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.PAPER) }
|
||||
|
||||
@Composable
|
||||
fun DroidDeckTheme(theme: String? = null, content: @Composable () -> Unit) {
|
||||
val id = theme ?: SessionPrefs.theme(LocalContext.current)
|
||||
val p = Themes.byId(id)
|
||||
val scheme = darkColorScheme(
|
||||
primary = p.primary, onPrimary = p.onPrimary, secondary = p.onSurfaceVariant,
|
||||
background = p.background, onBackground = p.onBackground,
|
||||
surface = p.surface, onSurface = p.onBackground,
|
||||
surfaceVariant = p.surfaceVariant, onSurfaceVariant = p.onSurfaceVariant,
|
||||
error = p.error,
|
||||
)
|
||||
CompositionLocalProvider(LocalPalette provides p) { MaterialTheme(colorScheme = scheme, content = content) }
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.droiddeck.launcher.wayland
|
||||
|
||||
import android.view.Choreographer
|
||||
import android.view.Surface
|
||||
|
||||
/**
|
||||
* The compositor is a process-wide thing, not an activity's: it is started once, keeps running
|
||||
* while the session does, and merely swaps the Surface it presents into as the activity comes and
|
||||
* goes. An activity that started it again on re-creation would be starting a second compositor on
|
||||
* a socket the first one owns.
|
||||
*/
|
||||
object CompositorHost {
|
||||
@Volatile
|
||||
private var started = false
|
||||
private var vsyncRunning = false
|
||||
|
||||
private val vsync = object : Choreographer.FrameCallback {
|
||||
override fun doFrame(frameTimeNanos: Long) {
|
||||
WaylandCompositor.nativeVsync(frameTimeNanos)
|
||||
if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this)
|
||||
}
|
||||
}
|
||||
|
||||
/** True when this call was the one that started the compositor. */
|
||||
@Synchronized
|
||||
fun startOrAttach(
|
||||
surface: Surface,
|
||||
xdgRuntimeDir: String,
|
||||
driverPath: String?,
|
||||
libraryName: String?,
|
||||
nativeLibDir: String,
|
||||
outputWidth: Int,
|
||||
outputHeight: Int,
|
||||
refreshHz: Float,
|
||||
): Boolean {
|
||||
if (started) {
|
||||
attached = surface
|
||||
WaylandCompositor.nativeSetSurface(surface)
|
||||
resumeVsync()
|
||||
return false
|
||||
}
|
||||
WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight)
|
||||
WaylandCompositor.nativeSetOutputRefreshRate(refreshHz)
|
||||
WaylandCompositor.nativeStartWithSurface(
|
||||
surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir,
|
||||
)
|
||||
attached = surface
|
||||
started = true
|
||||
resumeVsync()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* The Surface changed size under the compositor (a foldable opening or closing). Android does
|
||||
* not always recreate the Surface for that, and a swapchain built for the old size keeps
|
||||
* presenting: the system then scales those buffers onto the new window, which on a Fold showed
|
||||
* a 16:9 picture stretched to the square panel. Rebinding the window rebuilds the swapchain at
|
||||
* the new size, and the scale mode letterboxes as it should.
|
||||
*/
|
||||
@Synchronized
|
||||
fun resize(surface: Surface, rearm: () -> Unit) {
|
||||
if (!started) return
|
||||
// Frame generation does not live through a resize: its ring, its effects chain and its
|
||||
// multi-present pacing were all built against the old extent, and on a Fold the picture
|
||||
// came back stretched with an engine on and right with it off. Disarmed, the window is
|
||||
// rebound and the swapchain rebuilt; the caller re-arms once that has settled, and every
|
||||
// engine-side object is made again for the new size.
|
||||
WaylandCompositor.nativeSetFrameGenArmed(false, 0)
|
||||
WaylandCompositor.nativeLog("screen", "surface resized: rebinding the window, frame generation re-armed after")
|
||||
WaylandCompositor.nativeSetSurface(null)
|
||||
attached = surface
|
||||
WaylandCompositor.nativeSetSurface(surface)
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(rearm, 600)
|
||||
}
|
||||
|
||||
/**
|
||||
* The window the guest presents through has changed (the Steam menu opening or closing over a
|
||||
* fullscreen game swaps gamescope between forwarding the game's own buffers and its composited
|
||||
* output). The engine's ring and history straddle that switch and come back wrong-sized - a
|
||||
* game shown as a strip in a corner - so it is disarmed and re-armed against the new window.
|
||||
*/
|
||||
fun rearmFrameGen(rearm: () -> Unit) {
|
||||
if (!started) return
|
||||
WaylandCompositor.nativeSetFrameGenArmed(false, 0)
|
||||
WaylandCompositor.nativeLog("screen", "presenting window changed: frame generation re-armed")
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(rearm, 600)
|
||||
}
|
||||
|
||||
/**
|
||||
* The activity is going away. The compositor keeps running with nothing to present into -
|
||||
* the guest carries on, and its next frames land on the Surface the next activity brings.
|
||||
*/
|
||||
/** The Surface the compositor presents on; only its own owner may take it away. */
|
||||
private var attached: Surface? = null
|
||||
|
||||
/**
|
||||
* Only for the Surface that is attached. When one session hands over to the next (the
|
||||
* desktop's Steam launchers), the new activity attaches its Surface before the old one is
|
||||
* destroyed - and the old one's surfaceDestroyed then arrived here and took the new Surface
|
||||
* away: gamescope's frames came in by the thousand and nothing reached the screen.
|
||||
*/
|
||||
@Synchronized
|
||||
fun detach(surface: Surface?) {
|
||||
if (!started) return
|
||||
if (surface != null && attached != null && attached !== surface) return
|
||||
attached = null
|
||||
pauseVsync()
|
||||
WaylandCompositor.nativeSetSurface(null)
|
||||
}
|
||||
|
||||
/** Frames are only worth drawing while a Surface is attached. */
|
||||
private fun resumeVsync() {
|
||||
if (vsyncRunning) return
|
||||
vsyncRunning = true
|
||||
Choreographer.getInstance().postFrameCallback(vsync)
|
||||
}
|
||||
|
||||
private fun pauseVsync() {
|
||||
vsyncRunning = false
|
||||
}
|
||||
|
||||
/**
|
||||
* A new session behind a compositor that has already presented: the first-frame notice is
|
||||
* one-shot in native code, so it is re-armed here or the loading panel would never leave.
|
||||
*/
|
||||
fun newSession() {
|
||||
if (started) WaylandCompositor.nativeResetFirstFrame()
|
||||
}
|
||||
|
||||
val isStarted: Boolean get() = started
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.droiddeck.launcher.wayland
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
|
||||
/**
|
||||
* What the panel says about HDR, read from android.view.Display: the gate the compositor's HDR10
|
||||
* output sits behind (banner_color.h). A property of the display, not the device - and the
|
||||
* settings screen greys the HDR switch out with the reason when it is not there, rather than
|
||||
* offering a switch that a session would then silently ignore.
|
||||
*/
|
||||
class HdrProbe(
|
||||
val hdr10: Boolean,
|
||||
val formats: String,
|
||||
val maxLuminance: Float,
|
||||
val maxAverageLuminance: Float,
|
||||
val minLuminance: Float,
|
||||
val ratioAvailable: Boolean,
|
||||
val ratio: Float,
|
||||
val displayId: Int,
|
||||
val name: String,
|
||||
) {
|
||||
/** Why HDR cannot be offered, or null when it can. */
|
||||
val reason: String? = when {
|
||||
Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a colour space)"
|
||||
!hdr10 -> if (formats.isEmpty()) "this display reports no HDR support" else "this display supports $formats, not HDR10"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
object HdrSupport {
|
||||
fun probe(context: Context): HdrProbe {
|
||||
val display: Display? = if (Build.VERSION.SDK_INT >= 30) {
|
||||
try { context.display } catch (e: Exception) { null }
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
(context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
|
||||
}
|
||||
if (display == null) return HdrProbe(false, "", 0f, 0f, 0f, false, -1f, -1, "none")
|
||||
val caps = try { display.hdrCapabilities } catch (e: Exception) { null }
|
||||
val types = caps?.supportedHdrTypes ?: IntArray(0)
|
||||
val formats = types.joinToString(", ") { typeName(it) }
|
||||
val ratioAvailable = Build.VERSION.SDK_INT >= 34 && try { display.isHdrSdrRatioAvailable } catch (e: Exception) { false }
|
||||
val ratio = if (ratioAvailable) try { display.hdrSdrRatio } catch (e: Exception) { -1f } else -1f
|
||||
return HdrProbe(
|
||||
hdr10 = types.contains(Display.HdrCapabilities.HDR_TYPE_HDR10),
|
||||
formats = formats,
|
||||
maxLuminance = caps?.desiredMaxLuminance ?: 0f,
|
||||
maxAverageLuminance = caps?.desiredMaxAverageLuminance ?: 0f,
|
||||
minLuminance = caps?.desiredMinLuminance ?: 0f,
|
||||
ratioAvailable = ratioAvailable,
|
||||
ratio = ratio,
|
||||
displayId = display.displayId,
|
||||
name = display.name ?: "display",
|
||||
)
|
||||
}
|
||||
|
||||
private fun typeName(t: Int): String = when (t) {
|
||||
Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION -> "Dolby Vision"
|
||||
Display.HdrCapabilities.HDR_TYPE_HDR10 -> "HDR10"
|
||||
Display.HdrCapabilities.HDR_TYPE_HLG -> "HLG"
|
||||
Display.HdrCapabilities.HDR_TYPE_HDR10_PLUS -> "HDR10+"
|
||||
else -> "HDR"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
package com.droiddeck.launcher.wayland;
|
||||
|
||||
import android.view.Surface;
|
||||
|
||||
/**
|
||||
* Embedded Wayland compositor (experimental parallel display runtime).
|
||||
*
|
||||
* Brings up a libwayland-server compositor in-process so games launched through
|
||||
* Wine's winewayland.drv can present into it (companion to the winewayland Proton
|
||||
* build). Committed frames (dmabufs from winewayland's Vulkan WSI) are composited
|
||||
* onto the given Surface via the native Vulkan present backend. Not on the default
|
||||
* X11 path.
|
||||
*/
|
||||
public final class WaylandCompositor {
|
||||
static {
|
||||
System.loadLibrary("bannerwayland");
|
||||
}
|
||||
|
||||
private WaylandCompositor() {}
|
||||
|
||||
private static volatile Runnable firstFrameListener;
|
||||
|
||||
/** Register a callback fired once, when the compositor presents the first client
|
||||
* frame to the output Surface. Used to dismiss the launch overlay in wayland mode
|
||||
* (there is no XServer window-content hook). Runs on the compositor thread - the
|
||||
* listener must marshal to the UI thread itself. */
|
||||
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
|
||||
|
||||
/** Invoked from native (banner_on_first_frame) on the first present. */
|
||||
@SuppressWarnings("unused")
|
||||
static void onFirstFramePresented() {
|
||||
Runnable r = firstFrameListener;
|
||||
if (r != null) r.run();
|
||||
}
|
||||
|
||||
/** The in-game performance HUD's feed in wayland mode (X11 binds the HUD to the window
|
||||
* carrying _MESA_DRV and counts X presents; there is no X server here). */
|
||||
public interface GameListener {
|
||||
/** A window started presenting GPU frames ({@code window} describes it; {@code gpuName} is the
|
||||
* compositor's GPU), or {@code window == null} when that window closed. Compositor thread. */
|
||||
void onGameSurface(String window, String gpuName);
|
||||
/** One GPU frame from that window. Compositor thread - keep it cheap. */
|
||||
void onGameFrame();
|
||||
/** The program behind that window, right after {@link #onGameSurface}: its Linux pid (the
|
||||
* Wayland client's credentials) and executable name ({@code ""} when unknown). The app arms its
|
||||
* launch-time CPU affinity on it - on X11 that comes from window events, which a Wayland session
|
||||
* has none of. Compositor thread - marshal to the UI thread. */
|
||||
default void onGameProgram(int pid, String program) {}
|
||||
}
|
||||
|
||||
private static volatile GameListener gameListener;
|
||||
|
||||
public static void setGameListener(GameListener l) { gameListener = l; }
|
||||
|
||||
/** Invoked from native (banner_on_game_surface). */
|
||||
@SuppressWarnings("unused")
|
||||
static void onGameSurface(String window, String gpuName) {
|
||||
GameListener l = gameListener;
|
||||
if (l != null) l.onGameSurface(window, gpuName);
|
||||
}
|
||||
|
||||
/** Invoked from native (banner_on_game_frame) for every frame of the HUD's window. */
|
||||
@SuppressWarnings("unused")
|
||||
static void onGameFrame() {
|
||||
com.droiddeck.launcher.session.PerfHints.onFrame();
|
||||
GameListener l = gameListener;
|
||||
if (l != null) l.onGameFrame();
|
||||
}
|
||||
|
||||
/** Invoked from native (banner_on_game_program) once per game window that starts presenting. */
|
||||
@SuppressWarnings("unused")
|
||||
static void onGameProgram(int pid, String program) {
|
||||
GameListener l = gameListener;
|
||||
if (l != null) l.onGameProgram(pid, program != null ? program : "");
|
||||
}
|
||||
|
||||
/** Pointer lock (zwp_pointer_constraints_v1) state, for the app's input path. */
|
||||
public interface PointerLockListener {
|
||||
/** A program locked the pointer ({@code locked}): the app must feed the compositor deltas
|
||||
* (scene input type 6) instead of absolute positions. When the lock ends, {@code x,y} is
|
||||
* where the pointer now is (scene = virtual-desktop coordinates) for the app to re-sync
|
||||
* its own pointer to. Compositor thread. */
|
||||
void onPointerLock(boolean locked, int x, int y);
|
||||
}
|
||||
|
||||
private static volatile PointerLockListener pointerLockListener;
|
||||
|
||||
public static void setPointerLockListener(PointerLockListener l) { pointerLockListener = l; }
|
||||
|
||||
/** Invoked from native (banner_on_pointer_lock). */
|
||||
@SuppressWarnings("unused")
|
||||
static void onPointerLock(boolean locked, int x, int y) {
|
||||
PointerLockListener l = pointerLockListener;
|
||||
if (l != null) l.onPointerLock(locked, x, y);
|
||||
}
|
||||
|
||||
/** Clipboard text a program in the guest copied (wl_data_device / zwlr_data_control). */
|
||||
public interface ClipboardListener {
|
||||
/** {@code text} is what the guest put on its clipboard. Compositor thread. */
|
||||
void onGuestClipboardText(String text);
|
||||
}
|
||||
|
||||
private static volatile ClipboardListener clipboardListener;
|
||||
|
||||
public static void setClipboardListener(ClipboardListener l) { clipboardListener = l; }
|
||||
|
||||
/** Invoked from native (banner_on_clipboard_text) with UTF-8 bytes. */
|
||||
@SuppressWarnings("unused")
|
||||
static void onClipboardText(byte[] utf8) {
|
||||
ClipboardListener l = clipboardListener;
|
||||
if (l != null && utf8 != null) l.onGuestClipboardText(new String(utf8, java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** Text input (zwp_text_input_v3) state: a program accepts IME text, or stopped. */
|
||||
public interface TextInputListener {
|
||||
/** {@code enabled}: {@code program} (its exe name) accepts IME text; {@code x,y,w,h} is its caret
|
||||
* rectangle in scene (virtual desktop) pixels, all 0 until the program positions one. Compositor
|
||||
* thread. */
|
||||
void onTextInput(boolean enabled, String program, int x, int y, int w, int h);
|
||||
}
|
||||
|
||||
private static volatile TextInputListener textInputListener;
|
||||
|
||||
public static void setTextInputListener(TextInputListener l) { textInputListener = l; }
|
||||
|
||||
/** Invoked from native (banner_on_text_input). */
|
||||
@SuppressWarnings("unused")
|
||||
static void onTextInput(boolean enabled, String program, int x, int y, int w, int h) {
|
||||
TextInputListener l = textInputListener;
|
||||
if (l != null) l.onTextInput(enabled, program, x, y, w, h);
|
||||
}
|
||||
|
||||
private static byte[] utf8(String s) {
|
||||
return s == null ? new byte[0] : s.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** Android's clipboard text becomes the guest's selection ({@code null}/empty clears it). Any thread. */
|
||||
public static void setClipboardText(String text) { nativeSetClipboardText(utf8(text)); }
|
||||
|
||||
/** Commit soft-keyboard text to the program accepting text input. Any thread. */
|
||||
public static void textInputCommit(String text) { if (text != null && !text.isEmpty()) nativeTextInputCommit(utf8(text)); }
|
||||
|
||||
/** Composing (pre-edit) text with the caret at character index {@code cursor} (-1 = end); empty clears. */
|
||||
public static void textInputPreedit(String text, int cursor) { nativeTextInputPreedit(utf8(text), cursor, cursor); }
|
||||
|
||||
/** The IME deleted {@code before} characters before and {@code after} after the caret. */
|
||||
public static void textInputDelete(int before, int after) { nativeTextInputDelete(before, after); }
|
||||
|
||||
private static native void nativeSetClipboardText(byte[] utf8);
|
||||
private static native void nativeTextInputCommit(byte[] utf8);
|
||||
private static native void nativeTextInputPreedit(byte[] utf8, int cursorBegin, int cursorEnd);
|
||||
private static native void nativeTextInputDelete(int before, int after);
|
||||
|
||||
/** Start the compositor headless (no output window) - bring-up tests only. */
|
||||
public static native void nativeStart(String xdgRuntimeDir);
|
||||
|
||||
/** Start the compositor rendering to {@code surface}. XDG_RUNTIME_DIR = an
|
||||
* app-writable dir for the wayland socket (e.g. context.getFilesDir()).
|
||||
* driverPath/libraryName/nativeLibDir select the Turnip driver via adrenotools
|
||||
* (all null -> system libvulkan, which can't do dmabuf import). */
|
||||
public static native void nativeStartWithSurface(Surface surface, String xdgRuntimeDir,
|
||||
String driverPath, String libraryName,
|
||||
String nativeLibDir);
|
||||
|
||||
/** Replace/clear the output window when the SurfaceView is (re)created/destroyed. */
|
||||
public static native void nativeSetSurface(Surface surface);
|
||||
|
||||
/** Inject a pointer event into the compositor (from the SurfaceView touch listener).
|
||||
* action: 0=down, 1=move, 2=up. x/y in compositor output space (0..1919, 0..1079). */
|
||||
public static native void nativeSendPointer(int action, int x, int y);
|
||||
|
||||
/** Inject a key event. evdev = Linux input keycode (KEY_A=30…); state: 1=down, 0=up. */
|
||||
public static native void nativeSendKey(int evdev, int state);
|
||||
|
||||
/** One screen refresh (Choreographer frame callback). The compositor draws the newest state
|
||||
* once per tick, so games run unthrottled and the screen shows their latest frame. */
|
||||
public static native void nativeVsync(long frameTimeNanos);
|
||||
|
||||
/** The compositor thread's Linux tid, or 0 before it has started (see PerfHints). */
|
||||
public static native int nativeCompositorTid();
|
||||
|
||||
/** Shortcut launches: don't draw explorer's windows (desktop, taskbar, Start menu), matching the
|
||||
* X11 renderer's unviewable "explorer.exe". Set before the compositor starts. */
|
||||
public static native void nativeSetHideShell(boolean hide);
|
||||
|
||||
/** The panel's refresh rate in Hz, advertised on the Wayland output so Wine's display modes
|
||||
* carry the real rate (games that insist on their saved 144 Hz mode find it, as on X11).
|
||||
* Set before the compositor starts. */
|
||||
public static native void nativeSetOutputRefreshRate(float hz);
|
||||
|
||||
/** Show a single fullscreen window on its own Android layer (SurfaceControl) instead of blitting
|
||||
* it into the compositor's swapchain. BANNER_WAYLAND_ZERO_COPY=1 in the container's environment
|
||||
* variables is the launch default; see waylandcomp/ZERO_COPY_SPIKE.md.
|
||||
*
|
||||
* Live and thread-safe: before the compositor starts this is the initial state, and afterwards
|
||||
* the call is marshalled onto the compositor thread, which flips the state, tells every bound
|
||||
* game over banner_ahb_v1.mode to rebuild its swapchain for it, and redraws. The switch is one
|
||||
* frame's worth of latency; the picture never goes black, because the old swapchain's buffers
|
||||
* keep being shown until the game has replaced them. */
|
||||
public static native void nativeSetZeroCopy(boolean on);
|
||||
|
||||
/** Zero-copy frames the compositor presented in its LAST completed 10 s stats window (the
|
||||
* "| N zero-copy frames" figure of its session-log stats line); 0 while zero-copy is off or
|
||||
* before the first window closes. Read-only, any thread - the in-game drawer polls it. */
|
||||
public static native int nativeZeroCopyFrames();
|
||||
|
||||
/** Milliseconds since the compositor last put a game frame on the display layer without a copy;
|
||||
* -1 if it never has this session. Unlike nativeZeroCopyFrames this updates on every such frame
|
||||
* rather than once per 10 s window, so the drawer can tell "switching..." from "running" within
|
||||
* a frame or two of the live toggle. Read-only, any thread. */
|
||||
public static native int nativeZeroCopyLastFrameAgeMs();
|
||||
|
||||
/** Compressed (UBWC) game buffers: the compositor advertises DRM_FORMAT_MOD_QCOM_COMPRESSED next to
|
||||
* LINEAR on zwp_linux_dmabuf_v1 for every format its driver can import that way, so the game's
|
||||
* Turnip allocates compressed swapchain images instead of resolving every frame to a linear copy.
|
||||
* Default on; BANNER_WAYLAND_UBWC=0 in the container's environment variables turns it off (A/B).
|
||||
* Set before the compositor starts. */
|
||||
public static native void nativeSetUbwc(boolean on);
|
||||
|
||||
/** Debug: advertise no DRM device (main device 0:0) in the dma-buf feedback, as a phone that
|
||||
* exposes no /dev/dri node to apps does. BANNER_WAYLAND_NO_RENDER_NODE=1 in the container's or
|
||||
* shortcut's environment variables. Set before the compositor starts. */
|
||||
public static native void nativeSetNoRenderNode(boolean on);
|
||||
|
||||
/** VRR / refresh-rate matching: mirror the panel refresh-rate vote the activity puts on the
|
||||
* compositor's SurfaceView onto the game's own SurfaceControl layer. Under zero-copy the game's
|
||||
* frames go straight onto that layer and never reach the app's surface, so the surface vote alone
|
||||
* does not tell SurfaceFlinger the game's cadence. Same rate and compatibility as
|
||||
* {@code Surface.setFrameRate}; {@code 0} clears the vote. Callable any time from any thread; the
|
||||
* compositor applies it on its next layer transaction and writes one `layer` line per change to
|
||||
* the session log. A no-op on Android versions without {@code ASurfaceTransaction_setFrameRate}. */
|
||||
public static native void nativeSetLayerFrameRate(float hz);
|
||||
|
||||
/** Where the compositor was told to write its log, for the session collector; null if it was
|
||||
* left to choose. Set before the compositor starts - it opens the file once, at start. */
|
||||
private static volatile java.io.File sessionLogFile;
|
||||
|
||||
public static void setSessionLogFile(java.io.File file) {
|
||||
sessionLogFile = file;
|
||||
}
|
||||
|
||||
public static java.io.File currentLogFile() {
|
||||
return sessionLogFile;
|
||||
}
|
||||
|
||||
/** Write one line into the compositor's session log (Download/Wayland-logs) under the "display"
|
||||
* area, from Java. Used for facts the platform knows and the native side does not - the panel's
|
||||
* HDR capability, which lives behind android.view.Display. Safe before the compositor thread is
|
||||
* up (the line then only reaches logcat) and safe after it has gone. */
|
||||
public static native void nativeLogDisplay(String message);
|
||||
|
||||
/** The same under the "perf" area (e.g. the CPU cores Prefer Big Cores picked). Same safety. */
|
||||
public static native void nativeLogPerf(String message);
|
||||
|
||||
/** The container's screen size, advertised as the Wayland output's mode so Wine's display-mode
|
||||
* list stops at the desktop size, as the X server's does on X11. Set before the compositor starts. */
|
||||
public static native void nativeSetOutputSize(int width, int height);
|
||||
|
||||
/** Re-arms the one-shot first-frame notice, for a new session under a compositor that has
|
||||
* already presented a previous one. */
|
||||
public static native void nativeResetFirstFrame();
|
||||
|
||||
// ── HDR10 output, round 1 (waylandcomp/src/banner_color.h, wl_color_mgmt.c) ─────────────────
|
||||
// Opt-in: BANNER_WAYLAND_HDR=1 in the container's or shortcut's env vars. The compositor offers
|
||||
// games HDR10 (wp_color_manager_v1 + 10-bit buffers, frames tagged BT2020_PQ on the game's own
|
||||
// display layer) only when the game's display lists HDR10 as well; otherwise nothing changes and
|
||||
// the session log says why. Not the drawer's "HDR" effect, which is an SDR bloom/contrast filter.
|
||||
|
||||
/** HDR_MODE_OFF / HDR_MODE_ON (BANNER_WAYLAND_HDR=1) / HDR_MODE_FORCE (=force: skip the display
|
||||
* check, for testing the negotiation on an SDR panel). */
|
||||
public static final int HDR_MODE_OFF = 0, HDR_MODE_ON = 1, HDR_MODE_FORCE = 2;
|
||||
|
||||
/** The opt-in: mode, where it came from ("container env" / "shortcut env"), whether DXVK_HDR=1 is
|
||||
* in the game's environment, and whether the app turned zero-copy on for this session because HDR
|
||||
* needs it. Set before the compositor starts. */
|
||||
public static native void nativeSetHdrRequest(int mode, String source, boolean dxvkHdr, boolean zeroCopyForced);
|
||||
|
||||
/** The game's display as {@code android.view.Display} reports it. Before the compositor starts (it
|
||||
* feeds the gate) and again whenever it changes (logged; the gate is decided once per session). */
|
||||
public static native void nativeSetHdrDisplay(int displayId, String name, String formats, boolean hdr10,
|
||||
float maxLuminance, float maxAverageLuminance, float minLuminance,
|
||||
boolean hdrSdrRatioAvailable, float hdrSdrRatio, int apiLevel);
|
||||
|
||||
/** One {@code Display.getHdrSdrRatio()} reading ({@code < 0} = not available); {@code listener} = it
|
||||
* came from the display's ratio listener rather than the periodic sampler. Any thread. */
|
||||
public static native void nativeHdrSdrRatioSample(float ratio, boolean listener);
|
||||
|
||||
/** Milliseconds since an HDR frame last reached a display layer; -1 = none this session. Any thread. */
|
||||
public static native int nativeHdrLastFrameAgeMs();
|
||||
|
||||
/** -1 = the compositor has not decided the HDR gate yet, 0 = closed, 1 = open. Any thread. */
|
||||
public static native int nativeHdrGateState();
|
||||
|
||||
/** The session is ending: the compositor writes its "HDR on screen: …" summary line. Once. */
|
||||
public static native void nativeHdrSessionEnd();
|
||||
|
||||
/** True while HDR frames are really on screen: frames tagged BT2020_PQ reached the display in the
|
||||
* last 1.5 s and, where the display reports an HDR/SDR ratio, it is above 1 (the HUD's badge). */
|
||||
public static native boolean nativeHdrOnScreen();
|
||||
|
||||
/** One "color" line in the session log, from Java (the HDR environment, the DXVK warning). */
|
||||
public static native void nativeLogColor(String message);
|
||||
|
||||
/** One line in the session log under {@code area} (the log's 9-character column: "gpu", "nvapi"),
|
||||
* from Java: launch facts the app decides (the GPU name spoof, the Unreal Engine HDR mode). Like
|
||||
* {@link #nativeLogDisplay}, safe before the session file exists (the line is written when it
|
||||
* opens) and after it has gone. */
|
||||
public static native void nativeLog(String area, String message);
|
||||
|
||||
/** Nits at which SDR content is placed when the compositor composes an HDR picture (a window over
|
||||
* an HDR game, the desktop around a windowed one). Default 203 (BT.2408). Before the start. */
|
||||
public static native void nativeSetHdrSdrWhite(float nits);
|
||||
|
||||
/** The in-game drawer's HDR output switch (only meaningful while the HDR gate is open; per session,
|
||||
* starts on). On = the game's HDR frames go to the display as HDR; off = the same frames are shown
|
||||
* tone-mapped to SDR. Live, any thread (queued to the compositor, which logs the flip); the game is
|
||||
* told nothing - DXVK_HDR and the colour-manager offer were decided at launch. */
|
||||
public static native void nativeSetHdrOutput(boolean on);
|
||||
|
||||
/** The HDR output switch's current state (any thread). */
|
||||
public static native boolean nativeHdrOutput();
|
||||
|
||||
/** True while an HDR game's frames are being shown tone-mapped to SDR (the last one under 1.5 s ago). */
|
||||
public static native boolean nativeHdrToneMappedOnScreen();
|
||||
|
||||
/** 0 = no HDR frames on screen (or not confirmed yet), 1 = HDR frames on screen with HDR headroom,
|
||||
* 2 = HDR frames on screen but the display has given them no headroom (HDR/SDR ratio 1.00) for 5 s
|
||||
* or more - the brightness slider at maximum, or a screen recording (Android turns HDR headroom off
|
||||
* while the screen is recorded). The HUD badge and the drawer's HDR row. */
|
||||
public static native int nativeHdrState();
|
||||
|
||||
/** Device evidence beside the HDR/SDR headroom, HDR sessions only (any thread): PowerManager thermal
|
||||
* status (0..6, -1 unknown) and getThermalHeadroom(10) (NaN / negative = not available), and
|
||||
* Settings.System SCREEN_BRIGHTNESS (0..255, -1 unknown) + SCREEN_BRIGHTNESS_MODE (1 auto, 0 manual,
|
||||
* -1 unknown). The compositor logs changes of status and brightness and puts the values on every
|
||||
* no-headroom line, the 10 s HDR line and the verdict. */
|
||||
public static native void nativeHdrEnvSample(int thermalStatus, float thermalHeadroom, int brightness,
|
||||
int brightnessMode);
|
||||
|
||||
/** Display.getHighestHdrSdrRatio() (Android 16+), <= 0 = not reported: the display's own ceiling, capped
|
||||
* into the headroom request and logged in the verdict. Any thread. */
|
||||
public static native void nativeSetHdrHighestRatio(float ratio);
|
||||
|
||||
/** The HDR headroom the SCREEN surface should ask for while HDR frames go through the HDR10 swapchain
|
||||
* (frame generation), 0 = none; the app applies it (SurfaceView.setDesiredHdrHeadroom, API 35). */
|
||||
public static native float nativeHdrScreenHeadroom();
|
||||
|
||||
/** Why that value ("content peak 1207 nits (max CLL) / SDR 203 ..."), for the log line. */
|
||||
public static native String nativeHdrScreenHeadroomWhy();
|
||||
|
||||
/** What the app asked for on the screen surface: > 0 the ratio, 0 cleared, -1 not possible (< Android 15). */
|
||||
public static native void nativeHdrNoteHeadroomRequest(float ratio);
|
||||
|
||||
/** Fullscreen mode ({@code Container.FULLSCREEN_OFF/FIT/STRETCH/FILL/INTEGER}) and screen alignment
|
||||
* ({@code Container.ALIGN_CENTER/TOP/BOTTOM}): how the compositor fits the desktop onto the screen,
|
||||
* with the same arithmetic as {@code ViewTransformation} (which maps touch input), so the picture and
|
||||
* the pointer agree. OFF and FIT both letterbox. Callable any time; the next frame uses it. */
|
||||
public static native void nativeSetScaleMode(int fullscreenMode, int screenAlignment);
|
||||
|
||||
// ---- Screen effects: the X11 Vulkan renderer's post chain, run by the compositor between the
|
||||
// composited scene and the output blit (waylandcomp/src/effects_chain.c). Same modes, ranges and
|
||||
// pass order as VulkanRenderer's setters, so a saved preset looks the same on both backends.
|
||||
// Callable any time from any thread; the compositor applies them on its next frame and writes
|
||||
// one `effects` line to the session log per change. While any effect is on, a zero-copy
|
||||
// (layer-mode) game is presented through the compositor pass instead.
|
||||
|
||||
/** Scaling mode: 0=None 1=Linear 2=Nearest 3=SGSR 4=FSR 5=FSR Fit 6=Sharpen 7=NIS 8=SGSR HQ.
|
||||
* Resizes the scene to its mapped output size (there is no render scale on Wayland). */
|
||||
public static native void nativeSetUpscaler(int mode);
|
||||
|
||||
/** The upscaler's own sharpness slider 0..100 (RCAS lobe scale, SGSR edge 0.5..4.5, NIS). */
|
||||
public static native void nativeSetUpscaleSharpness(int sharpness);
|
||||
|
||||
/** AMD CAS sharpen toggle + level 0..100 (0 = the pass is off). */
|
||||
public static native void nativeSetCas(boolean enabled, int sharpness);
|
||||
|
||||
/** Fake-HDR toggle. */
|
||||
public static native void nativeSetHdr(boolean enabled);
|
||||
|
||||
/** Terminal debanding toggle + strength 0..200 (100 = 1 LSB). */
|
||||
public static native void nativeSetDeband(boolean enabled, int strength);
|
||||
|
||||
/** Colour grade in the drawer's slider units (brightness/contrast -100..100, gamma 0.5..3.0,
|
||||
* saturation 0..200 percent; 0/0/1/100 = neutral, pass off) plus the FXAA / Toon / CRT / NTSC
|
||||
* toggles - the same signature as {@code VulkanRenderer.setScreenEffects}. */
|
||||
public static native void nativeSetScreenEffects(float brightness, float contrast, float gamma, float saturation,
|
||||
boolean fxaa, boolean toon, boolean crt, boolean ntsc);
|
||||
|
||||
/** The Look the controls currently match ({@code null} = Custom); only named in the log line. */
|
||||
public static native void nativeSetLookName(String name);
|
||||
|
||||
/** The in-game FPS limiter: frames per second, 0 = unlimited. Paces when replaced buffers go
|
||||
* back to the game, like the X11 IdleNotify pacer, so the game itself slows to the cap. */
|
||||
public static native void nativeSetFpsLimit(int fps);
|
||||
|
||||
/** Inject the app's X-server input in scene (virtual desktop) pixels. type 2 = move to a,b;
|
||||
* 3 = evdev button a (BTN_LEFT=0x110…) pressed (b=1) or released (b=0); 4 = a wheel steps,
|
||||
* negative = up. */
|
||||
public static native void nativeSendSceneInput(int type, int a, int b);
|
||||
|
||||
// ── Frame generation (waylandcomp/src/framegen_bridge.c) ─────────────────────────────────
|
||||
// LSFG Native and Win-FG Native run inside the compositor's Turnip device, the same engines
|
||||
// the X11 VulkanRenderer hosts. Every setter only stores a value; the compositor thread applies
|
||||
// it on its next frame, so they are safe from any thread and before the compositor starts.
|
||||
// bionic-fg (the guest-side win-fg layer) is X11-only and has no Wayland counterpart.
|
||||
public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_WINFG = 1;
|
||||
|
||||
/** Which native engine generates: {@link #FG_ENGINE_LSFG} or {@link #FG_ENGINE_WINFG}. */
|
||||
public static native void nativeSetFrameGenEngine(int kind);
|
||||
|
||||
/** Arm (multiplier 2..4: one real frame plus multiplier-1 interpolated ones per game frame) or
|
||||
* disarm. Generated frames are presented ahead of the real frame on consecutive vblanks. */
|
||||
public static native void nativeSetFrameGenArmed(boolean armed, int multiplier);
|
||||
|
||||
/** LSFG Native: the SPIR-V cache built from the user's Lossless.dll ({@code LsfgNative.cacheFile}). */
|
||||
public static native void nativeSetLsfgCachePath(String path);
|
||||
|
||||
/** Flow scale (0.25-1.0) and the panel's real refresh rate (the pacer never generates above it). */
|
||||
public static native void nativeSetFrameGenTuning(float flowScale, float refreshHz);
|
||||
|
||||
/** Win-FG Native only: interpolation model (3/4) and performance preset (0..2). */
|
||||
public static native void nativeSetWinFgTuning(int model, int perfPreset);
|
||||
|
||||
/** Same codes as {@code VulkanRenderer.getFrameGenProblem()}: -1 not known yet (the compositor's
|
||||
* device is not up), 0 fine, 1 the driver lacks what the selected engine needs
|
||||
* ({@link #nativeFrameGenCapsReason()} says what), 2 the engine failed to start. */
|
||||
public static native int nativeFrameGenProblem();
|
||||
public static native String nativeFrameGenCapsReason();
|
||||
|
||||
/** Same shape as {@code VulkanRenderer.getFrameGenStats()}: {generations trusted, generations
|
||||
* planned, real fps, presented fps (generated frames included), thermal (-1 = none),
|
||||
* GPU ms per generated frame (-1 = unknown)}. */
|
||||
public static native float[] nativeFrameGenStats();
|
||||
|
||||
/** Relative pointer motion by dx,dy scene pixels (the Relative Mouse / captured-mouse path):
|
||||
* while a program holds a pointer lock this is what it receives as relative_motion; otherwise
|
||||
* the compositor moves its pointer by the delta. */
|
||||
public static void sendPointerDelta(int dx, int dy) {
|
||||
if (dx == 0 && dy == 0) return;
|
||||
nativeSendSceneInput(6, dx * 256, dy * 256);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user